code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/* $Id: UIMachineDefs.h $ */
/** @file
* VBox Qt GUI - Defines for Virtual Machine classes.
*/
/*
* Copyright (C) 2010-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef __UIMachineDefs_h__
#define __UIMachineDefs_h__
/* Global includes */
#include <iprt/cdefs.h>
/* Machine elements enum: */
enum UIVisualElement
{
UIVisualElement_WindowTitle = RT_BIT(0),
UIVisualElement_MouseIntegrationStuff = RT_BIT(1),
UIVisualElement_IndicatorPoolStuff = RT_BIT(2),
UIVisualElement_HDStuff = RT_BIT(3),
UIVisualElement_CDStuff = RT_BIT(4),
UIVisualElement_FDStuff = RT_BIT(5),
UIVisualElement_NetworkStuff = RT_BIT(6),
UIVisualElement_USBStuff = RT_BIT(7),
UIVisualElement_SharedFolderStuff = RT_BIT(8),
UIVisualElement_Display = RT_BIT(9),
UIVisualElement_VideoCapture = RT_BIT(10),
UIVisualElement_FeaturesStuff = RT_BIT(11),
#ifndef Q_WS_MAC
UIVisualElement_MiniToolBar = RT_BIT(12),
#endif /* !Q_WS_MAC */
UIVisualElement_AllStuff = 0xFFFF
};
/* Mouse states enum: */
enum UIMouseStateType
{
UIMouseStateType_MouseCaptured = RT_BIT(0),
UIMouseStateType_MouseAbsolute = RT_BIT(1),
UIMouseStateType_MouseAbsoluteDisabled = RT_BIT(2),
UIMouseStateType_MouseNeedsHostCursor = RT_BIT(3)
};
/* Machine View states enum: */
enum UIViewStateType
{
UIViewStateType_KeyboardCaptured = RT_BIT(0),
UIViewStateType_HostKeyPressed = RT_BIT(1)
};
#endif // __UIMachineDefs_h__
| Java |
/*
* net/dccp/ipv4.c
*
* An implementation of the DCCP protocol
* Arnaldo Carvalho de Melo <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/dccp.h>
#include <linux/icmp.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/random.h>
#include <net/icmp.h>
#include <net/inet_common.h>
#include <net/inet_hashtables.h>
#include <net/inet_sock.h>
#include <net/protocol.h>
#include <net/sock.h>
#include <net/timewait_sock.h>
#include <net/tcp_states.h>
#include <net/xfrm.h>
#include "ackvec.h"
#include "ccid.h"
#include "dccp.h"
#include "feat.h"
/*
* This is the global socket data structure used for responding to
* the Out-of-the-blue (OOTB) packets. A control sock will be created
* for this socket at the initialization time.
*/
static struct socket *dccp_v4_ctl_socket;
static int dccp_v4_get_port(struct sock *sk, const unsigned short snum)
{
return inet_csk_get_port(&dccp_hashinfo, sk, snum,
inet_csk_bind_conflict);
}
int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct rtable *rt;
__be32 daddr, nexthop;
int tmp;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
if (inet->opt != NULL && inet->opt->srr) {
if (daddr == 0)
return -EINVAL;
nexthop = inet->opt->faddr;
}
tmp = ip_route_connect(&rt, nexthop, inet->saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_DCCP,
inet->sport, usin->sin_port, sk);
if (tmp < 0)
return tmp;
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (inet->opt == NULL || !inet->opt->srr)
daddr = rt->rt_dst;
if (inet->saddr == 0)
inet->saddr = rt->rt_src;
inet->rcv_saddr = inet->saddr;
inet->dport = usin->sin_port;
inet->daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet->opt != NULL)
inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;
/*
* Socket identity is still unknown (sport may be zero).
* However we set state to DCCP_REQUESTING and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
dccp_set_state(sk, DCCP_REQUESTING);
err = inet_hash_connect(&dccp_death_row, sk);
if (err != 0)
goto failure;
err = ip_route_newports(&rt, IPPROTO_DCCP, inet->sport, inet->dport,
sk);
if (err != 0)
goto failure;
/* OK, now commit destination to socket. */
sk_setup_caps(sk, &rt->u.dst);
dp->dccps_iss = secure_dccp_sequence_number(inet->saddr, inet->daddr,
inet->sport, inet->dport);
inet->id = dp->dccps_iss ^ jiffies;
err = dccp_connect(sk);
rt = NULL;
if (err != 0)
goto failure;
out:
return err;
failure:
/*
* This unhashes the socket and releases the local port, if necessary.
*/
dccp_set_state(sk, DCCP_CLOSED);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->dport = 0;
goto out;
}
EXPORT_SYMBOL_GPL(dccp_v4_connect);
/*
* This routine does path mtu discovery as defined in RFC1191.
*/
static inline void dccp_do_pmtu_discovery(struct sock *sk,
const struct iphdr *iph,
u32 mtu)
{
struct dst_entry *dst;
const struct inet_sock *inet = inet_sk(sk);
const struct dccp_sock *dp = dccp_sk(sk);
/* We are not interested in DCCP_LISTEN and request_socks (RESPONSEs
* send out by Linux are always < 576bytes so they should go through
* unfragmented).
*/
if (sk->sk_state == DCCP_LISTEN)
return;
/* We don't check in the destentry if pmtu discovery is forbidden
* on this route. We just assume that no packet_to_big packets
* are send back when pmtu discovery is not active.
* There is a small race when the user changes this flag in the
* route, but I think that's acceptable.
*/
if ((dst = __sk_dst_check(sk, 0)) == NULL)
return;
dst->ops->update_pmtu(dst, mtu);
/* Something is about to be wrong... Remember soft error
* for the case, if this connection will not able to recover.
*/
if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst))
sk->sk_err_soft = EMSGSIZE;
mtu = dst_mtu(dst);
if (inet->pmtudisc != IP_PMTUDISC_DONT &&
inet_csk(sk)->icsk_pmtu_cookie > mtu) {
dccp_sync_mss(sk, mtu);
/*
* From RFC 4340, sec. 14.1:
*
* DCCP-Sync packets are the best choice for upward
* probing, since DCCP-Sync probes do not risk application
* data loss.
*/
dccp_send_sync(sk, dp->dccps_gsr, DCCP_PKT_SYNC);
} /* else let the usual retransmit timer handle it */
}
/*
* This routine is called by the ICMP module when it gets some sort of error
* condition. If err < 0 then the socket should be closed and the error
* returned to the user. If err > 0 it's just the icmp type << 8 | icmp code.
* After adjustment header points to the first 8 bytes of the tcp header. We
* need to find the appropriate port.
*
* The locking strategy used here is very "optimistic". When someone else
* accesses the socket the ICMP is just dropped and for some paths there is no
* check at all. A more general error queue to queue errors for later handling
* is probably better.
*/
static void dccp_v4_err(struct sk_buff *skb, u32 info)
{
const struct iphdr *iph = (struct iphdr *)skb->data;
const struct dccp_hdr *dh = (struct dccp_hdr *)(skb->data +
(iph->ihl << 2));
struct dccp_sock *dp;
struct inet_sock *inet;
const int type = skb->h.icmph->type;
const int code = skb->h.icmph->code;
struct sock *sk;
__u64 seq;
int err;
if (skb->len < (iph->ihl << 2) + 8) {
ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
return;
}
sk = inet_lookup(&dccp_hashinfo, iph->daddr, dh->dccph_dport,
iph->saddr, dh->dccph_sport, inet_iif(skb));
if (sk == NULL) {
ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
return;
}
if (sk->sk_state == DCCP_TIME_WAIT) {
inet_twsk_put(inet_twsk(sk));
return;
}
bh_lock_sock(sk);
/* If too many ICMPs get dropped on busy
* servers this needs to be solved differently.
*/
if (sock_owned_by_user(sk))
NET_INC_STATS_BH(LINUX_MIB_LOCKDROPPEDICMPS);
if (sk->sk_state == DCCP_CLOSED)
goto out;
dp = dccp_sk(sk);
seq = dccp_hdr_seq(skb);
if (sk->sk_state != DCCP_LISTEN &&
!between48(seq, dp->dccps_swl, dp->dccps_swh)) {
NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS);
goto out;
}
switch (type) {
case ICMP_SOURCE_QUENCH:
/* Just silently ignore these. */
goto out;
case ICMP_PARAMETERPROB:
err = EPROTO;
break;
case ICMP_DEST_UNREACH:
if (code > NR_ICMP_UNREACH)
goto out;
if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
if (!sock_owned_by_user(sk))
dccp_do_pmtu_discovery(sk, iph, info);
goto out;
}
err = icmp_err_convert[code].errno;
break;
case ICMP_TIME_EXCEEDED:
err = EHOSTUNREACH;
break;
default:
goto out;
}
switch (sk->sk_state) {
struct request_sock *req , **prev;
case DCCP_LISTEN:
if (sock_owned_by_user(sk))
goto out;
req = inet_csk_search_req(sk, &prev, dh->dccph_dport,
iph->daddr, iph->saddr);
if (!req)
goto out;
/*
* ICMPs are not backlogged, hence we cannot get an established
* socket here.
*/
BUG_TRAP(!req->sk);
if (seq != dccp_rsk(req)->dreq_iss) {
NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS);
goto out;
}
/*
* Still in RESPOND, just remove it silently.
* There is no good way to pass the error to the newly
* created socket, and POSIX does not want network
* errors returned from accept().
*/
inet_csk_reqsk_queue_drop(sk, req, prev);
goto out;
case DCCP_REQUESTING:
case DCCP_RESPOND:
if (!sock_owned_by_user(sk)) {
DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS);
sk->sk_err = err;
sk->sk_error_report(sk);
dccp_done(sk);
} else
sk->sk_err_soft = err;
goto out;
}
/* If we've already connected we will keep trying
* until we time out, or the user gives up.
*
* rfc1122 4.2.3.9 allows to consider as hard errors
* only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
* but it is obsoleted by pmtu discovery).
*
* Note, that in modern internet, where routing is unreliable
* and in each dark corner broken firewalls sit, sending random
* errors ordered by their masters even this two messages finally lose
* their original sense (even Linux sends invalid PORT_UNREACHs)
*
* Now we are in compliance with RFCs.
* --ANK (980905)
*/
inet = inet_sk(sk);
if (!sock_owned_by_user(sk) && inet->recverr) {
sk->sk_err = err;
sk->sk_error_report(sk);
} else /* Only an error on timeout */
sk->sk_err_soft = err;
out:
bh_unlock_sock(sk);
sock_put(sk);
}
static inline __sum16 dccp_v4_csum_finish(struct sk_buff *skb,
__be32 src, __be32 dst)
{
return csum_tcpudp_magic(src, dst, skb->len, IPPROTO_DCCP, skb->csum);
}
void dccp_v4_send_check(struct sock *sk, int unused, struct sk_buff *skb)
{
const struct inet_sock *inet = inet_sk(sk);
struct dccp_hdr *dh = dccp_hdr(skb);
dccp_csum_outgoing(skb);
dh->dccph_checksum = dccp_v4_csum_finish(skb, inet->saddr, inet->daddr);
}
EXPORT_SYMBOL_GPL(dccp_v4_send_check);
static inline u64 dccp_v4_init_sequence(const struct sk_buff *skb)
{
return secure_dccp_sequence_number(skb->nh.iph->daddr,
skb->nh.iph->saddr,
dccp_hdr(skb)->dccph_dport,
dccp_hdr(skb)->dccph_sport);
}
/*
* The three way handshake has completed - we got a valid ACK or DATAACK -
* now create the new socket.
*
* This is the equivalent of TCP's tcp_v4_syn_recv_sock
*/
struct sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet_request_sock *ireq;
struct inet_sock *newinet;
struct dccp_sock *newdp;
struct sock *newsk;
if (sk_acceptq_is_full(sk))
goto exit_overflow;
if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL)
goto exit;
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto exit;
sk_setup_caps(newsk, dst);
newdp = dccp_sk(newsk);
newinet = inet_sk(newsk);
ireq = inet_rsk(req);
newinet->daddr = ireq->rmt_addr;
newinet->rcv_saddr = ireq->loc_addr;
newinet->saddr = ireq->loc_addr;
newinet->opt = ireq->opt;
ireq->opt = NULL;
newinet->mc_index = inet_iif(skb);
newinet->mc_ttl = skb->nh.iph->ttl;
newinet->id = jiffies;
dccp_sync_mss(newsk, dst_mtu(dst));
__inet_hash(&dccp_hashinfo, newsk, 0);
__inet_inherit_port(&dccp_hashinfo, sk, newsk);
return newsk;
exit_overflow:
NET_INC_STATS_BH(LINUX_MIB_LISTENOVERFLOWS);
exit:
NET_INC_STATS_BH(LINUX_MIB_LISTENDROPS);
dst_release(dst);
return NULL;
}
EXPORT_SYMBOL_GPL(dccp_v4_request_recv_sock);
static struct sock *dccp_v4_hnd_req(struct sock *sk, struct sk_buff *skb)
{
const struct dccp_hdr *dh = dccp_hdr(skb);
const struct iphdr *iph = skb->nh.iph;
struct sock *nsk;
struct request_sock **prev;
/* Find possible connection requests. */
struct request_sock *req = inet_csk_search_req(sk, &prev,
dh->dccph_sport,
iph->saddr, iph->daddr);
if (req != NULL)
return dccp_check_req(sk, skb, req, prev);
nsk = inet_lookup_established(&dccp_hashinfo,
iph->saddr, dh->dccph_sport,
iph->daddr, dh->dccph_dport,
inet_iif(skb));
if (nsk != NULL) {
if (nsk->sk_state != DCCP_TIME_WAIT) {
bh_lock_sock(nsk);
return nsk;
}
inet_twsk_put(inet_twsk(nsk));
return NULL;
}
return sk;
}
static struct dst_entry* dccp_v4_route_skb(struct sock *sk,
struct sk_buff *skb)
{
struct rtable *rt;
struct flowi fl = { .oif = ((struct rtable *)skb->dst)->rt_iif,
.nl_u = { .ip4_u =
{ .daddr = skb->nh.iph->saddr,
.saddr = skb->nh.iph->daddr,
.tos = RT_CONN_FLAGS(sk) } },
.proto = sk->sk_protocol,
.uli_u = { .ports =
{ .sport = dccp_hdr(skb)->dccph_dport,
.dport = dccp_hdr(skb)->dccph_sport }
}
};
security_skb_classify_flow(skb, &fl);
if (ip_route_output_flow(&rt, &fl, sk, 0)) {
IP_INC_STATS_BH(IPSTATS_MIB_OUTNOROUTES);
return NULL;
}
return &rt->u.dst;
}
static int dccp_v4_send_response(struct sock *sk, struct request_sock *req,
struct dst_entry *dst)
{
int err = -1;
struct sk_buff *skb;
/* First, grab a route. */
if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL)
goto out;
skb = dccp_make_response(sk, dst, req);
if (skb != NULL) {
const struct inet_request_sock *ireq = inet_rsk(req);
struct dccp_hdr *dh = dccp_hdr(skb);
dh->dccph_checksum = dccp_v4_csum_finish(skb, ireq->loc_addr,
ireq->rmt_addr);
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
err = ip_build_and_send_pkt(skb, sk, ireq->loc_addr,
ireq->rmt_addr,
ireq->opt);
err = net_xmit_eval(err);
}
out:
dst_release(dst);
return err;
}
static void dccp_v4_ctl_send_reset(struct sock *sk, struct sk_buff *rxskb)
{
int err;
struct dccp_hdr *rxdh = dccp_hdr(rxskb), *dh;
const int dccp_hdr_reset_len = sizeof(struct dccp_hdr) +
sizeof(struct dccp_hdr_ext) +
sizeof(struct dccp_hdr_reset);
struct sk_buff *skb;
struct dst_entry *dst;
u64 seqno = 0;
/* Never send a reset in response to a reset. */
if (rxdh->dccph_type == DCCP_PKT_RESET)
return;
if (((struct rtable *)rxskb->dst)->rt_type != RTN_LOCAL)
return;
dst = dccp_v4_route_skb(dccp_v4_ctl_socket->sk, rxskb);
if (dst == NULL)
return;
skb = alloc_skb(dccp_v4_ctl_socket->sk->sk_prot->max_header,
GFP_ATOMIC);
if (skb == NULL)
goto out;
/* Reserve space for headers. */
skb_reserve(skb, dccp_v4_ctl_socket->sk->sk_prot->max_header);
skb->dst = dst_clone(dst);
dh = dccp_zeroed_hdr(skb, dccp_hdr_reset_len);
/* Build DCCP header and checksum it. */
dh->dccph_type = DCCP_PKT_RESET;
dh->dccph_sport = rxdh->dccph_dport;
dh->dccph_dport = rxdh->dccph_sport;
dh->dccph_doff = dccp_hdr_reset_len / 4;
dh->dccph_x = 1;
dccp_hdr_reset(skb)->dccph_reset_code =
DCCP_SKB_CB(rxskb)->dccpd_reset_code;
/* See "8.3.1. Abnormal Termination" in RFC 4340 */
if (DCCP_SKB_CB(rxskb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ)
dccp_set_seqno(&seqno, DCCP_SKB_CB(rxskb)->dccpd_ack_seq + 1);
dccp_hdr_set_seq(dh, seqno);
dccp_hdr_set_ack(dccp_hdr_ack_bits(skb), DCCP_SKB_CB(rxskb)->dccpd_seq);
dccp_csum_outgoing(skb);
dh->dccph_checksum = dccp_v4_csum_finish(skb, rxskb->nh.iph->saddr,
rxskb->nh.iph->daddr);
bh_lock_sock(dccp_v4_ctl_socket->sk);
err = ip_build_and_send_pkt(skb, dccp_v4_ctl_socket->sk,
rxskb->nh.iph->daddr,
rxskb->nh.iph->saddr, NULL);
bh_unlock_sock(dccp_v4_ctl_socket->sk);
if (net_xmit_eval(err) == 0) {
DCCP_INC_STATS_BH(DCCP_MIB_OUTSEGS);
DCCP_INC_STATS_BH(DCCP_MIB_OUTRSTS);
}
out:
dst_release(dst);
}
static void dccp_v4_reqsk_destructor(struct request_sock *req)
{
kfree(inet_rsk(req)->opt);
}
static struct request_sock_ops dccp_request_sock_ops __read_mostly = {
.family = PF_INET,
.obj_size = sizeof(struct dccp_request_sock),
.rtx_syn_ack = dccp_v4_send_response,
.send_ack = dccp_reqsk_send_ack,
.destructor = dccp_v4_reqsk_destructor,
.send_reset = dccp_v4_ctl_send_reset,
};
int dccp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
{
struct inet_request_sock *ireq;
struct request_sock *req;
struct dccp_request_sock *dreq;
const __be32 service = dccp_hdr_request(skb)->dccph_req_service;
struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb);
__u8 reset_code = DCCP_RESET_CODE_TOO_BUSY;
/* Never answer to DCCP_PKT_REQUESTs send to broadcast or multicast */
if (((struct rtable *)skb->dst)->rt_flags &
(RTCF_BROADCAST | RTCF_MULTICAST)) {
reset_code = DCCP_RESET_CODE_NO_CONNECTION;
goto drop;
}
if (dccp_bad_service_code(sk, service)) {
reset_code = DCCP_RESET_CODE_BAD_SERVICE_CODE;
goto drop;
}
/*
* TW buckets are converted to open requests without
* limitations, they conserve resources and peer is
* evidently real one.
*/
if (inet_csk_reqsk_queue_is_full(sk))
goto drop;
/*
* Accept backlog is full. If we have already queued enough
* of warm entries in syn queue, drop request. It is better than
* clogging syn queue with openreqs with exponentially increasing
* timeout.
*/
if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1)
goto drop;
req = reqsk_alloc(&dccp_request_sock_ops);
if (req == NULL)
goto drop;
if (dccp_parse_options(sk, skb))
goto drop_and_free;
dccp_reqsk_init(req, skb);
if (security_inet_conn_request(sk, skb, req))
goto drop_and_free;
ireq = inet_rsk(req);
ireq->loc_addr = skb->nh.iph->daddr;
ireq->rmt_addr = skb->nh.iph->saddr;
ireq->opt = NULL;
/*
* Step 3: Process LISTEN state
*
* Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie
*
* In fact we defer setting S.GSR, S.SWL, S.SWH to
* dccp_create_openreq_child.
*/
dreq = dccp_rsk(req);
dreq->dreq_isr = dcb->dccpd_seq;
dreq->dreq_iss = dccp_v4_init_sequence(skb);
dreq->dreq_service = service;
if (dccp_v4_send_response(sk, req, NULL))
goto drop_and_free;
inet_csk_reqsk_queue_hash_add(sk, req, DCCP_TIMEOUT_INIT);
return 0;
drop_and_free:
reqsk_free(req);
drop:
DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS);
dcb->dccpd_reset_code = reset_code;
return -1;
}
EXPORT_SYMBOL_GPL(dccp_v4_conn_request);
int dccp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
{
struct dccp_hdr *dh = dccp_hdr(skb);
if (sk->sk_state == DCCP_OPEN) { /* Fast path */
if (dccp_rcv_established(sk, skb, dh, skb->len))
goto reset;
return 0;
}
/*
* Step 3: Process LISTEN state
* If P.type == Request or P contains a valid Init Cookie option,
* (* Must scan the packet's options to check for Init
* Cookies. Only Init Cookies are processed here,
* however; other options are processed in Step 8. This
* scan need only be performed if the endpoint uses Init
* Cookies *)
* (* Generate a new socket and switch to that socket *)
* Set S := new socket for this port pair
* S.state = RESPOND
* Choose S.ISS (initial seqno) or set from Init Cookies
* Initialize S.GAR := S.ISS
* Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookies
* Continue with S.state == RESPOND
* (* A Response packet will be generated in Step 11 *)
* Otherwise,
* Generate Reset(No Connection) unless P.type == Reset
* Drop packet and return
*
* NOTE: the check for the packet types is done in
* dccp_rcv_state_process
*/
if (sk->sk_state == DCCP_LISTEN) {
struct sock *nsk = dccp_v4_hnd_req(sk, skb);
if (nsk == NULL)
goto discard;
if (nsk != sk) {
if (dccp_child_process(sk, nsk, skb))
goto reset;
return 0;
}
}
if (dccp_rcv_state_process(sk, skb, dh, skb->len))
goto reset;
return 0;
reset:
dccp_v4_ctl_send_reset(sk, skb);
discard:
kfree_skb(skb);
return 0;
}
EXPORT_SYMBOL_GPL(dccp_v4_do_rcv);
/**
* dccp_invalid_packet - check for malformed packets
* Implements RFC 4340, 8.5: Step 1: Check header basics
* Packets that fail these checks are ignored and do not receive Resets.
*/
int dccp_invalid_packet(struct sk_buff *skb)
{
const struct dccp_hdr *dh;
unsigned int cscov;
if (skb->pkt_type != PACKET_HOST)
return 1;
/* If the packet is shorter than 12 bytes, drop packet and return */
if (!pskb_may_pull(skb, sizeof(struct dccp_hdr))) {
DCCP_WARN("pskb_may_pull failed\n");
return 1;
}
dh = dccp_hdr(skb);
/* If P.type is not understood, drop packet and return */
if (dh->dccph_type >= DCCP_PKT_INVALID) {
DCCP_WARN("invalid packet type\n");
return 1;
}
/*
* If P.Data Offset is too small for packet type, drop packet and return
*/
if (dh->dccph_doff < dccp_hdr_len(skb) / sizeof(u32)) {
DCCP_WARN("P.Data Offset(%u) too small\n", dh->dccph_doff);
return 1;
}
/*
* If P.Data Offset is too too large for packet, drop packet and return
*/
if (!pskb_may_pull(skb, dh->dccph_doff * sizeof(u32))) {
DCCP_WARN("P.Data Offset(%u) too large\n", dh->dccph_doff);
return 1;
}
/*
* If P.type is not Data, Ack, or DataAck and P.X == 0 (the packet
* has short sequence numbers), drop packet and return
*/
if (dh->dccph_type >= DCCP_PKT_DATA &&
dh->dccph_type <= DCCP_PKT_DATAACK && dh->dccph_x == 0) {
DCCP_WARN("P.type (%s) not Data || [Data]Ack, while P.X == 0\n",
dccp_packet_name(dh->dccph_type));
return 1;
}
/*
* If P.CsCov is too large for the packet size, drop packet and return.
* This must come _before_ checksumming (not as RFC 4340 suggests).
*/
cscov = dccp_csum_coverage(skb);
if (cscov > skb->len) {
DCCP_WARN("P.CsCov %u exceeds packet length %d\n",
dh->dccph_cscov, skb->len);
return 1;
}
/* If header checksum is incorrect, drop packet and return.
* (This step is completed in the AF-dependent functions.) */
skb->csum = skb_checksum(skb, 0, cscov, 0);
return 0;
}
EXPORT_SYMBOL_GPL(dccp_invalid_packet);
/* this is called when real data arrives */
static int dccp_v4_rcv(struct sk_buff *skb)
{
const struct dccp_hdr *dh;
struct sock *sk;
int min_cov;
/* Step 1: Check header basics */
if (dccp_invalid_packet(skb))
goto discard_it;
/* Step 1: If header checksum is incorrect, drop packet and return */
if (dccp_v4_csum_finish(skb, skb->nh.iph->saddr, skb->nh.iph->daddr)) {
DCCP_WARN("dropped packet with invalid checksum\n");
goto discard_it;
}
dh = dccp_hdr(skb);
DCCP_SKB_CB(skb)->dccpd_seq = dccp_hdr_seq(skb);
DCCP_SKB_CB(skb)->dccpd_type = dh->dccph_type;
dccp_pr_debug("%8.8s "
"src=%u.%u.%u.%u@%-5d "
"dst=%u.%u.%u.%u@%-5d seq=%llu",
dccp_packet_name(dh->dccph_type),
NIPQUAD(skb->nh.iph->saddr), ntohs(dh->dccph_sport),
NIPQUAD(skb->nh.iph->daddr), ntohs(dh->dccph_dport),
(unsigned long long) DCCP_SKB_CB(skb)->dccpd_seq);
if (dccp_packet_without_ack(skb)) {
DCCP_SKB_CB(skb)->dccpd_ack_seq = DCCP_PKT_WITHOUT_ACK_SEQ;
dccp_pr_debug_cat("\n");
} else {
DCCP_SKB_CB(skb)->dccpd_ack_seq = dccp_hdr_ack_seq(skb);
dccp_pr_debug_cat(", ack=%llu\n", (unsigned long long)
DCCP_SKB_CB(skb)->dccpd_ack_seq);
}
/* Step 2:
* Look up flow ID in table and get corresponding socket */
sk = __inet_lookup(&dccp_hashinfo,
skb->nh.iph->saddr, dh->dccph_sport,
skb->nh.iph->daddr, dh->dccph_dport,
inet_iif(skb));
/*
* Step 2:
* If no socket ...
*/
if (sk == NULL) {
dccp_pr_debug("failed to look up flow ID in table and "
"get corresponding socket\n");
goto no_dccp_socket;
}
/*
* Step 2:
* ... or S.state == TIMEWAIT,
* Generate Reset(No Connection) unless P.type == Reset
* Drop packet and return
*/
if (sk->sk_state == DCCP_TIME_WAIT) {
dccp_pr_debug("sk->sk_state == DCCP_TIME_WAIT: do_time_wait\n");
inet_twsk_put(inet_twsk(sk));
goto no_dccp_socket;
}
/*
* RFC 4340, sec. 9.2.1: Minimum Checksum Coverage
* o if MinCsCov = 0, only packets with CsCov = 0 are accepted
* o if MinCsCov > 0, also accept packets with CsCov >= MinCsCov
*/
min_cov = dccp_sk(sk)->dccps_pcrlen;
if (dh->dccph_cscov && (min_cov == 0 || dh->dccph_cscov < min_cov)) {
dccp_pr_debug("Packet CsCov %d does not satisfy MinCsCov %d\n",
dh->dccph_cscov, min_cov);
/* FIXME: "Such packets SHOULD be reported using Data Dropped
* options (Section 11.7) with Drop Code 0, Protocol
* Constraints." */
goto discard_and_relse;
}
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_and_relse;
nf_reset(skb);
return sk_receive_skb(sk, skb, 1);
no_dccp_socket:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard_it;
/*
* Step 2:
* If no socket ...
* Generate Reset(No Connection) unless P.type == Reset
* Drop packet and return
*/
if (dh->dccph_type != DCCP_PKT_RESET) {
DCCP_SKB_CB(skb)->dccpd_reset_code =
DCCP_RESET_CODE_NO_CONNECTION;
dccp_v4_ctl_send_reset(sk, skb);
}
discard_it:
kfree_skb(skb);
return 0;
discard_and_relse:
sock_put(sk);
goto discard_it;
}
static struct inet_connection_sock_af_ops dccp_ipv4_af_ops = {
.queue_xmit = ip_queue_xmit,
.send_check = dccp_v4_send_check,
.rebuild_header = inet_sk_rebuild_header,
.conn_request = dccp_v4_conn_request,
.syn_recv_sock = dccp_v4_request_recv_sock,
.net_header_len = sizeof(struct iphdr),
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.addr2sockaddr = inet_csk_addr2sockaddr,
.sockaddr_len = sizeof(struct sockaddr_in),
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_ip_setsockopt,
.compat_getsockopt = compat_ip_getsockopt,
#endif
};
static int dccp_v4_init_sock(struct sock *sk)
{
static __u8 dccp_v4_ctl_sock_initialized;
int err = dccp_init_sock(sk, dccp_v4_ctl_sock_initialized);
if (err == 0) {
if (unlikely(!dccp_v4_ctl_sock_initialized))
dccp_v4_ctl_sock_initialized = 1;
inet_csk(sk)->icsk_af_ops = &dccp_ipv4_af_ops;
}
return err;
}
static struct timewait_sock_ops dccp_timewait_sock_ops = {
.twsk_obj_size = sizeof(struct inet_timewait_sock),
};
static struct proto dccp_v4_prot = {
.name = "DCCP",
.owner = THIS_MODULE,
.close = dccp_close,
.connect = dccp_v4_connect,
.disconnect = dccp_disconnect,
.ioctl = dccp_ioctl,
.init = dccp_v4_init_sock,
.setsockopt = dccp_setsockopt,
.getsockopt = dccp_getsockopt,
.sendmsg = dccp_sendmsg,
.recvmsg = dccp_recvmsg,
.backlog_rcv = dccp_v4_do_rcv,
.hash = dccp_hash,
.unhash = dccp_unhash,
.accept = inet_csk_accept,
.get_port = dccp_v4_get_port,
.shutdown = dccp_shutdown,
.destroy = dccp_destroy_sock,
.orphan_count = &dccp_orphan_count,
.max_header = MAX_DCCP_HEADER,
.obj_size = sizeof(struct dccp_sock),
.rsk_prot = &dccp_request_sock_ops,
.twsk_prot = &dccp_timewait_sock_ops,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_dccp_setsockopt,
.compat_getsockopt = compat_dccp_getsockopt,
#endif
};
static struct net_protocol dccp_v4_protocol = {
.handler = dccp_v4_rcv,
.err_handler = dccp_v4_err,
.no_policy = 1,
};
static const struct proto_ops inet_dccp_ops = {
.family = PF_INET,
.owner = THIS_MODULE,
.release = inet_release,
.bind = inet_bind,
.connect = inet_stream_connect,
.socketpair = sock_no_socketpair,
.accept = inet_accept,
.getname = inet_getname,
/* FIXME: work on tcp_poll to rename it to inet_csk_poll */
.poll = dccp_poll,
.ioctl = inet_ioctl,
/* FIXME: work on inet_listen to rename it to sock_common_listen */
.listen = inet_dccp_listen,
.shutdown = inet_shutdown,
.setsockopt = sock_common_setsockopt,
.getsockopt = sock_common_getsockopt,
.sendmsg = inet_sendmsg,
.recvmsg = sock_common_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
static struct inet_protosw dccp_v4_protosw = {
.type = SOCK_DCCP,
.protocol = IPPROTO_DCCP,
.prot = &dccp_v4_prot,
.ops = &inet_dccp_ops,
.capability = -1,
.no_check = 0,
.flags = INET_PROTOSW_ICSK,
};
static int __init dccp_v4_init(void)
{
int err = proto_register(&dccp_v4_prot, 1);
if (err != 0)
goto out;
err = inet_add_protocol(&dccp_v4_protocol, IPPROTO_DCCP);
if (err != 0)
goto out_proto_unregister;
inet_register_protosw(&dccp_v4_protosw);
err = inet_csk_ctl_sock_create(&dccp_v4_ctl_socket, PF_INET,
SOCK_DCCP, IPPROTO_DCCP);
if (err)
goto out_unregister_protosw;
out:
return err;
out_unregister_protosw:
inet_unregister_protosw(&dccp_v4_protosw);
inet_del_protocol(&dccp_v4_protocol, IPPROTO_DCCP);
out_proto_unregister:
proto_unregister(&dccp_v4_prot);
goto out;
}
static void __exit dccp_v4_exit(void)
{
inet_unregister_protosw(&dccp_v4_protosw);
inet_del_protocol(&dccp_v4_protocol, IPPROTO_DCCP);
proto_unregister(&dccp_v4_prot);
}
module_init(dccp_v4_init);
module_exit(dccp_v4_exit);
/*
* __stringify doesn't likes enums, so use SOCK_DCCP (6) and IPPROTO_DCCP (33)
* values directly, Also cover the case where the protocol is not specified,
* i.e. net-pf-PF_INET-proto-0-type-SOCK_DCCP
*/
MODULE_ALIAS("net-pf-" __stringify(PF_INET) "-proto-33-type-6");
MODULE_ALIAS("net-pf-" __stringify(PF_INET) "-proto-0-type-6");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arnaldo Carvalho de Melo <[email protected]>");
MODULE_DESCRIPTION("DCCP - Datagram Congestion Controlled Protocol");
| Java |
#ifndef __TYPES_V7__
#define __TYPES_V7__
#if defined(_WIN32) && defined(_MSC_VER)
# define ALIGN_PREFIX(bytes) __declspec(align(bytes))
# define ALIGN_POSTFIX(bytes)
# define FUNC_DEF_INLINE __inline
# define FUNC_DEF_EXTERN_INLINE extern __inline
#elif defined(__GNUC__)
# define ALIGN_PREFIX(bytes)
# define ALIGN_POSTFIX(bytes) __attribute__ ((aligned(bytes)))
# if defined (_DEBUG)
# define FUNC_DEF_EXTERN_INLINE extern __inline
# define FUNC_DEF_INLINE static __inline
# else
# define FUNC_DEF_EXTERN_INLINE extern __inline
# define FUNC_DEF_INLINE static __inline
# endif
#else
# define ALIGN_PREFIX(bytes)
# define ALIGN_POSTFIX(bytes)
# error UNKNOWN COMPILER AND OS
#endif
#define ALIGN16_PREFIX ALIGN_PREFIX(16)
#define ALIGN16_POSTFIX ALIGN_POSTFIX(16)
#define FUNC_CALL_TYPE __fastcall
#define FUNC_DEF_EXTERN extern
typedef signed long long int64;
typedef signed int int32;
typedef signed short int16;
typedef signed char int8;
typedef unsigned long long uint64;
typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef float float4[4];
typedef int32 int32_4[4];
typedef float float44[4][4];
typedef float ALIGN16_PREFIX vec4[4] ALIGN16_POSTFIX;
typedef int32 ALIGN16_PREFIX ivec4[4] ALIGN16_POSTFIX;
typedef float ALIGN16_PREFIX mtx[4][4] ALIGN16_POSTFIX;
typedef float ALIGN16_PREFIX quat[4] ALIGN16_POSTFIX;
typedef union _intf {
float f;
int32 i;
} intf;
#endif//__TYPES__ | Java |
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 1999 - 2008, Digium, Inc.
*
* Mark Spencer <[email protected]>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Core PBX routines.
*
* \author Mark Spencer <[email protected]>
*/
/*** MODULEINFO
<support_level>core</support_level>
***/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 388532 $")
#include "asterisk/_private.h"
#include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
#include <ctype.h>
#include <time.h>
#include <sys/time.h>
#if defined(HAVE_SYSINFO)
#include <sys/sysinfo.h>
#endif
#if defined(SOLARIS)
#include <sys/loadavg.h>
#endif
#include "asterisk/lock.h"
#include "asterisk/cli.h"
#include "asterisk/pbx.h"
#include "asterisk/channel.h"
#include "asterisk/file.h"
#include "asterisk/callerid.h"
#include "asterisk/cdr.h"
#include "asterisk/cel.h"
#include "asterisk/config.h"
#include "asterisk/term.h"
#include "asterisk/time.h"
#include "asterisk/manager.h"
#include "asterisk/ast_expr.h"
#include "asterisk/linkedlists.h"
#define SAY_STUBS /* generate declarations and stubs for say methods */
#include "asterisk/say.h"
#include "asterisk/utils.h"
#include "asterisk/causes.h"
#include "asterisk/musiconhold.h"
#include "asterisk/app.h"
#include "asterisk/devicestate.h"
#include "asterisk/event.h"
#include "asterisk/hashtab.h"
#include "asterisk/module.h"
#include "asterisk/indications.h"
#include "asterisk/taskprocessor.h"
#include "asterisk/xmldoc.h"
#include "asterisk/astobj2.h"
/*!
* \note I M P O R T A N T :
*
* The speed of extension handling will likely be among the most important
* aspects of this PBX. The switching scheme as it exists right now isn't
* terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
* of priorities, but a constant search time here would be great ;-)
*
* A new algorithm to do searching based on a 'compiled' pattern tree is introduced
* here, and shows a fairly flat (constant) search time, even for over
* 10000 patterns.
*
* Also, using a hash table for context/priority name lookup can help prevent
* the find_extension routines from absorbing exponential cpu cycles as the number
* of contexts/priorities grow. I've previously tested find_extension with red-black trees,
* which have O(log2(n)) speed. Right now, I'm using hash tables, which do
* searches (ideally) in O(1) time. While these techniques do not yield much
* speed in small dialplans, they are worth the trouble in large dialplans.
*
*/
/*** DOCUMENTATION
<application name="Answer" language="en_US">
<synopsis>
Answer a channel if ringing.
</synopsis>
<syntax>
<parameter name="delay">
<para>Asterisk will wait this number of milliseconds before returning to
the dialplan after answering the call.</para>
</parameter>
<parameter name="nocdr">
<para>Asterisk will send an answer signal to the calling phone, but will not
set the disposition or answer time in the CDR for this call.</para>
</parameter>
</syntax>
<description>
<para>If the call has not been answered, this application will
answer it. Otherwise, it has no effect on the call.</para>
</description>
<see-also>
<ref type="application">Hangup</ref>
</see-also>
</application>
<application name="BackGround" language="en_US">
<synopsis>
Play an audio file while waiting for digits of an extension to go to.
</synopsis>
<syntax>
<parameter name="filenames" required="true" argsep="&">
<argument name="filename1" required="true" />
<argument name="filename2" multiple="true" />
</parameter>
<parameter name="options">
<optionlist>
<option name="s">
<para>Causes the playback of the message to be skipped
if the channel is not in the <literal>up</literal> state (i.e. it
hasn't been answered yet). If this happens, the
application will return immediately.</para>
</option>
<option name="n">
<para>Don't answer the channel before playing the files.</para>
</option>
<option name="m">
<para>Only break if a digit hit matches a one digit
extension in the destination context.</para>
</option>
</optionlist>
</parameter>
<parameter name="langoverride">
<para>Explicitly specifies which language to attempt to use for the requested sound files.</para>
</parameter>
<parameter name="context">
<para>This is the dialplan context that this application will use when exiting
to a dialed extension.</para>
</parameter>
</syntax>
<description>
<para>This application will play the given list of files <emphasis>(do not put extension)</emphasis>
while waiting for an extension to be dialed by the calling channel. To continue waiting
for digits after this application has finished playing files, the <literal>WaitExten</literal>
application should be used.</para>
<para>If one of the requested sound files does not exist, call processing will be terminated.</para>
<para>This application sets the following channel variable upon completion:</para>
<variablelist>
<variable name="BACKGROUNDSTATUS">
<para>The status of the background attempt as a text string.</para>
<value name="SUCCESS" />
<value name="FAILED" />
</variable>
</variablelist>
</description>
<see-also>
<ref type="application">ControlPlayback</ref>
<ref type="application">WaitExten</ref>
<ref type="application">BackgroundDetect</ref>
<ref type="function">TIMEOUT</ref>
</see-also>
</application>
<application name="Busy" language="en_US">
<synopsis>
Indicate the Busy condition.
</synopsis>
<syntax>
<parameter name="timeout">
<para>If specified, the calling channel will be hung up after the specified number of seconds.
Otherwise, this application will wait until the calling channel hangs up.</para>
</parameter>
</syntax>
<description>
<para>This application will indicate the busy condition to the calling channel.</para>
</description>
<see-also>
<ref type="application">Congestion</ref>
<ref type="application">Progress</ref>
<ref type="application">Playtones</ref>
<ref type="application">Hangup</ref>
</see-also>
</application>
<application name="Congestion" language="en_US">
<synopsis>
Indicate the Congestion condition.
</synopsis>
<syntax>
<parameter name="timeout">
<para>If specified, the calling channel will be hung up after the specified number of seconds.
Otherwise, this application will wait until the calling channel hangs up.</para>
</parameter>
</syntax>
<description>
<para>This application will indicate the congestion condition to the calling channel.</para>
</description>
<see-also>
<ref type="application">Busy</ref>
<ref type="application">Progress</ref>
<ref type="application">Playtones</ref>
<ref type="application">Hangup</ref>
</see-also>
</application>
<application name="ExecIfTime" language="en_US">
<synopsis>
Conditional application execution based on the current time.
</synopsis>
<syntax argsep="?">
<parameter name="day_condition" required="true">
<argument name="times" required="true" />
<argument name="weekdays" required="true" />
<argument name="mdays" required="true" />
<argument name="months" required="true" />
<argument name="timezone" required="false" />
</parameter>
<parameter name="appname" required="true" hasparams="optional">
<argument name="appargs" required="true" />
</parameter>
</syntax>
<description>
<para>This application will execute the specified dialplan application, with optional
arguments, if the current time matches the given time specification.</para>
</description>
<see-also>
<ref type="application">Exec</ref>
<ref type="application">ExecIf</ref>
<ref type="application">TryExec</ref>
<ref type="application">GotoIfTime</ref>
</see-also>
</application>
<application name="Goto" language="en_US">
<synopsis>
Jump to a particular priority, extension, or context.
</synopsis>
<syntax>
<parameter name="context" />
<parameter name="extensions" />
<parameter name="priority" required="true" />
</syntax>
<description>
<para>This application will set the current context, extension, and priority in the channel structure.
After it completes, the pbx engine will continue dialplan execution at the specified location.
If no specific <replaceable>extension</replaceable>, or <replaceable>extension</replaceable> and
<replaceable>context</replaceable>, are specified, then this application will
just set the specified <replaceable>priority</replaceable> of the current extension.</para>
<para>At least a <replaceable>priority</replaceable> is required as an argument, or the goto will
return a <literal>-1</literal>, and the channel and call will be terminated.</para>
<para>If the location that is put into the channel information is bogus, and asterisk cannot
find that location in the dialplan, then the execution engine will try to find and execute the code in
the <literal>i</literal> (invalid) extension in the current context. If that does not exist, it will try to execute the
<literal>h</literal> extension. If neither the <literal>h</literal> nor <literal>i</literal> extensions
have been defined, the channel is hung up, and the execution of instructions on the channel is terminated.
What this means is that, for example, you specify a context that does not exist, then
it will not be possible to find the <literal>h</literal> or <literal>i</literal> extensions,
and the call will terminate!</para>
</description>
<see-also>
<ref type="application">GotoIf</ref>
<ref type="application">GotoIfTime</ref>
<ref type="application">Gosub</ref>
<ref type="application">Macro</ref>
</see-also>
</application>
<application name="GotoIf" language="en_US">
<synopsis>
Conditional goto.
</synopsis>
<syntax argsep="?">
<parameter name="condition" required="true" />
<parameter name="destination" required="true" argsep=":">
<argument name="labeliftrue">
<para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true.
Takes the form similar to Goto() of [[context,]extension,]priority.</para>
</argument>
<argument name="labeliffalse">
<para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false.
Takes the form similar to Goto() of [[context,]extension,]priority.</para>
</argument>
</parameter>
</syntax>
<description>
<para>This application will set the current context, extension, and priority in the channel structure
based on the evaluation of the given condition. After this application completes, the
pbx engine will continue dialplan execution at the specified location in the dialplan.
The labels are specified with the same syntax as used within the Goto application.
If the label chosen by the condition is omitted, no jump is performed, and the execution passes to the
next instruction. If the target location is bogus, and does not exist, the execution engine will try
to find and execute the code in the <literal>i</literal> (invalid) extension in the current context.
If that does not exist, it will try to execute the <literal>h</literal> extension.
If neither the <literal>h</literal> nor <literal>i</literal> extensions have been defined,
the channel is hung up, and the execution of instructions on the channel is terminated.
Remember that this command can set the current context, and if the context specified
does not exist, then it will not be able to find any 'h' or 'i' extensions there, and
the channel and call will both be terminated!.</para>
</description>
<see-also>
<ref type="application">Goto</ref>
<ref type="application">GotoIfTime</ref>
<ref type="application">GosubIf</ref>
<ref type="application">MacroIf</ref>
</see-also>
</application>
<application name="GotoIfTime" language="en_US">
<synopsis>
Conditional Goto based on the current time.
</synopsis>
<syntax argsep="?">
<parameter name="condition" required="true">
<argument name="times" required="true" />
<argument name="weekdays" required="true" />
<argument name="mdays" required="true" />
<argument name="months" required="true" />
<argument name="timezone" required="false" />
</parameter>
<parameter name="destination" required="true" argsep=":">
<argument name="labeliftrue">
<para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true.
Takes the form similar to Goto() of [[context,]extension,]priority.</para>
</argument>
<argument name="labeliffalse">
<para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false.
Takes the form similar to Goto() of [[context,]extension,]priority.</para>
</argument>
</parameter>
</syntax>
<description>
<para>This application will set the context, extension, and priority in the channel structure
based on the evaluation of the given time specification. After this application completes,
the pbx engine will continue dialplan execution at the specified location in the dialplan.
If the current time is within the given time specification, the channel will continue at
<replaceable>labeliftrue</replaceable>. Otherwise the channel will continue at <replaceable>labeliffalse</replaceable>.
If the label chosen by the condition is omitted, no jump is performed, and execution passes to the next
instruction. If the target jump location is bogus, the same actions would be taken as for <literal>Goto</literal>.
Further information on the time specification can be found in examples
illustrating how to do time-based context includes in the dialplan.</para>
</description>
<see-also>
<ref type="application">GotoIf</ref>
<ref type="application">Goto</ref>
<ref type="function">IFTIME</ref>
<ref type="function">TESTTIME</ref>
</see-also>
</application>
<application name="ImportVar" language="en_US">
<synopsis>
Import a variable from a channel into a new variable.
</synopsis>
<syntax argsep="=">
<parameter name="newvar" required="true" />
<parameter name="vardata" required="true">
<argument name="channelname" required="true" />
<argument name="variable" required="true" />
</parameter>
</syntax>
<description>
<para>This application imports a <replaceable>variable</replaceable> from the specified
<replaceable>channel</replaceable> (as opposed to the current one) and stores it as a variable
(<replaceable>newvar</replaceable>) in the current channel (the channel that is calling this
application). Variables created by this application have the same inheritance properties as those
created with the <literal>Set</literal> application.</para>
</description>
<see-also>
<ref type="application">Set</ref>
</see-also>
</application>
<application name="Hangup" language="en_US">
<synopsis>
Hang up the calling channel.
</synopsis>
<syntax>
<parameter name="causecode">
<para>If a <replaceable>causecode</replaceable> is given the channel's
hangup cause will be set to the given value.</para>
</parameter>
</syntax>
<description>
<para>This application will hang up the calling channel.</para>
</description>
<see-also>
<ref type="application">Answer</ref>
<ref type="application">Busy</ref>
<ref type="application">Congestion</ref>
</see-also>
</application>
<application name="Incomplete" language="en_US">
<synopsis>
Returns AST_PBX_INCOMPLETE value.
</synopsis>
<syntax>
<parameter name="n">
<para>If specified, then Incomplete will not attempt to answer the channel first.</para>
<note><para>Most channel types need to be in Answer state in order to receive DTMF.</para></note>
</parameter>
</syntax>
<description>
<para>Signals the PBX routines that the previous matched extension is incomplete
and that further input should be allowed before matching can be considered
to be complete. Can be used within a pattern match when certain criteria warrants
a longer match.</para>
</description>
</application>
<application name="NoOp" language="en_US">
<synopsis>
Do Nothing (No Operation).
</synopsis>
<syntax>
<parameter name="text">
<para>Any text provided can be viewed at the Asterisk CLI.</para>
</parameter>
</syntax>
<description>
<para>This application does nothing. However, it is useful for debugging purposes.</para>
<para>This method can be used to see the evaluations of variables or functions without having any effect.</para>
</description>
<see-also>
<ref type="application">Verbose</ref>
<ref type="application">Log</ref>
</see-also>
</application>
<application name="Proceeding" language="en_US">
<synopsis>
Indicate proceeding.
</synopsis>
<syntax />
<description>
<para>This application will request that a proceeding message be provided to the calling channel.</para>
</description>
</application>
<application name="Progress" language="en_US">
<synopsis>
Indicate progress.
</synopsis>
<syntax />
<description>
<para>This application will request that in-band progress information be provided to the calling channel.</para>
</description>
<see-also>
<ref type="application">Busy</ref>
<ref type="application">Congestion</ref>
<ref type="application">Ringing</ref>
<ref type="application">Playtones</ref>
</see-also>
</application>
<application name="RaiseException" language="en_US">
<synopsis>
Handle an exceptional condition.
</synopsis>
<syntax>
<parameter name="reason" required="true" />
</syntax>
<description>
<para>This application will jump to the <literal>e</literal> extension in the current context, setting the
dialplan function EXCEPTION(). If the <literal>e</literal> extension does not exist, the call will hangup.</para>
</description>
<see-also>
<ref type="function">Exception</ref>
</see-also>
</application>
<application name="ResetCDR" language="en_US">
<synopsis>
Resets the Call Data Record.
</synopsis>
<syntax>
<parameter name="options">
<optionlist>
<option name="w">
<para>Store the current CDR record before resetting it.</para>
</option>
<option name="a">
<para>Store any stacked records.</para>
</option>
<option name="v">
<para>Save CDR variables.</para>
</option>
<option name="e">
<para>Enable CDR only (negate effects of NoCDR).</para>
</option>
</optionlist>
</parameter>
</syntax>
<description>
<para>This application causes the Call Data Record to be reset.</para>
</description>
<see-also>
<ref type="application">ForkCDR</ref>
<ref type="application">NoCDR</ref>
</see-also>
</application>
<application name="Ringing" language="en_US">
<synopsis>
Indicate ringing tone.
</synopsis>
<syntax />
<description>
<para>This application will request that the channel indicate a ringing tone to the user.</para>
</description>
<see-also>
<ref type="application">Busy</ref>
<ref type="application">Congestion</ref>
<ref type="application">Progress</ref>
<ref type="application">Playtones</ref>
</see-also>
</application>
<application name="SayAlpha" language="en_US">
<synopsis>
Say Alpha.
</synopsis>
<syntax>
<parameter name="string" required="true" />
</syntax>
<description>
<para>This application will play the sounds that correspond to the letters of the
given <replaceable>string</replaceable>.</para>
</description>
<see-also>
<ref type="application">SayDigits</ref>
<ref type="application">SayNumber</ref>
<ref type="application">SayPhonetic</ref>
<ref type="function">CHANNEL</ref>
</see-also>
</application>
<application name="SayDigits" language="en_US">
<synopsis>
Say Digits.
</synopsis>
<syntax>
<parameter name="digits" required="true" />
</syntax>
<description>
<para>This application will play the sounds that correspond to the digits of
the given number. This will use the language that is currently set for the channel.</para>
</description>
<see-also>
<ref type="application">SayAlpha</ref>
<ref type="application">SayNumber</ref>
<ref type="application">SayPhonetic</ref>
<ref type="function">CHANNEL</ref>
</see-also>
</application>
<application name="SayNumber" language="en_US">
<synopsis>
Say Number.
</synopsis>
<syntax>
<parameter name="digits" required="true" />
<parameter name="gender" />
</syntax>
<description>
<para>This application will play the sounds that correspond to the given <replaceable>digits</replaceable>.
Optionally, a <replaceable>gender</replaceable> may be specified. This will use the language that is currently
set for the channel. See the CHANNEL() function for more information on setting the language for the channel.</para>
</description>
<see-also>
<ref type="application">SayAlpha</ref>
<ref type="application">SayDigits</ref>
<ref type="application">SayPhonetic</ref>
<ref type="function">CHANNEL</ref>
</see-also>
</application>
<application name="SayPhonetic" language="en_US">
<synopsis>
Say Phonetic.
</synopsis>
<syntax>
<parameter name="string" required="true" />
</syntax>
<description>
<para>This application will play the sounds from the phonetic alphabet that correspond to the
letters in the given <replaceable>string</replaceable>.</para>
</description>
<see-also>
<ref type="application">SayAlpha</ref>
<ref type="application">SayDigits</ref>
<ref type="application">SayNumber</ref>
</see-also>
</application>
<application name="Set" language="en_US">
<synopsis>
Set channel variable or function value.
</synopsis>
<syntax argsep="=">
<parameter name="name" required="true" />
<parameter name="value" required="true" />
</syntax>
<description>
<para>This function can be used to set the value of channel variables or dialplan functions.
When setting variables, if the variable name is prefixed with <literal>_</literal>,
the variable will be inherited into channels created from the current channel.
If the variable name is prefixed with <literal>__</literal>, the variable will be
inherited into channels created from the current channel and all children channels.</para>
<note><para>If (and only if), in <filename>/etc/asterisk/asterisk.conf</filename>, you have
a <literal>[compat]</literal> category, and you have <literal>app_set = 1.4</literal> under that, then
the behavior of this app changes, and strips surrounding quotes from the right hand side as
it did previously in 1.4.
The advantages of not stripping out quoting, and not caring about the separator characters (comma and vertical bar)
were sufficient to make these changes in 1.6. Confusion about how many backslashes would be needed to properly
protect separators and quotes in various database access strings has been greatly
reduced by these changes.</para></note>
</description>
<see-also>
<ref type="application">MSet</ref>
<ref type="function">GLOBAL</ref>
<ref type="function">SET</ref>
<ref type="function">ENV</ref>
</see-also>
</application>
<application name="MSet" language="en_US">
<synopsis>
Set channel variable(s) or function value(s).
</synopsis>
<syntax>
<parameter name="set1" required="true" argsep="=">
<argument name="name1" required="true" />
<argument name="value1" required="true" />
</parameter>
<parameter name="set2" multiple="true" argsep="=">
<argument name="name2" required="true" />
<argument name="value2" required="true" />
</parameter>
</syntax>
<description>
<para>This function can be used to set the value of channel variables or dialplan functions.
When setting variables, if the variable name is prefixed with <literal>_</literal>,
the variable will be inherited into channels created from the current channel
If the variable name is prefixed with <literal>__</literal>, the variable will be
inherited into channels created from the current channel and all children channels.
MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus
prone to doing things that you may not expect. For example, it strips surrounding
double-quotes from the right-hand side (value). If you need to put a separator
character (comma or vert-bar), you will need to escape them by inserting a backslash
before them. Avoid its use if possible.</para>
</description>
<see-also>
<ref type="application">Set</ref>
</see-also>
</application>
<application name="SetAMAFlags" language="en_US">
<synopsis>
Set the AMA Flags.
</synopsis>
<syntax>
<parameter name="flag" />
</syntax>
<description>
<para>This application will set the channel's AMA Flags for billing purposes.</para>
</description>
<see-also>
<ref type="function">CDR</ref>
</see-also>
</application>
<application name="Wait" language="en_US">
<synopsis>
Waits for some time.
</synopsis>
<syntax>
<parameter name="seconds" required="true">
<para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
application to wait for 1.5 seconds.</para>
</parameter>
</syntax>
<description>
<para>This application waits for a specified number of <replaceable>seconds</replaceable>.</para>
</description>
</application>
<application name="WaitExten" language="en_US">
<synopsis>
Waits for an extension to be entered.
</synopsis>
<syntax>
<parameter name="seconds">
<para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
application to wait for 1.5 seconds.</para>
</parameter>
<parameter name="options">
<optionlist>
<option name="m">
<para>Provide music on hold to the caller while waiting for an extension.</para>
<argument name="x">
<para>Specify the class for music on hold. <emphasis>CHANNEL(musicclass) will
be used instead if set</emphasis></para>
</argument>
</option>
</optionlist>
</parameter>
</syntax>
<description>
<para>This application waits for the user to enter a new extension for a specified number
of <replaceable>seconds</replaceable>.</para>
<xi:include xpointer="xpointer(/docs/application[@name='Macro']/description/warning[2])" />
</description>
<see-also>
<ref type="application">Background</ref>
<ref type="function">TIMEOUT</ref>
</see-also>
</application>
<function name="EXCEPTION" language="en_US">
<synopsis>
Retrieve the details of the current dialplan exception.
</synopsis>
<syntax>
<parameter name="field" required="true">
<para>The following fields are available for retrieval:</para>
<enumlist>
<enum name="reason">
<para>INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom
value set by the RaiseException() application</para>
</enum>
<enum name="context">
<para>The context executing when the exception occurred.</para>
</enum>
<enum name="exten">
<para>The extension executing when the exception occurred.</para>
</enum>
<enum name="priority">
<para>The numeric priority executing when the exception occurred.</para>
</enum>
</enumlist>
</parameter>
</syntax>
<description>
<para>Retrieve the details (specified <replaceable>field</replaceable>) of the current dialplan exception.</para>
</description>
<see-also>
<ref type="application">RaiseException</ref>
</see-also>
</function>
<function name="TESTTIME" language="en_US">
<synopsis>
Sets a time to be used with the channel to test logical conditions.
</synopsis>
<syntax>
<parameter name="date" required="true" argsep=" ">
<para>Date in ISO 8601 format</para>
</parameter>
<parameter name="time" required="true" argsep=" ">
<para>Time in HH:MM:SS format (24-hour time)</para>
</parameter>
<parameter name="zone" required="false">
<para>Timezone name</para>
</parameter>
</syntax>
<description>
<para>To test dialplan timing conditions at times other than the current time, use
this function to set an alternate date and time. For example, you may wish to evaluate
whether a location will correctly identify to callers that the area is closed on Christmas
Day, when Christmas would otherwise fall on a day when the office is normally open.</para>
</description>
<see-also>
<ref type="application">GotoIfTime</ref>
</see-also>
</function>
<manager name="ShowDialPlan" language="en_US">
<synopsis>
Show dialplan contexts and extensions
</synopsis>
<syntax>
<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
<parameter name="Extension">
<para>Show a specific extension.</para>
</parameter>
<parameter name="Context">
<para>Show a specific context.</para>
</parameter>
</syntax>
<description>
<para>Show dialplan contexts and extensions. Be aware that showing the full dialplan
may take a lot of capacity.</para>
</description>
</manager>
***/
#ifdef LOW_MEMORY
#define EXT_DATA_SIZE 256
#else
#define EXT_DATA_SIZE 8192
#endif
#define SWITCH_DATA_LENGTH 256
#define VAR_BUF_SIZE 4096
#define VAR_NORMAL 1
#define VAR_SOFTTRAN 2
#define VAR_HARDTRAN 3
#define BACKGROUND_SKIP (1 << 0)
#define BACKGROUND_NOANSWER (1 << 1)
#define BACKGROUND_MATCHEXTEN (1 << 2)
#define BACKGROUND_PLAYBACK (1 << 3)
AST_APP_OPTIONS(background_opts, {
AST_APP_OPTION('s', BACKGROUND_SKIP),
AST_APP_OPTION('n', BACKGROUND_NOANSWER),
AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
});
#define WAITEXTEN_MOH (1 << 0)
#define WAITEXTEN_DIALTONE (1 << 1)
AST_APP_OPTIONS(waitexten_opts, {
AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
});
struct ast_context;
struct ast_app;
static struct ast_taskprocessor *device_state_tps;
AST_THREADSTORAGE(switch_data);
AST_THREADSTORAGE(extensionstate_buf);
/*!
\brief ast_exten: An extension
The dialplan is saved as a linked list with each context
having it's own linked list of extensions - one item per
priority.
*/
struct ast_exten {
char *exten; /*!< Extension name */
int matchcid; /*!< Match caller id ? */
const char *cidmatch; /*!< Caller id to match for this extension */
int priority; /*!< Priority */
const char *label; /*!< Label */
struct ast_context *parent; /*!< The context this extension belongs to */
const char *app; /*!< Application to execute */
struct ast_app *cached_app; /*!< Cached location of application */
void *data; /*!< Data to use (arguments) */
void (*datad)(void *); /*!< Data destructor */
struct ast_exten *peer; /*!< Next higher priority with our extension */
struct ast_hashtab *peer_table; /*!< Priorities list in hashtab form -- only on the head of the peer list */
struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */
const char *registrar; /*!< Registrar */
struct ast_exten *next; /*!< Extension with a greater ID */
char stuff[0];
};
/*! \brief ast_include: include= support in extensions.conf */
struct ast_include {
const char *name;
const char *rname; /*!< Context to include */
const char *registrar; /*!< Registrar */
int hastime; /*!< If time construct exists */
struct ast_timing timing; /*!< time construct */
struct ast_include *next; /*!< Link them together */
char stuff[0];
};
/*! \brief ast_sw: Switch statement in extensions.conf */
struct ast_sw {
char *name;
const char *registrar; /*!< Registrar */
char *data; /*!< Data load */
int eval;
AST_LIST_ENTRY(ast_sw) list;
char stuff[0];
};
/*! \brief ast_ignorepat: Ignore patterns in dial plan */
struct ast_ignorepat {
const char *registrar;
struct ast_ignorepat *next;
const char pattern[0];
};
/*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
struct match_char
{
int is_pattern; /* the pattern started with '_' */
int deleted; /* if this is set, then... don't return it */
int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
struct match_char *alt_char;
struct match_char *next_char;
struct ast_exten *exten; /* attached to last char of a pattern for exten */
char x[1]; /* the pattern itself-- matches a single char */
};
struct scoreboard /* make sure all fields are 0 before calling new_find_extension */
{
int total_specificity;
int total_length;
char last_char; /* set to ! or . if they are the end of the pattern */
int canmatch; /* if the string to match was just too short */
struct match_char *node;
struct ast_exten *canmatch_exten;
struct ast_exten *exten;
};
/*! \brief ast_context: An extension context */
struct ast_context {
ast_rwlock_t lock; /*!< A lock to prevent multiple threads from clobbering the context */
struct ast_exten *root; /*!< The root of the list of extensions */
struct ast_hashtab *root_table; /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree */
struct match_char *pattern_tree; /*!< A tree to speed up extension pattern matching */
struct ast_context *next; /*!< Link them together */
struct ast_include *includes; /*!< Include other contexts */
struct ast_ignorepat *ignorepats; /*!< Patterns for which to continue playing dialtone */
char *registrar; /*!< Registrar -- make sure you malloc this, as the registrar may have to survive module unloads */
int refcount; /*!< each module that would have created this context should inc/dec this as appropriate */
AST_LIST_HEAD_NOLOCK(, ast_sw) alts; /*!< Alternative switches */
ast_mutex_t macrolock; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
char name[0]; /*!< Name of the context */
};
/*! \brief ast_app: A registered application */
struct ast_app {
int (*execute)(struct ast_channel *chan, const char *data);
AST_DECLARE_STRING_FIELDS(
AST_STRING_FIELD(synopsis); /*!< Synopsis text for 'show applications' */
AST_STRING_FIELD(description); /*!< Description (help text) for 'show application <name>' */
AST_STRING_FIELD(syntax); /*!< Syntax text for 'core show applications' */
AST_STRING_FIELD(arguments); /*!< Arguments description */
AST_STRING_FIELD(seealso); /*!< See also */
);
#ifdef AST_XML_DOCS
enum ast_doc_src docsrc; /*!< Where the documentation come from. */
#endif
AST_RWLIST_ENTRY(ast_app) list; /*!< Next app in list */
struct ast_module *module; /*!< Module this app belongs to */
char name[0]; /*!< Name of the application */
};
/*! \brief ast_state_cb: An extension state notify register item */
struct ast_state_cb {
/*! Watcher ID returned when registered. */
int id;
/*! Arbitrary data passed for callbacks. */
void *data;
/*! Callback when state changes. */
ast_state_cb_type change_cb;
/*! Callback when destroyed so any resources given by the registerer can be freed. */
ast_state_cb_destroy_type destroy_cb;
/*! \note Only used by ast_merge_contexts_and_delete */
AST_LIST_ENTRY(ast_state_cb) entry;
};
/*!
* \brief Structure for dial plan hints
*
* \note Hints are pointers from an extension in the dialplan to
* one or more devices (tech/name)
*
* See \ref AstExtState
*/
struct ast_hint {
/*!
* \brief Hint extension
*
* \note
* Will never be NULL while the hint is in the hints container.
*/
struct ast_exten *exten;
struct ao2_container *callbacks; /*!< Callback container for this extension */
int laststate; /*!< Last known state */
char context_name[AST_MAX_CONTEXT];/*!< Context of destroyed hint extension. */
char exten_name[AST_MAX_EXTENSION];/*!< Extension of destroyed hint extension. */
};
/* --- Hash tables of various objects --------*/
#ifdef LOW_MEMORY
#define HASH_EXTENHINT_SIZE 17
#else
#define HASH_EXTENHINT_SIZE 563
#endif
static const struct cfextension_states {
int extension_state;
const char * const text;
} extension_states[] = {
{ AST_EXTENSION_NOT_INUSE, "Idle" },
{ AST_EXTENSION_INUSE, "InUse" },
{ AST_EXTENSION_BUSY, "Busy" },
{ AST_EXTENSION_UNAVAILABLE, "Unavailable" },
{ AST_EXTENSION_RINGING, "Ringing" },
{ AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
{ AST_EXTENSION_ONHOLD, "Hold" },
{ AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD, "InUse&Hold" }
};
struct statechange {
AST_LIST_ENTRY(statechange) entry;
char dev[0];
};
struct pbx_exception {
AST_DECLARE_STRING_FIELDS(
AST_STRING_FIELD(context); /*!< Context associated with this exception */
AST_STRING_FIELD(exten); /*!< Exten associated with this exception */
AST_STRING_FIELD(reason); /*!< The exception reason */
);
int priority; /*!< Priority associated with this exception */
};
static int pbx_builtin_answer(struct ast_channel *, const char *);
static int pbx_builtin_goto(struct ast_channel *, const char *);
static int pbx_builtin_hangup(struct ast_channel *, const char *);
static int pbx_builtin_background(struct ast_channel *, const char *);
static int pbx_builtin_wait(struct ast_channel *, const char *);
static int pbx_builtin_waitexten(struct ast_channel *, const char *);
static int pbx_builtin_incomplete(struct ast_channel *, const char *);
static int pbx_builtin_resetcdr(struct ast_channel *, const char *);
static int pbx_builtin_setamaflags(struct ast_channel *, const char *);
static int pbx_builtin_ringing(struct ast_channel *, const char *);
static int pbx_builtin_proceeding(struct ast_channel *, const char *);
static int pbx_builtin_progress(struct ast_channel *, const char *);
static int pbx_builtin_congestion(struct ast_channel *, const char *);
static int pbx_builtin_busy(struct ast_channel *, const char *);
static int pbx_builtin_noop(struct ast_channel *, const char *);
static int pbx_builtin_gotoif(struct ast_channel *, const char *);
static int pbx_builtin_gotoiftime(struct ast_channel *, const char *);
static int pbx_builtin_execiftime(struct ast_channel *, const char *);
static int pbx_builtin_saynumber(struct ast_channel *, const char *);
static int pbx_builtin_saydigits(struct ast_channel *, const char *);
static int pbx_builtin_saycharacters(struct ast_channel *, const char *);
static int pbx_builtin_sayphonetic(struct ast_channel *, const char *);
static int matchcid(const char *cidpattern, const char *callerid);
#ifdef NEED_DEBUG
static void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */
#endif
static int pbx_builtin_importvar(struct ast_channel *, const char *);
static void set_ext_pri(struct ast_channel *c, const char *exten, int pri);
static void new_find_extension(const char *str, struct scoreboard *score,
struct match_char *tree, int length, int spec, const char *callerid,
const char *label, enum ext_match_t action);
static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern);
static struct match_char *add_exten_to_pattern_tree(struct ast_context *con,
struct ast_exten *e1, int findonly);
static void create_match_char_tree(struct ast_context *con);
static struct ast_exten *get_canmatch_exten(struct match_char *node);
static void destroy_pattern_tree(struct match_char *pattern_tree);
static int hashtab_compare_extens(const void *ha_a, const void *ah_b);
static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b);
static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b);
static unsigned int hashtab_hash_extens(const void *obj);
static unsigned int hashtab_hash_priority(const void *obj);
static unsigned int hashtab_hash_labels(const void *obj);
static void __ast_internal_context_destroy( struct ast_context *con);
static int ast_add_extension_nolock(const char *context, int replace, const char *extension,
int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *), const char *registrar);
static int ast_add_extension2_lockopt(struct ast_context *con,
int replace, const char *extension, int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *),
const char *registrar, int lock_context);
static struct ast_context *find_context_locked(const char *context);
static struct ast_context *find_context(const char *context);
/*!
* \internal
* \brief Character array comparison function for qsort.
*
* \param a Left side object.
* \param b Right side object.
*
* \retval <0 if a < b
* \retval =0 if a = b
* \retval >0 if a > b
*/
static int compare_char(const void *a, const void *b)
{
const unsigned char *ac = a;
const unsigned char *bc = b;
return *ac - *bc;
}
/* labels, contexts are case sensitive priority numbers are ints */
int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
{
const struct ast_context *ac = ah_a;
const struct ast_context *bc = ah_b;
if (!ac || !bc) /* safety valve, but it might prevent a crash you'd rather have happen */
return 1;
/* assume context names are registered in a string table! */
return strcmp(ac->name, bc->name);
}
static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
int x = strcmp(ac->exten, bc->exten);
if (x) { /* if exten names are diff, then return */
return x;
}
/* but if they are the same, do the cidmatch values match? */
if (ac->matchcid && bc->matchcid) {
return strcmp(ac->cidmatch,bc->cidmatch);
} else if (!ac->matchcid && !bc->matchcid) {
return 0; /* if there's no matchcid on either side, then this is a match */
} else {
return 1; /* if there's matchcid on one but not the other, they are different */
}
}
static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
return ac->priority != bc->priority;
}
static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
{
const struct ast_exten *ac = ah_a;
const struct ast_exten *bc = ah_b;
return strcmp(S_OR(ac->label, ""), S_OR(bc->label, ""));
}
unsigned int ast_hashtab_hash_contexts(const void *obj)
{
const struct ast_context *ac = obj;
return ast_hashtab_hash_string(ac->name);
}
static unsigned int hashtab_hash_extens(const void *obj)
{
const struct ast_exten *ac = obj;
unsigned int x = ast_hashtab_hash_string(ac->exten);
unsigned int y = 0;
if (ac->matchcid)
y = ast_hashtab_hash_string(ac->cidmatch);
return x+y;
}
static unsigned int hashtab_hash_priority(const void *obj)
{
const struct ast_exten *ac = obj;
return ast_hashtab_hash_int(ac->priority);
}
static unsigned int hashtab_hash_labels(const void *obj)
{
const struct ast_exten *ac = obj;
return ast_hashtab_hash_string(S_OR(ac->label, ""));
}
AST_RWLOCK_DEFINE_STATIC(globalslock);
static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
static int autofallthrough = 1;
static int extenpatternmatchnew = 0;
static char *overrideswitch = NULL;
/*! \brief Subscription for device state change events */
static struct ast_event_sub *device_state_sub;
AST_MUTEX_DEFINE_STATIC(maxcalllock);
static int countcalls;
static int totalcalls;
static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
/*! \brief Declaration of builtin applications */
static struct pbx_builtin {
char name[AST_MAX_APP];
int (*execute)(struct ast_channel *chan, const char *data);
} builtins[] =
{
/* These applications are built into the PBX core and do not
need separate modules */
{ "Answer", pbx_builtin_answer },
{ "BackGround", pbx_builtin_background },
{ "Busy", pbx_builtin_busy },
{ "Congestion", pbx_builtin_congestion },
{ "ExecIfTime", pbx_builtin_execiftime },
{ "Goto", pbx_builtin_goto },
{ "GotoIf", pbx_builtin_gotoif },
{ "GotoIfTime", pbx_builtin_gotoiftime },
{ "ImportVar", pbx_builtin_importvar },
{ "Hangup", pbx_builtin_hangup },
{ "Incomplete", pbx_builtin_incomplete },
{ "NoOp", pbx_builtin_noop },
{ "Proceeding", pbx_builtin_proceeding },
{ "Progress", pbx_builtin_progress },
{ "RaiseException", pbx_builtin_raise_exception },
{ "ResetCDR", pbx_builtin_resetcdr },
{ "Ringing", pbx_builtin_ringing },
{ "SayAlpha", pbx_builtin_saycharacters },
{ "SayDigits", pbx_builtin_saydigits },
{ "SayNumber", pbx_builtin_saynumber },
{ "SayPhonetic", pbx_builtin_sayphonetic },
{ "Set", pbx_builtin_setvar },
{ "MSet", pbx_builtin_setvar_multiple },
{ "SetAMAFlags", pbx_builtin_setamaflags },
{ "Wait", pbx_builtin_wait },
{ "WaitExten", pbx_builtin_waitexten }
};
static struct ast_context *contexts;
static struct ast_hashtab *contexts_table = NULL;
/*!
* \brief Lock for the ast_context list
* \note
* This lock MUST be recursive, or a deadlock on reload may result. See
* https://issues.asterisk.org/view.php?id=17643
*/
AST_MUTEX_DEFINE_STATIC(conlock);
/*!
* \brief Lock to hold off restructuring of hints by ast_merge_contexts_and_delete.
*/
AST_MUTEX_DEFINE_STATIC(context_merge_lock);
static AST_RWLIST_HEAD_STATIC(apps, ast_app);
static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
static int stateid = 1;
/*!
* \note When holding this container's lock, do _not_ do
* anything that will cause conlock to be taken, unless you
* _already_ hold it. The ast_merge_contexts_and_delete function
* will take the locks in conlock/hints order, so any other
* paths that require both locks must also take them in that
* order.
*/
static struct ao2_container *hints;
static struct ao2_container *statecbs;
#ifdef CONTEXT_DEBUG
/* these routines are provided for doing run-time checks
on the extension structures, in case you are having
problems, this routine might help you localize where
the problem is occurring. It's kinda like a debug memory
allocator's arena checker... It'll eat up your cpu cycles!
but you'll see, if you call it in the right places,
right where your problems began...
*/
/* you can break on the check_contexts_trouble()
routine in your debugger to stop at the moment
there's a problem */
void check_contexts_trouble(void);
void check_contexts_trouble(void)
{
int x = 1;
x = 2;
}
int check_contexts(char *, int);
int check_contexts(char *file, int line )
{
struct ast_hashtab_iter *t1;
struct ast_context *c1, *c2;
int found = 0;
struct ast_exten *e1, *e2, *e3;
struct ast_exten ex;
/* try to find inconsistencies */
/* is every context in the context table in the context list and vice-versa ? */
if (!contexts_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: No contexts_table!\n", file, line);
usleep(500000);
}
t1 = ast_hashtab_start_traversal(contexts_table);
while( (c1 = ast_hashtab_next(t1))) {
for(c2=contexts;c2;c2=c2->next) {
if (!strcmp(c1->name, c2->name)) {
found = 1;
break;
}
}
if (!found) {
ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the linked list\n", file, line, c1->name);
check_contexts_trouble();
}
}
ast_hashtab_end_traversal(t1);
for(c2=contexts;c2;c2=c2->next) {
c1 = find_context_locked(c2->name);
if (!c1) {
ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the hashtab\n", file, line, c2->name);
check_contexts_trouble();
} else
ast_unlock_contexts();
}
/* loop thru all contexts, and verify the exten structure compares to the
hashtab structure */
for(c2=contexts;c2;c2=c2->next) {
c1 = find_context_locked(c2->name);
if (c1) {
ast_unlock_contexts();
/* is every entry in the root list also in the root_table? */
for(e1 = c1->root; e1; e1=e1->next)
{
char dummy_name[1024];
ex.exten = dummy_name;
ex.matchcid = e1->matchcid;
ex.cidmatch = e1->cidmatch;
ast_copy_string(dummy_name, e1->exten, sizeof(dummy_name));
e2 = ast_hashtab_lookup(c1->root_table, &ex);
if (!e2) {
if (e1->matchcid) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s (CID match: %s) but it is not in its root_table\n", file, line, c2->name, dummy_name, e1->cidmatch );
} else {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, dummy_name );
}
check_contexts_trouble();
}
}
/* is every entry in the root_table also in the root list? */
if (!c2->root_table) {
if (c2->root) {
ast_log(LOG_NOTICE,"Called from: %s:%d: No c2->root_table for context %s!\n", file, line, c2->name);
usleep(500000);
}
} else {
t1 = ast_hashtab_start_traversal(c2->root_table);
while( (e2 = ast_hashtab_next(t1)) ) {
for(e1=c2->root;e1;e1=e1->next) {
if (!strcmp(e1->exten, e2->exten)) {
found = 1;
break;
}
}
if (!found) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, e2->exten);
check_contexts_trouble();
}
}
ast_hashtab_end_traversal(t1);
}
}
/* is every priority reflected in the peer_table at the head of the list? */
/* is every entry in the root list also in the root_table? */
/* are the per-extension peer_tables in the right place? */
for(e1 = c2->root; e1; e1 = e1->next) {
for(e2=e1;e2;e2=e2->peer) {
ex.priority = e2->priority;
if (e2 != e1 && e2->peer_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
if (e2 != e1 && e2->peer_label_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_label_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
if (e2 == e1 && !e2->peer_table){
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_table!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
if (e2 == e1 && !e2->peer_label_table) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_label_table!\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
e3 = ast_hashtab_lookup(e1->peer_table, &ex);
if (!e3) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer_table\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
}
if (!e1->peer_table){
ast_log(LOG_NOTICE,"Called from: %s:%d: No e1->peer_table!\n", file, line);
usleep(500000);
}
/* is every entry in the peer_table also in the peer list? */
t1 = ast_hashtab_start_traversal(e1->peer_table);
while( (e2 = ast_hashtab_next(t1)) ) {
for(e3=e1;e3;e3=e3->peer) {
if (e3->priority == e2->priority) {
found = 1;
break;
}
}
if (!found) {
ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer list\n", file, line, c2->name, e1->exten, e2->priority );
check_contexts_trouble();
}
}
ast_hashtab_end_traversal(t1);
}
}
return 0;
}
#endif
/*
\note This function is special. It saves the stack so that no matter
how many times it is called, it returns to the same place */
int pbx_exec(struct ast_channel *c, /*!< Channel */
struct ast_app *app, /*!< Application */
const char *data) /*!< Data for execution */
{
int res;
struct ast_module_user *u = NULL;
const char *saved_c_appl;
const char *saved_c_data;
if (c->cdr && !ast_check_hangup(c))
ast_cdr_setapp(c->cdr, app->name, data);
/* save channel values */
saved_c_appl= c->appl;
saved_c_data= c->data;
c->appl = app->name;
c->data = data;
ast_cel_report_event(c, AST_CEL_APP_START, NULL, NULL, NULL);
if (app->module)
u = __ast_module_user_add(app->module, c);
if (strcasecmp(app->name, "system") && !ast_strlen_zero(data) &&
strchr(data, '|') && !strchr(data, ',') && !ast_opt_dont_warn) {
ast_log(LOG_WARNING, "The application delimiter is now the comma, not "
"the pipe. Did you forget to convert your dialplan? (%s(%s))\n",
app->name, (char *) data);
}
res = app->execute(c, S_OR(data, ""));
if (app->module && u)
__ast_module_user_remove(app->module, u);
ast_cel_report_event(c, AST_CEL_APP_END, NULL, NULL, NULL);
/* restore channel values */
c->appl = saved_c_appl;
c->data = saved_c_data;
return res;
}
/*! Go no deeper than this through includes (not counting loops) */
#define AST_PBX_MAX_STACK 128
/*! \brief Find application handle in linked list
*/
struct ast_app *pbx_findapp(const char *app)
{
struct ast_app *tmp;
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, tmp, list) {
if (!strcasecmp(tmp->name, app))
break;
}
AST_RWLIST_UNLOCK(&apps);
return tmp;
}
static struct ast_switch *pbx_findswitch(const char *sw)
{
struct ast_switch *asw;
AST_RWLIST_RDLOCK(&switches);
AST_RWLIST_TRAVERSE(&switches, asw, list) {
if (!strcasecmp(asw->name, sw))
break;
}
AST_RWLIST_UNLOCK(&switches);
return asw;
}
static inline int include_valid(struct ast_include *i)
{
if (!i->hastime)
return 1;
return ast_check_timing(&(i->timing));
}
static void pbx_destroy(struct ast_pbx *p)
{
ast_free(p);
}
/* form a tree that fully describes all the patterns in a context's extensions
* in this tree, a "node" represents an individual character or character set
* meant to match the corresponding character in a dial string. The tree
* consists of a series of match_char structs linked in a chain
* via the alt_char pointers. More than one pattern can share the same parts of the
* tree as other extensions with the same pattern to that point.
* My first attempt to duplicate the finding of the 'best' pattern was flawed in that
* I misunderstood the general algorithm. I thought that the 'best' pattern
* was the one with lowest total score. This was not true. Thus, if you have
* patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
* the "best" match because it has fewer X's, and is therefore more specific,
* but this is not how the old algorithm works. It sorts matching patterns
* in a similar collating sequence as sorting alphabetic strings, from left to
* right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
* because "1" is more specific than "X".
* So, to accomodate this philosophy, I sort the tree branches along the alt_char
* line so they are lowest to highest in specificity numbers. This way, as soon
* as we encounter our first complete match, we automatically have the "best"
* match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
* If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
* they are welcome to revert pbx to before 1 Apr 2008.
* As an example, consider these 4 extensions:
* (a) NXXNXXXXXX
* (b) 307754XXXX
* (c) fax
* (d) NXXXXXXXXX
*
* In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
* most numbers. For all numbers beginning with 307754, (b) should always win.
*
* These pattern should form a (sorted) tree that looks like this:
* { "3" } --next--> { "0" } --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
* |
* |alt
* |
* { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) }
* { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
* | |
* | |alt
* |alt |
* | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
* |
* NULL
*
* In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
* fewer CPU cycles than a call to strchr("23456789",*z), where *z is the char to match...
*
* traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern, it calls itself
* on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
* We pass a pointer to a scoreboard down through, also.
* The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
* The first complete match ends the traversal, which should make this version of the pattern matcher faster
* the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
* these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
* according to the sort criteria.
* Hope the limit on stack depth won't be a problem... this routine should
* be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
*
* In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d. All are
* of length 10; they have total specificities of 24580, 10246, and 25090, respectively, not that this matters
* at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
* left the specificity totals in the code as an artifact; at some point, I will strip it out.
*
* Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
* because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
* can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
* more times faster in extreme cases.
*
* MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
* can have patterns in your CID field as well.
*
* */
static void update_scoreboard(struct scoreboard *board, int length, int spec, struct ast_exten *exten, char last, const char *callerid, int deleted, struct match_char *node)
{
/* if this extension is marked as deleted, then skip this -- if it never shows
on the scoreboard, it will never be found, nor will halt the traversal. */
if (deleted)
return;
board->total_specificity = spec;
board->total_length = length;
board->exten = exten;
board->last_char = last;
board->node = node;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
#endif
}
#ifdef NEED_DEBUG
static void log_match_char_tree(struct match_char *node, char *prefix)
{
char extenstr[40];
struct ast_str *my_prefix = ast_str_alloca(1024);
extenstr[0] = '\0';
if (node && node->exten)
snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
if (strlen(node->x) > 1) {
ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
node->exten ? node->exten->exten : "", extenstr);
} else {
ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
node->exten ? node->exten->exten : "", extenstr);
}
ast_str_set(&my_prefix, 0, "%s+ ", prefix);
if (node->next_char)
log_match_char_tree(node->next_char, ast_str_buffer(my_prefix));
if (node->alt_char)
log_match_char_tree(node->alt_char, prefix);
}
#endif
static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
{
char extenstr[40];
struct ast_str *my_prefix = ast_str_alloca(1024);
extenstr[0] = '\0';
if (node->exten) {
snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
}
if (strlen(node->x) > 1) {
ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
node->exten ? node->exten->exten : "", extenstr);
} else {
ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
node->exten ? node->exten->exten : "", extenstr);
}
ast_str_set(&my_prefix, 0, "%s+ ", prefix);
if (node->next_char)
cli_match_char_tree(node->next_char, ast_str_buffer(my_prefix), fd);
if (node->alt_char)
cli_match_char_tree(node->alt_char, prefix, fd);
}
static struct ast_exten *get_canmatch_exten(struct match_char *node)
{
/* find the exten at the end of the rope */
struct match_char *node2 = node;
for (node2 = node; node2; node2 = node2->next_char) {
if (node2->exten) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
#endif
return node2->exten;
}
}
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
#endif
return 0;
}
static struct ast_exten *trie_find_next_match(struct match_char *node)
{
struct match_char *m3;
struct match_char *m4;
struct ast_exten *e3;
if (node && node->x[0] == '.' && !node->x[1]) { /* dot and ! will ALWAYS be next match in a matchmore */
return node->exten;
}
if (node && node->x[0] == '!' && !node->x[1]) {
return node->exten;
}
if (!node || !node->next_char) {
return NULL;
}
m3 = node->next_char;
if (m3->exten) {
return m3->exten;
}
for (m4 = m3->alt_char; m4; m4 = m4->alt_char) {
if (m4->exten) {
return m4->exten;
}
}
for (m4 = m3; m4; m4 = m4->alt_char) {
e3 = trie_find_next_match(m3);
if (e3) {
return e3;
}
}
return NULL;
}
#ifdef DEBUG_THIS
static char *action2str(enum ext_match_t action)
{
switch (action) {
case E_MATCH:
return "MATCH";
case E_CANMATCH:
return "CANMATCH";
case E_MATCHMORE:
return "MATCHMORE";
case E_FINDLABEL:
return "FINDLABEL";
case E_SPAWN:
return "SPAWN";
default:
return "?ACTION?";
}
}
#endif
static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, const char *label, enum ext_match_t action)
{
struct match_char *p; /* note minimal stack storage requirements */
struct ast_exten pattern = { .label = label };
#ifdef DEBUG_THIS
if (tree)
ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action));
else
ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action));
#endif
for (p = tree; p; p = p->alt_char) {
if (p->is_pattern) {
if (p->x[0] == 'N') {
if (p->x[1] == 0 && *str >= '2' && *str <= '9' ) {
#define NEW_MATCHER_CHK_MATCH \
if (p->exten && !(*(str + 1))) { /* if a shorter pattern matches along the way, might as well report it */ \
if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */ \
update_scoreboard(score, length + 1, spec + p->specificity, p->exten, 0, callerid, p->deleted, p); \
if (!p->deleted) { \
if (action == E_FINDLABEL) { \
if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) { \
ast_debug(4, "Found label in preferred extension\n"); \
return; \
} \
} else { \
ast_debug(4, "returning an exact match-- first found-- %s\n", p->exten->exten); \
return; /* the first match, by definition, will be the best, because of the sorted tree */ \
} \
} \
} \
}
#define NEW_MATCHER_RECURSE \
if (p->next_char && (*(str + 1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0) \
|| p->next_char->x[0] == '!')) { \
if (*(str + 1) || p->next_char->x[0] == '!') { \
new_find_extension(str + 1, score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \
if (score->exten) { \
ast_debug(4 ,"returning an exact match-- %s\n", score->exten->exten); \
return; /* the first match is all we need */ \
} \
} else { \
new_find_extension("/", score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { \
ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten : \
"NULL"); \
return; /* the first match is all we need */ \
} \
} \
} else if ((p->next_char || action == E_CANMATCH) && !*(str + 1)) { \
score->canmatch = 1; \
score->canmatch_exten = get_canmatch_exten(p); \
if (action == E_CANMATCH || action == E_MATCHMORE) { \
ast_debug(4, "returning a canmatch/matchmore--- str=%s\n", str); \
return; \
} \
}
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (p->x[0] == 'Z') {
if (p->x[1] == 0 && *str >= '1' && *str <= '9' ) {
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (p->x[0] == 'X') {
if (p->x[1] == 0 && *str >= '0' && *str <= '9' ) {
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (p->x[0] == '.' && p->x[1] == 0) {
/* how many chars will the . match against? */
int i = 0;
const char *str2 = str;
while (*str2 && *str2 != '/') {
str2++;
i++;
}
if (p->exten && *str2 != '/') {
update_scoreboard(score, length + i, spec + (i * p->specificity), p->exten, '.', callerid, p->deleted, p);
if (score->exten) {
ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score->exten->exten);
return; /* the first match is all we need */
}
}
if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
new_find_extension("/", score, p->next_char, length + i, spec+(p->specificity*i), callerid, label, action);
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score->exten ? score->exten->exten : "NULL");
return; /* the first match is all we need */
}
}
} else if (p->x[0] == '!' && p->x[1] == 0) {
/* how many chars will the . match against? */
int i = 1;
const char *str2 = str;
while (*str2 && *str2 != '/') {
str2++;
i++;
}
if (p->exten && *str2 != '/') {
update_scoreboard(score, length + 1, spec + (p->specificity * i), p->exten, '!', callerid, p->deleted, p);
if (score->exten) {
ast_debug(4, "return because scoreboard has a '!' match--- %s\n", score->exten->exten);
return; /* the first match is all we need */
}
}
if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
new_find_extension("/", score, p->next_char, length + i, spec + (p->specificity * i), callerid, label, action);
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score->exten ? score->exten->exten : "NULL");
return; /* the first match is all we need */
}
}
} else if (p->x[0] == '/' && p->x[1] == 0) {
/* the pattern in the tree includes the cid match! */
if (p->next_char && callerid && *callerid) {
new_find_extension(callerid, score, p->next_char, length + 1, spec, callerid, label, action);
if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score->exten ? score->exten->exten : "NULL");
return; /* the first match is all we need */
}
}
} else if (strchr(p->x, *str)) {
ast_debug(4, "Nothing strange about this match\n");
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
} else if (strchr(p->x, *str)) {
ast_debug(4, "Nothing strange about this match\n");
NEW_MATCHER_CHK_MATCH;
NEW_MATCHER_RECURSE;
}
}
ast_debug(4, "return at end of func\n");
}
/* the algorithm for forming the extension pattern tree is also a bit simple; you
* traverse all the extensions in a context, and for each char of the extension,
* you see if it exists in the tree; if it doesn't, you add it at the appropriate
* spot. What more can I say? At the end of each exten, you cap it off by adding the
* address of the extension involved. Duplicate patterns will be complained about.
*
* Ideally, this would be done for each context after it is created and fully
* filled. It could be done as a finishing step after extensions.conf or .ael is
* loaded, or it could be done when the first search is encountered. It should only
* have to be done once, until the next unload or reload.
*
* I guess forming this pattern tree would be analogous to compiling a regex. Except
* that a regex only handles 1 pattern, really. This trie holds any number
* of patterns. Well, really, it **could** be considered a single pattern,
* where the "|" (or) operator is allowed, I guess, in a way, sort of...
*/
static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern)
{
struct match_char *t;
if (!current) {
return 0;
}
for (t = current; t; t = t->alt_char) {
if (is_pattern == t->is_pattern && !strcmp(pat, t->x)) {/* uh, we may want to sort exploded [] contents to make matching easy */
return t;
}
}
return 0;
}
/* The first arg is the location of the tree ptr, or the
address of the next_char ptr in the node, so we can mess
with it, if we need to insert at the beginning of the list */
static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node)
{
struct match_char *curr, *lcurr;
/* insert node into the tree at "current", so the alt_char list from current is
sorted in increasing value as you go to the leaves */
if (!(*parent_ptr)) {
*parent_ptr = node;
return;
}
if ((*parent_ptr)->specificity > node->specificity) {
/* insert at head */
node->alt_char = (*parent_ptr);
*parent_ptr = node;
return;
}
lcurr = *parent_ptr;
for (curr = (*parent_ptr)->alt_char; curr; curr = curr->alt_char) {
if (curr->specificity > node->specificity) {
node->alt_char = curr;
lcurr->alt_char = node;
break;
}
lcurr = curr;
}
if (!curr) {
lcurr->alt_char = node;
}
}
struct pattern_node {
/*! Pattern node specificity */
int specif;
/*! Pattern node match characters. */
char buf[256];
};
static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, const struct pattern_node *pattern, int is_pattern, int already, struct match_char **nextcharptr)
{
struct match_char *m;
if (!(m = ast_calloc(1, sizeof(*m) + strlen(pattern->buf)))) {
return NULL;
}
/* strcpy is safe here since we know its size and have allocated
* just enough space for when we allocated m
*/
strcpy(m->x, pattern->buf);
/* the specificity scores are the same as used in the old
pattern matcher. */
m->is_pattern = is_pattern;
if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'N') {
m->specificity = 0x0832;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'Z') {
m->specificity = 0x0931;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'X') {
m->specificity = 0x0a30;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == '.') {
m->specificity = 0x18000;
} else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == '!') {
m->specificity = 0x28000;
} else {
m->specificity = pattern->specif;
}
if (!con->pattern_tree) {
insert_in_next_chars_alt_char_list(&con->pattern_tree, m);
} else {
if (already) { /* switch to the new regime (traversing vs appending)*/
insert_in_next_chars_alt_char_list(nextcharptr, m);
} else {
insert_in_next_chars_alt_char_list(¤t->next_char, m);
}
}
return m;
}
/*!
* \internal
* \brief Extract the next exten pattern node.
*
* \param node Pattern node to fill.
* \param src Next source character to read.
* \param pattern TRUE if the exten is a pattern.
* \param extenbuf Original exten buffer to use in diagnostic messages.
*
* \retval Ptr to next extenbuf pos to read.
*/
static const char *get_pattern_node(struct pattern_node *node, const char *src, int pattern, const char *extenbuf)
{
#define INC_DST_OVERFLOW_CHECK \
do { \
if (dst - node->buf < sizeof(node->buf) - 1) { \
++dst; \
} else { \
overflow = 1; \
} \
} while (0)
node->specif = 0;
node->buf[0] = '\0';
while (*src) {
if (*src == '[' && pattern) {
char *dst = node->buf;
const char *src_next;
int length;
int overflow = 0;
/* get past the '[' */
++src;
for (;;) {
if (*src == '\\') {
/* Escaped character. */
++src;
if (*src == '[' || *src == '\\' || *src == '-' || *src == ']') {
*dst = *src++;
INC_DST_OVERFLOW_CHECK;
}
} else if (*src == '-') {
unsigned char first;
unsigned char last;
src_next = src;
first = *(src_next - 1);
last = *++src_next;
if (last == '\\') {
/* Escaped character. */
last = *++src_next;
}
/* Possible char range. */
if (node->buf[0] && last) {
/* Expand the char range. */
while (++first <= last) {
*dst = first;
INC_DST_OVERFLOW_CHECK;
}
src = src_next + 1;
} else {
/*
* There was no left or right char for the range.
* It is just a '-'.
*/
*dst = *src++;
INC_DST_OVERFLOW_CHECK;
}
} else if (*src == '\0') {
ast_log(LOG_WARNING,
"A matching ']' was not found for '[' in exten pattern '%s'\n",
extenbuf);
break;
} else if (*src == ']') {
++src;
break;
} else {
*dst = *src++;
INC_DST_OVERFLOW_CHECK;
}
}
/* null terminate the exploded range */
*dst = '\0';
if (overflow) {
ast_log(LOG_ERROR,
"Expanded character set too large to deal with in exten pattern '%s'. Ignoring character set.\n",
extenbuf);
node->buf[0] = '\0';
continue;
}
/* Sort the characters in character set. */
length = strlen(node->buf);
if (!length) {
ast_log(LOG_WARNING, "Empty character set in exten pattern '%s'. Ignoring.\n",
extenbuf);
node->buf[0] = '\0';
continue;
}
qsort(node->buf, length, 1, compare_char);
/* Remove duplicate characters from character set. */
dst = node->buf;
src_next = node->buf;
while (*src_next++) {
if (*dst != *src_next) {
*++dst = *src_next;
}
}
length = strlen(node->buf);
length <<= 8;
node->specif = length | (unsigned char) node->buf[0];
break;
} else if (*src == '-') {
/* Skip dashes in all extensions. */
++src;
} else {
if (*src == '\\') {
/*
* XXX The escape character here does not remove any special
* meaning to characters except the '[', '\\', and '-'
* characters since they are special only in this function.
*/
node->buf[0] = *++src;
if (!node->buf[0]) {
break;
}
} else {
node->buf[0] = *src;
if (pattern) {
/* make sure n,x,z patterns are canonicalized to N,X,Z */
if (node->buf[0] == 'n') {
node->buf[0] = 'N';
} else if (node->buf[0] == 'x') {
node->buf[0] = 'X';
} else if (node->buf[0] == 'z') {
node->buf[0] = 'Z';
}
}
}
node->buf[1] = '\0';
node->specif = 1;
++src;
break;
}
}
return src;
#undef INC_DST_OVERFLOW_CHECK
}
static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly)
{
struct match_char *m1 = NULL;
struct match_char *m2 = NULL;
struct match_char **m0;
const char *pos;
int already;
int pattern = 0;
int idx_cur;
int idx_next;
char extenbuf[512];
struct pattern_node pat_node[2];
if (e1->matchcid) {
if (sizeof(extenbuf) < strlen(e1->exten) + strlen(e1->cidmatch) + 2) {
ast_log(LOG_ERROR,
"The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n",
e1->exten, e1->cidmatch);
return NULL;
}
sprintf(extenbuf, "%s/%s", e1->exten, e1->cidmatch);/* Safe. We just checked. */
} else {
ast_copy_string(extenbuf, e1->exten, sizeof(extenbuf));
}
#ifdef NEED_DEBUG
ast_log(LOG_DEBUG, "Adding exten %s to tree\n", extenbuf);
#endif
m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */
m0 = &con->pattern_tree;
already = 1;
pos = extenbuf;
if (*pos == '_') {
pattern = 1;
++pos;
}
idx_cur = 0;
pos = get_pattern_node(&pat_node[idx_cur], pos, pattern, extenbuf);
for (; pat_node[idx_cur].buf[0]; idx_cur = idx_next) {
idx_next = (idx_cur + 1) % ARRAY_LEN(pat_node);
pos = get_pattern_node(&pat_node[idx_next], pos, pattern, extenbuf);
/* See about adding node to tree. */
m2 = NULL;
if (already && (m2 = already_in_tree(m1, pat_node[idx_cur].buf, pattern))
&& m2->next_char) {
if (!pat_node[idx_next].buf[0]) {
/*
* This is the end of the pattern, but not the end of the tree.
* Mark this node with the exten... a shorter pattern might win
* if the longer one doesn't match.
*/
if (findonly) {
return m2;
}
if (m2->exten) {
ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n",
m2->deleted ? "(deleted/invalid)" : m2->exten->exten, e1->exten);
}
m2->exten = e1;
m2->deleted = 0;
}
m1 = m2->next_char; /* m1 points to the node to compare against */
m0 = &m2->next_char; /* m0 points to the ptr that points to m1 */
} else { /* not already OR not m2 OR nor m2->next_char */
if (m2) {
if (findonly) {
return m2;
}
m1 = m2; /* while m0 stays the same */
} else {
if (findonly) {
return m1;
}
m1 = add_pattern_node(con, m1, &pat_node[idx_cur], pattern, already, m0);
if (!m1) { /* m1 is the node just added */
return NULL;
}
m0 = &m1->next_char;
}
if (!pat_node[idx_next].buf[0]) {
if (m2 && m2->exten) {
ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n",
m2->deleted ? "(deleted/invalid)" : m2->exten->exten, e1->exten);
}
m1->deleted = 0;
m1->exten = e1;
}
/* The 'already' variable is a mini-optimization designed to make it so that we
* don't have to call already_in_tree when we know it will return false.
*/
already = 0;
}
}
return m1;
}
static void create_match_char_tree(struct ast_context *con)
{
struct ast_hashtab_iter *t1;
struct ast_exten *e1;
#ifdef NEED_DEBUG
int biggest_bucket, resizes, numobjs, numbucks;
ast_log(LOG_DEBUG,"Creating Extension Trie for context %s(%p)\n", con->name, con);
ast_hashtab_get_stats(con->root_table, &biggest_bucket, &resizes, &numobjs, &numbucks);
ast_log(LOG_DEBUG,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n",
numobjs, numbucks, biggest_bucket, resizes);
#endif
t1 = ast_hashtab_start_traversal(con->root_table);
while ((e1 = ast_hashtab_next(t1))) {
if (e1->exten) {
add_exten_to_pattern_tree(con, e1, 0);
} else {
ast_log(LOG_ERROR, "Attempt to create extension with no extension name.\n");
}
}
ast_hashtab_end_traversal(t1);
}
static void destroy_pattern_tree(struct match_char *pattern_tree) /* pattern tree is a simple binary tree, sort of, so the proper way to destroy it is... recursively! */
{
/* destroy all the alternates */
if (pattern_tree->alt_char) {
destroy_pattern_tree(pattern_tree->alt_char);
pattern_tree->alt_char = 0;
}
/* destroy all the nexts */
if (pattern_tree->next_char) {
destroy_pattern_tree(pattern_tree->next_char);
pattern_tree->next_char = 0;
}
pattern_tree->exten = 0; /* never hurts to make sure there's no pointers laying around */
ast_free(pattern_tree);
}
/*!
* \internal
* \brief Get the length of the exten string.
*
* \param str Exten to get length.
*
* \retval strlen of exten.
*/
static int ext_cmp_exten_strlen(const char *str)
{
int len;
len = 0;
for (;;) {
/* Ignore '-' chars as eye candy fluff. */
while (*str == '-') {
++str;
}
if (!*str) {
break;
}
++str;
++len;
}
return len;
}
/*!
* \internal
* \brief Partial comparison of non-pattern extens.
*
* \param left Exten to compare.
* \param right Exten to compare. Also matches if this string ends first.
*
* \retval <0 if left < right
* \retval =0 if left == right
* \retval >0 if left > right
*/
static int ext_cmp_exten_partial(const char *left, const char *right)
{
int cmp;
for (;;) {
/* Ignore '-' chars as eye candy fluff. */
while (*left == '-') {
++left;
}
while (*right == '-') {
++right;
}
if (!*right) {
/*
* Right ended first for partial match or both ended at the same
* time for a match.
*/
cmp = 0;
break;
}
cmp = *left - *right;
if (cmp) {
break;
}
++left;
++right;
}
return cmp;
}
/*!
* \internal
* \brief Comparison of non-pattern extens.
*
* \param left Exten to compare.
* \param right Exten to compare.
*
* \retval <0 if left < right
* \retval =0 if left == right
* \retval >0 if left > right
*/
static int ext_cmp_exten(const char *left, const char *right)
{
int cmp;
for (;;) {
/* Ignore '-' chars as eye candy fluff. */
while (*left == '-') {
++left;
}
while (*right == '-') {
++right;
}
cmp = *left - *right;
if (cmp) {
break;
}
if (!*left) {
/*
* Get here only if both strings ended at the same time. cmp
* would be non-zero if only one string ended.
*/
break;
}
++left;
++right;
}
return cmp;
}
/*
* Special characters used in patterns:
* '_' underscore is the leading character of a pattern.
* In other position it is treated as a regular char.
* '-' The '-' is a separator and ignored. Why? So patterns like NXX-XXX-XXXX work.
* . one or more of any character. Only allowed at the end of
* a pattern.
* ! zero or more of anything. Also impacts the result of CANMATCH
* and MATCHMORE. Only allowed at the end of a pattern.
* In the core routine, ! causes a match with a return code of 2.
* In turn, depending on the search mode: (XXX check if it is implemented)
* - E_MATCH retuns 1 (does match)
* - E_MATCHMORE returns 0 (no match)
* - E_CANMATCH returns 1 (does match)
*
* / should not appear as it is considered the separator of the CID info.
* XXX at the moment we may stop on this char.
*
* X Z N match ranges 0-9, 1-9, 2-9 respectively.
* [ denotes the start of a set of character. Everything inside
* is considered literally. We can have ranges a-d and individual
* characters. A '[' and '-' can be considered literally if they
* are just before ']'.
* XXX currently there is no way to specify ']' in a range, nor \ is
* considered specially.
*
* When we compare a pattern with a specific extension, all characters in the extension
* itself are considered literally.
* XXX do we want to consider space as a separator as well ?
* XXX do we want to consider the separators in non-patterns as well ?
*/
/*!
* \brief helper functions to sort extension patterns in the desired way,
* so that more specific patterns appear first.
*
* \details
* The function compares individual characters (or sets of), returning
* an int where bits 0-7 are the ASCII code of the first char in the set,
* bits 8-15 are the number of characters in the set, and bits 16-20 are
* for special cases.
* This way more specific patterns (smaller character sets) appear first.
* Wildcards have a special value, so that we can directly compare them to
* sets by subtracting the two values. In particular:
* 0x001xx one character, character set starting with xx
* 0x0yyxx yy characters, character set starting with xx
* 0x18000 '.' (one or more of anything)
* 0x28000 '!' (zero or more of anything)
* 0x30000 NUL (end of string)
* 0x40000 error in set.
* The pointer to the string is advanced according to needs.
* NOTES:
* 1. the empty set is ignored.
* 2. given that a full set has always 0 as the first element,
* we could encode the special cases as 0xffXX where XX
* is 1, 2, 3, 4 as used above.
*/
static int ext_cmp_pattern_pos(const char **p, unsigned char *bitwise)
{
#define BITS_PER 8 /* Number of bits per unit (byte). */
unsigned char c;
unsigned char cmin;
int count;
const char *end;
do {
/* Get character and advance. (Ignore '-' chars as eye candy fluff.) */
do {
c = *(*p)++;
} while (c == '-');
/* always return unless we have a set of chars */
switch (c) {
default:
/* ordinary character */
bitwise[c / BITS_PER] = 1 << ((BITS_PER - 1) - (c % BITS_PER));
return 0x0100 | c;
case 'n':
case 'N':
/* 2..9 */
bitwise[6] = 0x3f;
bitwise[7] = 0xc0;
return 0x0800 | '2';
case 'x':
case 'X':
/* 0..9 */
bitwise[6] = 0xff;
bitwise[7] = 0xc0;
return 0x0A00 | '0';
case 'z':
case 'Z':
/* 1..9 */
bitwise[6] = 0x7f;
bitwise[7] = 0xc0;
return 0x0900 | '1';
case '.':
/* wildcard */
return 0x18000;
case '!':
/* earlymatch */
return 0x28000; /* less specific than '.' */
case '\0':
/* empty string */
*p = NULL;
return 0x30000;
case '[':
/* char set */
break;
}
/* locate end of set */
end = strchr(*p, ']');
if (!end) {
ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
return 0x40000; /* XXX make this entry go last... */
}
count = 0;
cmin = 0xFF;
for (; *p < end; ++*p) {
unsigned char c1; /* first char in range */
unsigned char c2; /* last char in range */
c1 = (*p)[0];
if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
c2 = (*p)[2];
*p += 2; /* skip a total of 3 chars */
} else { /* individual character */
c2 = c1;
}
if (c1 < cmin) {
cmin = c1;
}
for (; c1 <= c2; ++c1) {
unsigned char mask = 1 << ((BITS_PER - 1) - (c1 % BITS_PER));
/*
* Note: If two character sets score the same, the one with the
* lowest ASCII values will compare as coming first. Must fill
* in most significant bits for lower ASCII values to accomplish
* the desired sort order.
*/
if (!(bitwise[c1 / BITS_PER] & mask)) {
/* Add the character to the set. */
bitwise[c1 / BITS_PER] |= mask;
count += 0x100;
}
}
}
++*p;
} while (!count);/* While the char set was empty. */
return count | cmin;
}
/*!
* \internal
* \brief Comparison of exten patterns.
*
* \param left Pattern to compare.
* \param right Pattern to compare.
*
* \retval <0 if left < right
* \retval =0 if left == right
* \retval >0 if left > right
*/
static int ext_cmp_pattern(const char *left, const char *right)
{
int cmp;
int left_pos;
int right_pos;
for (;;) {
unsigned char left_bitwise[32] = { 0, };
unsigned char right_bitwise[32] = { 0, };
left_pos = ext_cmp_pattern_pos(&left, left_bitwise);
right_pos = ext_cmp_pattern_pos(&right, right_bitwise);
cmp = left_pos - right_pos;
if (!cmp) {
/*
* Are the character sets different, even though they score the same?
*
* Note: Must swap left and right to get the sense of the
* comparison correct. Otherwise, we would need to multiply by
* -1 instead.
*/
cmp = memcmp(right_bitwise, left_bitwise, ARRAY_LEN(left_bitwise));
}
if (cmp) {
break;
}
if (!left) {
/*
* Get here only if both patterns ended at the same time. cmp
* would be non-zero if only one pattern ended.
*/
break;
}
}
return cmp;
}
/*!
* \internal
* \brief Comparison of dialplan extens for sorting purposes.
*
* \param left Exten/pattern to compare.
* \param right Exten/pattern to compare.
*
* \retval <0 if left < right
* \retval =0 if left == right
* \retval >0 if left > right
*/
static int ext_cmp(const char *left, const char *right)
{
/* Make sure non-pattern extens come first. */
if (left[0] != '_') {
if (right[0] == '_') {
return -1;
}
/* Compare two non-pattern extens. */
return ext_cmp_exten(left, right);
}
if (right[0] != '_') {
return 1;
}
/*
* OK, we need full pattern sorting routine.
*
* Skip past the underscores
*/
return ext_cmp_pattern(left + 1, right + 1);
}
int ast_extension_cmp(const char *a, const char *b)
{
int cmp;
cmp = ext_cmp(a, b);
if (cmp < 0) {
return -1;
}
if (cmp > 0) {
return 1;
}
return 0;
}
/*!
* \internal
* \brief used ast_extension_{match|close}
* mode is as follows:
* E_MATCH success only on exact match
* E_MATCHMORE success only on partial match (i.e. leftover digits in pattern)
* E_CANMATCH either of the above.
* \retval 0 on no-match
* \retval 1 on match
* \retval 2 on early match.
*/
static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
{
mode &= E_MATCH_MASK; /* only consider the relevant bits */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode);
#endif
if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
int lp = ext_cmp_exten_strlen(pattern);
int ld = ext_cmp_exten_strlen(data);
if (lp < ld) { /* pattern too short, cannot match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) - pattern too short, cannot match\n");
#endif
return 0;
}
/* depending on the mode, accept full or partial match or both */
if (mode == E_MATCH) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (!ext_cmp_exten(%s,%s) when mode== E_MATCH)\n", pattern, data);
#endif
return !ext_cmp_exten(pattern, data); /* 1 on match, 0 on fail */
}
if (ld == 0 || !ext_cmp_exten_partial(pattern, data)) { /* partial or full match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode, lp, ld);
#endif
return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
} else {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data);
#endif
return 0;
}
}
if (mode == E_MATCH && data[0] == '_') {
/*
* XXX It is bad design that we don't know if we should be
* comparing data and pattern as patterns or comparing data if
* it conforms to pattern when the function is called. First,
* assume they are both patterns. If they don't match then try
* to see if data conforms to the given pattern.
*
* note: if this test is left out, then _x. will not match _x. !!!
*/
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "Comparing as patterns first. pattern:%s data:%s\n", pattern, data);
#endif
if (!ext_cmp_pattern(pattern + 1, data + 1)) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (1) - pattern matches pattern\n");
#endif
return 1;
}
}
++pattern; /* skip leading _ */
/*
* XXX below we stop at '/' which is a separator for the CID info. However we should
* not store '/' in the pattern at all. When we insure it, we can remove the checks.
*/
for (;;) {
const char *end;
/* Ignore '-' chars as eye candy fluff. */
while (*data == '-') {
++data;
}
while (*pattern == '-') {
++pattern;
}
if (!*data || !*pattern || *pattern == '/') {
break;
}
switch (*pattern) {
case '[': /* a range */
++pattern;
end = strchr(pattern, ']'); /* XXX should deal with escapes ? */
if (!end) {
ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
return 0; /* unconditional failure */
}
if (pattern == end) {
/* Ignore empty character sets. */
++pattern;
continue;
}
for (; pattern < end; ++pattern) {
if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
if (*data >= pattern[0] && *data <= pattern[2])
break; /* match found */
else {
pattern += 2; /* skip a total of 3 chars */
continue;
}
} else if (*data == pattern[0])
break; /* match found */
}
if (pattern >= end) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) when pattern>=end\n");
#endif
return 0;
}
pattern = end; /* skip and continue */
break;
case 'n':
case 'N':
if (*data < '2' || *data > '9') {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) N is not matched\n");
#endif
return 0;
}
break;
case 'x':
case 'X':
if (*data < '0' || *data > '9') {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) X is not matched\n");
#endif
return 0;
}
break;
case 'z':
case 'Z':
if (*data < '1' || *data > '9') {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"return (0) Z is not matched\n");
#endif
return 0;
}
break;
case '.': /* Must match, even with more digits */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (1) when '.' is matched\n");
#endif
return 1;
case '!': /* Early match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (2) when '!' is matched\n");
#endif
return 2;
default:
if (*data != *pattern) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern);
#endif
return 0;
}
break;
}
++data;
++pattern;
}
if (*data) /* data longer than pattern, no match */ {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "return (0) when data longer than pattern\n");
#endif
return 0;
}
/*
* match so far, but ran off the end of data.
* Depending on what is next, determine match or not.
*/
if (*pattern == '\0' || *pattern == '/') { /* exact match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "at end, return (%d) in 'exact match'\n", (mode==E_MATCHMORE) ? 0 : 1);
#endif
return (mode == E_MATCHMORE) ? 0 : 1; /* this is a failure for E_MATCHMORE */
} else if (*pattern == '!') { /* early match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "at end, return (2) when '!' is matched\n");
#endif
return 2;
} else { /* partial match */
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "at end, return (%d) which deps on E_MATCH\n", (mode == E_MATCH) ? 0 : 1);
#endif
return (mode == E_MATCH) ? 0 : 1; /* this is a failure for E_MATCH */
}
}
/*
* Wrapper around _extension_match_core() to do performance measurement
* using the profiling code.
*/
static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
{
int i;
static int prof_id = -2; /* marker for 'unallocated' id */
if (prof_id == -2) {
prof_id = ast_add_profile("ext_match", 0);
}
ast_mark(prof_id, 1);
i = _extension_match_core(ast_strlen_zero(pattern) ? "" : pattern, ast_strlen_zero(data) ? "" : data, mode);
ast_mark(prof_id, 0);
return i;
}
int ast_extension_match(const char *pattern, const char *data)
{
return extension_match_core(pattern, data, E_MATCH);
}
int ast_extension_close(const char *pattern, const char *data, int needmore)
{
if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
return extension_match_core(pattern, data, needmore);
}
struct fake_context /* this struct is purely for matching in the hashtab */
{
ast_rwlock_t lock;
struct ast_exten *root;
struct ast_hashtab *root_table;
struct match_char *pattern_tree;
struct ast_context *next;
struct ast_include *includes;
struct ast_ignorepat *ignorepats;
const char *registrar;
int refcount;
AST_LIST_HEAD_NOLOCK(, ast_sw) alts;
ast_mutex_t macrolock;
char name[256];
};
struct ast_context *ast_context_find(const char *name)
{
struct ast_context *tmp;
struct fake_context item;
if (!name) {
return NULL;
}
ast_rdlock_contexts();
if (contexts_table) {
ast_copy_string(item.name, name, sizeof(item.name));
tmp = ast_hashtab_lookup(contexts_table, &item);
} else {
tmp = NULL;
while ((tmp = ast_walk_contexts(tmp))) {
if (!strcasecmp(name, tmp->name)) {
break;
}
}
}
ast_unlock_contexts();
return tmp;
}
#define STATUS_NO_CONTEXT 1
#define STATUS_NO_EXTENSION 2
#define STATUS_NO_PRIORITY 3
#define STATUS_NO_LABEL 4
#define STATUS_SUCCESS 5
static int matchcid(const char *cidpattern, const char *callerid)
{
/* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
failing to get a number should count as a match, otherwise not */
if (ast_strlen_zero(callerid)) {
return ast_strlen_zero(cidpattern) ? 1 : 0;
}
return ast_extension_match(cidpattern, callerid);
}
struct ast_exten *pbx_find_extension(struct ast_channel *chan,
struct ast_context *bypass, struct pbx_find_info *q,
const char *context, const char *exten, int priority,
const char *label, const char *callerid, enum ext_match_t action)
{
int x, res;
struct ast_context *tmp = NULL;
struct ast_exten *e = NULL, *eroot = NULL;
struct ast_include *i = NULL;
struct ast_sw *sw = NULL;
struct ast_exten pattern = {NULL, };
struct scoreboard score = {0, };
struct ast_str *tmpdata = NULL;
pattern.label = label;
pattern.priority = priority;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context, exten, priority, label, (int) action);
#endif
/* Initialize status if appropriate */
if (q->stacklen == 0) {
q->status = STATUS_NO_CONTEXT;
q->swo = NULL;
q->data = NULL;
q->foundcontext = NULL;
} else if (q->stacklen >= AST_PBX_MAX_STACK) {
ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
return NULL;
}
/* Check first to see if we've already been checked */
for (x = 0; x < q->stacklen; x++) {
if (!strcasecmp(q->incstack[x], context))
return NULL;
}
if (bypass) { /* bypass means we only look there */
tmp = bypass;
} else { /* look in contexts */
tmp = find_context(context);
if (!tmp) {
return NULL;
}
}
if (q->status < STATUS_NO_EXTENSION)
q->status = STATUS_NO_EXTENSION;
/* Do a search for matching extension */
eroot = NULL;
score.total_specificity = 0;
score.exten = 0;
score.total_length = 0;
if (!tmp->pattern_tree && tmp->root_table) {
create_match_char_tree(tmp);
#ifdef NEED_DEBUG
ast_log(LOG_DEBUG, "Tree Created in context %s:\n", context);
log_match_char_tree(tmp->pattern_tree," ");
#endif
}
#ifdef NEED_DEBUG
ast_log(LOG_NOTICE, "The Trie we are searching in:\n");
log_match_char_tree(tmp->pattern_tree, ":: ");
#endif
do {
if (!ast_strlen_zero(overrideswitch)) {
char *osw = ast_strdupa(overrideswitch), *name;
struct ast_switch *asw;
ast_switch_f *aswf = NULL;
char *datap;
int eval = 0;
name = strsep(&osw, "/");
asw = pbx_findswitch(name);
if (!asw) {
ast_log(LOG_WARNING, "No such switch '%s'\n", name);
break;
}
if (osw && strchr(osw, '$')) {
eval = 1;
}
if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) {
ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!\n");
break;
} else if (eval) {
/* Substitute variables now */
pbx_substitute_variables_helper(chan, osw, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
datap = ast_str_buffer(tmpdata);
} else {
datap = osw;
}
/* equivalent of extension_match_core() at the switch level */
if (action == E_CANMATCH)
aswf = asw->canmatch;
else if (action == E_MATCHMORE)
aswf = asw->matchmore;
else /* action == E_MATCH */
aswf = asw->exists;
if (!aswf) {
res = 0;
} else {
if (chan) {
ast_autoservice_start(chan);
}
res = aswf(chan, context, exten, priority, callerid, datap);
if (chan) {
ast_autoservice_stop(chan);
}
}
if (res) { /* Got a match */
q->swo = asw;
q->data = datap;
q->foundcontext = context;
/* XXX keep status = STATUS_NO_CONTEXT ? */
return NULL;
}
}
} while (0);
if (extenpatternmatchnew) {
new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action);
eroot = score.exten;
if (score.last_char == '!' && action == E_MATCHMORE) {
/* We match an extension ending in '!'.
* The decision in this case is final and is NULL (no match).
*/
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n");
#endif
return NULL;
}
if (!eroot && (action == E_CANMATCH || action == E_MATCHMORE) && score.canmatch_exten) {
q->status = STATUS_SUCCESS;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH exten %s\n", score.canmatch_exten->exten);
#endif
return score.canmatch_exten;
}
if ((action == E_MATCHMORE || action == E_CANMATCH) && eroot) {
if (score.node) {
struct ast_exten *z = trie_find_next_match(score.node);
if (z) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten);
#endif
} else {
if (score.canmatch_exten) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score.canmatch_exten->exten, score.canmatch_exten);
#endif
return score.canmatch_exten;
} else {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
#endif
}
}
return z;
}
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE, "Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
#endif
return NULL; /* according to the code, complete matches are null matches in MATCHMORE mode */
}
if (eroot) {
/* found entry, now look for the right priority */
if (q->status < STATUS_NO_PRIORITY)
q->status = STATUS_NO_PRIORITY;
e = NULL;
if (action == E_FINDLABEL && label ) {
if (q->status < STATUS_NO_LABEL)
q->status = STATUS_NO_LABEL;
e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
} else {
e = ast_hashtab_lookup(eroot->peer_table, &pattern);
}
if (e) { /* found a valid match */
q->status = STATUS_SUCCESS;
q->foundcontext = context;
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning complete match of exten %s\n", e->exten);
#endif
return e;
}
}
} else { /* the old/current default exten pattern match algorithm */
/* scan the list trying to match extension and CID */
eroot = NULL;
while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
int match = extension_match_core(eroot->exten, exten, action);
/* 0 on fail, 1 on match, 2 on earlymatch */
if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
continue; /* keep trying */
if (match == 2 && action == E_MATCHMORE) {
/* We match an extension ending in '!'.
* The decision in this case is final and is NULL (no match).
*/
return NULL;
}
/* found entry, now look for the right priority */
if (q->status < STATUS_NO_PRIORITY)
q->status = STATUS_NO_PRIORITY;
e = NULL;
if (action == E_FINDLABEL && label ) {
if (q->status < STATUS_NO_LABEL)
q->status = STATUS_NO_LABEL;
e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
} else {
e = ast_hashtab_lookup(eroot->peer_table, &pattern);
}
if (e) { /* found a valid match */
q->status = STATUS_SUCCESS;
q->foundcontext = context;
return e;
}
}
}
/* Check alternative switches */
AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
struct ast_switch *asw = pbx_findswitch(sw->name);
ast_switch_f *aswf = NULL;
char *datap;
if (!asw) {
ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
continue;
}
/* Substitute variables now */
if (sw->eval) {
if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) {
ast_log(LOG_WARNING, "Can't evaluate switch?!\n");
continue;
}
pbx_substitute_variables_helper(chan, sw->data, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
}
/* equivalent of extension_match_core() at the switch level */
if (action == E_CANMATCH)
aswf = asw->canmatch;
else if (action == E_MATCHMORE)
aswf = asw->matchmore;
else /* action == E_MATCH */
aswf = asw->exists;
datap = sw->eval ? ast_str_buffer(tmpdata) : sw->data;
if (!aswf)
res = 0;
else {
if (chan)
ast_autoservice_start(chan);
res = aswf(chan, context, exten, priority, callerid, datap);
if (chan)
ast_autoservice_stop(chan);
}
if (res) { /* Got a match */
q->swo = asw;
q->data = datap;
q->foundcontext = context;
/* XXX keep status = STATUS_NO_CONTEXT ? */
return NULL;
}
}
q->incstack[q->stacklen++] = tmp->name; /* Setup the stack */
/* Now try any includes we have in this context */
for (i = tmp->includes; i; i = i->next) {
if (include_valid(i)) {
if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action))) {
#ifdef NEED_DEBUG_HERE
ast_log(LOG_NOTICE,"Returning recursive match of %s\n", e->exten);
#endif
return e;
}
if (q->swo)
return NULL;
}
}
return NULL;
}
/*!
* \brief extract offset:length from variable name.
* \return 1 if there is a offset:length part, which is
* trimmed off (values go into variables)
*/
static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
{
int parens = 0;
*offset = 0;
*length = INT_MAX;
*isfunc = 0;
for (; *var; var++) {
if (*var == '(') {
(*isfunc)++;
parens++;
} else if (*var == ')') {
parens--;
} else if (*var == ':' && parens == 0) {
*var++ = '\0';
sscanf(var, "%30d:%30d", offset, length);
return 1; /* offset:length valid */
}
}
return 0;
}
/*!
*\brief takes a substring. It is ok to call with value == workspace.
* \param value
* \param offset < 0 means start from the end of the string and set the beginning
* to be that many characters back.
* \param length is the length of the substring, a value less than 0 means to leave
* that many off the end.
* \param workspace
* \param workspace_len
* Always return a copy in workspace.
*/
static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
{
char *ret = workspace;
int lr; /* length of the input string after the copy */
ast_copy_string(workspace, value, workspace_len); /* always make a copy */
lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
/* Quick check if no need to do anything */
if (offset == 0 && length >= lr) /* take the whole string */
return ret;
if (offset < 0) { /* translate negative offset into positive ones */
offset = lr + offset;
if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
offset = 0;
}
/* too large offset result in empty string so we know what to return */
if (offset >= lr)
return ret + lr; /* the final '\0' */
ret += offset; /* move to the start position */
if (length >= 0 && length < lr - offset) /* truncate if necessary */
ret[length] = '\0';
else if (length < 0) {
if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */
ret[lr + length - offset] = '\0';
else
ret[0] = '\0';
}
return ret;
}
static const char *ast_str_substring(struct ast_str *value, int offset, int length)
{
int lr; /* length of the input string after the copy */
lr = ast_str_strlen(value); /* compute length after copy, so we never go out of the workspace */
/* Quick check if no need to do anything */
if (offset == 0 && length >= lr) /* take the whole string */
return ast_str_buffer(value);
if (offset < 0) { /* translate negative offset into positive ones */
offset = lr + offset;
if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
offset = 0;
}
/* too large offset result in empty string so we know what to return */
if (offset >= lr) {
ast_str_reset(value);
return ast_str_buffer(value);
}
if (offset > 0) {
/* Go ahead and chop off the beginning */
memmove(ast_str_buffer(value), ast_str_buffer(value) + offset, ast_str_strlen(value) - offset + 1);
lr -= offset;
}
if (length >= 0 && length < lr) { /* truncate if necessary */
char *tmp = ast_str_buffer(value);
tmp[length] = '\0';
ast_str_update(value);
} else if (length < 0) {
if (lr > -length) { /* After we remove from the front and from the rear, is there anything left? */
char *tmp = ast_str_buffer(value);
tmp[lr + length] = '\0';
ast_str_update(value);
} else {
ast_str_reset(value);
}
} else {
/* Nothing to do, but update the buffer length */
ast_str_update(value);
}
return ast_str_buffer(value);
}
/*! \brief Support for Asterisk built-in variables in the dialplan
\note See also
- \ref AstVar Channel variables
- \ref AstCauses The HANGUPCAUSE variable
*/
void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
{
struct ast_str *str = ast_str_create(16);
const char *cret;
cret = ast_str_retrieve_variable(&str, 0, c, headp, var);
ast_copy_string(workspace, ast_str_buffer(str), workspacelen);
*ret = cret ? workspace : NULL;
ast_free(str);
}
const char *ast_str_retrieve_variable(struct ast_str **str, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *var)
{
const char not_found = '\0';
char *tmpvar;
const char *ret;
const char *s; /* the result */
int offset, length;
int i, need_substring;
struct varshead *places[2] = { headp, &globals }; /* list of places where we may look */
char workspace[20];
if (c) {
ast_channel_lock(c);
places[0] = &c->varshead;
}
/*
* Make a copy of var because parse_variable_name() modifies the string.
* Then if called directly, we might need to run substring() on the result;
* remember this for later in 'need_substring', 'offset' and 'length'
*/
tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */
need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
/*
* Look first into predefined variables, then into variable lists.
* Variable 's' points to the result, according to the following rules:
* s == ¬_found (set at the beginning) means that we did not find a
* matching variable and need to look into more places.
* If s != ¬_found, s is a valid result string as follows:
* s = NULL if the variable does not have a value;
* you typically do this when looking for an unset predefined variable.
* s = workspace if the result has been assembled there;
* typically done when the result is built e.g. with an snprintf(),
* so we don't need to do an additional copy.
* s != workspace in case we have a string, that needs to be copied
* (the ast_copy_string is done once for all at the end).
* Typically done when the result is already available in some string.
*/
s = ¬_found; /* default value */
if (c) { /* This group requires a valid channel */
/* Names with common parts are looked up a piece at a time using strncmp. */
if (!strncmp(var, "CALL", 4)) {
if (!strncmp(var + 4, "ING", 3)) {
if (!strcmp(var + 7, "PRES")) { /* CALLINGPRES */
ast_str_set(str, maxlen, "%d",
ast_party_id_presentation(&c->caller.id));
s = ast_str_buffer(*str);
} else if (!strcmp(var + 7, "ANI2")) { /* CALLINGANI2 */
ast_str_set(str, maxlen, "%d", c->caller.ani2);
s = ast_str_buffer(*str);
} else if (!strcmp(var + 7, "TON")) { /* CALLINGTON */
ast_str_set(str, maxlen, "%d", c->caller.id.number.plan);
s = ast_str_buffer(*str);
} else if (!strcmp(var + 7, "TNS")) { /* CALLINGTNS */
ast_str_set(str, maxlen, "%d", c->dialed.transit_network_select);
s = ast_str_buffer(*str);
}
}
} else if (!strcmp(var, "HINT")) {
s = ast_str_get_hint(str, maxlen, NULL, 0, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL;
} else if (!strcmp(var, "HINTNAME")) {
s = ast_str_get_hint(NULL, 0, str, maxlen, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL;
} else if (!strcmp(var, "EXTEN")) {
s = c->exten;
} else if (!strcmp(var, "CONTEXT")) {
s = c->context;
} else if (!strcmp(var, "PRIORITY")) {
ast_str_set(str, maxlen, "%d", c->priority);
s = ast_str_buffer(*str);
} else if (!strcmp(var, "CHANNEL")) {
s = c->name;
} else if (!strcmp(var, "UNIQUEID")) {
s = c->uniqueid;
} else if (!strcmp(var, "HANGUPCAUSE")) {
ast_str_set(str, maxlen, "%d", c->hangupcause);
s = ast_str_buffer(*str);
}
}
if (s == ¬_found) { /* look for more */
if (!strcmp(var, "EPOCH")) {
ast_str_set(str, maxlen, "%u", (int) time(NULL));
s = ast_str_buffer(*str);
} else if (!strcmp(var, "SYSTEMNAME")) {
s = ast_config_AST_SYSTEM_NAME;
} else if (!strcmp(var, "ENTITYID")) {
ast_eid_to_str(workspace, sizeof(workspace), &ast_eid_default);
s = workspace;
}
}
/* if not found, look into chanvars or global vars */
for (i = 0; s == ¬_found && i < ARRAY_LEN(places); i++) {
struct ast_var_t *variables;
if (!places[i])
continue;
if (places[i] == &globals)
ast_rwlock_rdlock(&globalslock);
AST_LIST_TRAVERSE(places[i], variables, entries) {
if (!strcasecmp(ast_var_name(variables), var)) {
s = ast_var_value(variables);
break;
}
}
if (places[i] == &globals)
ast_rwlock_unlock(&globalslock);
}
if (s == ¬_found || s == NULL) {
ast_debug(5, "Result of '%s' is NULL\n", var);
ret = NULL;
} else {
ast_debug(5, "Result of '%s' is '%s'\n", var, s);
if (s != ast_str_buffer(*str)) {
ast_str_set(str, maxlen, "%s", s);
}
ret = ast_str_buffer(*str);
if (need_substring) {
ret = ast_str_substring(*str, offset, length);
ast_debug(2, "Final result of '%s' is '%s'\n", var, ret);
}
}
if (c) {
ast_channel_unlock(c);
}
return ret;
}
static void exception_store_free(void *data)
{
struct pbx_exception *exception = data;
ast_string_field_free_memory(exception);
ast_free(exception);
}
static const struct ast_datastore_info exception_store_info = {
.type = "EXCEPTION",
.destroy = exception_store_free,
};
/*!
* \internal
* \brief Set the PBX to execute the exception extension.
*
* \param chan Channel to raise the exception on.
* \param reason Reason exception is raised.
* \param priority Dialplan priority to set.
*
* \retval 0 on success.
* \retval -1 on error.
*/
static int raise_exception(struct ast_channel *chan, const char *reason, int priority)
{
struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
struct pbx_exception *exception = NULL;
if (!ds) {
ds = ast_datastore_alloc(&exception_store_info, NULL);
if (!ds)
return -1;
if (!(exception = ast_calloc_with_stringfields(1, struct pbx_exception, 128))) {
ast_datastore_free(ds);
return -1;
}
ds->data = exception;
ast_channel_datastore_add(chan, ds);
} else
exception = ds->data;
ast_string_field_set(exception, reason, reason);
ast_string_field_set(exception, context, chan->context);
ast_string_field_set(exception, exten, chan->exten);
exception->priority = chan->priority;
set_ext_pri(chan, "e", priority);
return 0;
}
int pbx_builtin_raise_exception(struct ast_channel *chan, const char *reason)
{
/* Priority will become 1, next time through the AUTOLOOP */
return raise_exception(chan, reason, 0);
}
static int acf_exception_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
{
struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
struct pbx_exception *exception = NULL;
if (!ds || !ds->data)
return -1;
exception = ds->data;
if (!strcasecmp(data, "REASON"))
ast_copy_string(buf, exception->reason, buflen);
else if (!strcasecmp(data, "CONTEXT"))
ast_copy_string(buf, exception->context, buflen);
else if (!strncasecmp(data, "EXTEN", 5))
ast_copy_string(buf, exception->exten, buflen);
else if (!strcasecmp(data, "PRIORITY"))
snprintf(buf, buflen, "%d", exception->priority);
else
return -1;
return 0;
}
static struct ast_custom_function exception_function = {
.name = "EXCEPTION",
.read = acf_exception_read,
};
static char *handle_show_functions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_custom_function *acf;
int count_acf = 0;
int like = 0;
switch (cmd) {
case CLI_INIT:
e->command = "core show functions [like]";
e->usage =
"Usage: core show functions [like <text>]\n"
" List builtin functions, optionally only those matching a given string\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc == 5 && (!strcmp(a->argv[3], "like")) ) {
like = 1;
} else if (a->argc != 3) {
return CLI_SHOWUSAGE;
}
ast_cli(a->fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
AST_RWLIST_RDLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
if (!like || strstr(acf->name, a->argv[4])) {
count_acf++;
ast_cli(a->fd, "%-20.20s %-35.35s %s\n",
S_OR(acf->name, ""),
S_OR(acf->syntax, ""),
S_OR(acf->synopsis, ""));
}
}
AST_RWLIST_UNLOCK(&acf_root);
ast_cli(a->fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
return CLI_SUCCESS;
}
static char *handle_show_function(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_custom_function *acf;
/* Maximum number of characters added by terminal coloring is 22 */
char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], argtitle[40], seealsotitle[40];
char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *seealso = NULL;
char stxtitle[40], *syntax = NULL, *arguments = NULL;
int syntax_size, description_size, synopsis_size, arguments_size, seealso_size;
char *ret = NULL;
int which = 0;
int wordlen;
switch (cmd) {
case CLI_INIT:
e->command = "core show function";
e->usage =
"Usage: core show function <function>\n"
" Describe a particular dialplan function.\n";
return NULL;
case CLI_GENERATE:
wordlen = strlen(a->word);
/* case-insensitive for convenience in this 'complete' function */
AST_RWLIST_RDLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
if (!strncasecmp(a->word, acf->name, wordlen) && ++which > a->n) {
ret = ast_strdup(acf->name);
break;
}
}
AST_RWLIST_UNLOCK(&acf_root);
return ret;
}
if (a->argc < 4) {
return CLI_SHOWUSAGE;
}
if (!(acf = ast_custom_function_find(a->argv[3]))) {
ast_cli(a->fd, "No function by that name registered.\n");
return CLI_FAILURE;
}
syntax_size = strlen(S_OR(acf->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
if (!(syntax = ast_malloc(syntax_size))) {
ast_cli(a->fd, "Memory allocation failure!\n");
return CLI_FAILURE;
}
snprintf(info, sizeof(info), "\n -= Info about function '%s' =- \n\n", acf->name);
term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle));
term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40);
term_color(syntax, S_OR(acf->syntax, "Not available"), COLOR_CYAN, 0, syntax_size);
#ifdef AST_XML_DOCS
if (acf->docsrc == AST_XML_DOC) {
arguments = ast_xmldoc_printable(S_OR(acf->arguments, "Not available"), 1);
synopsis = ast_xmldoc_printable(S_OR(acf->synopsis, "Not available"), 1);
description = ast_xmldoc_printable(S_OR(acf->desc, "Not available"), 1);
seealso = ast_xmldoc_printable(S_OR(acf->seealso, "Not available"), 1);
} else
#endif
{
synopsis_size = strlen(S_OR(acf->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
synopsis = ast_malloc(synopsis_size);
description_size = strlen(S_OR(acf->desc, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
description = ast_malloc(description_size);
arguments_size = strlen(S_OR(acf->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
arguments = ast_malloc(arguments_size);
seealso_size = strlen(S_OR(acf->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
seealso = ast_malloc(seealso_size);
/* check allocated memory. */
if (!synopsis || !description || !arguments || !seealso) {
ast_free(synopsis);
ast_free(description);
ast_free(arguments);
ast_free(seealso);
ast_free(syntax);
return CLI_FAILURE;
}
term_color(arguments, S_OR(acf->arguments, "Not available"), COLOR_CYAN, 0, arguments_size);
term_color(synopsis, S_OR(acf->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size);
term_color(description, S_OR(acf->desc, "Not available"), COLOR_CYAN, 0, description_size);
term_color(seealso, S_OR(acf->seealso, "Not available"), COLOR_CYAN, 0, seealso_size);
}
ast_cli(a->fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n",
infotitle, syntitle, synopsis, destitle, description,
stxtitle, syntax, argtitle, arguments, seealsotitle, seealso);
ast_free(arguments);
ast_free(synopsis);
ast_free(description);
ast_free(seealso);
ast_free(syntax);
return CLI_SUCCESS;
}
struct ast_custom_function *ast_custom_function_find(const char *name)
{
struct ast_custom_function *acf = NULL;
AST_RWLIST_RDLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
if (!strcmp(name, acf->name))
break;
}
AST_RWLIST_UNLOCK(&acf_root);
return acf;
}
int ast_custom_function_unregister(struct ast_custom_function *acf)
{
struct ast_custom_function *cur;
if (!acf) {
return -1;
}
AST_RWLIST_WRLOCK(&acf_root);
if ((cur = AST_RWLIST_REMOVE(&acf_root, acf, acflist))) {
#ifdef AST_XML_DOCS
if (cur->docsrc == AST_XML_DOC) {
ast_string_field_free_memory(acf);
}
#endif
ast_verb(2, "Unregistered custom function %s\n", cur->name);
}
AST_RWLIST_UNLOCK(&acf_root);
return cur ? 0 : -1;
}
/*! \internal
* \brief Retrieve the XML documentation of a specified ast_custom_function,
* and populate ast_custom_function string fields.
* \param acf ast_custom_function structure with empty 'desc' and 'synopsis'
* but with a function 'name'.
* \retval -1 On error.
* \retval 0 On succes.
*/
static int acf_retrieve_docs(struct ast_custom_function *acf)
{
#ifdef AST_XML_DOCS
char *tmpxml;
/* Let's try to find it in the Documentation XML */
if (!ast_strlen_zero(acf->desc) || !ast_strlen_zero(acf->synopsis)) {
return 0;
}
if (ast_string_field_init(acf, 128)) {
return -1;
}
/* load synopsis */
tmpxml = ast_xmldoc_build_synopsis("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, synopsis, tmpxml);
ast_free(tmpxml);
/* load description */
tmpxml = ast_xmldoc_build_description("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, desc, tmpxml);
ast_free(tmpxml);
/* load syntax */
tmpxml = ast_xmldoc_build_syntax("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, syntax, tmpxml);
ast_free(tmpxml);
/* load arguments */
tmpxml = ast_xmldoc_build_arguments("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, arguments, tmpxml);
ast_free(tmpxml);
/* load seealso */
tmpxml = ast_xmldoc_build_seealso("function", acf->name, ast_module_name(acf->mod));
ast_string_field_set(acf, seealso, tmpxml);
ast_free(tmpxml);
acf->docsrc = AST_XML_DOC;
#endif
return 0;
}
int __ast_custom_function_register(struct ast_custom_function *acf, struct ast_module *mod)
{
struct ast_custom_function *cur;
char tmps[80];
if (!acf) {
return -1;
}
acf->mod = mod;
#ifdef AST_XML_DOCS
acf->docsrc = AST_STATIC_DOC;
#endif
if (acf_retrieve_docs(acf)) {
return -1;
}
AST_RWLIST_WRLOCK(&acf_root);
AST_RWLIST_TRAVERSE(&acf_root, cur, acflist) {
if (!strcmp(acf->name, cur->name)) {
ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name);
AST_RWLIST_UNLOCK(&acf_root);
return -1;
}
}
/* Store in alphabetical order */
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) {
if (strcasecmp(acf->name, cur->name) < 0) {
AST_RWLIST_INSERT_BEFORE_CURRENT(acf, acflist);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
if (!cur) {
AST_RWLIST_INSERT_TAIL(&acf_root, acf, acflist);
}
AST_RWLIST_UNLOCK(&acf_root);
ast_verb(2, "Registered custom function '%s'\n", term_color(tmps, acf->name, COLOR_BRCYAN, 0, sizeof(tmps)));
return 0;
}
/*! \brief return a pointer to the arguments of the function,
* and terminates the function name with '\\0'
*/
static char *func_args(char *function)
{
char *args = strchr(function, '(');
if (!args) {
ast_log(LOG_WARNING, "Function '%s' doesn't contain parentheses. Assuming null argument.\n", function);
} else {
char *p;
*args++ = '\0';
if ((p = strrchr(args, ')'))) {
*p = '\0';
} else {
ast_log(LOG_WARNING, "Can't find trailing parenthesis for function '%s(%s'?\n", function, args);
}
}
return args;
}
int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len)
{
char *copy = ast_strdupa(function);
char *args = func_args(copy);
struct ast_custom_function *acfptr = ast_custom_function_find(copy);
int res;
struct ast_module_user *u = NULL;
if (acfptr == NULL) {
ast_log(LOG_ERROR, "Function %s not registered\n", copy);
} else if (!acfptr->read && !acfptr->read2) {
ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
} else if (acfptr->read) {
if (acfptr->mod) {
u = __ast_module_user_add(acfptr->mod, chan);
}
res = acfptr->read(chan, copy, args, workspace, len);
if (acfptr->mod && u) {
__ast_module_user_remove(acfptr->mod, u);
}
return res;
} else {
struct ast_str *str = ast_str_create(16);
if (acfptr->mod) {
u = __ast_module_user_add(acfptr->mod, chan);
}
res = acfptr->read2(chan, copy, args, &str, 0);
if (acfptr->mod && u) {
__ast_module_user_remove(acfptr->mod, u);
}
ast_copy_string(workspace, ast_str_buffer(str), len > ast_str_size(str) ? ast_str_size(str) : len);
ast_free(str);
return res;
}
return -1;
}
int ast_func_read2(struct ast_channel *chan, const char *function, struct ast_str **str, ssize_t maxlen)
{
char *copy = ast_strdupa(function);
char *args = func_args(copy);
struct ast_custom_function *acfptr = ast_custom_function_find(copy);
int res;
struct ast_module_user *u = NULL;
if (acfptr == NULL) {
ast_log(LOG_ERROR, "Function %s not registered\n", copy);
} else if (!acfptr->read && !acfptr->read2) {
ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
} else {
if (acfptr->mod) {
u = __ast_module_user_add(acfptr->mod, chan);
}
ast_str_reset(*str);
if (acfptr->read2) {
/* ast_str enabled */
res = acfptr->read2(chan, copy, args, str, maxlen);
} else {
/* Legacy function pointer, allocate buffer for result */
int maxsize = ast_str_size(*str);
if (maxlen > -1) {
if (maxlen == 0) {
if (acfptr->read_max) {
maxsize = acfptr->read_max;
} else {
maxsize = VAR_BUF_SIZE;
}
} else {
maxsize = maxlen;
}
ast_str_make_space(str, maxsize);
}
res = acfptr->read(chan, copy, args, ast_str_buffer(*str), maxsize);
}
if (acfptr->mod && u) {
__ast_module_user_remove(acfptr->mod, u);
}
return res;
}
return -1;
}
int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
{
char *copy = ast_strdupa(function);
char *args = func_args(copy);
struct ast_custom_function *acfptr = ast_custom_function_find(copy);
if (acfptr == NULL)
ast_log(LOG_ERROR, "Function %s not registered\n", copy);
else if (!acfptr->write)
ast_log(LOG_ERROR, "Function %s cannot be written to\n", copy);
else {
int res;
struct ast_module_user *u = NULL;
if (acfptr->mod)
u = __ast_module_user_add(acfptr->mod, chan);
res = acfptr->write(chan, copy, args, value);
if (acfptr->mod && u)
__ast_module_user_remove(acfptr->mod, u);
return res;
}
return -1;
}
void ast_str_substitute_variables_full(struct ast_str **buf, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *templ, size_t *used)
{
/* Substitutes variables into buf, based on string templ */
char *cp4 = NULL;
const char *tmp, *whereweare;
int orig_size = 0;
int offset, offset2, isfunction;
const char *nextvar, *nextexp, *nextthing;
const char *vars, *vare;
char *finalvars;
int pos, brackets, needsub, len;
struct ast_str *substr1 = ast_str_create(16), *substr2 = NULL, *substr3 = ast_str_create(16);
ast_str_reset(*buf);
whereweare = tmp = templ;
while (!ast_strlen_zero(whereweare)) {
/* reset our buffer */
ast_str_reset(substr3);
/* Assume we're copying the whole remaining string */
pos = strlen(whereweare);
nextvar = NULL;
nextexp = NULL;
nextthing = strchr(whereweare, '$');
if (nextthing) {
switch (nextthing[1]) {
case '{':
nextvar = nextthing;
pos = nextvar - whereweare;
break;
case '[':
nextexp = nextthing;
pos = nextexp - whereweare;
break;
default:
pos = 1;
}
}
if (pos) {
/* Copy that many bytes */
ast_str_append_substr(buf, maxlen, whereweare, pos);
templ += pos;
whereweare += pos;
}
if (nextvar) {
/* We have a variable. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextvar + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
} else if (vare[0] == '{') {
brackets++;
} else if (vare[0] == '}') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '['))
needsub++;
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
len = vare - vars - 1;
/* Skip totally over variable string */
whereweare += (len + 3);
/* Store variable name (and truncate) */
ast_str_set_substr(&substr1, 0, vars, len);
ast_debug(5, "Evaluating '%s' (from '%s' len %d)\n", ast_str_buffer(substr1), vars, len);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!substr2) {
substr2 = ast_str_create(16);
}
ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used);
finalvars = ast_str_buffer(substr2);
} else {
finalvars = ast_str_buffer(substr1);
}
parse_variable_name(finalvars, &offset, &offset2, &isfunction);
if (isfunction) {
/* Evaluate function */
if (c || !headp) {
cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3);
} else {
struct varshead old;
struct ast_channel *bogus = ast_dummy_channel_alloc();
if (bogus) {
memcpy(&old, &bogus->varshead, sizeof(old));
memcpy(&bogus->varshead, headp, sizeof(bogus->varshead));
cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3);
/* Don't deallocate the varshead that was passed in */
memcpy(&bogus->varshead, &old, sizeof(bogus->varshead));
ast_channel_unref(bogus);
} else {
ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
}
}
ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
} else {
/* Retrieve variable value */
ast_str_retrieve_variable(&substr3, 0, c, headp, finalvars);
cp4 = ast_str_buffer(substr3);
}
if (cp4) {
ast_str_substring(substr3, offset, offset2);
ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3));
}
} else if (nextexp) {
/* We have an expression. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextexp + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '[')) {
needsub++;
brackets++;
vare++;
} else if (vare[0] == '[') {
brackets++;
} else if (vare[0] == ']') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
vare++;
}
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
len = vare - vars - 1;
/* Skip totally over expression */
whereweare += (len + 3);
/* Store variable name (and truncate) */
ast_str_set_substr(&substr1, 0, vars, len);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!substr2) {
substr2 = ast_str_create(16);
}
ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used);
finalvars = ast_str_buffer(substr2);
} else {
finalvars = ast_str_buffer(substr1);
}
if (ast_str_expr(&substr3, 0, c, finalvars)) {
ast_debug(2, "Expression result is '%s'\n", ast_str_buffer(substr3));
}
ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3));
}
}
*used = ast_str_strlen(*buf) - orig_size;
ast_free(substr1);
ast_free(substr2);
ast_free(substr3);
}
void ast_str_substitute_variables(struct ast_str **buf, ssize_t maxlen, struct ast_channel *chan, const char *templ)
{
size_t used;
ast_str_substitute_variables_full(buf, maxlen, chan, NULL, templ, &used);
}
void ast_str_substitute_variables_varshead(struct ast_str **buf, ssize_t maxlen, struct varshead *headp, const char *templ)
{
size_t used;
ast_str_substitute_variables_full(buf, maxlen, NULL, headp, templ, &used);
}
void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count, size_t *used)
{
/* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!! */
char *cp4 = NULL;
const char *tmp, *whereweare, *orig_cp2 = cp2;
int length, offset, offset2, isfunction;
char *workspace = NULL;
char *ltmp = NULL, *var = NULL;
char *nextvar, *nextexp, *nextthing;
char *vars, *vare;
int pos, brackets, needsub, len;
*cp2 = 0; /* just in case nothing ends up there */
whereweare=tmp=cp1;
while (!ast_strlen_zero(whereweare) && count) {
/* Assume we're copying the whole remaining string */
pos = strlen(whereweare);
nextvar = NULL;
nextexp = NULL;
nextthing = strchr(whereweare, '$');
if (nextthing) {
switch (nextthing[1]) {
case '{':
nextvar = nextthing;
pos = nextvar - whereweare;
break;
case '[':
nextexp = nextthing;
pos = nextexp - whereweare;
break;
default:
pos = 1;
}
}
if (pos) {
/* Can't copy more than 'count' bytes */
if (pos > count)
pos = count;
/* Copy that many bytes */
memcpy(cp2, whereweare, pos);
count -= pos;
cp2 += pos;
whereweare += pos;
*cp2 = 0;
}
if (nextvar) {
/* We have a variable. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextvar + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
} else if (vare[0] == '{') {
brackets++;
} else if (vare[0] == '}') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '['))
needsub++;
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
len = vare - vars - 1;
/* Skip totally over variable string */
whereweare += (len + 3);
if (!var)
var = ast_alloca(VAR_BUF_SIZE);
/* Store variable name (and truncate) */
ast_copy_string(var, vars, len + 1);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!ltmp)
ltmp = ast_alloca(VAR_BUF_SIZE);
pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used);
vars = ltmp;
} else {
vars = var;
}
if (!workspace)
workspace = ast_alloca(VAR_BUF_SIZE);
workspace[0] = '\0';
parse_variable_name(vars, &offset, &offset2, &isfunction);
if (isfunction) {
/* Evaluate function */
if (c || !headp)
cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
else {
struct varshead old;
struct ast_channel *c = ast_dummy_channel_alloc();
if (c) {
memcpy(&old, &c->varshead, sizeof(old));
memcpy(&c->varshead, headp, sizeof(c->varshead));
cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
/* Don't deallocate the varshead that was passed in */
memcpy(&c->varshead, &old, sizeof(c->varshead));
c = ast_channel_unref(c);
} else {
ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
}
}
ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
} else {
/* Retrieve variable value */
pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
}
if (cp4) {
cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
length = strlen(cp4);
if (length > count)
length = count;
memcpy(cp2, cp4, length);
count -= length;
cp2 += length;
*cp2 = 0;
}
} else if (nextexp) {
/* We have an expression. Find the start and end, and determine
if we are going to have to recursively call ourselves on the
contents */
vars = vare = nextexp + 2;
brackets = 1;
needsub = 0;
/* Find the end of it */
while (brackets && *vare) {
if ((vare[0] == '$') && (vare[1] == '[')) {
needsub++;
brackets++;
vare++;
} else if (vare[0] == '[') {
brackets++;
} else if (vare[0] == ']') {
brackets--;
} else if ((vare[0] == '$') && (vare[1] == '{')) {
needsub++;
vare++;
}
vare++;
}
if (brackets)
ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
len = vare - vars - 1;
/* Skip totally over expression */
whereweare += (len + 3);
if (!var)
var = ast_alloca(VAR_BUF_SIZE);
/* Store variable name (and truncate) */
ast_copy_string(var, vars, len + 1);
/* Substitute if necessary */
if (needsub) {
size_t used;
if (!ltmp)
ltmp = ast_alloca(VAR_BUF_SIZE);
pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used);
vars = ltmp;
} else {
vars = var;
}
length = ast_expr(vars, cp2, count, c);
if (length) {
ast_debug(1, "Expression result is '%s'\n", cp2);
count -= length;
cp2 += length;
*cp2 = 0;
}
}
}
*used = cp2 - orig_cp2;
}
void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
{
size_t used;
pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count, &used);
}
void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
{
size_t used;
pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count, &used);
}
static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
{
const char *tmp;
/* Nothing more to do */
if (!e->data) {
*passdata = '\0';
return;
}
/* No variables or expressions in e->data, so why scan it? */
if ((!(tmp = strchr(e->data, '$'))) || (!strstr(tmp, "${") && !strstr(tmp, "$["))) {
ast_copy_string(passdata, e->data, datalen);
return;
}
pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
}
/*!
* \brief The return value depends on the action:
*
* E_MATCH, E_CANMATCH, E_MATCHMORE require a real match,
* and return 0 on failure, -1 on match;
* E_FINDLABEL maps the label to a priority, and returns
* the priority on success, ... XXX
* E_SPAWN, spawn an application,
*
* \retval 0 on success.
* \retval -1 on failure.
*
* \note The channel is auto-serviced in this function, because doing an extension
* match may block for a long time. For example, if the lookup has to use a network
* dialplan switch, such as DUNDi or IAX2, it may take a while. However, the channel
* auto-service code will queue up any important signalling frames to be processed
* after this is done.
*/
static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
const char *context, const char *exten, int priority,
const char *label, const char *callerid, enum ext_match_t action, int *found, int combined_find_spawn)
{
struct ast_exten *e;
struct ast_app *app;
int res;
struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
char passdata[EXT_DATA_SIZE];
int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
ast_rdlock_contexts();
if (found)
*found = 0;
e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
if (e) {
if (found)
*found = 1;
if (matching_action) {
ast_unlock_contexts();
return -1; /* success, we found it */
} else if (action == E_FINDLABEL) { /* map the label to a priority */
res = e->priority;
ast_unlock_contexts();
return res; /* the priority we were looking for */
} else { /* spawn */
if (!e->cached_app)
e->cached_app = pbx_findapp(e->app);
app = e->cached_app;
ast_unlock_contexts();
if (!app) {
ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
return -1;
}
if (c->context != context)
ast_copy_string(c->context, context, sizeof(c->context));
if (c->exten != exten)
ast_copy_string(c->exten, exten, sizeof(c->exten));
c->priority = priority;
pbx_substitute_variables(passdata, sizeof(passdata), c, e);
#ifdef CHANNEL_TRACE
ast_channel_trace_update(c);
#endif
ast_debug(1, "Launching '%s'\n", app->name);
if (VERBOSITY_ATLEAST(3)) {
char tmp[80], tmp2[80], tmp3[EXT_DATA_SIZE];
ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n",
exten, context, priority,
term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)),
term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)),
"in new stack");
}
manager_event(EVENT_FLAG_DIALPLAN, "Newexten",
"Channel: %s\r\n"
"Context: %s\r\n"
"Extension: %s\r\n"
"Priority: %d\r\n"
"Application: %s\r\n"
"AppData: %s\r\n"
"Uniqueid: %s\r\n",
c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid);
return pbx_exec(c, app, passdata); /* 0 on success, -1 on failure */
}
} else if (q.swo) { /* not found here, but in another switch */
if (found)
*found = 1;
ast_unlock_contexts();
if (matching_action) {
return -1;
} else {
if (!q.swo->exec) {
ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name);
res = -1;
}
return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);
}
} else { /* not found anywhere, see what happened */
ast_unlock_contexts();
/* Using S_OR here because Solaris doesn't like NULL being passed to ast_log */
switch (q.status) {
case STATUS_NO_CONTEXT:
if (!matching_action && !combined_find_spawn)
ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", S_OR(context, ""));
break;
case STATUS_NO_EXTENSION:
if (!matching_action && !combined_find_spawn)
ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, S_OR(context, ""));
break;
case STATUS_NO_PRIORITY:
if (!matching_action && !combined_find_spawn)
ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, S_OR(context, ""));
break;
case STATUS_NO_LABEL:
if (context && !combined_find_spawn)
ast_log(LOG_NOTICE, "No such label '%s' in extension '%s' in context '%s'\n", label, exten, S_OR(context, ""));
break;
default:
ast_debug(1, "Shouldn't happen!\n");
}
return (matching_action) ? 0 : -1;
}
}
/*! \brief Find hint for given extension in context */
static struct ast_exten *ast_hint_extension_nolock(struct ast_channel *c, const char *context, const char *exten)
{
struct pbx_find_info q = { .stacklen = 0 }; /* the rest is set in pbx_find_context */
return pbx_find_extension(c, NULL, &q, context, exten, PRIORITY_HINT, NULL, "", E_MATCH);
}
static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e;
ast_rdlock_contexts();
e = ast_hint_extension_nolock(c, context, exten);
ast_unlock_contexts();
return e;
}
enum ast_extension_states ast_devstate_to_extenstate(enum ast_device_state devstate)
{
switch (devstate) {
case AST_DEVICE_ONHOLD:
return AST_EXTENSION_ONHOLD;
case AST_DEVICE_BUSY:
return AST_EXTENSION_BUSY;
case AST_DEVICE_UNKNOWN:
return AST_EXTENSION_NOT_INUSE;
case AST_DEVICE_UNAVAILABLE:
case AST_DEVICE_INVALID:
return AST_EXTENSION_UNAVAILABLE;
case AST_DEVICE_RINGINUSE:
return (AST_EXTENSION_INUSE | AST_EXTENSION_RINGING);
case AST_DEVICE_RINGING:
return AST_EXTENSION_RINGING;
case AST_DEVICE_INUSE:
return AST_EXTENSION_INUSE;
case AST_DEVICE_NOT_INUSE:
return AST_EXTENSION_NOT_INUSE;
case AST_DEVICE_TOTAL: /* not a device state, included for completeness */
break;
}
return AST_EXTENSION_NOT_INUSE;
}
static int ast_extension_state3(struct ast_str *hint_app)
{
char *cur;
char *rest;
struct ast_devstate_aggregate agg;
/* One or more devices separated with a & character */
rest = ast_str_buffer(hint_app);
ast_devstate_aggregate_init(&agg);
while ((cur = strsep(&rest, "&"))) {
ast_devstate_aggregate_add(&agg, ast_device_state(cur));
}
return ast_devstate_to_extenstate(ast_devstate_aggregate_result(&agg));
}
/*! \brief Check state of extension by using hints */
static int ast_extension_state2(struct ast_exten *e)
{
struct ast_str *hint_app = ast_str_thread_get(&extensionstate_buf, 32);
if (!e || !hint_app) {
return -1;
}
ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(e));
return ast_extension_state3(hint_app);
}
/*! \brief Return extension_state as string */
const char *ast_extension_state2str(int extension_state)
{
int i;
for (i = 0; (i < ARRAY_LEN(extension_states)); i++) {
if (extension_states[i].extension_state == extension_state)
return extension_states[i].text;
}
return "Unknown";
}
/*! \brief Check extension state for an extension by using hint */
int ast_extension_state(struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e;
if (!(e = ast_hint_extension(c, context, exten))) { /* Do we have a hint for this extension ? */
return -1; /* No hint, return -1 */
}
if (e->exten[0] == '_') {
/* Create this hint on-the-fly */
ast_add_extension(e->parent->name, 0, exten, e->priority, e->label,
e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr,
e->registrar);
if (!(e = ast_hint_extension(c, context, exten))) {
/* Improbable, but not impossible */
return -1;
}
}
return ast_extension_state2(e); /* Check all devices in the hint */
}
static int handle_statechange(void *datap)
{
struct ast_hint *hint;
struct ast_str *hint_app;
struct statechange *sc = datap;
struct ao2_iterator i;
struct ao2_iterator cb_iter;
char context_name[AST_MAX_CONTEXT];
char exten_name[AST_MAX_EXTENSION];
hint_app = ast_str_create(1024);
if (!hint_app) {
ast_free(sc);
return -1;
}
ast_mutex_lock(&context_merge_lock);/* Hold off ast_merge_contexts_and_delete */
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
struct ast_state_cb *state_cb;
char *cur, *parse;
int state;
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
/* Does this hint monitor the device that changed state? */
ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(hint->exten));
parse = ast_str_buffer(hint_app);
while ((cur = strsep(&parse, "&"))) {
if (!strcasecmp(cur, sc->dev)) {
/* The hint monitors the device. */
break;
}
}
if (!cur) {
/* The hint does not monitor the device. */
ao2_unlock(hint);
continue;
}
/*
* Save off strings in case the hint extension gets destroyed
* while we are notifying the watchers.
*/
ast_copy_string(context_name,
ast_get_context_name(ast_get_extension_context(hint->exten)),
sizeof(context_name));
ast_copy_string(exten_name, ast_get_extension_name(hint->exten),
sizeof(exten_name));
ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(hint->exten));
ao2_unlock(hint);
/*
* Get device state for this hint.
*
* NOTE: We cannot hold any locks while determining the hint
* device state or notifying the watchers without causing a
* deadlock. (conlock, hints, and hint)
*/
state = ast_extension_state3(hint_app);
if (state == hint->laststate) {
continue;
}
/* Device state changed since last check - notify the watchers. */
hint->laststate = state; /* record we saw the change */
/* For general callbacks */
cb_iter = ao2_iterator_init(statecbs, 0);
for (; (state_cb = ao2_iterator_next(&cb_iter)); ao2_ref(state_cb, -1)) {
state_cb->change_cb(context_name, exten_name, state, state_cb->data);
}
ao2_iterator_destroy(&cb_iter);
/* For extension callbacks */
cb_iter = ao2_iterator_init(hint->callbacks, 0);
for (; (state_cb = ao2_iterator_next(&cb_iter)); ao2_ref(state_cb, -1)) {
state_cb->change_cb(context_name, exten_name, state, state_cb->data);
}
ao2_iterator_destroy(&cb_iter);
}
ao2_iterator_destroy(&i);
ast_mutex_unlock(&context_merge_lock);
ast_free(hint_app);
ast_free(sc);
return 0;
}
/*!
* \internal
* \brief Destroy the given state callback object.
*
* \param doomed State callback to destroy.
*
* \return Nothing
*/
static void destroy_state_cb(void *doomed)
{
struct ast_state_cb *state_cb = doomed;
if (state_cb->destroy_cb) {
state_cb->destroy_cb(state_cb->id, state_cb->data);
}
}
/*! \brief Add watcher for extension states with destructor */
int ast_extension_state_add_destroy(const char *context, const char *exten,
ast_state_cb_type change_cb, ast_state_cb_destroy_type destroy_cb, void *data)
{
struct ast_hint *hint;
struct ast_state_cb *state_cb;
struct ast_exten *e;
int id;
/* If there's no context and extension: add callback to statecbs list */
if (!context && !exten) {
/* Prevent multiple adds from adding the same change_cb at the same time. */
ao2_lock(statecbs);
/* Remove any existing change_cb. */
ao2_find(statecbs, change_cb, OBJ_UNLINK | OBJ_NODATA);
/* Now insert the change_cb */
if (!(state_cb = ao2_alloc(sizeof(*state_cb), destroy_state_cb))) {
ao2_unlock(statecbs);
return -1;
}
state_cb->id = 0;
state_cb->change_cb = change_cb;
state_cb->destroy_cb = destroy_cb;
state_cb->data = data;
ao2_link(statecbs, state_cb);
ao2_ref(state_cb, -1);
ao2_unlock(statecbs);
return 0;
}
if (!context || !exten)
return -1;
/* This callback type is for only one hint, so get the hint */
e = ast_hint_extension(NULL, context, exten);
if (!e) {
return -1;
}
/* If this is a pattern, dynamically create a new extension for this
* particular match. Note that this will only happen once for each
* individual extension, because the pattern will no longer match first.
*/
if (e->exten[0] == '_') {
ast_add_extension(e->parent->name, 0, exten, e->priority, e->label,
e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr,
e->registrar);
e = ast_hint_extension(NULL, context, exten);
if (!e || e->exten[0] == '_') {
return -1;
}
}
/* Find the hint in the hints container */
ao2_lock(hints);/* Locked to hold off ast_merge_contexts_and_delete */
hint = ao2_find(hints, e, 0);
if (!hint) {
ao2_unlock(hints);
return -1;
}
/* Now insert the callback in the callback list */
if (!(state_cb = ao2_alloc(sizeof(*state_cb), destroy_state_cb))) {
ao2_ref(hint, -1);
ao2_unlock(hints);
return -1;
}
do {
id = stateid++; /* Unique ID for this callback */
/* Do not allow id to ever be -1 or 0. */
} while (id == -1 || id == 0);
state_cb->id = id;
state_cb->change_cb = change_cb; /* Pointer to callback routine */
state_cb->destroy_cb = destroy_cb;
state_cb->data = data; /* Data for the callback */
ao2_link(hint->callbacks, state_cb);
ao2_ref(state_cb, -1);
ao2_ref(hint, -1);
ao2_unlock(hints);
return id;
}
/*! \brief Add watcher for extension states */
int ast_extension_state_add(const char *context, const char *exten,
ast_state_cb_type change_cb, void *data)
{
return ast_extension_state_add_destroy(context, exten, change_cb, NULL, data);
}
/*! \brief Remove a watcher from the callback list */
static int find_hint_by_cb_id(void *obj, void *arg, int flags)
{
struct ast_state_cb *state_cb;
const struct ast_hint *hint = obj;
int *id = arg;
if ((state_cb = ao2_find(hint->callbacks, id, 0))) {
ao2_ref(state_cb, -1);
return CMP_MATCH | CMP_STOP;
}
return 0;
}
/*! \brief ast_extension_state_del: Remove a watcher from the callback list */
int ast_extension_state_del(int id, ast_state_cb_type change_cb)
{
struct ast_state_cb *p_cur;
int ret = -1;
if (!id) { /* id == 0 is a callback without extension */
if (!change_cb) {
return ret;
}
p_cur = ao2_find(statecbs, change_cb, OBJ_UNLINK);
if (p_cur) {
ret = 0;
ao2_ref(p_cur, -1);
}
} else { /* callback with extension, find the callback based on ID */
struct ast_hint *hint;
ao2_lock(hints);/* Locked to hold off ast_merge_contexts_and_delete */
hint = ao2_callback(hints, 0, find_hint_by_cb_id, &id);
if (hint) {
p_cur = ao2_find(hint->callbacks, &id, OBJ_UNLINK);
if (p_cur) {
ret = 0;
ao2_ref(p_cur, -1);
}
ao2_ref(hint, -1);
}
ao2_unlock(hints);
}
return ret;
}
static int hint_id_cmp(void *obj, void *arg, int flags)
{
const struct ast_state_cb *cb = obj;
int *id = arg;
return (cb->id == *id) ? CMP_MATCH | CMP_STOP : 0;
}
/*!
* \internal
* \brief Destroy the given hint object.
*
* \param obj Hint to destroy.
*
* \return Nothing
*/
static void destroy_hint(void *obj)
{
struct ast_hint *hint = obj;
if (hint->callbacks) {
struct ast_state_cb *state_cb;
const char *context_name;
const char *exten_name;
if (hint->exten) {
context_name = ast_get_context_name(ast_get_extension_context(hint->exten));
exten_name = ast_get_extension_name(hint->exten);
hint->exten = NULL;
} else {
/* The extension has already been destroyed */
context_name = hint->context_name;
exten_name = hint->exten_name;
}
while ((state_cb = ao2_callback(hint->callbacks, OBJ_UNLINK, NULL, NULL))) {
/* Notify with -1 and remove all callbacks */
/* NOTE: The casts will not be needed for v1.10 and later */
state_cb->change_cb((char *) context_name, (char *) exten_name,
AST_EXTENSION_DEACTIVATED, state_cb->data);
ao2_ref(state_cb, -1);
}
ao2_ref(hint->callbacks, -1);
}
}
/*! \brief Remove hint from extension */
static int ast_remove_hint(struct ast_exten *e)
{
/* Cleanup the Notifys if hint is removed */
struct ast_hint *hint;
if (!e) {
return -1;
}
hint = ao2_find(hints, e, OBJ_UNLINK);
if (!hint) {
return -1;
}
/*
* The extension is being destroyed so we must save some
* information to notify that the extension is deactivated.
*/
ao2_lock(hint);
ast_copy_string(hint->context_name,
ast_get_context_name(ast_get_extension_context(hint->exten)),
sizeof(hint->context_name));
ast_copy_string(hint->exten_name, ast_get_extension_name(hint->exten),
sizeof(hint->exten_name));
hint->exten = NULL;
ao2_unlock(hint);
ao2_ref(hint, -1);
return 0;
}
/*! \brief Add hint to hint list, check initial extension state */
static int ast_add_hint(struct ast_exten *e)
{
struct ast_hint *hint_new;
struct ast_hint *hint_found;
if (!e) {
return -1;
}
/*
* We must create the hint we wish to add before determining if
* it is already in the hints container to avoid possible
* deadlock when getting the current extension state.
*/
hint_new = ao2_alloc(sizeof(*hint_new), destroy_hint);
if (!hint_new) {
return -1;
}
/* Initialize new hint. */
hint_new->callbacks = ao2_container_alloc(1, NULL, hint_id_cmp);
if (!hint_new->callbacks) {
ao2_ref(hint_new, -1);
return -1;
}
hint_new->exten = e;
hint_new->laststate = ast_extension_state2(e);
/* Prevent multiple add hints from adding the same hint at the same time. */
ao2_lock(hints);
/* Search if hint exists, do nothing */
hint_found = ao2_find(hints, e, 0);
if (hint_found) {
ao2_ref(hint_found, -1);
ao2_unlock(hints);
ao2_ref(hint_new, -1);
ast_debug(2, "HINTS: Not re-adding existing hint %s: %s\n",
ast_get_extension_name(e), ast_get_extension_app(e));
return -1;
}
/* Add new hint to the hints container */
ast_debug(2, "HINTS: Adding hint %s: %s\n",
ast_get_extension_name(e), ast_get_extension_app(e));
ao2_link(hints, hint_new);
ao2_unlock(hints);
ao2_ref(hint_new, -1);
return 0;
}
/*! \brief Change hint for an extension */
static int ast_change_hint(struct ast_exten *oe, struct ast_exten *ne)
{
struct ast_hint *hint;
if (!oe || !ne) {
return -1;
}
ao2_lock(hints);/* Locked to hold off others while we move the hint around. */
/*
* Unlink the hint from the hints container as the extension
* name (which is the hash value) could change.
*/
hint = ao2_find(hints, oe, OBJ_UNLINK);
if (!hint) {
ao2_unlock(hints);
return -1;
}
/* Update the hint and put it back in the hints container. */
ao2_lock(hint);
hint->exten = ne;
ao2_unlock(hint);
ao2_link(hints, hint);
ao2_unlock(hints);
ao2_ref(hint, -1);
return 0;
}
/*! \brief Get hint for channel */
int ast_get_hint(char *hint, int hintsize, char *name, int namesize, struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e = ast_hint_extension(c, context, exten);
if (e) {
if (hint)
ast_copy_string(hint, ast_get_extension_app(e), hintsize);
if (name) {
const char *tmp = ast_get_extension_app_data(e);
if (tmp)
ast_copy_string(name, tmp, namesize);
}
return -1;
}
return 0;
}
/*! \brief Get hint for channel */
int ast_str_get_hint(struct ast_str **hint, ssize_t hintsize, struct ast_str **name, ssize_t namesize, struct ast_channel *c, const char *context, const char *exten)
{
struct ast_exten *e = ast_hint_extension(c, context, exten);
if (!e) {
return 0;
}
if (hint) {
ast_str_set(hint, hintsize, "%s", ast_get_extension_app(e));
}
if (name) {
const char *tmp = ast_get_extension_app_data(e);
if (tmp) {
ast_str_set(name, namesize, "%s", tmp);
}
}
return -1;
}
int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCH, 0, 0);
}
int ast_findlabel_extension(struct ast_channel *c, const char *context, const char *exten, const char *label, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, 0, label, callerid, E_FINDLABEL, 0, 0);
}
int ast_findlabel_extension2(struct ast_channel *c, struct ast_context *con, const char *exten, const char *label, const char *callerid)
{
return pbx_extension_helper(c, con, NULL, exten, 0, label, callerid, E_FINDLABEL, 0, 0);
}
int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_CANMATCH, 0, 0);
}
int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCHMORE, 0, 0);
}
int ast_spawn_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid, int *found, int combined_find_spawn)
{
return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_SPAWN, found, combined_find_spawn);
}
/*! helper function to set extension and priority */
static void set_ext_pri(struct ast_channel *c, const char *exten, int pri)
{
ast_channel_lock(c);
ast_copy_string(c->exten, exten, sizeof(c->exten));
c->priority = pri;
ast_channel_unlock(c);
}
/*!
* \brief collect digits from the channel into the buffer.
* \param c, buf, buflen, pos
* \param waittime is in milliseconds
* \retval 0 on timeout or done.
* \retval -1 on error.
*/
static int collect_digits(struct ast_channel *c, int waittime, char *buf, int buflen, int pos)
{
int digit;
buf[pos] = '\0'; /* make sure it is properly terminated */
while (ast_matchmore_extension(c, c->context, buf, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* As long as we're willing to wait, and as long as it's not defined,
keep reading digits until we can't possibly get a right answer anymore. */
digit = ast_waitfordigit(c, waittime);
if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) {
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO);
} else {
if (!digit) /* No entry */
break;
if (digit < 0) /* Error, maybe a hangup */
return -1;
if (pos < buflen - 1) { /* XXX maybe error otherwise ? */
buf[pos++] = digit;
buf[pos] = '\0';
}
waittime = c->pbx->dtimeoutms;
}
}
return 0;
}
static enum ast_pbx_result __ast_pbx_run(struct ast_channel *c,
struct ast_pbx_args *args)
{
int found = 0; /* set if we find at least one match */
int res = 0;
int autoloopflag;
int error = 0; /* set an error conditions */
/* A little initial setup here */
if (c->pbx) {
ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name);
/* XXX and now what ? */
ast_free(c->pbx);
}
if (!(c->pbx = ast_calloc(1, sizeof(*c->pbx))))
return -1;
/* Set reasonable defaults */
c->pbx->rtimeoutms = 10000;
c->pbx->dtimeoutms = 5000;
autoloopflag = ast_test_flag(c, AST_FLAG_IN_AUTOLOOP); /* save value to restore at the end */
ast_set_flag(c, AST_FLAG_IN_AUTOLOOP);
/* Start by trying whatever the channel is set to */
if (!ast_exists_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* If not successful fall back to 's' */
ast_verb(2, "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c->name, c->context, c->exten, c->priority);
/* XXX the original code used the existing priority in the call to
* ast_exists_extension(), and reset it to 1 afterwards.
* I believe the correct thing is to set it to 1 immediately.
*/
set_ext_pri(c, "s", 1);
if (!ast_exists_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* JK02: And finally back to default if everything else failed */
ast_verb(2, "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c->name, c->context, c->exten, c->priority);
ast_copy_string(c->context, "default", sizeof(c->context));
}
}
ast_channel_lock(c);
if (c->cdr) {
/* allow CDR variables that have been collected after channel was created to be visible during call */
ast_cdr_update(c);
}
ast_channel_unlock(c);
for (;;) {
char dst_exten[256]; /* buffer to accumulate digits */
int pos = 0; /* XXX should check bounds */
int digit = 0;
int invalid = 0;
int timeout = 0;
/* No digits pressed yet */
dst_exten[pos] = '\0';
/* loop on priorities in this context/exten */
while (!(res = ast_spawn_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL),
&found, 1))) {
if (!ast_check_hangup(c)) {
++c->priority;
continue;
}
/* Check softhangup flags. */
if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) {
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO);
continue;
}
if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) {
if (ast_exists_extension(c, c->context, "T", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
set_ext_pri(c, "T", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "ABSOLUTETIMEOUT", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
}
/* Call timed out with no special extension to jump to. */
error = 1;
break;
}
ast_debug(1, "Extension %s, priority %d returned normally even though call was hung up\n",
c->exten, c->priority);
error = 1;
break;
} /* end while - from here on we can use 'break' to go out */
if (found && res) {
/* Something bad happened, or a hangup has been requested. */
if (strchr("0123456789ABCDEF*#", res)) {
ast_debug(1, "Oooh, got something to jump out with ('%c')!\n", res);
pos = 0;
dst_exten[pos++] = digit = res;
dst_exten[pos] = '\0';
} else if (res == AST_PBX_INCOMPLETE) {
ast_debug(1, "Spawn extension (%s,%s,%d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name);
ast_verb(2, "Spawn extension (%s, %s, %d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name);
/* Don't cycle on incomplete - this will happen if the only extension that matches is our "incomplete" extension */
if (!ast_matchmore_extension(c, c->context, c->exten, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
invalid = 1;
} else {
ast_copy_string(dst_exten, c->exten, sizeof(dst_exten));
digit = 1;
pos = strlen(dst_exten);
}
} else {
ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
if ((res == AST_PBX_ERROR)
&& ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
/* if we are already on the 'e' exten, don't jump to it again */
if (!strcmp(c->exten, "e")) {
ast_verb(2, "Spawn extension (%s, %s, %d) exited ERROR while already on 'e' exten on '%s'\n", c->context, c->exten, c->priority, c->name);
error = 1;
} else {
raise_exception(c, "ERROR", 1);
continue;
}
}
if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) {
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO);
continue;
}
if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) {
if (ast_exists_extension(c, c->context, "T", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
set_ext_pri(c, "T", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "ABSOLUTETIMEOUT", 1);
/* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
memset(&c->whentohangup, 0, sizeof(c->whentohangup));
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
continue;
}
/* Call timed out with no special extension to jump to. */
}
ast_channel_lock(c);
if (c->cdr) {
ast_cdr_update(c);
}
ast_channel_unlock(c);
error = 1;
break;
}
}
if (error)
break;
/*!\note
* We get here on a failure of some kind: non-existing extension or
* hangup. We have options, here. We can either catch the failure
* and continue, or we can drop out entirely. */
if (invalid
|| (ast_strlen_zero(dst_exten) &&
!ast_exists_extension(c, c->context, c->exten, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL)))) {
/*!\note
* If there is no match at priority 1, it is not a valid extension anymore.
* Try to continue at "i" (for invalid) or "e" (for exception) or exit if
* neither exist.
*/
if (ast_exists_extension(c, c->context, "i", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
ast_verb(3, "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name);
pbx_builtin_setvar_helper(c, "INVALID_EXTEN", c->exten);
set_ext_pri(c, "i", 1);
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "INVALID", 1);
} else {
ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
c->name, c->exten, c->context);
error = 1; /* we know what to do with it */
break;
}
} else if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) {
/* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */
ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT);
} else { /* keypress received, get more digits for a full extension */
int waittime = 0;
if (digit)
waittime = c->pbx->dtimeoutms;
else if (!autofallthrough)
waittime = c->pbx->rtimeoutms;
if (!waittime) {
const char *status = pbx_builtin_getvar_helper(c, "DIALSTATUS");
if (!status)
status = "UNKNOWN";
ast_verb(3, "Auto fallthrough, channel '%s' status is '%s'\n", c->name, status);
if (!strcasecmp(status, "CONGESTION"))
res = pbx_builtin_congestion(c, "10");
else if (!strcasecmp(status, "CHANUNAVAIL"))
res = pbx_builtin_congestion(c, "10");
else if (!strcasecmp(status, "BUSY"))
res = pbx_builtin_busy(c, "10");
error = 1; /* XXX disable message */
break; /* exit from the 'for' loop */
}
if (collect_digits(c, waittime, dst_exten, sizeof(dst_exten), pos))
break;
if (res == AST_PBX_INCOMPLETE && ast_strlen_zero(&dst_exten[pos]))
timeout = 1;
if (!timeout
&& ast_exists_extension(c, c->context, dst_exten, 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* Prepare the next cycle */
set_ext_pri(c, dst_exten, 1);
} else {
/* No such extension */
if (!timeout && !ast_strlen_zero(dst_exten)) {
/* An invalid extension */
if (ast_exists_extension(c, c->context, "i", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
ast_verb(3, "Invalid extension '%s' in context '%s' on %s\n", dst_exten, c->context, c->name);
pbx_builtin_setvar_helper(c, "INVALID_EXTEN", dst_exten);
set_ext_pri(c, "i", 1);
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "INVALID", 1);
} else {
ast_log(LOG_WARNING,
"Invalid extension '%s', but no rule 'i' or 'e' in context '%s'\n",
dst_exten, c->context);
found = 1; /* XXX disable message */
break;
}
} else {
/* A simple timeout */
if (ast_exists_extension(c, c->context, "t", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
ast_verb(3, "Timeout on %s\n", c->name);
set_ext_pri(c, "t", 1);
} else if (ast_exists_extension(c, c->context, "e", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
raise_exception(c, "RESPONSETIMEOUT", 1);
} else {
ast_log(LOG_WARNING,
"Timeout, but no rule 't' or 'e' in context '%s'\n",
c->context);
found = 1; /* XXX disable message */
break;
}
}
}
ast_channel_lock(c);
if (c->cdr) {
ast_verb(2, "CDR updated on %s\n",c->name);
ast_cdr_update(c);
}
ast_channel_unlock(c);
}
}
if (!found && !error) {
ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name);
}
if (!args || !args->no_hangup_chan) {
ast_softhangup(c, AST_SOFTHANGUP_APPUNLOAD);
}
if ((!args || !args->no_hangup_chan)
&& !ast_test_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN)
&& ast_exists_extension(c, c->context, "h", 1,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) {
set_ext_pri(c, "h", 1);
if (c->cdr && ast_opt_end_cdr_before_h_exten) {
ast_cdr_end(c->cdr);
}
while ((res = ast_spawn_extension(c, c->context, c->exten, c->priority,
S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL),
&found, 1)) == 0) {
c->priority++;
}
if (found && res) {
/* Something bad happened, or a hangup has been requested. */
ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
}
}
ast_set2_flag(c, autoloopflag, AST_FLAG_IN_AUTOLOOP);
ast_clear_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN); /* from one round to the next, make sure this gets cleared */
pbx_destroy(c->pbx);
c->pbx = NULL;
if (!args || !args->no_hangup_chan) {
ast_hangup(c);
}
return 0;
}
/*!
* \brief Increase call count for channel
* \retval 0 on success
* \retval non-zero if a configured limit (maxcalls, maxload, minmemfree) was reached
*/
static int increase_call_count(const struct ast_channel *c)
{
int failed = 0;
double curloadavg;
#if defined(HAVE_SYSINFO)
long curfreemem;
struct sysinfo sys_info;
#endif
ast_mutex_lock(&maxcalllock);
if (option_maxcalls) {
if (countcalls >= option_maxcalls) {
ast_log(LOG_WARNING, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls, c->name);
failed = -1;
}
}
if (option_maxload) {
getloadavg(&curloadavg, 1);
if (curloadavg >= option_maxload) {
ast_log(LOG_WARNING, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload, c->name, curloadavg);
failed = -1;
}
}
#if defined(HAVE_SYSINFO)
if (option_minmemfree) {
if (!sysinfo(&sys_info)) {
/* make sure that the free system memory is above the configured low watermark
* convert the amount of freeram from mem_units to MB */
curfreemem = sys_info.freeram * sys_info.mem_unit;
curfreemem /= 1024 * 1024;
if (curfreemem < option_minmemfree) {
ast_log(LOG_WARNING, "Available system memory (~%ldMB) is below the configured low watermark (%ldMB)\n", curfreemem, option_minmemfree);
failed = -1;
}
}
}
#endif
if (!failed) {
countcalls++;
totalcalls++;
}
ast_mutex_unlock(&maxcalllock);
return failed;
}
static void decrease_call_count(void)
{
ast_mutex_lock(&maxcalllock);
if (countcalls > 0)
countcalls--;
ast_mutex_unlock(&maxcalllock);
}
static void destroy_exten(struct ast_exten *e)
{
if (e->priority == PRIORITY_HINT)
ast_remove_hint(e);
if (e->peer_table)
ast_hashtab_destroy(e->peer_table,0);
if (e->peer_label_table)
ast_hashtab_destroy(e->peer_label_table, 0);
if (e->datad)
e->datad(e->data);
ast_free(e);
}
static void *pbx_thread(void *data)
{
/* Oh joyeous kernel, we're a new thread, with nothing to do but
answer this channel and get it going.
*/
/* NOTE:
The launcher of this function _MUST_ increment 'countcalls'
before invoking the function; it will be decremented when the
PBX has finished running on the channel
*/
struct ast_channel *c = data;
__ast_pbx_run(c, NULL);
decrease_call_count();
pthread_exit(NULL);
return NULL;
}
enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
{
pthread_t t;
if (!c) {
ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n");
return AST_PBX_FAILED;
}
if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
ast_log(LOG_WARNING, "PBX requires Asterisk to be fully booted\n");
return AST_PBX_FAILED;
}
if (increase_call_count(c))
return AST_PBX_CALL_LIMIT;
/* Start a new thread, and get something handling this channel. */
if (ast_pthread_create_detached(&t, NULL, pbx_thread, c)) {
ast_log(LOG_WARNING, "Failed to create new channel thread\n");
decrease_call_count();
return AST_PBX_FAILED;
}
return AST_PBX_SUCCESS;
}
enum ast_pbx_result ast_pbx_run_args(struct ast_channel *c, struct ast_pbx_args *args)
{
enum ast_pbx_result res = AST_PBX_SUCCESS;
if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
ast_log(LOG_WARNING, "PBX requires Asterisk to be fully booted\n");
return AST_PBX_FAILED;
}
if (increase_call_count(c)) {
return AST_PBX_CALL_LIMIT;
}
res = __ast_pbx_run(c, args);
decrease_call_count();
return res;
}
enum ast_pbx_result ast_pbx_run(struct ast_channel *c)
{
return ast_pbx_run_args(c, NULL);
}
int ast_active_calls(void)
{
return countcalls;
}
int ast_processed_calls(void)
{
return totalcalls;
}
int pbx_set_autofallthrough(int newval)
{
int oldval = autofallthrough;
autofallthrough = newval;
return oldval;
}
int pbx_set_extenpatternmatchnew(int newval)
{
int oldval = extenpatternmatchnew;
extenpatternmatchnew = newval;
return oldval;
}
void pbx_set_overrideswitch(const char *newval)
{
if (overrideswitch) {
ast_free(overrideswitch);
}
if (!ast_strlen_zero(newval)) {
overrideswitch = ast_strdup(newval);
} else {
overrideswitch = NULL;
}
}
/*!
* \brief lookup for a context with a given name,
* \retval found context or NULL if not found.
*/
static struct ast_context *find_context(const char *context)
{
struct fake_context item;
ast_copy_string(item.name, context, sizeof(item.name));
return ast_hashtab_lookup(contexts_table, &item);
}
/*!
* \brief lookup for a context with a given name,
* \retval with conlock held if found.
* \retval NULL if not found.
*/
static struct ast_context *find_context_locked(const char *context)
{
struct ast_context *c;
struct fake_context item;
ast_copy_string(item.name, context, sizeof(item.name));
ast_rdlock_contexts();
c = ast_hashtab_lookup(contexts_table, &item);
if (!c) {
ast_unlock_contexts();
}
return c;
}
/*!
* \brief Remove included contexts.
* This function locks contexts list by &conlist, search for the right context
* structure, leave context list locked and call ast_context_remove_include2
* which removes include, unlock contexts list and return ...
*/
int ast_context_remove_include(const char *context, const char *include, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
/* found, remove include from this context ... */
ret = ast_context_remove_include2(c, include, registrar);
ast_unlock_contexts();
}
return ret;
}
/*!
* \brief Locks context, remove included contexts, unlocks context.
* When we call this function, &conlock lock must be locked, because when
* we giving *con argument, some process can remove/change this context
* and after that there can be segfault.
*
* \retval 0 on success.
* \retval -1 on failure.
*/
int ast_context_remove_include2(struct ast_context *con, const char *include, const char *registrar)
{
struct ast_include *i, *pi = NULL;
int ret = -1;
ast_wrlock_context(con);
/* find our include */
for (i = con->includes; i; pi = i, i = i->next) {
if (!strcmp(i->name, include) &&
(!registrar || !strcmp(i->registrar, registrar))) {
/* remove from list */
ast_verb(3, "Removing inclusion of context '%s' in context '%s; registrar=%s'\n", include, ast_get_context_name(con), registrar);
if (pi)
pi->next = i->next;
else
con->includes = i->next;
/* free include and return */
ast_destroy_timing(&(i->timing));
ast_free(i);
ret = 0;
break;
}
}
ast_unlock_context(con);
return ret;
}
/*!
* \note This function locks contexts list by &conlist, search for the rigt context
* structure, leave context list locked and call ast_context_remove_switch2
* which removes switch, unlock contexts list and return ...
*/
int ast_context_remove_switch(const char *context, const char *sw, const char *data, const char *registrar)
{
int ret = -1; /* default error return */
struct ast_context *c;
c = find_context_locked(context);
if (c) {
/* remove switch from this context ... */
ret = ast_context_remove_switch2(c, sw, data, registrar);
ast_unlock_contexts();
}
return ret;
}
/*!
* \brief This function locks given context, removes switch, unlock context and
* return.
* \note When we call this function, &conlock lock must be locked, because when
* we giving *con argument, some process can remove/change this context
* and after that there can be segfault.
*
*/
int ast_context_remove_switch2(struct ast_context *con, const char *sw, const char *data, const char *registrar)
{
struct ast_sw *i;
int ret = -1;
ast_wrlock_context(con);
/* walk switches */
AST_LIST_TRAVERSE_SAFE_BEGIN(&con->alts, i, list) {
if (!strcmp(i->name, sw) && !strcmp(i->data, data) &&
(!registrar || !strcmp(i->registrar, registrar))) {
/* found, remove from list */
ast_verb(3, "Removing switch '%s' from context '%s; registrar=%s'\n", sw, ast_get_context_name(con), registrar);
AST_LIST_REMOVE_CURRENT(list);
ast_free(i); /* free switch and return */
ret = 0;
break;
}
}
AST_LIST_TRAVERSE_SAFE_END;
ast_unlock_context(con);
return ret;
}
/*! \note This function will lock conlock. */
int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
{
return ast_context_remove_extension_callerid(context, extension, priority, NULL, 0, registrar);
}
int ast_context_remove_extension_callerid(const char *context, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar)
{
int ret = -1; /* default error return */
struct ast_context *c;
c = find_context_locked(context);
if (c) { /* ... remove extension ... */
ret = ast_context_remove_extension_callerid2(c, extension, priority, callerid,
matchcallerid, registrar, 0);
ast_unlock_contexts();
}
return ret;
}
/*!
* \brief This functionc locks given context, search for the right extension and
* fires out all peer in this extensions with given priority. If priority
* is set to 0, all peers are removed. After that, unlock context and
* return.
* \note When do you want to call this function, make sure that &conlock is locked,
* because some process can handle with your *con context before you lock
* it.
*
*/
int ast_context_remove_extension2(struct ast_context *con, const char *extension, int priority, const char *registrar, int already_locked)
{
return ast_context_remove_extension_callerid2(con, extension, priority, NULL, 0, registrar, already_locked);
}
int ast_context_remove_extension_callerid2(struct ast_context *con, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar, int already_locked)
{
struct ast_exten *exten, *prev_exten = NULL;
struct ast_exten *peer;
struct ast_exten ex, *exten2, *exten3;
char dummy_name[1024];
struct ast_exten *previous_peer = NULL;
struct ast_exten *next_peer = NULL;
int found = 0;
if (!already_locked)
ast_wrlock_context(con);
/* Handle this is in the new world */
/* FIXME For backwards compatibility, if callerid==NULL, then remove ALL
* peers, not just those matching the callerid. */
#ifdef NEED_DEBUG
ast_verb(3,"Removing %s/%s/%d%s%s from trees, registrar=%s\n", con->name, extension, priority, matchcallerid ? "/" : "", matchcallerid ? callerid : "", registrar);
#endif
#ifdef CONTEXT_DEBUG
check_contexts(__FILE__, __LINE__);
#endif
/* find this particular extension */
ex.exten = dummy_name;
ex.matchcid = matchcallerid && !ast_strlen_zero(callerid); /* don't say match if there's no callerid */
ex.cidmatch = callerid;
ast_copy_string(dummy_name, extension, sizeof(dummy_name));
exten = ast_hashtab_lookup(con->root_table, &ex);
if (exten) {
if (priority == 0) {
exten2 = ast_hashtab_remove_this_object(con->root_table, exten);
if (!exten2)
ast_log(LOG_ERROR,"Trying to delete the exten %s from context %s, but could not remove from the root_table\n", extension, con->name);
if (con->pattern_tree) {
struct match_char *x = add_exten_to_pattern_tree(con, exten, 1);
if (x->exten) { /* this test for safety purposes */
x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
x->exten = 0; /* get rid of what will become a bad pointer */
} else {
ast_log(LOG_WARNING,"Trying to delete an exten from a context, but the pattern tree node returned isn't a full extension\n");
}
}
} else {
ex.priority = priority;
exten2 = ast_hashtab_lookup(exten->peer_table, &ex);
if (exten2) {
if (exten2->label) { /* if this exten has a label, remove that, too */
exten3 = ast_hashtab_remove_this_object(exten->peer_label_table,exten2);
if (!exten3)
ast_log(LOG_ERROR,"Did not remove this priority label (%d/%s) from the peer_label_table of context %s, extension %s!\n", priority, exten2->label, con->name, exten2->exten);
}
exten3 = ast_hashtab_remove_this_object(exten->peer_table, exten2);
if (!exten3)
ast_log(LOG_ERROR,"Did not remove this priority (%d) from the peer_table of context %s, extension %s!\n", priority, con->name, exten2->exten);
if (exten2 == exten && exten2->peer) {
exten2 = ast_hashtab_remove_this_object(con->root_table, exten);
ast_hashtab_insert_immediate(con->root_table, exten2->peer);
}
if (ast_hashtab_size(exten->peer_table) == 0) {
/* well, if the last priority of an exten is to be removed,
then, the extension is removed, too! */
exten3 = ast_hashtab_remove_this_object(con->root_table, exten);
if (!exten3)
ast_log(LOG_ERROR,"Did not remove this exten (%s) from the context root_table (%s) (priority %d)\n", exten->exten, con->name, priority);
if (con->pattern_tree) {
struct match_char *x = add_exten_to_pattern_tree(con, exten, 1);
if (x->exten) { /* this test for safety purposes */
x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
x->exten = 0; /* get rid of what will become a bad pointer */
}
}
}
} else {
ast_log(LOG_ERROR,"Could not find priority %d of exten %s in context %s!\n",
priority, exten->exten, con->name);
}
}
} else {
/* hmmm? this exten is not in this pattern tree? */
ast_log(LOG_WARNING,"Cannot find extension %s in root_table in context %s\n",
extension, con->name);
}
#ifdef NEED_DEBUG
if (con->pattern_tree) {
ast_log(LOG_NOTICE,"match char tree after exten removal:\n");
log_match_char_tree(con->pattern_tree, " ");
}
#endif
/* scan the extension list to find first matching extension-registrar */
for (exten = con->root; exten; prev_exten = exten, exten = exten->next) {
if (!strcmp(exten->exten, extension) &&
(!registrar || !strcmp(exten->registrar, registrar)) &&
(!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(exten->cidmatch) && !strcmp(exten->cidmatch, callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(exten->cidmatch))))
break;
}
if (!exten) {
/* we can't find right extension */
if (!already_locked)
ast_unlock_context(con);
return -1;
}
/* scan the priority list to remove extension with exten->priority == priority */
for (peer = exten, next_peer = exten->peer ? exten->peer : exten->next;
peer && !strcmp(peer->exten, extension) && (!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(peer->cidmatch) && !strcmp(peer->cidmatch,callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(peer->cidmatch)));
peer = next_peer, next_peer = next_peer ? (next_peer->peer ? next_peer->peer : next_peer->next) : NULL) {
if ((priority == 0 || peer->priority == priority) &&
(!callerid || !matchcallerid || (matchcallerid && !strcmp(peer->cidmatch, callerid))) &&
(!registrar || !strcmp(peer->registrar, registrar) )) {
found = 1;
/* we are first priority extension? */
if (!previous_peer) {
/*
* We are first in the priority chain, so must update the extension chain.
* The next node is either the next priority or the next extension
*/
struct ast_exten *next_node = peer->peer ? peer->peer : peer->next;
if (peer->peer) {
/* move the peer_table and peer_label_table down to the next peer, if
it is there */
peer->peer->peer_table = peer->peer_table;
peer->peer->peer_label_table = peer->peer_label_table;
peer->peer_table = NULL;
peer->peer_label_table = NULL;
}
if (!prev_exten) { /* change the root... */
con->root = next_node;
} else {
prev_exten->next = next_node; /* unlink */
}
if (peer->peer) { /* update the new head of the pri list */
peer->peer->next = peer->next;
}
} else { /* easy, we are not first priority in extension */
previous_peer->peer = peer->peer;
}
/* now, free whole priority extension */
destroy_exten(peer);
} else {
previous_peer = peer;
}
}
if (!already_locked)
ast_unlock_context(con);
return found ? 0 : -1;
}
/*!
* \note This function locks contexts list by &conlist, searches for the right context
* structure, and locks the macrolock mutex in that context.
* macrolock is used to limit a macro to be executed by one call at a time.
*/
int ast_context_lockmacro(const char *context)
{
struct ast_context *c;
int ret = -1;
c = find_context_locked(context);
if (c) {
ast_unlock_contexts();
/* if we found context, lock macrolock */
ret = ast_mutex_lock(&c->macrolock);
}
return ret;
}
/*!
* \note This function locks contexts list by &conlist, searches for the right context
* structure, and unlocks the macrolock mutex in that context.
* macrolock is used to limit a macro to be executed by one call at a time.
*/
int ast_context_unlockmacro(const char *context)
{
struct ast_context *c;
int ret = -1;
c = find_context_locked(context);
if (c) {
ast_unlock_contexts();
/* if we found context, unlock macrolock */
ret = ast_mutex_unlock(&c->macrolock);
}
return ret;
}
/*! \brief Dynamically register a new dial plan application */
int ast_register_application2(const char *app, int (*execute)(struct ast_channel *, const char *), const char *synopsis, const char *description, void *mod)
{
struct ast_app *tmp, *cur = NULL;
char tmps[80];
int length, res;
#ifdef AST_XML_DOCS
char *tmpxml;
#endif
AST_RWLIST_WRLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, tmp, list) {
if (!(res = strcasecmp(app, tmp->name))) {
ast_log(LOG_WARNING, "Already have an application '%s'\n", app);
AST_RWLIST_UNLOCK(&apps);
return -1;
} else if (res < 0)
break;
}
length = sizeof(*tmp) + strlen(app) + 1;
if (!(tmp = ast_calloc(1, length))) {
AST_RWLIST_UNLOCK(&apps);
return -1;
}
if (ast_string_field_init(tmp, 128)) {
AST_RWLIST_UNLOCK(&apps);
ast_free(tmp);
return -1;
}
strcpy(tmp->name, app);
tmp->execute = execute;
tmp->module = mod;
#ifdef AST_XML_DOCS
/* Try to lookup the docs in our XML documentation database */
if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
/* load synopsis */
tmpxml = ast_xmldoc_build_synopsis("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, synopsis, tmpxml);
ast_free(tmpxml);
/* load description */
tmpxml = ast_xmldoc_build_description("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, description, tmpxml);
ast_free(tmpxml);
/* load syntax */
tmpxml = ast_xmldoc_build_syntax("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, syntax, tmpxml);
ast_free(tmpxml);
/* load arguments */
tmpxml = ast_xmldoc_build_arguments("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, arguments, tmpxml);
ast_free(tmpxml);
/* load seealso */
tmpxml = ast_xmldoc_build_seealso("application", app, ast_module_name(tmp->module));
ast_string_field_set(tmp, seealso, tmpxml);
ast_free(tmpxml);
tmp->docsrc = AST_XML_DOC;
} else {
#endif
ast_string_field_set(tmp, synopsis, synopsis);
ast_string_field_set(tmp, description, description);
#ifdef AST_XML_DOCS
tmp->docsrc = AST_STATIC_DOC;
}
#endif
/* Store in alphabetical order */
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, cur, list) {
if (strcasecmp(tmp->name, cur->name) < 0) {
AST_RWLIST_INSERT_BEFORE_CURRENT(tmp, list);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
if (!cur)
AST_RWLIST_INSERT_TAIL(&apps, tmp, list);
ast_verb(2, "Registered application '%s'\n", term_color(tmps, tmp->name, COLOR_BRCYAN, 0, sizeof(tmps)));
AST_RWLIST_UNLOCK(&apps);
return 0;
}
/*
* Append to the list. We don't have a tail pointer because we need
* to scan the list anyways to check for duplicates during insertion.
*/
int ast_register_switch(struct ast_switch *sw)
{
struct ast_switch *tmp;
AST_RWLIST_WRLOCK(&switches);
AST_RWLIST_TRAVERSE(&switches, tmp, list) {
if (!strcasecmp(tmp->name, sw->name)) {
AST_RWLIST_UNLOCK(&switches);
ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name);
return -1;
}
}
AST_RWLIST_INSERT_TAIL(&switches, sw, list);
AST_RWLIST_UNLOCK(&switches);
return 0;
}
void ast_unregister_switch(struct ast_switch *sw)
{
AST_RWLIST_WRLOCK(&switches);
AST_RWLIST_REMOVE(&switches, sw, list);
AST_RWLIST_UNLOCK(&switches);
}
/*
* Help for CLI commands ...
*/
static void print_app_docs(struct ast_app *aa, int fd)
{
/* Maximum number of characters added by terminal coloring is 22 */
char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], stxtitle[40], argtitle[40];
char seealsotitle[40];
char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *syntax = NULL, *arguments = NULL;
char *seealso = NULL;
int syntax_size, synopsis_size, description_size, arguments_size, seealso_size;
snprintf(info, sizeof(info), "\n -= Info about application '%s' =- \n\n", aa->name);
term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle));
term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40);
#ifdef AST_XML_DOCS
if (aa->docsrc == AST_XML_DOC) {
description = ast_xmldoc_printable(S_OR(aa->description, "Not available"), 1);
arguments = ast_xmldoc_printable(S_OR(aa->arguments, "Not available"), 1);
synopsis = ast_xmldoc_printable(S_OR(aa->synopsis, "Not available"), 1);
seealso = ast_xmldoc_printable(S_OR(aa->seealso, "Not available"), 1);
if (!synopsis || !description || !arguments || !seealso) {
goto return_cleanup;
}
} else
#endif
{
synopsis_size = strlen(S_OR(aa->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
synopsis = ast_malloc(synopsis_size);
description_size = strlen(S_OR(aa->description, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
description = ast_malloc(description_size);
arguments_size = strlen(S_OR(aa->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
arguments = ast_malloc(arguments_size);
seealso_size = strlen(S_OR(aa->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
seealso = ast_malloc(seealso_size);
if (!synopsis || !description || !arguments || !seealso) {
goto return_cleanup;
}
term_color(synopsis, S_OR(aa->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size);
term_color(description, S_OR(aa->description, "Not available"), COLOR_CYAN, 0, description_size);
term_color(arguments, S_OR(aa->arguments, "Not available"), COLOR_CYAN, 0, arguments_size);
term_color(seealso, S_OR(aa->seealso, "Not available"), COLOR_CYAN, 0, seealso_size);
}
/* Handle the syntax the same for both XML and raw docs */
syntax_size = strlen(S_OR(aa->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS;
if (!(syntax = ast_malloc(syntax_size))) {
goto return_cleanup;
}
term_color(syntax, S_OR(aa->syntax, "Not available"), COLOR_CYAN, 0, syntax_size);
ast_cli(fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n",
infotitle, syntitle, synopsis, destitle, description,
stxtitle, syntax, argtitle, arguments, seealsotitle, seealso);
return_cleanup:
ast_free(description);
ast_free(arguments);
ast_free(synopsis);
ast_free(seealso);
ast_free(syntax);
}
/*
* \brief 'show application' CLI command implementation function...
*/
static char *handle_show_application(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_app *aa;
int app, no_registered_app = 1;
switch (cmd) {
case CLI_INIT:
e->command = "core show application";
e->usage =
"Usage: core show application <application> [<application> [<application> [...]]]\n"
" Describes a particular application.\n";
return NULL;
case CLI_GENERATE:
/*
* There is a possibility to show informations about more than one
* application at one time. You can type 'show application Dial Echo' and
* you will see informations about these two applications ...
*/
return ast_complete_applications(a->line, a->word, a->n);
}
if (a->argc < 4) {
return CLI_SHOWUSAGE;
}
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, aa, list) {
/* Check for each app that was supplied as an argument */
for (app = 3; app < a->argc; app++) {
if (strcasecmp(aa->name, a->argv[app])) {
continue;
}
/* We found it! */
no_registered_app = 0;
print_app_docs(aa, a->fd);
}
}
AST_RWLIST_UNLOCK(&apps);
/* we found at least one app? no? */
if (no_registered_app) {
ast_cli(a->fd, "Your application(s) is (are) not registered\n");
return CLI_FAILURE;
}
return CLI_SUCCESS;
}
/*! \brief handle_show_hints: CLI support for listing registered dial plan hints */
static char *handle_show_hints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_hint *hint;
int num = 0;
int watchers;
struct ao2_iterator i;
switch (cmd) {
case CLI_INIT:
e->command = "core show hints";
e->usage =
"Usage: core show hints\n"
" List registered hints\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (ao2_container_count(hints) == 0) {
ast_cli(a->fd, "There are no registered dialplan hints\n");
return CLI_SUCCESS;
}
/* ... we have hints ... */
ast_cli(a->fd, "\n -= Registered Asterisk Dial Plan Hints =-\n");
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
watchers = ao2_container_count(hint->callbacks);
ast_cli(a->fd, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n",
ast_get_extension_name(hint->exten),
ast_get_context_name(ast_get_extension_context(hint->exten)),
ast_get_extension_app(hint->exten),
ast_extension_state2str(hint->laststate), watchers);
ao2_unlock(hint);
num++;
}
ao2_iterator_destroy(&i);
ast_cli(a->fd, "----------------\n");
ast_cli(a->fd, "- %d hints registered\n", num);
return CLI_SUCCESS;
}
/*! \brief autocomplete for CLI command 'core show hint' */
static char *complete_core_show_hint(const char *line, const char *word, int pos, int state)
{
struct ast_hint *hint;
char *ret = NULL;
int which = 0;
int wordlen;
struct ao2_iterator i;
if (pos != 3)
return NULL;
wordlen = strlen(word);
/* walk through all hints */
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
if (!strncasecmp(word, ast_get_extension_name(hint->exten), wordlen) && ++which > state) {
ret = ast_strdup(ast_get_extension_name(hint->exten));
ao2_unlock(hint);
ao2_ref(hint, -1);
break;
}
ao2_unlock(hint);
}
ao2_iterator_destroy(&i);
return ret;
}
/*! \brief handle_show_hint: CLI support for listing registered dial plan hint */
static char *handle_show_hint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_hint *hint;
int watchers;
int num = 0, extenlen;
struct ao2_iterator i;
switch (cmd) {
case CLI_INIT:
e->command = "core show hint";
e->usage =
"Usage: core show hint <exten>\n"
" List registered hint\n";
return NULL;
case CLI_GENERATE:
return complete_core_show_hint(a->line, a->word, a->pos, a->n);
}
if (a->argc < 4)
return CLI_SHOWUSAGE;
if (ao2_container_count(hints) == 0) {
ast_cli(a->fd, "There are no registered dialplan hints\n");
return CLI_SUCCESS;
}
extenlen = strlen(a->argv[3]);
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed */
ao2_unlock(hint);
continue;
}
if (!strncasecmp(ast_get_extension_name(hint->exten), a->argv[3], extenlen)) {
watchers = ao2_container_count(hint->callbacks);
ast_cli(a->fd, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n",
ast_get_extension_name(hint->exten),
ast_get_context_name(ast_get_extension_context(hint->exten)),
ast_get_extension_app(hint->exten),
ast_extension_state2str(hint->laststate), watchers);
num++;
}
ao2_unlock(hint);
}
ao2_iterator_destroy(&i);
if (!num)
ast_cli(a->fd, "No hints matching extension %s\n", a->argv[3]);
else
ast_cli(a->fd, "%d hint%s matching extension %s\n", num, (num!=1 ? "s":""), a->argv[3]);
return CLI_SUCCESS;
}
/*! \brief handle_show_switches: CLI support for listing registered dial plan switches */
static char *handle_show_switches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_switch *sw;
switch (cmd) {
case CLI_INIT:
e->command = "core show switches";
e->usage =
"Usage: core show switches\n"
" List registered switches\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
AST_RWLIST_RDLOCK(&switches);
if (AST_RWLIST_EMPTY(&switches)) {
AST_RWLIST_UNLOCK(&switches);
ast_cli(a->fd, "There are no registered alternative switches\n");
return CLI_SUCCESS;
}
ast_cli(a->fd, "\n -= Registered Asterisk Alternative Switches =-\n");
AST_RWLIST_TRAVERSE(&switches, sw, list)
ast_cli(a->fd, "%s: %s\n", sw->name, sw->description);
AST_RWLIST_UNLOCK(&switches);
return CLI_SUCCESS;
}
static char *handle_show_applications(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_app *aa;
int like = 0, describing = 0;
int total_match = 0; /* Number of matches in like clause */
int total_apps = 0; /* Number of apps registered */
static const char * const choices[] = { "like", "describing", NULL };
switch (cmd) {
case CLI_INIT:
e->command = "core show applications [like|describing]";
e->usage =
"Usage: core show applications [{like|describing} <text>]\n"
" List applications which are currently available.\n"
" If 'like', <text> will be a substring of the app name\n"
" If 'describing', <text> will be a substring of the description\n";
return NULL;
case CLI_GENERATE:
return (a->pos != 3) ? NULL : ast_cli_complete(a->word, choices, a->n);
}
AST_RWLIST_RDLOCK(&apps);
if (AST_RWLIST_EMPTY(&apps)) {
ast_cli(a->fd, "There are no registered applications\n");
AST_RWLIST_UNLOCK(&apps);
return CLI_SUCCESS;
}
/* core list applications like <keyword> */
if ((a->argc == 5) && (!strcmp(a->argv[3], "like"))) {
like = 1;
} else if ((a->argc > 4) && (!strcmp(a->argv[3], "describing"))) {
describing = 1;
}
/* core list applications describing <keyword1> [<keyword2>] [...] */
if ((!like) && (!describing)) {
ast_cli(a->fd, " -= Registered Asterisk Applications =-\n");
} else {
ast_cli(a->fd, " -= Matching Asterisk Applications =-\n");
}
AST_RWLIST_TRAVERSE(&apps, aa, list) {
int printapp = 0;
total_apps++;
if (like) {
if (strcasestr(aa->name, a->argv[4])) {
printapp = 1;
total_match++;
}
} else if (describing) {
if (aa->description) {
/* Match all words on command line */
int i;
printapp = 1;
for (i = 4; i < a->argc; i++) {
if (!strcasestr(aa->description, a->argv[i])) {
printapp = 0;
} else {
total_match++;
}
}
}
} else {
printapp = 1;
}
if (printapp) {
ast_cli(a->fd," %20s: %s\n", aa->name, aa->synopsis ? aa->synopsis : "<Synopsis not available>");
}
}
if ((!like) && (!describing)) {
ast_cli(a->fd, " -= %d Applications Registered =-\n",total_apps);
} else {
ast_cli(a->fd, " -= %d Applications Matching =-\n",total_match);
}
AST_RWLIST_UNLOCK(&apps);
return CLI_SUCCESS;
}
/*
* 'show dialplan' CLI command implementation functions ...
*/
static char *complete_show_dialplan_context(const char *line, const char *word, int pos,
int state)
{
struct ast_context *c = NULL;
char *ret = NULL;
int which = 0;
int wordlen;
/* we are do completion of [exten@]context on second position only */
if (pos != 2)
return NULL;
ast_rdlock_contexts();
wordlen = strlen(word);
/* walk through all contexts and return the n-th match */
while ( (c = ast_walk_contexts(c)) ) {
if (!strncasecmp(word, ast_get_context_name(c), wordlen) && ++which > state) {
ret = ast_strdup(ast_get_context_name(c));
break;
}
}
ast_unlock_contexts();
return ret;
}
/*! \brief Counters for the show dialplan manager command */
struct dialplan_counters {
int total_items;
int total_context;
int total_exten;
int total_prio;
int context_existence;
int extension_existence;
};
/*! \brief helper function to print an extension */
static void print_ext(struct ast_exten *e, char * buf, int buflen)
{
int prio = ast_get_extension_priority(e);
if (prio == PRIORITY_HINT) {
snprintf(buf, buflen, "hint: %s",
ast_get_extension_app(e));
} else {
snprintf(buf, buflen, "%d. %s(%s)",
prio, ast_get_extension_app(e),
(!ast_strlen_zero(ast_get_extension_app_data(e)) ? (char *)ast_get_extension_app_data(e) : ""));
}
}
/* XXX not verified */
static int show_dialplan_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
{
struct ast_context *c = NULL;
int res = 0, old_total_exten = dpc->total_exten;
ast_rdlock_contexts();
/* walk all contexts ... */
while ( (c = ast_walk_contexts(c)) ) {
struct ast_exten *e;
struct ast_include *i;
struct ast_ignorepat *ip;
char buf[256], buf2[256];
int context_info_printed = 0;
if (context && strcmp(ast_get_context_name(c), context))
continue; /* skip this one, name doesn't match */
dpc->context_existence = 1;
ast_rdlock_context(c);
/* are we looking for exten too? if yes, we print context
* only if we find our extension.
* Otherwise print context even if empty ?
* XXX i am not sure how the rinclude is handled.
* I think it ought to go inside.
*/
if (!exten) {
dpc->total_context++;
ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
context_info_printed = 1;
}
/* walk extensions ... */
e = NULL;
while ( (e = ast_walk_context_extensions(c, e)) ) {
struct ast_exten *p;
if (exten && !ast_extension_match(ast_get_extension_name(e), exten))
continue; /* skip, extension match failed */
dpc->extension_existence = 1;
/* may we print context info? */
if (!context_info_printed) {
dpc->total_context++;
if (rinclude) { /* TODO Print more info about rinclude */
ast_cli(fd, "[ Included context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
} else {
ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
}
context_info_printed = 1;
}
dpc->total_prio++;
/* write extension name and first peer */
if (e->matchcid)
snprintf(buf, sizeof(buf), "'%s' (CID match '%s') => ", ast_get_extension_name(e), e->cidmatch);
else
snprintf(buf, sizeof(buf), "'%s' =>", ast_get_extension_name(e));
print_ext(e, buf2, sizeof(buf2));
ast_cli(fd, " %-17s %-45s [%s]\n", buf, buf2,
ast_get_extension_registrar(e));
dpc->total_exten++;
/* walk next extension peers */
p = e; /* skip the first one, we already got it */
while ( (p = ast_walk_extension_priorities(e, p)) ) {
const char *el = ast_get_extension_label(p);
dpc->total_prio++;
if (el)
snprintf(buf, sizeof(buf), " [%s]", el);
else
buf[0] = '\0';
print_ext(p, buf2, sizeof(buf2));
ast_cli(fd," %-17s %-45s [%s]\n", buf, buf2,
ast_get_extension_registrar(p));
}
}
/* walk included and write info ... */
i = NULL;
while ( (i = ast_walk_context_includes(c, i)) ) {
snprintf(buf, sizeof(buf), "'%s'", ast_get_include_name(i));
if (exten) {
/* Check all includes for the requested extension */
if (includecount >= AST_PBX_MAX_STACK) {
ast_log(LOG_WARNING, "Maximum include depth exceeded!\n");
} else {
int dupe = 0;
int x;
for (x = 0; x < includecount; x++) {
if (!strcasecmp(includes[x], ast_get_include_name(i))) {
dupe++;
break;
}
}
if (!dupe) {
includes[includecount] = ast_get_include_name(i);
show_dialplan_helper(fd, ast_get_include_name(i), exten, dpc, i, includecount + 1, includes);
} else {
ast_log(LOG_WARNING, "Avoiding circular include of %s within %s\n", ast_get_include_name(i), context);
}
}
} else {
ast_cli(fd, " Include => %-45s [%s]\n",
buf, ast_get_include_registrar(i));
}
}
/* walk ignore patterns and write info ... */
ip = NULL;
while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
const char *ipname = ast_get_ignorepat_name(ip);
char ignorepat[AST_MAX_EXTENSION];
snprintf(buf, sizeof(buf), "'%s'", ipname);
snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
if (!exten || ast_extension_match(ignorepat, exten)) {
ast_cli(fd, " Ignore pattern => %-45s [%s]\n",
buf, ast_get_ignorepat_registrar(ip));
}
}
if (!rinclude) {
struct ast_sw *sw = NULL;
while ( (sw = ast_walk_context_switches(c, sw)) ) {
snprintf(buf, sizeof(buf), "'%s/%s'",
ast_get_switch_name(sw),
ast_get_switch_data(sw));
ast_cli(fd, " Alt. Switch => %-45s [%s]\n",
buf, ast_get_switch_registrar(sw));
}
}
ast_unlock_context(c);
/* if we print something in context, make an empty line */
if (context_info_printed)
ast_cli(fd, "\n");
}
ast_unlock_contexts();
return (dpc->total_exten == old_total_exten) ? -1 : res;
}
static int show_debug_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
{
struct ast_context *c = NULL;
int res = 0, old_total_exten = dpc->total_exten;
ast_cli(fd,"\n In-mem exten Trie for Fast Extension Pattern Matching:\n\n");
ast_cli(fd,"\n Explanation: Node Contents Format = <char(s) to match>:<pattern?>:<specif>:[matched extension]\n");
ast_cli(fd, " Where <char(s) to match> is a set of chars, any one of which should match the current character\n");
ast_cli(fd, " <pattern?>: Y if this a pattern match (eg. _XZN[5-7]), N otherwise\n");
ast_cli(fd, " <specif>: an assigned 'exactness' number for this matching char. The lower the number, the more exact the match\n");
ast_cli(fd, " [matched exten]: If all chars matched to this point, which extension this matches. In form: EXTEN:<exten string>\n");
ast_cli(fd, " In general, you match a trie node to a string character, from left to right. All possible matching chars\n");
ast_cli(fd, " are in a string vertically, separated by an unbroken string of '+' characters.\n\n");
ast_rdlock_contexts();
/* walk all contexts ... */
while ( (c = ast_walk_contexts(c)) ) {
int context_info_printed = 0;
if (context && strcmp(ast_get_context_name(c), context))
continue; /* skip this one, name doesn't match */
dpc->context_existence = 1;
if (!c->pattern_tree) {
/* Ignore check_return warning from Coverity for ast_exists_extension below */
ast_exists_extension(NULL, c->name, "s", 1, ""); /* do this to force the trie to built, if it is not already */
}
ast_rdlock_context(c);
dpc->total_context++;
ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
ast_get_context_name(c), ast_get_context_registrar(c));
context_info_printed = 1;
if (c->pattern_tree)
{
cli_match_char_tree(c->pattern_tree, " ", fd);
} else {
ast_cli(fd,"\n No Pattern Trie present. Perhaps the context is empty...or there is trouble...\n\n");
}
ast_unlock_context(c);
/* if we print something in context, make an empty line */
if (context_info_printed)
ast_cli(fd, "\n");
}
ast_unlock_contexts();
return (dpc->total_exten == old_total_exten) ? -1 : res;
}
static char *handle_show_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
char *exten = NULL, *context = NULL;
/* Variables used for different counters */
struct dialplan_counters counters;
const char *incstack[AST_PBX_MAX_STACK];
switch (cmd) {
case CLI_INIT:
e->command = "dialplan show";
e->usage =
"Usage: dialplan show [[exten@]context]\n"
" Show dialplan\n";
return NULL;
case CLI_GENERATE:
return complete_show_dialplan_context(a->line, a->word, a->pos, a->n);
}
memset(&counters, 0, sizeof(counters));
if (a->argc != 2 && a->argc != 3)
return CLI_SHOWUSAGE;
/* we obtain [exten@]context? if yes, split them ... */
if (a->argc == 3) {
if (strchr(a->argv[2], '@')) { /* split into exten & context */
context = ast_strdupa(a->argv[2]);
exten = strsep(&context, "@");
/* change empty strings to NULL */
if (ast_strlen_zero(exten))
exten = NULL;
} else { /* no '@' char, only context given */
context = ast_strdupa(a->argv[2]);
}
if (ast_strlen_zero(context))
context = NULL;
}
/* else Show complete dial plan, context and exten are NULL */
show_dialplan_helper(a->fd, context, exten, &counters, NULL, 0, incstack);
/* check for input failure and throw some error messages */
if (context && !counters.context_existence) {
ast_cli(a->fd, "There is no existence of '%s' context\n", context);
return CLI_FAILURE;
}
if (exten && !counters.extension_existence) {
if (context)
ast_cli(a->fd, "There is no existence of %s@%s extension\n",
exten, context);
else
ast_cli(a->fd,
"There is no existence of '%s' extension in all contexts\n",
exten);
return CLI_FAILURE;
}
ast_cli(a->fd,"-= %d %s (%d %s) in %d %s. =-\n",
counters.total_exten, counters.total_exten == 1 ? "extension" : "extensions",
counters.total_prio, counters.total_prio == 1 ? "priority" : "priorities",
counters.total_context, counters.total_context == 1 ? "context" : "contexts");
/* everything ok */
return CLI_SUCCESS;
}
/*! \brief Send ack once */
static char *handle_debug_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
char *exten = NULL, *context = NULL;
/* Variables used for different counters */
struct dialplan_counters counters;
const char *incstack[AST_PBX_MAX_STACK];
switch (cmd) {
case CLI_INIT:
e->command = "dialplan debug";
e->usage =
"Usage: dialplan debug [context]\n"
" Show dialplan context Trie(s). Usually only useful to folks debugging the deep internals of the fast pattern matcher\n";
return NULL;
case CLI_GENERATE:
return complete_show_dialplan_context(a->line, a->word, a->pos, a->n);
}
memset(&counters, 0, sizeof(counters));
if (a->argc != 2 && a->argc != 3)
return CLI_SHOWUSAGE;
/* we obtain [exten@]context? if yes, split them ... */
/* note: we ignore the exten totally here .... */
if (a->argc == 3) {
if (strchr(a->argv[2], '@')) { /* split into exten & context */
context = ast_strdupa(a->argv[2]);
exten = strsep(&context, "@");
/* change empty strings to NULL */
if (ast_strlen_zero(exten))
exten = NULL;
} else { /* no '@' char, only context given */
context = ast_strdupa(a->argv[2]);
}
if (ast_strlen_zero(context))
context = NULL;
}
/* else Show complete dial plan, context and exten are NULL */
show_debug_helper(a->fd, context, exten, &counters, NULL, 0, incstack);
/* check for input failure and throw some error messages */
if (context && !counters.context_existence) {
ast_cli(a->fd, "There is no existence of '%s' context\n", context);
return CLI_FAILURE;
}
ast_cli(a->fd,"-= %d %s. =-\n",
counters.total_context, counters.total_context == 1 ? "context" : "contexts");
/* everything ok */
return CLI_SUCCESS;
}
/*! \brief Send ack once */
static void manager_dpsendack(struct mansession *s, const struct message *m)
{
astman_send_listack(s, m, "DialPlan list will follow", "start");
}
/*! \brief Show dialplan extensions
* XXX this function is similar but not exactly the same as the CLI's
* show dialplan. Must check whether the difference is intentional or not.
*/
static int manager_show_dialplan_helper(struct mansession *s, const struct message *m,
const char *actionidtext, const char *context,
const char *exten, struct dialplan_counters *dpc,
struct ast_include *rinclude)
{
struct ast_context *c;
int res = 0, old_total_exten = dpc->total_exten;
if (ast_strlen_zero(exten))
exten = NULL;
if (ast_strlen_zero(context))
context = NULL;
ast_debug(3, "manager_show_dialplan: Context: -%s- Extension: -%s-\n", context, exten);
/* try to lock contexts */
if (ast_rdlock_contexts()) {
astman_send_error(s, m, "Failed to lock contexts");
ast_log(LOG_WARNING, "Failed to lock contexts list for manager: listdialplan\n");
return -1;
}
c = NULL; /* walk all contexts ... */
while ( (c = ast_walk_contexts(c)) ) {
struct ast_exten *e;
struct ast_include *i;
struct ast_ignorepat *ip;
if (context && strcmp(ast_get_context_name(c), context) != 0)
continue; /* not the name we want */
dpc->context_existence = 1;
dpc->total_context++;
ast_debug(3, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c));
if (ast_rdlock_context(c)) { /* failed to lock */
ast_debug(3, "manager_show_dialplan: Failed to lock context\n");
continue;
}
/* XXX note- an empty context is not printed */
e = NULL; /* walk extensions in context */
while ( (e = ast_walk_context_extensions(c, e)) ) {
struct ast_exten *p;
/* looking for extension? is this our extension? */
if (exten && !ast_extension_match(ast_get_extension_name(e), exten)) {
/* not the one we are looking for, continue */
ast_debug(3, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e));
continue;
}
ast_debug(3, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e));
dpc->extension_existence = 1;
dpc->total_exten++;
p = NULL; /* walk next extension peers */
while ( (p = ast_walk_extension_priorities(e, p)) ) {
int prio = ast_get_extension_priority(p);
dpc->total_prio++;
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) );
/* XXX maybe make this conditional, if p != e ? */
if (ast_get_extension_label(p))
astman_append(s, "ExtensionLabel: %s\r\n", ast_get_extension_label(p));
if (prio == PRIORITY_HINT) {
astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p));
} else {
astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(p), (char *) ast_get_extension_app_data(p));
}
astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e));
}
}
i = NULL; /* walk included and write info ... */
while ( (i = ast_walk_context_includes(c, i)) ) {
if (exten) {
/* Check all includes for the requested extension */
manager_show_dialplan_helper(s, m, actionidtext, ast_get_include_name(i), exten, dpc, i);
} else {
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_include_name(i), ast_get_include_registrar(i));
astman_append(s, "\r\n");
ast_debug(3, "manager_show_dialplan: Found Included context: %s \n", ast_get_include_name(i));
}
}
ip = NULL; /* walk ignore patterns and write info ... */
while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
const char *ipname = ast_get_ignorepat_name(ip);
char ignorepat[AST_MAX_EXTENSION];
snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
if (!exten || ast_extension_match(ignorepat, exten)) {
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ipname, ast_get_ignorepat_registrar(ip));
astman_append(s, "\r\n");
}
}
if (!rinclude) {
struct ast_sw *sw = NULL;
while ( (sw = ast_walk_context_switches(c, sw)) ) {
if (!dpc->total_items++)
manager_dpsendack(s, m);
astman_append(s, "Event: ListDialplan\r\n%s", actionidtext);
astman_append(s, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_registrar(sw));
astman_append(s, "\r\n");
ast_debug(3, "manager_show_dialplan: Found Switch : %s \n", ast_get_switch_name(sw));
}
}
ast_unlock_context(c);
}
ast_unlock_contexts();
if (dpc->total_exten == old_total_exten) {
ast_debug(3, "manager_show_dialplan: Found nothing new\n");
/* Nothing new under the sun */
return -1;
} else {
return res;
}
}
/*! \brief Manager listing of dial plan */
static int manager_show_dialplan(struct mansession *s, const struct message *m)
{
const char *exten, *context;
const char *id = astman_get_header(m, "ActionID");
char idtext[256];
/* Variables used for different counters */
struct dialplan_counters counters;
if (!ast_strlen_zero(id))
snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
else
idtext[0] = '\0';
memset(&counters, 0, sizeof(counters));
exten = astman_get_header(m, "Extension");
context = astman_get_header(m, "Context");
manager_show_dialplan_helper(s, m, idtext, context, exten, &counters, NULL);
if (!ast_strlen_zero(context) && !counters.context_existence) {
char errorbuf[BUFSIZ];
snprintf(errorbuf, sizeof(errorbuf), "Did not find context %s", context);
astman_send_error(s, m, errorbuf);
return 0;
}
if (!ast_strlen_zero(exten) && !counters.extension_existence) {
char errorbuf[BUFSIZ];
if (!ast_strlen_zero(context))
snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s@%s", exten, context);
else
snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s in any context", exten);
astman_send_error(s, m, errorbuf);
return 0;
}
if (!counters.total_items) {
manager_dpsendack(s, m);
}
astman_append(s, "Event: ShowDialPlanComplete\r\n"
"EventList: Complete\r\n"
"ListItems: %d\r\n"
"ListExtensions: %d\r\n"
"ListPriorities: %d\r\n"
"ListContexts: %d\r\n"
"%s"
"\r\n", counters.total_items, counters.total_exten, counters.total_prio, counters.total_context, idtext);
/* everything ok */
return 0;
}
/*! \brief CLI support for listing global variables in a parseable way */
static char *handle_show_globals(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int i = 0;
struct ast_var_t *newvariable;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan show globals";
e->usage =
"Usage: dialplan show globals\n"
" List current global dialplan variables and their values\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
ast_rwlock_rdlock(&globalslock);
AST_LIST_TRAVERSE (&globals, newvariable, entries) {
i++;
ast_cli(a->fd, " %s=%s\n", ast_var_name(newvariable), ast_var_value(newvariable));
}
ast_rwlock_unlock(&globalslock);
ast_cli(a->fd, "\n -- %d variable(s)\n", i);
return CLI_SUCCESS;
}
#ifdef AST_DEVMODE
static char *handle_show_device2extenstate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_devstate_aggregate agg;
int i, j, exten, combined;
switch (cmd) {
case CLI_INIT:
e->command = "core show device2extenstate";
e->usage =
"Usage: core show device2extenstate\n"
" Lists device state to extension state combinations.\n";
case CLI_GENERATE:
return NULL;
}
for (i = 0; i < AST_DEVICE_TOTAL; i++) {
for (j = 0; j < AST_DEVICE_TOTAL; j++) {
ast_devstate_aggregate_init(&agg);
ast_devstate_aggregate_add(&agg, i);
ast_devstate_aggregate_add(&agg, j);
combined = ast_devstate_aggregate_result(&agg);
exten = ast_devstate_to_extenstate(combined);
ast_cli(a->fd, "\n Exten:%14s CombinedDevice:%12s Dev1:%12s Dev2:%12s", ast_extension_state2str(exten), ast_devstate_str(combined), ast_devstate_str(j), ast_devstate_str(i));
}
}
ast_cli(a->fd, "\n");
return CLI_SUCCESS;
}
#endif
/*! \brief CLI support for listing chanvar's variables in a parseable way */
static char *handle_show_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_channel *chan = NULL;
struct ast_str *vars = ast_str_alloca(BUFSIZ * 4); /* XXX large because we might have lots of channel vars */
switch (cmd) {
case CLI_INIT:
e->command = "dialplan show chanvar";
e->usage =
"Usage: dialplan show chanvar <channel>\n"
" List current channel variables and their values\n";
return NULL;
case CLI_GENERATE:
return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
}
if (a->argc != e->args + 1)
return CLI_SHOWUSAGE;
if (!(chan = ast_channel_get_by_name(a->argv[e->args]))) {
ast_cli(a->fd, "Channel '%s' not found\n", a->argv[e->args]);
return CLI_FAILURE;
}
pbx_builtin_serialize_variables(chan, &vars);
if (ast_str_strlen(vars)) {
ast_cli(a->fd, "\nVariables for channel %s:\n%s\n", a->argv[e->args], ast_str_buffer(vars));
}
chan = ast_channel_unref(chan);
return CLI_SUCCESS;
}
static char *handle_set_global(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set global";
e->usage =
"Usage: dialplan set global <name> <value>\n"
" Set global dialplan variable <name> to <value>\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != e->args + 2)
return CLI_SHOWUSAGE;
pbx_builtin_setvar_helper(NULL, a->argv[3], a->argv[4]);
ast_cli(a->fd, "\n -- Global variable '%s' set to '%s'\n", a->argv[3], a->argv[4]);
return CLI_SUCCESS;
}
static char *handle_set_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct ast_channel *chan;
const char *chan_name, *var_name, *var_value;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set chanvar";
e->usage =
"Usage: dialplan set chanvar <channel> <varname> <value>\n"
" Set channel variable <varname> to <value>\n";
return NULL;
case CLI_GENERATE:
return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
}
if (a->argc != e->args + 3)
return CLI_SHOWUSAGE;
chan_name = a->argv[e->args];
var_name = a->argv[e->args + 1];
var_value = a->argv[e->args + 2];
if (!(chan = ast_channel_get_by_name(chan_name))) {
ast_cli(a->fd, "Channel '%s' not found\n", chan_name);
return CLI_FAILURE;
}
pbx_builtin_setvar_helper(chan, var_name, var_value);
chan = ast_channel_unref(chan);
ast_cli(a->fd, "\n -- Channel variable '%s' set to '%s' for '%s'\n", var_name, var_value, chan_name);
return CLI_SUCCESS;
}
static char *handle_set_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int oldval = 0;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set extenpatternmatchnew true";
e->usage =
"Usage: dialplan set extenpatternmatchnew true|false\n"
" Use the NEW extension pattern matching algorithm, true or false.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 4)
return CLI_SHOWUSAGE;
oldval = pbx_set_extenpatternmatchnew(1);
if (oldval)
ast_cli(a->fd, "\n -- Still using the NEW pattern match algorithm for extension names in the dialplan.\n");
else
ast_cli(a->fd, "\n -- Switched to using the NEW pattern match algorithm for extension names in the dialplan.\n");
return CLI_SUCCESS;
}
static char *handle_unset_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int oldval = 0;
switch (cmd) {
case CLI_INIT:
e->command = "dialplan set extenpatternmatchnew false";
e->usage =
"Usage: dialplan set extenpatternmatchnew true|false\n"
" Use the NEW extension pattern matching algorithm, true or false.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc != 4)
return CLI_SHOWUSAGE;
oldval = pbx_set_extenpatternmatchnew(0);
if (!oldval)
ast_cli(a->fd, "\n -- Still using the OLD pattern match algorithm for extension names in the dialplan.\n");
else
ast_cli(a->fd, "\n -- Switched to using the OLD pattern match algorithm for extension names in the dialplan.\n");
return CLI_SUCCESS;
}
/*
* CLI entries for upper commands ...
*/
static struct ast_cli_entry pbx_cli[] = {
AST_CLI_DEFINE(handle_show_applications, "Shows registered dialplan applications"),
AST_CLI_DEFINE(handle_show_functions, "Shows registered dialplan functions"),
AST_CLI_DEFINE(handle_show_switches, "Show alternative switches"),
AST_CLI_DEFINE(handle_show_hints, "Show dialplan hints"),
AST_CLI_DEFINE(handle_show_hint, "Show dialplan hint"),
AST_CLI_DEFINE(handle_show_globals, "Show global dialplan variables"),
#ifdef AST_DEVMODE
AST_CLI_DEFINE(handle_show_device2extenstate, "Show expected exten state from multiple device states"),
#endif
AST_CLI_DEFINE(handle_show_chanvar, "Show channel variables"),
AST_CLI_DEFINE(handle_show_function, "Describe a specific dialplan function"),
AST_CLI_DEFINE(handle_show_application, "Describe a specific dialplan application"),
AST_CLI_DEFINE(handle_set_global, "Set global dialplan variable"),
AST_CLI_DEFINE(handle_set_chanvar, "Set a channel variable"),
AST_CLI_DEFINE(handle_show_dialplan, "Show dialplan"),
AST_CLI_DEFINE(handle_debug_dialplan, "Show fast extension pattern matching data structures"),
AST_CLI_DEFINE(handle_unset_extenpatternmatchnew, "Use the Old extension pattern matching algorithm."),
AST_CLI_DEFINE(handle_set_extenpatternmatchnew, "Use the New extension pattern matching algorithm."),
};
static void unreference_cached_app(struct ast_app *app)
{
struct ast_context *context = NULL;
struct ast_exten *eroot = NULL, *e = NULL;
ast_rdlock_contexts();
while ((context = ast_walk_contexts(context))) {
while ((eroot = ast_walk_context_extensions(context, eroot))) {
while ((e = ast_walk_extension_priorities(eroot, e))) {
if (e->cached_app == app)
e->cached_app = NULL;
}
}
}
ast_unlock_contexts();
return;
}
int ast_unregister_application(const char *app)
{
struct ast_app *tmp;
AST_RWLIST_WRLOCK(&apps);
AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, tmp, list) {
if (!strcasecmp(app, tmp->name)) {
unreference_cached_app(tmp);
AST_RWLIST_REMOVE_CURRENT(list);
ast_verb(2, "Unregistered application '%s'\n", tmp->name);
ast_string_field_free_memory(tmp);
ast_free(tmp);
break;
}
}
AST_RWLIST_TRAVERSE_SAFE_END;
AST_RWLIST_UNLOCK(&apps);
return tmp ? 0 : -1;
}
struct ast_context *ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
{
struct ast_context *tmp, **local_contexts;
struct fake_context search;
int length = sizeof(struct ast_context) + strlen(name) + 1;
if (!contexts_table) {
/* Protect creation of contexts_table from reentrancy. */
ast_wrlock_contexts();
if (!contexts_table) {
contexts_table = ast_hashtab_create(17,
ast_hashtab_compare_contexts,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
ast_hashtab_hash_contexts,
0);
}
ast_unlock_contexts();
}
ast_copy_string(search.name, name, sizeof(search.name));
if (!extcontexts) {
ast_rdlock_contexts();
local_contexts = &contexts;
tmp = ast_hashtab_lookup(contexts_table, &search);
ast_unlock_contexts();
if (tmp) {
tmp->refcount++;
return tmp;
}
} else { /* local contexts just in a linked list; search there for the new context; slow, linear search, but not frequent */
local_contexts = extcontexts;
tmp = ast_hashtab_lookup(exttable, &search);
if (tmp) {
tmp->refcount++;
return tmp;
}
}
if ((tmp = ast_calloc(1, length))) {
ast_rwlock_init(&tmp->lock);
ast_mutex_init(&tmp->macrolock);
strcpy(tmp->name, name);
tmp->root = NULL;
tmp->root_table = NULL;
tmp->registrar = ast_strdup(registrar);
tmp->includes = NULL;
tmp->ignorepats = NULL;
tmp->refcount = 1;
} else {
ast_log(LOG_ERROR, "Danger! We failed to allocate a context for %s!\n", name);
return NULL;
}
if (!extcontexts) {
ast_wrlock_contexts();
tmp->next = *local_contexts;
*local_contexts = tmp;
ast_hashtab_insert_safe(contexts_table, tmp); /*put this context into the tree */
ast_unlock_contexts();
ast_debug(1, "Registered context '%s'(%p) in table %p registrar: %s\n", tmp->name, tmp, contexts_table, registrar);
ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar);
} else {
tmp->next = *local_contexts;
if (exttable)
ast_hashtab_insert_immediate(exttable, tmp); /*put this context into the tree */
*local_contexts = tmp;
ast_debug(1, "Registered context '%s'(%p) in local table %p; registrar: %s\n", tmp->name, tmp, exttable, registrar);
ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar);
}
return tmp;
}
void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar);
struct store_hint {
char *context;
char *exten;
AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks;
int laststate;
AST_LIST_ENTRY(store_hint) list;
char data[1];
};
AST_LIST_HEAD_NOLOCK(store_hints, store_hint);
static void context_merge_incls_swits_igps_other_registrars(struct ast_context *new, struct ast_context *old, const char *registrar)
{
struct ast_include *i;
struct ast_ignorepat *ip;
struct ast_sw *sw;
ast_verb(3, "merging incls/swits/igpats from old(%s) to new(%s) context, registrar = %s\n", ast_get_context_name(old), ast_get_context_name(new), registrar);
/* copy in the includes, switches, and ignorepats */
/* walk through includes */
for (i = NULL; (i = ast_walk_context_includes(old, i)) ; ) {
if (strcmp(ast_get_include_registrar(i), registrar) == 0)
continue; /* not mine */
ast_context_add_include2(new, ast_get_include_name(i), ast_get_include_registrar(i));
}
/* walk through switches */
for (sw = NULL; (sw = ast_walk_context_switches(old, sw)) ; ) {
if (strcmp(ast_get_switch_registrar(sw), registrar) == 0)
continue; /* not mine */
ast_context_add_switch2(new, ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_eval(sw), ast_get_switch_registrar(sw));
}
/* walk thru ignorepats ... */
for (ip = NULL; (ip = ast_walk_context_ignorepats(old, ip)); ) {
if (strcmp(ast_get_ignorepat_registrar(ip), registrar) == 0)
continue; /* not mine */
ast_context_add_ignorepat2(new, ast_get_ignorepat_name(ip), ast_get_ignorepat_registrar(ip));
}
}
/* the purpose of this routine is to duplicate a context, with all its substructure,
except for any extens that have a matching registrar */
static void context_merge(struct ast_context **extcontexts, struct ast_hashtab *exttable, struct ast_context *context, const char *registrar)
{
struct ast_context *new = ast_hashtab_lookup(exttable, context); /* is there a match in the new set? */
struct ast_exten *exten_item, *prio_item, *new_exten_item, *new_prio_item;
struct ast_hashtab_iter *exten_iter;
struct ast_hashtab_iter *prio_iter;
int insert_count = 0;
int first = 1;
/* We'll traverse all the extensions/prios, and see which are not registrar'd with
the current registrar, and copy them to the new context. If the new context does not
exist, we'll create it "on demand". If no items are in this context to copy, then we'll
only create the empty matching context if the old one meets the criteria */
if (context->root_table) {
exten_iter = ast_hashtab_start_traversal(context->root_table);
while ((exten_item=ast_hashtab_next(exten_iter))) {
if (new) {
new_exten_item = ast_hashtab_lookup(new->root_table, exten_item);
} else {
new_exten_item = NULL;
}
prio_iter = ast_hashtab_start_traversal(exten_item->peer_table);
while ((prio_item=ast_hashtab_next(prio_iter))) {
int res1;
char *dupdstr;
if (new_exten_item) {
new_prio_item = ast_hashtab_lookup(new_exten_item->peer_table, prio_item);
} else {
new_prio_item = NULL;
}
if (strcmp(prio_item->registrar,registrar) == 0) {
continue;
}
/* make sure the new context exists, so we have somewhere to stick this exten/prio */
if (!new) {
new = ast_context_find_or_create(extcontexts, exttable, context->name, prio_item->registrar); /* a new context created via priority from a different context in the old dialplan, gets its registrar from the prio's registrar */
}
/* copy in the includes, switches, and ignorepats */
if (first) { /* but, only need to do this once */
context_merge_incls_swits_igps_other_registrars(new, context, registrar);
first = 0;
}
if (!new) {
ast_log(LOG_ERROR,"Could not allocate a new context for %s in merge_and_delete! Danger!\n", context->name);
ast_hashtab_end_traversal(prio_iter);
ast_hashtab_end_traversal(exten_iter);
return; /* no sense continuing. */
}
/* we will not replace existing entries in the new context with stuff from the old context.
but, if this is because of some sort of registrar conflict, we ought to say something... */
dupdstr = ast_strdup(prio_item->data);
res1 = ast_add_extension2(new, 0, prio_item->exten, prio_item->priority, prio_item->label,
prio_item->matchcid ? prio_item->cidmatch : NULL, prio_item->app, dupdstr, prio_item->datad, prio_item->registrar);
if (!res1 && new_exten_item && new_prio_item){
ast_verb(3,"Dropping old dialplan item %s/%s/%d [%s(%s)] (registrar=%s) due to conflict with new dialplan\n",
context->name, prio_item->exten, prio_item->priority, prio_item->app, (char*)prio_item->data, prio_item->registrar);
} else {
/* we do NOT pass the priority data from the old to the new -- we pass a copy of it, so no changes to the current dialplan take place,
and no double frees take place, either! */
insert_count++;
}
}
ast_hashtab_end_traversal(prio_iter);
}
ast_hashtab_end_traversal(exten_iter);
}
if (!insert_count && !new && (strcmp(context->registrar, registrar) != 0 ||
(strcmp(context->registrar, registrar) == 0 && context->refcount > 1))) {
/* we could have given it the registrar of the other module who incremented the refcount,
but that's not available, so we give it the registrar we know about */
new = ast_context_find_or_create(extcontexts, exttable, context->name, context->registrar);
/* copy in the includes, switches, and ignorepats */
context_merge_incls_swits_igps_other_registrars(new, context, registrar);
}
}
/* XXX this does not check that multiple contexts are merged */
void ast_merge_contexts_and_delete(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *registrar)
{
double ft;
struct ast_context *tmp;
struct ast_context *oldcontextslist;
struct ast_hashtab *oldtable;
struct store_hints hints_stored = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
struct store_hints hints_removed = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
struct store_hint *saved_hint;
struct ast_hint *hint;
struct ast_exten *exten;
int length;
struct ast_state_cb *thiscb;
struct ast_hashtab_iter *iter;
struct ao2_iterator i;
struct timeval begintime;
struct timeval writelocktime;
struct timeval endlocktime;
struct timeval enddeltime;
/*
* It is very important that this function hold the hints
* container lock _and_ the conlock during its operation; not
* only do we need to ensure that the list of contexts and
* extensions does not change, but also that no hint callbacks
* (watchers) are added or removed during the merge/delete
* process
*
* In addition, the locks _must_ be taken in this order, because
* there are already other code paths that use this order
*/
begintime = ast_tvnow();
ast_mutex_lock(&context_merge_lock);/* Serialize ast_merge_contexts_and_delete */
ast_wrlock_contexts();
iter = ast_hashtab_start_traversal(contexts_table);
while ((tmp = ast_hashtab_next(iter))) {
context_merge(extcontexts, exttable, tmp, registrar);
}
ast_hashtab_end_traversal(iter);
ao2_lock(hints);
writelocktime = ast_tvnow();
/* preserve all watchers for hints */
i = ao2_iterator_init(hints, AO2_ITERATOR_DONTLOCK);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
if (ao2_container_count(hint->callbacks)) {
ao2_lock(hint);
if (!hint->exten) {
/* The extension has already been destroyed. (Should never happen here) */
ao2_unlock(hint);
continue;
}
length = strlen(hint->exten->exten) + strlen(hint->exten->parent->name) + 2
+ sizeof(*saved_hint);
if (!(saved_hint = ast_calloc(1, length))) {
ao2_unlock(hint);
continue;
}
/* This removes all the callbacks from the hint into saved_hint. */
while ((thiscb = ao2_callback(hint->callbacks, OBJ_UNLINK, NULL, NULL))) {
AST_LIST_INSERT_TAIL(&saved_hint->callbacks, thiscb, entry);
/*
* We intentionally do not unref thiscb to account for the
* non-ao2 reference in saved_hint->callbacks
*/
}
saved_hint->laststate = hint->laststate;
saved_hint->context = saved_hint->data;
strcpy(saved_hint->data, hint->exten->parent->name);
saved_hint->exten = saved_hint->data + strlen(saved_hint->context) + 1;
strcpy(saved_hint->exten, hint->exten->exten);
ao2_unlock(hint);
AST_LIST_INSERT_HEAD(&hints_stored, saved_hint, list);
}
}
ao2_iterator_destroy(&i);
/* save the old table and list */
oldtable = contexts_table;
oldcontextslist = contexts;
/* move in the new table and list */
contexts_table = exttable;
contexts = *extcontexts;
/*
* Restore the watchers for hints that can be found; notify
* those that cannot be restored.
*/
while ((saved_hint = AST_LIST_REMOVE_HEAD(&hints_stored, list))) {
struct pbx_find_info q = { .stacklen = 0 };
exten = pbx_find_extension(NULL, NULL, &q, saved_hint->context, saved_hint->exten,
PRIORITY_HINT, NULL, "", E_MATCH);
/*
* If this is a pattern, dynamically create a new extension for this
* particular match. Note that this will only happen once for each
* individual extension, because the pattern will no longer match first.
*/
if (exten && exten->exten[0] == '_') {
ast_add_extension_nolock(exten->parent->name, 0, saved_hint->exten,
PRIORITY_HINT, NULL, 0, exten->app, ast_strdup(exten->data), ast_free_ptr,
exten->registrar);
/* rwlocks are not recursive locks */
exten = ast_hint_extension_nolock(NULL, saved_hint->context,
saved_hint->exten);
}
/* Find the hint in the hints container */
hint = exten ? ao2_find(hints, exten, 0) : NULL;
if (!hint) {
/*
* Notify watchers of this removed hint later when we aren't
* encumberd by so many locks.
*/
AST_LIST_INSERT_HEAD(&hints_removed, saved_hint, list);
} else {
ao2_lock(hint);
while ((thiscb = AST_LIST_REMOVE_HEAD(&saved_hint->callbacks, entry))) {
ao2_link(hint->callbacks, thiscb);
/* Ref that we added when putting into saved_hint->callbacks */
ao2_ref(thiscb, -1);
}
hint->laststate = saved_hint->laststate;
ao2_unlock(hint);
ao2_ref(hint, -1);
ast_free(saved_hint);
}
}
ao2_unlock(hints);
ast_unlock_contexts();
/*
* Notify watchers of all removed hints with the same lock
* environment as handle_statechange().
*/
while ((saved_hint = AST_LIST_REMOVE_HEAD(&hints_removed, list))) {
/* this hint has been removed, notify the watchers */
while ((thiscb = AST_LIST_REMOVE_HEAD(&saved_hint->callbacks, entry))) {
thiscb->change_cb(saved_hint->context, saved_hint->exten,
AST_EXTENSION_REMOVED, thiscb->data);
/* Ref that we added when putting into saved_hint->callbacks */
ao2_ref(thiscb, -1);
}
ast_free(saved_hint);
}
ast_mutex_unlock(&context_merge_lock);
endlocktime = ast_tvnow();
/*
* The old list and hashtab no longer are relevant, delete them
* while the rest of asterisk is now freely using the new stuff
* instead.
*/
ast_hashtab_destroy(oldtable, NULL);
for (tmp = oldcontextslist; tmp; ) {
struct ast_context *next; /* next starting point */
next = tmp->next;
__ast_internal_context_destroy(tmp);
tmp = next;
}
enddeltime = ast_tvnow();
ft = ast_tvdiff_us(writelocktime, begintime);
ft /= 1000000.0;
ast_verb(3,"Time to scan old dialplan and merge leftovers back into the new: %8.6f sec\n", ft);
ft = ast_tvdiff_us(endlocktime, writelocktime);
ft /= 1000000.0;
ast_verb(3,"Time to restore hints and swap in new dialplan: %8.6f sec\n", ft);
ft = ast_tvdiff_us(enddeltime, endlocktime);
ft /= 1000000.0;
ast_verb(3,"Time to delete the old dialplan: %8.6f sec\n", ft);
ft = ast_tvdiff_us(enddeltime, begintime);
ft /= 1000000.0;
ast_verb(3,"Total time merge_contexts_delete: %8.6f sec\n", ft);
}
/*
* errno values
* EBUSY - can't lock
* ENOENT - no existence of context
*/
int ast_context_add_include(const char *context, const char *include, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_context_add_include2(c, include, registrar);
ast_unlock_contexts();
}
return ret;
}
/*! \brief Helper for get_range.
* return the index of the matching entry, starting from 1.
* If names is not supplied, try numeric values.
*/
static int lookup_name(const char *s, const char * const names[], int max)
{
int i;
if (names && *s > '9') {
for (i = 0; names[i]; i++) {
if (!strcasecmp(s, names[i])) {
return i;
}
}
}
/* Allow months and weekdays to be specified as numbers, as well */
if (sscanf(s, "%2d", &i) == 1 && i >= 1 && i <= max) {
/* What the array offset would have been: "1" would be at offset 0 */
return i - 1;
}
return -1; /* error return */
}
/*! \brief helper function to return a range up to max (7, 12, 31 respectively).
* names, if supplied, is an array of names that should be mapped to numbers.
*/
static unsigned get_range(char *src, int max, const char * const names[], const char *msg)
{
int start, end; /* start and ending position */
unsigned int mask = 0;
char *part;
/* Check for whole range */
if (ast_strlen_zero(src) || !strcmp(src, "*")) {
return (1 << max) - 1;
}
while ((part = strsep(&src, "&"))) {
/* Get start and ending position */
char *endpart = strchr(part, '-');
if (endpart) {
*endpart++ = '\0';
}
/* Find the start */
if ((start = lookup_name(part, names, max)) < 0) {
ast_log(LOG_WARNING, "Invalid %s '%s', skipping element\n", msg, part);
continue;
}
if (endpart) { /* find end of range */
if ((end = lookup_name(endpart, names, max)) < 0) {
ast_log(LOG_WARNING, "Invalid end %s '%s', skipping element\n", msg, endpart);
continue;
}
} else {
end = start;
}
/* Fill the mask. Remember that ranges are cyclic */
mask |= (1 << end); /* initialize with last element */
while (start != end) {
mask |= (1 << start);
if (++start >= max) {
start = 0;
}
}
}
return mask;
}
/*! \brief store a bitmask of valid times, one bit each 1 minute */
static void get_timerange(struct ast_timing *i, char *times)
{
char *endpart, *part;
int x;
int st_h, st_m;
int endh, endm;
int minute_start, minute_end;
/* start disabling all times, fill the fields with 0's, as they may contain garbage */
memset(i->minmask, 0, sizeof(i->minmask));
/* 1-minute per bit */
/* Star is all times */
if (ast_strlen_zero(times) || !strcmp(times, "*")) {
/* 48, because each hour takes 2 integers; 30 bits each */
for (x = 0; x < 48; x++) {
i->minmask[x] = 0x3fffffff; /* 30 bits */
}
return;
}
/* Otherwise expect a range */
while ((part = strsep(×, "&"))) {
if (!(endpart = strchr(part, '-'))) {
if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) {
ast_log(LOG_WARNING, "%s isn't a valid time.\n", part);
continue;
}
i->minmask[st_h * 2 + (st_m >= 30 ? 1 : 0)] |= (1 << (st_m % 30));
continue;
}
*endpart++ = '\0';
/* why skip non digits? Mostly to skip spaces */
while (*endpart && !isdigit(*endpart)) {
endpart++;
}
if (!*endpart) {
ast_log(LOG_WARNING, "Invalid time range starting with '%s-'.\n", part);
continue;
}
if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) {
ast_log(LOG_WARNING, "'%s' isn't a valid start time.\n", part);
continue;
}
if (sscanf(endpart, "%2d:%2d", &endh, &endm) != 2 || endh < 0 || endh > 23 || endm < 0 || endm > 59) {
ast_log(LOG_WARNING, "'%s' isn't a valid end time.\n", endpart);
continue;
}
minute_start = st_h * 60 + st_m;
minute_end = endh * 60 + endm;
/* Go through the time and enable each appropriate bit */
for (x = minute_start; x != minute_end; x = (x + 1) % (24 * 60)) {
i->minmask[x / 30] |= (1 << (x % 30));
}
/* Do the last one */
i->minmask[x / 30] |= (1 << (x % 30));
}
/* All done */
return;
}
static const char * const days[] =
{
"sun",
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
NULL,
};
static const char * const months[] =
{
"jan",
"feb",
"mar",
"apr",
"may",
"jun",
"jul",
"aug",
"sep",
"oct",
"nov",
"dec",
NULL,
};
int ast_build_timing(struct ast_timing *i, const char *info_in)
{
char *info;
int j, num_fields, last_sep = -1;
/* Check for empty just in case */
if (ast_strlen_zero(info_in)) {
return 0;
}
/* make a copy just in case we were passed a static string */
info = ast_strdupa(info_in);
/* count the number of fields in the timespec */
for (j = 0, num_fields = 1; info[j] != '\0'; j++) {
if (info[j] == ',') {
last_sep = j;
num_fields++;
}
}
/* save the timezone, if it is specified */
if (num_fields == 5) {
i->timezone = ast_strdup(info + last_sep + 1);
} else {
i->timezone = NULL;
}
/* Assume everything except time */
i->monthmask = 0xfff; /* 12 bits */
i->daymask = 0x7fffffffU; /* 31 bits */
i->dowmask = 0x7f; /* 7 bits */
/* on each call, use strsep() to move info to the next argument */
get_timerange(i, strsep(&info, "|,"));
if (info)
i->dowmask = get_range(strsep(&info, "|,"), 7, days, "day of week");
if (info)
i->daymask = get_range(strsep(&info, "|,"), 31, NULL, "day");
if (info)
i->monthmask = get_range(strsep(&info, "|,"), 12, months, "month");
return 1;
}
int ast_check_timing(const struct ast_timing *i)
{
return ast_check_timing2(i, ast_tvnow());
}
int ast_check_timing2(const struct ast_timing *i, const struct timeval tv)
{
struct ast_tm tm;
ast_localtime(&tv, &tm, i->timezone);
/* If it's not the right month, return */
if (!(i->monthmask & (1 << tm.tm_mon)))
return 0;
/* If it's not that time of the month.... */
/* Warning, tm_mday has range 1..31! */
if (!(i->daymask & (1 << (tm.tm_mday-1))))
return 0;
/* If it's not the right day of the week */
if (!(i->dowmask & (1 << tm.tm_wday)))
return 0;
/* Sanity check the hour just to be safe */
if ((tm.tm_hour < 0) || (tm.tm_hour > 23)) {
ast_log(LOG_WARNING, "Insane time...\n");
return 0;
}
/* Now the tough part, we calculate if it fits
in the right time based on min/hour */
if (!(i->minmask[tm.tm_hour * 2 + (tm.tm_min >= 30 ? 1 : 0)] & (1 << (tm.tm_min >= 30 ? tm.tm_min - 30 : tm.tm_min))))
return 0;
/* If we got this far, then we're good */
return 1;
}
int ast_destroy_timing(struct ast_timing *i)
{
if (i->timezone) {
ast_free(i->timezone);
i->timezone = NULL;
}
return 0;
}
/*
* errno values
* ENOMEM - out of memory
* EBUSY - can't lock
* EEXIST - already included
* EINVAL - there is no existence of context for inclusion
*/
int ast_context_add_include2(struct ast_context *con, const char *value,
const char *registrar)
{
struct ast_include *new_include;
char *c;
struct ast_include *i, *il = NULL; /* include, include_last */
int length;
char *p;
length = sizeof(struct ast_include);
length += 2 * (strlen(value) + 1);
/* allocate new include structure ... */
if (!(new_include = ast_calloc(1, length)))
return -1;
/* Fill in this structure. Use 'p' for assignments, as the fields
* in the structure are 'const char *'
*/
p = new_include->stuff;
new_include->name = p;
strcpy(p, value);
p += strlen(value) + 1;
new_include->rname = p;
strcpy(p, value);
/* Strip off timing info, and process if it is there */
if ( (c = strchr(p, ',')) ) {
*c++ = '\0';
new_include->hastime = ast_build_timing(&(new_include->timing), c);
}
new_include->next = NULL;
new_include->registrar = registrar;
ast_wrlock_context(con);
/* ... go to last include and check if context is already included too... */
for (i = con->includes; i; i = i->next) {
if (!strcasecmp(i->name, new_include->name)) {
ast_destroy_timing(&(new_include->timing));
ast_free(new_include);
ast_unlock_context(con);
errno = EEXIST;
return -1;
}
il = i;
}
/* ... include new context into context list, unlock, return */
if (il)
il->next = new_include;
else
con->includes = new_include;
ast_verb(3, "Including context '%s' in context '%s'\n", new_include->name, ast_get_context_name(con));
ast_unlock_context(con);
return 0;
}
/*
* errno values
* EBUSY - can't lock
* ENOENT - no existence of context
*/
int ast_context_add_switch(const char *context, const char *sw, const char *data, int eval, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) { /* found, add switch to this context */
ret = ast_context_add_switch2(c, sw, data, eval, registrar);
ast_unlock_contexts();
}
return ret;
}
/*
* errno values
* ENOMEM - out of memory
* EBUSY - can't lock
* EEXIST - already included
* EINVAL - there is no existence of context for inclusion
*/
int ast_context_add_switch2(struct ast_context *con, const char *value,
const char *data, int eval, const char *registrar)
{
struct ast_sw *new_sw;
struct ast_sw *i;
int length;
char *p;
length = sizeof(struct ast_sw);
length += strlen(value) + 1;
if (data)
length += strlen(data);
length++;
/* allocate new sw structure ... */
if (!(new_sw = ast_calloc(1, length)))
return -1;
/* ... fill in this structure ... */
p = new_sw->stuff;
new_sw->name = p;
strcpy(new_sw->name, value);
p += strlen(value) + 1;
new_sw->data = p;
if (data) {
strcpy(new_sw->data, data);
p += strlen(data) + 1;
} else {
strcpy(new_sw->data, "");
p++;
}
new_sw->eval = eval;
new_sw->registrar = registrar;
/* ... try to lock this context ... */
ast_wrlock_context(con);
/* ... go to last sw and check if context is already swd too... */
AST_LIST_TRAVERSE(&con->alts, i, list) {
if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) {
ast_free(new_sw);
ast_unlock_context(con);
errno = EEXIST;
return -1;
}
}
/* ... sw new context into context list, unlock, return */
AST_LIST_INSERT_TAIL(&con->alts, new_sw, list);
ast_verb(3, "Including switch '%s/%s' in context '%s'\n", new_sw->name, new_sw->data, ast_get_context_name(con));
ast_unlock_context(con);
return 0;
}
/*
* EBUSY - can't lock
* ENOENT - there is not context existence
*/
int ast_context_remove_ignorepat(const char *context, const char *ignorepat, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_context_remove_ignorepat2(c, ignorepat, registrar);
ast_unlock_contexts();
}
return ret;
}
int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat, const char *registrar)
{
struct ast_ignorepat *ip, *ipl = NULL;
ast_wrlock_context(con);
for (ip = con->ignorepats; ip; ip = ip->next) {
if (!strcmp(ip->pattern, ignorepat) &&
(!registrar || (registrar == ip->registrar))) {
if (ipl) {
ipl->next = ip->next;
ast_free(ip);
} else {
con->ignorepats = ip->next;
ast_free(ip);
}
ast_unlock_context(con);
return 0;
}
ipl = ip;
}
ast_unlock_context(con);
errno = EINVAL;
return -1;
}
/*
* EBUSY - can't lock
* ENOENT - there is no existence of context
*/
int ast_context_add_ignorepat(const char *context, const char *value, const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_context_add_ignorepat2(c, value, registrar);
ast_unlock_contexts();
}
return ret;
}
int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const char *registrar)
{
struct ast_ignorepat *ignorepat, *ignorepatc, *ignorepatl = NULL;
int length;
char *pattern;
length = sizeof(struct ast_ignorepat);
length += strlen(value) + 1;
if (!(ignorepat = ast_calloc(1, length)))
return -1;
/* The cast to char * is because we need to write the initial value.
* The field is not supposed to be modified otherwise. Also, gcc 4.2
* sees the cast as dereferencing a type-punned pointer and warns about
* it. This is the workaround (we're telling gcc, yes, that's really
* what we wanted to do).
*/
pattern = (char *) ignorepat->pattern;
strcpy(pattern, value);
ignorepat->next = NULL;
ignorepat->registrar = registrar;
ast_wrlock_context(con);
for (ignorepatc = con->ignorepats; ignorepatc; ignorepatc = ignorepatc->next) {
ignorepatl = ignorepatc;
if (!strcasecmp(ignorepatc->pattern, value)) {
/* Already there */
ast_unlock_context(con);
ast_free(ignorepat);
errno = EEXIST;
return -1;
}
}
if (ignorepatl)
ignorepatl->next = ignorepat;
else
con->ignorepats = ignorepat;
ast_unlock_context(con);
return 0;
}
int ast_ignore_pattern(const char *context, const char *pattern)
{
struct ast_context *con = ast_context_find(context);
if (con) {
struct ast_ignorepat *pat;
for (pat = con->ignorepats; pat; pat = pat->next) {
if (ast_extension_match(pat->pattern, pattern))
return 1;
}
}
return 0;
}
/*
* ast_add_extension_nolock -- use only in situations where the conlock is already held
* ENOENT - no existence of context
*
*/
static int ast_add_extension_nolock(const char *context, int replace, const char *extension,
int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *), const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context(context);
if (c) {
ret = ast_add_extension2_lockopt(c, replace, extension, priority, label, callerid,
application, data, datad, registrar, 1);
}
return ret;
}
/*
* EBUSY - can't lock
* ENOENT - no existence of context
*
*/
int ast_add_extension(const char *context, int replace, const char *extension,
int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *), const char *registrar)
{
int ret = -1;
struct ast_context *c;
c = find_context_locked(context);
if (c) {
ret = ast_add_extension2(c, replace, extension, priority, label, callerid,
application, data, datad, registrar);
ast_unlock_contexts();
}
return ret;
}
int ast_explicit_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
{
if (!chan)
return -1;
ast_channel_lock(chan);
if (!ast_strlen_zero(context))
ast_copy_string(chan->context, context, sizeof(chan->context));
if (!ast_strlen_zero(exten))
ast_copy_string(chan->exten, exten, sizeof(chan->exten));
if (priority > -1) {
chan->priority = priority;
/* see flag description in channel.h for explanation */
if (ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP))
chan->priority--;
}
ast_channel_unlock(chan);
return 0;
}
int ast_async_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
{
int res = 0;
struct ast_channel *tmpchan;
struct {
char *accountcode;
char *exten;
char *context;
char *linkedid;
char *name;
struct ast_cdr *cdr;
int amaflags;
int state;
format_t readformat;
format_t writeformat;
} tmpvars = { 0, };
ast_channel_lock(chan);
if (chan->pbx) { /* This channel is currently in the PBX */
ast_explicit_goto(chan, context, exten, priority + 1);
ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
ast_channel_unlock(chan);
return res;
}
/* In order to do it when the channel doesn't really exist within
* the PBX, we have to make a new channel, masquerade, and start the PBX
* at the new location */
tmpvars.accountcode = ast_strdupa(chan->accountcode);
tmpvars.exten = ast_strdupa(chan->exten);
tmpvars.context = ast_strdupa(chan->context);
tmpvars.linkedid = ast_strdupa(chan->linkedid);
tmpvars.name = ast_strdupa(chan->name);
tmpvars.amaflags = chan->amaflags;
tmpvars.state = chan->_state;
tmpvars.writeformat = chan->writeformat;
tmpvars.readformat = chan->readformat;
tmpvars.cdr = chan->cdr ? ast_cdr_dup(chan->cdr) : NULL;
ast_channel_unlock(chan);
/* Do not hold any channel locks while calling channel_alloc() since the function
* locks the channel container when linking the new channel in. */
if (!(tmpchan = ast_channel_alloc(0, tmpvars.state, 0, 0, tmpvars.accountcode, tmpvars.exten, tmpvars.context, tmpvars.linkedid, tmpvars.amaflags, "AsyncGoto/%s", tmpvars.name))) {
ast_cdr_discard(tmpvars.cdr);
return -1;
}
/* copy the cdr info over */
if (tmpvars.cdr) {
ast_cdr_discard(tmpchan->cdr);
tmpchan->cdr = tmpvars.cdr;
tmpvars.cdr = NULL;
}
/* Make formats okay */
tmpchan->readformat = tmpvars.readformat;
tmpchan->writeformat = tmpvars.writeformat;
/* Setup proper location. Never hold another channel lock while calling this function. */
ast_explicit_goto(tmpchan, S_OR(context, tmpvars.context), S_OR(exten, tmpvars.exten), priority);
/* Masquerade into tmp channel */
if (ast_channel_masquerade(tmpchan, chan)) {
/* Failed to set up the masquerade. It's probably chan_local
* in the middle of optimizing itself out. Sad. :( */
ast_hangup(tmpchan);
tmpchan = NULL;
res = -1;
} else {
ast_do_masquerade(tmpchan);
/* Start the PBX going on our stolen channel */
if (ast_pbx_start(tmpchan)) {
ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmpchan->name);
ast_hangup(tmpchan);
res = -1;
}
}
return res;
}
int ast_async_goto_by_name(const char *channame, const char *context, const char *exten, int priority)
{
struct ast_channel *chan;
int res = -1;
if ((chan = ast_channel_get_by_name(channame))) {
res = ast_async_goto(chan, context, exten, priority);
chan = ast_channel_unref(chan);
}
return res;
}
/*! \brief copy a string skipping whitespace */
static int ext_strncpy(char *dst, const char *src, int len)
{
int count = 0;
int insquares = 0;
while (*src && (count < len - 1)) {
if (*src == '[') {
insquares = 1;
} else if (*src == ']') {
insquares = 0;
} else if (*src == ' ' && !insquares) {
src++;
continue;
}
*dst = *src;
dst++;
src++;
count++;
}
*dst = '\0';
return count;
}
/*!
* \brief add the extension in the priority chain.
* \retval 0 on success.
* \retval -1 on failure.
*/
static int add_priority(struct ast_context *con, struct ast_exten *tmp,
struct ast_exten *el, struct ast_exten *e, int replace)
{
struct ast_exten *ep;
struct ast_exten *eh=e;
int repeated_label = 0; /* Track if this label is a repeat, assume no. */
for (ep = NULL; e ; ep = e, e = e->peer) {
if (e->label && tmp->label && e->priority != tmp->priority && !strcmp(e->label, tmp->label)) {
if (strcmp(e->exten, tmp->exten)) {
ast_log(LOG_WARNING,
"Extension '%s' priority %d in '%s', label '%s' already in use at aliased extension '%s' priority %d\n",
tmp->exten, tmp->priority, con->name, tmp->label, e->exten, e->priority);
} else {
ast_log(LOG_WARNING,
"Extension '%s' priority %d in '%s', label '%s' already in use at priority %d\n",
tmp->exten, tmp->priority, con->name, tmp->label, e->priority);
}
repeated_label = 1;
}
if (e->priority >= tmp->priority) {
break;
}
}
if (repeated_label) { /* Discard the label since it's a repeat. */
tmp->label = NULL;
}
if (!e) { /* go at the end, and ep is surely set because the list is not empty */
ast_hashtab_insert_safe(eh->peer_table, tmp);
if (tmp->label) {
ast_hashtab_insert_safe(eh->peer_label_table, tmp);
}
ep->peer = tmp;
return 0; /* success */
}
if (e->priority == tmp->priority) {
/* Can't have something exactly the same. Is this a
replacement? If so, replace, otherwise, bonk. */
if (!replace) {
if (strcmp(e->exten, tmp->exten)) {
ast_log(LOG_WARNING,
"Unable to register extension '%s' priority %d in '%s', already in use by aliased extension '%s'\n",
tmp->exten, tmp->priority, con->name, e->exten);
} else {
ast_log(LOG_WARNING,
"Unable to register extension '%s' priority %d in '%s', already in use\n",
tmp->exten, tmp->priority, con->name);
}
if (tmp->datad) {
tmp->datad(tmp->data);
/* if you free this, null it out */
tmp->data = NULL;
}
ast_free(tmp);
return -1;
}
/* we are replacing e, so copy the link fields and then update
* whoever pointed to e to point to us
*/
tmp->next = e->next; /* not meaningful if we are not first in the peer list */
tmp->peer = e->peer; /* always meaningful */
if (ep) { /* We're in the peer list, just insert ourselves */
ast_hashtab_remove_object_via_lookup(eh->peer_table,e);
if (e->label) {
ast_hashtab_remove_object_via_lookup(eh->peer_label_table,e);
}
ast_hashtab_insert_safe(eh->peer_table,tmp);
if (tmp->label) {
ast_hashtab_insert_safe(eh->peer_label_table,tmp);
}
ep->peer = tmp;
} else if (el) { /* We're the first extension. Take over e's functions */
struct match_char *x = add_exten_to_pattern_tree(con, e, 1);
tmp->peer_table = e->peer_table;
tmp->peer_label_table = e->peer_label_table;
ast_hashtab_remove_object_via_lookup(tmp->peer_table,e);
ast_hashtab_insert_safe(tmp->peer_table,tmp);
if (e->label) {
ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e);
}
if (tmp->label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
el->next = tmp;
/* The pattern trie points to this exten; replace the pointer,
and all will be well */
if (x) { /* if the trie isn't formed yet, don't sweat this */
if (x->exten) { /* this test for safety purposes */
x->exten = tmp; /* replace what would become a bad pointer */
} else {
ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
}
}
} else { /* We're the very first extension. */
struct match_char *x = add_exten_to_pattern_tree(con, e, 1);
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
tmp->peer_table = e->peer_table;
tmp->peer_label_table = e->peer_label_table;
ast_hashtab_remove_object_via_lookup(tmp->peer_table, e);
ast_hashtab_insert_safe(tmp->peer_table, tmp);
if (e->label) {
ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e);
}
if (tmp->label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
con->root = tmp;
/* The pattern trie points to this exten; replace the pointer,
and all will be well */
if (x) { /* if the trie isn't formed yet; no problem */
if (x->exten) { /* this test for safety purposes */
x->exten = tmp; /* replace what would become a bad pointer */
} else {
ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
}
}
}
if (tmp->priority == PRIORITY_HINT)
ast_change_hint(e,tmp);
/* Destroy the old one */
if (e->datad)
e->datad(e->data);
ast_free(e);
} else { /* Slip ourselves in just before e */
tmp->peer = e;
tmp->next = e->next; /* extension chain, or NULL if e is not the first extension */
if (ep) { /* Easy enough, we're just in the peer list */
if (tmp->label) {
ast_hashtab_insert_safe(eh->peer_label_table, tmp);
}
ast_hashtab_insert_safe(eh->peer_table, tmp);
ep->peer = tmp;
} else { /* we are the first in some peer list, so link in the ext list */
tmp->peer_table = e->peer_table;
tmp->peer_label_table = e->peer_label_table;
e->peer_table = 0;
e->peer_label_table = 0;
ast_hashtab_insert_safe(tmp->peer_table, tmp);
if (tmp->label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_remove_object_via_lookup(con->root_table, e);
ast_hashtab_insert_safe(con->root_table, tmp);
if (el)
el->next = tmp; /* in the middle... */
else
con->root = tmp; /* ... or at the head */
e->next = NULL; /* e is no more at the head, so e->next must be reset */
}
/* And immediately return success. */
if (tmp->priority == PRIORITY_HINT) {
ast_add_hint(tmp);
}
}
return 0;
}
/*! \brief
* Main interface to add extensions to the list for out context.
*
* We sort extensions in order of matching preference, so that we can
* stop the search as soon as we find a suitable match.
* This ordering also takes care of wildcards such as '.' (meaning
* "one or more of any character") and '!' (which is 'earlymatch',
* meaning "zero or more of any character" but also impacts the
* return value from CANMATCH and EARLYMATCH.
*
* The extension match rules defined in the devmeeting 2006.05.05 are
* quite simple: WE SELECT THE LONGEST MATCH.
* In detail, "longest" means the number of matched characters in
* the extension. In case of ties (e.g. _XXX and 333) in the length
* of a pattern, we give priority to entries with the smallest cardinality
* (e.g, [5-9] comes before [2-8] before the former has only 5 elements,
* while the latter has 7, etc.
* In case of same cardinality, the first element in the range counts.
* If we still have a tie, any final '!' will make this as a possibly
* less specific pattern.
*
* EBUSY - can't lock
* EEXIST - extension with the same priority exist and no replace is set
*
*/
int ast_add_extension2(struct ast_context *con,
int replace, const char *extension, int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *),
const char *registrar)
{
return ast_add_extension2_lockopt(con, replace, extension, priority, label, callerid,
application, data, datad, registrar, 1);
}
/*!
* \brief Same as ast_add_extension2() but controls the context locking.
*
* \details
* Does all the work of ast_add_extension2, but adds an arg to
* determine if context locking should be done.
*/
static int ast_add_extension2_lockopt(struct ast_context *con,
int replace, const char *extension, int priority, const char *label, const char *callerid,
const char *application, void *data, void (*datad)(void *),
const char *registrar, int lock_context)
{
/*
* Sort extensions (or patterns) according to the rules indicated above.
* These are implemented by the function ext_cmp()).
* All priorities for the same ext/pattern/cid are kept in a list,
* using the 'peer' field as a link field..
*/
struct ast_exten *tmp, *tmp2, *e, *el = NULL;
int res;
int length;
char *p;
char expand_buf[VAR_BUF_SIZE];
struct ast_exten dummy_exten = {0};
char dummy_name[1024];
if (ast_strlen_zero(extension)) {
ast_log(LOG_ERROR,"You have to be kidding-- add exten '' to context %s? Figure out a name and call me back. Action ignored.\n",
con->name);
return -1;
}
/* If we are adding a hint evalulate in variables and global variables */
if (priority == PRIORITY_HINT && strstr(application, "${") && extension[0] != '_') {
struct ast_channel *c = ast_dummy_channel_alloc();
if (c) {
ast_copy_string(c->exten, extension, sizeof(c->exten));
ast_copy_string(c->context, con->name, sizeof(c->context));
}
pbx_substitute_variables_helper(c, application, expand_buf, sizeof(expand_buf));
application = expand_buf;
if (c) {
ast_channel_unref(c);
}
}
length = sizeof(struct ast_exten);
length += strlen(extension) + 1;
length += strlen(application) + 1;
if (label)
length += strlen(label) + 1;
if (callerid)
length += strlen(callerid) + 1;
else
length ++; /* just the '\0' */
/* Be optimistic: Build the extension structure first */
if (!(tmp = ast_calloc(1, length)))
return -1;
if (ast_strlen_zero(label)) /* let's turn empty labels to a null ptr */
label = 0;
/* use p as dst in assignments, as the fields are const char * */
p = tmp->stuff;
if (label) {
tmp->label = p;
strcpy(p, label);
p += strlen(label) + 1;
}
tmp->exten = p;
p += ext_strncpy(p, extension, strlen(extension) + 1) + 1;
tmp->priority = priority;
tmp->cidmatch = p; /* but use p for assignments below */
/* Blank callerid and NULL callerid are two SEPARATE things. Do NOT confuse the two!!! */
if (callerid) {
p += ext_strncpy(p, callerid, strlen(callerid) + 1) + 1;
tmp->matchcid = 1;
} else {
*p++ = '\0';
tmp->matchcid = 0;
}
tmp->app = p;
strcpy(p, application);
tmp->parent = con;
tmp->data = data;
tmp->datad = datad;
tmp->registrar = registrar;
if (lock_context) {
ast_wrlock_context(con);
}
if (con->pattern_tree) { /* usually, on initial load, the pattern_tree isn't formed until the first find_exten; so if we are adding
an extension, and the trie exists, then we need to incrementally add this pattern to it. */
ast_copy_string(dummy_name, extension, sizeof(dummy_name));
dummy_exten.exten = dummy_name;
dummy_exten.matchcid = 0;
dummy_exten.cidmatch = 0;
tmp2 = ast_hashtab_lookup(con->root_table, &dummy_exten);
if (!tmp2) {
/* hmmm, not in the trie; */
add_exten_to_pattern_tree(con, tmp, 0);
ast_hashtab_insert_safe(con->root_table, tmp); /* for the sake of completeness */
}
}
res = 0; /* some compilers will think it is uninitialized otherwise */
for (e = con->root; e; el = e, e = e->next) { /* scan the extension list */
res = ext_cmp(e->exten, tmp->exten);
if (res == 0) { /* extension match, now look at cidmatch */
if (!e->matchcid && !tmp->matchcid)
res = 0;
else if (tmp->matchcid && !e->matchcid)
res = 1;
else if (e->matchcid && !tmp->matchcid)
res = -1;
else
res = ext_cmp(e->cidmatch, tmp->cidmatch);
}
if (res >= 0)
break;
}
if (e && res == 0) { /* exact match, insert in the priority chain */
res = add_priority(con, tmp, el, e, replace);
if (lock_context) {
ast_unlock_context(con);
}
if (res < 0) {
errno = EEXIST; /* XXX do we care ? */
return 0; /* XXX should we return -1 maybe ? */
}
} else {
/*
* not an exact match, this is the first entry with this pattern,
* so insert in the main list right before 'e' (if any)
*/
tmp->next = e;
if (el) { /* there is another exten already in this context */
el->next = tmp;
tmp->peer_table = ast_hashtab_create(13,
hashtab_compare_exten_numbers,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_priority,
0);
tmp->peer_label_table = ast_hashtab_create(7,
hashtab_compare_exten_labels,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_labels,
0);
if (label) {
ast_hashtab_insert_safe(tmp->peer_label_table, tmp);
}
ast_hashtab_insert_safe(tmp->peer_table, tmp);
} else { /* this is the first exten in this context */
if (!con->root_table)
con->root_table = ast_hashtab_create(27,
hashtab_compare_extens,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_extens,
0);
con->root = tmp;
con->root->peer_table = ast_hashtab_create(13,
hashtab_compare_exten_numbers,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_priority,
0);
con->root->peer_label_table = ast_hashtab_create(7,
hashtab_compare_exten_labels,
ast_hashtab_resize_java,
ast_hashtab_newsize_java,
hashtab_hash_labels,
0);
if (label) {
ast_hashtab_insert_safe(con->root->peer_label_table, tmp);
}
ast_hashtab_insert_safe(con->root->peer_table, tmp);
}
ast_hashtab_insert_safe(con->root_table, tmp);
if (lock_context) {
ast_unlock_context(con);
}
if (tmp->priority == PRIORITY_HINT) {
ast_add_hint(tmp);
}
}
if (option_debug) {
if (tmp->matchcid) {
ast_debug(1, "Added extension '%s' priority %d (CID match '%s') to %s (%p)\n",
tmp->exten, tmp->priority, tmp->cidmatch, con->name, con);
} else {
ast_debug(1, "Added extension '%s' priority %d to %s (%p)\n",
tmp->exten, tmp->priority, con->name, con);
}
}
if (tmp->matchcid) {
ast_verb(3, "Added extension '%s' priority %d (CID match '%s') to %s\n",
tmp->exten, tmp->priority, tmp->cidmatch, con->name);
} else {
ast_verb(3, "Added extension '%s' priority %d to %s\n",
tmp->exten, tmp->priority, con->name);
}
return 0;
}
struct async_stat {
pthread_t p;
struct ast_channel *chan;
char context[AST_MAX_CONTEXT];
char exten[AST_MAX_EXTENSION];
int priority;
int timeout;
char app[AST_MAX_EXTENSION];
char appdata[1024];
};
static void *async_wait(void *data)
{
struct async_stat *as = data;
struct ast_channel *chan = as->chan;
int timeout = as->timeout;
int res;
struct ast_frame *f;
struct ast_app *app;
struct timeval start = ast_tvnow();
int ms;
while ((ms = ast_remaining_ms(start, timeout)) &&
chan->_state != AST_STATE_UP) {
res = ast_waitfor(chan, ms);
if (res < 1)
break;
f = ast_read(chan);
if (!f)
break;
if (f->frametype == AST_FRAME_CONTROL) {
if ((f->subclass.integer == AST_CONTROL_BUSY) ||
(f->subclass.integer == AST_CONTROL_CONGESTION) ) {
ast_frfree(f);
break;
}
}
ast_frfree(f);
}
if (chan->_state == AST_STATE_UP) {
if (!ast_strlen_zero(as->app)) {
app = pbx_findapp(as->app);
if (app) {
ast_verb(3, "Launching %s(%s) on %s\n", as->app, as->appdata, chan->name);
pbx_exec(chan, app, as->appdata);
} else
ast_log(LOG_WARNING, "No such application '%s'\n", as->app);
} else {
if (!ast_strlen_zero(as->context))
ast_copy_string(chan->context, as->context, sizeof(chan->context));
if (!ast_strlen_zero(as->exten))
ast_copy_string(chan->exten, as->exten, sizeof(chan->exten));
if (as->priority > 0)
chan->priority = as->priority;
/* Run the PBX */
if (ast_pbx_run(chan)) {
ast_log(LOG_ERROR, "Failed to start PBX on %s\n", chan->name);
} else {
/* PBX will have taken care of this */
chan = NULL;
}
}
}
ast_free(as);
if (chan)
ast_hangup(chan);
return NULL;
}
/*!
* \brief Function to post an empty cdr after a spool call fails.
* \note This function posts an empty cdr for a failed spool call
*/
static int ast_pbx_outgoing_cdr_failed(void)
{
/* allocate a channel */
struct ast_channel *chan = ast_dummy_channel_alloc();
if (!chan)
return -1; /* failure */
chan->cdr = ast_cdr_alloc();
if (!chan->cdr) {
/* allocation of the cdr failed */
chan = ast_channel_unref(chan); /* free the channel */
return -1; /* return failure */
}
/* allocation of the cdr was successful */
ast_cdr_init(chan->cdr, chan); /* initialize our channel's cdr */
ast_cdr_start(chan->cdr); /* record the start and stop time */
ast_cdr_end(chan->cdr);
ast_cdr_failed(chan->cdr); /* set the status to failed */
ast_cdr_detach(chan->cdr); /* post and free the record */
chan->cdr = NULL;
chan = ast_channel_unref(chan); /* free the channel */
return 0; /* success */
}
int ast_pbx_outgoing_exten(const char *type, format_t format, void *data, int timeout, const char *context, const char *exten, int priority, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **channel)
{
struct ast_channel *chan;
struct async_stat *as;
int res = -1, cdr_res = -1;
struct outgoing_helper oh;
if (synchronous) {
oh.context = context;
oh.exten = exten;
oh.priority = priority;
oh.cid_num = cid_num;
oh.cid_name = cid_name;
oh.account = account;
oh.vars = vars;
oh.parent_channel = NULL;
chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
if (channel) {
*channel = chan;
if (chan)
ast_channel_lock(chan);
}
if (chan) {
if (chan->_state == AST_STATE_UP) {
res = 0;
ast_verb(4, "Channel %s was answered.\n", chan->name);
if (synchronous > 1) {
if (channel)
ast_channel_unlock(chan);
if (ast_pbx_run(chan)) {
ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
if (channel)
*channel = NULL;
ast_hangup(chan);
chan = NULL;
res = -1;
}
} else {
if (ast_pbx_start(chan)) {
ast_log(LOG_ERROR, "Unable to start PBX on %s\n", chan->name);
if (channel) {
*channel = NULL;
ast_channel_unlock(chan);
}
ast_hangup(chan);
res = -1;
}
chan = NULL;
}
} else {
ast_verb(4, "Channel %s was never answered.\n", chan->name);
if (chan->cdr) { /* update the cdr */
/* here we update the status of the call, which sould be busy.
* if that fails then we set the status to failed */
if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
ast_cdr_failed(chan->cdr);
}
if (channel) {
*channel = NULL;
ast_channel_unlock(chan);
}
ast_hangup(chan);
chan = NULL;
}
}
if (res < 0) { /* the call failed for some reason */
if (*reason == 0) { /* if the call failed (not busy or no answer)
* update the cdr with the failed message */
cdr_res = ast_pbx_outgoing_cdr_failed();
if (cdr_res != 0) {
res = cdr_res;
goto outgoing_exten_cleanup;
}
}
/* create a fake channel and execute the "failed" extension (if it exists) within the requested context */
/* check if "failed" exists */
if (ast_exists_extension(chan, context, "failed", 1, NULL)) {
chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", NULL, 0, "OutgoingSpoolFailed");
if (chan) {
char failed_reason[4] = "";
if (!ast_strlen_zero(context))
ast_copy_string(chan->context, context, sizeof(chan->context));
set_ext_pri(chan, "failed", 1);
ast_set_variables(chan, vars);
snprintf(failed_reason, sizeof(failed_reason), "%d", *reason);
pbx_builtin_setvar_helper(chan, "REASON", failed_reason);
if (account)
ast_cdr_setaccount(chan, account);
if (ast_pbx_run(chan)) {
ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
ast_hangup(chan);
}
chan = NULL;
}
}
}
} else {
if (!(as = ast_calloc(1, sizeof(*as)))) {
res = -1;
goto outgoing_exten_cleanup;
}
chan = ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name);
if (channel) {
*channel = chan;
if (chan)
ast_channel_lock(chan);
}
if (!chan) {
ast_free(as);
res = -1;
goto outgoing_exten_cleanup;
}
as->chan = chan;
ast_copy_string(as->context, context, sizeof(as->context));
set_ext_pri(as->chan, exten, priority);
as->timeout = timeout;
ast_set_variables(chan, vars);
if (account)
ast_cdr_setaccount(chan, account);
if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
ast_log(LOG_WARNING, "Failed to start async wait\n");
ast_free(as);
if (channel) {
*channel = NULL;
ast_channel_unlock(chan);
}
ast_hangup(chan);
res = -1;
goto outgoing_exten_cleanup;
}
res = 0;
}
outgoing_exten_cleanup:
ast_variables_destroy(vars);
return res;
}
struct app_tmp {
struct ast_channel *chan;
pthread_t t;
AST_DECLARE_STRING_FIELDS (
AST_STRING_FIELD(app);
AST_STRING_FIELD(data);
);
};
/*! \brief run the application and free the descriptor once done */
static void *ast_pbx_run_app(void *data)
{
struct app_tmp *tmp = data;
struct ast_app *app;
app = pbx_findapp(tmp->app);
if (app) {
ast_verb(4, "Launching %s(%s) on %s\n", tmp->app, tmp->data, tmp->chan->name);
pbx_exec(tmp->chan, app, tmp->data);
} else
ast_log(LOG_WARNING, "No such application '%s'\n", tmp->app);
ast_hangup(tmp->chan);
ast_string_field_free_memory(tmp);
ast_free(tmp);
return NULL;
}
int ast_pbx_outgoing_app(const char *type, format_t format, void *data, int timeout, const char *app, const char *appdata, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **locked_channel)
{
struct ast_channel *chan;
struct app_tmp *tmp;
int res = -1, cdr_res = -1;
struct outgoing_helper oh;
memset(&oh, 0, sizeof(oh));
oh.vars = vars;
oh.account = account;
if (locked_channel)
*locked_channel = NULL;
if (ast_strlen_zero(app)) {
res = -1;
goto outgoing_app_cleanup;
}
if (synchronous) {
chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
if (chan) {
ast_set_variables(chan, vars);
if (account)
ast_cdr_setaccount(chan, account);
if (chan->_state == AST_STATE_UP) {
res = 0;
ast_verb(4, "Channel %s was answered.\n", chan->name);
tmp = ast_calloc(1, sizeof(*tmp));
if (!tmp || ast_string_field_init(tmp, 252)) {
if (tmp) {
ast_free(tmp);
}
res = -1;
} else {
ast_string_field_set(tmp, app, app);
ast_string_field_set(tmp, data, appdata);
tmp->chan = chan;
if (synchronous > 1) {
if (locked_channel)
ast_channel_unlock(chan);
ast_pbx_run_app(tmp);
} else {
if (locked_channel)
ast_channel_lock(chan);
if (ast_pthread_create_detached(&tmp->t, NULL, ast_pbx_run_app, tmp)) {
ast_log(LOG_WARNING, "Unable to spawn execute thread on %s: %s\n", chan->name, strerror(errno));
ast_string_field_free_memory(tmp);
ast_free(tmp);
if (locked_channel)
ast_channel_unlock(chan);
ast_hangup(chan);
res = -1;
} else {
if (locked_channel)
*locked_channel = chan;
}
}
}
} else {
ast_verb(4, "Channel %s was never answered.\n", chan->name);
if (chan->cdr) { /* update the cdr */
/* here we update the status of the call, which sould be busy.
* if that fails then we set the status to failed */
if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
ast_cdr_failed(chan->cdr);
}
ast_hangup(chan);
}
}
if (res < 0) { /* the call failed for some reason */
if (*reason == 0) { /* if the call failed (not busy or no answer)
* update the cdr with the failed message */
cdr_res = ast_pbx_outgoing_cdr_failed();
if (cdr_res != 0) {
res = cdr_res;
goto outgoing_app_cleanup;
}
}
}
} else {
struct async_stat *as;
if (!(as = ast_calloc(1, sizeof(*as)))) {
res = -1;
goto outgoing_app_cleanup;
}
chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh);
if (!chan) {
ast_free(as);
res = -1;
goto outgoing_app_cleanup;
}
as->chan = chan;
ast_copy_string(as->app, app, sizeof(as->app));
if (appdata)
ast_copy_string(as->appdata, appdata, sizeof(as->appdata));
as->timeout = timeout;
ast_set_variables(chan, vars);
if (account)
ast_cdr_setaccount(chan, account);
/* Start a new thread, and get something handling this channel. */
if (locked_channel)
ast_channel_lock(chan);
if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) {
ast_log(LOG_WARNING, "Failed to start async wait\n");
ast_free(as);
if (locked_channel)
ast_channel_unlock(chan);
ast_hangup(chan);
res = -1;
goto outgoing_app_cleanup;
} else {
if (locked_channel)
*locked_channel = chan;
}
res = 0;
}
outgoing_app_cleanup:
ast_variables_destroy(vars);
return res;
}
/* this is the guts of destroying a context --
freeing up the structure, traversing and destroying the
extensions, switches, ignorepats, includes, etc. etc. */
static void __ast_internal_context_destroy( struct ast_context *con)
{
struct ast_include *tmpi;
struct ast_sw *sw;
struct ast_exten *e, *el, *en;
struct ast_ignorepat *ipi;
struct ast_context *tmp = con;
for (tmpi = tmp->includes; tmpi; ) { /* Free includes */
struct ast_include *tmpil = tmpi;
tmpi = tmpi->next;
ast_free(tmpil);
}
for (ipi = tmp->ignorepats; ipi; ) { /* Free ignorepats */
struct ast_ignorepat *ipl = ipi;
ipi = ipi->next;
ast_free(ipl);
}
if (tmp->registrar)
ast_free(tmp->registrar);
/* destroy the hash tabs */
if (tmp->root_table) {
ast_hashtab_destroy(tmp->root_table, 0);
}
/* and destroy the pattern tree */
if (tmp->pattern_tree)
destroy_pattern_tree(tmp->pattern_tree);
while ((sw = AST_LIST_REMOVE_HEAD(&tmp->alts, list)))
ast_free(sw);
for (e = tmp->root; e;) {
for (en = e->peer; en;) {
el = en;
en = en->peer;
destroy_exten(el);
}
el = e;
e = e->next;
destroy_exten(el);
}
tmp->root = NULL;
ast_rwlock_destroy(&tmp->lock);
ast_mutex_destroy(&tmp->macrolock);
ast_free(tmp);
}
void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar)
{
struct ast_context *tmp, *tmpl=NULL;
struct ast_exten *exten_item, *prio_item;
for (tmp = list; tmp; ) {
struct ast_context *next = NULL; /* next starting point */
/* The following code used to skip forward to the next
context with matching registrar, but this didn't
make sense; individual priorities registrar'd to
the matching registrar could occur in any context! */
ast_debug(1, "Investigate ctx %s %s\n", tmp->name, tmp->registrar);
if (con) {
for (; tmp; tmpl = tmp, tmp = tmp->next) { /* skip to the matching context */
ast_debug(1, "check ctx %s %s\n", tmp->name, tmp->registrar);
if ( !strcasecmp(tmp->name, con->name) ) {
break; /* found it */
}
}
}
if (!tmp) /* not found, we are done */
break;
ast_wrlock_context(tmp);
if (registrar) {
/* then search thru and remove any extens that match registrar. */
struct ast_hashtab_iter *exten_iter;
struct ast_hashtab_iter *prio_iter;
struct ast_ignorepat *ip, *ipl = NULL, *ipn = NULL;
struct ast_include *i, *pi = NULL, *ni = NULL;
struct ast_sw *sw = NULL;
/* remove any ignorepats whose registrar matches */
for (ip = tmp->ignorepats; ip; ip = ipn) {
ipn = ip->next;
if (!strcmp(ip->registrar, registrar)) {
if (ipl) {
ipl->next = ip->next;
ast_free(ip);
continue; /* don't change ipl */
} else {
tmp->ignorepats = ip->next;
ast_free(ip);
continue; /* don't change ipl */
}
}
ipl = ip;
}
/* remove any includes whose registrar matches */
for (i = tmp->includes; i; i = ni) {
ni = i->next;
if (strcmp(i->registrar, registrar) == 0) {
/* remove from list */
if (pi) {
pi->next = i->next;
/* free include */
ast_free(i);
continue; /* don't change pi */
} else {
tmp->includes = i->next;
/* free include */
ast_free(i);
continue; /* don't change pi */
}
}
pi = i;
}
/* remove any switches whose registrar matches */
AST_LIST_TRAVERSE_SAFE_BEGIN(&tmp->alts, sw, list) {
if (strcmp(sw->registrar,registrar) == 0) {
AST_LIST_REMOVE_CURRENT(list);
ast_free(sw);
}
}
AST_LIST_TRAVERSE_SAFE_END;
if (tmp->root_table) { /* it is entirely possible that the context is EMPTY */
exten_iter = ast_hashtab_start_traversal(tmp->root_table);
while ((exten_item=ast_hashtab_next(exten_iter))) {
int end_traversal = 1;
prio_iter = ast_hashtab_start_traversal(exten_item->peer_table);
while ((prio_item=ast_hashtab_next(prio_iter))) {
char extension[AST_MAX_EXTENSION];
char cidmatch[AST_MAX_EXTENSION];
if (!prio_item->registrar || strcmp(prio_item->registrar, registrar) != 0) {
continue;
}
ast_verb(3, "Remove %s/%s/%d, registrar=%s; con=%s(%p); con->root=%p\n",
tmp->name, prio_item->exten, prio_item->priority, registrar, con? con->name : "<nil>", con, con? con->root_table: NULL);
/* set matchcid to 1 to insure we get a direct match, and NULL registrar to make sure no wildcarding is done */
ast_copy_string(extension, prio_item->exten, sizeof(extension));
if (prio_item->cidmatch) {
ast_copy_string(cidmatch, prio_item->cidmatch, sizeof(cidmatch));
}
end_traversal &= ast_context_remove_extension_callerid2(tmp, extension, prio_item->priority, prio_item->cidmatch ? cidmatch : NULL, 1, NULL, 1);
}
/* Explanation:
* ast_context_remove_extension_callerid2 will destroy the extension that it comes across. This
* destruction includes destroying the exten's peer_table, which we are currently traversing. If
* ast_context_remove_extension_callerid2 ever should return '0' then this means we have destroyed
* the hashtable which we are traversing, and thus calling ast_hashtab_end_traversal will result
* in reading invalid memory. Thus, if we detect that we destroyed the hashtable, then we will simply
* free the iterator
*/
if (end_traversal) {
ast_hashtab_end_traversal(prio_iter);
} else {
ast_free(prio_iter);
}
}
ast_hashtab_end_traversal(exten_iter);
}
/* delete the context if it's registrar matches, is empty, has refcount of 1, */
/* it's not empty, if it has includes, ignorepats, or switches that are registered from
another registrar. It's not empty if there are any extensions */
if (strcmp(tmp->registrar, registrar) == 0 && tmp->refcount < 2 && !tmp->root && !tmp->ignorepats && !tmp->includes && AST_LIST_EMPTY(&tmp->alts)) {
ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar);
ast_hashtab_remove_this_object(contexttab, tmp);
next = tmp->next;
if (tmpl)
tmpl->next = next;
else
contexts = next;
/* Okay, now we're safe to let it go -- in a sense, we were
ready to let it go as soon as we locked it. */
ast_unlock_context(tmp);
__ast_internal_context_destroy(tmp);
} else {
ast_debug(1,"Couldn't delete ctx %s/%s; refc=%d; tmp.root=%p\n", tmp->name, tmp->registrar,
tmp->refcount, tmp->root);
ast_unlock_context(tmp);
next = tmp->next;
tmpl = tmp;
}
} else if (con) {
ast_verb(3, "Deleting context %s registrar=%s\n", tmp->name, tmp->registrar);
ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar);
ast_hashtab_remove_this_object(contexttab, tmp);
next = tmp->next;
if (tmpl)
tmpl->next = next;
else
contexts = next;
/* Okay, now we're safe to let it go -- in a sense, we were
ready to let it go as soon as we locked it. */
ast_unlock_context(tmp);
__ast_internal_context_destroy(tmp);
}
/* if we have a specific match, we are done, otherwise continue */
tmp = con ? NULL : next;
}
}
void ast_context_destroy(struct ast_context *con, const char *registrar)
{
ast_wrlock_contexts();
__ast_context_destroy(contexts, contexts_table, con,registrar);
ast_unlock_contexts();
}
static void wait_for_hangup(struct ast_channel *chan, const void *data)
{
int res;
struct ast_frame *f;
double waitsec;
int waittime;
if (ast_strlen_zero(data) || (sscanf(data, "%30lg", &waitsec) != 1) || (waitsec < 0))
waitsec = -1;
if (waitsec > -1) {
waittime = waitsec * 1000.0;
ast_safe_sleep(chan, waittime);
} else do {
res = ast_waitfor(chan, -1);
if (res < 0)
return;
f = ast_read(chan);
if (f)
ast_frfree(f);
} while(f);
}
/*!
* \ingroup applications
*/
static int pbx_builtin_proceeding(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_PROCEEDING);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_progress(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_PROGRESS);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_ringing(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_RINGING);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_busy(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_BUSY);
/* Don't change state of an UP channel, just indicate
busy in audio */
if (chan->_state != AST_STATE_UP) {
ast_setstate(chan, AST_STATE_BUSY);
ast_cdr_busy(chan->cdr);
}
wait_for_hangup(chan, data);
return -1;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_congestion(struct ast_channel *chan, const char *data)
{
ast_indicate(chan, AST_CONTROL_CONGESTION);
/* Don't change state of an UP channel, just indicate
congestion in audio */
if (chan->_state != AST_STATE_UP)
ast_setstate(chan, AST_STATE_BUSY);
wait_for_hangup(chan, data);
return -1;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_answer(struct ast_channel *chan, const char *data)
{
int delay = 0;
int answer_cdr = 1;
char *parse;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(delay);
AST_APP_ARG(answer_cdr);
);
if (ast_strlen_zero(data)) {
return __ast_answer(chan, 0, 1);
}
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
if (!ast_strlen_zero(args.delay) && (chan->_state != AST_STATE_UP))
delay = atoi(data);
if (delay < 0) {
delay = 0;
}
if (!ast_strlen_zero(args.answer_cdr) && !strcasecmp(args.answer_cdr, "nocdr")) {
answer_cdr = 0;
}
return __ast_answer(chan, delay, answer_cdr);
}
static int pbx_builtin_incomplete(struct ast_channel *chan, const char *data)
{
const char *options = data;
int answer = 1;
/* Some channels can receive DTMF in unanswered state; some cannot */
if (!ast_strlen_zero(options) && strchr(options, 'n')) {
answer = 0;
}
/* If the channel is hungup, stop waiting */
if (ast_check_hangup(chan)) {
return -1;
} else if (chan->_state != AST_STATE_UP && answer) {
__ast_answer(chan, 0, 1);
}
ast_indicate(chan, AST_CONTROL_INCOMPLETE);
return AST_PBX_INCOMPLETE;
}
AST_APP_OPTIONS(resetcdr_opts, {
AST_APP_OPTION('w', AST_CDR_FLAG_POSTED),
AST_APP_OPTION('a', AST_CDR_FLAG_LOCKED),
AST_APP_OPTION('v', AST_CDR_FLAG_KEEP_VARS),
AST_APP_OPTION('e', AST_CDR_FLAG_POST_ENABLE),
});
/*!
* \ingroup applications
*/
static int pbx_builtin_resetcdr(struct ast_channel *chan, const char *data)
{
char *args;
struct ast_flags flags = { 0 };
if (!ast_strlen_zero(data)) {
args = ast_strdupa(data);
ast_app_parse_options(resetcdr_opts, &flags, NULL, args);
}
ast_cdr_reset(chan->cdr, &flags);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_setamaflags(struct ast_channel *chan, const char *data)
{
/* Copy the AMA Flags as specified */
ast_channel_lock(chan);
ast_cdr_setamaflags(chan, data ? data : "");
ast_channel_unlock(chan);
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_hangup(struct ast_channel *chan, const char *data)
{
ast_set_hangupsource(chan, "dialplan/builtin", 0);
if (!ast_strlen_zero(data)) {
int cause;
char *endptr;
if ((cause = ast_str2cause(data)) > -1) {
chan->hangupcause = cause;
return -1;
}
cause = strtol((const char *) data, &endptr, 10);
if (cause != 0 || (data != endptr)) {
chan->hangupcause = cause;
return -1;
}
ast_log(LOG_WARNING, "Invalid cause given to Hangup(): \"%s\"\n", (char *) data);
}
if (!chan->hangupcause) {
chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
}
return -1;
}
/*!
* \ingroup functions
*/
static int testtime_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
{
struct ast_tm tm;
struct timeval tv;
char *remainder, result[30], timezone[80];
/* Turn off testing? */
if (!pbx_checkcondition(value)) {
pbx_builtin_setvar_helper(chan, "TESTTIME", NULL);
return 0;
}
/* Parse specified time */
if (!(remainder = ast_strptime(value, "%Y/%m/%d %H:%M:%S", &tm))) {
return -1;
}
sscanf(remainder, "%79s", timezone);
tv = ast_mktime(&tm, S_OR(timezone, NULL));
snprintf(result, sizeof(result), "%ld", (long) tv.tv_sec);
pbx_builtin_setvar_helper(chan, "__TESTTIME", result);
return 0;
}
static struct ast_custom_function testtime_function = {
.name = "TESTTIME",
.write = testtime_write,
};
/*!
* \ingroup applications
*/
static int pbx_builtin_gotoiftime(struct ast_channel *chan, const char *data)
{
char *s, *ts, *branch1, *branch2, *branch;
struct ast_timing timing;
const char *ctime;
struct timeval tv = ast_tvnow();
long timesecs;
if (!chan) {
ast_log(LOG_WARNING, "GotoIfTime requires a channel on which to operate\n");
return -1;
}
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "GotoIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>[,<timezone>]?'labeliftrue':'labeliffalse'\n");
return -1;
}
ts = s = ast_strdupa(data);
ast_channel_lock(chan);
if ((ctime = pbx_builtin_getvar_helper(chan, "TESTTIME")) && sscanf(ctime, "%ld", ×ecs) == 1) {
tv.tv_sec = timesecs;
} else if (ctime) {
ast_log(LOG_WARNING, "Using current time to evaluate\n");
/* Reset when unparseable */
pbx_builtin_setvar_helper(chan, "TESTTIME", NULL);
}
ast_channel_unlock(chan);
/* Separate the Goto path */
strsep(&ts, "?");
branch1 = strsep(&ts,":");
branch2 = strsep(&ts,"");
/* struct ast_include include contained garbage here, fixed by zeroing it on get_timerange */
if (ast_build_timing(&timing, s) && ast_check_timing2(&timing, tv)) {
branch = branch1;
} else {
branch = branch2;
}
ast_destroy_timing(&timing);
if (ast_strlen_zero(branch)) {
ast_debug(1, "Not taking any branch\n");
return 0;
}
return pbx_builtin_goto(chan, branch);
}
/*!
* \ingroup applications
*/
static int pbx_builtin_execiftime(struct ast_channel *chan, const char *data)
{
char *s, *appname;
struct ast_timing timing;
struct ast_app *app;
static const char * const usage = "ExecIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>[,<timezone>]?<appname>[(<appargs>)]";
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "%s\n", usage);
return -1;
}
appname = ast_strdupa(data);
s = strsep(&appname, "?"); /* Separate the timerange and application name/data */
if (!appname) { /* missing application */
ast_log(LOG_WARNING, "%s\n", usage);
return -1;
}
if (!ast_build_timing(&timing, s)) {
ast_log(LOG_WARNING, "Invalid Time Spec: %s\nCorrect usage: %s\n", s, usage);
ast_destroy_timing(&timing);
return -1;
}
if (!ast_check_timing(&timing)) { /* outside the valid time window, just return */
ast_destroy_timing(&timing);
return 0;
}
ast_destroy_timing(&timing);
/* now split appname(appargs) */
if ((s = strchr(appname, '('))) {
char *e;
*s++ = '\0';
if ((e = strrchr(s, ')')))
*e = '\0';
else
ast_log(LOG_WARNING, "Failed to find closing parenthesis\n");
}
if ((app = pbx_findapp(appname))) {
return pbx_exec(chan, app, S_OR(s, ""));
} else {
ast_log(LOG_WARNING, "Cannot locate application %s\n", appname);
return -1;
}
}
/*!
* \ingroup applications
*/
static int pbx_builtin_wait(struct ast_channel *chan, const char *data)
{
int ms;
/* Wait for "n" seconds */
if (!ast_app_parse_timelen(data, &ms, TIMELEN_SECONDS) && ms > 0) {
return ast_safe_sleep(chan, ms);
}
return 0;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_waitexten(struct ast_channel *chan, const char *data)
{
int ms, res;
struct ast_flags flags = {0};
char *opts[1] = { NULL };
char *parse;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(timeout);
AST_APP_ARG(options);
);
if (!ast_strlen_zero(data)) {
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
} else
memset(&args, 0, sizeof(args));
if (args.options)
ast_app_parse_options(waitexten_opts, &flags, opts, args.options);
if (ast_test_flag(&flags, WAITEXTEN_MOH) && !opts[0] ) {
ast_log(LOG_WARNING, "The 'm' option has been specified for WaitExten without a class.\n");
} else if (ast_test_flag(&flags, WAITEXTEN_MOH)) {
ast_indicate_data(chan, AST_CONTROL_HOLD, S_OR(opts[0], NULL),
!ast_strlen_zero(opts[0]) ? strlen(opts[0]) + 1 : 0);
} else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE)) {
struct ast_tone_zone_sound *ts = ast_get_indication_tone(chan->zone, "dial");
if (ts) {
ast_playtones_start(chan, 0, ts->data, 0);
ts = ast_tone_zone_sound_unref(ts);
} else {
ast_tonepair_start(chan, 350, 440, 0, 0);
}
}
/* Wait for "n" seconds */
if (!ast_app_parse_timelen(args.timeout, &ms, TIMELEN_SECONDS) && ms > 0) {
/* Yay! */
} else if (chan->pbx) {
ms = chan->pbx->rtimeoutms;
} else {
ms = 10000;
}
res = ast_waitfordigit(chan, ms);
if (!res) {
if (ast_check_hangup(chan)) {
/* Call is hungup for some reason. */
res = -1;
} else if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
ast_verb(3, "Timeout on %s, continuing...\n", chan->name);
} else if (ast_exists_extension(chan, chan->context, "t", 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
ast_verb(3, "Timeout on %s, going to 't'\n", chan->name);
set_ext_pri(chan, "t", 0); /* 0 will become 1, next time through the loop */
} else if (ast_exists_extension(chan, chan->context, "e", 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
raise_exception(chan, "RESPONSETIMEOUT", 0); /* 0 will become 1, next time through the loop */
} else {
ast_log(LOG_WARNING, "Timeout but no rule 't' or 'e' in context '%s'\n",
chan->context);
res = -1;
}
}
if (ast_test_flag(&flags, WAITEXTEN_MOH))
ast_indicate(chan, AST_CONTROL_UNHOLD);
else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE))
ast_playtones_stop(chan);
return res;
}
/*!
* \ingroup applications
*/
static int pbx_builtin_background(struct ast_channel *chan, const char *data)
{
int res = 0;
int mres = 0;
struct ast_flags flags = {0};
char *parse, exten[2] = "";
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(filename);
AST_APP_ARG(options);
AST_APP_ARG(lang);
AST_APP_ARG(context);
);
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Background requires an argument (filename)\n");
return -1;
}
parse = ast_strdupa(data);
AST_STANDARD_APP_ARGS(args, parse);
if (ast_strlen_zero(args.lang))
args.lang = (char *)chan->language; /* XXX this is const */
if (ast_strlen_zero(args.context)) {
const char *context;
ast_channel_lock(chan);
if ((context = pbx_builtin_getvar_helper(chan, "MACRO_CONTEXT"))) {
args.context = ast_strdupa(context);
} else {
args.context = chan->context;
}
ast_channel_unlock(chan);
}
if (args.options) {
if (!strcasecmp(args.options, "skip"))
flags.flags = BACKGROUND_SKIP;
else if (!strcasecmp(args.options, "noanswer"))
flags.flags = BACKGROUND_NOANSWER;
else
ast_app_parse_options(background_opts, &flags, NULL, args.options);
}
/* Answer if need be */
if (chan->_state != AST_STATE_UP) {
if (ast_test_flag(&flags, BACKGROUND_SKIP)) {
goto done;
} else if (!ast_test_flag(&flags, BACKGROUND_NOANSWER)) {
res = ast_answer(chan);
}
}
if (!res) {
char *back = ast_strip(args.filename);
char *front;
ast_stopstream(chan); /* Stop anything playing */
/* Stream the list of files */
while (!res && (front = strsep(&back, "&")) ) {
if ( (res = ast_streamfile(chan, front, args.lang)) ) {
ast_log(LOG_WARNING, "ast_streamfile failed on %s for %s\n", chan->name, (char*)data);
res = 0;
mres = 1;
break;
}
if (ast_test_flag(&flags, BACKGROUND_PLAYBACK)) {
res = ast_waitstream(chan, "");
} else if (ast_test_flag(&flags, BACKGROUND_MATCHEXTEN)) {
res = ast_waitstream_exten(chan, args.context);
} else {
res = ast_waitstream(chan, AST_DIGIT_ANY);
}
ast_stopstream(chan);
}
}
/*
* If the single digit DTMF is an extension in the specified context, then
* go there and signal no DTMF. Otherwise, we should exit with that DTMF.
* If we're in Macro, we'll exit and seek that DTMF as the beginning of an
* extension in the Macro's calling context. If we're not in Macro, then
* we'll simply seek that extension in the calling context. Previously,
* someone complained about the behavior as it related to the interior of a
* Gosub routine, and the fix (#14011) inadvertently broke FreePBX
* (#14940). This change should fix both of these situations, but with the
* possible incompatibility that if a single digit extension does not exist
* (but a longer extension COULD have matched), it would have previously
* gone immediately to the "i" extension, but will now need to wait for a
* timeout.
*
* Later, we had to add a flag to disable this workaround, because AGI
* users can EXEC Background and reasonably expect that the DTMF code will
* be returned (see #16434).
*/
if (!ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS)
&& (exten[0] = res)
&& ast_canmatch_extension(chan, args.context, exten, 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
&& !ast_matchmore_extension(chan, args.context, exten, 1,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
snprintf(chan->exten, sizeof(chan->exten), "%c", res);
ast_copy_string(chan->context, args.context, sizeof(chan->context));
chan->priority = 0;
res = 0;
}
done:
pbx_builtin_setvar_helper(chan, "BACKGROUNDSTATUS", mres ? "FAILED" : "SUCCESS");
return res;
}
/*! Goto
* \ingroup applications
*/
static int pbx_builtin_goto(struct ast_channel *chan, const char *data)
{
int res = ast_parseable_goto(chan, data);
if (!res)
ast_verb(3, "Goto (%s,%s,%d)\n", chan->context, chan->exten, chan->priority + 1);
return res;
}
int pbx_builtin_serialize_variables(struct ast_channel *chan, struct ast_str **buf)
{
struct ast_var_t *variables;
const char *var, *val;
int total = 0;
if (!chan)
return 0;
ast_str_reset(*buf);
ast_channel_lock(chan);
AST_LIST_TRAVERSE(&chan->varshead, variables, entries) {
if ((var = ast_var_name(variables)) && (val = ast_var_value(variables))
/* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */
) {
if (ast_str_append(buf, 0, "%s=%s\n", var, val) < 0) {
ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
break;
} else
total++;
} else
break;
}
ast_channel_unlock(chan);
return total;
}
const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
{
struct ast_var_t *variables;
const char *ret = NULL;
int i;
struct varshead *places[2] = { NULL, &globals };
if (!name)
return NULL;
if (chan) {
ast_channel_lock(chan);
places[0] = &chan->varshead;
}
for (i = 0; i < 2; i++) {
if (!places[i])
continue;
if (places[i] == &globals)
ast_rwlock_rdlock(&globalslock);
AST_LIST_TRAVERSE(places[i], variables, entries) {
if (!strcmp(name, ast_var_name(variables))) {
ret = ast_var_value(variables);
break;
}
}
if (places[i] == &globals)
ast_rwlock_unlock(&globalslock);
if (ret)
break;
}
if (chan)
ast_channel_unlock(chan);
return ret;
}
void pbx_builtin_pushvar_helper(struct ast_channel *chan, const char *name, const char *value)
{
struct ast_var_t *newvariable;
struct varshead *headp;
if (name[strlen(name)-1] == ')') {
char *function = ast_strdupa(name);
ast_log(LOG_WARNING, "Cannot push a value onto a function\n");
ast_func_write(chan, function, value);
return;
}
if (chan) {
ast_channel_lock(chan);
headp = &chan->varshead;
} else {
ast_rwlock_wrlock(&globalslock);
headp = &globals;
}
if (value) {
if (headp == &globals)
ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value);
newvariable = ast_var_assign(name, value);
AST_LIST_INSERT_HEAD(headp, newvariable, entries);
}
if (chan)
ast_channel_unlock(chan);
else
ast_rwlock_unlock(&globalslock);
}
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
{
struct ast_var_t *newvariable;
struct varshead *headp;
const char *nametail = name;
if (name[strlen(name) - 1] == ')') {
char *function = ast_strdupa(name);
return ast_func_write(chan, function, value);
}
if (chan) {
ast_channel_lock(chan);
headp = &chan->varshead;
} else {
ast_rwlock_wrlock(&globalslock);
headp = &globals;
}
/* For comparison purposes, we have to strip leading underscores */
if (*nametail == '_') {
nametail++;
if (*nametail == '_')
nametail++;
}
AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
if (strcmp(ast_var_name(newvariable), nametail) == 0) {
/* there is already such a variable, delete it */
AST_LIST_REMOVE_CURRENT(entries);
ast_var_delete(newvariable);
break;
}
}
AST_LIST_TRAVERSE_SAFE_END;
if (value) {
if (headp == &globals)
ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value);
newvariable = ast_var_assign(name, value);
AST_LIST_INSERT_HEAD(headp, newvariable, entries);
manager_event(EVENT_FLAG_DIALPLAN, "VarSet",
"Channel: %s\r\n"
"Variable: %s\r\n"
"Value: %s\r\n"
"Uniqueid: %s\r\n",
chan ? chan->name : "none", name, value,
chan ? chan->uniqueid : "none");
}
if (chan)
ast_channel_unlock(chan);
else
ast_rwlock_unlock(&globalslock);
return 0;
}
int pbx_builtin_setvar(struct ast_channel *chan, const char *data)
{
char *name, *value, *mydata;
if (ast_compat_app_set) {
return pbx_builtin_setvar_multiple(chan, data);
}
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Set requires one variable name/value pair.\n");
return 0;
}
mydata = ast_strdupa(data);
name = strsep(&mydata, "=");
value = mydata;
if (!value) {
ast_log(LOG_WARNING, "Set requires an '=' to be a valid assignment.\n");
return 0;
}
if (strchr(name, ' ')) {
ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", name, mydata);
}
pbx_builtin_setvar_helper(chan, name, value);
return 0;
}
int pbx_builtin_setvar_multiple(struct ast_channel *chan, const char *vdata)
{
char *data;
int x;
AST_DECLARE_APP_ARGS(args,
AST_APP_ARG(pair)[24];
);
AST_DECLARE_APP_ARGS(pair,
AST_APP_ARG(name);
AST_APP_ARG(value);
);
if (ast_strlen_zero(vdata)) {
ast_log(LOG_WARNING, "MSet requires at least one variable name/value pair.\n");
return 0;
}
data = ast_strdupa(vdata);
AST_STANDARD_APP_ARGS(args, data);
for (x = 0; x < args.argc; x++) {
AST_NONSTANDARD_APP_ARGS(pair, args.pair[x], '=');
if (pair.argc == 2) {
pbx_builtin_setvar_helper(chan, pair.name, pair.value);
if (strchr(pair.name, ' '))
ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", pair.name, pair.value);
} else if (!chan) {
ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '='\n", pair.name);
} else {
ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '=' (in %s@%s:%d\n", pair.name, chan->exten, chan->context, chan->priority);
}
}
return 0;
}
int pbx_builtin_importvar(struct ast_channel *chan, const char *data)
{
char *name;
char *value;
char *channel;
char tmp[VAR_BUF_SIZE];
static int deprecation_warning = 0;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Ignoring, since there is no variable to set\n");
return 0;
}
tmp[0] = 0;
if (!deprecation_warning) {
ast_log(LOG_WARNING, "ImportVar is deprecated. Please use Set(varname=${IMPORT(channel,variable)}) instead.\n");
deprecation_warning = 1;
}
value = ast_strdupa(data);
name = strsep(&value,"=");
channel = strsep(&value,",");
if (channel && value && name) { /*! \todo XXX should do !ast_strlen_zero(..) of the args ? */
struct ast_channel *chan2 = ast_channel_get_by_name(channel);
if (chan2) {
char *s = ast_alloca(strlen(value) + 4);
sprintf(s, "${%s}", value);
pbx_substitute_variables_helper(chan2, s, tmp, sizeof(tmp) - 1);
chan2 = ast_channel_unref(chan2);
}
pbx_builtin_setvar_helper(chan, name, tmp);
}
return(0);
}
static int pbx_builtin_noop(struct ast_channel *chan, const char *data)
{
return 0;
}
void pbx_builtin_clear_globals(void)
{
struct ast_var_t *vardata;
ast_rwlock_wrlock(&globalslock);
while ((vardata = AST_LIST_REMOVE_HEAD(&globals, entries)))
ast_var_delete(vardata);
ast_rwlock_unlock(&globalslock);
}
int pbx_checkcondition(const char *condition)
{
int res;
if (ast_strlen_zero(condition)) { /* NULL or empty strings are false */
return 0;
} else if (sscanf(condition, "%30d", &res) == 1) { /* Numbers are evaluated for truth */
return res;
} else { /* Strings are true */
return 1;
}
}
static int pbx_builtin_gotoif(struct ast_channel *chan, const char *data)
{
char *condition, *branch1, *branch2, *branch;
char *stringp;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "Ignoring, since there is no variable to check\n");
return 0;
}
stringp = ast_strdupa(data);
condition = strsep(&stringp,"?");
branch1 = strsep(&stringp,":");
branch2 = strsep(&stringp,"");
branch = pbx_checkcondition(condition) ? branch1 : branch2;
if (ast_strlen_zero(branch)) {
ast_debug(1, "Not taking any branch\n");
return 0;
}
return pbx_builtin_goto(chan, branch);
}
static int pbx_builtin_saynumber(struct ast_channel *chan, const char *data)
{
char tmp[256];
char *number = tmp;
char *options;
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "SayNumber requires an argument (number)\n");
return -1;
}
ast_copy_string(tmp, data, sizeof(tmp));
strsep(&number, ",");
options = strsep(&number, ",");
if (options) {
if ( strcasecmp(options, "f") && strcasecmp(options, "m") &&
strcasecmp(options, "c") && strcasecmp(options, "n") ) {
ast_log(LOG_WARNING, "SayNumber gender option is either 'f', 'm', 'c' or 'n'\n");
return -1;
}
}
if (ast_say_number(chan, atoi(tmp), "", chan->language, options)) {
ast_log(LOG_WARNING, "We were unable to say the number %s, is it too large?\n", tmp);
}
return 0;
}
static int pbx_builtin_saydigits(struct ast_channel *chan, const char *data)
{
int res = 0;
if (data)
res = ast_say_digit_str(chan, data, "", chan->language);
return res;
}
static int pbx_builtin_saycharacters(struct ast_channel *chan, const char *data)
{
int res = 0;
if (data)
res = ast_say_character_str(chan, data, "", chan->language);
return res;
}
static int pbx_builtin_sayphonetic(struct ast_channel *chan, const char *data)
{
int res = 0;
if (data)
res = ast_say_phonetic_str(chan, data, "", chan->language);
return res;
}
static void device_state_cb(const struct ast_event *event, void *unused)
{
const char *device;
struct statechange *sc;
device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
if (ast_strlen_zero(device)) {
ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
return;
}
if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(device) + 1)))
return;
strcpy(sc->dev, device);
if (ast_taskprocessor_push(device_state_tps, handle_statechange, sc) < 0) {
ast_free(sc);
}
}
/*!
* \internal
* \brief Implements the hints data provider.
*/
static int hints_data_provider_get(const struct ast_data_search *search,
struct ast_data *data_root)
{
struct ast_data *data_hint;
struct ast_hint *hint;
int watchers;
struct ao2_iterator i;
if (ao2_container_count(hints) == 0) {
return 0;
}
i = ao2_iterator_init(hints, 0);
for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) {
watchers = ao2_container_count(hint->callbacks);
data_hint = ast_data_add_node(data_root, "hint");
if (!data_hint) {
continue;
}
ast_data_add_str(data_hint, "extension", ast_get_extension_name(hint->exten));
ast_data_add_str(data_hint, "context", ast_get_context_name(ast_get_extension_context(hint->exten)));
ast_data_add_str(data_hint, "application", ast_get_extension_app(hint->exten));
ast_data_add_str(data_hint, "state", ast_extension_state2str(hint->laststate));
ast_data_add_int(data_hint, "watchers", watchers);
if (!ast_data_search_match(search, data_hint)) {
ast_data_remove_node(data_root, data_hint);
}
}
ao2_iterator_destroy(&i);
return 0;
}
static const struct ast_data_handler hints_data_provider = {
.version = AST_DATA_HANDLER_VERSION,
.get = hints_data_provider_get
};
static const struct ast_data_entry pbx_data_providers[] = {
AST_DATA_ENTRY("asterisk/core/hints", &hints_data_provider),
};
/*! \internal \brief Clean up resources on Asterisk shutdown.
* \note Cleans up resources allocated in load_pbx */
static void unload_pbx(void)
{
int x;
if (device_state_sub) {
device_state_sub = ast_event_unsubscribe(device_state_sub);
}
if (device_state_tps) {
ast_taskprocessor_unreference(device_state_tps);
device_state_tps = NULL;
}
/* Unregister builtin applications */
for (x = 0; x < ARRAY_LEN(builtins); x++) {
ast_unregister_application(builtins[x].name);
}
ast_manager_unregister("ShowDialPlan");
ast_cli_unregister_multiple(pbx_cli, ARRAY_LEN(pbx_cli));
ast_custom_function_unregister(&exception_function);
ast_custom_function_unregister(&testtime_function);
ast_data_unregister(NULL);
}
int load_pbx(void)
{
int x;
ast_register_atexit(unload_pbx);
/* Initialize the PBX */
ast_verb(1, "Asterisk PBX Core Initializing\n");
if (!(device_state_tps = ast_taskprocessor_get("pbx-core", 0))) {
ast_log(LOG_WARNING, "failed to create pbx-core taskprocessor\n");
}
ast_verb(1, "Registering builtin applications:\n");
ast_cli_register_multiple(pbx_cli, ARRAY_LEN(pbx_cli));
ast_data_register_multiple_core(pbx_data_providers, ARRAY_LEN(pbx_data_providers));
__ast_custom_function_register(&exception_function, NULL);
__ast_custom_function_register(&testtime_function, NULL);
/* Register builtin applications */
for (x = 0; x < ARRAY_LEN(builtins); x++) {
ast_verb(1, "[%s]\n", builtins[x].name);
if (ast_register_application2(builtins[x].name, builtins[x].execute, NULL, NULL, NULL)) {
ast_log(LOG_ERROR, "Unable to register builtin application '%s'\n", builtins[x].name);
return -1;
}
}
/* Register manager application */
ast_manager_register_xml("ShowDialPlan", EVENT_FLAG_CONFIG | EVENT_FLAG_REPORTING, manager_show_dialplan);
if (!(device_state_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE, device_state_cb, "pbx Device State Change", NULL,
AST_EVENT_IE_END))) {
return -1;
}
return 0;
}
/*
* Lock context list functions ...
*/
int ast_wrlock_contexts(void)
{
return ast_mutex_lock(&conlock);
}
int ast_rdlock_contexts(void)
{
return ast_mutex_lock(&conlock);
}
int ast_unlock_contexts(void)
{
return ast_mutex_unlock(&conlock);
}
/*
* Lock context ...
*/
int ast_wrlock_context(struct ast_context *con)
{
return ast_rwlock_wrlock(&con->lock);
}
int ast_rdlock_context(struct ast_context *con)
{
return ast_rwlock_rdlock(&con->lock);
}
int ast_unlock_context(struct ast_context *con)
{
return ast_rwlock_unlock(&con->lock);
}
/*
* Name functions ...
*/
const char *ast_get_context_name(struct ast_context *con)
{
return con ? con->name : NULL;
}
struct ast_context *ast_get_extension_context(struct ast_exten *exten)
{
return exten ? exten->parent : NULL;
}
const char *ast_get_extension_name(struct ast_exten *exten)
{
return exten ? exten->exten : NULL;
}
const char *ast_get_extension_label(struct ast_exten *exten)
{
return exten ? exten->label : NULL;
}
const char *ast_get_include_name(struct ast_include *inc)
{
return inc ? inc->name : NULL;
}
const char *ast_get_ignorepat_name(struct ast_ignorepat *ip)
{
return ip ? ip->pattern : NULL;
}
int ast_get_extension_priority(struct ast_exten *exten)
{
return exten ? exten->priority : -1;
}
/*
* Registrar info functions ...
*/
const char *ast_get_context_registrar(struct ast_context *c)
{
return c ? c->registrar : NULL;
}
const char *ast_get_extension_registrar(struct ast_exten *e)
{
return e ? e->registrar : NULL;
}
const char *ast_get_include_registrar(struct ast_include *i)
{
return i ? i->registrar : NULL;
}
const char *ast_get_ignorepat_registrar(struct ast_ignorepat *ip)
{
return ip ? ip->registrar : NULL;
}
int ast_get_extension_matchcid(struct ast_exten *e)
{
return e ? e->matchcid : 0;
}
const char *ast_get_extension_cidmatch(struct ast_exten *e)
{
return e ? e->cidmatch : NULL;
}
const char *ast_get_extension_app(struct ast_exten *e)
{
return e ? e->app : NULL;
}
void *ast_get_extension_app_data(struct ast_exten *e)
{
return e ? e->data : NULL;
}
const char *ast_get_switch_name(struct ast_sw *sw)
{
return sw ? sw->name : NULL;
}
const char *ast_get_switch_data(struct ast_sw *sw)
{
return sw ? sw->data : NULL;
}
int ast_get_switch_eval(struct ast_sw *sw)
{
return sw->eval;
}
const char *ast_get_switch_registrar(struct ast_sw *sw)
{
return sw ? sw->registrar : NULL;
}
/*
* Walking functions ...
*/
struct ast_context *ast_walk_contexts(struct ast_context *con)
{
return con ? con->next : contexts;
}
struct ast_exten *ast_walk_context_extensions(struct ast_context *con,
struct ast_exten *exten)
{
if (!exten)
return con ? con->root : NULL;
else
return exten->next;
}
struct ast_sw *ast_walk_context_switches(struct ast_context *con,
struct ast_sw *sw)
{
if (!sw)
return con ? AST_LIST_FIRST(&con->alts) : NULL;
else
return AST_LIST_NEXT(sw, list);
}
struct ast_exten *ast_walk_extension_priorities(struct ast_exten *exten,
struct ast_exten *priority)
{
return priority ? priority->peer : exten;
}
struct ast_include *ast_walk_context_includes(struct ast_context *con,
struct ast_include *inc)
{
if (!inc)
return con ? con->includes : NULL;
else
return inc->next;
}
struct ast_ignorepat *ast_walk_context_ignorepats(struct ast_context *con,
struct ast_ignorepat *ip)
{
if (!ip)
return con ? con->ignorepats : NULL;
else
return ip->next;
}
int ast_context_verify_includes(struct ast_context *con)
{
struct ast_include *inc = NULL;
int res = 0;
while ( (inc = ast_walk_context_includes(con, inc)) ) {
if (ast_context_find(inc->rname))
continue;
res = -1;
ast_log(LOG_WARNING, "Context '%s' tries to include nonexistent context '%s'\n",
ast_get_context_name(con), inc->rname);
break;
}
return res;
}
static int __ast_goto_if_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, int async)
{
int (*goto_func)(struct ast_channel *chan, const char *context, const char *exten, int priority);
if (!chan)
return -2;
if (context == NULL)
context = chan->context;
if (exten == NULL)
exten = chan->exten;
goto_func = (async) ? ast_async_goto : ast_explicit_goto;
if (ast_exists_extension(chan, context, exten, priority,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)))
return goto_func(chan, context, exten, priority);
else {
return AST_PBX_GOTO_FAILED;
}
}
int ast_goto_if_exists(struct ast_channel *chan, const char* context, const char *exten, int priority)
{
return __ast_goto_if_exists(chan, context, exten, priority, 0);
}
int ast_async_goto_if_exists(struct ast_channel *chan, const char * context, const char *exten, int priority)
{
return __ast_goto_if_exists(chan, context, exten, priority, 1);
}
static int pbx_parseable_goto(struct ast_channel *chan, const char *goto_string, int async)
{
char *exten, *pri, *context;
char *stringp;
int ipri;
int mode = 0;
if (ast_strlen_zero(goto_string)) {
ast_log(LOG_WARNING, "Goto requires an argument ([[context,]extension,]priority)\n");
return -1;
}
stringp = ast_strdupa(goto_string);
context = strsep(&stringp, ","); /* guaranteed non-null */
exten = strsep(&stringp, ",");
pri = strsep(&stringp, ",");
if (!exten) { /* Only a priority in this one */
pri = context;
exten = NULL;
context = NULL;
} else if (!pri) { /* Only an extension and priority in this one */
pri = exten;
exten = context;
context = NULL;
}
if (*pri == '+') {
mode = 1;
pri++;
} else if (*pri == '-') {
mode = -1;
pri++;
}
if (sscanf(pri, "%30d", &ipri) != 1) {
ipri = ast_findlabel_extension(chan, context ? context : chan->context,
exten ? exten : chan->exten, pri,
S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL));
if (ipri < 1) {
ast_log(LOG_WARNING, "Priority '%s' must be a number > 0, or valid label\n", pri);
return -1;
} else
mode = 0;
}
/* At this point we have a priority and maybe an extension and a context */
if (mode)
ipri = chan->priority + (ipri * mode);
if (async)
ast_async_goto(chan, context, exten, ipri);
else
ast_explicit_goto(chan, context, exten, ipri);
return 0;
}
int ast_parseable_goto(struct ast_channel *chan, const char *goto_string)
{
return pbx_parseable_goto(chan, goto_string, 0);
}
int ast_async_parseable_goto(struct ast_channel *chan, const char *goto_string)
{
return pbx_parseable_goto(chan, goto_string, 1);
}
char *ast_complete_applications(const char *line, const char *word, int state)
{
struct ast_app *app = NULL;
int which = 0;
char *ret = NULL;
size_t wordlen = strlen(word);
AST_RWLIST_RDLOCK(&apps);
AST_RWLIST_TRAVERSE(&apps, app, list) {
if (!strncasecmp(word, app->name, wordlen) && ++which > state) {
ret = ast_strdup(app->name);
break;
}
}
AST_RWLIST_UNLOCK(&apps);
return ret;
}
static int hint_hash(const void *obj, const int flags)
{
const struct ast_hint *hint = obj;
const char *exten_name;
int res;
exten_name = ast_get_extension_name(hint->exten);
if (ast_strlen_zero(exten_name)) {
/*
* If the exten or extension name isn't set, return 0 so that
* the ao2_find() search will start in the first bucket.
*/
res = 0;
} else {
res = ast_str_case_hash(exten_name);
}
return res;
}
static int hint_cmp(void *obj, void *arg, int flags)
{
const struct ast_hint *hint = obj;
const struct ast_exten *exten = arg;
return (hint->exten == exten) ? CMP_MATCH | CMP_STOP : 0;
}
static int statecbs_cmp(void *obj, void *arg, int flags)
{
const struct ast_state_cb *state_cb = obj;
ast_state_cb_type change_cb = arg;
return (state_cb->change_cb == change_cb) ? CMP_MATCH | CMP_STOP : 0;
}
static void pbx_shutdown(void)
{
if (hints) {
ao2_ref(hints, -1);
hints = NULL;
}
if (statecbs) {
ao2_ref(statecbs, -1);
statecbs = NULL;
}
if (contexts_table) {
ast_hashtab_destroy(contexts_table, NULL);
}
pbx_builtin_clear_globals();
}
int ast_pbx_init(void)
{
hints = ao2_container_alloc(HASH_EXTENHINT_SIZE, hint_hash, hint_cmp);
statecbs = ao2_container_alloc(1, NULL, statecbs_cmp);
ast_register_atexit(pbx_shutdown);
return (hints && statecbs) ? 0 : -1;
}
| Java |
/*jshint strict: false */
/*global chrome */
var merge = require('./merge');
exports.extend = require('pouchdb-extend');
exports.ajax = require('./deps/ajax');
exports.createBlob = require('./deps/blob');
exports.uuid = require('./deps/uuid');
exports.getArguments = require('argsarray');
var buffer = require('./deps/buffer');
var errors = require('./deps/errors');
var EventEmitter = require('events').EventEmitter;
var collections = require('./deps/collections');
exports.Map = collections.Map;
exports.Set = collections.Set;
if (typeof global.Promise === 'function') {
exports.Promise = global.Promise;
} else {
exports.Promise = require('bluebird');
}
var Promise = exports.Promise;
function toObject(array) {
var obj = {};
array.forEach(function (item) { obj[item] = true; });
return obj;
}
// List of top level reserved words for doc
var reservedWords = toObject([
'_id',
'_rev',
'_attachments',
'_deleted',
'_revisions',
'_revs_info',
'_conflicts',
'_deleted_conflicts',
'_local_seq',
'_rev_tree',
//replication documents
'_replication_id',
'_replication_state',
'_replication_state_time',
'_replication_state_reason',
'_replication_stats'
]);
// List of reserved words that should end up the document
var dataWords = toObject([
'_attachments',
//replication documents
'_replication_id',
'_replication_state',
'_replication_state_time',
'_replication_state_reason',
'_replication_stats'
]);
exports.lastIndexOf = function (str, char) {
for (var i = str.length - 1; i >= 0; i--) {
if (str.charAt(i) === char) {
return i;
}
}
return -1;
};
exports.clone = function (obj) {
return exports.extend(true, {}, obj);
};
exports.inherits = require('inherits');
// Determine id an ID is valid
// - invalid IDs begin with an underescore that does not begin '_design' or
// '_local'
// - any other string value is a valid id
// Returns the specific error object for each case
exports.invalidIdError = function (id) {
var err;
if (!id) {
err = new TypeError(errors.MISSING_ID.message);
err.status = 412;
} else if (typeof id !== 'string') {
err = new TypeError(errors.INVALID_ID.message);
err.status = 400;
} else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
err = new TypeError(errors.RESERVED_ID.message);
err.status = 400;
}
if (err) {
throw err;
}
};
function isChromeApp() {
return (typeof chrome !== "undefined" &&
typeof chrome.storage !== "undefined" &&
typeof chrome.storage.local !== "undefined");
}
// Pretty dumb name for a function, just wraps callback calls so we dont
// to if (callback) callback() everywhere
exports.call = exports.getArguments(function (args) {
if (!args.length) {
return;
}
var fun = args.shift();
if (typeof fun === 'function') {
fun.apply(this, args);
}
});
exports.isLocalId = function (id) {
return (/^_local/).test(id);
};
// check if a specific revision of a doc has been deleted
// - metadata: the metadata object from the doc store
// - rev: (optional) the revision to check. defaults to winning revision
exports.isDeleted = function (metadata, rev) {
if (!rev) {
rev = merge.winningRev(metadata);
}
var dashIndex = rev.indexOf('-');
if (dashIndex !== -1) {
rev = rev.substring(dashIndex + 1);
}
var deleted = false;
merge.traverseRevTree(metadata.rev_tree,
function (isLeaf, pos, id, acc, opts) {
if (id === rev) {
deleted = !!opts.deleted;
}
});
return deleted;
};
exports.revExists = function (metadata, rev) {
var found = false;
merge.traverseRevTree(metadata.rev_tree, function (leaf, pos, id, acc, opts) {
if ((pos + '-' + id) === rev) {
found = true;
}
});
return found;
};
exports.filterChange = function (opts) {
return function (change) {
var req = {};
var hasFilter = opts.filter && typeof opts.filter === 'function';
req.query = opts.query_params;
if (opts.filter && hasFilter && !opts.filter.call(this, change.doc, req)) {
return false;
}
if (opts.doc_ids && opts.doc_ids.indexOf(change.id) === -1) {
return false;
}
if (!opts.include_docs) {
delete change.doc;
} else {
for (var att in change.doc._attachments) {
if (change.doc._attachments.hasOwnProperty(att)) {
change.doc._attachments[att].stub = true;
}
}
}
return true;
};
};
// Preprocess documents, parse their revisions, assign an id and a
// revision for new writes that are missing them, etc
exports.parseDoc = function (doc, newEdits) {
var nRevNum;
var newRevId;
var revInfo;
var error;
var opts = {status: 'available'};
if (doc._deleted) {
opts.deleted = true;
}
if (newEdits) {
if (!doc._id) {
doc._id = exports.uuid();
}
newRevId = exports.uuid(32, 16).toLowerCase();
if (doc._rev) {
revInfo = /^(\d+)-(.+)$/.exec(doc._rev);
if (!revInfo) {
var err = new TypeError("invalid value for property '_rev'");
err.status = 400;
}
doc._rev_tree = [{
pos: parseInt(revInfo[1], 10),
ids: [revInfo[2], {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = parseInt(revInfo[1], 10) + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = [{
pos: doc._revisions.start - doc._revisions.ids.length + 1,
ids: doc._revisions.ids.reduce(function (acc, x) {
if (acc === null) {
return [x, opts, []];
} else {
return [x, {status: 'missing'}, [acc]];
}
}, null)
}];
nRevNum = doc._revisions.start;
newRevId = doc._revisions.ids[0];
}
if (!doc._rev_tree) {
revInfo = /^(\d+)-(.+)$/.exec(doc._rev);
if (!revInfo) {
error = new TypeError(errors.BAD_ARG.message);
error.status = errors.BAD_ARG.status;
throw error;
}
nRevNum = parseInt(revInfo[1], 10);
newRevId = revInfo[2];
doc._rev_tree = [{
pos: parseInt(revInfo[1], 10),
ids: [revInfo[2], opts, []]
}];
}
}
exports.invalidIdError(doc._id);
doc._rev = [nRevNum, newRevId].join('-');
var result = {metadata : {}, data : {}};
for (var key in doc) {
if (doc.hasOwnProperty(key)) {
var specialKey = key[0] === '_';
if (specialKey && !reservedWords[key]) {
error = new Error(errors.DOC_VALIDATION.message + ': ' + key);
error.status = errors.DOC_VALIDATION.status;
throw error;
} else if (specialKey && !dataWords[key]) {
result.metadata[key.slice(1)] = doc[key];
} else {
result.data[key] = doc[key];
}
}
}
return result;
};
exports.isCordova = function () {
return (typeof cordova !== "undefined" ||
typeof PhoneGap !== "undefined" ||
typeof phonegap !== "undefined");
};
exports.hasLocalStorage = function () {
if (isChromeApp()) {
return false;
}
try {
return global.localStorage;
} catch (e) {
return false;
}
};
exports.Changes = Changes;
exports.inherits(Changes, EventEmitter);
function Changes() {
if (!(this instanceof Changes)) {
return new Changes();
}
var self = this;
EventEmitter.call(this);
this.isChrome = isChromeApp();
this.listeners = {};
this.hasLocal = false;
if (!this.isChrome) {
this.hasLocal = exports.hasLocalStorage();
}
if (this.isChrome) {
chrome.storage.onChanged.addListener(function (e) {
// make sure it's event addressed to us
if (e.db_name != null) {
//object only has oldValue, newValue members
self.emit(e.dbName.newValue);
}
});
} else if (this.hasLocal) {
if (global.addEventListener) {
global.addEventListener("storage", function (e) {
self.emit(e.key);
});
} else {
global.attachEvent("storage", function (e) {
self.emit(e.key);
});
}
}
}
Changes.prototype.addListener = function (dbName, id, db, opts) {
if (this.listeners[id]) {
return;
}
function eventFunction() {
db.changes({
include_docs: opts.include_docs,
conflicts: opts.conflicts,
continuous: false,
descending: false,
filter: opts.filter,
view: opts.view,
since: opts.since,
query_params: opts.query_params,
onChange: function (c) {
if (c.seq > opts.since && !opts.cancelled) {
opts.since = c.seq;
exports.call(opts.onChange, c);
}
}
});
}
this.listeners[id] = eventFunction;
this.on(dbName, eventFunction);
};
Changes.prototype.removeListener = function (dbName, id) {
if (!(id in this.listeners)) {
return;
}
EventEmitter.prototype.removeListener.call(this, dbName,
this.listeners[id]);
};
Changes.prototype.notifyLocalWindows = function (dbName) {
//do a useless change on a storage thing
//in order to get other windows's listeners to activate
if (this.isChrome) {
chrome.storage.local.set({dbName: dbName});
} else if (this.hasLocal) {
localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
}
};
Changes.prototype.notify = function (dbName) {
this.emit(dbName);
this.notifyLocalWindows(dbName);
};
if (!process.browser || !('atob' in global)) {
exports.atob = function (str) {
var base64 = new buffer(str, 'base64');
// Node.js will just skip the characters it can't encode instead of
// throwing and exception
if (base64.toString('base64') !== str) {
throw ("Cannot base64 encode full string");
}
return base64.toString('binary');
};
} else {
exports.atob = function (str) {
return atob(str);
};
}
if (!process.browser || !('btoa' in global)) {
exports.btoa = function (str) {
return new buffer(str, 'binary').toString('base64');
};
} else {
exports.btoa = function (str) {
return btoa(str);
};
}
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
exports.fixBinary = function (bin) {
if (!process.browser) {
// don't need to do this in Node
return bin;
}
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
};
// shim for browsers that don't support it
exports.readAsBinaryString = function (blob, callback) {
var reader = new FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(exports.arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
};
exports.once = function (fun) {
var called = false;
return exports.getArguments(function (args) {
if (called) {
throw new Error('once called more than once');
} else {
called = true;
fun.apply(this, args);
}
});
};
exports.toPromise = function (func) {
//create the function we will be returning
return exports.getArguments(function (args) {
var self = this;
var tempCB =
(typeof args[args.length - 1] === 'function') ? args.pop() : false;
// if the last argument is a function, assume its a callback
var usedCB;
if (tempCB) {
// if it was a callback, create a new callback which calls it,
// but do so async so we don't trap any errors
usedCB = function (err, resp) {
process.nextTick(function () {
tempCB(err, resp);
});
};
}
var promise = new Promise(function (fulfill, reject) {
var resp;
try {
var callback = exports.once(function (err, mesg) {
if (err) {
reject(err);
} else {
fulfill(mesg);
}
});
// create a callback for this invocation
// apply the function in the orig context
args.push(callback);
resp = func.apply(self, args);
if (resp && typeof resp.then === 'function') {
fulfill(resp);
}
} catch (e) {
reject(e);
}
});
// if there is a callback, call it back
if (usedCB) {
promise.then(function (result) {
usedCB(null, result);
}, usedCB);
}
promise.cancel = function () {
return this;
};
return promise;
});
};
exports.adapterFun = function (name, callback) {
return exports.toPromise(exports.getArguments(function (args) {
if (this._closed) {
return Promise.reject(new Error('database is closed'));
}
var self = this;
if (!this.taskqueue.isReady) {
return new exports.Promise(function (fulfill, reject) {
self.taskqueue.addTask(function (failed) {
if (failed) {
reject(failed);
} else {
fulfill(self[name].apply(self, args));
}
});
});
}
return callback.apply(this, args);
}));
};
//Can't find original post, but this is close
//http://stackoverflow.com/questions/6965107/ (continues on next line)
//converting-between-strings-and-arraybuffers
exports.arrayBufferToBinaryString = function (buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return binary;
};
exports.cancellableFun = function (fun, self, opts) {
opts = opts ? exports.clone(true, {}, opts) : {};
var emitter = new EventEmitter();
var oldComplete = opts.complete || function () { };
var complete = opts.complete = exports.once(function (err, resp) {
if (err) {
oldComplete(err);
} else {
emitter.emit('end', resp);
oldComplete(null, resp);
}
emitter.removeAllListeners();
});
var oldOnChange = opts.onChange || function () {};
var lastChange = 0;
self.on('destroyed', function () {
emitter.removeAllListeners();
});
opts.onChange = function (change) {
oldOnChange(change);
if (change.seq <= lastChange) {
return;
}
lastChange = change.seq;
emitter.emit('change', change);
if (change.deleted) {
emitter.emit('delete', change);
} else if (change.changes.length === 1 &&
change.changes[0].rev.slice(0, 1) === '1-') {
emitter.emit('create', change);
} else {
emitter.emit('update', change);
}
};
var promise = new Promise(function (fulfill, reject) {
opts.complete = function (err, res) {
if (err) {
reject(err);
} else {
fulfill(res);
}
};
});
promise.then(function (result) {
complete(null, result);
}, complete);
// this needs to be overwridden by caller, dont fire complete until
// the task is ready
promise.cancel = function () {
promise.isCancelled = true;
if (self.taskqueue.isReady) {
opts.complete(null, {status: 'cancelled'});
}
};
if (!self.taskqueue.isReady) {
self.taskqueue.addTask(function () {
if (promise.isCancelled) {
opts.complete(null, {status: 'cancelled'});
} else {
fun(self, opts, promise);
}
});
} else {
fun(self, opts, promise);
}
promise.on = emitter.on.bind(emitter);
promise.once = emitter.once.bind(emitter);
promise.addListener = emitter.addListener.bind(emitter);
promise.removeListener = emitter.removeListener.bind(emitter);
promise.removeAllListeners = emitter.removeAllListeners.bind(emitter);
promise.setMaxListeners = emitter.setMaxListeners.bind(emitter);
promise.listeners = emitter.listeners.bind(emitter);
promise.emit = emitter.emit.bind(emitter);
return promise;
};
exports.MD5 = exports.toPromise(require('./deps/md5'));
// designed to give info to browser users, who are disturbed
// when they see 404s in the console
exports.explain404 = function (str) {
if (process.browser && 'console' in global && 'info' in console) {
console.info('The above 404 is totally normal. ' +
str + '\n\u2665 the PouchDB team');
}
};
exports.parseUri = require('./deps/parse-uri');
exports.compare = function (left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}; | Java |
/**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark 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.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01168")
public class BenchmarkTest01168 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
boolean flag = true;
java.util.Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements() && flag) {
String name = (String) names.nextElement();
java.util.Enumeration<String> values = request.getHeaders(name);
if (values != null) {
while (values.hasMoreElements() && flag) {
String value = (String) values.nextElement();
if (value.equals("vector")) {
param = name;
flag = false;
}
}
}
}
String bar = new Test().doSomething(param);
try {
java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG");
double rand = getNextNumber(numGen);
String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
String user = "SafeDonatella";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
}
double getNextNumber(java.util.Random generator) {
return generator.nextDouble();
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns constant to bar on true condition
int num = 86;
if ( (7*42) - num > 200 )
bar = "This_should_always_happen";
else bar = param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| Java |
# axios
[](https://www.npmjs.org/package/axios)
[](https://travis-ci.org/mzabriskie/axios)
[](https://coveralls.io/r/mzabriskie/axios)
[](https://www.npmjs.org/package/axios)
[](https://gitter.im/mzabriskie/axios)
Promise based HTTP client for the browser and node.js
## Features
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
- Make [http](http://nodejs.org/api/http.html) requests from node.js
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
- Intercept request and response
- Transform request and response data
- Automatic transforms for JSON data
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
## Browser Support
 |  |  |  |  |  |
--- | --- | --- | --- | --- | --- |
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
[](https://saucelabs.com/u/axios)
## Installing
Using cdn:
```html
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>
```
Using npm:
```bash
$ npm install axios
```
Using bower:
```bash
$ bower install axios
```
## Example
Performing a `GET` request
```js
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
```
Performing a `POST` request
```js
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
```
Performing multiple concurrent requests
```js
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
```
## axios API
Requests can be made by passing the relevant config to `axios`.
##### axios(config)
```js
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
```
##### axios(url[, config])
```js
// Send a GET request (default method)
axios('/user/12345');
```
### Request method aliases
For convenience aliases have been provided for all supported request methods.
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
##### axios.post(url[, data[, config]])
##### axios.put(url[, data[, config]])
##### axios.patch(url[, data[, config]])
###### NOTE
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
### Concurrency
Helper functions for dealing with concurrent requests.
##### axios.all(iterable)
##### axios.spread(callback)
### Creating an instance
You can create a new instance of axios with a custom config.
##### axios.create([config])
```js
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
```
### Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
##### axios#request(config)
##### axios#get(url[, config])
##### axios#delete(url[, config])
##### axios#head(url[, config])
##### axios#post(url[, data[, config]])
##### axios#put(url[, data[, config]])
##### axios#patch(url[, data[, config]])
## Request Config
These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
```js
{
// `url` is the server URL that will be used for the request
url: '/user',
// `method` is the request method to be used when making the request
method: 'get', // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/',
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string, an ArrayBuffer, or a Stream
transformRequest: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the request
params: {
ID: 12345
},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be a string, an ArrayBuffer, a hash, or a Stream
data: {
firstName: 'Fred'
},
// `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.
timeout: 1000,
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default
// `adapter` allows custom handling of requests which makes testing easier.
// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).
adapter: function (resolve, reject, config) {
/* ... */
},
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
// `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `progress` allows handling of progress events for 'POST' and 'PUT uploads'
// as well as 'GET' downloads
progress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength` defines the max size of the http response content allowed
maxContentLength: 2000,
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}
}
```
## Response Schema
The response for a request contains the following information.
```js
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {}
}
```
When using `then` or `catch`, you will receive the response as follows:
```js
axios.get('/user/12345')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
```
## Config Defaults
You can specify config defaults that will be applied to every request.
### Global axios defaults
```js
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```
### Custom instance defaults
```js
// Set config defaults when creating the instance
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
```
### Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in `lib/defaults.js`, then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.
```js
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
var instance = axios.create();
// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
timeout: 5000
});
```
## Interceptors
You can intercept requests or responses before they are handled by `then` or `catch`.
```js
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
```
If you may need to remove an interceptor later you can.
```js
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
```
You can add interceptors to a custom instance of axios.
```js
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
```
## Handling Errors
```js
axios.get('/user/12345')
.catch(function (response) {
if (response instanceof Error) {
// Something happened in setting up the request that triggered an Error
console.log('Error', response.message);
} else {
// The request was made, but the server responded with a status code
// that falls out of the range of 2xx
console.log(response.data);
console.log(response.status);
console.log(response.headers);
console.log(response.config);
}
});
```
You can define a custom HTTP status code error range using the `validateStatus` config option.
```js
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
```
## Semver
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
## Promises
axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
## TypeScript
axios includes a [TypeScript](http://typescriptlang.org) definition.
```typescript
/// <reference path="axios.d.ts" />
import * as axios from 'axios';
axios.get('/user?ID=12345');
```
## Resources
* [Changelog](https://github.com/mzabriskie/axios/blob/master/CHANGELOG.md)
* [Ecosystem](https://github.com/mzabriskie/axios/blob/master/ECOSYSTEM.md)
* [Contributing Guide](https://github.com/mzabriskie/axios/blob/master/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/mzabriskie/axios/blob/master/CODE_OF_CONDUCT.md)
## Credits
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.
## License
MIT
| Java |
/* Minimal malloc implementation for interposition tests.
Copyright (C) 2016-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
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; see the file COPYING.LIB. If
not, see <http://www.gnu.org/licenses/>. */
#include "tst-interpose-aux.h"
#include <errno.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
#if INTERPOSE_THREADS
#include <pthread.h>
#endif
/* Print the error message and terminate the process with status 1. */
__attribute__ ((noreturn))
__attribute__ ((format (printf, 1, 2)))
static void *
fail (const char *format, ...)
{
/* This assumes that vsnprintf will not call malloc. It does not do
so for the format strings we use. */
char message[4096];
va_list ap;
va_start (ap, format);
vsnprintf (message, sizeof (message), format, ap);
va_end (ap);
enum { count = 3 };
struct iovec iov[count];
iov[0].iov_base = (char *) "error: ";
iov[1].iov_base = (char *) message;
iov[2].iov_base = (char *) "\n";
for (int i = 0; i < count; ++i)
iov[i].iov_len = strlen (iov[i].iov_base);
int unused __attribute__ ((unused));
unused = writev (STDOUT_FILENO, iov, count);
_exit (1);
}
#if INTERPOSE_THREADS
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static void
lock (void)
{
#if INTERPOSE_THREADS
int ret = pthread_mutex_lock (&mutex);
if (ret != 0)
{
errno = ret;
fail ("pthread_mutex_lock: %m");
}
#endif
}
static void
unlock (void)
{
#if INTERPOSE_THREADS
int ret = pthread_mutex_unlock (&mutex);
if (ret != 0)
{
errno = ret;
fail ("pthread_mutex_unlock: %m");
}
#endif
}
struct __attribute__ ((aligned (__alignof__ (max_align_t)))) allocation_header
{
size_t allocation_index;
size_t allocation_size;
};
/* Array of known allocations, to track invalid frees. */
enum { max_allocations = 65536 };
static struct allocation_header *allocations[max_allocations];
static size_t allocation_index;
static size_t deallocation_count;
/* Sanity check for successful malloc interposition. */
__attribute__ ((destructor))
static void
check_for_allocations (void)
{
if (allocation_index == 0)
{
/* Make sure that malloc is called at least once from libc. */
void *volatile ptr = strdup ("ptr");
/* Compiler barrier. The strdup function calls malloc, which
updates allocation_index, but strdup is marked __THROW, so
the compiler could optimize away the reload. */
__asm__ volatile ("" ::: "memory");
free (ptr);
/* If the allocation count is still zero, it means we did not
interpose malloc successfully. */
if (allocation_index == 0)
fail ("malloc does not seem to have been interposed");
}
}
static struct allocation_header *get_header (const char *op, void *ptr)
{
struct allocation_header *header = ((struct allocation_header *) ptr) - 1;
if (header->allocation_index >= allocation_index)
fail ("%s: %p: invalid allocation index: %zu (not less than %zu)",
op, ptr, header->allocation_index, allocation_index);
if (allocations[header->allocation_index] != header)
fail ("%s: %p: allocation pointer does not point to header, but %p",
op, ptr, allocations[header->allocation_index]);
return header;
}
/* Internal helper functions. Those must be called while the lock is
acquired. */
static void *
malloc_internal (size_t size)
{
if (allocation_index == max_allocations)
{
errno = ENOMEM;
return NULL;
}
size_t allocation_size = size + sizeof (struct allocation_header);
if (allocation_size < size)
{
errno = ENOMEM;
return NULL;
}
size_t index = allocation_index++;
void *result = mmap (NULL, allocation_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (result == MAP_FAILED)
return NULL;
allocations[index] = result;
*allocations[index] = (struct allocation_header)
{
.allocation_index = index,
.allocation_size = allocation_size
};
return allocations[index] + 1;
}
static void
free_internal (const char *op, struct allocation_header *header)
{
size_t index = header->allocation_index;
int result = mprotect (header, header->allocation_size, PROT_NONE);
if (result != 0)
fail ("%s: mprotect (%p, %zu): %m", op, header, header->allocation_size);
/* Catch double-free issues. */
allocations[index] = NULL;
++deallocation_count;
}
static void *
realloc_internal (void *ptr, size_t new_size)
{
struct allocation_header *header = get_header ("realloc", ptr);
size_t old_size = header->allocation_size - sizeof (struct allocation_header);
if (old_size >= new_size)
return ptr;
void *newptr = malloc_internal (new_size);
if (newptr == NULL)
return NULL;
memcpy (newptr, ptr, old_size);
free_internal ("realloc", header);
return newptr;
}
/* Public interfaces. These functions must perform locking. */
size_t
malloc_allocation_count (void)
{
lock ();
size_t count = allocation_index;
unlock ();
return count;
}
size_t
malloc_deallocation_count (void)
{
lock ();
size_t count = deallocation_count;
unlock ();
return count;
}
void *
malloc (size_t size)
{
lock ();
void *result = malloc_internal (size);
unlock ();
return result;
}
void
free (void *ptr)
{
if (ptr == NULL)
return;
lock ();
struct allocation_header *header = get_header ("free", ptr);
free_internal ("free", header);
unlock ();
}
void *
calloc (size_t a, size_t b)
{
if (b > 0 && a > SIZE_MAX / b)
{
errno = ENOMEM;
return NULL;
}
lock ();
/* malloc_internal uses mmap, so the memory is zeroed. */
void *result = malloc_internal (a * b);
unlock ();
return result;
}
void *
realloc (void *ptr, size_t n)
{
if (n ==0)
{
free (ptr);
return NULL;
}
else if (ptr == NULL)
return malloc (n);
else
{
lock ();
void *result = realloc_internal (ptr, n);
unlock ();
return result;
}
}
| Java |
/*
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
[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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Apr 18, 2009
*/
package com.bigdata.relation.accesspath;
import junit.framework.TestCase2;
import com.bigdata.striterator.IChunkedIterator;
/**
* @author <a href="mailto:[email protected]">Bryan Thompson</a>
* @version $Id$
*/
public class TestUnsynchronizedUnboundedChunkBuffer extends TestCase2 {
/**
*
*/
public TestUnsynchronizedUnboundedChunkBuffer() {
}
/**
* @param arg0
*/
public TestUnsynchronizedUnboundedChunkBuffer(String arg0) {
super(arg0);
}
/**
* Test empty iterator.
*/
public void test_emptyIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
// the iterator is initially empty.
assertFalse(buffer.iterator().hasNext());
}
/**
* Verify that elements are flushed when an iterator is requested so
* that they will be visited by the iterator.
*/
public void test_bufferFlushedByIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
assertSameIterator(new String[] { "a" }, buffer.iterator());
}
/**
* Verify that the iterator has snapshot semantics.
*/
public void test_snapshotIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.add("b");
buffer.add("c");
// visit once.
assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator());
// will visit again.
assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator());
}
/**
* Verify iterator visits chunks as placed onto the queue.
*/
public void test_chunkedIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.flush();
buffer.add("b");
buffer.add("c");
// visit once.
assertSameChunkedIterator(new String[][] { new String[] { "a" },
new String[] { "b", "c" } }, buffer.iterator());
}
/**
* Test class of chunks created by the iterator (the array class should be
* taken from the first visited chunk's class).
*/
// @SuppressWarnings("unchecked")
public void test_chunkClass() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.flush();
buffer.add("b");
buffer.add("c");
// visit once.
assertSameChunkedIterator(new String[][] { new String[] { "a" },
new String[] { "b", "c" } }, buffer.iterator());
}
/**
* Verify that the iterator visits the expected chunks in the expected
* order.
*
* @param <E>
* @param chunks
* @param itr
*/
protected <E> void assertSameChunkedIterator(final E[][] chunks,
final IChunkedIterator<E> itr) {
for(E[] chunk : chunks) {
assertTrue(itr.hasNext());
final E[] actual = itr.nextChunk();
assertSameArray(chunk, actual);
}
assertFalse(itr.hasNext());
}
}
| Java |
/*******************************************************************************
* Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved.
* <p>
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or any later version.
* <p>
* 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.
* <p>
* 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.
*******************************************************************************/
package edu.cornell.cs.nlp.spf.parser.ccg.rules.coordination;
import edu.cornell.cs.nlp.spf.ccg.categories.Category;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.ComplexSyntax;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Slash;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Syntax;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.IBinaryParseRule;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.ParseRuleResult;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.SentenceSpan;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName.Direction;
class C2Rule<MR> implements IBinaryParseRule<MR> {
private static final RuleName RULE_NAME = RuleName
.create("c2",
Direction.FORWARD);
private static final long serialVersionUID = 1876084168220307197L;
private final ICoordinationServices<MR> services;
public C2Rule(ICoordinationServices<MR> services) {
this.services = services;
}
@Override
public ParseRuleResult<MR> apply(Category<MR> left, Category<MR> right,
SentenceSpan span) {
if (left.getSyntax().equals(Syntax.C)
&& SyntaxCoordinationServices.isCoordinationOfType(
right.getSyntax(), null)) {
final MR semantics = services.expandCoordination(right
.getSemantics());
if (semantics != null) {
return new ParseRuleResult<MR>(RULE_NAME,
Category.create(
new ComplexSyntax(right.getSyntax(),
SyntaxCoordinationServices
.getCoordinationType(right
.getSyntax()),
Slash.BACKWARD), semantics));
}
}
return null;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
final C2Rule other = (C2Rule) obj;
if (services == null) {
if (other.services != null) {
return false;
}
} else if (!services.equals(other.services)) {
return false;
}
return true;
}
@Override
public RuleName getName() {
return RULE_NAME;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ (RULE_NAME == null ? 0 : RULE_NAME.hashCode());
result = prime * result + (services == null ? 0 : services.hashCode());
return result;
}
}
| Java |
<?php
// https://raw.github.com/facebook/php-sdk/master/src/facebook.php
// modified
// Facebook PHP SDK (v.3.1.1)
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
/**
* Identical to the parent constructor, except that
* we start a PHP session to store the user ID and
* access token if during the course of execution
* we discover them.
*
* @param Array $config the application configuration.
* @see BaseFacebook::__construct in facebook.php
*/
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
}
protected static $kSupportedKeys =
array('state', 'code', 'access_token', 'user_id');
/**
* Provides the implementations of the inherited abstract
* methods. The implementation uses PHP sessions to maintain
* a store for authorization codes, user ids, CSRF states, and
* access tokens.
*/
protected function setPersistentData($key, $value) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to setPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
$_SESSION[$session_var_name] = $value;
}
protected function getPersistentData($key, $default = false) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to getPersistentData.');
return $default;
}
$session_var_name = $this->constructSessionVariableName($key);
return isset($_SESSION[$session_var_name]) ?
$_SESSION[$session_var_name] : $default;
}
protected function clearPersistentData($key) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to clearPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
unset($_SESSION[$session_var_name]);
}
protected function clearAllPersistentData() {
foreach (self::$kSupportedKeys as $key) {
$this->clearPersistentData($key);
}
}
protected function constructSessionVariableName($key) {
return implode('_', array('fb',
$this->getAppId(),
$key));
}
}
| Java |
/*
* linux/fs/ext4/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/jbd2.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/parser.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/random.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/ctype.h>
#include <linux/log2.h>
#include <linux/crc16.h>
#include <linux/cleancache.h>
#include <asm/uaccess.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include "ext4.h"
#include "ext4_extents.h" /* Needed for trace points definition */
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "mballoc.h"
#define CREATE_TRACE_POINTS
#include <trace/events/ext4.h>
static struct proc_dir_entry *ext4_proc_root;
static struct kset *ext4_kset;
static struct ext4_lazy_init *ext4_li_info;
static struct mutex ext4_li_mtx;
static struct ext4_features *ext4_feat;
static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
unsigned long journal_devnum);
static int ext4_show_options(struct seq_file *seq, struct dentry *root);
static int ext4_commit_super(struct super_block *sb, int sync);
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es);
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_sync_fs(struct super_block *sb, int wait);
static int ext4_sync_fs_nojournal(struct super_block *sb, int wait);
static int ext4_remount(struct super_block *sb, int *flags, char *data);
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ext4_unfreeze(struct super_block *sb);
static int ext4_freeze(struct super_block *sb);
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data);
static inline int ext2_feature_set_ok(struct super_block *sb);
static inline int ext3_feature_set_ok(struct super_block *sb);
static int ext4_feature_set_ok(struct super_block *sb, int readonly);
static void ext4_destroy_lazyinit_thread(void);
static void ext4_unregister_li_request(struct super_block *sb);
static void ext4_clear_request_list(void);
static int ext4_reserve_clusters(struct ext4_sb_info *, ext4_fsblk_t);
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
MODULE_ALIAS("ext2");
#define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
#else
#define IS_EXT2_SB(sb) (0)
#endif
#if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static struct file_system_type ext3_fs_type = {
.owner = THIS_MODULE,
.name = "ext3",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext3");
MODULE_ALIAS("ext3");
#define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
#else
#define IS_EXT3_SB(sb) (0)
#endif
static int ext4_verify_csum_type(struct super_block *sb,
struct ext4_super_block *es)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return 1;
return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
}
static __le32 ext4_superblock_csum(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct ext4_super_block, s_checksum);
__u32 csum;
csum = ext4_chksum(sbi, ~0, (char *)es, offset);
return cpu_to_le32(csum);
}
int ext4_superblock_csum_verify(struct super_block *sb,
struct ext4_super_block *es)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return 1;
return es->s_checksum == ext4_superblock_csum(sb, es);
}
void ext4_superblock_csum_set(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return;
es->s_checksum = ext4_superblock_csum(sb, es);
}
void *ext4_kvmalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kmalloc(size, flags);
if (!ret)
ret = __vmalloc(size, flags, PAGE_KERNEL);
return ret;
}
void *ext4_kvzalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kzalloc(size, flags);
if (!ret)
ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
return ret;
}
void ext4_kvfree(void *ptr)
{
if (is_vmalloc_addr(ptr))
vfree(ptr);
else
kfree(ptr);
}
ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_block_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_table_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
}
__u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_blocks_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
}
__u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_inodes_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
}
__u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_used_dirs_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
}
__u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_itable_unused_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
}
void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
}
void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
}
void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
}
void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
}
void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
}
static void __save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
es->s_last_error_time = cpu_to_le32(get_seconds());
strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
es->s_last_error_line = cpu_to_le32(line);
if (!es->s_first_error_time) {
es->s_first_error_time = es->s_last_error_time;
strncpy(es->s_first_error_func, func,
sizeof(es->s_first_error_func));
es->s_first_error_line = cpu_to_le32(line);
es->s_first_error_ino = es->s_last_error_ino;
es->s_first_error_block = es->s_last_error_block;
}
/*
* Start the daily error reporting function if it hasn't been
* started already
*/
if (!es->s_error_count)
mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
le32_add_cpu(&es->s_error_count, 1);
}
static void save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
__save_error_info(sb, func, line);
ext4_commit_super(sb, 1);
}
/*
* The del_gendisk() function uninitializes the disk-specific data
* structures, including the bdi structure, without telling anyone
* else. Once this happens, any attempt to call mark_buffer_dirty()
* (for example, by ext4_commit_super), will cause a kernel OOPS.
* This is a kludge to prevent these oops until we can put in a proper
* hook in del_gendisk() to inform the VFS and file system layers.
*/
static int block_device_ejected(struct super_block *sb)
{
struct inode *bd_inode = sb->s_bdev->bd_inode;
struct backing_dev_info *bdi = bd_inode->i_mapping->backing_dev_info;
return bdi->dev == NULL;
}
static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int error = is_journal_aborted(journal);
struct ext4_journal_cb_entry *jce;
BUG_ON(txn->t_state == T_FINISHED);
spin_lock(&sbi->s_md_lock);
while (!list_empty(&txn->t_private_list)) {
jce = list_entry(txn->t_private_list.next,
struct ext4_journal_cb_entry, jce_list);
list_del_init(&jce->jce_list);
spin_unlock(&sbi->s_md_lock);
jce->jce_func(sb, jce, error);
spin_lock(&sbi->s_md_lock);
}
spin_unlock(&sbi->s_md_lock);
}
/* Deal with the reporting of failure conditions on a filesystem such as
* inconsistencies detected or read IO failures.
*
* On ext2, we can store the error state of the filesystem in the
* superblock. That is not possible on ext4, because we may have other
* write ordering constraints on the superblock which prevent us from
* writing it out straight away; and given that the journal is about to
* be aborted, we can't rely on the current, or future, transactions to
* write out the superblock safely.
*
* We'll just use the jbd2_journal_abort() error code to record an error in
* the journal instead. On recovery, the journal will complain about
* that error until we've noted it down and cleared it.
*/
static void ext4_handle_error(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return;
if (!test_opt(sb, ERRORS_CONT)) {
journal_t *journal = EXT4_SB(sb)->s_journal;
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
if (journal)
jbd2_journal_abort(journal, -EIO);
}
if (test_opt(sb, ERRORS_RO)) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
}
if (test_opt(sb, ERRORS_PANIC))
panic("EXT4-fs (device %s): panic forced after error\n",
sb->s_id);
}
void __ext4_error(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
sb->s_id, function, line, current->comm, &vaf);
va_end(args);
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
void __ext4_error_inode(struct inode *inode, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
es->s_last_error_block = cpu_to_le64(block);
save_error_info(inode->i_sb, function, line);
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: block %llu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, &vaf);
else
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, &vaf);
va_end(args);
ext4_handle_error(inode->i_sb);
}
void __ext4_error_file(struct file *file, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es;
struct inode *inode = file_inode(file);
char pathname[80], *path;
es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
save_error_info(inode->i_sb, function, line);
path = d_path(&(file->f_path), pathname, sizeof(pathname));
if (IS_ERR(path))
path = "(unknown)";
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"block %llu: comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, path, &vaf);
else
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, path, &vaf);
va_end(args);
ext4_handle_error(inode->i_sb);
}
const char *ext4_decode_error(struct super_block *sb, int errno,
char nbuf[16])
{
char *errstr = NULL;
switch (errno) {
case -EIO:
errstr = "IO failure";
break;
case -ENOMEM:
errstr = "Out of memory";
break;
case -EROFS:
if (!sb || (EXT4_SB(sb)->s_journal &&
EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
errstr = "Journal has aborted";
else
errstr = "Readonly filesystem";
break;
default:
/* If the caller passed in an extra buffer for unknown
* errors, textualise them now. Else we just return
* NULL. */
if (nbuf) {
/* Check for truncated error codes... */
if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
errstr = nbuf;
}
break;
}
return errstr;
}
/* __ext4_std_error decodes expected errors from journaling functions
* automatically and invokes the appropriate error response. */
void __ext4_std_error(struct super_block *sb, const char *function,
unsigned int line, int errno)
{
char nbuf[16];
const char *errstr;
/* Special case: if the error is EROFS, and we're not already
* inside a transaction, then there's really no point in logging
* an error. */
if (errno == -EROFS && journal_current_handle() == NULL &&
(sb->s_flags & MS_RDONLY))
return;
errstr = ext4_decode_error(sb, errno, nbuf);
printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
sb->s_id, function, line, errstr);
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
/*
* ext4_abort is a much stronger failure handler than ext4_error. The
* abort function may be used to deal with unrecoverable failures such
* as journal IO errors or ENOMEM at a critical moment in log management.
*
* We unconditionally force the filesystem into an ABORT|READONLY state,
* unless the error response on the fs has been set to panic in which
* case we take the easy way out and panic immediately.
*/
void __ext4_abort(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
va_list args;
save_error_info(sb, function, line);
va_start(args, fmt);
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: ", sb->s_id,
function, line);
vprintk(fmt, args);
printk("\n");
va_end(args);
if ((sb->s_flags & MS_RDONLY) == 0) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
if (EXT4_SB(sb)->s_journal)
jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
save_error_info(sb, function, line);
}
if (test_opt(sb, ERRORS_PANIC))
panic("EXT4-fs panic from previous error\n");
}
void __ext4_msg(struct super_block *sb,
const char *prefix, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
va_end(args);
}
void __ext4_warning(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
}
void __ext4_grp_locked_error(const char *function, unsigned int line,
struct super_block *sb, ext4_group_t grp,
unsigned long ino, ext4_fsblk_t block,
const char *fmt, ...)
__releases(bitlock)
__acquires(bitlock)
{
struct va_format vaf;
va_list args;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
es->s_last_error_ino = cpu_to_le32(ino);
es->s_last_error_block = cpu_to_le64(block);
__save_error_info(sb, function, line);
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
sb->s_id, function, line, grp);
if (ino)
printk(KERN_CONT "inode %lu: ", ino);
if (block)
printk(KERN_CONT "block %llu:", (unsigned long long) block);
printk(KERN_CONT "%pV\n", &vaf);
va_end(args);
if (test_opt(sb, ERRORS_CONT)) {
ext4_commit_super(sb, 0);
return;
}
ext4_unlock_group(sb, grp);
ext4_handle_error(sb);
/*
* We only get here in the ERRORS_RO case; relocking the group
* may be dangerous, but nothing bad will happen since the
* filesystem will have already been marked read/only and the
* journal has been aborted. We return 1 as a hint to callers
* who might what to use the return value from
* ext4_grp_locked_error() to distinguish between the
* ERRORS_CONT and ERRORS_RO case, and perhaps return more
* aggressively from the ext4 function in question, with a
* more appropriate error code.
*/
ext4_lock_group(sb, grp);
return;
}
void ext4_update_dynamic_rev(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
return;
ext4_warning(sb,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT4_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
/*
* Open the external journal device
*/
static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
{
struct block_device *bdev;
char b[BDEVNAME_SIZE];
bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
if (IS_ERR(bdev))
goto fail;
return bdev;
fail:
ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
__bdevname(dev, b), PTR_ERR(bdev));
return NULL;
}
/*
* Release the journal device
*/
static void ext4_blkdev_put(struct block_device *bdev)
{
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
}
static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
{
struct block_device *bdev;
bdev = sbi->journal_bdev;
if (bdev) {
ext4_blkdev_put(bdev);
sbi->journal_bdev = NULL;
}
}
static inline struct inode *orphan_list_entry(struct list_head *l)
{
return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
}
static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
{
struct list_head *l;
ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
le32_to_cpu(sbi->s_es->s_last_orphan));
printk(KERN_ERR "sb_info orphan list:\n");
list_for_each(l, &sbi->s_orphan) {
struct inode *inode = orphan_list_entry(l);
printk(KERN_ERR " "
"inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
inode->i_sb->s_id, inode->i_ino, inode,
inode->i_mode, inode->i_nlink,
NEXT_ORPHAN(inode));
}
}
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->unrsv_conversion_wq);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->unrsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_es_unregister_shrinker(sbi);
del_timer(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
ext4_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
if (sbi->s_proc) {
remove_proc_entry("options", sbi->s_proc);
remove_proc_entry(sb->s_id, ext4_proc_root);
}
kobject_del(&sbi->s_kobj);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
ext4_kvfree(sbi->s_group_desc);
ext4_kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
percpu_counter_destroy(&sbi->s_extent_cache_cnt);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
static struct kmem_cache *ext4_inode_cachep;
/*
* Called inside transaction, so use GFP_NOFS
*/
static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
ext4_es_init_tree(&ei->i_es_tree);
rwlock_init(&ei->i_es_lock);
INIT_LIST_HEAD(&ei->i_es_lru);
ei->i_es_lru_nr = 0;
ei->i_touch_when = 0;
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_da_metadata_calc_last_lblock = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
ei->jinode = NULL;
INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
INIT_LIST_HEAD(&ei->i_unrsv_conversion_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
atomic_set(&ei->i_ioend_count, 0);
atomic_set(&ei->i_unwritten, 0);
INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
INIT_WORK(&ei->i_unrsv_conversion_work, ext4_end_io_unrsv_work);
return &ei->vfs_inode;
}
static int ext4_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
trace_ext4_drop_inode(inode, drop);
return drop;
}
static void ext4_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
}
static void ext4_destroy_inode(struct inode *inode)
{
if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): orphan list check failed!",
inode->i_ino, EXT4_I(inode));
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
EXT4_I(inode), sizeof(struct ext4_inode_info),
true);
dump_stack();
}
call_rcu(&inode->i_rcu, ext4_i_callback);
}
static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
inode_init_once(&ei->vfs_inode);
}
static int init_inodecache(void)
{
ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
sizeof(struct ext4_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once);
if (ext4_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_inode_cachep);
}
void ext4_clear_inode(struct inode *inode)
{
invalidate_inode_buffers(inode);
clear_inode(inode);
dquot_drop(inode);
ext4_discard_preallocations(inode);
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
ext4_es_lru_del(inode);
if (EXT4_I(inode)->jinode) {
jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode);
jbd2_free_inode(EXT4_I(inode)->jinode);
EXT4_I(inode)->jinode = NULL;
}
}
static struct inode *ext4_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/* iget isn't really right if the inode is currently unallocated!!
*
* ext4_read_inode will return a bad_inode if the inode had been
* deleted, so we should be safe.
*
* Currently we don't know the generation for parent directory, so
* a generation of 0 means "accept any"
*/
inode = ext4_iget(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
/*
* Try to release metadata pages (indirect blocks, directories) which are
* mapped via the block device. Since these pages could have journal heads
* which would prevent try_to_free_buffers() from freeing them, we must use
* jbd2 layer's try_to_free_buffers() function to release them.
*/
static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
gfp_t wait)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
WARN_ON(PageChecked(page));
if (!page_has_buffers(page))
return 0;
if (journal)
return jbd2_journal_try_to_free_buffers(journal, page,
wait & ~__GFP_WAIT);
return try_to_free_buffers(page);
}
#ifdef CONFIG_QUOTA
#define QTYPE2NAME(t) ((t) == USRQUOTA ? "user" : "group")
#define QTYPE2MOPT(on, t) ((t) == USRQUOTA?((on)##USRJQUOTA):((on)##GRPJQUOTA))
static int ext4_write_dquot(struct dquot *dquot);
static int ext4_acquire_dquot(struct dquot *dquot);
static int ext4_release_dquot(struct dquot *dquot);
static int ext4_mark_dquot_dirty(struct dquot *dquot);
static int ext4_write_info(struct super_block *sb, int type);
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path);
static int ext4_quota_on_sysfile(struct super_block *sb, int type,
int format_id);
static int ext4_quota_off(struct super_block *sb, int type);
static int ext4_quota_off_sysfile(struct super_block *sb, int type);
static int ext4_quota_on_mount(struct super_block *sb, int type);
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off);
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off);
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags);
static int ext4_enable_quotas(struct super_block *sb);
static const struct dquot_operations ext4_quota_operations = {
.get_reserved_space = ext4_get_reserved_space,
.write_dquot = ext4_write_dquot,
.acquire_dquot = ext4_acquire_dquot,
.release_dquot = ext4_release_dquot,
.mark_dirty = ext4_mark_dquot_dirty,
.write_info = ext4_write_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
};
static const struct quotactl_ops ext4_qctl_operations = {
.quota_on = ext4_quota_on,
.quota_off = ext4_quota_off,
.quota_sync = dquot_quota_sync,
.get_info = dquot_get_dqinfo,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk
};
static const struct quotactl_ops ext4_qctl_sysfile_operations = {
.quota_on_meta = ext4_quota_on_sysfile,
.quota_off = ext4_quota_off_sysfile,
.quota_sync = dquot_quota_sync,
.get_info = dquot_get_dqinfo,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk
};
#endif
static const struct super_operations ext4_sops = {
.alloc_inode = ext4_alloc_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.put_super = ext4_put_super,
.sync_fs = ext4_sync_fs,
.freeze_fs = ext4_freeze,
.unfreeze_fs = ext4_unfreeze,
.statfs = ext4_statfs,
.remount_fs = ext4_remount,
.show_options = ext4_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
#endif
.bdev_try_to_free_page = bdev_try_to_free_page,
};
static const struct super_operations ext4_nojournal_sops = {
.alloc_inode = ext4_alloc_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.sync_fs = ext4_sync_fs_nojournal,
.put_super = ext4_put_super,
.statfs = ext4_statfs,
.remount_fs = ext4_remount,
.show_options = ext4_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
#endif
.bdev_try_to_free_page = bdev_try_to_free_page,
};
static const struct export_operations ext4_export_ops = {
.fh_to_dentry = ext4_fh_to_dentry,
.fh_to_parent = ext4_fh_to_parent,
.get_parent = ext4_get_parent,
};
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
Opt_nouid32, Opt_debug, Opt_removed,
Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
Opt_commit, Opt_min_batch_time, Opt_max_batch_time,
Opt_journal_dev, Opt_journal_checksum, Opt_journal_async_commit,
Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
Opt_data_err_abort, Opt_data_err_ignore,
Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
Opt_usrquota, Opt_grpquota, Opt_i_version,
Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit,
Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
Opt_inode_readahead_blks, Opt_journal_ioprio,
Opt_dioread_nolock, Opt_dioread_lock,
Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
Opt_max_dir_size_kb,
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_debug, "debug"},
{Opt_removed, "oldalloc"},
{Opt_removed, "orlov"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_noload, "norecovery"},
{Opt_noload, "noload"},
{Opt_removed, "nobh"},
{Opt_removed, "bh"},
{Opt_commit, "commit=%u"},
{Opt_min_batch_time, "min_batch_time=%u"},
{Opt_max_batch_time, "max_batch_time=%u"},
{Opt_journal_dev, "journal_dev=%u"},
{Opt_journal_checksum, "journal_checksum"},
{Opt_journal_async_commit, "journal_async_commit"},
{Opt_abort, "abort"},
{Opt_data_journal, "data=journal"},
{Opt_data_ordered, "data=ordered"},
{Opt_data_writeback, "data=writeback"},
{Opt_data_err_abort, "data_err=abort"},
{Opt_data_err_ignore, "data_err=ignore"},
{Opt_offusrjquota, "usrjquota="},
{Opt_usrjquota, "usrjquota=%s"},
{Opt_offgrpjquota, "grpjquota="},
{Opt_grpjquota, "grpjquota=%s"},
{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
{Opt_grpquota, "grpquota"},
{Opt_noquota, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_barrier, "barrier=%u"},
{Opt_barrier, "barrier"},
{Opt_nobarrier, "nobarrier"},
{Opt_i_version, "i_version"},
{Opt_stripe, "stripe=%u"},
{Opt_delalloc, "delalloc"},
{Opt_nodelalloc, "nodelalloc"},
{Opt_removed, "mblk_io_submit"},
{Opt_removed, "nomblk_io_submit"},
{Opt_block_validity, "block_validity"},
{Opt_noblock_validity, "noblock_validity"},
{Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
{Opt_journal_ioprio, "journal_ioprio=%u"},
{Opt_auto_da_alloc, "auto_da_alloc=%u"},
{Opt_auto_da_alloc, "auto_da_alloc"},
{Opt_noauto_da_alloc, "noauto_da_alloc"},
{Opt_dioread_nolock, "dioread_nolock"},
{Opt_dioread_lock, "dioread_lock"},
{Opt_discard, "discard"},
{Opt_nodiscard, "nodiscard"},
{Opt_init_itable, "init_itable=%u"},
{Opt_init_itable, "init_itable"},
{Opt_noinit_itable, "noinit_itable"},
{Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
{Opt_removed, "check=none"}, /* mount option from ext2/3 */
{Opt_removed, "nocheck"}, /* mount option from ext2/3 */
{Opt_removed, "reservation"}, /* mount option from ext2/3 */
{Opt_removed, "noreservation"}, /* mount option from ext2/3 */
{Opt_removed, "journal=%u"}, /* mount option from ext2/3 */
{Opt_err, NULL},
};
static ext4_fsblk_t get_sb_block(void **data)
{
ext4_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/* TODO: use simple_strtoll with >32bit ext4 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
#define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n"
"Contact [email protected] if you think we should keep it.\n";
#ifdef CONFIG_QUOTA
static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *qname;
int ret = -1;
if (sb_any_quota_loaded(sb) &&
!sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) {
ext4_msg(sb, KERN_ERR, "Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
qname = match_strdup(args);
if (!qname) {
ext4_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -1;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 1;
else
ext4_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
ext4_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sb, QUOTA);
return 1;
errout:
kfree(qname);
return ret;
}
static int clear_qf_name(struct super_block *sb, int qtype)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sb_any_quota_loaded(sb) &&
sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
" when quota turned on");
return -1;
}
kfree(sbi->s_qf_names[qtype]);
sbi->s_qf_names[qtype] = NULL;
return 1;
}
#endif
#define MOPT_SET 0x0001
#define MOPT_CLEAR 0x0002
#define MOPT_NOSUPPORT 0x0004
#define MOPT_EXPLICIT 0x0008
#define MOPT_CLEAR_ERR 0x0010
#define MOPT_GTE0 0x0020
#ifdef CONFIG_QUOTA
#define MOPT_Q 0
#define MOPT_QFMT 0x0040
#else
#define MOPT_Q MOPT_NOSUPPORT
#define MOPT_QFMT MOPT_NOSUPPORT
#endif
#define MOPT_DATAJ 0x0080
#define MOPT_NO_EXT2 0x0100
#define MOPT_NO_EXT3 0x0200
#define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3)
static const struct mount_opts {
int token;
int mount_opt;
int flags;
} ext4_mount_opts[] = {
{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
{Opt_delalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_CLEAR | MOPT_EXPLICIT},
{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
EXT4_MOUNT_JOURNAL_CHECKSUM),
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
{Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_SET},
{Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_CLEAR},
{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
{Opt_commit, 0, MOPT_GTE0},
{Opt_max_batch_time, 0, MOPT_GTE0},
{Opt_min_batch_time, 0, MOPT_GTE0},
{Opt_inode_readahead_blks, 0, MOPT_GTE0},
{Opt_init_itable, 0, MOPT_GTE0},
{Opt_stripe, 0, MOPT_GTE0},
{Opt_resuid, 0, MOPT_GTE0},
{Opt_resgid, 0, MOPT_GTE0},
{Opt_journal_dev, 0, MOPT_GTE0},
{Opt_journal_ioprio, 0, MOPT_GTE0},
{Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
{Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
#ifdef CONFIG_EXT4_FS_POSIX_ACL
{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
{Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
#else
{Opt_acl, 0, MOPT_NOSUPPORT},
{Opt_noacl, 0, MOPT_NOSUPPORT},
#endif
{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
MOPT_SET | MOPT_Q},
{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
MOPT_SET | MOPT_Q},
{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA), MOPT_CLEAR | MOPT_Q},
{Opt_usrjquota, 0, MOPT_Q},
{Opt_grpjquota, 0, MOPT_Q},
{Opt_offusrjquota, 0, MOPT_Q},
{Opt_offgrpjquota, 0, MOPT_Q},
{Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
{Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
{Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
{Opt_max_dir_size_kb, 0, MOPT_GTE0},
{Opt_err, 0, 0}
};
static int handle_mount_opt(struct super_block *sb, char *opt, int token,
substring_t *args, unsigned long *journal_devnum,
unsigned int *journal_ioprio, int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
const struct mount_opts *m;
kuid_t uid;
kgid_t gid;
int arg = 0;
#ifdef CONFIG_QUOTA
if (token == Opt_usrjquota)
return set_qf_name(sb, USRQUOTA, &args[0]);
else if (token == Opt_grpjquota)
return set_qf_name(sb, GRPQUOTA, &args[0]);
else if (token == Opt_offusrjquota)
return clear_qf_name(sb, USRQUOTA);
else if (token == Opt_offgrpjquota)
return clear_qf_name(sb, GRPQUOTA);
#endif
switch (token) {
case Opt_noacl:
case Opt_nouser_xattr:
ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
break;
case Opt_sb:
return 1; /* handled by get_sb_block() */
case Opt_removed:
ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
return 1;
case Opt_abort:
sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
return 1;
case Opt_i_version:
sb->s_flags |= MS_I_VERSION;
return 1;
}
for (m = ext4_mount_opts; m->token != Opt_err; m++)
if (token == m->token)
break;
if (m->token == Opt_err) {
ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
"or missing value", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext2", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext3", opt);
return -1;
}
if (args->from && match_int(args, &arg))
return -1;
if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
return -1;
if (m->flags & MOPT_EXPLICIT)
set_opt2(sb, EXPLICIT_DELALLOC);
if (m->flags & MOPT_CLEAR_ERR)
clear_opt(sb, ERRORS_MASK);
if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot change quota "
"options when quota turned on");
return -1;
}
if (m->flags & MOPT_NOSUPPORT) {
ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
} else if (token == Opt_commit) {
if (arg == 0)
arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
sbi->s_commit_interval = HZ * arg;
} else if (token == Opt_max_batch_time) {
if (arg == 0)
arg = EXT4_DEF_MAX_BATCH_TIME;
sbi->s_max_batch_time = arg;
} else if (token == Opt_min_batch_time) {
sbi->s_min_batch_time = arg;
} else if (token == Opt_inode_readahead_blks) {
if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
ext4_msg(sb, KERN_ERR,
"EXT4-fs: inode_readahead_blks must be "
"0 or a power of 2 smaller than 2^31");
return -1;
}
sbi->s_inode_readahead_blks = arg;
} else if (token == Opt_init_itable) {
set_opt(sb, INIT_INODE_TABLE);
if (!args->from)
arg = EXT4_DEF_LI_WAIT_MULT;
sbi->s_li_wait_mult = arg;
} else if (token == Opt_max_dir_size_kb) {
sbi->s_max_dir_size_kb = arg;
} else if (token == Opt_stripe) {
sbi->s_stripe = arg;
} else if (token == Opt_resuid) {
uid = make_kuid(current_user_ns(), arg);
if (!uid_valid(uid)) {
ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
return -1;
}
sbi->s_resuid = uid;
} else if (token == Opt_resgid) {
gid = make_kgid(current_user_ns(), arg);
if (!gid_valid(gid)) {
ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
return -1;
}
sbi->s_resgid = gid;
} else if (token == Opt_journal_dev) {
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
*journal_devnum = arg;
} else if (token == Opt_journal_ioprio) {
if (arg > 7) {
ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
" (must be 0-7)");
return -1;
}
*journal_ioprio =
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
} else if (m->flags & MOPT_DATAJ) {
if (is_remount) {
if (!sbi->s_journal)
ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
ext4_msg(sb, KERN_ERR,
"Cannot change data mode on remount");
return -1;
}
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_mount_opt |= m->mount_opt;
}
#ifdef CONFIG_QUOTA
} else if (m->flags & MOPT_QFMT) {
if (sb_any_quota_loaded(sb) &&
sbi->s_jquota_fmt != m->mount_opt) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_QUOTA)) {
ext4_msg(sb, KERN_ERR,
"Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
sbi->s_jquota_fmt = m->mount_opt;
#endif
} else {
if (!args->from)
arg = 1;
if (m->flags & MOPT_CLEAR)
arg = !arg;
else if (unlikely(!(m->flags & MOPT_SET))) {
ext4_msg(sb, KERN_WARNING,
"buggy handling of option %s", opt);
WARN_ON(1);
return -1;
}
if (arg != 0)
sbi->s_mount_opt |= m->mount_opt;
else
sbi->s_mount_opt &= ~m->mount_opt;
}
return 1;
}
static int parse_options(char *options, struct super_block *sb,
unsigned long *journal_devnum,
unsigned int *journal_ioprio,
int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *p;
substring_t args[MAX_OPT_ARGS];
int token;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
/*
* Initialize args struct so we know whether arg was
* found; some options take optional arguments.
*/
args[0].to = args[0].from = NULL;
token = match_token(p, tokens, args);
if (handle_mount_opt(sb, p, token, args, journal_devnum,
journal_ioprio, is_remount) < 0)
return 0;
}
#ifdef CONFIG_QUOTA
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) &&
(test_opt(sb, USRQUOTA) || test_opt(sb, GRPQUOTA))) {
ext4_msg(sb, KERN_ERR, "Cannot set quota options when QUOTA "
"feature is enabled");
return 0;
}
if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
clear_opt(sb, USRQUOTA);
if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
clear_opt(sb, GRPQUOTA);
if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
ext4_msg(sb, KERN_ERR, "old and new quota "
"format mixing");
return 0;
}
if (!sbi->s_jquota_fmt) {
ext4_msg(sb, KERN_ERR, "journaled quota format "
"not specified");
return 0;
}
} else {
if (sbi->s_jquota_fmt) {
ext4_msg(sb, KERN_ERR, "journaled quota format "
"specified with no journaling "
"enabled");
return 0;
}
}
#endif
if (test_opt(sb, DIOREAD_NOLOCK)) {
int blocksize =
BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (blocksize < PAGE_CACHE_SIZE) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"dioread_nolock if block size != PAGE_SIZE");
return 0;
}
}
return 1;
}
static inline void ext4_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_printf(seq, ",usrjquota=%s", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_printf(seq, ",grpjquota=%s", sbi->s_qf_names[GRPQUOTA]);
#endif
}
static const char *token2str(int token)
{
const struct match_token *t;
for (t = tokens; t->token != Opt_err; t++)
if (t->token == token && !strchr(t->pattern, '='))
break;
return t->pattern;
}
/*
* Show an option if
* - it's set to a non-default value OR
* - if the per-sb default is different from the global default
*/
static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
int nodefs)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt;
const struct mount_opts *m;
char sep = nodefs ? '\n' : ',';
#define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
#define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
if (sbi->s_sb_block != 1)
SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
for (m = ext4_mount_opts; m->token != Opt_err; m++) {
int want_set = m->flags & MOPT_SET;
if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
(m->flags & MOPT_CLEAR_ERR))
continue;
if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
continue; /* skip if same as the default */
if ((want_set &&
(sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
(!want_set && (sbi->s_mount_opt & m->mount_opt)))
continue; /* select Opt_noFoo vs Opt_Foo */
SEQ_OPTS_PRINT("%s", token2str(m->token));
}
if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
SEQ_OPTS_PRINT("resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
SEQ_OPTS_PRINT("resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
SEQ_OPTS_PUTS("errors=remount-ro");
if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
SEQ_OPTS_PUTS("errors=continue");
if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
SEQ_OPTS_PUTS("errors=panic");
if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
if (sb->s_flags & MS_I_VERSION)
SEQ_OPTS_PUTS("i_version");
if (nodefs || sbi->s_stripe)
SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
SEQ_OPTS_PUTS("data=journal");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
SEQ_OPTS_PUTS("data=ordered");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
SEQ_OPTS_PUTS("data=writeback");
}
if (nodefs ||
sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
SEQ_OPTS_PRINT("inode_readahead_blks=%u",
sbi->s_inode_readahead_blks);
if (nodefs || (test_opt(sb, INIT_INODE_TABLE) &&
(sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
if (nodefs || sbi->s_max_dir_size_kb)
SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
ext4_show_quota_options(seq, sb);
return 0;
}
static int ext4_show_options(struct seq_file *seq, struct dentry *root)
{
return _ext4_show_options(seq, root->d_sb, 0);
}
static int options_seq_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
int rc;
seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw");
rc = _ext4_show_options(seq, sb, 1);
seq_puts(seq, "\n");
return rc;
}
static int options_open_fs(struct inode *inode, struct file *file)
{
return single_open(file, options_seq_show, PDE_DATA(inode));
}
static const struct file_operations ext4_seq_options_fops = {
.owner = THIS_MODULE,
.open = options_open_fs,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
int read_only)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int res = 0;
if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
ext4_msg(sb, KERN_ERR, "revision level too high, "
"forcing read-only mode");
res = MS_RDONLY;
}
if (read_only)
goto done;
if (!(sbi->s_mount_state & EXT4_VALID_FS))
ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if ((sbi->s_mount_state & EXT4_ERROR_FS))
ext4_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext4_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= get_seconds()))
ext4_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!sbi->s_journal)
es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
es->s_mtime = cpu_to_le32(get_seconds());
ext4_update_dynamic_rev(sb);
if (sbi->s_journal)
EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
ext4_commit_super(sb, 1);
done:
if (test_opt(sb, DEBUG))
printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
sb->s_blocksize,
sbi->s_groups_count,
EXT4_BLOCKS_PER_GROUP(sb),
EXT4_INODES_PER_GROUP(sb),
sbi->s_mount_opt, sbi->s_mount_opt2);
cleancache_init_fs(sb);
return res;
}
int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct flex_groups *new_groups;
int size;
if (!sbi->s_log_groups_per_flex)
return 0;
size = ext4_flex_group(sbi, ngroup - 1) + 1;
if (size <= sbi->s_flex_groups_allocated)
return 0;
size = roundup_pow_of_two(size * sizeof(struct flex_groups));
new_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (!new_groups) {
ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups",
size / (int) sizeof(struct flex_groups));
return -ENOMEM;
}
if (sbi->s_flex_groups) {
memcpy(new_groups, sbi->s_flex_groups,
(sbi->s_flex_groups_allocated *
sizeof(struct flex_groups)));
ext4_kvfree(sbi->s_flex_groups);
}
sbi->s_flex_groups = new_groups;
sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups);
return 0;
}
static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group;
int i, err;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
if (err)
goto failed;
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic64_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
static __le16 ext4_group_desc_csum(struct ext4_sb_info *sbi, __u32 block_group,
struct ext4_group_desc *gdp)
{
int offset;
__u16 crc = 0;
__le32 le_group = cpu_to_le32(block_group);
if ((sbi->s_es->s_feature_ro_compat &
cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))) {
/* Use new metadata_csum algorithm */
__le16 save_csum;
__u32 csum32;
save_csum = gdp->bg_checksum;
gdp->bg_checksum = 0;
csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
sizeof(le_group));
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp,
sbi->s_desc_size);
gdp->bg_checksum = save_csum;
crc = csum32 & 0xFFFF;
goto out;
}
/* old crc16 code */
offset = offsetof(struct ext4_group_desc, bg_checksum);
crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
crc = crc16(crc, (__u8 *)gdp, offset);
offset += sizeof(gdp->bg_checksum); /* skip checksum */
/* for checksum of struct ext4_group_desc do the rest...*/
if ((sbi->s_es->s_feature_incompat &
cpu_to_le32(EXT4_FEATURE_INCOMPAT_64BIT)) &&
offset < le16_to_cpu(sbi->s_es->s_desc_size))
crc = crc16(crc, (__u8 *)gdp + offset,
le16_to_cpu(sbi->s_es->s_desc_size) -
offset);
out:
return cpu_to_le16(crc);
}
int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_checksum != ext4_group_desc_csum(EXT4_SB(sb),
block_group, gdp)))
return 0;
return 1;
}
void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (!ext4_has_group_desc_csum(sb))
return;
gdp->bg_checksum = ext4_group_desc_csum(EXT4_SB(sb), block_group, gdp);
}
/* Called at mount-time, super-block is locked */
static int ext4_check_descriptors(struct super_block *sb,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
ext4_fsblk_t last_block;
ext4_fsblk_t block_bitmap;
ext4_fsblk_t inode_bitmap;
ext4_fsblk_t inode_table;
int flexbg_flag = 0;
ext4_group_t i, grp = sbi->s_groups_count;
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))
flexbg_flag = 1;
ext4_debug("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (i == sbi->s_groups_count - 1 || flexbg_flag)
last_block = ext4_blocks_count(sbi->s_es) - 1;
else
last_block = first_block +
(EXT4_BLOCKS_PER_GROUP(sb) - 1);
if ((grp == sbi->s_groups_count) &&
!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
grp = i;
block_bitmap = ext4_block_bitmap(sb, gdp);
if (block_bitmap < first_block || block_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u not in group "
"(block %llu)!", i, block_bitmap);
return 0;
}
inode_bitmap = ext4_inode_bitmap(sb, gdp);
if (inode_bitmap < first_block || inode_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u not in group "
"(block %llu)!", i, inode_bitmap);
return 0;
}
inode_table = ext4_inode_table(sb, gdp);
if (inode_table < first_block ||
inode_table + sbi->s_itb_per_group - 1 > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u not in group "
"(block %llu)!", i, inode_table);
return 0;
}
ext4_lock_group(sb, i);
if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Checksum for group %u failed (%u!=%u)",
i, le16_to_cpu(ext4_group_desc_csum(sbi, i,
gdp)), le16_to_cpu(gdp->bg_checksum));
if (!(sb->s_flags & MS_RDONLY)) {
ext4_unlock_group(sb, i);
return 0;
}
}
ext4_unlock_group(sb, i);
if (!flexbg_flag)
first_block += EXT4_BLOCKS_PER_GROUP(sb);
}
if (NULL != first_not_zeroed)
*first_not_zeroed = grp;
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, ext4_count_free_clusters(sb)));
sbi->s_es->s_free_inodes_count =cpu_to_le32(ext4_count_free_inodes(sb));
return 1;
}
/* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
* the superblock) which were deleted from all directories, but held open by
* a process at the time of a crash. We walk the list and try to delete these
* inodes at recovery time (only with a read-write filesystem).
*
* In order to keep the orphan inode chain consistent during traversal (in
* case of crash during recovery), we link each inode into the superblock
* orphan list_head and handle it the same way as an inode deletion during
* normal operation (which journals the operations for us).
*
* We only do an iget() and an iput() on each inode, which is very safe if we
* accidentally point at an in-use or already deleted inode. The worst that
* can happen in this case is that we get a "bit already cleared" message from
* ext4_free_inode(). The only reason we would point at a wrong inode is if
* e2fsck was run on this filesystem, and it must have already done the orphan
* inode cleanup for us, so we can safely abort without any further action.
*/
static void ext4_orphan_cleanup(struct super_block *sb,
struct ext4_super_block *es)
{
unsigned int s_flags = sb->s_flags;
int nr_orphans = 0, nr_truncates = 0;
#ifdef CONFIG_QUOTA
int i;
#endif
if (!es->s_last_orphan) {
jbd_debug(4, "no orphan inodes to clean up\n");
return;
}
if (bdev_read_only(sb->s_bdev)) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, skipping orphan cleanup");
return;
}
/* Check if feature set would not allow a r/w mount */
if (!ext4_feature_set_ok(sb, 0)) {
ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
"unknown ROCOMPAT features");
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
/* don't clear list on RO mount w/ errors */
if (es->s_last_orphan && !(s_flags & MS_RDONLY)) {
jbd_debug(1, "Errors on filesystem, "
"clearing orphan list.\n");
es->s_last_orphan = 0;
}
jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
return;
}
if (s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
sb->s_flags &= ~MS_RDONLY;
}
#ifdef CONFIG_QUOTA
/* Needed for iput() to work correctly and not trash data */
sb->s_flags |= MS_ACTIVE;
/* Turn on quotas so that they are updated correctly */
for (i = 0; i < MAXQUOTAS; i++) {
if (EXT4_SB(sb)->s_qf_names[i]) {
int ret = ext4_quota_on_mount(sb, i);
if (ret < 0)
ext4_msg(sb, KERN_ERR,
"Cannot turn on journaled "
"quota: error %d", ret);
}
}
#endif
while (es->s_last_orphan) {
struct inode *inode;
inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
if (IS_ERR(inode)) {
es->s_last_orphan = 0;
break;
}
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
dquot_initialize(inode);
if (inode->i_nlink) {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: truncating inode %lu to %lld bytes",
__func__, inode->i_ino, inode->i_size);
jbd_debug(2, "truncating inode %lu to %lld bytes\n",
inode->i_ino, inode->i_size);
mutex_lock(&inode->i_mutex);
truncate_inode_pages(inode->i_mapping, inode->i_size);
ext4_truncate(inode);
mutex_unlock(&inode->i_mutex);
nr_truncates++;
} else {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: deleting unreferenced inode %lu",
__func__, inode->i_ino);
jbd_debug(2, "deleting unreferenced inode %lu\n",
inode->i_ino);
nr_orphans++;
}
iput(inode); /* The delete magic happens here! */
}
#define PLURAL(x) (x), ((x) == 1) ? "" : "s"
if (nr_orphans)
ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
PLURAL(nr_orphans));
if (nr_truncates)
ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
PLURAL(nr_truncates));
#ifdef CONFIG_QUOTA
/* Turn quotas off */
for (i = 0; i < MAXQUOTAS; i++) {
if (sb_dqopt(sb)->files[i])
dquot_quota_off(sb, i);
}
#endif
sb->s_flags = s_flags; /* Restore MS_RDONLY status */
}
/*
* Maximal extent format file size.
* Resulting logical blkno at s_maxbytes must fit in our on-disk
* extent format containers, within a sector_t, and within i_blocks
* in the vfs. ext4 inode has 48 bits of i_block in fsblock units,
* so that won't be a limiting factor.
*
* However there is other limiting factor. We do store extents in the form
* of starting block and length, hence the resulting length of the extent
* covering maximum file size must fit into on-disk format containers as
* well. Given that length is always by 1 unit bigger than max unit (because
* we count 0 as well) we have to lower the s_maxbytes by one fs block.
*
* Note, this does *not* consider any metadata overhead for vfs i_blocks.
*/
static loff_t ext4_max_size(int blkbits, int has_huge_files)
{
loff_t res;
loff_t upper_limit = MAX_LFS_FILESIZE;
/* small i_blocks in vfs inode? */
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* CONFIG_LBDAF is not enabled implies the inode
* i_block represent total blocks in 512 bytes
* 32 == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (blkbits - 9);
upper_limit <<= blkbits;
}
/*
* 32-bit extent-start container, ee_block. We lower the maxbytes
* by one fs block, so ee_len can cover the extent of maximum file
* size
*/
res = (1LL << 32) - 1;
res <<= blkbits;
/* Sanity check against vm- & vfs- imposed limits */
if (res > upper_limit)
res = upper_limit;
return res;
}
/*
* Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^48 sector limit.
*/
static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
{
loff_t res = EXT4_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a dense, block
* mapped file such that the file's total number of 512-byte sectors,
* including data and all indirect blocks, does not exceed (2^48 - 1).
*
* __u32 i_blocks_lo and _u16 i_blocks_high represent the total
* number of 512-byte sectors of the file.
*/
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* !has_huge_files or CONFIG_LBDAF not enabled implies that
* the inode i_block field represents total file blocks in
* 2^32 512-byte sectors == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
} else {
/*
* We use 48 bit ext4_inode i_blocks
* With EXT4_HUGE_FILE_FL set the i_blocks
* represent total number of blocks in
* file system block size
*/
upper_limit = (1LL << 48) - 1;
}
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static ext4_fsblk_t descriptor_loc(struct super_block *sb,
ext4_fsblk_t logical_sb_block, int nr)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_META_BG) ||
nr < first_meta_bg)
return logical_sb_block + nr + 1;
bg = sbi->s_desc_per_block * nr;
if (ext4_bg_has_super(sb, bg))
has_super = 1;
return (has_super + ext4_group_first_block_no(sb, bg));
}
/**
* ext4_get_stripe_size: Get the stripe size.
* @sbi: In memory super block info
*
* If we have specified it via mount option, then
* use the mount option value. If the value specified at mount time is
* greater than the blocks per group use the super block value.
* If the super block value is greater than blocks per group return 0.
* Allocator needs it be less than blocks per group.
*
*/
static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
{
unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
unsigned long stripe_width =
le32_to_cpu(sbi->s_es->s_raid_stripe_width);
int ret;
if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
ret = sbi->s_stripe;
else if (stripe_width <= sbi->s_blocks_per_group)
ret = stripe_width;
else if (stride <= sbi->s_blocks_per_group)
ret = stride;
else
ret = 0;
/*
* If the stripe width is 1, this makes no sense and
* we set it to 0 to turn off stripe handling code.
*/
if (ret <= 1)
ret = 0;
return ret;
}
/* sysfs supprt */
struct ext4_attr {
struct attribute attr;
ssize_t (*show)(struct ext4_attr *, struct ext4_sb_info *, char *);
ssize_t (*store)(struct ext4_attr *, struct ext4_sb_info *,
const char *, size_t);
union {
int offset;
int deprecated_val;
} u;
};
static int parse_strtoull(const char *buf,
unsigned long long max, unsigned long long *value)
{
int ret;
ret = kstrtoull(skip_spaces(buf), 0, value);
if (!ret && *value > max)
ret = -EINVAL;
return ret;
}
static ssize_t delayed_allocation_blocks_show(struct ext4_attr *a,
struct ext4_sb_info *sbi,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%llu\n",
(s64) EXT4_C2B(sbi,
percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
}
static ssize_t session_write_kbytes_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
struct super_block *sb = sbi->s_buddy_cache->i_sb;
if (!sb->s_bdev->bd_part)
return snprintf(buf, PAGE_SIZE, "0\n");
return snprintf(buf, PAGE_SIZE, "%lu\n",
(part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
sbi->s_sectors_written_start) >> 1);
}
static ssize_t lifetime_write_kbytes_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
struct super_block *sb = sbi->s_buddy_cache->i_sb;
if (!sb->s_bdev->bd_part)
return snprintf(buf, PAGE_SIZE, "0\n");
return snprintf(buf, PAGE_SIZE, "%llu\n",
(unsigned long long)(sbi->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1)));
}
static ssize_t inode_readahead_blks_store(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned long t;
int ret;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
if (t && (!is_power_of_2(t) || t > 0x40000000))
return -EINVAL;
sbi->s_inode_readahead_blks = t;
return count;
}
static ssize_t sbi_ui_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
unsigned int *ui = (unsigned int *) (((char *) sbi) + a->u.offset);
return snprintf(buf, PAGE_SIZE, "%u\n", *ui);
}
static ssize_t sbi_ui_store(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned int *ui = (unsigned int *) (((char *) sbi) + a->u.offset);
unsigned long t;
int ret;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
*ui = t;
return count;
}
static ssize_t reserved_clusters_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%llu\n",
(unsigned long long) atomic64_read(&sbi->s_resv_clusters));
}
static ssize_t reserved_clusters_store(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned long long val;
int ret;
if (parse_strtoull(buf, -1ULL, &val))
return -EINVAL;
ret = ext4_reserve_clusters(sbi, val);
return ret ? ret : count;
}
static ssize_t trigger_test_error(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
int len = count;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (len && buf[len-1] == '\n')
len--;
if (len)
ext4_error(sbi->s_sb, "%.*s", len, buf);
return count;
}
static ssize_t sbi_deprecated_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", a->u.deprecated_val);
}
#define EXT4_ATTR_OFFSET(_name,_mode,_show,_store,_elname) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.show = _show, \
.store = _store, \
.u = { \
.offset = offsetof(struct ext4_sb_info, _elname),\
}, \
}
#define EXT4_ATTR(name, mode, show, store) \
static struct ext4_attr ext4_attr_##name = __ATTR(name, mode, show, store)
#define EXT4_INFO_ATTR(name) EXT4_ATTR(name, 0444, NULL, NULL)
#define EXT4_RO_ATTR(name) EXT4_ATTR(name, 0444, name##_show, NULL)
#define EXT4_RW_ATTR(name) EXT4_ATTR(name, 0644, name##_show, name##_store)
#define EXT4_RW_ATTR_SBI_UI(name, elname) \
EXT4_ATTR_OFFSET(name, 0644, sbi_ui_show, sbi_ui_store, elname)
#define ATTR_LIST(name) &ext4_attr_##name.attr
#define EXT4_DEPRECATED_ATTR(_name, _val) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = 0444 }, \
.show = sbi_deprecated_show, \
.u = { \
.deprecated_val = _val, \
}, \
}
EXT4_RO_ATTR(delayed_allocation_blocks);
EXT4_RO_ATTR(session_write_kbytes);
EXT4_RO_ATTR(lifetime_write_kbytes);
EXT4_RW_ATTR(reserved_clusters);
EXT4_ATTR_OFFSET(inode_readahead_blks, 0644, sbi_ui_show,
inode_readahead_blks_store, s_inode_readahead_blks);
EXT4_RW_ATTR_SBI_UI(inode_goal, s_inode_goal);
EXT4_RW_ATTR_SBI_UI(mb_stats, s_mb_stats);
EXT4_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan);
EXT4_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan);
EXT4_RW_ATTR_SBI_UI(mb_order2_req, s_mb_order2_reqs);
EXT4_RW_ATTR_SBI_UI(mb_stream_req, s_mb_stream_request);
EXT4_RW_ATTR_SBI_UI(mb_group_prealloc, s_mb_group_prealloc);
EXT4_DEPRECATED_ATTR(max_writeback_mb_bump, 128);
EXT4_RW_ATTR_SBI_UI(extent_max_zeroout_kb, s_extent_max_zeroout_kb);
EXT4_ATTR(trigger_fs_error, 0200, NULL, trigger_test_error);
static struct attribute *ext4_attrs[] = {
ATTR_LIST(delayed_allocation_blocks),
ATTR_LIST(session_write_kbytes),
ATTR_LIST(lifetime_write_kbytes),
ATTR_LIST(reserved_clusters),
ATTR_LIST(inode_readahead_blks),
ATTR_LIST(inode_goal),
ATTR_LIST(mb_stats),
ATTR_LIST(mb_max_to_scan),
ATTR_LIST(mb_min_to_scan),
ATTR_LIST(mb_order2_req),
ATTR_LIST(mb_stream_req),
ATTR_LIST(mb_group_prealloc),
ATTR_LIST(max_writeback_mb_bump),
ATTR_LIST(extent_max_zeroout_kb),
ATTR_LIST(trigger_fs_error),
NULL,
};
/* Features this copy of ext4 supports */
EXT4_INFO_ATTR(lazy_itable_init);
EXT4_INFO_ATTR(batched_discard);
EXT4_INFO_ATTR(meta_bg_resize);
static struct attribute *ext4_feat_attrs[] = {
ATTR_LIST(lazy_itable_init),
ATTR_LIST(batched_discard),
ATTR_LIST(meta_bg_resize),
NULL,
};
static ssize_t ext4_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
return a->show ? a->show(a, sbi, buf) : 0;
}
static ssize_t ext4_attr_store(struct kobject *kobj,
struct attribute *attr,
const char *buf, size_t len)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
return a->store ? a->store(a, sbi, buf, len) : 0;
}
static void ext4_sb_release(struct kobject *kobj)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
complete(&sbi->s_kobj_unregister);
}
static const struct sysfs_ops ext4_attr_ops = {
.show = ext4_attr_show,
.store = ext4_attr_store,
};
static struct kobj_type ext4_ktype = {
.default_attrs = ext4_attrs,
.sysfs_ops = &ext4_attr_ops,
.release = ext4_sb_release,
};
static void ext4_feat_release(struct kobject *kobj)
{
complete(&ext4_feat->f_kobj_unregister);
}
static struct kobj_type ext4_feat_ktype = {
.default_attrs = ext4_feat_attrs,
.sysfs_ops = &ext4_attr_ops,
.release = ext4_feat_release,
};
/*
* Check whether this filesystem can be mounted based on
* the features present and the RDONLY/RDWR mount requested.
* Returns 1 if this filesystem can be mounted as requested,
* 0 if it cannot be.
*/
static int ext4_feature_set_ok(struct super_block *sb, int readonly)
{
if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT4_FEATURE_INCOMPAT_SUPP)) {
ext4_msg(sb, KERN_ERR,
"Couldn't mount because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
~EXT4_FEATURE_INCOMPAT_SUPP));
return 0;
}
if (readonly)
return 1;
/* Check that feature set is OK for a read-write mount */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT4_FEATURE_RO_COMPAT_SUPP)) {
ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
~EXT4_FEATURE_RO_COMPAT_SUPP));
return 0;
}
/*
* Large file size enabled file system can only be mounted
* read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
*/
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
if (sizeof(blkcnt_t) < sizeof(u64)) {
ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
"cannot be mounted RDWR without "
"CONFIG_LBDAF");
return 0;
}
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC) &&
!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
ext4_msg(sb, KERN_ERR,
"Can't support bigalloc feature without "
"extents feature\n");
return 0;
}
#ifndef CONFIG_QUOTA
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) &&
!readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
#endif /* CONFIG_QUOTA */
return 1;
}
/*
* This function is called once a day if we have errors logged
* on the file system
*/
static void print_daily_error_info(unsigned long arg)
{
struct super_block *sb = (struct super_block *) arg;
struct ext4_sb_info *sbi;
struct ext4_super_block *es;
sbi = EXT4_SB(sb);
es = sbi->s_es;
if (es->s_error_count)
ext4_msg(sb, KERN_NOTICE, "error count: %u",
le32_to_cpu(es->s_error_count));
if (es->s_first_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): initial error at %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_first_error_time),
(int) sizeof(es->s_first_error_func),
es->s_first_error_func,
le32_to_cpu(es->s_first_error_line));
if (es->s_first_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_first_error_ino));
if (es->s_first_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_first_error_block));
printk("\n");
}
if (es->s_last_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): last error at %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_last_error_time),
(int) sizeof(es->s_last_error_func),
es->s_last_error_func,
le32_to_cpu(es->s_last_error_line));
if (es->s_last_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_last_error_ino));
if (es->s_last_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_last_error_block));
printk("\n");
}
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */
}
/* Find next suitable group and run ext4_init_inode_table */
static int ext4_run_li_request(struct ext4_li_request *elr)
{
struct ext4_group_desc *gdp = NULL;
ext4_group_t group, ngroups;
struct super_block *sb;
unsigned long timeout = 0;
int ret = 0;
sb = elr->lr_super;
ngroups = EXT4_SB(sb)->s_groups_count;
sb_start_write(sb);
for (group = elr->lr_next_group; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp) {
ret = 1;
break;
}
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
if (group >= ngroups)
ret = 1;
if (!ret) {
timeout = jiffies;
ret = ext4_init_inode_table(sb, group,
elr->lr_timeout ? 0 : 1);
if (elr->lr_timeout == 0) {
timeout = (jiffies - timeout) *
elr->lr_sbi->s_li_wait_mult;
elr->lr_timeout = timeout;
}
elr->lr_next_sched = jiffies + elr->lr_timeout;
elr->lr_next_group = group + 1;
}
sb_end_write(sb);
return ret;
}
/*
* Remove lr_request from the list_request and free the
* request structure. Should be called with li_list_mtx held
*/
static void ext4_remove_li_request(struct ext4_li_request *elr)
{
struct ext4_sb_info *sbi;
if (!elr)
return;
sbi = elr->lr_sbi;
list_del(&elr->lr_request);
sbi->s_li_request = NULL;
kfree(elr);
}
static void ext4_unregister_li_request(struct super_block *sb)
{
mutex_lock(&ext4_li_mtx);
if (!ext4_li_info) {
mutex_unlock(&ext4_li_mtx);
return;
}
mutex_lock(&ext4_li_info->li_list_mtx);
ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
mutex_unlock(&ext4_li_info->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
}
static struct task_struct *ext4_lazyinit_task;
/*
* This is the function where ext4lazyinit thread lives. It walks
* through the request list searching for next scheduled filesystem.
* When such a fs is found, run the lazy initialization request
* (ext4_rn_li_request) and keep track of the time spend in this
* function. Based on that time we compute next schedule time of
* the request. When walking through the list is complete, compute
* next waking time and put itself into sleep.
*/
static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_after_eq(jiffies, elr->lr_next_sched)) {
if (ext4_run_li_request(elr) != 0) {
/* error, remove the lazy_init job */
ext4_remove_li_request(elr);
continue;
}
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
try_to_freeze();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
static void ext4_clear_request_list(void)
{
struct list_head *pos, *n;
struct ext4_li_request *elr;
mutex_lock(&ext4_li_info->li_list_mtx);
list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
ext4_remove_li_request(elr);
}
mutex_unlock(&ext4_li_info->li_list_mtx);
}
static int ext4_run_lazyinit_thread(void)
{
ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
ext4_li_info, "ext4lazyinit");
if (IS_ERR(ext4_lazyinit_task)) {
int err = PTR_ERR(ext4_lazyinit_task);
ext4_clear_request_list();
kfree(ext4_li_info);
ext4_li_info = NULL;
printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
"initialization thread\n",
err);
return err;
}
ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
return 0;
}
/*
* Check whether it make sense to run itable init. thread or not.
* If there is at least one uninitialized inode table, return
* corresponding group number, else the loop goes through all
* groups and return total number of groups.
*/
static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
{
ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
struct ext4_group_desc *gdp = NULL;
for (group = 0; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp)
continue;
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
return group;
}
static int ext4_li_info_new(void)
{
struct ext4_lazy_init *eli = NULL;
eli = kzalloc(sizeof(*eli), GFP_KERNEL);
if (!eli)
return -ENOMEM;
INIT_LIST_HEAD(&eli->li_request_list);
mutex_init(&eli->li_list_mtx);
eli->li_state |= EXT4_LAZYINIT_QUIT;
ext4_li_info = eli;
return 0;
}
static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
ext4_group_t start)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr;
unsigned long rnd;
elr = kzalloc(sizeof(*elr), GFP_KERNEL);
if (!elr)
return NULL;
elr->lr_super = sb;
elr->lr_sbi = sbi;
elr->lr_next_group = start;
/*
* Randomize first schedule time of the request to
* spread the inode table initialization requests
* better.
*/
get_random_bytes(&rnd, sizeof(rnd));
elr->lr_next_sched = jiffies + (unsigned long)rnd %
(EXT4_DEF_LI_MAX_START_DELAY * HZ);
return elr;
}
int ext4_register_li_request(struct super_block *sb,
ext4_group_t first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr = NULL;
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
int ret = 0;
mutex_lock(&ext4_li_mtx);
if (sbi->s_li_request != NULL) {
/*
* Reset timeout so it can be computed again, because
* s_li_wait_mult might have changed.
*/
sbi->s_li_request->lr_timeout = 0;
goto out;
}
if (first_not_zeroed == ngroups ||
(sb->s_flags & MS_RDONLY) ||
!test_opt(sb, INIT_INODE_TABLE))
goto out;
elr = ext4_li_request_new(sb, first_not_zeroed);
if (!elr) {
ret = -ENOMEM;
goto out;
}
if (NULL == ext4_li_info) {
ret = ext4_li_info_new();
if (ret)
goto out;
}
mutex_lock(&ext4_li_info->li_list_mtx);
list_add(&elr->lr_request, &ext4_li_info->li_request_list);
mutex_unlock(&ext4_li_info->li_list_mtx);
sbi->s_li_request = elr;
/*
* set elr to NULL here since it has been inserted to
* the request_list and the removal and free of it is
* handled by ext4_clear_request_list from now on.
*/
elr = NULL;
if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
ret = ext4_run_lazyinit_thread();
if (ret)
goto out;
}
out:
mutex_unlock(&ext4_li_mtx);
if (ret)
kfree(elr);
return ret;
}
/*
* We do not need to lock anything since this is called on
* module unload.
*/
static void ext4_destroy_lazyinit_thread(void)
{
/*
* If thread exited earlier
* there's nothing to be done.
*/
if (!ext4_li_info || !ext4_lazyinit_task)
return;
kthread_stop(ext4_lazyinit_task);
}
static int set_journal_csum_feature_set(struct super_block *sb)
{
int ret = 1;
int compat, incompat;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
/* journal checksum v2 */
compat = 0;
incompat = JBD2_FEATURE_INCOMPAT_CSUM_V2;
} else {
/* journal checksum v1 */
compat = JBD2_FEATURE_COMPAT_CHECKSUM;
incompat = 0;
}
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
incompat);
} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
incompat);
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
} else {
jbd2_journal_clear_features(sbi->s_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
JBD2_FEATURE_INCOMPAT_CSUM_V2);
}
return ret;
}
/*
* Note: calculating the overhead so we can be compatible with
* historical BSD practice is quite difficult in the face of
* clusters/bigalloc. This is because multiple metadata blocks from
* different block group can end up in the same allocation cluster.
* Calculating the exact overhead in the face of clustered allocation
* requires either O(all block bitmaps) in memory or O(number of block
* groups**2) in time. We will still calculate the superblock for
* older file systems --- and if we come across with a bigalloc file
* system with zero in s_overhead_clusters the estimate will be close to
* correct especially for very large cluster sizes --- but for newer
* file systems, it's better to calculate this figure once at mkfs
* time, and store it in the superblock. If the superblock value is
* present (even for non-bigalloc file systems), we will use it.
*/
static int count_overhead(struct super_block *sb, ext4_group_t grp,
char *buf)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_fsblk_t first_block, last_block, b;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int s, j, count = 0;
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC))
return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
sbi->s_itb_per_group + 2);
first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
(grp * EXT4_BLOCKS_PER_GROUP(sb));
last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
b = ext4_block_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_table(sb, gdp);
if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
int c = EXT4_B2C(sbi, b - first_block);
ext4_set_bit(c, buf);
count++;
}
if (i != grp)
continue;
s = 0;
if (ext4_bg_has_super(sb, grp)) {
ext4_set_bit(s++, buf);
count++;
}
for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) {
ext4_set_bit(EXT4_B2C(sbi, s++), buf);
count++;
}
}
if (!count)
return 0;
return EXT4_CLUSTERS_PER_GROUP(sb) -
ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
}
/*
* Compute the overhead and stash it in sbi->s_overhead
*/
int ext4_calculate_overhead(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
ext4_fsblk_t overhead = 0;
char *buf = (char *) get_zeroed_page(GFP_KERNEL);
if (!buf)
return -ENOMEM;
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are overhead
*/
overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
/*
* Add the overhead found in each block group
*/
for (i = 0; i < ngroups; i++) {
int blks;
blks = count_overhead(sb, i, buf);
overhead += blks;
if (blks)
memset(buf, 0, PAGE_SIZE);
cond_resched();
}
/* Add the journal blocks as well */
if (sbi->s_journal)
overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
sbi->s_overhead = overhead;
smp_wmb();
free_page((unsigned long) buf);
return 0;
}
static ext4_fsblk_t ext4_calculate_resv_clusters(struct ext4_sb_info *sbi)
{
ext4_fsblk_t resv_clusters;
/*
* By default we reserve 2% or 4096 clusters, whichever is smaller.
* This should cover the situations where we can not afford to run
* out of space like for example punch hole, or converting
* uninitialized extents in delalloc path. In most cases such
* allocation would require 1, or 2 blocks, higher numbers are
* very rare.
*/
resv_clusters = ext4_blocks_count(sbi->s_es) >> sbi->s_cluster_bits;
do_div(resv_clusters, 50);
resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
return resv_clusters;
}
static int ext4_reserve_clusters(struct ext4_sb_info *sbi, ext4_fsblk_t count)
{
ext4_fsblk_t clusters = ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits;
if (count >= clusters)
return -EINVAL;
atomic64_set(&sbi->s_resv_clusters, count);
return 0;
}
static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi;
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
char *cp;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto out_free_orig;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
goto out_free_orig;
}
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
for (cp = sb->s_id; (cp = strchr(cp, '/'));)
*cp = '!';
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
ext4_warning(sb, KERN_INFO "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
if (def_mount_opts & EXT4_DEFM_BLOCK_VALIDITY)
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (!parse_options((char *) sbi->s_es->s_mount_opts, sb,
&journal_devnum, &journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
sbi->s_es->s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(EXT4_HAS_COMPAT_FEATURE(sb, ~0U) ||
EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||
EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d", blocksize);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_HUGE_FILE);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0)
goto cantfind_ext4;
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
if (sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#inodes per group too big: %lu",
sbi->s_inodes_per_group);
goto failed_mount;
}
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
if (ext4_proc_root)
sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root);
if (sbi->s_proc)
proc_create_data("options", S_IRUGO, sbi->s_proc,
&ext4_seq_options_fops, sb);
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
goto failed_mount2;
}
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
init_timer(&sbi->s_err_report);
sbi->s_err_report.function = print_daily_error_info;
sbi->s_err_report.data = (unsigned long) sb;
/* Register extent status tree shrinker */
ext4_es_register_shrinker(sbi);
err = percpu_counter_init(&sbi->s_freeclusters_counter,
ext4_count_free_clusters(sb));
if (!err) {
err = percpu_counter_init(&sbi->s_freeinodes_counter,
ext4_count_free_inodes(sb));
}
if (!err) {
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb));
}
if (!err) {
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0);
}
if (!err) {
err = percpu_counter_init(&sbi->s_extent_cache_cnt, 0);
}
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount3;
}
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
if (!test_opt(sb, NOLOAD) &&
EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL))
sb->s_op = &ext4_sops;
else
sb->s_op = &ext4_nojournal_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA))
sb->s_qcop = &ext4_qctl_sysfile_operations;
else
sb->s_qcop = &ext4_qctl_operations;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_RECOVER));
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_MMP) &&
!(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) &&
EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
/*
* The journal may have updated the bg summary counts, so we
* need to update the global counters.
*/
percpu_counter_set(&sbi->s_freeclusters_counter,
ext4_count_free_clusters(sb));
percpu_counter_set(&sbi->s_freeinodes_counter,
ext4_count_free_inodes(sb));
percpu_counter_set(&sbi->s_dirs_counter,
ext4_count_dirs(sb));
percpu_counter_set(&sbi->s_dirtyclusters_counter, 0);
no_journal:
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
EXT4_SB(sb)->unrsv_conversion_wq =
alloc_workqueue("ext4-unrsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->unrsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
err = ext4_reserve_clusters(sbi, ext4_calculate_resv_clusters(sbi));
if (err) {
ext4_msg(sb, KERN_ERR, "failed to reserve %llu clusters for "
"reserved pool", ext4_calculate_resv_clusters(sbi));
goto failed_mount4a;
}
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
sbi->s_kobj.kset = ext4_kset;
init_completion(&sbi->s_kobj_unregister);
err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL,
"%s", sb->s_id);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) &&
!(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %s%s%s", descr, sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
kfree(orig_data);
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
kobject_del(&sbi->s_kobj);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
if (EXT4_SB(sb)->unrsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->unrsv_conversion_wq);
failed_mount_wq:
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3:
ext4_es_unregister_shrinker(sbi);
del_timer(&sbi->s_err_report);
if (sbi->s_flex_groups)
ext4_kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
percpu_counter_destroy(&sbi->s_extent_cache_cnt);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
ext4_kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
if (sbi->s_proc) {
remove_proc_entry("options", sbi->s_proc);
remove_proc_entry(sb->s_id, ext4_proc_root);
}
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
out_free_orig:
kfree(orig_data);
return err ? err : ret;
}
/*
* Setup any per-fs journal parameters now. We'll do this both on
* initial mount, once the journal has been initialised but before we've
* done any recovery; and again on any subsequent remount.
*/
static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
write_unlock(&journal->j_state_lock);
}
static journal_t *ext4_get_journal(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
journal_t *journal;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
/* First, test for the existence of a valid inode on disk. Bad
* things happen if we iget() an unused inode, as the subsequent
* iput() will try to delete it. */
journal_inode = ext4_iget(sb, journal_inum);
if (IS_ERR(journal_inode)) {
ext4_msg(sb, KERN_ERR, "no journal found");
return NULL;
}
if (!journal_inode->i_nlink) {
make_bad_inode(journal_inode);
iput(journal_inode);
ext4_msg(sb, KERN_ERR, "journal inode is deleted");
return NULL;
}
jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
journal_inode, journal_inode->i_size);
if (!S_ISREG(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "invalid journal inode");
iput(journal_inode);
return NULL;
}
journal = jbd2_journal_init_inode(journal_inode);
if (!journal) {
ext4_msg(sb, KERN_ERR, "Could not load journal inode");
iput(journal_inode);
return NULL;
}
journal->j_private = sb;
ext4_init_journal_params(sb, journal);
return journal;
}
static journal_t *ext4_get_dev_journal(struct super_block *sb,
dev_t j_dev)
{
struct buffer_head *bh;
journal_t *journal;
ext4_fsblk_t start;
ext4_fsblk_t len;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
struct block_device *bdev;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
bdev = ext4_blkdev_get(j_dev, sb);
if (bdev == NULL)
return NULL;
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
if (!(bh = __bread(bdev, sb_block, blocksize))) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
goto out_bdev;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"bad superblock");
brelse(bh);
goto out_bdev;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
brelse(bh);
goto out_bdev;
}
len = ext4_blocks_count(es);
start = sb_block + 1;
brelse(bh); /* we're done with the superblock */
journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
start, len, blocksize);
if (!journal) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
goto out_bdev;
}
journal->j_private = sb;
ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
wait_on_buffer(journal->j_sb_buffer);
if (!buffer_uptodate(journal->j_sb_buffer)) {
ext4_msg(sb, KERN_ERR, "I/O error on journal device");
goto out_journal;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
goto out_journal;
}
EXT4_SB(sb)->journal_bdev = bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
ext4_blkdev_put(bdev);
return NULL;
}
static int ext4_load_journal(struct super_block *sb,
struct ext4_super_block *es,
unsigned long journal_devnum)
{
journal_t *journal;
unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
dev_t journal_dev;
int err = 0;
int really_read_only;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
if (journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
ext4_msg(sb, KERN_INFO, "external journal device major/minor "
"numbers have changed");
journal_dev = new_decode_dev(journal_devnum);
} else
journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
really_read_only = bdev_read_only(sb->s_bdev);
/*
* Are we loading a blank journal or performing recovery after a
* crash? For recovery, we need to check in advance whether we
* can get read-write access to the device.
*/
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {
if (sb->s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "INFO: recovery "
"required on readonly filesystem");
if (really_read_only) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, cannot proceed");
return -EROFS;
}
ext4_msg(sb, KERN_INFO, "write access will "
"be enabled during recovery");
}
}
if (journal_inum && journal_dev) {
ext4_msg(sb, KERN_ERR, "filesystem has both journal "
"and inode journals!");
return -EINVAL;
}
if (journal_inum) {
if (!(journal = ext4_get_journal(sb, journal_inum)))
return -EINVAL;
} else {
if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
return -EINVAL;
}
if (!(journal->j_flags & JBD2_BARRIER))
ext4_msg(sb, KERN_INFO, "barriers disabled");
if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER))
err = jbd2_journal_wipe(journal, !really_read_only);
if (!err) {
char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
if (save)
memcpy(save, ((char *) es) +
EXT4_S_ERR_START, EXT4_S_ERR_LEN);
err = jbd2_journal_load(journal);
if (save)
memcpy(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN);
kfree(save);
}
if (err) {
ext4_msg(sb, KERN_ERR, "error loading journal");
jbd2_journal_destroy(journal);
return err;
}
EXT4_SB(sb)->s_journal = journal;
ext4_clear_journal_err(sb, es);
if (!really_read_only && journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
es->s_journal_dev = cpu_to_le32(journal_devnum);
/* Make sure we flush the recovery flag to disk. */
ext4_commit_super(sb, 1);
}
return 0;
}
static int ext4_commit_super(struct super_block *sb, int sync)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
int error = 0;
if (!sbh || block_device_ejected(sb))
return error;
if (buffer_write_io_error(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext4_msg(sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
/*
* If the file system is mounted read-only, don't update the
* superblock write time. This avoids updating the superblock
* write time when we are mounting the root file system
* read/only but we need to replay the journal; at that point,
* for people who are east of GMT and who make their clock
* tick in localtime for Windows bug-for-bug compatibility,
* the clock is set in the future, and this will cause e2fsck
* to complain and force a full file system check.
*/
if (!(sb->s_flags & MS_RDONLY))
es->s_wtime = cpu_to_le32(get_seconds());
if (sb->s_bdev->bd_part)
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1));
else
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
ext4_free_blocks_count_set(es,
EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeclusters_counter)));
es->s_free_inodes_count =
cpu_to_le32(percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeinodes_counter));
BUFFER_TRACE(sbh, "marking dirty");
ext4_superblock_csum_set(sb);
mark_buffer_dirty(sbh);
if (sync) {
error = sync_dirty_buffer(sbh);
if (error)
return error;
error = buffer_write_io_error(sbh);
if (error) {
ext4_msg(sb, KERN_ERR, "I/O error while writing "
"superblock");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
}
return error;
}
/*
* Have we just finished recovery? If so, and if we are mounting (or
* remounting) the filesystem readonly, then we will end up with a
* consistent fs on disk. Record that fact.
*/
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {
BUG_ON(journal != NULL);
return;
}
jbd2_journal_lock_updates(journal);
if (jbd2_journal_flush(journal) < 0)
goto out;
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER) &&
sb->s_flags & MS_RDONLY) {
EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
ext4_commit_super(sb, 1);
}
out:
jbd2_journal_unlock_updates(journal);
}
/*
* If we are mounting (or read-write remounting) a filesystem whose journal
* has recorded an error from a previous lifetime, move that error to the
* main filesystem now.
*/
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal;
int j_errno;
const char *errstr;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
journal = EXT4_SB(sb)->s_journal;
/*
* Now check for any error status which may have been recorded in the
* journal by a prior ext4_error() or ext4_abort()
*/
j_errno = jbd2_journal_errno(journal);
if (j_errno) {
char nbuf[16];
errstr = ext4_decode_error(sb, j_errno, nbuf);
ext4_warning(sb, "Filesystem error recorded "
"from previous mount: %s", errstr);
ext4_warning(sb, "Marking fs in need of filesystem check.");
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
ext4_commit_super(sb, 1);
jbd2_journal_clear_err(journal);
jbd2_journal_update_sb_errno(journal);
}
}
/*
* Force the running and committing transactions to commit,
* and wait on the commit.
*/
int ext4_force_commit(struct super_block *sb)
{
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
return ext4_journal_force_commit(journal);
}
static int ext4_sync_fs(struct super_block *sb, int wait)
{
int ret = 0;
tid_t target;
bool needs_barrier = false;
struct ext4_sb_info *sbi = EXT4_SB(sb);
trace_ext4_sync_fs(sb, wait);
flush_workqueue(sbi->rsv_conversion_wq);
flush_workqueue(sbi->unrsv_conversion_wq);
/*
* Writeback quota in non-journalled quota case - journalled quota has
* no dirty dquots
*/
dquot_writeback_dquots(sb, -1);
/*
* Data writeback is possible w/o journal transaction, so barrier must
* being sent at the end of the function. But we can skip it if
* transaction_commit will do it for us.
*/
target = jbd2_get_latest_transaction(sbi->s_journal);
if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
needs_barrier = true;
if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
if (wait)
ret = jbd2_log_wait_commit(sbi->s_journal, target);
}
if (needs_barrier) {
int err;
err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
if (!ret)
ret = err;
}
return ret;
}
static int ext4_sync_fs_nojournal(struct super_block *sb, int wait)
{
int ret = 0;
trace_ext4_sync_fs(sb, wait);
flush_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
flush_workqueue(EXT4_SB(sb)->unrsv_conversion_wq);
dquot_writeback_dquots(sb, -1);
if (wait && test_opt(sb, BARRIER))
ret = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
return ret;
}
/*
* LVM calls this function before a (read-only) snapshot is created. This
* gives us a chance to flush the journal completely and mark the fs clean.
*
* Note that only this function cannot bring a filesystem to be in a clean
* state independently. It relies on upper layer to stop all data & metadata
* modifications.
*/
static int ext4_freeze(struct super_block *sb)
{
int error = 0;
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
/* Now we set up the journal barrier. */
jbd2_journal_lock_updates(journal);
/*
* Don't clear the needs_recovery flag if we failed to flush
* the journal.
*/
error = jbd2_journal_flush(journal);
if (error < 0)
goto out;
/* Journal blocked and flushed, clear needs_recovery flag. */
EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
error = ext4_commit_super(sb, 1);
out:
/* we rely on upper layer to stop further updates */
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
return error;
}
/*
* Called by LVM after the snapshot is done. We need to reset the RECOVER
* flag here, even though the filesystem is not technically dirty yet.
*/
static int ext4_unfreeze(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return 0;
/* Reset the needs_recovery flag before the fs is unlocked. */
EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
ext4_commit_super(sb, 1);
return 0;
}
/*
* Structure to save mount options for ext4_remount's benefit
*/
struct ext4_mount_options {
unsigned long s_mount_opt;
unsigned long s_mount_opt2;
kuid_t s_resuid;
kgid_t s_resgid;
unsigned long s_commit_interval;
u32 s_min_batch_time, s_max_batch_time;
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[MAXQUOTAS];
#endif
};
static int ext4_remount(struct super_block *sb, int *flags, char *data)
{
struct ext4_super_block *es;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long old_sb_flags;
struct ext4_mount_options old_opts;
int enable_quota = 0;
ext4_group_t g;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
int err = 0;
#ifdef CONFIG_QUOTA
int i, j;
#endif
char *orig_data = kstrdup(data, GFP_KERNEL);
/* Store the original options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_mount_opt2 = sbi->s_mount_opt2;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
old_opts.s_commit_interval = sbi->s_commit_interval;
old_opts.s_min_batch_time = sbi->s_min_batch_time;
old_opts.s_max_batch_time = sbi->s_max_batch_time;
#ifdef CONFIG_QUOTA
old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < MAXQUOTAS; i++)
if (sbi->s_qf_names[i]) {
old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i],
GFP_KERNEL);
if (!old_opts.s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(old_opts.s_qf_names[j]);
kfree(orig_data);
return -ENOMEM;
}
} else
old_opts.s_qf_names[i] = NULL;
#endif
if (sbi->s_journal && sbi->s_journal->j_task->io_context)
journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
/*
* Allow the "check" option to be passed as a remount option.
*/
if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
err = -EINVAL;
goto restore_opts;
}
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
ext4_abort(sb, "Abort forced by user");
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
es = sbi->s_es;
if (sbi->s_journal) {
ext4_init_journal_params(sb, sbi->s_journal);
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
}
if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) {
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
err = -EROFS;
goto restore_opts;
}
if (*flags & MS_RDONLY) {
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
/*
* First of all, the unconditional stuff we have to do
* to disable replay of the journal when we next remount
*/
sb->s_flags |= MS_RDONLY;
/*
* OK, test if we are remounting a valid rw partition
* readonly, and if so set the rdonly flag and then
* mark the partition as valid again.
*/
if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
(sbi->s_mount_state & EXT4_VALID_FS))
es->s_state = cpu_to_le16(sbi->s_mount_state);
if (sbi->s_journal)
ext4_mark_recovery_complete(sb, es);
} else {
/* Make sure we can mount this feature set readwrite */
if (!ext4_feature_set_ok(sb, 0)) {
err = -EROFS;
goto restore_opts;
}
/*
* Make sure the group descriptor checksums
* are sane. If they aren't, refuse to remount r/w.
*/
for (g = 0; g < sbi->s_groups_count; g++) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, g, NULL);
if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
ext4_msg(sb, KERN_ERR,
"ext4_remount: Checksum for group %u failed (%u!=%u)",
g, le16_to_cpu(ext4_group_desc_csum(sbi, g, gdp)),
le16_to_cpu(gdp->bg_checksum));
err = -EINVAL;
goto restore_opts;
}
}
/*
* If we have an unprocessed orphan list hanging
* around from a previously readonly bdev mount,
* require a full umount/remount for now.
*/
if (es->s_last_orphan) {
ext4_msg(sb, KERN_WARNING, "Couldn't "
"remount RDWR because of unprocessed "
"orphan inode list. Please "
"umount/remount instead");
err = -EINVAL;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread
* and store the current valid flag. (It may have
* been changed by e2fsck since we originally mounted
* the partition.)
*/
if (sbi->s_journal)
ext4_clear_journal_err(sb, es);
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext4_setup_super(sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
if (EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_MMP))
if (ext4_multi_mount_protect(sb,
le64_to_cpu(es->s_mmp_block))) {
err = -EROFS;
goto restore_opts;
}
enable_quota = 1;
}
}
/*
* Reinitialize lazy itable initialization thread based on
* current settings
*/
if ((sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE))
ext4_unregister_li_request(sb);
else {
ext4_group_t first_not_zeroed;
first_not_zeroed = ext4_has_uninit_itable(sb);
ext4_register_li_request(sb, first_not_zeroed);
}
ext4_setup_system_zone(sb);
if (sbi->s_journal == NULL && !(old_sb_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
#ifdef CONFIG_QUOTA
/* Release old quota file names */
for (i = 0; i < MAXQUOTAS; i++)
kfree(old_opts.s_qf_names[i]);
if (enable_quota) {
if (sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
else if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_QUOTA)) {
err = ext4_enable_quotas(sb);
if (err)
goto restore_opts;
}
}
#endif
ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
kfree(orig_data);
return 0;
restore_opts:
sb->s_flags = old_sb_flags;
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_mount_opt2 = old_opts.s_mount_opt2;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sbi->s_commit_interval = old_opts.s_commit_interval;
sbi->s_min_batch_time = old_opts.s_min_batch_time;
sbi->s_max_batch_time = old_opts.s_max_batch_time;
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
for (i = 0; i < MAXQUOTAS; i++) {
kfree(sbi->s_qf_names[i]);
sbi->s_qf_names[i] = old_opts.s_qf_names[i];
}
#endif
kfree(orig_data);
return err;
}
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t overhead = 0, resv_blocks;
u64 fsid;
s64 bfree;
resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
if (!test_opt(sb, MINIX_DF))
overhead = sbi->s_overhead;
buf->f_type = EXT4_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
/* prevent underflow in case that few free space is available */
buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
buf->f_bavail = buf->f_bfree -
(ext4_r_blocks_count(es) + resv_blocks);
if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
buf->f_namelen = EXT4_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
return 0;
}
/* Helper function for writing quotas on sync - we need to start transaction
* before quota file is locked for write. Otherwise the are possible deadlocks:
* Process 1 Process 2
* ext4_create() quota_sync()
* jbd2_journal_start() write_dquot()
* dquot_initialize() down(dqio_mutex)
* down(dqio_mutex) jbd2_journal_start()
*
*/
#ifdef CONFIG_QUOTA
static inline struct inode *dquot_to_inode(struct dquot *dquot)
{
return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
}
static int ext4_write_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
struct inode *inode;
inode = dquot_to_inode(dquot);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_release_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle)) {
/* Release dquot anyway to avoid endless cycle in dqput() */
dquot_release(dquot);
return PTR_ERR(handle);
}
ret = dquot_release(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_mark_dquot_dirty(struct dquot *dquot)
{
struct super_block *sb = dquot->dq_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Are we journaling quotas? */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) ||
sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
dquot_mark_dquot_dirty(dquot);
return ext4_write_dquot(dquot);
} else {
return dquot_mark_dquot_dirty(dquot);
}
}
static int ext4_write_info(struct super_block *sb, int type)
{
int ret, err;
handle_t *handle;
/* Data block + inode block */
handle = ext4_journal_start(sb->s_root->d_inode, EXT4_HT_QUOTA, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit_info(sb, type);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
/*
* Turn on quotas during mount time - we need to find
* the quota file and such...
*/
static int ext4_quota_on_mount(struct super_block *sb, int type)
{
return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type],
EXT4_SB(sb)->s_jquota_fmt, type);
}
/*
* Standard function to be called on quota_on
*/
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path)
{
int err;
if (!test_opt(sb, QUOTA))
return -EINVAL;
/* Quotafile not on the same filesystem? */
if (path->dentry->d_sb != sb)
return -EXDEV;
/* Journaling quota? */
if (EXT4_SB(sb)->s_qf_names[type]) {
/* Quotafile not in fs root? */
if (path->dentry->d_parent != sb->s_root)
ext4_msg(sb, KERN_WARNING,
"Quota file not on filesystem root. "
"Journaled quota will not work");
}
/*
* When we journal data on quota file, we have to flush journal to see
* all updates to the file when we bypass pagecache...
*/
if (EXT4_SB(sb)->s_journal &&
ext4_should_journal_data(path->dentry->d_inode)) {
/*
* We don't need to lock updates but journal_flush() could
* otherwise be livelocked...
*/
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
if (err)
return err;
}
return dquot_quota_on(sb, type, format_id, path);
}
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags)
{
int err;
struct inode *qf_inode;
unsigned long qf_inums[MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum)
};
BUG_ON(!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA));
if (!qf_inums[type])
return -EPERM;
qf_inode = ext4_iget(sb, qf_inums[type]);
if (IS_ERR(qf_inode)) {
ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
return PTR_ERR(qf_inode);
}
/* Don't account quota for quota files to avoid recursion */
qf_inode->i_flags |= S_NOQUOTA;
err = dquot_enable(qf_inode, type, format_id, flags);
iput(qf_inode);
return err;
}
/* Enable usage tracking for all quota types. */
static int ext4_enable_quotas(struct super_block *sb)
{
int type, err = 0;
unsigned long qf_inums[MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum)
};
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
for (type = 0; type < MAXQUOTAS; type++) {
if (qf_inums[type]) {
err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
DQUOT_USAGE_ENABLED);
if (err) {
ext4_warning(sb,
"Failed to enable quota tracking "
"(type=%d, err=%d). Please run "
"e2fsck to fix.", type, err);
return err;
}
}
}
return 0;
}
/*
* quota_on function that is used when QUOTA feature is set.
*/
static int ext4_quota_on_sysfile(struct super_block *sb, int type,
int format_id)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA))
return -EINVAL;
/*
* USAGE was enabled at mount time. Only need to enable LIMITS now.
*/
return ext4_quota_enable(sb, type, format_id, DQUOT_LIMITS_ENABLED);
}
static int ext4_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
handle_t *handle;
/* Force all delayed allocation blocks to be allocated.
* Caller already holds s_umount sem */
if (test_opt(sb, DELALLOC))
sync_filesystem(sb);
if (!inode)
goto out;
/* Update modification times of quota files when userspace can
* start looking at them */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle))
goto out;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
out:
return dquot_quota_off(sb, type);
}
/*
* quota_off function that is used when QUOTA feature is set.
*/
static int ext4_quota_off_sysfile(struct super_block *sb, int type)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA))
return -EINVAL;
/* Disable only the limits. */
return dquot_disable(sb, type, DQUOT_LIMITS_ENABLED);
}
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err = 0;
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
bh = ext4_bread(NULL, inode, blk, 0, &err);
if (err)
return err;
if (!bh) /* A hole? */
memset(data, 0, tocopy);
else
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile (we know the transaction is already started and has
* enough credits) */
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err = 0;
int offset = off & (sb->s_blocksize - 1);
struct buffer_head *bh;
handle_t *handle = journal_current_handle();
if (EXT4_SB(sb)->s_journal && !handle) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because transaction is not started",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
/*
* Since we account only one data block in transaction credits,
* then it is impossible to cross a block boundary.
*/
if (sb->s_blocksize - offset < len) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because not block aligned",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
bh = ext4_bread(handle, inode, blk, 1, &err);
if (!bh)
goto out;
err = ext4_journal_get_write_access(handle, bh);
if (err) {
brelse(bh);
goto out;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, len);
flush_dcache_page(bh->b_page);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
out:
if (err)
return err;
if (inode->i_size < off + len) {
i_size_write(inode, off + len);
EXT4_I(inode)->i_disksize = inode->i_size;
ext4_mark_inode_dirty(handle, inode);
}
return len;
}
#endif
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
}
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static inline void register_as_ext2(void)
{
int err = register_filesystem(&ext2_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext2 (%d)\n", err);
}
static inline void unregister_as_ext2(void)
{
unregister_filesystem(&ext2_fs_type);
}
static inline int ext2_feature_set_ok(struct super_block *sb)
{
if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))
return 0;
return 1;
}
#else
static inline void register_as_ext2(void) { }
static inline void unregister_as_ext2(void) { }
static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
#endif
#if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static inline void register_as_ext3(void)
{
int err = register_filesystem(&ext3_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext3 (%d)\n", err);
}
static inline void unregister_as_ext3(void)
{
unregister_filesystem(&ext3_fs_type);
}
static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT3_FEATURE_INCOMPAT_SUPP))
return 0;
if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT3_FEATURE_RO_COMPAT_SUPP))
return 0;
return 1;
}
#else
static inline void register_as_ext3(void) { }
static inline void unregister_as_ext3(void) { }
static inline int ext3_feature_set_ok(struct super_block *sb) { return 0; }
#endif
static struct file_system_type ext4_fs_type = {
.owner = THIS_MODULE,
.name = "ext4",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext4");
static int __init ext4_init_feat_adverts(void)
{
struct ext4_features *ef;
int ret = -ENOMEM;
ef = kzalloc(sizeof(struct ext4_features), GFP_KERNEL);
if (!ef)
goto out;
ef->f_kobj.kset = ext4_kset;
init_completion(&ef->f_kobj_unregister);
ret = kobject_init_and_add(&ef->f_kobj, &ext4_feat_ktype, NULL,
"features");
if (ret) {
kfree(ef);
goto out;
}
ext4_feat = ef;
ret = 0;
out:
return ret;
}
static void ext4_exit_feat_adverts(void)
{
kobject_put(&ext4_feat->f_kobj);
wait_for_completion(&ext4_feat->f_kobj_unregister);
kfree(ext4_feat);
}
/* Shared across all ext4 file systems */
wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
struct mutex ext4__aio_mutex[EXT4_WQ_HASH_SZ];
static int __init ext4_init_fs(void)
{
int i, err;
ext4_li_info = NULL;
mutex_init(&ext4_li_mtx);
/* Build-time check for flags consistency */
ext4_check_flag_values();
for (i = 0; i < EXT4_WQ_HASH_SZ; i++) {
mutex_init(&ext4__aio_mutex[i]);
init_waitqueue_head(&ext4__ioend_wq[i]);
}
err = ext4_init_es();
if (err)
return err;
err = ext4_init_pageio();
if (err)
goto out7;
err = ext4_init_system_zone();
if (err)
goto out6;
ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj);
if (!ext4_kset) {
err = -ENOMEM;
goto out5;
}
ext4_proc_root = proc_mkdir("fs/ext4", NULL);
err = ext4_init_feat_adverts();
if (err)
goto out4;
err = ext4_init_mballoc();
if (err)
goto out3;
err = ext4_init_xattr();
if (err)
goto out2;
err = init_inodecache();
if (err)
goto out1;
register_as_ext3();
register_as_ext2();
err = register_filesystem(&ext4_fs_type);
if (err)
goto out;
return 0;
out:
unregister_as_ext2();
unregister_as_ext3();
destroy_inodecache();
out1:
ext4_exit_xattr();
out2:
ext4_exit_mballoc();
out3:
ext4_exit_feat_adverts();
out4:
if (ext4_proc_root)
remove_proc_entry("fs/ext4", NULL);
kset_unregister(ext4_kset);
out5:
ext4_exit_system_zone();
out6:
ext4_exit_pageio();
out7:
ext4_exit_es();
return err;
}
static void __exit ext4_exit_fs(void)
{
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
destroy_inodecache();
ext4_exit_xattr();
ext4_exit_mballoc();
ext4_exit_feat_adverts();
remove_proc_entry("fs/ext4", NULL);
kset_unregister(ext4_kset);
ext4_exit_system_zone();
ext4_exit_pageio();
ext4_exit_es();
}
MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
MODULE_DESCRIPTION("Fourth Extended Filesystem");
MODULE_LICENSE("GPL");
module_init(ext4_init_fs)
module_exit(ext4_exit_fs)
| Java |
/* 32-bit ELF support for S+core.
Copyright (C) 2006-2017 Free Software Foundation, Inc.
Contributed by
Brain.lin ([email protected])
Mei Ligang ([email protected])
Pei-Lin Tsai ([email protected])
This file is part of BFD, the Binary File Descriptor library.
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., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "libiberty.h"
#include "elf-bfd.h"
#include "elf/score.h"
#include "elf/common.h"
#include "elf/internal.h"
#include "hashtab.h"
#include "elf32-score.h"
int score3 = 0;
int score7 = 1;
/* The SCORE ELF linker needs additional information for each symbol in
the global hash table. */
struct score_elf_link_hash_entry
{
struct elf_link_hash_entry root;
/* Number of R_SCORE_ABS32, R_SCORE_REL32 relocs against this symbol. */
unsigned int possibly_dynamic_relocs;
/* If the R_SCORE_ABS32, R_SCORE_REL32 reloc is against a readonly section. */
bfd_boolean readonly_reloc;
/* We must not create a stub for a symbol that has relocations related to
taking the function's address, i.e. any but R_SCORE_CALL15 ones. */
bfd_boolean no_fn_stub;
/* Are we forced local? This will only be set if we have converted
the initial global GOT entry to a local GOT entry. */
bfd_boolean forced_local;
};
/* Traverse a score ELF linker hash table. */
#define score_elf_link_hash_traverse(table, func, info) \
(elf_link_hash_traverse \
((table), \
(bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func), \
(info)))
/* This structure is used to hold .got entries while estimating got sizes. */
struct score_got_entry
{
/* The input bfd in which the symbol is defined. */
bfd *abfd;
/* The index of the symbol, as stored in the relocation r_info, if
we have a local symbol; -1 otherwise. */
long symndx;
union
{
/* If abfd == NULL, an address that must be stored in the got. */
bfd_vma address;
/* If abfd != NULL && symndx != -1, the addend of the relocation
that should be added to the symbol value. */
bfd_vma addend;
/* If abfd != NULL && symndx == -1, the hash table entry
corresponding to a global symbol in the got (or, local, if
h->forced_local). */
struct score_elf_link_hash_entry *h;
} d;
/* The offset from the beginning of the .got section to the entry
corresponding to this symbol+addend. If it's a global symbol
whose offset is yet to be decided, it's going to be -1. */
long gotidx;
};
/* This structure is passed to score_elf_sort_hash_table_f when sorting
the dynamic symbols. */
struct score_elf_hash_sort_data
{
/* The symbol in the global GOT with the lowest dynamic symbol table index. */
struct elf_link_hash_entry *low;
/* The least dynamic symbol table index corresponding to a symbol with a GOT entry. */
long min_got_dynindx;
/* The greatest dynamic symbol table index corresponding to a symbol
with a GOT entry that is not referenced (e.g., a dynamic symbol
with dynamic relocations pointing to it from non-primary GOTs). */
long max_unref_got_dynindx;
/* The greatest dynamic symbol table index not corresponding to a
symbol without a GOT entry. */
long max_non_got_dynindx;
};
struct score_got_info
{
/* The global symbol in the GOT with the lowest index in the dynamic
symbol table. */
struct elf_link_hash_entry *global_gotsym;
/* The number of global .got entries. */
unsigned int global_gotno;
/* The number of local .got entries. */
unsigned int local_gotno;
/* The number of local .got entries we have used. */
unsigned int assigned_gotno;
/* A hash table holding members of the got. */
struct htab *got_entries;
/* In multi-got links, a pointer to the next got (err, rather, most
of the time, it points to the previous got). */
struct score_got_info *next;
};
/* A structure used to count GOT entries, for GOT entry or ELF symbol table traversal. */
struct _score_elf_section_data
{
struct bfd_elf_section_data elf;
union
{
struct score_got_info *got_info;
bfd_byte *tdata;
}
u;
};
#define score_elf_section_data(sec) \
((struct _score_elf_section_data *) elf_section_data (sec))
/* The size of a symbol-table entry. */
#define SCORE_ELF_SYM_SIZE(abfd) \
(get_elf_backend_data (abfd)->s->sizeof_sym)
/* In case we're on a 32-bit machine, construct a 64-bit "-1" value
from smaller values. Start with zero, widen, *then* decrement. */
#define MINUS_ONE (((bfd_vma)0) - 1)
#define MINUS_TWO (((bfd_vma)0) - 2)
#define PDR_SIZE 32
/* The number of local .got entries we reserve. */
#define SCORE_RESERVED_GOTNO (2)
#define ELF_DYNAMIC_INTERPRETER "/usr/lib/ld.so.1"
/* The offset of $gp from the beginning of the .got section. */
#define ELF_SCORE_GP_OFFSET(abfd) (0x3ff0)
/* The maximum size of the GOT for it to be addressable using 15-bit offsets from $gp. */
#define SCORE_ELF_GOT_MAX_SIZE(abfd) (ELF_SCORE_GP_OFFSET(abfd) + 0x3fff)
#define SCORE_ELF_STUB_SECTION_NAME (".SCORE.stub")
#define SCORE_FUNCTION_STUB_SIZE (16)
#define STUB_LW 0xc3bcc010 /* lw r29, [r28, -0x3ff0] */
#define STUB_MOVE 0x8363bc56 /* mv r27, r3 */
#define STUB_LI16 0x87548000 /* ori r26, .dynsym_index */
#define STUB_BRL 0x801dbc09 /* brl r29 */
#define SCORE_ELF_GOT_SIZE(abfd) \
(get_elf_backend_data (abfd)->s->arch_size / 8)
#define SCORE_ELF_ADD_DYNAMIC_ENTRY(info, tag, val) \
(_bfd_elf_add_dynamic_entry (info, (bfd_vma) tag, (bfd_vma) val))
/* The size of an external dynamic table entry. */
#define SCORE_ELF_DYN_SIZE(abfd) \
(get_elf_backend_data (abfd)->s->sizeof_dyn)
/* The size of an external REL relocation. */
#define SCORE_ELF_REL_SIZE(abfd) \
(get_elf_backend_data (abfd)->s->sizeof_rel)
/* The default alignment for sections, as a power of two. */
#define SCORE_ELF_LOG_FILE_ALIGN(abfd)\
(get_elf_backend_data (abfd)->s->log_file_align)
static bfd_byte *hi16_rel_addr;
/* This will be used when we sort the dynamic relocation records. */
static bfd *reldyn_sorting_bfd;
/* SCORE ELF uses two common sections. One is the usual one, and the
other is for small objects. All the small objects are kept
together, and then referenced via the gp pointer, which yields
faster assembler code. This is what we use for the small common
section. This approach is copied from ecoff.c. */
static asection score_elf_scom_section;
static asymbol score_elf_scom_symbol;
static asymbol *score_elf_scom_symbol_ptr;
static bfd_vma
score_bfd_get_16 (bfd *abfd, const void *data)
{
return bfd_get_16 (abfd, data);
}
static bfd_vma
score3_bfd_getl32 (const void *p)
{
const bfd_byte *addr = p;
unsigned long v;
v = (unsigned long) addr[2];
v |= (unsigned long) addr[3] << 8;
v |= (unsigned long) addr[0] << 16;
v |= (unsigned long) addr[1] << 24;
return v;
}
static bfd_vma
score3_bfd_getl48 (const void *p)
{
const bfd_byte *addr = p;
unsigned long long v;
v = (unsigned long long) addr[4];
v |= (unsigned long long) addr[5] << 8;
v |= (unsigned long long) addr[2] << 16;
v |= (unsigned long long) addr[3] << 24;
v |= (unsigned long long) addr[0] << 32;
v |= (unsigned long long) addr[1] << 40;
return v;
}
static bfd_vma
score_bfd_get_32 (bfd *abfd, const void *data)
{
if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE)
return score3_bfd_getl32 (data);
else
return bfd_get_32 (abfd, data);
}
static bfd_vma
score_bfd_get_48 (bfd *abfd, const void *p)
{
if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE)
return score3_bfd_getl48 (p);
else
return bfd_get_bits (p, 48, 1);
}
static void
score_bfd_put_16 (bfd *abfd, bfd_vma addr, void *data)
{
return bfd_put_16 (abfd, addr, data);
}
static void
score3_bfd_putl32 (bfd_vma data, void *p)
{
bfd_byte *addr = p;
addr[0] = (data >> 16) & 0xff;
addr[1] = (data >> 24) & 0xff;
addr[2] = data & 0xff;
addr[3] = (data >> 8) & 0xff;
}
static void
score3_bfd_putl48 (bfd_vma data, void *p)
{
bfd_byte *addr = p;
addr[0] = (data >> 32) & 0xff;
addr[1] = (data >> 40) & 0xff;
addr[2] = (data >> 16) & 0xff;
addr[3] = (data >> 24) & 0xff;
addr[4] = data & 0xff;
addr[5] = (data >> 8) & 0xff;
}
static void
score_bfd_put_32 (bfd *abfd, bfd_vma addr, void *data)
{
if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE)
return score3_bfd_putl32 (addr, data);
else
return bfd_put_32 (abfd, addr, data);
}
static void
score_bfd_put_48 (bfd *abfd, bfd_vma val, void *p)
{
if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE)
return score3_bfd_putl48 (val, p);
else
return bfd_put_bits (val, p, 48, 1);
}
static bfd_reloc_status_type
score_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED,
arelent *reloc_entry,
asymbol *symbol ATTRIBUTE_UNUSED,
void * data,
asection *input_section ATTRIBUTE_UNUSED,
bfd *output_bfd ATTRIBUTE_UNUSED,
char **error_message ATTRIBUTE_UNUSED)
{
hi16_rel_addr = (bfd_byte *) data + reloc_entry->address;
return bfd_reloc_ok;
}
static bfd_reloc_status_type
score_elf_lo16_reloc (bfd *abfd,
arelent *reloc_entry,
asymbol *symbol ATTRIBUTE_UNUSED,
void * data,
asection *input_section,
bfd *output_bfd ATTRIBUTE_UNUSED,
char **error_message ATTRIBUTE_UNUSED)
{
bfd_vma addend = 0, offset = 0;
unsigned long val;
unsigned long hi16_offset, hi16_value, uvalue;
hi16_value = score_bfd_get_32 (abfd, hi16_rel_addr);
hi16_offset = ((((hi16_value >> 16) & 0x3) << 15) | (hi16_value & 0x7fff)) >> 1;
addend = score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address);
offset = ((((addend >> 16) & 0x3) << 15) | (addend & 0x7fff)) >> 1;
val = reloc_entry->addend;
if (reloc_entry->address > input_section->size)
return bfd_reloc_outofrange;
uvalue = ((hi16_offset << 16) | (offset & 0xffff)) + val;
hi16_offset = (uvalue >> 16) << 1;
hi16_value = (hi16_value & ~0x37fff) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000);
score_bfd_put_32 (abfd, hi16_value, hi16_rel_addr);
offset = (uvalue & 0xffff) << 1;
addend = (addend & ~0x37fff) | (offset & 0x7fff) | ((offset << 1) & 0x30000);
score_bfd_put_32 (abfd, addend, (bfd_byte *) data + reloc_entry->address);
return bfd_reloc_ok;
}
/* Set the GP value for OUTPUT_BFD. Returns FALSE if this is a
dangerous relocation. */
static bfd_boolean
score_elf_assign_gp (bfd *output_bfd, bfd_vma *pgp)
{
unsigned int count;
asymbol **sym;
unsigned int i;
/* If we've already figured out what GP will be, just return it. */
*pgp = _bfd_get_gp_value (output_bfd);
if (*pgp)
return TRUE;
count = bfd_get_symcount (output_bfd);
sym = bfd_get_outsymbols (output_bfd);
/* The linker script will have created a symbol named `_gp' with the
appropriate value. */
if (sym == NULL)
i = count;
else
{
for (i = 0; i < count; i++, sym++)
{
const char *name;
name = bfd_asymbol_name (*sym);
if (*name == '_' && strcmp (name, "_gp") == 0)
{
*pgp = bfd_asymbol_value (*sym);
_bfd_set_gp_value (output_bfd, *pgp);
break;
}
}
}
if (i >= count)
{
/* Only get the error once. */
*pgp = 4;
_bfd_set_gp_value (output_bfd, *pgp);
return FALSE;
}
return TRUE;
}
/* We have to figure out the gp value, so that we can adjust the
symbol value correctly. We look up the symbol _gp in the output
BFD. If we can't find it, we're stuck. We cache it in the ELF
target data. We don't need to adjust the symbol value for an
external symbol if we are producing relocatable output. */
static bfd_reloc_status_type
score_elf_final_gp (bfd *output_bfd,
asymbol *symbol,
bfd_boolean relocatable,
char **error_message,
bfd_vma *pgp)
{
if (bfd_is_und_section (symbol->section)
&& ! relocatable)
{
*pgp = 0;
return bfd_reloc_undefined;
}
*pgp = _bfd_get_gp_value (output_bfd);
if (*pgp == 0
&& (! relocatable
|| (symbol->flags & BSF_SECTION_SYM) != 0))
{
if (relocatable)
{
/* Make up a value. */
*pgp = symbol->section->output_section->vma + 0x4000;
_bfd_set_gp_value (output_bfd, *pgp);
}
else if (!score_elf_assign_gp (output_bfd, pgp))
{
*error_message =
(char *) _("GP relative relocation when _gp not defined");
return bfd_reloc_dangerous;
}
}
return bfd_reloc_ok;
}
static bfd_reloc_status_type
score_elf_gprel15_with_gp (bfd *abfd,
asymbol *symbol,
arelent *reloc_entry,
asection *input_section,
bfd_boolean relocateable,
void * data,
bfd_vma gp ATTRIBUTE_UNUSED)
{
bfd_vma relocation;
unsigned long insn;
if (bfd_is_com_section (symbol->section))
relocation = 0;
else
relocation = symbol->value;
relocation += symbol->section->output_section->vma;
relocation += symbol->section->output_offset;
if (reloc_entry->address > input_section->size)
return bfd_reloc_outofrange;
insn = score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address);
if (((reloc_entry->addend & 0xffffc000) != 0)
&& ((reloc_entry->addend & 0xffffc000) != 0xffffc000))
return bfd_reloc_overflow;
insn = (insn & ~0x7fff) | (reloc_entry->addend & 0x7fff);
score_bfd_put_32 (abfd, insn, (bfd_byte *) data + reloc_entry->address);
if (relocateable)
reloc_entry->address += input_section->output_offset;
return bfd_reloc_ok;
}
static bfd_reloc_status_type
gprel32_with_gp (bfd *abfd, asymbol *symbol, arelent *reloc_entry,
asection *input_section, bfd_boolean relocatable,
void *data, bfd_vma gp)
{
bfd_vma relocation;
bfd_vma val;
if (bfd_is_com_section (symbol->section))
relocation = 0;
else
relocation = symbol->value;
relocation += symbol->section->output_section->vma;
relocation += symbol->section->output_offset;
if (reloc_entry->address > bfd_get_section_limit (abfd, input_section))
return bfd_reloc_outofrange;
/* Set val to the offset into the section or symbol. */
val = reloc_entry->addend;
if (reloc_entry->howto->partial_inplace)
val += score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address);
/* Adjust val for the final section location and GP value. If we
are producing relocatable output, we don't want to do this for
an external symbol. */
if (! relocatable
|| (symbol->flags & BSF_SECTION_SYM) != 0)
val += relocation - gp;
if (reloc_entry->howto->partial_inplace)
score_bfd_put_32 (abfd, val, (bfd_byte *) data + reloc_entry->address);
else
reloc_entry->addend = val;
if (relocatable)
reloc_entry->address += input_section->output_offset;
return bfd_reloc_ok;
}
static bfd_reloc_status_type
score_elf_gprel15_reloc (bfd *abfd,
arelent *reloc_entry,
asymbol *symbol,
void * data,
asection *input_section,
bfd *output_bfd,
char **error_message)
{
bfd_boolean relocateable;
bfd_reloc_status_type ret;
bfd_vma gp;
if (output_bfd != NULL
&& (symbol->flags & BSF_SECTION_SYM) == 0 && reloc_entry->addend == 0)
{
reloc_entry->address += input_section->output_offset;
return bfd_reloc_ok;
}
if (output_bfd != NULL)
relocateable = TRUE;
else
{
relocateable = FALSE;
output_bfd = symbol->section->output_section->owner;
}
ret = score_elf_final_gp (output_bfd, symbol, relocateable, error_message, &gp);
if (ret != bfd_reloc_ok)
return ret;
return score_elf_gprel15_with_gp (abfd, symbol, reloc_entry,
input_section, relocateable, data, gp);
}
/* Do a R_SCORE_GPREL32 relocation. This is a 32 bit value which must
become the offset from the gp register. */
static bfd_reloc_status_type
score_elf_gprel32_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
void *data, asection *input_section, bfd *output_bfd,
char **error_message)
{
bfd_boolean relocatable;
bfd_reloc_status_type ret;
bfd_vma gp;
/* R_SCORE_GPREL32 relocations are defined for local symbols only. */
if (output_bfd != NULL
&& (symbol->flags & BSF_SECTION_SYM) == 0
&& (symbol->flags & BSF_LOCAL) != 0)
{
*error_message = (char *)
_("32bits gp relative relocation occurs for an external symbol");
return bfd_reloc_outofrange;
}
if (output_bfd != NULL)
relocatable = TRUE;
else
{
relocatable = FALSE;
output_bfd = symbol->section->output_section->owner;
}
ret = score_elf_final_gp (output_bfd, symbol, relocatable, error_message, &gp);
if (ret != bfd_reloc_ok)
return ret;
gp = 0;
return gprel32_with_gp (abfd, symbol, reloc_entry, input_section,
relocatable, data, gp);
}
/* A howto special_function for R_SCORE_GOT15 relocations. This is just
like any other 16-bit relocation when applied to global symbols, but is
treated in the same as R_SCORE_HI16 when applied to local symbols. */
static bfd_reloc_status_type
score_elf_got15_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol,
void *data, asection *input_section,
bfd *output_bfd, char **error_message)
{
if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
|| bfd_is_und_section (bfd_get_section (symbol))
|| bfd_is_com_section (bfd_get_section (symbol)))
/* The relocation is against a global symbol. */
return bfd_elf_generic_reloc (abfd, reloc_entry, symbol, data,
input_section, output_bfd,
error_message);
return score_elf_hi16_reloc (abfd, reloc_entry, symbol, data,
input_section, output_bfd, error_message);
}
static bfd_reloc_status_type
score_elf_got_lo16_reloc (bfd *abfd,
arelent *reloc_entry,
asymbol *symbol ATTRIBUTE_UNUSED,
void * data,
asection *input_section,
bfd *output_bfd ATTRIBUTE_UNUSED,
char **error_message ATTRIBUTE_UNUSED)
{
bfd_vma addend = 0, offset = 0;
signed long val;
signed long hi16_offset, hi16_value, uvalue;
hi16_value = score_bfd_get_32 (abfd, hi16_rel_addr);
hi16_offset = ((((hi16_value >> 16) & 0x3) << 15) | (hi16_value & 0x7fff)) >> 1;
addend = score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address);
offset = ((((addend >> 16) & 0x3) << 15) | (addend & 0x7fff)) >> 1;
val = reloc_entry->addend;
if (reloc_entry->address > input_section->size)
return bfd_reloc_outofrange;
uvalue = ((hi16_offset << 16) | (offset & 0xffff)) + val;
if ((uvalue > -0x8000) && (uvalue < 0x7fff))
hi16_offset = 0;
else
hi16_offset = (uvalue >> 16) & 0x7fff;
hi16_value = (hi16_value & ~0x37fff) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000);
score_bfd_put_32 (abfd, hi16_value, hi16_rel_addr);
offset = (uvalue & 0xffff) << 1;
addend = (addend & ~0x37fff) | (offset & 0x7fff) | ((offset << 1) & 0x30000);
score_bfd_put_32 (abfd, addend, (bfd_byte *) data + reloc_entry->address);
return bfd_reloc_ok;
}
static reloc_howto_type elf32_score_howto_table[] =
{
/* No relocation. */
HOWTO (R_SCORE_NONE, /* type */
0, /* rightshift */
3, /* size (0 = byte, 1 = short, 2 = long) */
0, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_NONE", /* name */
FALSE, /* partial_inplace */
0, /* src_mask */
0, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_HI16 */
HOWTO (R_SCORE_HI16, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
score_elf_hi16_reloc, /* special_function */
"R_SCORE_HI16", /* name */
TRUE, /* partial_inplace */
0x37fff, /* src_mask */
0x37fff, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_LO16 */
HOWTO (R_SCORE_LO16, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
score_elf_lo16_reloc, /* special_function */
"R_SCORE_LO16", /* name */
TRUE, /* partial_inplace */
0x37fff, /* src_mask */
0x37fff, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_BCMP */
HOWTO (R_SCORE_BCMP, /* type */
1, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
TRUE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_BCMP", /* name */
FALSE, /* partial_inplace */
0x03e00381, /* src_mask */
0x03e00381, /* dst_mask */
FALSE), /* pcrel_offset */
/*R_SCORE_24 */
HOWTO (R_SCORE_24, /* type */
1, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
24, /* bitsize */
FALSE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_24", /* name */
FALSE, /* partial_inplace */
0x3ff7fff, /* src_mask */
0x3ff7fff, /* dst_mask */
FALSE), /* pcrel_offset */
/*R_SCORE_PC19 */
HOWTO (R_SCORE_PC19, /* type */
1, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
19, /* bitsize */
TRUE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_PC19", /* name */
FALSE, /* partial_inplace */
0x3ff03fe, /* src_mask */
0x3ff03fe, /* dst_mask */
FALSE), /* pcrel_offset */
/*R_SCORE16_11 */
HOWTO (R_SCORE16_11, /* type */
1, /* rightshift */
1, /* size (0 = byte, 1 = short, 2 = long) */
11, /* bitsize */
FALSE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE16_11", /* name */
FALSE, /* partial_inplace */
0x000000ffe, /* src_mask */
0x000000ffe, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE16_PC8 */
HOWTO (R_SCORE16_PC8, /* type */
1, /* rightshift */
1, /* size (0 = byte, 1 = short, 2 = long) */
9, /* bitsize */
TRUE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE16_PC8", /* name */
FALSE, /* partial_inplace */
0x000001ff, /* src_mask */
0x000001ff, /* dst_mask */
FALSE), /* pcrel_offset */
/* 32 bit absolute */
HOWTO (R_SCORE_ABS32, /* type 8 */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
32, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_bitfield, /* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_ABS32", /* name */
FALSE, /* partial_inplace */
0xffffffff, /* src_mask */
0xffffffff, /* dst_mask */
FALSE), /* pcrel_offset */
/* 16 bit absolute */
HOWTO (R_SCORE_ABS16, /* type 11 */
0, /* rightshift */
1, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_bitfield, /* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_ABS16", /* name */
FALSE, /* partial_inplace */
0x0000ffff, /* src_mask */
0x0000ffff, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_DUMMY2 */
HOWTO (R_SCORE_DUMMY2, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_DUMMY2", /* name */
TRUE, /* partial_inplace */
0x00007fff, /* src_mask */
0x00007fff, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_GP15 */
HOWTO (R_SCORE_GP15, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
score_elf_gprel15_reloc,/* special_function */
"R_SCORE_GP15", /* name */
TRUE, /* partial_inplace */
0x00007fff, /* src_mask */
0x00007fff, /* dst_mask */
FALSE), /* pcrel_offset */
/* GNU extension to record C++ vtable hierarchy. */
HOWTO (R_SCORE_GNU_VTINHERIT, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
0, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
NULL, /* special_function */
"R_SCORE_GNU_VTINHERIT", /* name */
FALSE, /* partial_inplace */
0, /* src_mask */
0, /* dst_mask */
FALSE), /* pcrel_offset */
/* GNU extension to record C++ vtable member usage */
HOWTO (R_SCORE_GNU_VTENTRY, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
0, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
_bfd_elf_rel_vtable_reloc_fn, /* special_function */
"R_SCORE_GNU_VTENTRY", /* name */
FALSE, /* partial_inplace */
0, /* src_mask */
0, /* dst_mask */
FALSE), /* pcrel_offset */
/* Reference to global offset table. */
HOWTO (R_SCORE_GOT15, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_signed, /* complain_on_overflow */
score_elf_got15_reloc, /* special_function */
"R_SCORE_GOT15", /* name */
TRUE, /* partial_inplace */
0x00007fff, /* src_mask */
0x00007fff, /* dst_mask */
FALSE), /* pcrel_offset */
/* Low 16 bits of displacement in global offset table. */
HOWTO (R_SCORE_GOT_LO16, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
score_elf_got_lo16_reloc, /* special_function */
"R_SCORE_GOT_LO16", /* name */
TRUE, /* partial_inplace */
0x37ffe, /* src_mask */
0x37ffe, /* dst_mask */
FALSE), /* pcrel_offset */
/* 15 bit call through global offset table. */
HOWTO (R_SCORE_CALL15, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_signed, /* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_CALL15", /* name */
TRUE, /* partial_inplace */
0x0000ffff, /* src_mask */
0x0000ffff, /* dst_mask */
FALSE), /* pcrel_offset */
/* 32 bit GP relative reference. */
HOWTO (R_SCORE_GPREL32, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
32, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
score_elf_gprel32_reloc, /* special_function */
"R_SCORE_GPREL32", /* name */
TRUE, /* partial_inplace */
0xffffffff, /* src_mask */
0xffffffff, /* dst_mask */
FALSE), /* pcrel_offset */
/* 32 bit symbol relative relocation. */
HOWTO (R_SCORE_REL32, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
32, /* bitsize */
FALSE, /* pc_relative */
0, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_REL32", /* name */
TRUE, /* partial_inplace */
0xffffffff, /* src_mask */
0xffffffff, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_DUMMY_HI16 */
HOWTO (R_SCORE_DUMMY_HI16, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
16, /* bitsize */
FALSE, /* pc_relative */
1, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
score_elf_hi16_reloc, /* special_function */
"R_SCORE_DUMMY_HI16", /* name */
TRUE, /* partial_inplace */
0x37fff, /* src_mask */
0x37fff, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_IMM30 */
HOWTO (R_SCORE_IMM30, /* type */
2, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
30, /* bitsize */
FALSE, /* pc_relative */
7, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_IMM30", /* name */
FALSE, /* partial_inplace */
0x7f7fff7f80LL, /* src_mask */
0x7f7fff7f80LL, /* dst_mask */
FALSE), /* pcrel_offset */
/* R_SCORE_IMM32 */
HOWTO (R_SCORE_IMM32, /* type */
0, /* rightshift */
2, /* size (0 = byte, 1 = short, 2 = long) */
32, /* bitsize */
FALSE, /* pc_relative */
5, /* bitpos */
complain_overflow_dont,/* complain_on_overflow */
bfd_elf_generic_reloc, /* special_function */
"R_SCORE_IMM32", /* name */
FALSE, /* partial_inplace */
0x7f7fff7fe0LL, /* src_mask */
0x7f7fff7fe0LL, /* dst_mask */
FALSE), /* pcrel_offset */
};
struct score_reloc_map
{
bfd_reloc_code_real_type bfd_reloc_val;
unsigned char elf_reloc_val;
};
static const struct score_reloc_map elf32_score_reloc_map[] =
{
{BFD_RELOC_NONE, R_SCORE_NONE},
{BFD_RELOC_HI16_S, R_SCORE_HI16},
{BFD_RELOC_LO16, R_SCORE_LO16},
{BFD_RELOC_SCORE_BCMP, R_SCORE_BCMP},
{BFD_RELOC_SCORE_JMP, R_SCORE_24},
{BFD_RELOC_SCORE_BRANCH, R_SCORE_PC19},
{BFD_RELOC_SCORE16_JMP, R_SCORE16_11},
{BFD_RELOC_SCORE16_BRANCH, R_SCORE16_PC8},
{BFD_RELOC_32, R_SCORE_ABS32},
{BFD_RELOC_16, R_SCORE_ABS16},
{BFD_RELOC_SCORE_DUMMY2, R_SCORE_DUMMY2},
{BFD_RELOC_SCORE_GPREL15, R_SCORE_GP15},
{BFD_RELOC_VTABLE_INHERIT, R_SCORE_GNU_VTINHERIT},
{BFD_RELOC_VTABLE_ENTRY, R_SCORE_GNU_VTENTRY},
{BFD_RELOC_SCORE_GOT15, R_SCORE_GOT15},
{BFD_RELOC_SCORE_GOT_LO16, R_SCORE_GOT_LO16},
{BFD_RELOC_SCORE_CALL15, R_SCORE_CALL15},
{BFD_RELOC_GPREL32, R_SCORE_GPREL32},
{BFD_RELOC_32_PCREL, R_SCORE_REL32},
{BFD_RELOC_SCORE_DUMMY_HI16, R_SCORE_DUMMY_HI16},
{BFD_RELOC_SCORE_IMM30, R_SCORE_IMM30},
{BFD_RELOC_SCORE_IMM32, R_SCORE_IMM32},
};
/* got_entries only match if they're identical, except for gotidx, so
use all fields to compute the hash, and compare the appropriate
union members. */
static hashval_t
score_elf_got_entry_hash (const void *entry_)
{
const struct score_got_entry *entry = (struct score_got_entry *)entry_;
return entry->symndx
+ (!entry->abfd ? entry->d.address : entry->abfd->id);
}
static int
score_elf_got_entry_eq (const void *entry1, const void *entry2)
{
const struct score_got_entry *e1 = (struct score_got_entry *)entry1;
const struct score_got_entry *e2 = (struct score_got_entry *)entry2;
return e1->abfd == e2->abfd && e1->symndx == e2->symndx
&& (! e1->abfd ? e1->d.address == e2->d.address
: e1->symndx >= 0 ? e1->d.addend == e2->d.addend
: e1->d.h == e2->d.h);
}
/* If H needs a GOT entry, assign it the highest available dynamic
index. Otherwise, assign it the lowest available dynamic
index. */
static bfd_boolean
score_elf_sort_hash_table_f (struct score_elf_link_hash_entry *h, void *data)
{
struct score_elf_hash_sort_data *hsd = data;
/* Symbols without dynamic symbol table entries aren't interesting at all. */
if (h->root.dynindx == -1)
return TRUE;
/* Global symbols that need GOT entries that are not explicitly
referenced are marked with got offset 2. Those that are
referenced get a 1, and those that don't need GOT entries get
-1. */
if (h->root.got.offset == 2)
{
if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx)
hsd->low = (struct elf_link_hash_entry *) h;
h->root.dynindx = hsd->max_unref_got_dynindx++;
}
else if (h->root.got.offset != 1)
h->root.dynindx = hsd->max_non_got_dynindx++;
else
{
h->root.dynindx = --hsd->min_got_dynindx;
hsd->low = (struct elf_link_hash_entry *) h;
}
return TRUE;
}
static asection *
score_elf_got_section (bfd *abfd, bfd_boolean maybe_excluded)
{
asection *sgot = bfd_get_linker_section (abfd, ".got");
if (sgot == NULL || (! maybe_excluded && (sgot->flags & SEC_EXCLUDE) != 0))
return NULL;
return sgot;
}
/* Returns the GOT information associated with the link indicated by
INFO. If SGOTP is non-NULL, it is filled in with the GOT section. */
static struct score_got_info *
score_elf_got_info (bfd *abfd, asection **sgotp)
{
asection *sgot;
struct score_got_info *g;
sgot = score_elf_got_section (abfd, TRUE);
BFD_ASSERT (sgot != NULL);
BFD_ASSERT (elf_section_data (sgot) != NULL);
g = score_elf_section_data (sgot)->u.got_info;
BFD_ASSERT (g != NULL);
if (sgotp)
*sgotp = sgot;
return g;
}
/* Sort the dynamic symbol table so that symbols that need GOT entries
appear towards the end. This reduces the amount of GOT space
required. MAX_LOCAL is used to set the number of local symbols
known to be in the dynamic symbol table. During
s3_bfd_score_elf_size_dynamic_sections, this value is 1. Afterward, the
section symbols are added and the count is higher. */
static bfd_boolean
score_elf_sort_hash_table (struct bfd_link_info *info,
unsigned long max_local)
{
struct score_elf_hash_sort_data hsd;
struct score_got_info *g;
bfd *dynobj;
dynobj = elf_hash_table (info)->dynobj;
g = score_elf_got_info (dynobj, NULL);
hsd.low = NULL;
hsd.max_unref_got_dynindx =
hsd.min_got_dynindx = elf_hash_table (info)->dynsymcount
/* In the multi-got case, assigned_gotno of the master got_info
indicate the number of entries that aren't referenced in the
primary GOT, but that must have entries because there are
dynamic relocations that reference it. Since they aren't
referenced, we move them to the end of the GOT, so that they
don't prevent other entries that are referenced from getting
too large offsets. */
- (g->next ? g->assigned_gotno : 0);
hsd.max_non_got_dynindx = max_local;
score_elf_link_hash_traverse (elf_hash_table (info),
score_elf_sort_hash_table_f,
&hsd);
/* There should have been enough room in the symbol table to
accommodate both the GOT and non-GOT symbols. */
BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx);
BFD_ASSERT ((unsigned long)hsd.max_unref_got_dynindx
<= elf_hash_table (info)->dynsymcount);
/* Now we know which dynamic symbol has the lowest dynamic symbol
table index in the GOT. */
g->global_gotsym = hsd.low;
return TRUE;
}
/* Create an entry in an score ELF linker hash table. */
static struct bfd_hash_entry *
score_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
struct bfd_hash_table *table,
const char *string)
{
struct score_elf_link_hash_entry *ret = (struct score_elf_link_hash_entry *) entry;
/* Allocate the structure if it has not already been allocated by a subclass. */
if (ret == NULL)
ret = bfd_hash_allocate (table, sizeof (struct score_elf_link_hash_entry));
if (ret == NULL)
return (struct bfd_hash_entry *) ret;
/* Call the allocation method of the superclass. */
ret = ((struct score_elf_link_hash_entry *)
_bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret, table, string));
if (ret != NULL)
{
ret->possibly_dynamic_relocs = 0;
ret->readonly_reloc = FALSE;
ret->no_fn_stub = FALSE;
ret->forced_local = FALSE;
}
return (struct bfd_hash_entry *) ret;
}
/* Returns the first relocation of type r_type found, beginning with
RELOCATION. RELEND is one-past-the-end of the relocation table. */
static const Elf_Internal_Rela *
score_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type,
const Elf_Internal_Rela *relocation,
const Elf_Internal_Rela *relend)
{
while (relocation < relend)
{
if (ELF32_R_TYPE (relocation->r_info) == r_type)
return relocation;
++relocation;
}
/* We didn't find it. */
bfd_set_error (bfd_error_bad_value);
return NULL;
}
/* This function is called via qsort() to sort the dynamic relocation
entries by increasing r_symndx value. */
static int
score_elf_sort_dynamic_relocs (const void *arg1, const void *arg2)
{
Elf_Internal_Rela int_reloc1;
Elf_Internal_Rela int_reloc2;
bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1);
bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2);
return (ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info));
}
/* Return whether a relocation is against a local symbol. */
static bfd_boolean
score_elf_local_relocation_p (bfd *input_bfd,
const Elf_Internal_Rela *relocation,
asection **local_sections,
bfd_boolean check_forced)
{
unsigned long r_symndx;
Elf_Internal_Shdr *symtab_hdr;
struct score_elf_link_hash_entry *h;
size_t extsymoff;
r_symndx = ELF32_R_SYM (relocation->r_info);
symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
if (r_symndx < extsymoff)
return TRUE;
if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL)
return TRUE;
if (check_forced)
{
/* Look up the hash table to check whether the symbol was forced local. */
h = (struct score_elf_link_hash_entry *)
elf_sym_hashes (input_bfd) [r_symndx - extsymoff];
/* Find the real hash-table entry for this symbol. */
while (h->root.root.type == bfd_link_hash_indirect
|| h->root.root.type == bfd_link_hash_warning)
h = (struct score_elf_link_hash_entry *) h->root.root.u.i.link;
if (h->root.forced_local)
return TRUE;
}
return FALSE;
}
/* Returns the dynamic relocation section for DYNOBJ. */
static asection *
score_elf_rel_dyn_section (bfd *dynobj, bfd_boolean create_p)
{
static const char dname[] = ".rel.dyn";
asection *sreloc;
sreloc = bfd_get_linker_section (dynobj, dname);
if (sreloc == NULL && create_p)
{
sreloc = bfd_make_section_anyway_with_flags (dynobj, dname,
(SEC_ALLOC
| SEC_LOAD
| SEC_HAS_CONTENTS
| SEC_IN_MEMORY
| SEC_LINKER_CREATED
| SEC_READONLY));
if (sreloc == NULL
|| ! bfd_set_section_alignment (dynobj, sreloc,
SCORE_ELF_LOG_FILE_ALIGN (dynobj)))
return NULL;
}
return sreloc;
}
static void
score_elf_allocate_dynamic_relocations (bfd *abfd, unsigned int n)
{
asection *s;
s = score_elf_rel_dyn_section (abfd, FALSE);
BFD_ASSERT (s != NULL);
if (s->size == 0)
{
/* Make room for a null element. */
s->size += SCORE_ELF_REL_SIZE (abfd);
++s->reloc_count;
}
s->size += n * SCORE_ELF_REL_SIZE (abfd);
}
/* Create a rel.dyn relocation for the dynamic linker to resolve. REL
is the original relocation, which is now being transformed into a
dynamic relocation. The ADDENDP is adjusted if necessary; the
caller should store the result in place of the original addend. */
static bfd_boolean
score_elf_create_dynamic_relocation (bfd *output_bfd,
struct bfd_link_info *info,
const Elf_Internal_Rela *rel,
struct score_elf_link_hash_entry *h,
bfd_vma symbol,
bfd_vma *addendp, asection *input_section)
{
Elf_Internal_Rela outrel[3];
asection *sreloc;
bfd *dynobj;
int r_type;
long indx;
bfd_boolean defined_p;
r_type = ELF32_R_TYPE (rel->r_info);
dynobj = elf_hash_table (info)->dynobj;
sreloc = score_elf_rel_dyn_section (dynobj, FALSE);
BFD_ASSERT (sreloc != NULL);
BFD_ASSERT (sreloc->contents != NULL);
BFD_ASSERT (sreloc->reloc_count * SCORE_ELF_REL_SIZE (output_bfd) < sreloc->size);
outrel[0].r_offset =
_bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset);
outrel[1].r_offset =
_bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset);
outrel[2].r_offset =
_bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset);
if (outrel[0].r_offset == MINUS_ONE)
/* The relocation field has been deleted. */
return TRUE;
if (outrel[0].r_offset == MINUS_TWO)
{
/* The relocation field has been converted into a relative value of
some sort. Functions like _bfd_elf_write_section_eh_frame expect
the field to be fully relocated, so add in the symbol's value. */
*addendp += symbol;
return TRUE;
}
/* We must now calculate the dynamic symbol table index to use
in the relocation. */
if (h != NULL
&& (! info->symbolic || !h->root.def_regular)
/* h->root.dynindx may be -1 if this symbol was marked to
become local. */
&& h->root.dynindx != -1)
{
indx = h->root.dynindx;
/* ??? glibc's ld.so just adds the final GOT entry to the
relocation field. It therefore treats relocs against
defined symbols in the same way as relocs against
undefined symbols. */
defined_p = FALSE;
}
else
{
indx = 0;
defined_p = TRUE;
}
/* If the relocation was previously an absolute relocation and
this symbol will not be referred to by the relocation, we must
adjust it by the value we give it in the dynamic symbol table.
Otherwise leave the job up to the dynamic linker. */
if (defined_p && r_type != R_SCORE_REL32)
*addendp += symbol;
/* The relocation is always an REL32 relocation because we don't
know where the shared library will wind up at load-time. */
outrel[0].r_info = ELF32_R_INFO ((unsigned long) indx, R_SCORE_REL32);
/* For strict adherence to the ABI specification, we should
generate a R_SCORE_64 relocation record by itself before the
_REL32/_64 record as well, such that the addend is read in as
a 64-bit value (REL32 is a 32-bit relocation, after all).
However, since none of the existing ELF64 SCORE dynamic
loaders seems to care, we don't waste space with these
artificial relocations. If this turns out to not be true,
score_elf_allocate_dynamic_relocations() should be tweaked so
as to make room for a pair of dynamic relocations per
invocation if ABI_64_P, and here we should generate an
additional relocation record with R_SCORE_64 by itself for a
NULL symbol before this relocation record. */
outrel[1].r_info = ELF32_R_INFO (0, R_SCORE_NONE);
outrel[2].r_info = ELF32_R_INFO (0, R_SCORE_NONE);
/* Adjust the output offset of the relocation to reference the
correct location in the output file. */
outrel[0].r_offset += (input_section->output_section->vma
+ input_section->output_offset);
outrel[1].r_offset += (input_section->output_section->vma
+ input_section->output_offset);
outrel[2].r_offset += (input_section->output_section->vma
+ input_section->output_offset);
/* Put the relocation back out. We have to use the special
relocation outputter in the 64-bit case since the 64-bit
relocation format is non-standard. */
bfd_elf32_swap_reloc_out
(output_bfd, &outrel[0],
(sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel)));
/* We've now added another relocation. */
++sreloc->reloc_count;
/* Make sure the output section is writable. The dynamic linker
will be writing to it. */
elf_section_data (input_section->output_section)->this_hdr.sh_flags |= SHF_WRITE;
return TRUE;
}
static bfd_boolean
score_elf_create_got_section (bfd *abfd,
struct bfd_link_info *info,
bfd_boolean maybe_exclude)
{
flagword flags;
asection *s;
struct elf_link_hash_entry *h;
struct bfd_link_hash_entry *bh;
struct score_got_info *g;
bfd_size_type amt;
/* This function may be called more than once. */
s = score_elf_got_section (abfd, TRUE);
if (s)
{
if (! maybe_exclude)
s->flags &= ~SEC_EXCLUDE;
return TRUE;
}
flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED);
if (maybe_exclude)
flags |= SEC_EXCLUDE;
/* We have to use an alignment of 2**4 here because this is hardcoded
in the function stub generation and in the linker script. */
s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
elf_hash_table (info)->sgot = s;
if (s == NULL
|| ! bfd_set_section_alignment (abfd, s, 4))
return FALSE;
/* Define the symbol _GLOBAL_OFFSET_TABLE_. We don't do this in the
linker script because we don't want to define the symbol if we
are not creating a global offset table. */
bh = NULL;
if (! (_bfd_generic_link_add_one_symbol
(info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s,
0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
return FALSE;
h = (struct elf_link_hash_entry *) bh;
h->non_elf = 0;
h->def_regular = 1;
h->type = STT_OBJECT;
elf_hash_table (info)->hgot = h;
if (bfd_link_pic (info) && ! bfd_elf_link_record_dynamic_symbol (info, h))
return FALSE;
amt = sizeof (struct score_got_info);
g = bfd_alloc (abfd, amt);
if (g == NULL)
return FALSE;
g->global_gotsym = NULL;
g->global_gotno = 0;
g->local_gotno = SCORE_RESERVED_GOTNO;
g->assigned_gotno = SCORE_RESERVED_GOTNO;
g->next = NULL;
g->got_entries = htab_try_create (1, score_elf_got_entry_hash,
score_elf_got_entry_eq, NULL);
if (g->got_entries == NULL)
return FALSE;
score_elf_section_data (s)->u.got_info = g;
score_elf_section_data (s)->elf.this_hdr.sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_SCORE_GPREL;
return TRUE;
}
/* Calculate the %high function. */
static bfd_vma
score_elf_high (bfd_vma value)
{
return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff;
}
/* Create a local GOT entry for VALUE. Return the index of the entry,
or -1 if it could not be created. */
static struct score_got_entry *
score_elf_create_local_got_entry (bfd *abfd,
bfd *ibfd ATTRIBUTE_UNUSED,
struct score_got_info *gg,
asection *sgot, bfd_vma value,
unsigned long r_symndx ATTRIBUTE_UNUSED,
struct score_elf_link_hash_entry *h ATTRIBUTE_UNUSED,
int r_type ATTRIBUTE_UNUSED)
{
struct score_got_entry entry, **loc;
struct score_got_info *g;
entry.abfd = NULL;
entry.symndx = -1;
entry.d.address = value;
g = gg;
loc = (struct score_got_entry **) htab_find_slot (g->got_entries, &entry, INSERT);
if (*loc)
return *loc;
entry.gotidx = SCORE_ELF_GOT_SIZE (abfd) * g->assigned_gotno++;
*loc = bfd_alloc (abfd, sizeof entry);
if (! *loc)
return NULL;
memcpy (*loc, &entry, sizeof entry);
if (g->assigned_gotno >= g->local_gotno)
{
(*loc)->gotidx = -1;
/* We didn't allocate enough space in the GOT. */
_bfd_error_handler
(_("not enough GOT space for local GOT entries"));
bfd_set_error (bfd_error_bad_value);
return NULL;
}
score_bfd_put_32 (abfd, value, (sgot->contents + entry.gotidx));
return *loc;
}
/* Find a GOT entry whose higher-order 16 bits are the same as those
for value. Return the index into the GOT for this entry. */
static bfd_vma
score_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
bfd_vma value, bfd_boolean external)
{
asection *sgot;
struct score_got_info *g;
struct score_got_entry *entry;
if (!external)
{
/* Although the ABI says that it is "the high-order 16 bits" that we
want, it is really the %high value. The complete value is
calculated with a `addiu' of a LO16 relocation, just as with a
HI16/LO16 pair. */
value = score_elf_high (value) << 16;
}
g = score_elf_got_info (elf_hash_table (info)->dynobj, &sgot);
entry = score_elf_create_local_got_entry (abfd, ibfd, g, sgot, value, 0, NULL,
R_SCORE_GOT15);
if (entry)
return entry->gotidx;
else
return MINUS_ONE;
}
static void
s3_bfd_score_elf_hide_symbol (struct bfd_link_info *info,
struct elf_link_hash_entry *entry,
bfd_boolean force_local)
{
bfd *dynobj;
asection *got;
struct score_got_info *g;
struct score_elf_link_hash_entry *h;
h = (struct score_elf_link_hash_entry *) entry;
if (h->forced_local)
return;
h->forced_local = TRUE;
dynobj = elf_hash_table (info)->dynobj;
if (dynobj != NULL && force_local)
{
got = score_elf_got_section (dynobj, FALSE);
if (got == NULL)
return;
g = score_elf_section_data (got)->u.got_info;
if (g->next)
{
struct score_got_entry e;
struct score_got_info *gg = g;
/* Since we're turning what used to be a global symbol into a
local one, bump up the number of local entries of each GOT
that had an entry for it. This will automatically decrease
the number of global entries, since global_gotno is actually
the upper limit of global entries. */
e.abfd = dynobj;
e.symndx = -1;
e.d.h = h;
for (g = g->next; g != gg; g = g->next)
if (htab_find (g->got_entries, &e))
{
BFD_ASSERT (g->global_gotno > 0);
g->local_gotno++;
g->global_gotno--;
}
/* If this was a global symbol forced into the primary GOT, we
no longer need an entry for it. We can't release the entry
at this point, but we must at least stop counting it as one
of the symbols that required a forced got entry. */
if (h->root.got.offset == 2)
{
BFD_ASSERT (gg->assigned_gotno > 0);
gg->assigned_gotno--;
}
}
else if (g->global_gotno == 0 && g->global_gotsym == NULL)
/* If we haven't got through GOT allocation yet, just bump up the
number of local entries, as this symbol won't be counted as
global. */
g->local_gotno++;
else if (h->root.got.offset == 1)
{
/* If we're past non-multi-GOT allocation and this symbol had
been marked for a global got entry, give it a local entry
instead. */
BFD_ASSERT (g->global_gotno > 0);
g->local_gotno++;
g->global_gotno--;
}
}
_bfd_elf_link_hash_hide_symbol (info, &h->root, force_local);
}
/* If H is a symbol that needs a global GOT entry, but has a dynamic
symbol table index lower than any we've seen to date, record it for
posterity. */
static bfd_boolean
score_elf_record_global_got_symbol (struct elf_link_hash_entry *h,
bfd *abfd,
struct bfd_link_info *info,
struct score_got_info *g)
{
struct score_got_entry entry, **loc;
/* A global symbol in the GOT must also be in the dynamic symbol table. */
if (h->dynindx == -1)
{
switch (ELF_ST_VISIBILITY (h->other))
{
case STV_INTERNAL:
case STV_HIDDEN:
s3_bfd_score_elf_hide_symbol (info, h, TRUE);
break;
}
if (!bfd_elf_link_record_dynamic_symbol (info, h))
return FALSE;
}
entry.abfd = abfd;
entry.symndx = -1;
entry.d.h = (struct score_elf_link_hash_entry *)h;
loc = (struct score_got_entry **)htab_find_slot (g->got_entries, &entry, INSERT);
/* If we've already marked this entry as needing GOT space, we don't
need to do it again. */
if (*loc)
return TRUE;
*loc = bfd_alloc (abfd, sizeof entry);
if (! *loc)
return FALSE;
entry.gotidx = -1;
memcpy (*loc, &entry, sizeof (entry));
if (h->got.offset != MINUS_ONE)
return TRUE;
/* By setting this to a value other than -1, we are indicating that
there needs to be a GOT entry for H. Avoid using zero, as the
generic ELF copy_indirect_symbol tests for <= 0. */
h->got.offset = 1;
return TRUE;
}
/* Reserve space in G for a GOT entry containing the value of symbol
SYMNDX in input bfd ABDF, plus ADDEND. */
static bfd_boolean
score_elf_record_local_got_symbol (bfd *abfd,
long symndx,
bfd_vma addend,
struct score_got_info *g)
{
struct score_got_entry entry, **loc;
entry.abfd = abfd;
entry.symndx = symndx;
entry.d.addend = addend;
loc = (struct score_got_entry **)htab_find_slot (g->got_entries, &entry, INSERT);
if (*loc)
return TRUE;
entry.gotidx = g->local_gotno++;
*loc = bfd_alloc (abfd, sizeof(entry));
if (! *loc)
return FALSE;
memcpy (*loc, &entry, sizeof (entry));
return TRUE;
}
/* Returns the GOT offset at which the indicated address can be found.
If there is not yet a GOT entry for this value, create one.
Returns -1 if no satisfactory GOT offset can be found. */
static bfd_vma
score_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info,
bfd_vma value, unsigned long r_symndx,
struct score_elf_link_hash_entry *h, int r_type)
{
asection *sgot;
struct score_got_info *g;
struct score_got_entry *entry;
g = score_elf_got_info (elf_hash_table (info)->dynobj, &sgot);
entry = score_elf_create_local_got_entry (abfd, ibfd, g, sgot, value,
r_symndx, h, r_type);
if (!entry)
return MINUS_ONE;
else
return entry->gotidx;
}
/* Returns the GOT index for the global symbol indicated by H. */
static bfd_vma
score_elf_global_got_index (bfd *abfd, struct elf_link_hash_entry *h)
{
bfd_vma got_index;
asection *sgot;
struct score_got_info *g;
long global_got_dynindx = 0;
g = score_elf_got_info (abfd, &sgot);
if (g->global_gotsym != NULL)
global_got_dynindx = g->global_gotsym->dynindx;
/* Once we determine the global GOT entry with the lowest dynamic
symbol table index, we must put all dynamic symbols with greater
indices into the GOT. That makes it easy to calculate the GOT
offset. */
BFD_ASSERT (h->dynindx >= global_got_dynindx);
got_index = ((h->dynindx - global_got_dynindx + g->local_gotno) * SCORE_ELF_GOT_SIZE (abfd));
BFD_ASSERT (got_index < sgot->size);
return got_index;
}
/* Returns the offset for the entry at the INDEXth position in the GOT. */
static bfd_vma
score_elf_got_offset_from_index (bfd *dynobj,
bfd *output_bfd,
bfd *input_bfd ATTRIBUTE_UNUSED,
bfd_vma got_index)
{
asection *sgot;
bfd_vma gp;
score_elf_got_info (dynobj, &sgot);
gp = _bfd_get_gp_value (output_bfd);
return sgot->output_section->vma + sgot->output_offset + got_index - gp;
}
/* Follow indirect and warning hash entries so that each got entry
points to the final symbol definition. P must point to a pointer
to the hash table we're traversing. Since this traversal may
modify the hash table, we set this pointer to NULL to indicate
we've made a potentially-destructive change to the hash table, so
the traversal must be restarted. */
static int
score_elf_resolve_final_got_entry (void **entryp, void *p)
{
struct score_got_entry *entry = (struct score_got_entry *)*entryp;
htab_t got_entries = *(htab_t *)p;
if (entry->abfd != NULL && entry->symndx == -1)
{
struct score_elf_link_hash_entry *h = entry->d.h;
while (h->root.root.type == bfd_link_hash_indirect
|| h->root.root.type == bfd_link_hash_warning)
h = (struct score_elf_link_hash_entry *) h->root.root.u.i.link;
if (entry->d.h == h)
return 1;
entry->d.h = h;
/* If we can't find this entry with the new bfd hash, re-insert
it, and get the traversal restarted. */
if (! htab_find (got_entries, entry))
{
htab_clear_slot (got_entries, entryp);
entryp = htab_find_slot (got_entries, entry, INSERT);
if (! *entryp)
*entryp = entry;
/* Abort the traversal, since the whole table may have
moved, and leave it up to the parent to restart the
process. */
*(htab_t *)p = NULL;
return 0;
}
/* We might want to decrement the global_gotno count, but it's
either too early or too late for that at this point. */
}
return 1;
}
/* Turn indirect got entries in a got_entries table into their final locations. */
static void
score_elf_resolve_final_got_entries (struct score_got_info *g)
{
htab_t got_entries;
do
{
got_entries = g->got_entries;
htab_traverse (got_entries,
score_elf_resolve_final_got_entry,
&got_entries);
}
while (got_entries == NULL);
}
/* Add INCREMENT to the reloc (of type HOWTO) at ADDRESS. for -r */
static void
score_elf_add_to_rel (bfd *abfd,
bfd_byte *address,
reloc_howto_type *howto,
bfd_signed_vma increment)
{
bfd_signed_vma addend;
bfd_vma contents;
unsigned long offset;
unsigned long r_type = howto->type;
unsigned long hi16_addend, hi16_offset, hi16_value, uvalue;
contents = score_bfd_get_32 (abfd, address);
/* Get the (signed) value from the instruction. */
addend = contents & howto->src_mask;
if (addend & ((howto->src_mask + 1) >> 1))
{
bfd_signed_vma mask;
mask = -1;
mask &= ~howto->src_mask;
addend |= mask;
}
/* Add in the increment, (which is a byte value). */
switch (r_type)
{
case R_SCORE_PC19:
offset =
(((contents & howto->src_mask) & 0x3ff0000) >> 6) | ((contents & howto->src_mask) & 0x3ff);
offset += increment;
contents =
(contents & ~howto->
src_mask) | (((offset << 6) & howto->src_mask) & 0x3ff0000) | (offset & 0x3ff);
score_bfd_put_32 (abfd, contents, address);
break;
case R_SCORE_HI16:
break;
case R_SCORE_LO16:
hi16_addend = score_bfd_get_32 (abfd, address - 4);
hi16_offset = ((((hi16_addend >> 16) & 0x3) << 15) | (hi16_addend & 0x7fff)) >> 1;
offset = ((((contents >> 16) & 0x3) << 15) | (contents & 0x7fff)) >> 1;
offset = (hi16_offset << 16) | (offset & 0xffff);
uvalue = increment + offset;
hi16_offset = (uvalue >> 16) << 1;
hi16_value = (hi16_addend & (~(howto->dst_mask)))
| (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000);
score_bfd_put_32 (abfd, hi16_value, address - 4);
offset = (uvalue & 0xffff) << 1;
contents = (contents & (~(howto->dst_mask))) | (offset & 0x7fff) | ((offset << 1) & 0x30000);
score_bfd_put_32 (abfd, contents, address);
break;
case R_SCORE_24:
offset =
(((contents & howto->src_mask) >> 1) & 0x1ff8000) | ((contents & howto->src_mask) & 0x7fff);
offset += increment;
contents =
(contents & ~howto->
src_mask) | (((offset << 1) & howto->src_mask) & 0x3ff0000) | (offset & 0x7fff);
score_bfd_put_32 (abfd, contents, address);
break;
case R_SCORE16_11:
contents = score_bfd_get_16 (abfd, address);
offset = contents & howto->src_mask;
offset += increment;
contents = (contents & ~howto->src_mask) | (offset & howto->src_mask);
score_bfd_put_16 (abfd, contents, address);
break;
case R_SCORE16_PC8:
contents = score_bfd_get_16 (abfd, address);
offset = (contents & howto->src_mask) + ((increment >> 1) & 0x1ff);
contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask);
score_bfd_put_16 (abfd, contents, address);
break;
case R_SCORE_BCMP:
contents = score_bfd_get_32 (abfd, address);
offset = (contents & howto->src_mask);
offset <<= howto->rightshift;
offset += increment;
offset >>= howto->rightshift;
contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask);
score_bfd_put_32 (abfd, contents, address);
break;
case R_SCORE_IMM30:
contents = score_bfd_get_48 (abfd, address);
offset = (contents & howto->src_mask);
offset <<= howto->rightshift;
offset += increment;
offset >>= howto->rightshift;
contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask);
score_bfd_put_48 (abfd, contents, address);
break;
case R_SCORE_IMM32:
contents = score_bfd_get_48 (abfd, address);
offset = (contents & howto->src_mask);
offset += increment;
contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask);
score_bfd_put_48 (abfd, contents, address);
break;
default:
addend += increment;
contents = (contents & ~howto->dst_mask) | (addend & howto->dst_mask);
score_bfd_put_32 (abfd, contents, address);
break;
}
}
/* Perform a relocation as part of a final link. */
static bfd_reloc_status_type
score_elf_final_link_relocate (reloc_howto_type *howto,
bfd *input_bfd,
bfd *output_bfd,
asection *input_section,
bfd_byte *contents,
Elf_Internal_Rela *rel,
Elf_Internal_Rela *relocs,
bfd_vma symbol,
struct bfd_link_info *info,
const char *sym_name ATTRIBUTE_UNUSED,
int sym_flags ATTRIBUTE_UNUSED,
struct score_elf_link_hash_entry *h,
asection **local_sections,
bfd_boolean gp_disp_p)
{
unsigned long r_type;
unsigned long r_symndx;
bfd_byte *hit_data = contents + rel->r_offset;
bfd_vma addend;
/* The final GP value to be used for the relocatable, executable, or
shared object file being produced. */
bfd_vma gp = MINUS_ONE;
/* The place (section offset or address) of the storage unit being relocated. */
bfd_vma rel_addr;
/* The offset into the global offset table at which the address of the relocation entry
symbol, adjusted by the addend, resides during execution. */
bfd_vma g = MINUS_ONE;
/* TRUE if the symbol referred to by this relocation is a local symbol. */
bfd_boolean local_p;
/* The eventual value we will relocate. */
bfd_vma value = symbol;
unsigned long hi16_addend, hi16_offset, hi16_value, uvalue, offset, abs_value = 0;
if (elf_gp (output_bfd) == 0)
{
struct bfd_link_hash_entry *bh;
asection *o;
bh = bfd_link_hash_lookup (info->hash, "_gp", 0, 0, 1);
if (bh != NULL && bh->type == bfd_link_hash_defined)
elf_gp (output_bfd) = (bh->u.def.value
+ bh->u.def.section->output_section->vma
+ bh->u.def.section->output_offset);
else if (bfd_link_relocatable (info))
{
bfd_vma lo = -1;
/* Find the GP-relative section with the lowest offset. */
for (o = output_bfd->sections; o != NULL; o = o->next)
if (o->vma < lo)
lo = o->vma;
/* And calculate GP relative to that. */
elf_gp (output_bfd) = lo + ELF_SCORE_GP_OFFSET (input_bfd);
}
else
{
/* If the relocate_section function needs to do a reloc
involving the GP value, it should make a reloc_dangerous
callback to warn that GP is not defined. */
}
}
/* Parse the relocation. */
r_symndx = ELF32_R_SYM (rel->r_info);
r_type = ELF32_R_TYPE (rel->r_info);
rel_addr = (input_section->output_section->vma + input_section->output_offset + rel->r_offset);
local_p = score_elf_local_relocation_p (input_bfd, rel, local_sections, TRUE);
if (r_type == R_SCORE_GOT15)
{
const Elf_Internal_Rela *relend;
const Elf_Internal_Rela *lo16_rel;
const struct elf_backend_data *bed;
bfd_vma lo_value = 0;
bed = get_elf_backend_data (output_bfd);
relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel;
lo16_rel = score_elf_next_relocation (input_bfd, R_SCORE_GOT_LO16, rel, relend);
if ((local_p) && (lo16_rel != NULL))
{
bfd_vma tmp = 0;
tmp = score_bfd_get_32 (input_bfd, contents + lo16_rel->r_offset);
lo_value = (((tmp >> 16) & 0x3) << 14) | ((tmp & 0x7fff) >> 1);
}
addend = lo_value;
}
/* For score3 R_SCORE_ABS32. */
else if (r_type == R_SCORE_ABS32 || r_type == R_SCORE_REL32)
{
addend = (bfd_get_32 (input_bfd, hit_data) >> howto->bitpos) & howto->src_mask;
}
else
{
addend = (score_bfd_get_32 (input_bfd, hit_data) >> howto->bitpos) & howto->src_mask;
}
/* If we haven't already determined the GOT offset, or the GP value,
and we're going to need it, get it now. */
switch (r_type)
{
case R_SCORE_CALL15:
case R_SCORE_GOT15:
if (!local_p)
{
g = score_elf_global_got_index (elf_hash_table (info)->dynobj,
(struct elf_link_hash_entry *) h);
if ((! elf_hash_table (info)->dynamic_sections_created
|| (bfd_link_pic (info)
&& (info->symbolic || h->root.dynindx == -1)
&& h->root.def_regular)))
{
/* This is a static link or a -Bsymbolic link. The
symbol is defined locally, or was forced to be local.
We must initialize this entry in the GOT. */
bfd *tmpbfd = elf_hash_table (info)->dynobj;
asection *sgot = score_elf_got_section (tmpbfd, FALSE);
score_bfd_put_32 (tmpbfd, value, sgot->contents + g);
}
}
else if (r_type == R_SCORE_GOT15 || r_type == R_SCORE_CALL15)
{
/* There's no need to create a local GOT entry here; the
calculation for a local GOT15 entry does not involve G. */
;
}
else
{
g = score_elf_local_got_index (output_bfd, input_bfd, info,
symbol + addend, r_symndx, h, r_type);
if (g == MINUS_ONE)
return bfd_reloc_outofrange;
}
/* Convert GOT indices to actual offsets. */
g = score_elf_got_offset_from_index (elf_hash_table (info)->dynobj,
output_bfd, input_bfd, g);
break;
case R_SCORE_HI16:
case R_SCORE_LO16:
case R_SCORE_GPREL32:
gp = _bfd_get_gp_value (output_bfd);
break;
case R_SCORE_GP15:
gp = _bfd_get_gp_value (output_bfd);
default:
break;
}
switch (r_type)
{
case R_SCORE_NONE:
return bfd_reloc_ok;
case R_SCORE_ABS32:
case R_SCORE_REL32:
if ((bfd_link_pic (info)
|| (elf_hash_table (info)->dynamic_sections_created
&& h != NULL
&& h->root.def_dynamic
&& !h->root.def_regular))
&& r_symndx != STN_UNDEF
&& (input_section->flags & SEC_ALLOC) != 0)
{
/* If we're creating a shared library, or this relocation is against a symbol
in a shared library, then we can't know where the symbol will end up.
So, we create a relocation record in the output, and leave the job up
to the dynamic linker. */
value = addend;
if (!score_elf_create_dynamic_relocation (output_bfd, info, rel, h,
symbol, &value,
input_section))
return bfd_reloc_undefined;
}
else if (r_symndx == STN_UNDEF)
/* r_symndx will be STN_UNDEF (zero) only for relocs against symbols
from removed linkonce sections, or sections discarded by
a linker script. */
value = 0;
else
{
if (r_type != R_SCORE_REL32)
value = symbol + addend;
else
value = addend;
}
value &= howto->dst_mask;
bfd_put_32 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_ABS16:
value += addend;
if ((long)value > 0x7fff || (long)value < -0x8000)
return bfd_reloc_overflow;
score_bfd_put_16 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_24:
addend = score_bfd_get_32 (input_bfd, hit_data);
offset = (((addend & howto->src_mask) >> 1) & 0x1ff8000) | ((addend & howto->src_mask) & 0x7fff);
if ((offset & 0x1000000) != 0)
offset |= 0xfe000000;
value += offset;
abs_value = value - rel_addr;
if ((abs_value & 0xfe000000) != 0)
return bfd_reloc_overflow;
addend = (addend & ~howto->src_mask)
| (((value << 1) & howto->src_mask) & 0x3ff0000) | (value & 0x7fff);
score_bfd_put_32 (input_bfd, addend, hit_data);
return bfd_reloc_ok;
/* signed imm32. */
case R_SCORE_IMM30:
{
int not_word_align_p = 0;
bfd_vma imm_offset = 0;
addend = score_bfd_get_48 (input_bfd, hit_data);
imm_offset = ((addend >> 7) & 0xff)
| (((addend >> 16) & 0x7fff) << 8)
| (((addend >> 32) & 0x7f) << 23);
imm_offset <<= howto->rightshift;
value += imm_offset;
value &= 0xffffffff;
/* Check lw48/sw48 rd, value/label word align. */
if ((value & 0x3) != 0)
not_word_align_p = 1;
value >>= howto->rightshift;
addend = (addend & ~howto->src_mask)
| (((value & 0xff) >> 0) << 7)
| (((value & 0x7fff00) >> 8) << 16)
| (((value & 0x3f800000) >> 23) << 32);
score_bfd_put_48 (input_bfd, addend, hit_data);
if (not_word_align_p)
return bfd_reloc_other;
else
return bfd_reloc_ok;
}
case R_SCORE_IMM32:
{
bfd_vma imm_offset = 0;
addend = score_bfd_get_48 (input_bfd, hit_data);
imm_offset = ((addend >> 5) & 0x3ff)
| (((addend >> 16) & 0x7fff) << 10)
| (((addend >> 32) & 0x7f) << 25);
value += imm_offset;
value &= 0xffffffff;
addend = (addend & ~howto->src_mask)
| ((value & 0x3ff) << 5)
| (((value >> 10) & 0x7fff) << 16)
| (((value >> 25) & 0x7f) << 32);
score_bfd_put_48 (input_bfd, addend, hit_data);
return bfd_reloc_ok;
}
case R_SCORE_PC19:
addend = score_bfd_get_32 (input_bfd, hit_data);
offset = (((addend & howto->src_mask) & 0x3ff0000) >> 6) | ((addend & howto->src_mask) & 0x3ff);
if ((offset & 0x80000) != 0)
offset |= 0xfff00000;
abs_value = value = value - rel_addr + offset;
/* exceed 20 bit : overflow. */
if ((abs_value & 0x80000000) == 0x80000000)
abs_value = 0xffffffff - value + 1;
if ((abs_value & 0xfff80000) != 0)
return bfd_reloc_overflow;
addend = (addend & ~howto->src_mask)
| (((value << 6) & howto->src_mask) & 0x3ff0000) | (value & 0x3ff);
score_bfd_put_32 (input_bfd, addend, hit_data);
return bfd_reloc_ok;
case R_SCORE16_11:
addend = score_bfd_get_16 (input_bfd, hit_data);
offset = addend & howto->src_mask;
if ((offset & 0x800) != 0) /* Offset is negative. */
offset |= 0xfffff000;
value += offset;
abs_value = value - rel_addr;
if ((abs_value & 0xfffff000) != 0)
return bfd_reloc_overflow;
addend = (addend & ~howto->src_mask) | (value & howto->src_mask);
score_bfd_put_16 (input_bfd, addend, hit_data);
return bfd_reloc_ok;
case R_SCORE16_PC8:
addend = score_bfd_get_16 (input_bfd, hit_data);
offset = (addend & howto->src_mask) << 1;
if ((offset & 0x200) != 0) /* Offset is negative. */
offset |= 0xfffffe00;
abs_value = value = value - rel_addr + offset;
/* Sign bit + exceed 9 bit. */
if (((value & 0xfffffe00) != 0) && ((value & 0xfffffe00) != 0xfffffe00))
return bfd_reloc_overflow;
value >>= 1;
addend = (addend & ~howto->src_mask) | (value & howto->src_mask);
score_bfd_put_16 (input_bfd, addend, hit_data);
return bfd_reloc_ok;
case R_SCORE_BCMP:
addend = score_bfd_get_32 (input_bfd, hit_data);
offset = (addend & howto->src_mask) << howto->rightshift;
if ((offset & 0x200) != 0) /* Offset is negative. */
offset |= 0xfffffe00;
value = value - rel_addr + offset;
/* Sign bit + exceed 9 bit. */
if (((value & 0xfffffe00) != 0) && ((value & 0xfffffe00) != 0xfffffe00))
return bfd_reloc_overflow;
value >>= howto->rightshift;
addend = (addend & ~howto->src_mask)
| (value & 0x1)
| (((value >> 1) & 0x7) << 7)
| (((value >> 4) & 0x1f) << 21);
score_bfd_put_32 (input_bfd, addend, hit_data);
return bfd_reloc_ok;
case R_SCORE_HI16:
return bfd_reloc_ok;
case R_SCORE_LO16:
hi16_addend = score_bfd_get_32 (input_bfd, hit_data - 4);
hi16_offset = ((((hi16_addend >> 16) & 0x3) << 15) | (hi16_addend & 0x7fff)) >> 1;
addend = score_bfd_get_32 (input_bfd, hit_data);
offset = ((((addend >> 16) & 0x3) << 15) | (addend & 0x7fff)) >> 1;
offset = (hi16_offset << 16) | (offset & 0xffff);
if (!gp_disp_p)
uvalue = value + offset;
else
uvalue = offset + gp - rel_addr + 4;
hi16_offset = (uvalue >> 16) << 1;
hi16_value = (hi16_addend & (~(howto->dst_mask)))
| (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000);
score_bfd_put_32 (input_bfd, hi16_value, hit_data - 4);
offset = (uvalue & 0xffff) << 1;
value = (addend & (~(howto->dst_mask))) | (offset & 0x7fff) | ((offset << 1) & 0x30000);
score_bfd_put_32 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_GP15:
addend = score_bfd_get_32 (input_bfd, hit_data);
offset = addend & 0x7fff;
if ((offset & 0x4000) == 0x4000)
offset |= 0xffffc000;
value = value + offset - gp;
if (((value & 0xffffc000) != 0) && ((value & 0xffffc000) != 0xffffc000))
return bfd_reloc_overflow;
value = (addend & ~howto->src_mask) | (value & howto->src_mask);
score_bfd_put_32 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_GOT15:
case R_SCORE_CALL15:
if (local_p)
{
bfd_boolean forced;
/* The special case is when the symbol is forced to be local. We need the
full address in the GOT since no R_SCORE_GOT_LO16 relocation follows. */
forced = ! score_elf_local_relocation_p (input_bfd, rel,
local_sections, FALSE);
value = score_elf_got16_entry (output_bfd, input_bfd, info,
symbol + addend, forced);
if (value == MINUS_ONE)
return bfd_reloc_outofrange;
value = score_elf_got_offset_from_index (elf_hash_table (info)->dynobj,
output_bfd, input_bfd, value);
}
else
{
value = g;
}
if ((long) value > 0x3fff || (long) value < -0x4000)
return bfd_reloc_overflow;
addend = score_bfd_get_32 (input_bfd, hit_data);
value = (addend & ~howto->dst_mask) | (value & howto->dst_mask);
score_bfd_put_32 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_GPREL32:
value = (addend + symbol - gp);
value &= howto->dst_mask;
score_bfd_put_32 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_GOT_LO16:
addend = score_bfd_get_32 (input_bfd, hit_data);
value = (((addend >> 16) & 0x3) << 14) | ((addend & 0x7fff) >> 1);
value += symbol;
value = (addend & (~(howto->dst_mask))) | ((value & 0x3fff) << 1)
| (((value >> 14) & 0x3) << 16);
score_bfd_put_32 (input_bfd, value, hit_data);
return bfd_reloc_ok;
case R_SCORE_DUMMY_HI16:
return bfd_reloc_ok;
case R_SCORE_GNU_VTINHERIT:
case R_SCORE_GNU_VTENTRY:
/* We don't do anything with these at present. */
return bfd_reloc_continue;
default:
return bfd_reloc_notsupported;
}
}
/* Score backend functions. */
static void
s3_bfd_score_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
arelent *bfd_reloc,
Elf_Internal_Rela *elf_reloc)
{
unsigned int r_type;
r_type = ELF32_R_TYPE (elf_reloc->r_info);
if (r_type >= ARRAY_SIZE (elf32_score_howto_table))
bfd_reloc->howto = NULL;
else
bfd_reloc->howto = &elf32_score_howto_table[r_type];
}
/* Relocate an score ELF section. */
static bfd_boolean
s3_bfd_score_elf_relocate_section (bfd *output_bfd,
struct bfd_link_info *info,
bfd *input_bfd,
asection *input_section,
bfd_byte *contents,
Elf_Internal_Rela *relocs,
Elf_Internal_Sym *local_syms,
asection **local_sections)
{
Elf_Internal_Shdr *symtab_hdr;
Elf_Internal_Rela *rel;
Elf_Internal_Rela *relend;
const char *name;
unsigned long offset;
unsigned long hi16_addend, hi16_offset, hi16_value, uvalue;
size_t extsymoff;
bfd_boolean gp_disp_p = FALSE;
/* Sort dynsym. */
if (elf_hash_table (info)->dynamic_sections_created)
{
bfd_size_type dynsecsymcount = 0;
if (bfd_link_pic (info))
{
asection * p;
const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
for (p = output_bfd->sections; p ; p = p->next)
if ((p->flags & SEC_EXCLUDE) == 0
&& (p->flags & SEC_ALLOC) != 0
&& !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
++ dynsecsymcount;
}
if (!score_elf_sort_hash_table (info, dynsecsymcount + 1))
return FALSE;
}
symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info;
rel = relocs;
relend = relocs + input_section->reloc_count;
for (; rel < relend; rel++)
{
int r_type;
reloc_howto_type *howto;
unsigned long r_symndx;
Elf_Internal_Sym *sym;
asection *sec;
struct score_elf_link_hash_entry *h;
bfd_vma relocation = 0;
bfd_reloc_status_type r;
arelent bfd_reloc;
r_symndx = ELF32_R_SYM (rel->r_info);
r_type = ELF32_R_TYPE (rel->r_info);
s3_bfd_score_info_to_howto (input_bfd, &bfd_reloc, (Elf_Internal_Rela *) rel);
howto = bfd_reloc.howto;
h = NULL;
sym = NULL;
sec = NULL;
if (r_symndx < extsymoff)
{
sym = local_syms + r_symndx;
sec = local_sections[r_symndx];
relocation = (sec->output_section->vma
+ sec->output_offset
+ sym->st_value);
name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, sec);
if (!bfd_link_relocatable (info)
&& (sec->flags & SEC_MERGE)
&& ELF_ST_TYPE (sym->st_info) == STT_SECTION)
{
asection *msec;
bfd_vma addend, value;
switch (r_type)
{
case R_SCORE_HI16:
break;
case R_SCORE_LO16:
hi16_addend = score_bfd_get_32 (input_bfd, contents + rel->r_offset - 4);
hi16_offset = ((((hi16_addend >> 16) & 0x3) << 15) | (hi16_addend & 0x7fff)) >> 1;
value = score_bfd_get_32 (input_bfd, contents + rel->r_offset);
offset = ((((value >> 16) & 0x3) << 15) | (value & 0x7fff)) >> 1;
addend = (hi16_offset << 16) | (offset & 0xffff);
msec = sec;
addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend);
addend -= relocation;
addend += msec->output_section->vma + msec->output_offset;
uvalue = addend;
hi16_offset = (uvalue >> 16) << 1;
hi16_value = (hi16_addend & (~(howto->dst_mask)))
| (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000);
score_bfd_put_32 (input_bfd, hi16_value, contents + rel->r_offset - 4);
offset = (uvalue & 0xffff) << 1;
value = (value & (~(howto->dst_mask)))
| (offset & 0x7fff) | ((offset << 1) & 0x30000);
score_bfd_put_32 (input_bfd, value, contents + rel->r_offset);
break;
case R_SCORE_IMM32:
{
value = score_bfd_get_48 (input_bfd, contents + rel->r_offset);
addend = ((value >> 5) & 0x3ff)
| (((value >> 16) & 0x7fff) << 10)
| (((value >> 32) & 0x7f) << 25);
msec = sec;
addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend);
addend -= relocation;
addend += msec->output_section->vma + msec->output_offset;
addend &= 0xffffffff;
value = (value & ~howto->src_mask)
| ((addend & 0x3ff) << 5)
| (((addend >> 10) & 0x7fff) << 16)
| (((addend >> 25) & 0x7f) << 32);
score_bfd_put_48 (input_bfd, value, contents + rel->r_offset);
break;
}
case R_SCORE_IMM30:
{
int not_word_align_p = 0;
value = score_bfd_get_48 (input_bfd, contents + rel->r_offset);
addend = ((value >> 7) & 0xff)
| (((value >> 16) & 0x7fff) << 8)
| (((value >> 32) & 0x7f) << 23);
addend <<= howto->rightshift;
msec = sec;
addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend);
addend -= relocation;
addend += msec->output_section->vma + msec->output_offset;
addend &= 0xffffffff;
/* Check lw48/sw48 rd, value/label word align. */
if ((addend & 0x3) != 0)
not_word_align_p = 1;
addend >>= howto->rightshift;
value = (value & ~howto->src_mask)
| (((addend & 0xff) >> 0) << 7)
| (((addend & 0x7fff00) >> 8) << 16)
| (((addend & 0x3f800000) >> 23) << 32);
score_bfd_put_48 (input_bfd, value, contents + rel->r_offset);
if (not_word_align_p)
return bfd_reloc_other;
else
break;
}
case R_SCORE_GOT_LO16:
value = score_bfd_get_32 (input_bfd, contents + rel->r_offset);
addend = (((value >> 16) & 0x3) << 14) | ((value & 0x7fff) >> 1);
msec = sec;
addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend) - relocation;
addend += msec->output_section->vma + msec->output_offset;
value = (value & (~(howto->dst_mask))) | ((addend & 0x3fff) << 1)
| (((addend >> 14) & 0x3) << 16);
score_bfd_put_32 (input_bfd, value, contents + rel->r_offset);
break;
case R_SCORE_ABS32:
case R_SCORE_REL32:
value = bfd_get_32 (input_bfd, contents + rel->r_offset);
/* Get the (signed) value from the instruction. */
addend = value & howto->src_mask;
if (addend & ((howto->src_mask + 1) >> 1))
{
bfd_signed_vma mask;
mask = -1;
mask &= ~howto->src_mask;
addend |= mask;
}
msec = sec;
addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend) - relocation;
addend += msec->output_section->vma + msec->output_offset;
value = (value & ~howto->dst_mask) | (addend & howto->dst_mask);
bfd_put_32 (input_bfd, value, contents + rel->r_offset);
break;
default:
value = score_bfd_get_32 (input_bfd, contents + rel->r_offset);
/* Get the (signed) value from the instruction. */
addend = value & howto->src_mask;
if (addend & ((howto->src_mask + 1) >> 1))
{
bfd_signed_vma mask;
mask = -1;
mask &= ~howto->src_mask;
addend |= mask;
}
msec = sec;
addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend) - relocation;
addend += msec->output_section->vma + msec->output_offset;
value = (value & ~howto->dst_mask) | (addend & howto->dst_mask);
score_bfd_put_32 (input_bfd, value, contents + rel->r_offset);
break;
}
}
}
else
{
/* For global symbols we look up the symbol in the hash-table. */
h = ((struct score_elf_link_hash_entry *)
elf_sym_hashes (input_bfd) [r_symndx - extsymoff]);
if (info->wrap_hash != NULL
&& (input_section->flags & SEC_DEBUGGING) != 0)
h = ((struct score_elf_link_hash_entry *)
unwrap_hash_lookup (info, input_bfd, &h->root.root));
/* Find the real hash-table entry for this symbol. */
while (h->root.root.type == bfd_link_hash_indirect
|| h->root.root.type == bfd_link_hash_warning)
h = (struct score_elf_link_hash_entry *) h->root.root.u.i.link;
/* Record the name of this symbol, for our caller. */
name = h->root.root.root.string;
/* See if this is the special GP_DISP_LABEL symbol. Note that such a
symbol must always be a global symbol. */
if (strcmp (name, GP_DISP_LABEL) == 0)
{
/* Relocations against GP_DISP_LABEL are permitted only with
R_SCORE_HI16 and R_SCORE_LO16 relocations. */
if (r_type != R_SCORE_HI16 && r_type != R_SCORE_LO16)
return bfd_reloc_notsupported;
gp_disp_p = TRUE;
}
/* If this symbol is defined, calculate its address. Note that
GP_DISP_LABEL is a magic symbol, always implicitly defined by the
linker, so it's inappropriate to check to see whether or not
its defined. */
else if ((h->root.root.type == bfd_link_hash_defined
|| h->root.root.type == bfd_link_hash_defweak)
&& h->root.root.u.def.section)
{
sec = h->root.root.u.def.section;
if (sec->output_section)
relocation = (h->root.root.u.def.value
+ sec->output_section->vma
+ sec->output_offset);
else
{
relocation = h->root.root.u.def.value;
}
}
else if (h->root.root.type == bfd_link_hash_undefweak)
/* We allow relocations against undefined weak symbols, giving
it the value zero, so that you can undefined weak functions
and check to see if they exist by looking at their addresses. */
relocation = 0;
else if (info->unresolved_syms_in_objects == RM_IGNORE
&& ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT)
relocation = 0;
else if (strcmp (name, "_DYNAMIC_LINK") == 0)
{
/* If this is a dynamic link, we should have created a _DYNAMIC_LINK symbol
in s3_bfd_score_elf_create_dynamic_sections. Otherwise, we should define
the symbol with a value of 0. */
BFD_ASSERT (! bfd_link_pic (info));
BFD_ASSERT (bfd_get_section_by_name (output_bfd, ".dynamic") == NULL);
relocation = 0;
}
else if (!bfd_link_relocatable (info))
{
(*info->callbacks->undefined_symbol)
(info, h->root.root.root.string, input_bfd,
input_section, rel->r_offset,
(info->unresolved_syms_in_objects == RM_GENERATE_ERROR)
|| ELF_ST_VISIBILITY (h->root.other));
relocation = 0;
}
}
if (sec != NULL && discarded_section (sec))
RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section,
rel, 1, relend, howto, 0, contents);
if (bfd_link_relocatable (info))
{
/* This is a relocatable link. We don't have to change
anything, unless the reloc is against a section symbol,
in which case we have to adjust according to where the
section symbol winds up in the output section. */
if (r_symndx < symtab_hdr->sh_info)
{
sym = local_syms + r_symndx;
if (ELF_ST_TYPE (sym->st_info) == STT_SECTION)
{
sec = local_sections[r_symndx];
score_elf_add_to_rel (input_bfd, contents + rel->r_offset,
howto, (bfd_signed_vma) (sec->output_offset + sym->st_value));
}
}
continue;
}
/* This is a final link. */
r = score_elf_final_link_relocate (howto, input_bfd, output_bfd,
input_section, contents, rel, relocs,
relocation, info, name,
(h ? ELF_ST_TYPE ((unsigned int)h->root.root.type) :
ELF_ST_TYPE ((unsigned int)sym->st_info)), h, local_sections,
gp_disp_p);
if (r != bfd_reloc_ok)
{
const char *msg = (const char *)0;
switch (r)
{
case bfd_reloc_overflow:
/* If the overflowing reloc was to an undefined symbol,
we have already printed one error message and there
is no point complaining again. */
if (!h || h->root.root.type != bfd_link_hash_undefined)
(*info->callbacks->reloc_overflow)
(info, NULL, name, howto->name, (bfd_vma) 0,
input_bfd, input_section, rel->r_offset);
break;
case bfd_reloc_undefined:
(*info->callbacks->undefined_symbol)
(info, name, input_bfd, input_section, rel->r_offset, TRUE);
break;
case bfd_reloc_outofrange:
msg = _("internal error: out of range error");
goto common_error;
case bfd_reloc_notsupported:
msg = _("internal error: unsupported relocation error");
goto common_error;
case bfd_reloc_dangerous:
msg = _("internal error: dangerous error");
goto common_error;
/* Use bfd_reloc_other to check lw48, sw48 word align. */
case bfd_reloc_other:
msg = _("address not word align");
goto common_error;
default:
msg = _("internal error: unknown error");
/* Fall through. */
common_error:
(*info->callbacks->warning) (info, msg, name, input_bfd,
input_section, rel->r_offset);
break;
}
}
}
return TRUE;
}
/* Look through the relocs for a section during the first phase, and
allocate space in the global offset table. */
static bfd_boolean
s3_bfd_score_elf_check_relocs (bfd *abfd,
struct bfd_link_info *info,
asection *sec,
const Elf_Internal_Rela *relocs)
{
bfd *dynobj;
Elf_Internal_Shdr *symtab_hdr;
struct elf_link_hash_entry **sym_hashes;
struct score_got_info *g;
size_t extsymoff;
const Elf_Internal_Rela *rel;
const Elf_Internal_Rela *rel_end;
asection *sgot;
asection *sreloc;
const struct elf_backend_data *bed;
if (bfd_link_relocatable (info))
return TRUE;
dynobj = elf_hash_table (info)->dynobj;
symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
sym_hashes = elf_sym_hashes (abfd);
extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info;
if (dynobj == NULL)
{
sgot = NULL;
g = NULL;
}
else
{
sgot = score_elf_got_section (dynobj, FALSE);
if (sgot == NULL)
g = NULL;
else
{
BFD_ASSERT (score_elf_section_data (sgot) != NULL);
g = score_elf_section_data (sgot)->u.got_info;
BFD_ASSERT (g != NULL);
}
}
sreloc = NULL;
bed = get_elf_backend_data (abfd);
rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel;
for (rel = relocs; rel < rel_end; ++rel)
{
unsigned long r_symndx;
unsigned int r_type;
struct elf_link_hash_entry *h;
r_symndx = ELF32_R_SYM (rel->r_info);
r_type = ELF32_R_TYPE (rel->r_info);
if (r_symndx < extsymoff)
{
h = NULL;
}
else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr))
{
_bfd_error_handler
/* xgettext:c-format */
(_("%B: Malformed reloc detected for section %A"), abfd, sec);
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
else
{
h = sym_hashes[r_symndx - extsymoff];
/* This may be an indirect symbol created because of a version. */
if (h != NULL)
{
while (h->root.type == bfd_link_hash_indirect)
h = (struct elf_link_hash_entry *)h->root.u.i.link;
/* PR15323, ref flags aren't set for references in the
same object. */
h->root.non_ir_ref = 1;
}
}
/* Some relocs require a global offset table. */
if (dynobj == NULL || sgot == NULL)
{
switch (r_type)
{
case R_SCORE_GOT15:
case R_SCORE_CALL15:
if (dynobj == NULL)
elf_hash_table (info)->dynobj = dynobj = abfd;
if (!score_elf_create_got_section (dynobj, info, FALSE))
return FALSE;
g = score_elf_got_info (dynobj, &sgot);
break;
case R_SCORE_ABS32:
case R_SCORE_REL32:
if (dynobj == NULL
&& (bfd_link_pic (info) || h != NULL)
&& (sec->flags & SEC_ALLOC) != 0)
elf_hash_table (info)->dynobj = dynobj = abfd;
break;
default:
break;
}
}
if (!h && (r_type == R_SCORE_GOT_LO16))
{
if (! score_elf_record_local_got_symbol (abfd, r_symndx, rel->r_addend, g))
return FALSE;
}
switch (r_type)
{
case R_SCORE_CALL15:
if (h == NULL)
{
_bfd_error_handler
/* xgettext:c-format */
(_("%B: CALL15 reloc at 0x%lx not against global symbol"),
abfd, (unsigned long) rel->r_offset);
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
else
{
/* This symbol requires a global offset table entry. */
if (! score_elf_record_global_got_symbol (h, abfd, info, g))
return FALSE;
/* We need a stub, not a plt entry for the undefined function. But we record
it as if it needs plt. See _bfd_elf_adjust_dynamic_symbol. */
h->needs_plt = 1;
h->type = STT_FUNC;
}
break;
case R_SCORE_GOT15:
if (h && ! score_elf_record_global_got_symbol (h, abfd, info, g))
return FALSE;
break;
case R_SCORE_ABS32:
case R_SCORE_REL32:
if ((bfd_link_pic (info) || h != NULL)
&& (sec->flags & SEC_ALLOC) != 0)
{
if (sreloc == NULL)
{
sreloc = score_elf_rel_dyn_section (dynobj, TRUE);
if (sreloc == NULL)
return FALSE;
}
#define SCORE_READONLY_SECTION (SEC_ALLOC | SEC_LOAD | SEC_READONLY)
if (bfd_link_pic (info))
{
/* When creating a shared object, we must copy these reloc types into
the output file as R_SCORE_REL32 relocs. We make room for this reloc
in the .rel.dyn reloc section. */
score_elf_allocate_dynamic_relocations (dynobj, 1);
if ((sec->flags & SCORE_READONLY_SECTION)
== SCORE_READONLY_SECTION)
/* We tell the dynamic linker that there are
relocations against the text segment. */
info->flags |= DF_TEXTREL;
}
else
{
struct score_elf_link_hash_entry *hscore;
/* We only need to copy this reloc if the symbol is
defined in a dynamic object. */
hscore = (struct score_elf_link_hash_entry *)h;
++hscore->possibly_dynamic_relocs;
if ((sec->flags & SCORE_READONLY_SECTION)
== SCORE_READONLY_SECTION)
/* We need it to tell the dynamic linker if there
are relocations against the text segment. */
hscore->readonly_reloc = TRUE;
}
/* Even though we don't directly need a GOT entry for this symbol,
a symbol must have a dynamic symbol table index greater that
DT_SCORE_GOTSYM if there are dynamic relocations against it. */
if (h != NULL)
{
if (dynobj == NULL)
elf_hash_table (info)->dynobj = dynobj = abfd;
if (! score_elf_create_got_section (dynobj, info, TRUE))
return FALSE;
g = score_elf_got_info (dynobj, &sgot);
if (! score_elf_record_global_got_symbol (h, abfd, info, g))
return FALSE;
}
}
break;
/* This relocation describes the C++ object vtable hierarchy.
Reconstruct it for later use during GC. */
case R_SCORE_GNU_VTINHERIT:
if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset))
return FALSE;
break;
/* This relocation describes which C++ vtable entries are actually
used. Record for later use during GC. */
case R_SCORE_GNU_VTENTRY:
if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset))
return FALSE;
break;
default:
break;
}
/* We must not create a stub for a symbol that has relocations
related to taking the function's address. */
switch (r_type)
{
default:
if (h != NULL)
{
struct score_elf_link_hash_entry *sh;
sh = (struct score_elf_link_hash_entry *) h;
sh->no_fn_stub = TRUE;
}
break;
case R_SCORE_CALL15:
break;
}
}
return TRUE;
}
static bfd_boolean
s3_bfd_score_elf_add_symbol_hook (bfd *abfd,
struct bfd_link_info *info ATTRIBUTE_UNUSED,
Elf_Internal_Sym *sym,
const char **namep ATTRIBUTE_UNUSED,
flagword *flagsp ATTRIBUTE_UNUSED,
asection **secp,
bfd_vma *valp)
{
switch (sym->st_shndx)
{
case SHN_COMMON:
if (sym->st_size > elf_gp_size (abfd))
break;
/* Fall through. */
case SHN_SCORE_SCOMMON:
*secp = bfd_make_section_old_way (abfd, ".scommon");
(*secp)->flags |= SEC_IS_COMMON;
*valp = sym->st_size;
break;
}
return TRUE;
}
static void
s3_bfd_score_elf_symbol_processing (bfd *abfd, asymbol *asym)
{
elf_symbol_type *elfsym;
elfsym = (elf_symbol_type *) asym;
switch (elfsym->internal_elf_sym.st_shndx)
{
case SHN_COMMON:
if (asym->value > elf_gp_size (abfd))
break;
/* Fall through. */
case SHN_SCORE_SCOMMON:
if (score_elf_scom_section.name == NULL)
{
/* Initialize the small common section. */
score_elf_scom_section.name = ".scommon";
score_elf_scom_section.flags = SEC_IS_COMMON;
score_elf_scom_section.output_section = &score_elf_scom_section;
score_elf_scom_section.symbol = &score_elf_scom_symbol;
score_elf_scom_section.symbol_ptr_ptr = &score_elf_scom_symbol_ptr;
score_elf_scom_symbol.name = ".scommon";
score_elf_scom_symbol.flags = BSF_SECTION_SYM;
score_elf_scom_symbol.section = &score_elf_scom_section;
score_elf_scom_symbol_ptr = &score_elf_scom_symbol;
}
asym->section = &score_elf_scom_section;
asym->value = elfsym->internal_elf_sym.st_size;
break;
}
}
static int
s3_bfd_score_elf_link_output_symbol_hook (struct bfd_link_info *info ATTRIBUTE_UNUSED,
const char *name ATTRIBUTE_UNUSED,
Elf_Internal_Sym *sym,
asection *input_sec,
struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
{
/* If we see a common symbol, which implies a relocatable link, then
if a symbol was small common in an input file, mark it as small
common in the output file. */
if (sym->st_shndx == SHN_COMMON && strcmp (input_sec->name, ".scommon") == 0)
sym->st_shndx = SHN_SCORE_SCOMMON;
return 1;
}
static bfd_boolean
s3_bfd_score_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
asection *sec,
int *retval)
{
if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0)
{
*retval = SHN_SCORE_SCOMMON;
return TRUE;
}
return FALSE;
}
/* Adjust a symbol defined by a dynamic object and referenced by a
regular object. The current definition is in some section of the
dynamic object, but we're not including those sections. We have to
change the definition to something the rest of the link can understand. */
static bfd_boolean
s3_bfd_score_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
struct elf_link_hash_entry *h)
{
bfd *dynobj;
struct score_elf_link_hash_entry *hscore;
asection *s;
dynobj = elf_hash_table (info)->dynobj;
/* Make sure we know what is going on here. */
BFD_ASSERT (dynobj != NULL
&& (h->needs_plt
|| h->u.weakdef != NULL
|| (h->def_dynamic && h->ref_regular && !h->def_regular)));
/* If this symbol is defined in a dynamic object, we need to copy
any R_SCORE_ABS32 or R_SCORE_REL32 relocs against it into the output
file. */
hscore = (struct score_elf_link_hash_entry *)h;
if (!bfd_link_relocatable (info)
&& hscore->possibly_dynamic_relocs != 0
&& (h->root.type == bfd_link_hash_defweak || !h->def_regular))
{
score_elf_allocate_dynamic_relocations (dynobj, hscore->possibly_dynamic_relocs);
if (hscore->readonly_reloc)
/* We tell the dynamic linker that there are relocations
against the text segment. */
info->flags |= DF_TEXTREL;
}
/* For a function, create a stub, if allowed. */
if (!hscore->no_fn_stub && h->needs_plt)
{
if (!elf_hash_table (info)->dynamic_sections_created)
return TRUE;
/* If this symbol is not defined in a regular file, then set
the symbol to the stub location. This is required to make
function pointers compare as equal between the normal
executable and the shared library. */
if (!h->def_regular)
{
/* We need .stub section. */
s = bfd_get_linker_section (dynobj, SCORE_ELF_STUB_SECTION_NAME);
BFD_ASSERT (s != NULL);
h->root.u.def.section = s;
h->root.u.def.value = s->size;
/* XXX Write this stub address somewhere. */
h->plt.offset = s->size;
/* Make room for this stub code. */
s->size += SCORE_FUNCTION_STUB_SIZE;
/* The last half word of the stub will be filled with the index
of this symbol in .dynsym section. */
return TRUE;
}
}
else if ((h->type == STT_FUNC) && !h->needs_plt)
{
/* This will set the entry for this symbol in the GOT to 0, and
the dynamic linker will take care of this. */
h->root.u.def.value = 0;
return TRUE;
}
/* If this is a weak symbol, and there is a real definition, the
processor independent code will have arranged for us to see the
real definition first, and we can just use the same value. */
if (h->u.weakdef != NULL)
{
BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined
|| h->u.weakdef->root.type == bfd_link_hash_defweak);
h->root.u.def.section = h->u.weakdef->root.u.def.section;
h->root.u.def.value = h->u.weakdef->root.u.def.value;
return TRUE;
}
/* This is a reference to a symbol defined by a dynamic object which
is not a function. */
return TRUE;
}
/* This function is called after all the input files have been read,
and the input sections have been assigned to output sections. */
static bfd_boolean
s3_bfd_score_elf_always_size_sections (bfd *output_bfd,
struct bfd_link_info *info)
{
bfd *dynobj;
asection *s;
struct score_got_info *g;
int i;
bfd_size_type loadable_size = 0;
bfd_size_type local_gotno;
bfd *sub;
dynobj = elf_hash_table (info)->dynobj;
if (dynobj == NULL)
/* Relocatable links don't have it. */
return TRUE;
g = score_elf_got_info (dynobj, &s);
if (s == NULL)
return TRUE;
/* Calculate the total loadable size of the output. That will give us the
maximum number of GOT_PAGE entries required. */
for (sub = info->input_bfds; sub; sub = sub->link.next)
{
asection *subsection;
for (subsection = sub->sections;
subsection;
subsection = subsection->next)
{
if ((subsection->flags & SEC_ALLOC) == 0)
continue;
loadable_size += ((subsection->size + 0xf)
&~ (bfd_size_type) 0xf);
}
}
/* There has to be a global GOT entry for every symbol with
a dynamic symbol table index of DT_SCORE_GOTSYM or
higher. Therefore, it make sense to put those symbols
that need GOT entries at the end of the symbol table. We
do that here. */
if (! score_elf_sort_hash_table (info, 1))
return FALSE;
if (g->global_gotsym != NULL)
i = elf_hash_table (info)->dynsymcount - g->global_gotsym->dynindx;
else
/* If there are no global symbols, or none requiring
relocations, then GLOBAL_GOTSYM will be NULL. */
i = 0;
/* In the worst case, we'll get one stub per dynamic symbol. */
loadable_size += SCORE_FUNCTION_STUB_SIZE * i;
/* Assume there are two loadable segments consisting of
contiguous sections. Is 5 enough? */
local_gotno = (loadable_size >> 16) + 5;
g->local_gotno += local_gotno;
s->size += g->local_gotno * SCORE_ELF_GOT_SIZE (output_bfd);
g->global_gotno = i;
s->size += i * SCORE_ELF_GOT_SIZE (output_bfd);
score_elf_resolve_final_got_entries (g);
if (s->size > SCORE_ELF_GOT_MAX_SIZE (output_bfd))
{
/* Fixme. Error message or Warning message should be issued here. */
}
return TRUE;
}
/* Set the sizes of the dynamic sections. */
static bfd_boolean
s3_bfd_score_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info)
{
bfd *dynobj;
asection *s;
bfd_boolean reltext;
dynobj = elf_hash_table (info)->dynobj;
BFD_ASSERT (dynobj != NULL);
if (elf_hash_table (info)->dynamic_sections_created)
{
/* Set the contents of the .interp section to the interpreter. */
if (!bfd_link_pic (info) && !info->nointerp)
{
s = bfd_get_linker_section (dynobj, ".interp");
BFD_ASSERT (s != NULL);
s->size = strlen (ELF_DYNAMIC_INTERPRETER) + 1;
s->contents = (bfd_byte *) ELF_DYNAMIC_INTERPRETER;
}
}
/* The check_relocs and adjust_dynamic_symbol entry points have
determined the sizes of the various dynamic sections. Allocate
memory for them. */
reltext = FALSE;
for (s = dynobj->sections; s != NULL; s = s->next)
{
const char *name;
if ((s->flags & SEC_LINKER_CREATED) == 0)
continue;
/* It's OK to base decisions on the section name, because none
of the dynobj section names depend upon the input files. */
name = bfd_get_section_name (dynobj, s);
if (CONST_STRNEQ (name, ".rel"))
{
if (s->size == 0)
{
/* We only strip the section if the output section name
has the same name. Otherwise, there might be several
input sections for this output section. FIXME: This
code is probably not needed these days anyhow, since
the linker now does not create empty output sections. */
if (s->output_section != NULL
&& strcmp (name,
bfd_get_section_name (s->output_section->owner,
s->output_section)) == 0)
s->flags |= SEC_EXCLUDE;
}
else
{
const char *outname;
asection *target;
/* If this relocation section applies to a read only
section, then we probably need a DT_TEXTREL entry.
If the relocation section is .rel.dyn, we always
assert a DT_TEXTREL entry rather than testing whether
there exists a relocation to a read only section or
not. */
outname = bfd_get_section_name (output_bfd, s->output_section);
target = bfd_get_section_by_name (output_bfd, outname + 4);
if ((target != NULL
&& (target->flags & SEC_READONLY) != 0
&& (target->flags & SEC_ALLOC) != 0) || strcmp (outname, ".rel.dyn") == 0)
reltext = TRUE;
/* We use the reloc_count field as a counter if we need
to copy relocs into the output file. */
if (strcmp (name, ".rel.dyn") != 0)
s->reloc_count = 0;
}
}
else if (CONST_STRNEQ (name, ".got"))
{
/* s3_bfd_score_elf_always_size_sections() has already done
most of the work, but some symbols may have been mapped
to versions that we must now resolve in the got_entries
hash tables. */
}
else if (strcmp (name, SCORE_ELF_STUB_SECTION_NAME) == 0)
{
/* IRIX rld assumes that the function stub isn't at the end
of .text section. So put a dummy. XXX */
s->size += SCORE_FUNCTION_STUB_SIZE;
}
else if (! CONST_STRNEQ (name, ".init"))
{
/* It's not one of our sections, so don't allocate space. */
continue;
}
/* Allocate memory for the section contents. */
s->contents = bfd_zalloc (dynobj, s->size);
if (s->contents == NULL && s->size != 0)
{
bfd_set_error (bfd_error_no_memory);
return FALSE;
}
}
if (elf_hash_table (info)->dynamic_sections_created)
{
/* Add some entries to the .dynamic section. We fill in the
values later, in s3_bfd_score_elf_finish_dynamic_sections, but we
must add the entries now so that we get the correct size for
the .dynamic section. The DT_DEBUG entry is filled in by the
dynamic linker and used by the debugger. */
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0))
return FALSE;
if (reltext)
info->flags |= DF_TEXTREL;
if ((info->flags & DF_TEXTREL) != 0)
{
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0))
return FALSE;
}
if (! SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0))
return FALSE;
if (score_elf_rel_dyn_section (dynobj, FALSE))
{
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0))
return FALSE;
}
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_BASE_ADDRESS, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_LOCAL_GOTNO, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_SYMTABNO, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_UNREFEXTNO, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_GOTSYM, 0))
return FALSE;
if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_HIPAGENO, 0))
return FALSE;
}
return TRUE;
}
static bfd_boolean
s3_bfd_score_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
{
struct elf_link_hash_entry *h;
struct bfd_link_hash_entry *bh;
flagword flags;
asection *s;
flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY
| SEC_LINKER_CREATED | SEC_READONLY);
/* ABI requests the .dynamic section to be read only. */
s = bfd_get_linker_section (abfd, ".dynamic");
if (s != NULL)
{
if (!bfd_set_section_flags (abfd, s, flags))
return FALSE;
}
/* We need to create .got section. */
if (!score_elf_create_got_section (abfd, info, FALSE))
return FALSE;
if (!score_elf_rel_dyn_section (elf_hash_table (info)->dynobj, TRUE))
return FALSE;
/* Create .stub section. */
if (bfd_get_linker_section (abfd, SCORE_ELF_STUB_SECTION_NAME) == NULL)
{
s = bfd_make_section_anyway_with_flags (abfd, SCORE_ELF_STUB_SECTION_NAME,
flags | SEC_CODE);
if (s == NULL
|| !bfd_set_section_alignment (abfd, s, 2))
return FALSE;
}
if (!bfd_link_pic (info))
{
const char *name;
name = "_DYNAMIC_LINK";
bh = NULL;
if (!(_bfd_generic_link_add_one_symbol
(info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr,
(bfd_vma) 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh)))
return FALSE;
h = (struct elf_link_hash_entry *)bh;
h->non_elf = 0;
h->def_regular = 1;
h->type = STT_SECTION;
if (!bfd_elf_link_record_dynamic_symbol (info, h))
return FALSE;
}
return TRUE;
}
/* Finish up dynamic symbol handling. We set the contents of various
dynamic sections here. */
static bfd_boolean
s3_bfd_score_elf_finish_dynamic_symbol (bfd *output_bfd,
struct bfd_link_info *info,
struct elf_link_hash_entry *h,
Elf_Internal_Sym *sym)
{
bfd *dynobj;
asection *sgot;
struct score_got_info *g;
const char *name;
dynobj = elf_hash_table (info)->dynobj;
if (h->plt.offset != MINUS_ONE)
{
asection *s;
bfd_byte stub[SCORE_FUNCTION_STUB_SIZE];
/* This symbol has a stub. Set it up. */
BFD_ASSERT (h->dynindx != -1);
s = bfd_get_linker_section (dynobj, SCORE_ELF_STUB_SECTION_NAME);
BFD_ASSERT (s != NULL);
/* FIXME: Can h->dynindex be more than 64K? */
if (h->dynindx & 0xffff0000)
return FALSE;
/* Fill the stub. */
score_bfd_put_32 (output_bfd, STUB_LW, stub);
score_bfd_put_32 (output_bfd, STUB_MOVE, stub + 4);
score_bfd_put_32 (output_bfd, STUB_LI16 | (h->dynindx << 1), stub + 8);
score_bfd_put_32 (output_bfd, STUB_BRL, stub + 12);
BFD_ASSERT (h->plt.offset <= s->size);
memcpy (s->contents + h->plt.offset, stub, SCORE_FUNCTION_STUB_SIZE);
/* Mark the symbol as undefined. plt.offset != -1 occurs
only for the referenced symbol. */
sym->st_shndx = SHN_UNDEF;
/* The run-time linker uses the st_value field of the symbol
to reset the global offset table entry for this external
to its stub address when unlinking a shared object. */
sym->st_value = (s->output_section->vma + s->output_offset + h->plt.offset);
}
BFD_ASSERT (h->dynindx != -1 || h->forced_local);
sgot = score_elf_got_section (dynobj, FALSE);
BFD_ASSERT (sgot != NULL);
BFD_ASSERT (score_elf_section_data (sgot) != NULL);
g = score_elf_section_data (sgot)->u.got_info;
BFD_ASSERT (g != NULL);
/* Run through the global symbol table, creating GOT entries for all
the symbols that need them. */
if (g->global_gotsym != NULL && h->dynindx >= g->global_gotsym->dynindx)
{
bfd_vma offset;
bfd_vma value;
value = sym->st_value;
offset = score_elf_global_got_index (dynobj, h);
score_bfd_put_32 (output_bfd, value, sgot->contents + offset);
}
/* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute. */
name = h->root.root.string;
if (h == elf_hash_table (info)->hdynamic
|| h == elf_hash_table (info)->hgot)
sym->st_shndx = SHN_ABS;
else if (strcmp (name, "_DYNAMIC_LINK") == 0)
{
sym->st_shndx = SHN_ABS;
sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
sym->st_value = 1;
}
else if (strcmp (name, GP_DISP_LABEL) == 0)
{
sym->st_shndx = SHN_ABS;
sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
sym->st_value = elf_gp (output_bfd);
}
return TRUE;
}
/* Finish up the dynamic sections. */
static bfd_boolean
s3_bfd_score_elf_finish_dynamic_sections (bfd *output_bfd,
struct bfd_link_info *info)
{
bfd *dynobj;
asection *sdyn;
asection *sgot;
asection *s;
struct score_got_info *g;
dynobj = elf_hash_table (info)->dynobj;
sdyn = bfd_get_linker_section (dynobj, ".dynamic");
sgot = score_elf_got_section (dynobj, FALSE);
if (sgot == NULL)
g = NULL;
else
{
BFD_ASSERT (score_elf_section_data (sgot) != NULL);
g = score_elf_section_data (sgot)->u.got_info;
BFD_ASSERT (g != NULL);
}
if (elf_hash_table (info)->dynamic_sections_created)
{
bfd_byte *b;
BFD_ASSERT (sdyn != NULL);
BFD_ASSERT (g != NULL);
for (b = sdyn->contents;
b < sdyn->contents + sdyn->size;
b += SCORE_ELF_DYN_SIZE (dynobj))
{
Elf_Internal_Dyn dyn;
const char *name;
size_t elemsize;
bfd_boolean swap_out_p;
/* Read in the current dynamic entry. */
(*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn);
/* Assume that we're going to modify it and write it out. */
swap_out_p = TRUE;
switch (dyn.d_tag)
{
case DT_RELENT:
dyn.d_un.d_val = SCORE_ELF_REL_SIZE (dynobj);
break;
case DT_STRSZ:
/* Rewrite DT_STRSZ. */
dyn.d_un.d_val
= _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
break;
case DT_PLTGOT:
s = elf_hash_table (info)->sgot;
dyn.d_un.d_ptr = s->output_section->vma + s->output_offset;
break;
case DT_SCORE_BASE_ADDRESS:
s = output_bfd->sections;
BFD_ASSERT (s != NULL);
dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff;
break;
case DT_SCORE_LOCAL_GOTNO:
dyn.d_un.d_val = g->local_gotno;
break;
case DT_SCORE_UNREFEXTNO:
/* The index into the dynamic symbol table which is the
entry of the first external symbol that is not
referenced within the same object. */
dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1;
break;
case DT_SCORE_GOTSYM:
if (g->global_gotsym)
{
dyn.d_un.d_val = g->global_gotsym->dynindx;
break;
}
/* In case if we don't have global got symbols we default
to setting DT_SCORE_GOTSYM to the same value as
DT_SCORE_SYMTABNO. */
/* Fall through. */
case DT_SCORE_SYMTABNO:
name = ".dynsym";
elemsize = SCORE_ELF_SYM_SIZE (output_bfd);
s = bfd_get_linker_section (dynobj, name);
dyn.d_un.d_val = s->size / elemsize;
break;
case DT_SCORE_HIPAGENO:
dyn.d_un.d_val = g->local_gotno - SCORE_RESERVED_GOTNO;
break;
default:
swap_out_p = FALSE;
break;
}
if (swap_out_p)
(*get_elf_backend_data (dynobj)->s->swap_dyn_out) (dynobj, &dyn, b);
}
}
/* The first entry of the global offset table will be filled at
runtime. The second entry will be used by some runtime loaders.
This isn't the case of IRIX rld. */
if (sgot != NULL && sgot->size > 0)
{
score_bfd_put_32 (output_bfd, 0, sgot->contents);
score_bfd_put_32 (output_bfd, 0x80000000, sgot->contents + SCORE_ELF_GOT_SIZE (output_bfd));
}
if (sgot != NULL)
elf_section_data (sgot->output_section)->this_hdr.sh_entsize
= SCORE_ELF_GOT_SIZE (output_bfd);
/* We need to sort the entries of the dynamic relocation section. */
s = score_elf_rel_dyn_section (dynobj, FALSE);
if (s != NULL && s->size > (bfd_vma)2 * SCORE_ELF_REL_SIZE (output_bfd))
{
reldyn_sorting_bfd = output_bfd;
qsort ((Elf32_External_Rel *) s->contents + 1, s->reloc_count - 1,
sizeof (Elf32_External_Rel), score_elf_sort_dynamic_relocs);
}
return TRUE;
}
/* This function set up the ELF section header for a BFD section in preparation for writing
it out. This is where the flags and type fields are set for unusual sections. */
static bfd_boolean
s3_bfd_score_elf_fake_sections (bfd *abfd ATTRIBUTE_UNUSED,
Elf_Internal_Shdr *hdr,
asection *sec)
{
const char *name;
name = bfd_get_section_name (abfd, sec);
if (strcmp (name, ".got") == 0
|| strcmp (name, ".srdata") == 0
|| strcmp (name, ".sdata") == 0
|| strcmp (name, ".sbss") == 0)
hdr->sh_flags |= SHF_SCORE_GPREL;
return TRUE;
}
/* This function do additional processing on the ELF section header before writing
it out. This is used to set the flags and type fields for some sections. */
/* assign_file_positions_except_relocs() check section flag and if it is allocatable,
warning message will be issued. backend_fake_section is called before
assign_file_positions_except_relocs(); backend_section_processing after it. so, we
modify section flag there, but not backend_fake_section. */
static bfd_boolean
s3_bfd_score_elf_section_processing (bfd *abfd ATTRIBUTE_UNUSED, Elf_Internal_Shdr *hdr)
{
if (hdr->bfd_section != NULL)
{
const char *name = bfd_get_section_name (abfd, hdr->bfd_section);
if (strcmp (name, ".sdata") == 0)
{
hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_SCORE_GPREL;
hdr->sh_type = SHT_PROGBITS;
}
else if (strcmp (name, ".sbss") == 0)
{
hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_SCORE_GPREL;
hdr->sh_type = SHT_NOBITS;
}
else if (strcmp (name, ".srdata") == 0)
{
hdr->sh_flags |= SHF_ALLOC | SHF_SCORE_GPREL;
hdr->sh_type = SHT_PROGBITS;
}
}
return TRUE;
}
static bfd_boolean
s3_bfd_score_elf_write_section (bfd *output_bfd, asection *sec, bfd_byte *contents)
{
bfd_byte *to, *from, *end;
int i;
if (strcmp (sec->name, ".pdr") != 0)
return FALSE;
if (score_elf_section_data (sec)->u.tdata == NULL)
return FALSE;
to = contents;
end = contents + sec->size;
for (from = contents, i = 0; from < end; from += PDR_SIZE, i++)
{
if ((score_elf_section_data (sec)->u.tdata)[i] == 1)
continue;
if (to != from)
memcpy (to, from, PDR_SIZE);
to += PDR_SIZE;
}
bfd_set_section_contents (output_bfd, sec->output_section, contents,
(file_ptr) sec->output_offset, sec->size);
return TRUE;
}
/* Copy data from a SCORE ELF indirect symbol to its direct symbol, hiding the old
indirect symbol. Process additional relocation information. */
static void
s3_bfd_score_elf_copy_indirect_symbol (struct bfd_link_info *info,
struct elf_link_hash_entry *dir,
struct elf_link_hash_entry *ind)
{
struct score_elf_link_hash_entry *dirscore, *indscore;
_bfd_elf_link_hash_copy_indirect (info, dir, ind);
if (ind->root.type != bfd_link_hash_indirect)
return;
dirscore = (struct score_elf_link_hash_entry *) dir;
indscore = (struct score_elf_link_hash_entry *) ind;
dirscore->possibly_dynamic_relocs += indscore->possibly_dynamic_relocs;
if (indscore->readonly_reloc)
dirscore->readonly_reloc = TRUE;
if (indscore->no_fn_stub)
dirscore->no_fn_stub = TRUE;
}
/* Remove information about discarded functions from other sections which mention them. */
static bfd_boolean
s3_bfd_score_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
struct bfd_link_info *info)
{
asection *o;
bfd_boolean ret = FALSE;
unsigned char *tdata;
size_t i, skip;
o = bfd_get_section_by_name (abfd, ".pdr");
if ((!o) || (o->size == 0) || (o->size % PDR_SIZE != 0)
|| (o->output_section != NULL && bfd_is_abs_section (o->output_section)))
return FALSE;
tdata = bfd_zmalloc (o->size / PDR_SIZE);
if (!tdata)
return FALSE;
cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL, info->keep_memory);
if (!cookie->rels)
{
free (tdata);
return FALSE;
}
cookie->rel = cookie->rels;
cookie->relend = cookie->rels + o->reloc_count;
for (i = 0, skip = 0; i < o->size; i++)
{
if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie))
{
tdata[i] = 1;
skip++;
}
}
if (skip != 0)
{
score_elf_section_data (o)->u.tdata = tdata;
o->size -= skip * PDR_SIZE;
ret = TRUE;
}
else
free (tdata);
if (!info->keep_memory)
free (cookie->rels);
return ret;
}
/* Signal that discard_info() has removed the discarded relocations for this section. */
static bfd_boolean
s3_bfd_score_elf_ignore_discarded_relocs (asection *sec)
{
if (strcmp (sec->name, ".pdr") == 0)
return TRUE;
return FALSE;
}
/* Return the section that should be marked against GC for a given
relocation. */
static asection *
s3_bfd_score_elf_gc_mark_hook (asection *sec,
struct bfd_link_info *info,
Elf_Internal_Rela *rel,
struct elf_link_hash_entry *h,
Elf_Internal_Sym *sym)
{
if (h != NULL)
switch (ELF32_R_TYPE (rel->r_info))
{
case R_SCORE_GNU_VTINHERIT:
case R_SCORE_GNU_VTENTRY:
return NULL;
}
return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym);
}
/* Support for core dump NOTE sections. */
static bfd_boolean
s3_bfd_score_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
{
int offset;
unsigned int raw_size;
switch (note->descsz)
{
default:
return FALSE;
case 148: /* Linux/Score 32-bit. */
/* pr_cursig */
elf_tdata (abfd)->core->signal
= score_bfd_get_16 (abfd, note->descdata + 12);
/* pr_pid */
elf_tdata (abfd)->core->lwpid
= score_bfd_get_32 (abfd, note->descdata + 24);
/* pr_reg */
offset = 72;
raw_size = 72;
break;
}
/* Make a ".reg/999" section. */
return _bfd_elfcore_make_pseudosection (abfd, ".reg", raw_size,
note->descpos + offset);
}
static bfd_boolean
s3_bfd_score_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
{
switch (note->descsz)
{
default:
return FALSE;
case 124: /* Linux/Score elf_prpsinfo. */
elf_tdata (abfd)->core->program
= _bfd_elfcore_strndup (abfd, note->descdata + 28, 16);
elf_tdata (abfd)->core->command
= _bfd_elfcore_strndup (abfd, note->descdata + 44, 80);
}
/* Note that for some reason, a spurious space is tacked
onto the end of the args in some (at least one anyway)
implementations, so strip it off if it exists. */
{
char *command = elf_tdata (abfd)->core->command;
int n = strlen (command);
if (0 < n && command[n - 1] == ' ')
command[n - 1] = '\0';
}
return TRUE;
}
/* Score BFD functions. */
static reloc_howto_type *
s3_elf32_score_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED, bfd_reloc_code_real_type code)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE (elf32_score_reloc_map); i++)
if (elf32_score_reloc_map[i].bfd_reloc_val == code)
return &elf32_score_howto_table[elf32_score_reloc_map[i].elf_reloc_val];
return NULL;
}
static reloc_howto_type *
elf32_score_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED,
const char *r_name)
{
unsigned int i;
for (i = 0;
i < (sizeof (elf32_score_howto_table)
/ sizeof (elf32_score_howto_table[0]));
i++)
if (elf32_score_howto_table[i].name != NULL
&& strcasecmp (elf32_score_howto_table[i].name, r_name) == 0)
return &elf32_score_howto_table[i];
return NULL;
}
static bfd_boolean
s3_elf32_score_print_private_bfd_data (bfd *abfd, void * ptr)
{
FILE *file = (FILE *) ptr;
BFD_ASSERT (abfd != NULL && ptr != NULL);
/* Print normal ELF private data. */
_bfd_elf_print_private_bfd_data (abfd, ptr);
/* xgettext:c-format */
fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags);
if (elf_elfheader (abfd)->e_flags & EF_SCORE_PIC)
{
fprintf (file, _(" [pic]"));
}
if (elf_elfheader (abfd)->e_flags & EF_SCORE_FIXDEP)
{
fprintf (file, _(" [fix dep]"));
}
fputc ('\n', file);
return TRUE;
}
static bfd_boolean
s3_elf32_score_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
{
bfd *obfd = info->output_bfd;
flagword in_flags;
flagword out_flags;
if (!_bfd_generic_verify_endian_match (ibfd, info))
return FALSE;
in_flags = elf_elfheader (ibfd)->e_flags;
out_flags = elf_elfheader (obfd)->e_flags;
if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
|| bfd_get_flavour (obfd) != bfd_target_elf_flavour)
return TRUE;
in_flags = elf_elfheader (ibfd)->e_flags;
out_flags = elf_elfheader (obfd)->e_flags;
if (! elf_flags_init (obfd))
{
elf_flags_init (obfd) = TRUE;
elf_elfheader (obfd)->e_flags = in_flags;
if (bfd_get_arch (obfd) == bfd_get_arch (ibfd)
&& bfd_get_arch_info (obfd)->the_default)
{
return bfd_set_arch_mach (obfd, bfd_get_arch (ibfd), bfd_get_mach (ibfd));
}
return TRUE;
}
if (((in_flags & EF_SCORE_PIC) != 0) != ((out_flags & EF_SCORE_PIC) != 0))
_bfd_error_handler
(_("%B: warning: linking PIC files with non-PIC files"), ibfd);
/* FIXME: Maybe dependency fix compatibility should be checked here. */
return TRUE;
}
static bfd_boolean
s3_elf32_score_new_section_hook (bfd *abfd, asection *sec)
{
struct _score_elf_section_data *sdata;
bfd_size_type amt = sizeof (*sdata);
sdata = bfd_zalloc (abfd, amt);
if (sdata == NULL)
return FALSE;
sec->used_by_bfd = sdata;
return _bfd_elf_new_section_hook (abfd, sec);
}
/*****************************************************************************/
/* s3_s7: backend hooks. */
static void
_bfd_score_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
arelent *bfd_reloc,
Elf_Internal_Rela *elf_reloc)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_info_to_howto (abfd, bfd_reloc, elf_reloc);
else
return s7_bfd_score_info_to_howto (abfd, bfd_reloc, elf_reloc);
}
static bfd_boolean
_bfd_score_elf_relocate_section (bfd *output_bfd,
struct bfd_link_info *info,
bfd *input_bfd,
asection *input_section,
bfd_byte *contents,
Elf_Internal_Rela *relocs,
Elf_Internal_Sym *local_syms,
asection **local_sections)
{
if (bfd_get_mach (output_bfd) == bfd_mach_score3)
return s3_bfd_score_elf_relocate_section (output_bfd,
info, input_bfd, input_section, contents, relocs,
local_syms, local_sections);
else
return s7_bfd_score_elf_relocate_section (output_bfd,
info, input_bfd, input_section, contents, relocs,
local_syms, local_sections);
}
static bfd_boolean
_bfd_score_elf_check_relocs (bfd *abfd,
struct bfd_link_info *info,
asection *sec,
const Elf_Internal_Rela *relocs)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_check_relocs (abfd, info, sec, relocs);
else
return s7_bfd_score_elf_check_relocs (abfd, info, sec, relocs);
}
static bfd_boolean
_bfd_score_elf_add_symbol_hook (bfd *abfd,
struct bfd_link_info *info ATTRIBUTE_UNUSED,
Elf_Internal_Sym *sym,
const char **namep ATTRIBUTE_UNUSED,
flagword *flagsp ATTRIBUTE_UNUSED,
asection **secp,
bfd_vma *valp)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_add_symbol_hook (abfd, info, sym, namep, flagsp,
secp, valp);
else
return s7_bfd_score_elf_add_symbol_hook (abfd, info, sym, namep, flagsp,
secp, valp);
}
static void
_bfd_score_elf_symbol_processing (bfd *abfd, asymbol *asym)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_symbol_processing (abfd, asym);
else
return s7_bfd_score_elf_symbol_processing (abfd, asym);
}
static int
_bfd_score_elf_link_output_symbol_hook (struct bfd_link_info *info ATTRIBUTE_UNUSED,
const char *name ATTRIBUTE_UNUSED,
Elf_Internal_Sym *sym,
asection *input_sec,
struct elf_link_hash_entry *h ATTRIBUTE_UNUSED)
{
/* If link a empty .o, then this filed is NULL. */
if (info->input_bfds == NULL)
{
/* If we see a common symbol, which implies a relocatable link, then
if a symbol was small common in an input file, mark it as small
common in the output file. */
if (sym->st_shndx == SHN_COMMON && strcmp (input_sec->name, ".scommon") == 0)
sym->st_shndx = SHN_SCORE_SCOMMON;
return 1;
}
if (bfd_get_mach (info->input_bfds) == bfd_mach_score3)
return s3_bfd_score_elf_link_output_symbol_hook (info, name, sym, input_sec, h);
else
return s7_bfd_score_elf_link_output_symbol_hook (info, name, sym, input_sec, h);
}
static bfd_boolean
_bfd_score_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED,
asection *sec,
int *retval)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_section_from_bfd_section (abfd, sec, retval);
else
return s7_bfd_score_elf_section_from_bfd_section (abfd, sec, retval);
}
static bfd_boolean
_bfd_score_elf_adjust_dynamic_symbol (struct bfd_link_info *info,
struct elf_link_hash_entry *h)
{
if (bfd_get_mach (info->input_bfds) == bfd_mach_score3)
return s3_bfd_score_elf_adjust_dynamic_symbol (info, h);
else
return s7_bfd_score_elf_adjust_dynamic_symbol (info, h);
}
static bfd_boolean
_bfd_score_elf_always_size_sections (bfd *output_bfd,
struct bfd_link_info *info)
{
if (bfd_get_mach (output_bfd) == bfd_mach_score3)
return s3_bfd_score_elf_always_size_sections (output_bfd, info);
else
return s7_bfd_score_elf_always_size_sections (output_bfd, info);
}
static bfd_boolean
_bfd_score_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info)
{
if (bfd_get_mach (output_bfd) == bfd_mach_score3)
return s3_bfd_score_elf_size_dynamic_sections (output_bfd, info);
else
return s7_bfd_score_elf_size_dynamic_sections (output_bfd, info);
}
static bfd_boolean
_bfd_score_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_create_dynamic_sections (abfd, info);
else
return s7_bfd_score_elf_create_dynamic_sections (abfd, info);
}
static bfd_boolean
_bfd_score_elf_finish_dynamic_symbol (bfd *output_bfd,
struct bfd_link_info *info,
struct elf_link_hash_entry *h,
Elf_Internal_Sym *sym)
{
if (bfd_get_mach (output_bfd) == bfd_mach_score3)
return s3_bfd_score_elf_finish_dynamic_symbol (output_bfd, info, h, sym);
else
return s7_bfd_score_elf_finish_dynamic_symbol (output_bfd, info, h, sym);
}
static bfd_boolean
_bfd_score_elf_finish_dynamic_sections (bfd *output_bfd,
struct bfd_link_info *info)
{
if (bfd_get_mach (output_bfd) == bfd_mach_score3)
return s3_bfd_score_elf_finish_dynamic_sections (output_bfd, info);
else
return s7_bfd_score_elf_finish_dynamic_sections (output_bfd, info);
}
static bfd_boolean
_bfd_score_elf_fake_sections (bfd *abfd ATTRIBUTE_UNUSED,
Elf_Internal_Shdr *hdr,
asection *sec)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_fake_sections (abfd, hdr, sec);
else
return s7_bfd_score_elf_fake_sections (abfd, hdr, sec);
}
static bfd_boolean
_bfd_score_elf_section_processing (bfd *abfd ATTRIBUTE_UNUSED, Elf_Internal_Shdr *hdr)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_section_processing (abfd, hdr);
else
return s7_bfd_score_elf_section_processing (abfd, hdr);
}
static bfd_boolean
_bfd_score_elf_write_section (bfd *output_bfd,
struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
asection *sec, bfd_byte *contents)
{
if (bfd_get_mach (output_bfd) == bfd_mach_score3)
return s3_bfd_score_elf_write_section (output_bfd, sec, contents);
else
return s7_bfd_score_elf_write_section (output_bfd, sec, contents);
}
static void
_bfd_score_elf_copy_indirect_symbol (struct bfd_link_info *info,
struct elf_link_hash_entry *dir,
struct elf_link_hash_entry *ind)
{
if (bfd_get_mach (info->input_bfds) == bfd_mach_score3)
return s3_bfd_score_elf_copy_indirect_symbol (info, dir, ind);
else
return s7_bfd_score_elf_copy_indirect_symbol (info, dir, ind);
}
static void
_bfd_score_elf_hide_symbol (struct bfd_link_info *info,
struct elf_link_hash_entry *entry,
bfd_boolean force_local)
{
if (bfd_get_mach (info->input_bfds) == bfd_mach_score3)
return s3_bfd_score_elf_hide_symbol (info, entry, force_local);
else
return s7_bfd_score_elf_hide_symbol (info, entry, force_local);
}
static bfd_boolean
_bfd_score_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie,
struct bfd_link_info *info)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_discard_info (abfd, cookie, info);
else
return s7_bfd_score_elf_discard_info (abfd, cookie, info);
}
static bfd_boolean
_bfd_score_elf_ignore_discarded_relocs (asection *sec)
{
if (bfd_get_mach (sec->owner) == bfd_mach_score3)
return s3_bfd_score_elf_ignore_discarded_relocs (sec);
else
return s7_bfd_score_elf_ignore_discarded_relocs (sec);
}
static asection *
_bfd_score_elf_gc_mark_hook (asection *sec,
struct bfd_link_info *info,
Elf_Internal_Rela *rel,
struct elf_link_hash_entry *h,
Elf_Internal_Sym *sym)
{
if (bfd_get_mach (info->input_bfds) == bfd_mach_score3)
return s3_bfd_score_elf_gc_mark_hook (sec, info, rel, h, sym);
else
return s7_bfd_score_elf_gc_mark_hook (sec, info, rel, h, sym);
}
static bfd_boolean
_bfd_score_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_grok_prstatus (abfd, note);
else
return s7_bfd_score_elf_grok_prstatus (abfd, note);
}
static bfd_boolean
_bfd_score_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_bfd_score_elf_grok_psinfo (abfd, note);
else
return s7_bfd_score_elf_grok_psinfo (abfd, note);
}
static reloc_howto_type *
elf32_score_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED, bfd_reloc_code_real_type code)
{
/* s3: NOTE!!!
gas will call elf32_score_reloc_type_lookup, and don't write elf file.
So just using score3, but we don't know ld will call this or not.
If so, this way can't work. */
if (score3)
return s3_elf32_score_reloc_type_lookup (abfd, code);
else
return s7_elf32_score_reloc_type_lookup (abfd, code);
}
/* Create a score elf linker hash table.
This is a copy of _bfd_elf_link_hash_table_create() except with a
different hash table entry creation function. */
static struct bfd_link_hash_table *
elf32_score_link_hash_table_create (bfd *abfd)
{
struct elf_link_hash_table *ret;
bfd_size_type amt = sizeof (struct elf_link_hash_table);
ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
if (ret == NULL)
return NULL;
if (!_bfd_elf_link_hash_table_init (ret, abfd, score_elf_link_hash_newfunc,
sizeof (struct score_elf_link_hash_entry),
GENERIC_ELF_DATA))
{
free (ret);
return NULL;
}
return &ret->root;
}
static bfd_boolean
elf32_score_print_private_bfd_data (bfd *abfd, void * ptr)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_elf32_score_print_private_bfd_data (abfd, ptr);
else
return s7_elf32_score_print_private_bfd_data (abfd, ptr);
}
static bfd_boolean
elf32_score_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info)
{
if (bfd_get_mach (info->output_bfd) == bfd_mach_score3)
return s3_elf32_score_merge_private_bfd_data (ibfd, info);
else
return s7_elf32_score_merge_private_bfd_data (ibfd, info);
}
static bfd_boolean
elf32_score_new_section_hook (bfd *abfd, asection *sec)
{
if (bfd_get_mach (abfd) == bfd_mach_score3)
return s3_elf32_score_new_section_hook (abfd, sec);
else
return s7_elf32_score_new_section_hook (abfd, sec);
}
/* s3_s7: don't need to split. */
/* Set the right machine number. */
static bfd_boolean
_bfd_score_elf_score_object_p (bfd * abfd)
{
int e_set = bfd_mach_score7;
if (elf_elfheader (abfd)->e_machine == EM_SCORE)
{
int e_mach = elf_elfheader (abfd)->e_flags & EF_SCORE_MACH & EF_OMIT_PIC_FIXDD;
switch (e_mach)
{
/* Set default target is score7. */
default:
case E_SCORE_MACH_SCORE7:
e_set = bfd_mach_score7;
break;
case E_SCORE_MACH_SCORE3:
e_set = bfd_mach_score3;
break;
}
}
return bfd_default_set_arch_mach (abfd, bfd_arch_score, e_set);
}
bfd_boolean
_bfd_score_elf_common_definition (Elf_Internal_Sym *sym)
{
return (sym->st_shndx == SHN_COMMON || sym->st_shndx == SHN_SCORE_SCOMMON);
}
/*****************************************************************************/
#define USE_REL 1
#define TARGET_LITTLE_SYM score_elf32_le_vec
#define TARGET_LITTLE_NAME "elf32-littlescore"
#define TARGET_BIG_SYM score_elf32_be_vec
#define TARGET_BIG_NAME "elf32-bigscore"
#define ELF_ARCH bfd_arch_score
#define ELF_MACHINE_CODE EM_SCORE
#define ELF_MACHINE_ALT1 EM_SCORE_OLD
#define ELF_MAXPAGESIZE 0x8000
#define elf_info_to_howto 0
#define elf_info_to_howto_rel _bfd_score_info_to_howto
#define elf_backend_relocate_section _bfd_score_elf_relocate_section
#define elf_backend_check_relocs _bfd_score_elf_check_relocs
#define elf_backend_add_symbol_hook _bfd_score_elf_add_symbol_hook
#define elf_backend_symbol_processing _bfd_score_elf_symbol_processing
#define elf_backend_link_output_symbol_hook \
_bfd_score_elf_link_output_symbol_hook
#define elf_backend_section_from_bfd_section \
_bfd_score_elf_section_from_bfd_section
#define elf_backend_adjust_dynamic_symbol \
_bfd_score_elf_adjust_dynamic_symbol
#define elf_backend_always_size_sections \
_bfd_score_elf_always_size_sections
#define elf_backend_size_dynamic_sections \
_bfd_score_elf_size_dynamic_sections
#define elf_backend_omit_section_dynsym \
((bfd_boolean (*) (bfd *, struct bfd_link_info *, asection *)) bfd_true)
#define elf_backend_create_dynamic_sections \
_bfd_score_elf_create_dynamic_sections
#define elf_backend_finish_dynamic_symbol \
_bfd_score_elf_finish_dynamic_symbol
#define elf_backend_finish_dynamic_sections \
_bfd_score_elf_finish_dynamic_sections
#define elf_backend_fake_sections _bfd_score_elf_fake_sections
#define elf_backend_section_processing _bfd_score_elf_section_processing
#define elf_backend_write_section _bfd_score_elf_write_section
#define elf_backend_copy_indirect_symbol _bfd_score_elf_copy_indirect_symbol
#define elf_backend_hide_symbol _bfd_score_elf_hide_symbol
#define elf_backend_discard_info _bfd_score_elf_discard_info
#define elf_backend_ignore_discarded_relocs \
_bfd_score_elf_ignore_discarded_relocs
#define elf_backend_gc_mark_hook _bfd_score_elf_gc_mark_hook
#define elf_backend_grok_prstatus _bfd_score_elf_grok_prstatus
#define elf_backend_grok_psinfo _bfd_score_elf_grok_psinfo
#define elf_backend_can_gc_sections 1
#define elf_backend_want_plt_sym 0
#define elf_backend_got_header_size (4 * SCORE_RESERVED_GOTNO)
#define elf_backend_plt_header_size 0
#define elf_backend_collect TRUE
#define elf_backend_type_change_ok TRUE
#define elf_backend_object_p _bfd_score_elf_score_object_p
#define bfd_elf32_bfd_reloc_type_lookup elf32_score_reloc_type_lookup
#define bfd_elf32_bfd_reloc_name_lookup \
elf32_score_reloc_name_lookup
#define bfd_elf32_bfd_link_hash_table_create elf32_score_link_hash_table_create
#define bfd_elf32_bfd_print_private_bfd_data elf32_score_print_private_bfd_data
#define bfd_elf32_bfd_merge_private_bfd_data elf32_score_merge_private_bfd_data
#define bfd_elf32_new_section_hook elf32_score_new_section_hook
#include "elf32-target.h"
| Java |
/****************************************************************************************************************
Default styles for the WYSIWYG editor
Adding style-editor.css to a child theme's root will over-write these styles.
****************************************************************************************************************/
html .mceContentBody {
max-width:640px;
background:#fff;
color:#333;
font:100% Arial,sans-serif;
line-height:1.5em;
}
* {
font-family: Arial,sans-serif;
color: #333;
line-height: 1.5em;
}
a, a:visited {
text-decoration:none;
color:#999;
}
a:hover, a:active {
color:#333;
}
h1,h2,h3,h4,h5,h6 {
color:#111;
font-weight:bold;
font-family:Arial,sans-serif;
line-height:2em;
}
h1 { font-size:2em; }
h2 { font-size:1.8em; }
h3 { font-size:1.4em; }
h4 { font-size:1.2em; }
h5 { font-size:1em; }
h6 { font-size:.8em; }
hr {
margin:1.4em auto;
display:block;
clear:both;
border-collapse:collapse;
border:0;
border-bottom:1px solid #aaa;
}
p { margin-bottom:18px; }
blockquote { font-style:italic; }
cite { border:0; }
sup, sub { font-size:.6em; }
pre {
background:#f9f9f9;
padding:1em;
border:1px solid #dadada;
}
del {
color:inherit;
}
ins {
background:#ff8;
color:inherit;
text-decoration:none;
border:0;
padding:0 4px;
}
.wp-caption {
background:#f0f0f0;
color:#555;
padding:10px;
border:1px solid #ddd;
}
.wp-caption img { margin:0; padding:0; }
strong { color:#111; }
table {
border:1px solid #ddd;
width:100%;
}
table th {
padding:5px 20px;
text-align:left;
font-weight:bold;
color:#111;
}
table td {
border-top:1px solid #ddd;
padding:5px 20px;
}
.al, .alignleft, .left {
position:relative;
float:left!important;
margin-right:10px;
}
.ar, .alignright, .right {
position:relative;
float:right!important;
margin-left:10px;
}
.ma {margin:auto;}
.cb {clear:both;}
img, p img {
float:none;
margin:auto;
border:0;
}
.more-link {
display:block;
position:relative;
float:left;
clear:both;
}
.submit-button {
background:#333;
color:#fff;
border:0;
width:auto;
font-weight:bold;
text-transform:uppercase;
}
.submit-button:hover {
background:#555;
}
.hideme {
display:none;
}
dl,
ul,
ol {
margin:1em 2em;
}
dl dl,
ul ul,
ol ol {
margin:0em 2em;
}
ul {
list-style:disc;
}
ol {
list-style-type:lower-roman;
} | Java |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_OPERATORS_RX_SEQUENCE_EQUAL_HPP)
#define RXCPP_OPERATORS_RX_SEQUENCE_EQUAL_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class T, class Observable, class OtherObservable, class BinaryPredicate, class Coordination>
struct sequence_equal : public operator_base<bool>
{
typedef rxu::decay_t<Observable> source_type;
typedef rxu::decay_t<T> source_value_type;
typedef rxu::decay_t<OtherObservable> other_source_type;
typedef typename other_source_type::value_type other_source_value_type;
typedef rxu::decay_t<BinaryPredicate> predicate_type;
typedef rxu::decay_t<Coordination> coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
struct values {
values(source_type s, other_source_type t, predicate_type pred, coordination_type sf)
: source(std::move(s))
, other(std::move(t))
, pred(std::move(pred))
, coordination(std::move(sf))
{
}
source_type source;
other_source_type other;
predicate_type pred;
coordination_type coordination;
};
values initial;
sequence_equal(source_type s, other_source_type t, predicate_type pred, coordination_type sf)
: initial(std::move(s), std::move(t), std::move(pred), std::move(sf))
{
}
template<class Subscriber>
void on_subscribe(Subscriber s) const {
typedef Subscriber output_type;
struct state_type
: public std::enable_shared_from_this<state_type>
, public values
{
state_type(const values& vals, coordinator_type coor, const output_type& o)
: values(vals)
, coordinator(std::move(coor))
, out(o)
, source_completed(false)
, other_completed(false)
{
out.add(other_lifetime);
out.add(source_lifetime);
}
composite_subscription other_lifetime;
composite_subscription source_lifetime;
coordinator_type coordinator;
output_type out;
mutable std::list<source_value_type> source_values;
mutable std::list<other_source_value_type> other_values;
mutable bool source_completed;
mutable bool other_completed;
};
auto coordinator = initial.coordination.create_coordinator();
auto state = std::make_shared<state_type>(initial, std::move(coordinator), std::move(s));
auto other = on_exception(
[&](){ return state->coordinator.in(state->other); },
state->out);
if (other.empty()) {
return;
}
auto source = on_exception(
[&](){ return state->coordinator.in(state->source); },
state->out);
if (source.empty()) {
return;
}
auto check_equal = [state]() {
if(!state->source_values.empty() && !state->other_values.empty()) {
auto x = std::move(state->source_values.front());
state->source_values.pop_front();
auto y = std::move(state->other_values.front());
state->other_values.pop_front();
if (!state->pred(x, y)) {
state->out.on_next(false);
state->out.on_completed();
}
} else {
if((!state->source_values.empty() && state->other_completed) ||
(!state->other_values.empty() && state->source_completed)) {
state->out.on_next(false);
state->out.on_completed();
}
}
};
auto check_complete = [state]() {
if(state->source_completed && state->other_completed) {
state->out.on_next(state->source_values.empty() && state->other_values.empty());
state->out.on_completed();
}
};
auto sinkOther = make_subscriber<other_source_value_type>(
state->out,
state->other_lifetime,
// on_next
[state, check_equal](other_source_value_type t) {
auto& values = state->other_values;
values.push_back(t);
check_equal();
},
// on_error
[state](std::exception_ptr e) {
state->out.on_error(e);
},
// on_completed
[state, check_complete]() {
auto& completed = state->other_completed;
completed = true;
check_complete();
}
);
auto selectedSinkOther = on_exception(
[&](){ return state->coordinator.out(sinkOther); },
state->out);
if (selectedSinkOther.empty()) {
return;
}
other->subscribe(std::move(selectedSinkOther.get()));
source.get().subscribe(
state->source_lifetime,
// on_next
[state, check_equal](source_value_type t) {
auto& values = state->source_values;
values.push_back(t);
check_equal();
},
// on_error
[state](std::exception_ptr e) {
state->out.on_error(e);
},
// on_completed
[state, check_complete]() {
auto& completed = state->source_completed;
completed = true;
check_complete();
}
);
}
};
template<class OtherObservable, class BinaryPredicate, class Coordination>
class sequence_equal_factory
{
typedef rxu::decay_t<OtherObservable> other_source_type;
typedef rxu::decay_t<Coordination> coordination_type;
typedef rxu::decay_t<BinaryPredicate> predicate_type;
other_source_type other_source;
coordination_type coordination;
predicate_type pred;
public:
sequence_equal_factory(other_source_type t, predicate_type p, coordination_type sf)
: other_source(std::move(t))
, coordination(std::move(sf))
, pred(std::move(p))
{
}
template<class Observable>
auto operator()(Observable&& source)
-> observable<bool, sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>> {
return observable<bool, sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>>(
sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>(std::forward<Observable>(source), other_source, pred, coordination));
}
};
}
template<class OtherObservable>
inline auto sequence_equal(OtherObservable&& t)
-> detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, identity_one_worker> {
return detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, identity_one_worker>(std::forward<OtherObservable>(t), rxu::equal_to<>(), identity_current_thread());
}
template<class OtherObservable, class BinaryPredicate, class Check = typename std::enable_if<!is_coordination<BinaryPredicate>::value>::type>
inline auto sequence_equal(OtherObservable&& t, BinaryPredicate&& pred)
-> detail::sequence_equal_factory<OtherObservable, BinaryPredicate, identity_one_worker> {
return detail::sequence_equal_factory<OtherObservable, BinaryPredicate, identity_one_worker>(std::forward<OtherObservable>(t), std::forward<BinaryPredicate>(pred), identity_current_thread());
}
template<class OtherObservable, class Coordination, class Check = typename std::enable_if<is_coordination<Coordination>::value>::type>
inline auto sequence_equal(OtherObservable&& t, Coordination&& cn)
-> detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, Coordination> {
return detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, Coordination>(std::forward<OtherObservable>(t), rxu::equal_to<>(), std::forward<Coordination>(cn));
}
template<class OtherObservable, class BinaryPredicate, class Coordination>
inline auto sequence_equal(OtherObservable&& t, BinaryPredicate&& pred, Coordination&& cn)
-> detail::sequence_equal_factory<OtherObservable, BinaryPredicate, Coordination> {
return detail::sequence_equal_factory<OtherObservable, BinaryPredicate, Coordination>(std::forward<OtherObservable>(t), std::forward<BinaryPredicate>(pred), std::forward<Coordination>(cn));
}
}
}
#endif
| Java |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
var varienTabs = new Class.create();
varienTabs.prototype = {
initialize : function(containerId, destElementId, activeTabId, shadowTabs){
this.containerId = containerId;
this.destElementId = destElementId;
this.activeTab = null;
this.tabOnClick = this.tabMouseClick.bindAsEventListener(this);
this.tabs = $$('#'+this.containerId+' li a.tab-item-link');
this.hideAllTabsContent();
for (var tab=0; tab<this.tabs.length; tab++) {
Event.observe(this.tabs[tab],'click',this.tabOnClick);
// move tab contents to destination element
if($(this.destElementId)){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].contentMoved = true;
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
/*
// this code is pretty slow in IE, so lets do it in tabs*.phtml
// mark ajax tabs as not loaded
if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) {
Element.addClassName($(this.tabs[tab].id), 'notloaded');
}
*/
// bind shadow tabs
if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) {
this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id];
}
}
this.displayFirst = activeTabId;
Event.observe(window,'load',this.moveTabContentInDest.bind(this));
},
setSkipDisplayFirstTab : function(){
this.displayFirst = null;
},
moveTabContentInDest : function(){
for(var tab=0; tab<this.tabs.length; tab++){
if($(this.destElementId) && !this.tabs[tab].contentMoved){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
}
if (this.displayFirst) {
this.showTabContent($(this.displayFirst));
this.displayFirst = null;
}
},
getTabContentElementId : function(tab){
if(tab){
return tab.id+'_content';
}
return false;
},
tabMouseClick : function(event) {
var tab = Event.findElement(event, 'a');
// go directly to specified url or switch tab
if ((tab.href.indexOf('#') != tab.href.length-1)
&& !(Element.hasClassName(tab, 'ajax'))
) {
location.href = tab.href;
}
else {
this.showTabContent(tab);
}
Event.stop(event);
},
hideAllTabsContent : function(){
for(var tab in this.tabs){
this.hideTabContent(this.tabs[tab]);
}
},
// show tab, ready or not
showTabContentImmediately : function(tab) {
this.hideAllTabsContent();
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
Element.show(tabContentElement);
Element.addClassName(tab, 'active');
// load shadow tabs, if any
if (tab.shadowTabs && tab.shadowTabs.length) {
for (var k in tab.shadowTabs) {
this.loadShadowTab($(tab.shadowTabs[k]));
}
}
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
this.activeTab = tab;
}
if (varienGlobalEvents) {
varienGlobalEvents.fireEvent('showTab', {tab:tab});
}
},
// the lazy show tab method
showTabContent : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
if (this.activeTab != tab) {
if (varienGlobalEvents) {
if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) {
return;
};
}
}
// wait for ajax request, if defined
var isAjax = Element.hasClassName(tab, 'ajax');
var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1;
var isNotLoaded = Element.hasClassName(tab, 'notloaded');
if ( isAjax && (isEmpty || isNotLoaded) )
{
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}.bind(this)
});
}
else {
this.showTabContentImmediately(tab);
}
}
},
loadShadowTab : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) {
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}.bind(this)
});
}
},
hideTabContent : function(tab){
var tabContentElement = $(this.getTabContentElementId(tab));
if($(this.destElementId) && tabContentElement){
Element.hide(tabContentElement);
Element.removeClassName(tab, 'active');
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('hideTab', {tab:tab});
}
}
} | Java |
/*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2015 ArkCORE <http://www.arkania.net/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DatabaseEnv.h"
#include "Log.h"
ResultSet::ResultSet(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) :
_rowCount(rowCount),
_fieldCount(fieldCount),
_result(result),
_fields(fields)
{
_currentRow = new Field[_fieldCount];
ASSERT(_currentRow);
}
PreparedResultSet::PreparedResultSet(MYSQL_STMT* stmt, MYSQL_RES *result, uint64 rowCount, uint32 fieldCount) :
m_rowCount(rowCount),
m_rowPosition(0),
m_fieldCount(fieldCount),
m_rBind(NULL),
m_stmt(stmt),
m_res(result),
m_isNull(NULL),
m_length(NULL)
{
if (!m_res)
return;
if (m_stmt->bind_result_done)
{
delete[] m_stmt->bind->length;
delete[] m_stmt->bind->is_null;
}
m_rBind = new MYSQL_BIND[m_fieldCount];
m_isNull = new my_bool[m_fieldCount];
m_length = new unsigned long[m_fieldCount];
memset(m_isNull, 0, sizeof(my_bool) * m_fieldCount);
memset(m_rBind, 0, sizeof(MYSQL_BIND) * m_fieldCount);
memset(m_length, 0, sizeof(unsigned long) * m_fieldCount);
//- This is where we store the (entire) resultset
if (mysql_stmt_store_result(m_stmt))
{
TC_LOG_WARN("sql.sql", "%s:mysql_stmt_store_result, cannot bind result from MySQL server. Error: %s", __FUNCTION__, mysql_stmt_error(m_stmt));
delete[] m_rBind;
delete[] m_isNull;
delete[] m_length;
return;
}
//- This is where we prepare the buffer based on metadata
uint32 i = 0;
MYSQL_FIELD* field = mysql_fetch_field(m_res);
while (field)
{
size_t size = Field::SizeForType(field);
m_rBind[i].buffer_type = field->type;
m_rBind[i].buffer = malloc(size);
memset(m_rBind[i].buffer, 0, size);
m_rBind[i].buffer_length = size;
m_rBind[i].length = &m_length[i];
m_rBind[i].is_null = &m_isNull[i];
m_rBind[i].error = NULL;
m_rBind[i].is_unsigned = field->flags & UNSIGNED_FLAG;
++i;
field = mysql_fetch_field(m_res);
}
//- This is where we bind the bind the buffer to the statement
if (mysql_stmt_bind_result(m_stmt, m_rBind))
{
TC_LOG_WARN("sql.sql", "%s:mysql_stmt_bind_result, cannot bind result from MySQL server. Error: %s", __FUNCTION__, mysql_stmt_error(m_stmt));
delete[] m_rBind;
delete[] m_isNull;
delete[] m_length;
return;
}
m_rowCount = mysql_stmt_num_rows(m_stmt);
m_rows.resize(uint32(m_rowCount));
while (_NextRow())
{
m_rows[uint32(m_rowPosition)] = new Field[m_fieldCount];
for (uint64 fIndex = 0; fIndex < m_fieldCount; ++fIndex)
{
if (!*m_rBind[fIndex].is_null)
m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( m_rBind[fIndex].buffer,
m_rBind[fIndex].buffer_length,
m_rBind[fIndex].buffer_type,
*m_rBind[fIndex].length );
else
switch (m_rBind[fIndex].buffer_type)
{
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( "",
m_rBind[fIndex].buffer_length,
m_rBind[fIndex].buffer_type,
*m_rBind[fIndex].length );
break;
default:
m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( 0,
m_rBind[fIndex].buffer_length,
m_rBind[fIndex].buffer_type,
*m_rBind[fIndex].length );
}
}
m_rowPosition++;
}
m_rowPosition = 0;
/// All data is buffered, let go of mysql c api structures
CleanUp();
}
ResultSet::~ResultSet()
{
CleanUp();
}
PreparedResultSet::~PreparedResultSet()
{
for (uint32 i = 0; i < uint32(m_rowCount); ++i)
delete[] m_rows[i];
}
bool ResultSet::NextRow()
{
MYSQL_ROW row;
if (!_result)
return false;
row = mysql_fetch_row(_result);
if (!row)
{
CleanUp();
return false;
}
for (uint32 i = 0; i < _fieldCount; i++)
_currentRow[i].SetStructuredValue(row[i], _fields[i].type);
return true;
}
bool PreparedResultSet::NextRow()
{
/// Only updates the m_rowPosition so upper level code knows in which element
/// of the rows vector to look
if (++m_rowPosition >= m_rowCount)
return false;
return true;
}
bool PreparedResultSet::_NextRow()
{
/// Only called in low-level code, namely the constructor
/// Will iterate over every row of data and buffer it
if (m_rowPosition >= m_rowCount)
return false;
int retval = mysql_stmt_fetch( m_stmt );
if (!retval || retval == MYSQL_DATA_TRUNCATED)
retval = true;
if (retval == MYSQL_NO_DATA)
retval = false;
return retval;
}
void ResultSet::CleanUp()
{
if (_currentRow)
{
delete [] _currentRow;
_currentRow = NULL;
}
if (_result)
{
mysql_free_result(_result);
_result = NULL;
}
}
void PreparedResultSet::CleanUp()
{
/// More of the in our code allocated sources are deallocated by the poorly documented mysql c api
if (m_res)
mysql_free_result(m_res);
FreeBindBuffer();
mysql_stmt_free_result(m_stmt);
delete[] m_rBind;
}
void PreparedResultSet::FreeBindBuffer()
{
for (uint32 i = 0; i < m_fieldCount; ++i)
free (m_rBind[i].buffer);
}
| Java |
/* gsm_map_summary.c
* Routines for GSM MAP Statictics summary window
*
* Copyright 2004, Michael Lum <mlum [AT] telostech.com>
* In association with Telos Technology Inc.
*
* Modified from summary_dlg.c
*
* $Id: gsm_map_summary.c 48448 2013-03-21 02:58:59Z wmeier $
*
* 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.
*/
#include "config.h"
#include <gtk/gtk.h>
#include <wiretap/wtap.h>
#include <epan/epan.h>
#include <epan/packet.h>
#include <epan/packet_info.h>
#include <epan/value_string.h>
#include <epan/tap.h>
#include <epan/asn1.h>
#include <epan/dissectors/packet-gsm_map.h>
#include "../stat_menu.h"
#include "../globals.h"
#include "../file.h"
#include "../summary.h"
#include "ui/gtk/gui_stat_menu.h"
#include "ui/gtk/dlg_utils.h"
#include "ui/gtk/gui_utils.h"
#include "ui/gtk/gsm_map_stat.h"
#define SUM_STR_MAX 1024
static void
add_string_to_box(gchar *str, GtkWidget *box)
{
GtkWidget *lb;
lb = gtk_label_new(str);
gtk_misc_set_alignment(GTK_MISC(lb), 0.0f, 0.5f);
gtk_box_pack_start(GTK_BOX(box), lb,FALSE,FALSE, 0);
gtk_widget_show(lb);
}
void gsm_map_stat_gtk_sum_cb(GtkAction *action _U_, gpointer user_data _U_)
{
summary_tally summary;
GtkWidget *sum_open_w,
*main_vb, *file_fr, *data_fr, *file_box,
*data_box, *bbox, *close_bt,
*invoke_fr, *invoke_box,
*rr_fr, *rr_box,
*tot_fr, *tot_box;
gchar string_buff[SUM_STR_MAX];
double seconds;
int i;
int tot_invokes, tot_rr;
double tot_invokes_size, tot_rr_size;
/* initialize the tally */
summary_fill_in(&cfile, &summary);
/* initial computations */
seconds = summary.stop_time - summary.start_time;
sum_open_w = dlg_window_new("GSM MAP Statistics: Summary"); /* transient_for top_level */
gtk_window_set_destroy_with_parent (GTK_WINDOW(sum_open_w), TRUE);
/* Container for each row of widgets */
main_vb = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE);
gtk_container_set_border_width(GTK_CONTAINER(main_vb), 5);
gtk_container_add(GTK_CONTAINER(sum_open_w), main_vb);
gtk_widget_show(main_vb);
/* File frame */
file_fr = gtk_frame_new("File");
gtk_box_pack_start(GTK_BOX (main_vb), file_fr, TRUE, TRUE, 0);
gtk_widget_show(file_fr);
file_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE);
gtk_container_add(GTK_CONTAINER(file_fr), file_box);
gtk_widget_show(file_box);
/* filename */
g_snprintf(string_buff, SUM_STR_MAX, "Name: %s", ((summary.filename) ? summary.filename : "None"));
add_string_to_box(string_buff, file_box);
/* length */
g_snprintf(string_buff, SUM_STR_MAX, "Length: %" G_GINT64_MODIFIER "d", summary.file_length);
add_string_to_box(string_buff, file_box);
/* format */
g_snprintf(string_buff, SUM_STR_MAX, "Format: %s", wtap_file_type_string(summary.file_type));
add_string_to_box(string_buff, file_box);
if (summary.has_snap) {
/* snapshot length */
g_snprintf(string_buff, SUM_STR_MAX, "Snapshot length: %u", summary.snap);
add_string_to_box(string_buff, file_box);
}
/* Data frame */
data_fr = gtk_frame_new("Data");
gtk_box_pack_start(GTK_BOX (main_vb), data_fr, TRUE, TRUE, 0);
gtk_widget_show(data_fr);
data_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE);
gtk_container_add(GTK_CONTAINER(data_fr), data_box);
gtk_widget_show(data_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
/* seconds */
g_snprintf(string_buff, SUM_STR_MAX, "Elapsed time: %.3f seconds", summary.elapsed_time);
add_string_to_box(string_buff, data_box);
g_snprintf(string_buff, SUM_STR_MAX, "Between first and last packet: %.3f seconds", seconds);
add_string_to_box(string_buff, data_box);
}
/* Packet count */
g_snprintf(string_buff, SUM_STR_MAX, "Packet count: %i", summary.packet_count);
add_string_to_box(string_buff, data_box);
tot_invokes = 0;
tot_invokes_size = 0;
for (i=0; i < GSM_MAP_MAX_NUM_OPR_CODES; i++)
{
tot_invokes += gsm_map_stat.opr_code[i];
tot_invokes_size += gsm_map_stat.size[i];
}
tot_rr = 0;
tot_rr_size = 0;
for (i=0; i < GSM_MAP_MAX_NUM_OPR_CODES; i++)
{
tot_rr += gsm_map_stat.opr_code_rr[i];
tot_rr_size += gsm_map_stat.size_rr[i];
}
/* Invoke frame */
invoke_fr = gtk_frame_new("Invokes");
gtk_box_pack_start(GTK_BOX (main_vb), invoke_fr, TRUE, TRUE, 0);
gtk_widget_show(invoke_fr);
invoke_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE);
gtk_container_add(GTK_CONTAINER(invoke_fr), invoke_box);
gtk_widget_show(invoke_box);
/* Total number of invokes */
g_snprintf(string_buff, SUM_STR_MAX, "Total number of Invokes: %u", tot_invokes);
add_string_to_box(string_buff, invoke_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
/* Total number of invokes per second */
if (seconds)
g_snprintf(string_buff, SUM_STR_MAX, "Total number of Invokes per second: %.2f", tot_invokes/seconds);
else
g_snprintf(string_buff, SUM_STR_MAX, "Total number of Invokes per second: N/A");
add_string_to_box(string_buff, invoke_box);
}
/* Total size of invokes */
g_snprintf(string_buff, SUM_STR_MAX, "Total number of bytes for Invokes: %.0f", tot_invokes_size);
add_string_to_box(string_buff, invoke_box);
/* Average size of invokes */
if (tot_invokes)
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Invoke: %.2f", tot_invokes_size/tot_invokes);
else
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Invoke: N/A");
add_string_to_box(string_buff, invoke_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
/* Average size of invokes per second */
if (seconds)
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: %.2f", tot_invokes_size/seconds);
else
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: N/A");
add_string_to_box(string_buff, invoke_box);
}
/* Return Results frame */
rr_fr = gtk_frame_new("Return Results");
gtk_box_pack_start(GTK_BOX (main_vb), rr_fr, TRUE, TRUE, 0);
gtk_widget_show(rr_fr);
rr_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE);
gtk_container_add(GTK_CONTAINER(rr_fr), rr_box);
gtk_widget_show(rr_box);
/* Total number of return results */
g_snprintf(string_buff, SUM_STR_MAX, "Total number of Return Results: %u", tot_rr);
add_string_to_box(string_buff, rr_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
/* Total number of return results per second */
if (seconds)
g_snprintf(string_buff, SUM_STR_MAX, "Total number of Return Results per second: %.2f", tot_rr/seconds);
else
g_snprintf(string_buff, SUM_STR_MAX, "Total number of Return Results per second: N/A");
add_string_to_box(string_buff, rr_box);
}
/* Total size of return results */
g_snprintf(string_buff, SUM_STR_MAX, "Total number of bytes for Return Results: %.0f", tot_rr_size);
add_string_to_box(string_buff, rr_box);
/* Average size of return results */
if (tot_rr)
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Return Result: %.2f", tot_rr_size/tot_rr);
else
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Return Result: N/A");
add_string_to_box(string_buff, rr_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
/* Average size of return results per second */
if (seconds)
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: %.2f", tot_rr_size/seconds);
else
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: N/A");
add_string_to_box(string_buff, rr_box);
}
/* Totals frame */
tot_fr = gtk_frame_new("Totals");
gtk_box_pack_start(GTK_BOX (main_vb), tot_fr, TRUE, TRUE, 0);
gtk_widget_show(tot_fr);
tot_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE);
gtk_container_add(GTK_CONTAINER(tot_fr), tot_box);
gtk_widget_show(tot_box);
/* Total number of return results */
g_snprintf(string_buff, SUM_STR_MAX, "Total number of GSM MAP messages: %u", tot_invokes + tot_rr);
add_string_to_box(string_buff, tot_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
if (seconds)
g_snprintf(string_buff, SUM_STR_MAX, "Total number of GSM MAP messages per second: %.2f",
(tot_invokes + tot_rr)/seconds);
else
g_snprintf(string_buff, SUM_STR_MAX, "Total number of GSM MAP messages per second: N/A");
add_string_to_box(string_buff, tot_box);
}
g_snprintf(string_buff, SUM_STR_MAX, "Total number of bytes for GSM MAP messages: %.0f", tot_invokes_size + tot_rr_size);
add_string_to_box(string_buff, tot_box);
if (tot_invokes + tot_rr)
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per GSM MAP messages: %.2f",
(tot_invokes_size + tot_rr_size)/(tot_invokes + tot_rr));
else
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per GSM MAP messages: N/A");
add_string_to_box(string_buff, tot_box);
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count_ts >= 2) {
if (seconds)
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes second: %.2f",
(tot_invokes_size + tot_rr_size)/seconds);
else
g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes second: N/A");
add_string_to_box(string_buff, tot_box);
}
/* Button row. */
bbox = dlg_button_row_new(GTK_STOCK_CLOSE, NULL);
gtk_box_pack_start(GTK_BOX(main_vb), bbox, TRUE, TRUE, 0);
gtk_widget_show(bbox);
close_bt = (GtkWidget *)g_object_get_data(G_OBJECT(bbox), GTK_STOCK_CLOSE);
window_set_cancel_button(sum_open_w, close_bt, window_cancel_button_cb);
g_signal_connect(sum_open_w, "delete_event", G_CALLBACK(window_delete_event_cb), NULL);
gtk_widget_show(sum_open_w);
window_present(sum_open_w);
}
void
register_tap_listener_gtkgsm_map_summary(void)
{
}
| Java |
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <asm/setup.h>
#include <linux/pagemap.h>
struct st_read_proc {
char *name;
int (*read_proc)(char *, char **, off_t, int, int *, void *);
};
extern unsigned int get_pd_charge_flag(void);
extern unsigned int get_boot_into_recovery_flag(void);
extern unsigned int resetmode_is_normal(void);
extern unsigned int get_boot_into_recovery_flag(void);
/* same as in proc_misc.c */
static int proc_calc_metrics(char *page, char **start, off_t off,
int count, int *eof, int len)
{
if (len <= off + count)
*eof = 1;
*start = page + off;
len -= off;
if (len > count)
len = count;
if (len < 0)
len = 0;
return len;
}
static int app_tag_read_proc(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
int len = 0;
u32 charge_flag = 0;
u32 recovery_flag = 0;
u32 reset_normal_flag = 0;
recovery_flag = get_boot_into_recovery_flag();
charge_flag = get_pd_charge_flag();
reset_normal_flag = resetmode_is_normal();
len = snprintf(page, PAGE_SIZE,
"recovery_flag:\n%d\n"
"charge_flag:\n%d\n"
"reset_normal_flag:\n%d\n",
recovery_flag,
charge_flag,
reset_normal_flag);
return proc_calc_metrics(page, start, off, count, eof, len);
}
static struct st_read_proc simple_ones[] = {
{"app_info", app_tag_read_proc},
{NULL,}
};
void __init proc_app_info_init(void)
{
struct st_read_proc *p;
for (p = simple_ones; p->name; p++)
create_proc_read_entry(p->name, 0, NULL, p->read_proc, NULL);
}
| Java |
obj-y := version_balong.o
obj-y += sysfs_version.o
| Java |
Template.reassign_modal.helpers({
fields: function() {
var userOptions = null;
var showOrg = true;
var instance = WorkflowManager.getInstance();
var space = db.spaces.findOne(instance.space);
var flow = db.flows.findOne({
'_id': instance.flow
});
var curSpaceUser = db.space_users.findOne({
space: instance.space,
'user': Meteor.userId()
});
var organizations = db.organizations.find({
_id: {
$in: curSpaceUser.organizations
}
}).fetch();
if (space.admins.contains(Meteor.userId())) {
} else if (WorkflowManager.canAdmin(flow, curSpaceUser, organizations)) {
var currentStep = InstanceManager.getCurrentStep()
userOptions = ApproveManager.getNextStepUsers(instance, currentStep._id).getProperty("id").join(",")
showOrg = Session.get("next_step_users_showOrg")
} else {
userOptions = "0"
showOrg = false
}
var multi = false;
var c = InstanceManager.getCurrentStep();
if (c && c.step_type == "counterSign") {
multi = true;
}
return new SimpleSchema({
reassign_users: {
autoform: {
type: "selectuser",
userOptions: userOptions,
showOrg: showOrg,
multiple: multi
},
optional: true,
type: String,
label: TAPi18n.__("instance_reassign_user")
}
});
},
values: function() {
return {};
},
current_step_name: function() {
var s = InstanceManager.getCurrentStep();
var name;
if (s) {
name = s.name;
}
return name || '';
}
})
Template.reassign_modal.events({
'show.bs.modal #reassign_modal': function(event) {
var reassign_users = $("input[name='reassign_users']")[0];
reassign_users.value = "";
reassign_users.dataset.values = '';
$(reassign_users).change();
},
'click #reassign_help': function(event, template) {
Steedos.openWindow(t("reassign_help"));
},
'click #reassign_modal_ok': function(event, template) {
var val = AutoForm.getFieldValue("reassign_users", "reassign");
if (!val) {
toastr.error(TAPi18n.__("instance_reassign_error_users_required"));
return;
}
var reason = $("#reassign_modal_text").val();
var user_ids = val.split(",");
InstanceManager.reassignIns(user_ids, reason);
Modal.hide(template);
},
}) | Java |
<html lang="en">
<head>
<title>Meta Options - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Meta_002dDependent.html#Meta_002dDependent" title="Meta-Dependent">
<link rel="next" href="Meta-Syntax.html#Meta-Syntax" title="Meta Syntax">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2013 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="Meta-Options"></a>
Next: <a rel="next" accesskey="n" href="Meta-Syntax.html#Meta-Syntax">Meta Syntax</a>,
Up: <a rel="up" accesskey="u" href="Meta_002dDependent.html#Meta_002dDependent">Meta-Dependent</a>
<hr>
</div>
<h4 class="subsection">9.25.1 Options</h4>
<p><a name="index-options-for-Meta-1361"></a><a name="index-Meta-options-1362"></a><a name="index-architectures_002c-Meta-1363"></a><a name="index-Meta-architectures-1364"></a>
The Imagination Technologies Meta architecture is implemented in a
number of versions, with each new version adding new features such as
instructions and registers. For precise details of what instructions
each core supports, please see the chip's technical reference manual.
<p>The following table lists all available Meta options.
<!-- man begin OPTIONS -->
<dl>
<dt><code>-mcpu=metac11</code><dd>Generate code for Meta 1.1.
<br><dt><code>-mcpu=metac12</code><dd>Generate code for Meta 1.2.
<br><dt><code>-mcpu=metac21</code><dd>Generate code for Meta 2.1.
<br><dt><code>-mfpu=metac21</code><dd>Allow code to use FPU hardware of Meta 2.1.
</dl>
<!-- man end -->
</body></html>
| Java |
#ifndef _PLOT_H_
#define _PLOT_H_ 1
#include <qwt_plot.h>
class RectItem;
class QwtInterval;
class Plot: public QwtPlot
{
Q_OBJECT
public:
Plot( QWidget *parent, const QwtInterval & );
virtual void updateLayout();
void setRectOfInterest( const QRectF & );
Q_SIGNALS:
void resized( double xRatio, double yRatio );
private:
RectItem *d_rectOfInterest;
};
#endif
| Java |
#pragma checksum "C:\Users\INDIA\Desktop\SpeechKit-WP7-1.4.0\SampleVoiceApp\hotel.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "06F22895AB29E6AF87DE067810A1DD2E"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.269
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace SampleVoiceApp {
public partial class hotel : Microsoft.Phone.Controls.PhoneApplicationPage {
internal System.Windows.Controls.Grid LayoutRoot;
internal System.Windows.Controls.TextBlock textBlock1;
internal System.Windows.Controls.TextBlock textBlock2;
internal System.Windows.Controls.TextBlock textBlock3;
internal System.Windows.Controls.TextBlock textBlock4;
internal System.Windows.Controls.TextBlock textBlock5;
internal System.Windows.Controls.TextBlock textBlock6;
internal System.Windows.Controls.TextBlock textBlock7;
internal System.Windows.Controls.TextBlock textBlock8;
internal System.Windows.Controls.TextBlock textBlock9;
internal System.Windows.Controls.TextBlock textBlock11;
internal System.Windows.Controls.TextBlock textBlock12;
internal System.Windows.Controls.TextBlock textBlock13;
internal System.Windows.Controls.TextBlock textBlock14;
internal System.Windows.Controls.TextBlock textBlock15;
internal System.Windows.Controls.TextBlock textBlock16;
internal System.Windows.Controls.TextBlock textBlock17;
internal System.Windows.Controls.TextBlock textBlock18;
internal System.Windows.Controls.TextBlock textBlock19;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/SampleVoiceApp;component/hotel.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
this.textBlock1 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock1")));
this.textBlock2 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock2")));
this.textBlock3 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock3")));
this.textBlock4 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock4")));
this.textBlock5 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock5")));
this.textBlock6 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock6")));
this.textBlock7 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock7")));
this.textBlock8 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock8")));
this.textBlock9 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock9")));
this.textBlock11 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock11")));
this.textBlock12 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock12")));
this.textBlock13 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock13")));
this.textBlock14 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock14")));
this.textBlock15 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock15")));
this.textBlock16 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock16")));
this.textBlock17 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock17")));
this.textBlock18 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock18")));
this.textBlock19 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock19")));
}
}
}
| Java |
<?php
namespace Kbize\Sdk\Response;
class ProjectAndBoards
{
/**
*
* {
* "projects":[
* {"name":"Project","id":"1","boards":[
* {"name":"Service\/Merchant Integrations","id":"4"},
* {"name":"Tech Operations","id":"3"},
* {"name":"Main development","id":"2"}
* ]}
* ]
* }
*/
public static function fromArrayResponse(array $response)
{
return new self($response['projects']);
}
private function __construct(array $data)
{
$this->data = $data;
}
public function projects()
{
$projects = [];
foreach($this->data as $project) {
$projects[] = [
'name' => $project['name'],
'id' => $project['id'],
];
}
return $projects;
}
public function boards($projectId)
{
$projects = [];
foreach($this->data as $project) {
if ($project['id'] == $projectId) {
return $project['boards'];
}
}
throw new \Exception("Project: `$projectId` does not exists"); //TODO:! custom exception
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.sql;
public class SQLTransactionRollbackException extends SQLTransientException {
private static final long serialVersionUID = 5246680841170837229L;
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to null, the SQLState string is set to null and the Error Code is set
* to 0.
*/
public SQLTransactionRollbackException() {
super();
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to null and
* the Error Code is set to 0.
*
* @param reason
* the string to use as the Reason string
*/
public SQLTransactionRollbackException(String reason) {
super(reason, null, 0);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the Error Code is set to 0.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
*/
public SQLTransactionRollbackException(String reason, String sqlState) {
super(reason, sqlState, 0);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the Error Code is set to the given error code value.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param vendorCode
* the integer value for the error code
*/
public SQLTransactionRollbackException(String reason, String sqlState,
int vendorCode) {
super(reason, sqlState, vendorCode);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the null if cause == null or cause.toString() if cause!=null,and
* the cause Throwable object is set to the given cause Throwable object.
*
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(Throwable cause) {
super(cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given and the cause Throwable object is set to the given cause
* Throwable object.
*
* @param reason
* the string to use as the Reason string
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, Throwable cause) {
super(reason, cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the cause Throwable object is set to the given cause
* Throwable object.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, String sqlState,
Throwable cause) {
super(reason, sqlState, cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string , the Error Code is set to the given error code value,
* and the cause Throwable object is set to the given cause Throwable
* object.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param vendorCode
* the integer value for the error code
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, String sqlState,
int vendorCode, Throwable cause) {
super(reason, sqlState, vendorCode, cause);
}
} | Java |
#!/usr/bin/env python
#
# 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. See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.
# query.py: Perform a few varieties of queries
from __future__ import print_function
import time
import bugzilla
# public test instance of bugzilla.redhat.com. It's okay to make changes
URL = "partner-bugzilla.redhat.com"
bzapi = bugzilla.Bugzilla(URL)
# build_query is a helper function that handles some bugzilla version
# incompatibility issues. All it does is return a properly formatted
# dict(), and provide friendly parameter names. The param names map
# to those accepted by XMLRPC Bug.search:
# https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#search-bugs
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla")
# Since 'query' is just a dict, you could set your own parameters too, like
# if your bugzilla had a custom field. This will set 'status' for example,
# but for common opts it's better to use build_query
query["status"] = "CLOSED"
# query() is what actually performs the query. it's a wrapper around Bug.search
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Found %d bugs with our query" % len(bugs))
print("Query processing time: %s" % (t2 - t1))
# Depending on the size of your query, you can massively speed things up
# by telling bugzilla to only return the fields you care about, since a
# large chunk of the return time is transmitting the extra bug data. You
# tweak this with include_fields:
# https://wiki.mozilla.org/Bugzilla:BzAPI#Field_Control
# Bugzilla will only return those fields listed in include_fields.
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla",
include_fields=["id", "summary"])
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Quicker query processing time: %s" % (t2 - t1))
# bugzilla.redhat.com, and bugzilla >= 5.0 support queries using the same
# format as is used for 'advanced' search URLs via the Web UI. For example,
# I go to partner-bugzilla.redhat.com -> Search -> Advanced Search, select
# Classification=Fedora
# Product=Fedora
# Component=python-bugzilla
# Unselect all bug statuses (so, all status values)
# Under Custom Search
# Creation date -- is less than or equal to -- 2010-01-01
#
# Run that, copy the URL and bring it here, pass it to url_to_query to
# convert it to a dict(), and query as usual
query = bzapi.url_to_query("https://partner-bugzilla.redhat.com/"
"buglist.cgi?classification=Fedora&component=python-bugzilla&"
"f1=creation_ts&o1=lessthaneq&order=Importance&product=Fedora&"
"query_format=advanced&v1=2010-01-01")
query["include_fields"] = ["id", "summary"]
bugs = bzapi.query(query)
print("The URL query returned 22 bugs... "
"I know that without even checking because it shouldn't change!... "
"(count is %d)" % len(bugs))
# One note about querying... you can get subtley different results if
# you are not logged in. Depending on your bugzilla setup it may not matter,
# but if you are dealing with private bugs, check bzapi.logged_in setting
# to ensure your cached credentials are up to date. See update.py for
# an example usage
| Java |
/* Initialize
*/
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
jQuery(document).ready(function ($) {
// Bootstrap Init
$("[rel=tooltip]").tooltip();
$('[data-toggle=tooltip]').tooltip();
$("[rel=popover]").popover();
$('#authorTab a').click(function (e) {e.preventDefault(); $(this).tab('show'); });
$('.sc_tabs a').click(function (e) {e.preventDefault(); $(this).tab('show'); });
$(".videofit").fitVids();
$(".embed-youtube").fitVids();
$('.kad-select').customSelect();
$('.woocommerce-ordering select').customSelect();
$('.collapse-next').click(function (e) {
//e.preventDefault();
var $target = $(this).siblings('.sf-dropdown-menu');
if($target.hasClass('in') ) {
$target.collapse('toggle');
$(this).removeClass('toggle-active');
} else {
$target.collapse('toggle');
$(this).addClass('toggle-active');
}
});
// Lightbox
function kt_check_images( index, element ) {
return /(png|jpg|jpeg|gif|tiff|bmp)$/.test(
$( element ).attr( 'href' ).toLowerCase().split( '?' )[0].split( '#' )[0]
);
}
function kt_find_images() {
$( 'a[href]' ).filter( kt_check_images ).attr( 'data-rel', 'lightbox' );
}
kt_find_images();
$.extend(true, $.magnificPopup.defaults, {
tClose: '',
tLoading: light_load, // Text that is displayed during loading. Can contain %curr% and %total% keys
gallery: {
tPrev: '', // Alt text on left arrow
tNext: '', // Alt text on right arrow
tCounter: light_of // Markup for "1 of 7" counter
},
image: {
tError: light_error, // Error message when image could not be loaded
titleSrc: function(item) {
return item.el.find('img').attr('alt');
}
}
});
$("a[rel^='lightbox']").magnificPopup({type:'image'});
$("a[data-rel^='lightbox']").magnificPopup({type:'image'});
$('.kad-light-gallery').each(function(){
$(this).find('a[rel^="lightbox"]').magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: 'title'
}
});
});
$('.kad-light-gallery').each(function(){
$(this).find("a[data-rel^='lightbox']").magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: 'title'
}
});
});
$('.kad-light-wp-gallery').each(function(){
$(this).find('a[rel^="lightbox"]').magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: function(item) {
return item.el.find('img').attr('alt');
}
}
});
});
$('.kad-light-wp-gallery').each(function(){
$(this).find("a[data-rel^='lightbox']").magnificPopup({
type: 'image',
gallery: {
enabled:true
},
image: {
titleSrc: function(item) {
return item.el.find('img').attr('alt');
}
}
});
});
//Superfish Menu
$('ul.sf-menu').superfish({
delay: 200, // one second delay on mouseout
animation: {opacity:'show',height:'show'}, // fade-in and slide-down animation
speed: 'fast' // faster animation speed
});
function kad_fullwidth_panel() {
var margins = $(window).width() - $('#content').width();
$('.panel-row-style-wide-feature').each(function(){
$(this).css({'padding-left': margins/2 + 'px'});
$(this).css({'padding-right': margins/2 + 'px'});
$(this).css({'margin-left': '-' + margins/2 + 'px'});
$(this).css({'margin-right': '-' + margins/2 + 'px'});
$(this).css({'visibility': 'visible'});
});
}
kad_fullwidth_panel();
$(window).on("debouncedresize", function( event ) {kad_fullwidth_panel();});
//init Flexslider
$('.kt-flexslider').each(function(){
var flex_speed = $(this).data('flex-speed'),
flex_animation = $(this).data('flex-animation'),
flex_animation_speed = $(this).data('flex-anim-speed'),
flex_auto = $(this).data('flex-auto');
$(this).flexslider({
animation:flex_animation,
animationSpeed: flex_animation_speed,
slideshow: flex_auto,
slideshowSpeed: flex_speed,
start: function ( slider ) {
slider.removeClass( 'loading' );
}
});
});
//init masonry
$('.init-masonry').each(function(){
var masonrycontainer = $(this),
masonry_selector = $(this).data('masonry-selector');
masonrycontainer.imagesLoadedn( function(){
masonrycontainer.masonry({itemSelector: masonry_selector});
});
});
//init carousel
jQuery('.initcaroufedsel').each(function(){
var container = jQuery(this);
var wcontainerclass = container.data('carousel-container'),
cspeed = container.data('carousel-speed'),
ctransition = container.data('carousel-transition'),
cauto = container.data('carousel-auto'),
carouselid = container.data('carousel-id'),
ss = container.data('carousel-ss'),
xs = container.data('carousel-xs'),
sm = container.data('carousel-sm'),
md = container.data('carousel-md');
var wcontainer = jQuery(wcontainerclass);
function getUnitWidth() {var width;
if(jQuery(window).width() <= 540) {
width = wcontainer.width() / ss;
} else if(jQuery(window).width() <= 768) {
width = wcontainer.width() / xs;
} else if(jQuery(window).width() <= 990) {
width = wcontainer.width() / sm;
} else {
width = wcontainer.width() / md;
}
return width;
}
function setWidths() {
var unitWidth = getUnitWidth() -1;
container.children().css({ width: unitWidth });
}
setWidths();
function initCarousel() {
container.carouFredSel({
scroll: {items:1, easing: "swing", duration: ctransition, pauseOnHover : true},
auto: {play: cauto, timeoutDuration: cspeed},
prev: '#prevport-'+carouselid, next: '#nextport-'+carouselid, pagination: false, swipe: true, items: {visible: null}
});
}
container.imagesLoadedn( function(){
initCarousel();
});
wcontainer.animate({'opacity' : 1});
jQuery(window).on("debouncedresize", function( event ) {
container.trigger("destroy");
setWidths();
initCarousel();
});
});
//init carouselslider
jQuery('.initcarouselslider').each(function(){
var container = jQuery(this);
var wcontainerclass = container.data('carousel-container'),
cspeed = container.data('carousel-speed'),
ctransition = container.data('carousel-transition'),
cauto = container.data('carousel-auto'),
carouselid = container.data('carousel-id'),
carheight = container.data('carousel-height'),
align = 'center';
var wcontainer = jQuery(wcontainerclass);
function setWidths() {
var unitWidth = container.width();
container.children().css({ width: unitWidth });
if(jQuery(window).width() <= 768) {
carheight = null;
container.children().css({ height: 'auto' });
}
}
setWidths();
function initCarouselslider() {
container.carouFredSel({
width: '100%',
height: carheight,
align: align,
auto: {play: cauto, timeoutDuration: cspeed},
scroll: {items : 1,easing: 'quadratic'},
items: {visible: 1,width: 'variable'},
prev: '#prevport-'+carouselid,
next: '#nextport-'+carouselid,
swipe: {onMouse: false,onTouch: true},
});
}
container.imagesLoadedn( function(){
initCarouselslider();
wcontainer.animate({'opacity' : 1});
wcontainer.css({ height: 'auto' });
wcontainer.parent().removeClass('loading');
});
jQuery(window).on("debouncedresize", function( event ) {
container.trigger("destroy");
setWidths();
initCarouselslider();
});
});
});
if( isMobile.any() ) {
jQuery(document).ready(function ($) {
$('.caroufedselclass').tswipe({
excludedElements:"button, input, select, textarea, .noSwipe",
tswipeLeft: function() {
$('.caroufedselclass').trigger('next', 1);
},
tswipeRight: function() {
$('.caroufedselclass').trigger('prev', 1);
},
tap: function(event, target) {
window.open(jQuery(target).closest('.grid_item').find('a').attr('href'), '_self');
}
});
});
}
| Java |
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<meta charset="US-ASCII">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>ASN.1 JavaScript decoder</title>
<link rel="stylesheet" href="ASN.1%20JavaScript%20decoder_files/index.css" type="text/css">
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/hex.js"></script>
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/base64.js"></script>
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/oids.js"></script>
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/int10.js"></script>
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/asn1.js"></script>
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/dom.js"></script>
<script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/index.js"></script>
</head>
<body>
<h1>ASN.1 JavaScript decoder</h1>
<div style="position: relative; padding-bottom: 1em;">
<div id="dump" style="position: absolute; right: 0px;"></div>
<div id="tree"></div>
</div>
<form>
<textarea id="pem" style="width: 100%;" rows="8">MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIAwggHvMIIB
WKADAgECAhAvoXazbunwSfREtACZZhlFMA0GCSqGSIb3DQEBBQUAMAwxCjAIBgNVBAMMAWEwHhcN
MDgxMDE1MTUwMzQxWhcNMDkxMDE1MTUwMzQxWjAMMQowCAYDVQQDDAFhMIGfMA0GCSqGSIb3DQEB
AQUAA4GNADCBiQKBgQCJUwlwhu5hR8X01f+vG0mKPRHsVRjpZNxSEmsmFPdDiD9kylE3ertTDf0g
RkpIvWfNJ+eymuxoXF0Qgl5gXAVuSrjupGD6J+VapixJiwLXJHokmDihLs3zfGARz08O3qnO5ofB
y0pRxq5isu/bAAcjoByZ1sI/g0iAuotC1UFObwIDAQABo1IwUDAOBgNVHQ8BAf8EBAMCBPAwHQYD
VR0OBBYEFEIGXQB4h+04Z3y/n7Nv94+CqPitMB8GA1UdIwQYMBaAFEIGXQB4h+04Z3y/n7Nv94+C
qPitMA0GCSqGSIb3DQEBBQUAA4GBAE0G7tAiaacJxvP3fhEj+yP9VDxL0omrRRAEaMXwWaBf/Ggk
1T/u+8/CDAdjuGNCiF6ctooKc8u8KpnZJsGqnpGQ4n6L2KjTtRUDh+hija0eJRBFdirPQe2HAebQ
GFnmOk6Mn7KiQfBIsOzXim/bFqaBSbf06bLTQNwFouSO+jwOAAAxggElMIIBIQIBATAgMAwxCjAI
BgNVBAMMAWECEC+hdrNu6fBJ9ES0AJlmGUUwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkq
hkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTA4MTAxNTE1MDM0M1owIwYJKoZIhvcNAQkEMRYEFAAA
AAAAAAAAAAAAAAAAAAAAAAAAMA0GCSqGSIb3DQEBAQUABIGAdB7ShyMGf5lVdZtvwKlnYLHMUqJW
uBnFk7aQwHAmg3JnH6OcgId2F+xfg6twXm8hhUBkhHPlHGoWa5kQtN9n8rz3NorzvcM/1Xv9+0Ea
l7NYSn2Hb0C0DMj2XNIYH2C6CLIHkmy1egzUvzsomZPTkx5nGDWm+8WHCjWb9A6lyrMAAAAAAAA=
</textarea>
<br>
<label title="can be slow with big files"><input id="wantHex" checked="checked" type="checkbox"> with hex dump</label>
<input value="decode" onclick="decodeArea();" type="button">
<input value="clear" onclick="clearAll();" type="button">
<input style="display: block;" id="file" type="file">
</form>
<div id="help">
<h2>Instructions</h2>
<p>This page contains a JavaScript generic ASN.1 parser that can
decode any valid ASN.1 DER or BER structure whether Base64-encoded (raw
base64, PEM armoring and <span class="tt">begin-base64</span> are recognized) or Hex-encoded. </p>
<p>This tool can be used online at the address <a href="http://lapo.it/asn1js/"><span class="tt">http://lapo.it/asn1js/</span></a> or offline, unpacking <a href="http://lapo.it/asn1js/asn1js.zip">the ZIP file</a> in a directory and opening <span class="tt">index.html</span> in a browser</p>
<p>On the left of the page will be printed a tree representing the
hierarchical structure, on the right side an hex dump will be shown. <br>
Hovering on the tree highlights ancestry (the hovered node and all
its ancestors get colored) and the position of the hovered node gets
highlighted in the hex dump (with header and content in a different
colors). <br>
Clicking a node in the tree will hide its sub-nodes (collapsed nodes can be noticed because they will become <i>italic</i>).</p>
<div class="license">
<h3>Copyright</h3>
<div class="ref"><p class="hidden">
ASN.1 JavaScript decoder<br>
Copyright © 2008-2014 Lapo Luchini <[email protected]><br>
<br>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.<br>
<br>
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</p></div>
<p>ASN.1 JavaScript decoder Copyright © 2008-2014 <a href="http://lapo.it/">Lapo Luchini</a>; released as <a href="http://opensource.org/licenses/isc-license.txt">opensource</a> under the <a href="http://en.wikipedia.org/wiki/ISC_licence">ISC license</a>.</p>
</div>
<p><span class="tt">OBJECT IDENTIFIER</span> values are recognized using data taken from Peter Gutmann's <a href="http://www.cs.auckland.ac.nz/%7Epgut001/#standards">dumpasn1</a> program.</p>
<h3>Links</h3>
<ul>
<li><a href="http://lapo.it/asn1js/">official website</a></li>
<li><a href="http://idf.lapo.it/p/asn1js/">InDefero tracker</a></li>
<li><a href="https://github.com/lapo-luchini/asn1js">github mirror</a></li>
<li><a href="https://www.ohloh.net/p/asn1js">Ohloh code stats</a></li>
</ul>
</div>
</body></html> | Java |
<?php
/**
* sh404SEF - SEO extension for Joomla!
*
* @author Yannick Gaultier
* @copyright (c) Yannick Gaultier 2014
* @package sh404SEF
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @version 4.4.0.1725
* @date 2014-04-09
*/
// Security check to ensure this file is being included by a parent file.
if (!defined('_JEXEC')) die('Direct Access to this location is not allowed.');
$title = JText::_('COM_SH404SEF_ANALYTICS_REPORT_SOURCES') . '::' . JText::_('COM_SH404SEF_ANALYTICS_DATA_SOURCES_DESC_RAW');
?>
<div class="hasAnalyticsTip width-100" title="<?php echo $title; ?>">
<fieldset class="adminform">
<legend>
<?php echo JText::_('COM_SH404SEF_ANALYTICS_REPORT_SOURCES') . JText::_( 'COM_SH404SEF_ANALYTICS_REPORT_BY_LABEL') . Sh404sefHelperAnalytics::getDataTypeTitle(); ?>
</legend>
<ul class="adminformlist">
<li>
<div class="analytics-report-image"><img src="<?php echo $this->analytics->analyticsData->images['sources']; ?>" /></div>
</li>
</ul>
</fieldset>
</div> | Java |
using System.IO;
using Nequeo.Cryptography.Key.Utilities.IO;
namespace Nequeo.Cryptography.Key.Asn1
{
public class BerGenerator
: Asn1Generator
{
private bool _tagged = false;
private bool _isExplicit;
private int _tagNo;
protected BerGenerator(
Stream outStream)
: base(outStream)
{
}
public BerGenerator(
Stream outStream,
int tagNo,
bool isExplicit)
: base(outStream)
{
_tagged = true;
_isExplicit = isExplicit;
_tagNo = tagNo;
}
public override void AddObject(
Asn1Encodable obj)
{
new BerOutputStream(Out).WriteObject(obj);
}
public override Stream GetRawOutputStream()
{
return Out;
}
public override void Close()
{
WriteBerEnd();
}
private void WriteHdr(
int tag)
{
Out.WriteByte((byte) tag);
Out.WriteByte(0x80);
}
protected void WriteBerHeader(
int tag)
{
if (_tagged)
{
int tagNum = _tagNo | Asn1Tags.Tagged;
if (_isExplicit)
{
WriteHdr(tagNum | Asn1Tags.Constructed);
WriteHdr(tag);
}
else
{
if ((tag & Asn1Tags.Constructed) != 0)
{
WriteHdr(tagNum | Asn1Tags.Constructed);
}
else
{
WriteHdr(tagNum);
}
}
}
else
{
WriteHdr(tag);
}
}
protected void WriteBerBody(
Stream contentStream)
{
Streams.PipeAll(contentStream, Out);
}
protected void WriteBerEnd()
{
Out.WriteByte(0x00);
Out.WriteByte(0x00);
if (_tagged && _isExplicit) // write extra end for tag header
{
Out.WriteByte(0x00);
Out.WriteByte(0x00);
}
}
}
}
| Java |
/* GStreamer
* Copyright (C) <2009> Руслан Ижбулатов <lrn1986 _at_ gmail _dot_ com>
*
* This 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.
*
* 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
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst-i18n-plugin.h>
#include "gstvideomeasure.h"
#include "gstvideomeasure_ssim.h"
#include "gstvideomeasure_collector.h"
GstEvent *
gst_event_new_measured (guint64 framenumber, GstClockTime timestamp,
const gchar * metric, const GValue * mean, const GValue * lowest,
const GValue * highest)
{
GstStructure *str = gst_structure_new (GST_EVENT_VIDEO_MEASURE,
"event", G_TYPE_STRING, "frame-measured",
"offset", G_TYPE_UINT64, framenumber,
"timestamp", GST_TYPE_CLOCK_TIME, timestamp,
"metric", G_TYPE_STRING, metric,
NULL);
gst_structure_set_value (str, "mean", mean);
gst_structure_set_value (str, "lowest", lowest);
gst_structure_set_value (str, "highest", highest);
return gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, str);
}
static gboolean
plugin_init (GstPlugin * plugin)
{
gboolean res;
#ifdef ENABLE_NLS
GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
LOCALEDIR);
bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif
res = gst_element_register (plugin, "ssim", GST_RANK_NONE, GST_TYPE_SSIM);
res &= gst_element_register (plugin, "measurecollector", GST_RANK_NONE,
GST_TYPE_MEASURE_COLLECTOR);
return res;
}
GST_PLUGIN_DEFINE2 (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
videomeasure,
"Various video measurers",
plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
| Java |
<div class="wrap shopp">
<div class="icon32"></div>
<?php
shopp_admin_screen_tabs();
do_action('shopp_admin_notices');
?>
<?php if (count(shopp_setting('target_markets')) == 0) echo '<div class="error"><p>'.__('No target markets have been selected in your store setup.','Shopp').'</p></div>'; ?>
<?php $this->taxes_menu(); ?>
<form action="<?php echo esc_url($this->url); ?>" id="taxrates" method="post" enctype="multipart/form-data" accept="text/plain,text/xml">
<div>
<?php wp_nonce_field('shopp-settings-taxrates'); ?>
</div>
<div class="tablenav">
<div class="actions">
<button type="submit" name="addrate" id="addrate" class="button-secondary" tabindex="9999" <?php if (empty($countries)) echo 'disabled="disabled"'; ?>><?php _e('Add Tax Rate','Shopp'); ?></button>
</div>
</div>
<script id="property-menu" type="text/x-jquery-tmpl"><?php
$propertymenu = array(
'product-name' => __('Product name is','Shopp'),
'product-tags' => __('Product is tagged','Shopp'),
'product-category' => __('Product in category','Shopp'),
'customer-type' => __('Customer type is','Shopp')
);
echo Shopp::menuoptions($propertymenu,false,true);
?></script>
<script id="countries-menu" type="text/x-jquery-tmpl"><?php
echo Shopp::menuoptions($countries,false,true);
?></script>
<script id="conditional" type="text/x-jquery-tmpl">
<?php ob_start(); ?>
<li>
<?php echo ShoppUI::button('delete','deleterule'); ?>
<select name="settings[taxrates][${id}][rules][${ruleid}][p]" class="property">${property_menu}</select> <input type="text" name="settings[taxrates][${id}][rules][${ruleid}][v]" size="25" class="value" value="${rulevalue}" />
<?php echo ShoppUI::button('add','addrule'); ?></li>
<?php $conditional = ob_get_contents(); ob_end_clean(); echo str_replace(array("\n","\t"),'',$conditional); ?>
</script>
<script id="localrate" type="text/x-jquery-tmpl">
<?php ob_start(); ?>
<li><label title="${localename}"><input type="text" name="settings[taxrates][${id}][locals][${localename}]" size="6" value="${localerate}" /> ${localename}</label></li>
<?php $localrateui = ob_get_contents(); ob_end_clean(); echo $localrateui; ?>
</script>
<script id="editor" type="text/x-jquery-tmpl">
<?php ob_start(); ?>
<tr class="inline-edit-row ${classnames}" id="${id}">
<td colspan="5"><input type="hidden" name="id" value="${id}" /><input type="hidden" name="editing" value="true" />
<table id="taxrate-editor">
<tr>
<td scope="row" valign="top" class="rate"><input type="text" name="settings[taxrates][${id}][rate]" id="tax-rate" value="${rate}" size="7" class="selectall" tabindex="1" /><br /><label for="tax-rate"><?php _e('Tax Rate','Shopp'); ?></label><br />
<input type="hidden" name="settings[taxrates][${id}][compound]" value="off" /><label><input type="checkbox" id="tax-compound" name="settings[taxrates][${id}][compound]" value="on" ${compounded} tabindex="4" /> <?php Shopp::_e('Compound'); ?></label></td>
<td scope="row" class="conditions">
<select name="settings[taxrates][${id}][country]" class="country" tabindex="2">${countries}</select><select name="settings[taxrates][${id}][zone]" class="zone no-zones" tabindex="3">${zones}</select>
<?php echo ShoppUI::button('add','addrule'); ?>
<?php
$options = array('any' => Shopp::__('any'), 'all' => strtolower(Shopp::__('All')));
$menu = '<select name="settings[taxrates][${id}][logic]" class="logic">'.menuoptions($options,false,true).'</select>';
?>
<div class="conditionals no-conditions">
<p><label><?php printf(__('Apply tax rate when %s of the following conditions match','Shopp'),$menu); ?>:</label></p>
<ul>
${conditions}
</ul>
</div>
</td>
<td>
<div class="local-rates panel subpanel no-local-rates">
<div class="label"><label><?php _e('Local Rates','Shopp'); echo ShoppAdmin()->boxhelp('settings-taxes-localrates'); ?> <span class="counter"></span><input type="hidden" name="settings[taxrates][${id}][haslocals]" value="${haslocals}" class="has-locals" /></label></div>
<div class="ui">
<p class="instructions"><?php Shopp::_e('No local regions have been setup for this location. Local regions can be specified by uploading a formatted local rates file.'); ?></p>
${errors}
<ul>${localrates}</ul>
<div class="upload">
<h3><?php Shopp::_e('Upload Local Tax Rates'); ?></h3>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
<input type="file" name="ratefile" class="hide-if-js" />
<button type="submit" name="upload" class="button-secondary upload"><?php Shopp::_e('Upload'); ?></button>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<p class="textright">
<a href="<?php echo $this->url; ?>" class="button-secondary cancel alignleft"><?php Shopp::_e('Cancel'); ?></a>
<button type="submit" name="add-locals" class="button-secondary locals-toggle add-locals has-local-rates"><?php Shopp::_e('Add Local Rates'); ?></button>
<button type="submit" name="remove-locals" class="button-secondary locals-toggle rm-locals no-local-rates"><?php Shopp::_e('Remove Local Rates'); ?></button>
<input type="submit" class="button-primary" name="submit" value="<?php Shopp::_e('Save Changes'); ?>" />
</p>
</td>
</tr>
</table>
</td>
</tr>
<?php $editor = ob_get_contents(); ob_end_clean(); echo str_replace(array("\n","\t"),'',$editor); ?>
</script>
<table class="widefat" cellspacing="0">
<thead>
<tr><?php print_column_headers('shopp_page_shopp-settings-taxrates'); ?></tr>
</thead>
<tfoot>
<tr><?php print_column_headers('shopp_page_shopp-settings-taxrates',false); ?></tr>
</tfoot>
<tbody id="taxrates-table" class="list">
<?php
if ($edit !== false && !isset($rates[$edit])) {
$defaults = array(
'rate' => 0,
'country' => false,
'zone' => false,
'rules' => array(),
'locals' => array(),
'haslocals' => false,
'compound' => false
);
extract($defaults);
echo ShoppUI::template($editor,array(
'${id}' => $edit,
'${rate}' => percentage($rate,array('precision'=>4)),
'${countries}' => menuoptions($countries,$country,true),
'${zones}' => !empty($zones[$country])?menuoptions($zones[$country],$zone,true):'',
'${conditions}' => join('',$conditions),
'${haslocals}' => $haslocals,
'${localrates}' => join('',$localrates),
'${instructions}' => $localerror ? '<p class="error">'.$localerror.'</p>' : $instructions,
'${compounded}' => Shopp::str_true($compound) ? 'checked="checked"' : ''
));
}
if (count($rates) == 0 && $edit === false): ?>
<tr id="no-taxrates"><td colspan="5"><?php _e('No tax rates, yet.','Shopp'); ?></td></tr>
<?php
endif;
$hidden = get_hidden_columns('shopp_page_shopp-settings-taxrates');
$even = false;
foreach ($rates as $index => $taxrate):
$defaults = array(
'rate' => 0,
'country' => false,
'zone' => false,
'rules' => array(),
'locals' => array(),
'haslocals' => false
);
$taxrate = array_merge($defaults,$taxrate);
extract($taxrate);
$rate = Shopp::percentage(Shopp::floatval($rate), array('precision'=>4));
$location = $countries[ $country ];
if (isset($zone) && !empty($zone))
$location = $zones[$country][$zone].", $location";
$editurl = wp_nonce_url(add_query_arg(array('id'=>$index),$this->url));
$deleteurl = wp_nonce_url(add_query_arg(array('delete'=>$index),$this->url),'shopp_delete_taxrate');
$classes = array();
if (!$even) $classes[] = 'alternate'; $even = !$even;
if ($edit !== false && $edit === $index) {
$conditions = array();
foreach ($rules as $ruleid => $rule) {
$condition_template_data = array(
'${id}' => $edit,
'${ruleid}' => $ruleid,
'${property_menu}' => menuoptions($propertymenu,$rule['p'],true),
'${rulevalue}' => esc_attr($rule['v'])
);
$conditions[] = str_replace(array_keys($condition_template_data),$condition_template_data,$conditional);
}
$localrates = array();
foreach ($locals as $localename => $localerate) {
$localrateui_data = array(
'${id}' => $edit,
'${localename}' => $localename,
'${localerate}' => (float)$localerate,
);
$localrates[] = str_replace(array_keys($localrateui_data),$localrateui_data,$localrateui);
}
$data = array(
'${id}' => $edit,
'${rate}' => $rate,
'${countries}' => menuoptions($countries,$country,true),
'${zones}' => !empty($zones[$country])?menuoptions(array_merge(array(''=>''),$zones[$country]),$zone,true):'',
'${conditions}' => join('',$conditions),
'${haslocals}' => $haslocals,
'${localrates}' => join('',$localrates),
'${errors}' => $localerror ? '<p class="error">'.$localerror.'</p>' : '',
'${compounded}' => Shopp::str_true($compound) ? 'checked="checked"' : '',
'${cancel_href}' => $this->url
);
if ($conditions) $data['no-conditions'] = '';
if (!empty($zones[$country])) $data['no-zones'] = '';
if ($haslocals) $data['no-local-rates'] = '';
else $data['has-local-rates'] = '';
if (count($locals) > 0) $data['instructions'] = 'hidden';
echo ShoppUI::template($editor,$data);
if ($edit === $index) continue;
}
$label = "$rate — $location";
?>
<tr class="<?php echo join(' ',$classes); ?>" id="taxrates-<?php echo $index; ?>">
<td class="name column-name"><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> "<?php echo esc_attr($rate); ?>"" class="edit row-title"><?php echo esc_html($label); ?></a>
<div class="row-actions">
<span class='edit'><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> "<?php echo esc_attr($label); ?>"" class="edit"><?php _e('Edit','Shopp'); ?></a> | </span><span class='delete'><a href="<?php echo esc_url($deleteurl); ?>" title="<?php _e('Delete','Shopp'); ?> "<?php echo esc_attr($label); ?>"" class="delete"><?php _e('Delete','Shopp'); ?></a></span>
</div>
</td>
<td class="local column-local">
<div class="checkbox <?php if ( $haslocals ) echo 'checked'; ?>"> </div>
</td>
<td class="conditional column-conditional">
<div class="checkbox <?php if ( count($rules) > 0 ) echo 'checked'; ?>"> </div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
</div>
<script type="text/javascript">
/* <![CDATA[ */
var suggurl = '<?php echo wp_nonce_url(admin_url('admin-ajax.php'),'wp_ajax_shopp_suggestions'); ?>',
rates = <?php echo json_encode($rates); ?>,
base = <?php echo json_encode($base); ?>,
zones = <?php echo json_encode($zones); ?>,
localities = <?php echo json_encode(Lookup::localities()); ?>,
taxrates = [];
/* ]]> */
</script>
| Java |
/******************************************************************************/
/* Mednafen Fast SNES Emulation Module */
/******************************************************************************/
/* input.cpp:
** Copyright (C) 2015-2019 Mednafen Team
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "snes.h"
#include "input.h"
namespace MDFN_IEN_SNES_FAUST
{
class InputDevice
{
public:
InputDevice() MDFN_COLD;
virtual ~InputDevice() MDFN_COLD;
virtual void Power(void) MDFN_COLD;
virtual void MDFN_FASTCALL UpdatePhysicalState(const uint8* data);
virtual uint8 MDFN_FASTCALL Read(bool IOB) MDFN_HOT;
virtual void MDFN_FASTCALL SetLatch(bool state) MDFN_HOT;
virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix);
};
InputDevice::InputDevice()
{
}
InputDevice::~InputDevice()
{
}
void InputDevice::Power(void)
{
}
void InputDevice::UpdatePhysicalState(const uint8* data)
{
}
uint8 InputDevice::Read(bool IOB)
{
return 0;
}
void InputDevice::SetLatch(bool state)
{
}
void InputDevice::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix)
{
}
class InputDevice_MTap final : public InputDevice
{
public:
InputDevice_MTap() MDFN_COLD;
virtual ~InputDevice_MTap() override MDFN_COLD;
virtual void Power(void) override MDFN_COLD;
virtual uint8 MDFN_FASTCALL Read(bool IOB) override MDFN_HOT;
virtual void MDFN_FASTCALL SetLatch(bool state) override MDFN_HOT;
virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) override;
void SetSubDevice(const unsigned mport, InputDevice* device);
private:
InputDevice* MPorts[4];
bool pls;
};
void InputDevice_MTap::Power(void)
{
for(unsigned mport = 0; mport < 4; mport++)
MPorts[mport]->Power();
}
void InputDevice_MTap::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix)
{
SFORMAT StateRegs[] =
{
SFVAR(pls),
SFEND
};
char sname[64] = "MT_";
strncpy(sname + 3, sname_prefix, sizeof(sname) - 3);
sname[sizeof(sname) - 1] = 0;
if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, sname, true) && load)
Power();
else
{
for(unsigned mport = 0; mport < 4; mport++)
{
sname[2] = '0' + mport;
MPorts[mport]->StateAction(sm, load, data_only, sname);
}
if(load)
{
}
}
}
InputDevice_MTap::InputDevice_MTap()
{
for(unsigned mport = 0; mport < 4; mport++)
MPorts[mport] = nullptr;
pls = false;
}
InputDevice_MTap::~InputDevice_MTap()
{
}
uint8 InputDevice_MTap::Read(bool IOB)
{
uint8 ret;
ret = ((MPorts[(!IOB << 1) + 0]->Read(false) & 0x1) << 0) | ((MPorts[(!IOB << 1) + 1]->Read(false) & 0x1) << 1);
if(pls)
ret = 0x2;
return ret;
}
void InputDevice_MTap::SetLatch(bool state)
{
for(unsigned mport = 0; mport < 4; mport++)
MPorts[mport]->SetLatch(state);
pls = state;
}
void InputDevice_MTap::SetSubDevice(const unsigned mport, InputDevice* device)
{
MPorts[mport] = device;
}
class InputDevice_Gamepad final : public InputDevice
{
public:
InputDevice_Gamepad() MDFN_COLD;
virtual ~InputDevice_Gamepad() override MDFN_COLD;
virtual void Power(void) override MDFN_COLD;
virtual void MDFN_FASTCALL UpdatePhysicalState(const uint8* data) override;
virtual uint8 MDFN_FASTCALL Read(bool IOB) override MDFN_HOT;
virtual void MDFN_FASTCALL SetLatch(bool state) override MDFN_HOT;
virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) override;
private:
uint16 buttons;
uint32 latched;
bool pls;
};
InputDevice_Gamepad::InputDevice_Gamepad()
{
pls = false;
buttons = 0;
}
InputDevice_Gamepad::~InputDevice_Gamepad()
{
}
void InputDevice_Gamepad::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix)
{
SFORMAT StateRegs[] =
{
SFVAR(buttons),
SFVAR(latched),
SFVAR(pls),
SFEND
};
char sname[64] = "GP_";
strncpy(sname + 3, sname_prefix, sizeof(sname) - 3);
sname[sizeof(sname) - 1] = 0;
//printf("%s\n", sname);
if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, sname, true) && load)
Power();
else if(load)
{
}
}
void InputDevice_Gamepad::Power(void)
{
latched = ~0U;
}
void InputDevice_Gamepad::UpdatePhysicalState(const uint8* data)
{
buttons = MDFN_de16lsb(data);
if(pls)
latched = buttons | 0xFFFF0000;
}
uint8 InputDevice_Gamepad::Read(bool IOB)
{
uint8 ret = latched & 1;
if(!pls)
latched = (int32)latched >> 1;
return ret;
}
void InputDevice_Gamepad::SetLatch(bool state)
{
if(pls && !state)
latched = buttons | 0xFFFF0000;
pls = state;
}
//
//
//
//
//
static struct
{
InputDevice_Gamepad gamepad;
} PossibleDevices[8];
static InputDevice NoneDevice;
static InputDevice_MTap PossibleMTaps[2];
static bool MTapEnabled[2];
// Mednafen virtual
static InputDevice* Devices[8];
static uint8* DeviceData[8];
// SNES physical
static InputDevice* Ports[2];
static uint8 WRIO;
static bool JoyLS;
static uint8 JoyARData[8];
static DEFREAD(Read_JoyARData)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return JoyARData[A & 0x7];
}
CPUM.timestamp += MEMCYC_FAST;
//printf("Read: %08x\n", A);
return JoyARData[A & 0x7];
}
static DEFREAD(Read_4016)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return CPUM.mdr & 0xFC; // | TODO!
}
CPUM.timestamp += MEMCYC_XSLOW;
uint8 ret = CPUM.mdr & 0xFC;
ret |= Ports[0]->Read(WRIO & (0x40 << 0));
//printf("Read 4016: %02x\n", ret);
return ret;
}
static DEFWRITE(Write_4016)
{
CPUM.timestamp += MEMCYC_XSLOW;
JoyLS = V & 1;
for(unsigned sport = 0; sport < 2; sport++)
Ports[sport]->SetLatch(JoyLS);
//printf("Write 4016: %02x\n", V);
}
static DEFREAD(Read_4017)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return (CPUM.mdr & 0xE0) | 0x1C; // | TODO!
}
CPUM.timestamp += MEMCYC_XSLOW;
uint8 ret = (CPUM.mdr & 0xE0) | 0x1C;
ret |= Ports[1]->Read(WRIO & (0x40 << 1));
//printf("Read 4017: %02x\n", ret);
return ret;
}
static DEFWRITE(Write_WRIO)
{
CPUM.timestamp += MEMCYC_FAST;
WRIO = V;
}
static DEFREAD(Read_4213)
{
if(MDFN_UNLIKELY(DBG_InHLRead))
{
return WRIO;
}
CPUM.timestamp += MEMCYC_FAST;
return WRIO;
}
void INPUT_AutoRead(void)
{
for(unsigned sport = 0; sport < 2; sport++)
{
Ports[sport]->SetLatch(true);
Ports[sport]->SetLatch(false);
unsigned ard[2] = { 0 };
for(unsigned b = 0; b < 16; b++)
{
uint8 rv = Ports[sport]->Read(WRIO & (0x40 << sport));
ard[0] = (ard[0] << 1) | ((rv >> 0) & 1);
ard[1] = (ard[1] << 1) | ((rv >> 1) & 1);
}
for(unsigned ai = 0; ai < 2; ai++)
MDFN_en16lsb(&JoyARData[sport * 2 + ai * 4], ard[ai]);
}
JoyLS = false;
}
static MDFN_COLD void MapDevices(void)
{
for(unsigned sport = 0, vport = 0; sport < 2; sport++)
{
if(MTapEnabled[sport])
{
Ports[sport] = &PossibleMTaps[sport];
for(unsigned mport = 0; mport < 4; mport++)
PossibleMTaps[sport].SetSubDevice(mport, Devices[vport++]);
}
else
Ports[sport] = Devices[vport++];
}
}
void INPUT_Init(void)
{
for(unsigned bank = 0x00; bank < 0x100; bank++)
{
if(bank <= 0x3F || (bank >= 0x80 && bank <= 0xBF))
{
Set_A_Handlers((bank << 16) | 0x4016, Read_4016, Write_4016);
Set_A_Handlers((bank << 16) | 0x4017, Read_4017, OBWrite_XSLOW);
Set_A_Handlers((bank << 16) | 0x4201, OBRead_FAST, Write_WRIO);
Set_A_Handlers((bank << 16) | 0x4213, Read_4213, OBWrite_FAST);
Set_A_Handlers((bank << 16) | 0x4218, (bank << 16) | 0x421F, Read_JoyARData, OBWrite_FAST);
}
}
for(unsigned vport = 0; vport < 8; vport++)
{
DeviceData[vport] = nullptr;
Devices[vport] = &NoneDevice;
}
for(unsigned sport = 0; sport < 2; sport++)
for(unsigned mport = 0; mport < 4; mport++)
PossibleMTaps[sport].SetSubDevice(mport, &NoneDevice);
MTapEnabled[0] = MTapEnabled[1] = false;
MapDevices();
}
void INPUT_SetMultitap(const bool (&enabled)[2])
{
for(unsigned sport = 0; sport < 2; sport++)
{
if(enabled[sport] != MTapEnabled[sport])
{
PossibleMTaps[sport].SetLatch(JoyLS);
PossibleMTaps[sport].Power();
MTapEnabled[sport] = enabled[sport];
}
}
MapDevices();
}
void INPUT_Kill(void)
{
}
void INPUT_Reset(bool powering_up)
{
JoyLS = false;
for(unsigned sport = 0; sport < 2; sport++)
Ports[sport]->SetLatch(JoyLS);
memset(JoyARData, 0x00, sizeof(JoyARData));
if(powering_up)
{
WRIO = 0xFF;
for(unsigned sport = 0; sport < 2; sport++)
Ports[sport]->Power();
}
}
void INPUT_Set(unsigned vport, const char* type, uint8* ptr)
{
InputDevice* nd = &NoneDevice;
DeviceData[vport] = ptr;
if(!strcmp(type, "gamepad"))
nd = &PossibleDevices[vport].gamepad;
else if(strcmp(type, "none"))
abort();
if(Devices[vport] != nd)
{
Devices[vport] = nd;
Devices[vport]->SetLatch(JoyLS);
Devices[vport]->Power();
}
MapDevices();
}
void INPUT_StateAction(StateMem* sm, const unsigned load, const bool data_only)
{
SFORMAT StateRegs[] =
{
SFVAR(JoyARData),
SFVAR(JoyLS),
SFVAR(WRIO),
SFEND
};
MDFNSS_StateAction(sm, load, data_only, StateRegs, "INPUT");
for(unsigned sport = 0; sport < 2; sport++)
{
char sprefix[32] = "PORTn";
sprefix[4] = '0' + sport;
Ports[sport]->StateAction(sm, load, data_only, sprefix);
}
}
void INPUT_UpdatePhysicalState(void)
{
for(unsigned vport = 0; vport < 8; vport++)
Devices[vport]->UpdatePhysicalState(DeviceData[vport]);
}
static const IDIISG GamepadIDII =
{
IDIIS_ButtonCR("b", "B (center, lower)", 7, NULL),
IDIIS_ButtonCR("y", "Y (left)", 6, NULL),
IDIIS_Button("select", "SELECT", 4, NULL),
IDIIS_Button("start", "START", 5, NULL),
IDIIS_Button("up", "UP ↑", 0, "down"),
IDIIS_Button("down", "DOWN ↓", 1, "up"),
IDIIS_Button("left", "LEFT ←", 2, "right"),
IDIIS_Button("right", "RIGHT →", 3, "left"),
IDIIS_ButtonCR("a", "A (right)", 9, NULL),
IDIIS_ButtonCR("x", "X (center, upper)", 8, NULL),
IDIIS_Button("l", "Left Shoulder", 10, NULL),
IDIIS_Button("r", "Right Shoulder", 11, NULL),
};
static const std::vector<InputDeviceInfoStruct> InputDeviceInfo =
{
// None
{
"none",
"none",
NULL,
IDII_Empty
},
// Gamepad
{
"gamepad",
"Gamepad",
NULL,
GamepadIDII
},
};
const std::vector<InputPortInfoStruct> INPUT_PortInfo =
{
{ "port1", "Virtual Port 1", InputDeviceInfo, "gamepad" },
{ "port2", "Virtual Port 2", InputDeviceInfo, "gamepad" },
{ "port3", "Virtual Port 3", InputDeviceInfo, "gamepad" },
{ "port4", "Virtual Port 4", InputDeviceInfo, "gamepad" },
{ "port5", "Virtual Port 5", InputDeviceInfo, "gamepad" },
{ "port6", "Virtual Port 6", InputDeviceInfo, "gamepad" },
{ "port7", "Virtual Port 7", InputDeviceInfo, "gamepad" },
{ "port8", "Virtual Port 8", InputDeviceInfo, "gamepad" }
};
}
| Java |
/*
* CDE - Common Desktop Environment
*
* Copyright (c) 1993-2012, The Open Group. All rights reserved.
*
* These libraries and programs are free software; you can
* redistribute them and/or modify them under the terms of the GNU
* Lesser General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* These libraries and programs are distributed in the hope that
* they 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 these librararies and programs; if not, write
* to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*/
/* $TOG: EditAreaData.c /main/6 1998/03/03 16:18:13 mgreess $ */
/**********************************<+>*************************************
***************************************************************************
**
** File: EditAreaData.c
**
** Project: DtEditor widget for editing services
**
** Description: Contains functions for getting and setting the data
** on which the editor operates.
** -----------
**
*******************************************************************
*
* (c) Copyright 1993, 1994 Unix System Labs, Inc., a subsidiary of Novell, Inc.
* (c) Copyright 1996 Digital Equipment Corporation.
* (c) Copyright 1993, 1994, 1996 Hewlett-Packard Company.
* (c) Copyright 1993, 1994, 1996 International Business Machines Corp.
* (c) Copyright 1993, 1994, 1996 Sun Microsystems, Inc.
* (c) Copyright 1996 Novell, Inc.
* (c) Copyright 1996 FUJITSU LIMITED.
* (c) Copyright 1996 Hitachi.
*
********************************************************************
**
**
**************************************************************************
**********************************<+>*************************************/
#include "EditorP.h"
#include <X11/Xutil.h>
#include <Xm/TextP.h>
#include <unistd.h>
#include "DtWidgetI.h"
typedef enum _LoadActionType {
LOAD_DATA,
INSERT_DATA,
APPEND_DATA,
REPLACE_DATA
} LoadActionType;
static DtEditorErrorCode Check4EnoughMemory(
int numBytes);
static DtEditorErrorCode StripEmbeddedNulls(
char *stringData,
int *length);
static DtEditorErrorCode LoadFile(
Widget w,
char *fileName,
LoadActionType action,
XmTextPosition startReplace,
XmTextPosition endReplace );
#ifdef NEED_STRCASECMP
/*
* in case strcasecmp is not provided by the system here is one
* which does the trick
*/
static int
strcasecmp(s1, s2)
register char *s1, *s2;
{
register int c1, c2;
while (*s1 && *s2) {
c1 = isupper(*s1) ? tolower(*s1) : *s1;
c2 = isupper(*s2) ? tolower(*s2) : *s2;
if (c1 != c2)
return (1);
s1++;
s2++;
}
if (*s1 || *s2)
return (1);
return (0);
}
#endif
/*****************************************************************************
*
* Check4EnoughMemory - estimates whether there is enough memory to malloc
* "numBytes" of memory. This routine doubles the amount needed because the
* routines that use it are putting data into the text widget & we must make
* sure the widget will have room, too.
*
* Returns DtEDITOR_NO_ERRORS
* DtEDITOR_ILLEGAL_SIZE
* DtEDITOR_INSUFFICIENT_MEMORY
*
*****************************************************************************/
static DtEditorErrorCode
Check4EnoughMemory(
int numBytes)
{
DtEditorErrorCode returnVal = DtEDITOR_ILLEGAL_SIZE;
if (numBytes > 0) {
char *tmpString = (char *)malloc((2 * numBytes) + (numBytes/10));
if(tmpString == (char *)NULL)
returnVal = DtEDITOR_INSUFFICIENT_MEMORY;
else {
returnVal = DtEDITOR_NO_ERRORS;
free(tmpString);
}
}
return( returnVal );
} /* end Check4EnoughMemory */
/*****************************************************************************
*
* StripEmbeddedNulls - removes any embedded NULLs (\0) in a string of length
* 'length'. The removal occurs in place, with 'length' set to the
* new, stripped length. The resulting string is terminated with a
* trailing NULL.
*
* Returns DtEDITOR_NO_ERRORS - the string did not contain any embedded NULLs
* DtEDITOR_NULLS_REMOVED - the string did contain embedded
* NULLs that were removed.
*
*****************************************************************************/
static DtEditorErrorCode
StripEmbeddedNulls(
char *stringData,
int *length)
{
DtEditorErrorCode returnVal = DtEDITOR_NO_ERRORS;
if (strlen(stringData) != *length)
{
int firstNull;
returnVal = DtEDITOR_NULLS_REMOVED;
/*
* The file contains NULL characters, so we strip them out and
* report that we have done so.
*/
while((firstNull = strlen(stringData)) != *length)
{
int lastNull = firstNull;
while((lastNull + 1) < *length &&
stringData[lastNull + 1] == (char)'\0')
lastNull++;
memcpy(&stringData[firstNull], &stringData[lastNull + 1],
*length - lastNull);
*length -= 1 + lastNull - firstNull;
}
}
return( returnVal);
} /* end StripEmbeddedNulls */
/*****************************************************************************
*
* Retrieves the current location of the insert cursor
*
*****************************************************************************/
XmTextPosition
DtEditorGetInsertionPosition(
Widget widget)
{
DtEditorWidget editor = (DtEditorWidget) widget;
XmTextPosition result;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
result = XmTextGetInsertionPosition(M_text(editor));
_DtAppUnlock(app);
return result;
}
/*****************************************************************************
*
* Retrieves the current location of the last character in the widget
*
*****************************************************************************/
XmTextPosition
DtEditorGetLastPosition(
Widget widget)
{
DtEditorWidget editor = (DtEditorWidget) widget;
XmTextPosition result;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
result = XmTextGetLastPosition(M_text(editor));
_DtAppUnlock(app);
return result;
}
/*****************************************************************************
*
* Changes the current location of the insert cursor
*
*****************************************************************************/
void
DtEditorSetInsertionPosition(
Widget widget,
XmTextPosition position)
{
DtEditorWidget editor = (DtEditorWidget) widget;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
XmTextSetInsertionPosition(M_text(editor), position);
_DtAppUnlock(app);
}
static DtEditorErrorCode
setStringValue(
DtEditorWidget editor,
char *data)
{
/*
* Tell _DtEditorModifyVerifyCB() that we're replacing the entire
* contents, so it doesn't try to save the current document in an
* undo structure for a later undo.
*/
M_loadingAllNewData(editor) = True;
XmTextSetString( M_text(editor), data );
/*
* If the _DtEditorModifyVerifyCB() did not get called, reset the
* things which usually get reset there. The modifyVerify callback
* will not get called if the contents are being set to a null string
* and the widget is already empty.
*/
if (M_loadingAllNewData(editor) == True) {
M_loadingAllNewData(editor) = False;
M_unreadChanges(editor) = False;
_DtEditorResetUndo(editor);
}
return( DtEDITOR_NO_ERRORS );
} /* end setStringValue */
static DtEditorErrorCode
setDataValue(
DtEditorWidget widget,
void *rawData,
int length)
{
DtEditorErrorCode status = DtEDITOR_NULL_ITEM, tmpError;
/*
* Validate input
*/
if (rawData != (void *)NULL)
{
/*
* Check to see if we have a valid buffer size & enough memory to
* load the buffer into the text widget. This is only an estimate
* of our needs.
* Check4EnoughMemory() returns DtEDITOR_NO_ERRORS,
* DtEDITOR_ILLEGAL_SIZE, or DtEDITOR_INSUFFICIENT_MEMORY.
*/
status = Check4EnoughMemory( length );
if (status == DtEDITOR_NO_ERRORS)
{
/*
* Convert the data buffer into a string & insert into the widget
*/
char *textData = (char *)XtMalloc(length + 1);
memcpy( textData, rawData, length );
textData[length] = '\0';
/*
* Strip out any embedded NULLs because the text widget will only
* accept data up to the first NULL.
*
* StripEmbeddedNulls() returns DtEDITOR_NO_ERRORS or
* DtEDITOR_NULLS_REMOVED
*/
status = StripEmbeddedNulls( textData, &length );
/*
* Now, insert the converted string into the text widget
*/
tmpError = setStringValue( widget, textData );
if (tmpError != DtEDITOR_NO_ERRORS)
status = tmpError;
XtFree( (char *)textData );
}
}
return( status );
} /* end setDataValue */
static DtEditorErrorCode
setWcharValue(
DtEditorWidget editor,
wchar_t *data)
{
DtEditorErrorCode status;
wchar_t *tmp_wc;
int result, num_chars=0;
char *mb_value = (char *)NULL;
/*
* Convert the wide char string to a multi-byte string & stick it in
* the text widget.
*/
/*
* Determine how big the resulting mb string may be
*/
for (num_chars = 0, tmp_wc = data; *tmp_wc != (wchar_t)0L; num_chars++)
tmp_wc++;
/*
* Check to see if we have enough memory to load the string
* into the text widget. This is only an estimate of our needs.
* status will be set to DtEDITOR_NO_ERRORS, DtEDITOR_ILLEGAL_SIZE, or
* DtEDITOR_INSUFFICIENT_MEMORY.
*/
status = Check4EnoughMemory( (num_chars + 1) * MB_CUR_MAX );
if (status != DtEDITOR_NO_ERRORS) return status;
mb_value = XtMalloc( (unsigned)(num_chars + 1) * MB_CUR_MAX );
/*
* Convert the wchar string
* If wcstombs fails it returns (size_t) -1, so pass in empty
* string.
*/
result = wcstombs( mb_value, data, (num_chars + 1) * MB_CUR_MAX );
if (result == (size_t)-1)
result = 0;
/*
* wcstombs doesn't guarantee string is NULL terminated
*/
mb_value[result] = 0;
status = setStringValue( editor, mb_value );
XtFree(mb_value);
return( status );
} /* end setWcharValue */
static DtEditorErrorCode
insertStringValue(
DtEditorWidget editor,
char *data,
LoadActionType typeOfInsert,
XmTextPosition beginInsert,
XmTextPosition endInsert)
{
int numInserted;
switch( typeOfInsert )
{
case INSERT_DATA:
{
beginInsert = endInsert = XmTextGetInsertionPosition( M_text(editor) );
break;
}
case APPEND_DATA:
{
beginInsert = endInsert = XmTextGetLastPosition( M_text(editor) );
break;
}
case REPLACE_DATA:
{
break;
}
default:
{
}
} /* end switch */
/*
* Insert/Replace/Append the data and move the insertion cursor to
* the end of the inserted data.
*/
numInserted = _DtEditor_CountCharacters( data, strlen(data) );
XmTextReplace(M_text(editor), beginInsert, endInsert, data);
XmTextSetInsertionPosition( M_text(editor),
(XmTextPosition)(beginInsert + numInserted) );
return( DtEDITOR_NO_ERRORS );
} /* insertStringValue */
static DtEditorErrorCode
insertDataValue(
DtEditorWidget widget,
void *rawData,
int length,
LoadActionType typeOfInsert,
XmTextPosition beginInsert,
XmTextPosition endInsert)
{
DtEditorErrorCode status = DtEDITOR_NULL_ITEM, loadError;
/*
* Validate input
*/
if (rawData != (void *) NULL)
{
/*
* Check to see if we have a valid buffer size & enough memory to
* insert the buffer into the text widget. This is only an estimate
* of our needs.
* status will be set to DtEDITOR_NO_ERRORS, DtEDITOR_ILLEGAL_SIZE, or
* DtEDITOR_INSUFFICIENT_MEMORY.
*/
status = Check4EnoughMemory( length );
if (status == DtEDITOR_NO_ERRORS)
{
/*
* Convert the data buffer into a string & insert into the widget
*/
char *textData = (char *)XtMalloc(length + 1);
memcpy( textData, rawData, length );
textData[length] = '\0';
/*
* Strip out any embedded NULLs because the text widget will only
* accept data up to the first NULL.
*
* StripEmbeddedNulls() returns DtEDITOR_NO_ERRORS or
* DtEDITOR_NULLS_REMOVED
*/
status = StripEmbeddedNulls( textData, &length );
/*
* Now, insert the converted string into the text widget
*/
loadError = insertStringValue( widget, textData, typeOfInsert,
beginInsert, endInsert );
if (loadError != DtEDITOR_NO_ERRORS)
status = loadError;
XtFree( (char *)textData );
}
}
return( status );
} /* insertDataValue */
static DtEditorErrorCode
insertWcharValue(
DtEditorWidget editor,
wchar_t *data,
LoadActionType typeOfInsert,
XmTextPosition beginInsert,
XmTextPosition endInsert)
{
wchar_t *tmp_wc;
int result, num_chars=0;
char *mb_value = (char *)NULL;
DtEditorErrorCode status;
/*
* Convert the wide char string to a multi-byte string & insert it into
* the text widget.
*/
/*
* Determine how big the resulting mb string may be
*/
for (num_chars = 0, tmp_wc = data; *tmp_wc != (wchar_t)0L; num_chars++)
tmp_wc++;
/*
* Check to see if we have enough memory to insert the string
* into the text widget. This is only an estimate of our needs.
* status will be set to DtEDITOR_NO_ERRORS, DtEDITOR_ILLEGAL_SIZE, or
* DtEDITOR_INSUFFICIENT_MEMORY.
*/
status = Check4EnoughMemory( (num_chars + 1) * MB_CUR_MAX );
if(status != DtEDITOR_NO_ERRORS) return status;
mb_value = XtMalloc( (unsigned)(num_chars + 1) * MB_CUR_MAX );
/*
* Convert the wchar string.
* If wcstombs fails it returns (size_t) -1, so pass in empty
* string.
*/
result = wcstombs( mb_value, data, (num_chars + 1) * MB_CUR_MAX );
if (result == (size_t)-1)
result = 0;
/*
* wcstombs doesn't guarantee string is NULL terminated
*/
mb_value[result] = 0;
status = insertStringValue( editor, mb_value, typeOfInsert,
beginInsert, endInsert );
XtFree( mb_value );
return( status );
} /* insertWcharValue */
/***************************************************************************
*
* DtEditorSetContents - sets the contents of the DtEditor widget.
*
* Inputs: widget to set the contents
*
* a data structure containing the data to put into the
* widget. Depending upon the type of data being set, this
* structure will contain various fields:
*
* string - \0-terminated string of characters
* data - the data, the size of the data
*
* Returns 0 - contents were set sucessfully
* !0 - an error occured while setting the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorSetContents(
Widget widget,
DtEditorContentRec *data )
{
DtEditorErrorCode error = DtEDITOR_INVALID_TYPE;
DtEditorWidget editor = (DtEditorWidget) widget;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
switch( data->type )
{
case DtEDITOR_TEXT:
{
error = setStringValue ( editor, data->value.string );
break;
}
case DtEDITOR_DATA:
{
error = setDataValue ( editor, data->value.data.buf,
data->value.data.length);
break;
}
case DtEDITOR_WCHAR:
{
error = setWcharValue ( editor, data->value.wchar );
break;
}
default :
{
error = DtEDITOR_INVALID_TYPE;
}
} /* end switch */
/*
* Update the current-line-display in the status line
*/
if (error == DtEDITOR_NO_ERRORS)
_DtEditorUpdateLineDisplay(editor, 1, False );
_DtAppUnlock(app);
return( error );
}
/***************************************************************************
*
* DtEditorSetContentsFromFile - read a data file, putting the contents
* into a DtEditor widget.
*
* Inputs: widget to load the file into
*
* to indicate the type of contents loaded from the file:
* string - a \0-terminated string of characters
* data - untyped data
*
* filename - name of the file to read
*
* Returns 0 - contents were loaded sucessfully
* !0 - an error occured while loading the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorSetContentsFromFile(
Widget widget,
char *fileName)
{
DtEditorErrorCode result;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
result = LoadFile(widget, fileName, LOAD_DATA, 0, 0);
_DtAppUnlock(app);
return result;
}
/***************************************************************************
*
* DtEditorAppend - append data to the contents of the DtEditor widget.
*
* Inputs: widget to add to the contents
*
* a data structure containing the data to append to the
* widget. Depending upon the type of data being set, this
* structure will contain various fields:
*
* string - \0-terminated string of characters
* data - the data, the size of the data
*
* Returns 0 - contents were set sucessfully
* !0 - an error occured while setting the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorAppend(
Widget widget,
DtEditorContentRec *data )
{
DtEditorErrorCode error = DtEDITOR_INVALID_TYPE;
DtEditorWidget editor = (DtEditorWidget) widget;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
switch( data->type )
{
case DtEDITOR_TEXT:
{
error = insertStringValue ( editor, data->value.string,
APPEND_DATA, 0, 0 );
break;
}
case DtEDITOR_DATA:
{
error = insertDataValue ( editor, data->value.data.buf,
data->value.data.length, APPEND_DATA, 0,0);
break;
}
case DtEDITOR_WCHAR:
{
error = insertWcharValue ( editor, data->value.wchar,
APPEND_DATA, 0, 0 );
break;
}
default:
{
error = DtEDITOR_INVALID_TYPE;
}
} /* end switch */
_DtAppUnlock(app);
return( error );
}
/***************************************************************************
*
* DtEditorAppendFromFile - read a data file, appending the contents
* into a DtEditor widget.
*
* Inputs: widget to append the file to
*
* to indicate the type of contents appended from the file:
* string - a \0-terminated string of characters
* data - untyped data
*
* filename - name of the file to read
*
* Returns 0 - contents were appended sucessfully
* !0 - an error occured while appending the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorAppendFromFile(
Widget widget,
char *fileName)
{
DtEditorErrorCode result;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
result = LoadFile(widget, fileName, APPEND_DATA, 0, 0);
_DtAppUnlock(app);
return result;
}
/***************************************************************************
*
* DtEditorInsert - insert data into the contents of the DtEditor widget.
*
* Inputs: widget to add to the contents
*
* a data structure containing the data to insert into the
* widget. Depending upon the type of data being set, this
* structure will contain various fields:
*
* string - \0-terminated string of characters
* data - the data, the size of the data
*
* Returns 0 - contents were set sucessfully
* !0 - an error occured while setting the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorInsert(
Widget widget,
DtEditorContentRec *data )
{
DtEditorErrorCode error = DtEDITOR_INVALID_TYPE;
DtEditorWidget editor = (DtEditorWidget) widget;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
switch( data->type )
{
case DtEDITOR_TEXT:
{
error = insertStringValue ( editor, data->value.string,
INSERT_DATA, 0, 0 );
break;
}
case DtEDITOR_DATA:
{
error = insertDataValue ( editor, data->value.data.buf,
data->value.data.length, INSERT_DATA, 0,0);
break;
}
case DtEDITOR_WCHAR:
{
error = insertWcharValue ( editor, data->value.wchar,
INSERT_DATA, 0, 0 );
break;
}
default :
{
error = DtEDITOR_INVALID_TYPE;
}
} /* end switch */
_DtAppUnlock(app);
return( error );
}
/***************************************************************************
*
* DtEditorInsertFromFile - read a data file, inserting the contents
* into a DtEditor widget.
*
* Inputs: widget to insert the file to
*
* to indicate the type of contents inserted from the file:
* string - a \0-terminated string of characters
* data - untyped data
*
* filename - name of the file to read
*
* Returns 0 - contents were inserted sucessfully
* !0 - an error occured while inserting the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorInsertFromFile(
Widget widget,
char *fileName)
{
DtEditorErrorCode result;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
result = LoadFile(widget, fileName, INSERT_DATA, 0, 0);
_DtAppUnlock(app);
return result;
}
/***************************************************************************
*
* DtEditorReplace - replace a specified portion of the contents of the
* DtEditor widget with the supplied data.
*
* Inputs: widget to replace a portion of its contents
*
* starting character position of the portion to replace
*
* ending character position of the portion to replace
*
* a data structure containing the data to replace some data
* in the widget. Depending upon the type of data being set,
* this structure will contain various fields:
*
* string - \0-terminated string of characters
* data - the data, the size of the data
*
*
* Returns 0 - the portion was replaced sucessfully
* !0 - an error occured while replacing the portion
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorReplace(
Widget widget,
XmTextPosition startPos,
XmTextPosition endPos,
DtEditorContentRec *data)
{
DtEditorErrorCode error = DtEDITOR_INVALID_TYPE;
DtEditorWidget editor = (DtEditorWidget) widget;
XmTextWidget tw;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
tw = (XmTextWidget) M_text(editor);
if( startPos < 0 )
startPos = 0;
if( startPos > tw->text.last_position )
startPos = tw->text.last_position;
if( endPos < 0 )
endPos = 0;
if( endPos > tw->text.last_position )
endPos = tw->text.last_position;
if( startPos > endPos )
{
error = DtEDITOR_INVALID_RANGE;
}
else
{
switch( data->type )
{
case DtEDITOR_TEXT:
{
error = insertStringValue ( editor, data->value.string,
REPLACE_DATA, startPos, endPos );
break;
}
case DtEDITOR_DATA:
{
error = insertDataValue ( editor, data->value.data.buf,
data->value.data.length, REPLACE_DATA,
startPos, endPos );
break;
}
case DtEDITOR_WCHAR:
{
error = insertWcharValue ( editor, data->value.wchar,
REPLACE_DATA, startPos, endPos );
break;
}
default :
{
error = DtEDITOR_INVALID_TYPE;
}
} /* end switch */
}
_DtAppUnlock(app);
return( error );
}
/***************************************************************************
*
* DtEditorReplaceFromFile - read a data file, using the contents to replace
* a specified portion of the contntes of a
* DtEditor widget.
*
* Inputs: widget to insert the file to
*
* starting character position of the portion to replace
*
* ending character position of the portion to replace
*
* to indicate the type of contents inserted from the file:
* string - a \0-terminated string of characters
* data - untyped data
*
* filename - local name of the file to read
*
* Returns 0 - contents were inserted sucessfully
* !0 - an error occured while inserting the contents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorReplaceFromFile(
Widget widget,
XmTextPosition startPos,
XmTextPosition endPos,
char *fileName)
{
DtEditorWidget editor = (DtEditorWidget) widget;
XmTextWidget tw;
DtEditorErrorCode result;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
tw = (XmTextWidget) M_text(editor);
if( startPos < 0)
startPos = 0;
if( startPos > tw->text.last_position )
startPos = tw->text.last_position;
if( endPos < 0 )
endPos = 0;
if( endPos > tw->text.last_position )
endPos = tw->text.last_position;
if(startPos > endPos)
{
result = DtEDITOR_INVALID_RANGE;
}
else
{
result = LoadFile(widget, fileName, REPLACE_DATA, startPos, endPos);
}
_DtAppUnlock(app);
return result;
}
/***************************************************************************
*
* _DtEditorValidateFileAccess - check to see if file exists, whether we
* can get to it, and whether it is readable
* or writable.
*
* Note: does not check whether files for reading are read only.
*
* Inputs: filename - name of the local file to read
* flag indicating whether we want to read or write
* the file.
*
* Returns 0 file exists & we have read or write permissions.
*
* >0 if file cannot be read from/written to.
* errno is set to one of the following values:
*
* General errors:
* DtEDITOR_INVALID_FILENAME - 0 length filename
* DtEDITOR_NONEXISTENT_FILE - file does not exist
* (Note: this may not be considered an error when saving
* to a file. The file may just need to be created.)
* DtEDITOR_NO_FILE_ACCESS - cannot stat existing file
* DtEDITOR_DIRECTORY - file is a directory
* DtEDITOR_CHAR_SPECIAL_FILE - file is a device special file
* DtEDITOR_BLOCK_MODE_FILE - file is a block mode file
*
* additional READ_ACCESS errors:
* DtEDITOR_UNREADABLE_FILE -
*
* additional WRITE_ACCESS errors:
* DtEDITOR_UNWRITABLE_FILE -
* file or directory is write protected for
* another reason
*
***************************************************************************/
extern DtEditorErrorCode
_DtEditorValidateFileAccess(
char *fileName,
int accessType )
{
struct stat statbuf; /* Information on a file. */
DtEditorErrorCode error = DtEDITOR_INVALID_FILENAME;
/*
* First, make sure we were given a name
*/
if (fileName && *fileName )
{
/*
* Does the file already exist?
*/
if ( access(fileName, F_OK) != 0 )
error = DtEDITOR_NONEXISTENT_FILE;
else
{
error = DtEDITOR_NO_ERRORS;
/*
* The file exists, so lets do some type checking
*/
if( stat(fileName, &statbuf) != 0 )
error = DtEDITOR_NO_FILE_ACCESS;
else
{
/* if its a directory - can't save */
if( (statbuf.st_mode & S_IFMT) == S_IFDIR )
{
error = DtEDITOR_DIRECTORY;
return( error );
}
/* if its a character special device - can't save */
if( (statbuf.st_mode & S_IFMT) == S_IFCHR )
{
error = DtEDITOR_CHAR_SPECIAL_FILE;
return( error );
}
/* if its a block mode device - can't save */
if((statbuf.st_mode & S_IFMT) == S_IFBLK)
{
error = DtEDITOR_BLOCK_MODE_FILE;
return( error );
}
/*
* We now know that it's a regular file so check to whether we
* can read or write to it, as appropriate.
*/
switch( accessType )
{
case READ_ACCESS:
{
if( access(fileName, R_OK) != 0 )
error = DtEDITOR_UNREADABLE_FILE;
break;
}
case WRITE_ACCESS:
{
if( access(fileName, W_OK) == 0 )
{
/*
* Can write to it.
*/
error = DtEDITOR_WRITABLE_FILE;
}
else
{
/*
* Can't write to it.
*/
error = DtEDITOR_UNWRITABLE_FILE;
} /* end no write permission */
break;
}
default:
{
break;
}
} /* end switch */
} /* end stat suceeded */
} /* end file exists */
} /* end filename passed in */
return( error );
} /* end _DtEditorValidateFileAccess */
/************************************************************************
*
* LoadFile - Check if file exists, whether we can get to it, etc.
* If so, type and read its contents.
*
* Inputs: widget to set, add, or insert contents of file into
*
* name of file to read
*
* type of file (NULL). This will be set by LoadFile
*
* action to perform with the data (load, append, insert,
* replace a portion, attach)
*
* The following information will be used if the file
* contents will replace a portion of the widget's contents:
*
* starting character position of the portion to replace
*
* ending character position of the portion to replace
*
* Returns: DtEDITOR_NO_ERRORS - file was read sucessfully
* DtEDITOR_READ_ONLY_FILE - file was read sucessfully but
* is read only
* DtEDITOR_DIRECTORY - the file is a directory
* DtEDITOR_CHAR_SPECIAL_FILE - the file is a character
* special device
* DtEDITOR_BLOCK_MODE_FILE - the file is a block mode device
* DtEDITOR_NONEXISTENT_FILE - file does not exist
* DtEDITOR_NULLS_REMOVED - file contained embedded NULLs
* that were removed
* DtEDITOR_INSUFFICIENT_MEMORY - unable to allocate
* enough memory for contents of file
*
************************************************************************/
static DtEditorErrorCode
LoadFile(
Widget w,
char *fileName,
LoadActionType action,
XmTextPosition startReplace,
XmTextPosition endReplace )
{
DtEditorContentRec cr; /* Structure for passing data to widget */
struct stat statbuf; /* Information on a file. */
int file_length; /* Length of file. */
FILE *fp = NULL; /* Pointer to open file */
DtEditorErrorCode returnVal = DtEDITOR_NONEXISTENT_FILE;
/* Error accessing file & reading contents */
DtEditorErrorCode loadError=DtEDITOR_NO_ERRORS;
/* Error from placing bits into text widget */
/*
* First, make sure we were given a name
*/
if (fileName && *fileName )
{
/*
* Can we read the file?
*/
returnVal = _DtEditorValidateFileAccess( fileName, READ_ACCESS );
if( returnVal == DtEDITOR_NO_ERRORS )
{
/*
* Open the file for reading. If we can read/write, then we're
* cool, otherwise we might need to tell the user that the
* file's read-only, or that we can't even read from it.
*/
if( (fp = fopen(fileName, "r+")) == NULL )
{
/*
* We can't update (read/write) the file so try opening read-
* only
*/
if( (fp = fopen(fileName, "r")) == NULL )
{
/*
* We can't read from the file.
*/
return ( DtEDITOR_UNREADABLE_FILE );
}
else
{
/*
* Tell the application that the file's read-only.
* Becareful not to overwrite this value with one of the calls
* to set the widget's contents.
*/
returnVal = DtEDITOR_READ_ONLY_FILE;
}
} /* end open for read/write */
} /* end try to read the file */
} /* end if no filename */
/* If a file is open, get the bytes */
if ( fp )
{
stat( fileName, &statbuf );
file_length = statbuf.st_size;
/*
* Check to see if we have enough memory to load the file contents
* into the text widget. This is only an estimate of our needs.
* Check4EnoughMemory() returns DtEDITOR_NO_ERRORS,
* DtEDITOR_ILLEGAL_SIZE, or DtEDITOR_INSUFFICIENT_MEMORY.
*/
loadError = Check4EnoughMemory( file_length );
if (loadError == DtEDITOR_INSUFFICIENT_MEMORY)
returnVal = loadError;
else {
/*
* Read the file contents (with room for null) & convert to a
* string. We want to use a string because the
* DtEditorSetContents/Append/Insert/... functions create another
* copy of the data before actually putting it into the widget.
*/
char *file_string = (char*) XtMalloc(file_length + 1);
file_length = fread(file_string, sizeof(char), file_length, fp);
file_string[file_length] = '\0';
/*
* Strip out any embedded NULLs because the text widget will only
* accept data up to the first NULL.
*
* StripEmbeddedNulls() returns DtEDITOR_NO_ERRORS or
* DtEDITOR_NULLS_REMOVED
*/
loadError = StripEmbeddedNulls( file_string, &file_length );
if ( loadError != DtEDITOR_NO_ERRORS )
returnVal = loadError;
/*
* Insert it as a string, otherwise the following DtEditor*()
* functions will make another copy of the data.
*/
cr.type = DtEDITOR_TEXT;
cr.value.string = file_string;
/*
* Load, insert, append, or attach the file, as specified
*/
switch( action )
{
case LOAD_DATA:
{
loadError = DtEditorSetContents ( w, &cr );
break;
}
case INSERT_DATA:
{
loadError = DtEditorInsert ( w, &cr );
break;
}
case APPEND_DATA:
{
loadError = DtEditorAppend ( w, &cr );
break;
}
case REPLACE_DATA:
{
loadError = DtEditorReplace(w, startReplace, endReplace, &cr);
break;
}
default:
{
}
} /* end switch */
if ( loadError != DtEDITOR_NO_ERRORS )
returnVal = loadError;
/*
* The file is loaded, clean up.
*/
XtFree( file_string );
} /* end there is enough memory */
/* Close the file */
fclose(fp);
} /* end if a file is open */
return( returnVal );
} /* end LoadFile */
static char *
StringAdd(
char *destination,
char *source,
int number)
{
memcpy(destination, source, number);
destination[number] = (char)'\0';
destination += number;
return destination;
}
/***************************************************************************
*
* CopySubstring - copies out a portion of the text, optionally
* adding newlines at any and all wordwrap-caused
* "virtual" lines.
*
* Inputs: widget from which we get the data to write;
* startPos determines the first character to write out;
* endPos determines the last character to write out;
* buf is the character buffer into which we write. It
* is assumed to be large enough - be careful.
* addNewlines specifies whether to add '/n' to "virtual" lines.
* Returns Nuthin'
*
*
***************************************************************************/
static char *
CopySubstring(
XmTextWidget widget,
XmTextPosition startPos,
XmTextPosition endPos,
char *buf,
Boolean addNewlines)
{
register XmTextLineTable line_table = widget->text.line_table;
int currLine, firstLine;
char *pString, *pCurrChar, *pLastChar;
int numToCopy;
if(startPos < 0)
startPos = 0;
if(startPos > widget->text.last_position)
startPos = widget->text.last_position;
if(endPos < 0)
endPos = 0;
if(endPos > widget->text.last_position)
endPos = widget->text.last_position;
if(startPos > endPos)
return buf;
pString = XmTextGetString((Widget)widget);
if(addNewlines == False)
{
pCurrChar = _DtEditorGetPointer(pString, startPos);
pLastChar = _DtEditorGetPointer(pString, endPos);
numToCopy = pLastChar - pCurrChar + mblen(pLastChar, MB_CUR_MAX);
buf = StringAdd(buf, pCurrChar, numToCopy);
}
else
{
int *mb_str_loc, total, z, siz;
char *bptr;
mb_str_loc = (int *) XtMalloc(sizeof(int) * ((endPos-startPos)+1));
if (NULL == mb_str_loc)
{
/* Should figure out some way to pass back an error code. */
buf = CopySubstring(widget, startPos, endPos, buf, False);
return buf;
}
/*
* mb_str_loc[] is being used to replace the call
* to _DtEditorGetPointer. That function used
* mbtowc() to count the number of chars between the
* beginning of pString and startChar. The problem
* was that it sat in a loop and was also called for
* every line, so it was SLOW. Now, we count once
* and store the results in mb_str_loc[].
*/
/* Because startPos may not always == 0: */
/* mb_str_loc[0] = startPos */
/* mb_str_loc[endPos - startPos] = endPos */
/* */
/* So when accessing items, dereference off of */
/* startPos. */
mb_str_loc[0] = 0;
for(total=0, bptr=pString, z=1;
z <= (endPos - startPos); bptr += siz, z++)
{
if (MB_CUR_MAX > 1)
{
if ( (siz = mblen(bptr, MB_CUR_MAX)) < 0)
{
siz = 1;
total += 1;
}
else
total += siz;
}
else
{
siz = 1;
total += 1;
}
mb_str_loc[z] = total;
}
firstLine = currLine = _DtEditorGetLineIndex(widget, startPos);
do
{
if(startPos > (XmTextPosition)line_table[currLine].start_pos)
pCurrChar = pString + mb_str_loc[0];
else
{
z = line_table[currLine].start_pos;
pCurrChar = pString +
mb_str_loc[z - startPos];
}
if(addNewlines == True && currLine > firstLine &&
line_table[currLine].virt_line != 0)
{
buf[0] = (char)'\n';
buf[1] = (char)'\0';
buf++;
}
if(currLine >= (widget->text.total_lines - 1))
pLastChar = pString +
mb_str_loc[endPos - startPos];
else if((XmTextPosition)line_table[currLine + 1].start_pos <= endPos)
{
z = line_table[currLine+1].start_pos - 1;
pLastChar = pString +
mb_str_loc[z - startPos];
}
else
pLastChar = pString +
mb_str_loc[endPos - startPos];
numToCopy = pLastChar - pCurrChar + mblen(pLastChar, MB_CUR_MAX);
buf = StringAdd(buf, pCurrChar, numToCopy);
currLine++;
} while(currLine < widget->text.total_lines &&
(XmTextPosition)line_table[currLine].start_pos <= endPos);
XtFree((char*)mb_str_loc);
}
XtFree(pString);
return buf;
}
/*************************************************************************
*
* _DtEditorCopyDataOut - Writes the entire text editor buffer contents to
* the specified character array.
*
* Inputs: tw, to supply the data.
* buf, specifying the array to which to write the data.
*
*************************************************************************/
static char *
_DtEditorCopyDataOut(
XmTextWidget tw,
char *buf,
Boolean addNewlines)
{
buf = CopySubstring(tw, 0, tw->text.last_position, buf, addNewlines);
return buf;
}
static DtEditorErrorCode
getStringValue(
DtEditorWidget editor,
char **buf,
Boolean insertNewlines)
{
XmTextWidget tw = (XmTextWidget) M_text(editor);
int bufSize;
char *lastChar;
DtEditorErrorCode returnVal = DtEDITOR_NO_ERRORS;
/*
* Calculate the size of the buffer we need for the data.
* 1. Start with MB_CUR_MAX for each char in the text.
* 3. Add in 1 char for each line, if we have to insert newlines.
* 4. Add 1 for a terminating NULL.
*/
bufSize = tw->text.last_position * MB_CUR_MAX;
if(insertNewlines == True)
bufSize += tw->text.total_lines;
bufSize += 1;
returnVal = Check4EnoughMemory(bufSize);
if (DtEDITOR_NO_ERRORS != returnVal) return returnVal;
*buf = (char *) XtMalloc(bufSize);
lastChar = _DtEditorCopyDataOut(tw, *buf, insertNewlines);
return returnVal;
} /* end getStringValue */
static DtEditorErrorCode
getDataValue(
DtEditorWidget editor,
void **buf,
unsigned int *size,
Boolean insertNewlines)
{
DtEditorErrorCode error;
error = getStringValue(editor, (char **)buf, insertNewlines);
*size = strlen( *buf ); /* remember, strlen doesn't count \0 at end */
return( error );
} /* end getDataValue */
static DtEditorErrorCode
getWcharValue(
DtEditorWidget editor,
wchar_t **data,
Boolean insertNewlines)
{
DtEditorErrorCode error;
char *mb_value;
wchar_t *pWchar_value;
int num_char, result;
size_t nbytes;
error = getStringValue(editor, &mb_value, insertNewlines);
if (error == DtEDITOR_NO_ERRORS)
{
/*
* Allocate space for the wide character string
*/
num_char = _DtEditor_CountCharacters(mb_value, strlen(mb_value)) + 1;
nbytes = (size_t) num_char * sizeof(wchar_t);
error = Check4EnoughMemory(nbytes);
if (DtEDITOR_NO_ERRORS != error) return error;
pWchar_value = (wchar_t*) XtMalloc(nbytes);
/*
* Convert the multi-byte string to wide character
*/
result = mbstowcs(pWchar_value, mb_value, num_char*sizeof(wchar_t) );
if (result < 0) pWchar_value[0] = 0L;
*data = pWchar_value;
XtFree( mb_value );
}
return( error );
} /* end getWcharValue */
/***************************************************************************
*
* DtEditorGetContents - gets the contents of the DtEditor widget.
*
* Inputs: widget to retrieve the contents
*
* pointer to a data structure indicating how the retrieved
* data should be formatted. Depending upon the type of format,
* this structure will contain various fields:
* string - a NULL pointer (char *) to hold the data
* a new container will be created.
* data - void pointer to hold the data, unsigned int for the
* size of the data,
* a Boolean indicating whether Newline characters should be
* inserted at the end of each line, in string format.
* a Boolean indicating whether the the unsaved changes
* flag should be cleared. There may be times when an
* application will want to request a copy of the contents
* without effecting whether DtEditorCheckForUnsavedChanges
* reports there are unsaved changes.
*
* Returns 0 - contents were retrieved sucessfully
* !0 - an error occured while retrieving the contents
*
* The structure passed in will be set according to the
* requested format:
* string - a \0-terminated string of characters with
* optional Newlines
* container - handle to a Bento container
* data - the data, the size of the data
*
* The application is responsible for free'ing any data in the
* above structure.
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorGetContents(
Widget widget,
DtEditorContentRec *data,
Boolean hardCarriageReturns,
Boolean markContentsAsSaved )
{
DtEditorErrorCode error = DtEDITOR_INVALID_TYPE;
DtEditorWidget editor = (DtEditorWidget) widget;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
switch( data->type )
{
case DtEDITOR_TEXT:
{
error = getStringValue( editor, &(data->value.string),
hardCarriageReturns );
break;
}
case DtEDITOR_DATA:
{
error = getDataValue( editor, &(data->value.data.buf),
&(data->value.data.length),
hardCarriageReturns );
break;
}
case DtEDITOR_WCHAR:
{
error = getWcharValue( editor, &(data->value.wchar),
hardCarriageReturns );
break;
}
default :
{
error = DtEDITOR_INVALID_TYPE;
}
} /* end switch */
/*
* If there were no errors, mark there are now no unsaved changes (unless
* we were told not to).
*/
if ( error == DtEDITOR_NO_ERRORS && markContentsAsSaved == True )
M_unreadChanges( editor ) = False;
_DtAppUnlock(app);
return( error );
}
/***************************************************************************
*
* DtEditorSaveContentsToFile - saves the contents of the DtEditor
* widget to a disc file as string/data
* or a CDE Document (Bento container).
*
* Inputs: widget to retrieve the contents
*
* filename - name of the file to read
* a Boolean indicating whether the file should be
* overwritten if it currently exists.
* a Boolean indicating whether Newline characters should be
* inserted at the end of each line (string format only).
* a Boolean indicating whether the the unsaved changes
* flag should be cleared. There may be times when an
* application will want to request a copy of the contents
* without effecting whether DtEditorCheckForUnsavedChanges
* reports there are unsaved changes.
*
* Returns DtEDITOR_NO_ERRORS - contents were saved sucessfully
* DtEDITOR_UNWRITABLE_FILE - file is write protected
* DtEDITOR_WRITABLE_FILE - file exists and the
* overwriteIfExists parameter is False.
* DtEDITOR_SAVE_FAILED - write to the file failed; check
* disk space, etc.
* OR any errors from DtEditorGetContents
*
***************************************************************************/
extern DtEditorErrorCode
DtEditorSaveContentsToFile(
Widget widget,
char *fileName,
Boolean overwriteIfExists,
Boolean hardCarriageReturns,
Boolean markContentsAsSaved )
{
FILE *pFile;
DtEditorContentRec cr; /* Structure for retrieving contents of widget */
DtEditorWidget editor = (DtEditorWidget) widget;
DtEditorErrorCode error = DtEDITOR_INVALID_FILENAME;
_DtWidgetToAppContext(widget);
_DtAppLock(app);
/*
* First, make sure we were given a name
*/
if (fileName && *fileName )
{
/*
* Can we save to the file?
*/
error = _DtEditorValidateFileAccess( fileName, WRITE_ACCESS );
if( error == DtEDITOR_NO_ERRORS ||
error == DtEDITOR_NONEXISTENT_FILE ||
error == DtEDITOR_WRITABLE_FILE )
{
/*
* Don't overwrite an existing file if we've been told not to
*/
if( error == DtEDITOR_WRITABLE_FILE && overwriteIfExists == False )
{
_DtAppUnlock(app);
return( error );
}
/*
* Open the file for writing
*/
if ( (pFile = fopen(fileName, "w")) == NULL )
{
_DtAppUnlock(app);
return( DtEDITOR_UNWRITABLE_FILE );
}
else
{
/*
* Save the unsaved changes flag so we can restore it if the write
* to the file fails.
*/
Boolean saved_state = M_unreadChanges( editor );
/*
* Now, get the contents of the widget and write it to the file,
* depending upon the format requested.
*/
cr.type = DtEDITOR_DATA;
error = DtEditorGetContents( widget, &cr, hardCarriageReturns,
markContentsAsSaved );
if ( error == DtEDITOR_NO_ERRORS )
{
/*
* Write it to the file
*/
size_t size_written = fwrite( cr.value.data.buf, 1,
cr.value.data.length, pFile );
if( cr.value.data.length != size_written )
error = DtEDITOR_SAVE_FAILED;
XtFree( cr.value.data.buf );
}
fclose(pFile);
if( error == DtEDITOR_SAVE_FAILED )
{
/*
* Restore the unsaved changes flag since the save failed
*/
M_unreadChanges( editor ) = saved_state;
}
} /* end file is writable */
} /* end filename is valid */
}
_DtAppUnlock(app);
return( error );
} /* end DtEditorSaveContentsToFile */
/*
* _DtEditorGetPointer returns a pointer to the _character_
* numbered by startChar within the string pString.
* It accounts for possible multibyte chars.
*/
char *
_DtEditorGetPointer(
char *pString,
int startChar)
{
char *bptr;
int curChar, char_size;
if(MB_CUR_MAX > 1)
{
for(bptr = pString, curChar = 0;
curChar < startChar && *bptr != (char)'\0';
curChar++, bptr += char_size)
{
if ( (char_size = mblen(bptr, MB_CUR_MAX)) < 0)
char_size = 1;
}
}
else
{
bptr = pString + startChar;
}
return bptr;
} /* end _DtEditorGetPointer */
| Java |
#pragma once
/*
* Copyright (C) 2005-2015 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <memory>
#include <string>
#include <vector>
class CEvent;
namespace KODI
{
namespace MESSAGING
{
class CApplicationMessenger;
class ThreadMessage
{
friend CApplicationMessenger;
public:
ThreadMessage()
: ThreadMessage{ 0, -1, -1, nullptr }
{
}
explicit ThreadMessage(uint32_t messageId)
: ThreadMessage{ messageId, -1, -1, nullptr }
{
}
ThreadMessage(uint32_t messageId, int p1, int p2, void* payload)
: dwMessage{ messageId }
, param1{ p1 }
, param2{ p2 }
, lpVoid{ payload }
{
}
ThreadMessage(uint32_t messageId, int p1, int p2, void* payload, std::string param, std::vector<std::string> vecParams)
: dwMessage{ messageId }
, param1{ p1 }
, param2{ p2 }
, lpVoid{ payload }
, strParam( param )
, params( vecParams )
{
}
ThreadMessage(const ThreadMessage& other)
: dwMessage(other.dwMessage),
param1(other.param1),
param2(other.param2),
lpVoid(other.lpVoid),
strParam(other.strParam),
params(other.params),
waitEvent(other.waitEvent),
result(other.result)
{
}
ThreadMessage(ThreadMessage&& other)
: dwMessage(other.dwMessage),
param1(other.param1),
param2(other.param2),
lpVoid(other.lpVoid),
strParam(std::move(other.strParam)),
params(std::move(other.params)),
waitEvent(std::move(other.waitEvent)),
result(std::move(other.result))
{
}
ThreadMessage& operator=(const ThreadMessage& other)
{
if (this == &other)
return *this;
dwMessage = other.dwMessage;
param1 = other.param1;
param2 = other.param2;
lpVoid = other.lpVoid;
strParam = other.strParam;
params = other.params;
waitEvent = other.waitEvent;
result = other.result;
return *this;
}
ThreadMessage& operator=(ThreadMessage&& other)
{
if (this == &other)
return *this;
dwMessage = other.dwMessage;
param1 = other.param1;
param2 = other.param2;
lpVoid = other.lpVoid;
strParam = std::move(other.strParam);
params = std::move(other.params);
waitEvent = std::move(other.waitEvent);
result = std::move(other.result);
return *this;
}
uint32_t dwMessage;
int param1;
int param2;
void* lpVoid;
std::string strParam;
std::vector<std::string> params;
void SetResult(int res)
{
//On posted messages result will be zero, since they can't
//retrieve the response we silently ignore this to let message
//handlers not have to worry about it
if (result)
*result = res;
}
protected:
std::shared_ptr<CEvent> waitEvent;
std::shared_ptr<int> result;
};
}
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>oRTP: /Users/huyheo/Documents/Linphone/linphone-iphone/submodules/linphone/oRTP/src Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">oRTP
 <span id="projectnumber">0.22.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_2a7dcbd79b844734b273b7fb1d7d705c.html">linphone</a></li><li class="navelem"><a class="el" href="dir_ce0874cbbf4173a48245befc1202b926.html">oRTP</a></li><li class="navelem"><a class="el" href="dir_12068a0eb9ea07e5ea5c12c7c6d7e94f.html">src</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">src Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:avprofile_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>avprofile.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:b64_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="b64_8c.html">b64.c</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:dll__entry_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>dll_entry.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:event_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>event.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:jitterctl_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>jitterctl.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:jitterctl_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>jitterctl.h</b> <a href="jitterctl_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:logging_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>logging.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:netsim_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>netsim.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ortp-config-win32_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>ortp-config-win32.h</b> <a href="ortp-config-win32_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ortp_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>ortp.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ortp__srtp_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>ortp_srtp.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:payloadtype_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>payloadtype.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:port_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>port.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:posixtimer_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>posixtimer.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtcp_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtcp.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtcpparse_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtcpparse.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtpparse_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtpparse.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtpprofile_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtpprofile.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtpsession_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtpsession.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtpsession__inet_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtpsession_inet.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtpsession__priv_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtpsession_priv.h</b> <a href="rtpsession__priv_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtpsignaltable_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtpsignaltable.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtptimer_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtptimer.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:rtptimer_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>rtptimer.h</b> <a href="rtptimer_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:scheduler_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>scheduler.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:scheduler_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>scheduler.h</b> <a href="scheduler_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:sessionset_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>sessionset.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:str__utils_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>str_utils.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:stun_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>stun.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:stun__udp_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>stun_udp.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:telephonyevents_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>telephonyevents.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:utils_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>utils.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:utils_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>utils.h</b> <a href="utils_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:winrttimer_8h"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>winrttimer.h</b> <a href="winrttimer_8h_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:zrtp_8c"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>zrtp.c</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Jul 31 2013 14:43:09 for oRTP by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.3.1
</small></address>
</body>
</html>
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.3.1">
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="enumvalues_6a.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| Java |
<?php
class woocsvImport
{
public $importLog;
public $options;
public $header;
public $message;
public $options_default = array (
'seperator'=>',',
'skipfirstline'=>1,
'upload_dir' => '/csvimport/',
'blocksize' => 1,
'language' => 'EN',
'add_to_gallery' => 1,
'merge_products'=>1,
'add_to_categories'=>1,
'debug'=>0,
'match_by' => 'sku',
'roles' => array('shop_manager'),
'match_author_by' => 'login',
);
public $fields = array (
0 => 'sku',
1 => 'post_name',
2 => 'post_status',
3 => 'post_title',
4 => 'post_content',
5 => 'post_excerpt',
6 => 'category',
7 => 'tags',
8 => 'stock',
9 => 'price', /* ! 2.0.0 deprecated. Use regular_price or/and sale_price */
10 => 'regular_price',
11 => 'sale_price',
12 => 'weight' ,
13 => 'length',
14 => 'width' ,
15 => 'height' ,
//2.1.0 16 => 'images', //deprecated since 1.2.0, will be removed in 1.4.0
17 => 'tax_status',
18 => 'tax_class' ,
19 => 'stock_status', // instock, outofstock
20 => 'visibility', // visible, catelog, search, hidden
21 => 'backorders', // yes,no
22 => 'featured', // yes,no
23 => 'manage_stock', // yes,no
24 => 'featured_image',
25 => 'product_gallery',
26 => 'shipping_class',
27 => 'comment_status', //closed, open
28 => 'change_stock', // +1 -1 + 5 -8
29 =>'ID',
30 =>'ping_status',
31 => 'menu_order', // open,closed
32 => 'post_author', //user name or nice name of an user
);
public function __construct()
{
// activation hook
register_activation_hook( __FILE__, array($this, 'install' ));
//check install
$this->checkInstall();
//load options
$this->checkOptions();
//fill header
$this->fillHeader();
}
/* !1.2.7 plugins url */
public function plugin_url() {
if ( $this->plugin_url ) return $this->plugin_url;
return $this->plugin_url = untrailingslashit( plugins_url( '/', __FILE__ ) );
}
public function install()
{
$upload_dir = wp_upload_dir();
$dir = $upload_dir['basedir'] .'/csvimport/';
@mkdir($dir);
}
public function fillHeader() {
$header = get_option('woocsv-header');
if (!empty($header))
$this->header = $header;
}
public function checkOptions()
{
$update = false;
$options = get_option('woocsv-options');
$options_default = $this->options_default;
foreach ($options_default as $key=>$value) {
if (!isset($options[$key])) {
$options[$key] = $value;
$update = true;
}
}
if ($update) {
update_option('woocsv-options',$options);
}
$options = get_option('woocsv-options');
$this->options = $options;
}
public function checkInstall()
{
$message = $this->message;
if (!get_option('woocsv-options'))
$message .= __('Please save your settings!','woocsv-import');
$upload_dir = wp_upload_dir();
$dir = $upload_dir['basedir'] .'/csvimport/';
if (!is_dir($dir))
@mkdir($dir);
if (!is_writable($upload_dir['basedir'] .'/csvimport/'))
$message .= __('Upload directory is not writable, please check you permissions','woocsv-import');
$this->message = $message;
if ($message)
add_action( 'admin_notices', array($this, 'showWarning'));
}
public function showWarning()
{
global $current_screen;
if ($current_screen->parent_base == 'woocsv_import' )
echo '<div class="error"><p>'.$this->message.'</p></div>';
}
} | Java |
########################## NOTES ###############################################
# This files goal is to take CMake options found in kokkos_options.cmake but
# possibly set from elsewhere
# (see: trilinos/cmake/ProjectCOmpilerPostConfig.cmake)
# using CMake idioms and map them onto the KOKKOS_SETTINGS variables that gets
# passed to the kokkos makefile configuration:
# make -f ${CMAKE_SOURCE_DIR}/core/src/Makefile ${KOKKOS_SETTINGS} build-makefile-cmake-kokkos
# that generates KokkosCore_config.h and kokkos_generated_settings.cmake
# To understand how to form KOKKOS_SETTINGS, see
# <KOKKOS_PATH>/Makefile.kokkos
#-------------------------------------------------------------------------------
#------------------------------- GENERAL OPTIONS -------------------------------
#-------------------------------------------------------------------------------
# Ensure that KOKKOS_ARCH is in the ARCH_LIST
if (KOKKOS_ARCH MATCHES ",")
message("-- Detected a comma in: KOKKOS_ARCH=${KOKKOS_ARCH}")
message("-- Although we prefer KOKKOS_ARCH to be semicolon-delimited, we do allow")
message("-- comma-delimited values for compatibility with scripts (see github.com/trilinos/Trilinos/issues/2330)")
string(REPLACE "," ";" KOKKOS_ARCH "${KOKKOS_ARCH}")
message("-- Commas were changed to semicolons, now KOKKOS_ARCH=${KOKKOS_ARCH}")
endif()
foreach(arch ${KOKKOS_ARCH})
list(FIND KOKKOS_ARCH_LIST ${arch} indx)
if (indx EQUAL -1)
message(FATAL_ERROR "${arch} is not an accepted value for KOKKOS_ARCH."
" Please pick from these choices: ${KOKKOS_INTERNAL_ARCH_DOCSTR}")
endif ()
endforeach()
# KOKKOS_SETTINGS uses KOKKOS_ARCH
string(REPLACE ";" "," KOKKOS_GMAKE_ARCH "${KOKKOS_ARCH}")
# From Makefile.kokkos: Options: yes,no
if(${KOKKOS_ENABLE_DEBUG})
set(KOKKOS_GMAKE_DEBUG yes)
else()
set(KOKKOS_GMAKE_DEBUG no)
endif()
#------------------------------- KOKKOS_DEVICES --------------------------------
# Can have multiple devices
set(KOKKOS_DEVICESl)
foreach(devopt ${KOKKOS_DEVICES_LIST})
string(TOUPPER ${devopt} devoptuc)
if (${KOKKOS_ENABLE_${devoptuc}})
list(APPEND KOKKOS_DEVICESl ${devopt})
endif ()
endforeach()
# List needs to be comma-delmitted
string(REPLACE ";" "," KOKKOS_GMAKE_DEVICES "${KOKKOS_DEVICESl}")
#------------------------------- KOKKOS_OPTIONS --------------------------------
# From Makefile.kokkos: Options: aggressive_vectorization,disable_profiling,disable_deprecated_code
#compiler_warnings, aggressive_vectorization, disable_profiling, disable_dualview_modify_check, enable_profile_load_print
set(KOKKOS_OPTIONSl)
if(${KOKKOS_ENABLE_COMPILER_WARNINGS})
list(APPEND KOKKOS_OPTIONSl compiler_warnings)
endif()
if(${KOKKOS_ENABLE_AGGRESSIVE_VECTORIZATION})
list(APPEND KOKKOS_OPTIONSl aggressive_vectorization)
endif()
if(NOT ${KOKKOS_ENABLE_PROFILING})
list(APPEND KOKKOS_OPTIONSl disable_profiling)
endif()
if(NOT ${KOKKOS_ENABLE_DEPRECATED_CODE})
list(APPEND KOKKOS_OPTIONSl disable_deprecated_code)
endif()
if(NOT ${KOKKOS_ENABLE_DEBUG_DUALVIEW_MODIFY_CHECK})
list(APPEND KOKKOS_OPTIONSl disable_dualview_modify_check)
endif()
if(${KOKKOS_ENABLE_PROFILING_LOAD_PRINT})
list(APPEND KOKKOS_OPTIONSl enable_profile_load_print)
endif()
# List needs to be comma-delimitted
string(REPLACE ";" "," KOKKOS_GMAKE_OPTIONS "${KOKKOS_OPTIONSl}")
#------------------------------- KOKKOS_USE_TPLS -------------------------------
# Construct the Makefile options
set(KOKKOS_USE_TPLSl)
foreach(tplopt ${KOKKOS_USE_TPLS_LIST})
if (${KOKKOS_ENABLE_${tplopt}})
list(APPEND KOKKOS_USE_TPLSl ${KOKKOS_INTERNAL_${tplopt}})
endif ()
endforeach()
# List needs to be comma-delimitted
string(REPLACE ";" "," KOKKOS_GMAKE_USE_TPLS "${KOKKOS_USE_TPLSl}")
#------------------------------- KOKKOS_CUDA_OPTIONS ---------------------------
# Construct the Makefile options
set(KOKKOS_CUDA_OPTIONSl)
foreach(cudaopt ${KOKKOS_CUDA_OPTIONS_LIST})
if (${KOKKOS_ENABLE_CUDA_${cudaopt}})
list(APPEND KOKKOS_CUDA_OPTIONSl ${KOKKOS_INTERNAL_${cudaopt}})
endif ()
endforeach()
# List needs to be comma-delmitted
string(REPLACE ";" "," KOKKOS_GMAKE_CUDA_OPTIONS "${KOKKOS_CUDA_OPTIONSl}")
#------------------------------- PATH VARIABLES --------------------------------
# Want makefile to use same executables specified which means modifying
# the path so the $(shell ...) commands in the makefile see the right exec
# Also, the Makefile's use FOO_PATH naming scheme for -I/-L construction
#TODO: Makefile.kokkos allows this to be overwritten? ROCM_HCC_PATH
set(KOKKOS_INTERNAL_PATHS)
set(addpathl)
foreach(kvar IN LISTS KOKKOS_USE_TPLS_LIST ITEMS CUDA QTHREADS)
if(${KOKKOS_ENABLE_${kvar}})
if(DEFINED KOKKOS_${kvar}_DIR)
set(KOKKOS_INTERNAL_PATHS ${KOKKOS_INTERNAL_PATHS} "${kvar}_PATH=${KOKKOS_${kvar}_DIR}")
if(IS_DIRECTORY ${KOKKOS_${kvar}_DIR}/bin)
list(APPEND addpathl ${KOKKOS_${kvar}_DIR}/bin)
endif()
endif()
endif()
endforeach()
# Path env is : delimitted
string(REPLACE ";" ":" KOKKOS_INTERNAL_ADDTOPATH "${addpathl}")
######################### SET KOKKOS_SETTINGS ##################################
# Set the KOKKOS_SETTINGS String -- this is the primary communication with the
# makefile configuration. See Makefile.kokkos
set(KOKKOS_SETTINGS KOKKOS_SRC_PATH=${KOKKOS_SRC_PATH})
set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} KOKKOS_PATH=${KOKKOS_PATH})
set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} KOKKOS_INSTALL_PATH=${CMAKE_INSTALL_PREFIX})
# Form of KOKKOS_foo=$KOKKOS_foo
foreach(kvar ARCH;DEVICES;DEBUG;OPTIONS;CUDA_OPTIONS;USE_TPLS)
if(DEFINED KOKKOS_GMAKE_${kvar})
if (NOT "${KOKKOS_GMAKE_${kvar}}" STREQUAL "")
set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} KOKKOS_${kvar}=${KOKKOS_GMAKE_${kvar}})
endif()
endif()
endforeach()
# Form of VAR=VAL
#TODO: Makefile supports MPICH_CXX, OMPI_CXX as well
foreach(ovar CXX;CXXFLAGS;LDFLAGS)
if(DEFINED ${ovar})
if (NOT "${${ovar}}" STREQUAL "")
set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} ${ovar}=${${ovar}})
endif()
endif()
endforeach()
# Finally, do the paths
if (NOT "${KOKKOS_INTERNAL_PATHS}" STREQUAL "")
set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} ${KOKKOS_INTERNAL_PATHS})
endif()
if (NOT "${KOKKOS_INTERNAL_ADDTOPATH}" STREQUAL "")
set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} "PATH=\"${KOKKOS_INTERNAL_ADDTOPATH}:$ENV{PATH}\"")
endif()
# Final form that gets passed to make
set(KOKKOS_SETTINGS env ${KOKKOS_SETTINGS})
############################ PRINT CONFIGURE STATUS ############################
if(KOKKOS_CMAKE_VERBOSE)
message(STATUS "")
message(STATUS "****************** Kokkos Settings ******************")
message(STATUS "Execution Spaces")
if(KOKKOS_ENABLE_CUDA)
message(STATUS " Device Parallel: Cuda")
else()
message(STATUS " Device Parallel: None")
endif()
if(KOKKOS_ENABLE_OPENMP)
message(STATUS " Host Parallel: OpenMP")
elseif(KOKKOS_ENABLE_PTHREAD)
message(STATUS " Host Parallel: Pthread")
elseif(KOKKOS_ENABLE_QTHREADS)
message(STATUS " Host Parallel: Qthreads")
else()
message(STATUS " Host Parallel: None")
endif()
if(KOKKOS_ENABLE_SERIAL)
message(STATUS " Host Serial: Serial")
else()
message(STATUS " Host Serial: None")
endif()
message(STATUS "")
message(STATUS "Architectures:")
message(STATUS " ${KOKKOS_GMAKE_ARCH}")
message(STATUS "")
message(STATUS "Enabled options")
if(KOKKOS_SEPARATE_LIBS)
message(STATUS " KOKKOS_SEPARATE_LIBS")
endif()
foreach(opt IN LISTS KOKKOS_INTERNAL_ENABLE_OPTIONS_LIST)
string(TOUPPER ${opt} OPT)
if (KOKKOS_ENABLE_${OPT})
message(STATUS " KOKKOS_ENABLE_${OPT}")
endif()
endforeach()
if(KOKKOS_ENABLE_CUDA)
if(KOKKOS_CUDA_DIR)
message(STATUS " KOKKOS_CUDA_DIR: ${KOKKOS_CUDA_DIR}")
endif()
endif()
if(KOKKOS_QTHREADS_DIR)
message(STATUS " KOKKOS_QTHREADS_DIR: ${KOKKOS_QTHREADS_DIR}")
endif()
if(KOKKOS_HWLOC_DIR)
message(STATUS " KOKKOS_HWLOC_DIR: ${KOKKOS_HWLOC_DIR}")
endif()
if(KOKKOS_MEMKIND_DIR)
message(STATUS " KOKKOS_MEMKIND_DIR: ${KOKKOS_MEMKIND_DIR}")
endif()
message(STATUS "")
message(STATUS "Final kokkos settings variable:")
message(STATUS " ${KOKKOS_SETTINGS}")
message(STATUS "*****************************************************")
message(STATUS "")
endif()
| Java |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Tests\Extension\Core\Type;
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
use Symfony\Component\Form\FormError;
use Symfony\Component\Intl\Util\IntlTestHelper;
class DateTypeTest extends BaseTypeTest
{
const TESTED_TYPE = 'date';
private $defaultTimezone;
protected function setUp()
{
parent::setUp();
$this->defaultTimezone = date_default_timezone_get();
}
protected function tearDown()
{
date_default_timezone_set($this->defaultTimezone);
\Locale::setDefault('en');
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testInvalidWidgetOption()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'fake_widget',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testInvalidInputOption()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'input' => 'fake_input',
));
}
public function testSubmitFromSingleTextDateTimeWithDefaultFormat()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'datetime',
));
$form->submit('2010-06-02');
$this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
$this->assertEquals('2010-06-02', $form->getViewData());
}
public function testSubmitFromSingleTextDateTimeWithCustomFormat()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'datetime',
'format' => 'yyyy',
));
$form->submit('2010');
$this->assertDateTimeEquals(new \DateTime('2010-01-01 UTC'), $form->getData());
$this->assertEquals('2010', $form->getViewData());
}
public function testSubmitFromSingleTextDateTime()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'datetime',
));
$form->submit('2.6.2010');
$this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromSingleTextString()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'string',
));
$form->submit('2.6.2010');
$this->assertEquals('2010-06-02', $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromSingleTextTimestamp()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'timestamp',
));
$form->submit('2.6.2010');
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertEquals($dateTime->format('U'), $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromSingleTextRaw()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'single_text',
'input' => 'array',
));
$form->submit('2.6.2010');
$output = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$this->assertEquals($output, $form->getData());
$this->assertEquals('02.06.2010', $form->getViewData());
}
public function testSubmitFromText()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'text',
));
$text = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$form->submit($text);
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertDateTimeEquals($dateTime, $form->getData());
$this->assertEquals($text, $form->getViewData());
}
public function testSubmitFromChoice()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
'years' => array(2010),
));
$text = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$form->submit($text);
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertDateTimeEquals($dateTime, $form->getData());
$this->assertEquals($text, $form->getViewData());
}
public function testSubmitFromChoiceEmpty()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
'required' => false,
));
$text = array(
'day' => '',
'month' => '',
'year' => '',
);
$form->submit($text);
$this->assertNull($form->getData());
$this->assertEquals($text, $form->getViewData());
}
public function testSubmitFromInputDateTimeDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'datetime',
));
$form->submit('06*2010*02');
$this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
public function testSubmitFromInputStringDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'string',
));
$form->submit('06*2010*02');
$this->assertEquals('2010-06-02', $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
public function testSubmitFromInputTimestampDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'timestamp',
));
$form->submit('06*2010*02');
$dateTime = new \DateTime('2010-06-02 UTC');
$this->assertEquals($dateTime->format('U'), $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
public function testSubmitFromInputRawDifferentPattern()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'format' => 'MM*yyyy*dd',
'widget' => 'single_text',
'input' => 'array',
));
$form->submit('06*2010*02');
$output = array(
'day' => '2',
'month' => '6',
'year' => '2010',
);
$this->assertEquals($output, $form->getData());
$this->assertEquals('06*2010*02', $form->getViewData());
}
/**
* @dataProvider provideDateFormats
*/
public function testDatePatternWithFormatOption($format, $pattern)
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => $format,
))
->createView();
$this->assertEquals($pattern, $view->vars['date_pattern']);
}
public function provideDateFormats()
{
return array(
array('dMy', '{{ day }}{{ month }}{{ year }}'),
array('d-M-yyyy', '{{ day }}-{{ month }}-{{ year }}'),
array('M d y', '{{ month }} {{ day }} {{ year }}'),
);
}
/**
* This test is to check that the strings '0', '1', '2', '3' are not accepted
* as valid IntlDateFormatter constants for FULL, LONG, MEDIUM or SHORT respectively.
*
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfFormatIsNoPattern()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'format' => '0',
'widget' => 'single_text',
'input' => 'string',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
* @expectedExceptionMessage The "format" option should contain the letters "y", "M" and "d". Its current value is "yy".
*/
public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(6, 7),
'format' => 'yy',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
* @expectedExceptionMessage The "format" option should contain the letters "y", "M" or "d". Its current value is "wrong".
*/
public function testThrowExceptionIfFormatMissesYearMonthAndDayWithSingleTextWidget()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
'format' => 'wrong',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfFormatIsNoConstant()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'format' => 105,
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfFormatIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'format' => array(),
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfYearsIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'years' => 'bad value',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfMonthsIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'months' => 'bad value',
));
}
/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testThrowExceptionIfDaysIsInvalid()
{
$this->factory->create(static::TESTED_TYPE, null, array(
'days' => 'bad value',
));
}
public function testSetDataWithNegativeTimezoneOffsetStringInput()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'America/New_York',
'input' => 'string',
'widget' => 'single_text',
));
$form->setData('2010-06-02');
// 2010-06-02 00:00:00 UTC
// 2010-06-01 20:00:00 UTC-4
$this->assertEquals('01.06.2010', $form->getViewData());
}
public function testSetDataWithNegativeTimezoneOffsetDateTimeInput()
{
// we test against "de_DE", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_DE');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::MEDIUM,
'model_timezone' => 'UTC',
'view_timezone' => 'America/New_York',
'input' => 'datetime',
'widget' => 'single_text',
));
$dateTime = new \DateTime('2010-06-02 UTC');
$form->setData($dateTime);
// 2010-06-02 00:00:00 UTC
// 2010-06-01 20:00:00 UTC-4
$this->assertDateTimeEquals($dateTime, $form->getData());
$this->assertEquals('01.06.2010', $form->getViewData());
}
public function testYearsOption()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'years' => array(2010, 2011),
));
$view = $form->createView();
$this->assertEquals(array(
new ChoiceView('2010', '2010', '2010'),
new ChoiceView('2011', '2011', '2011'),
), $view['year']->vars['choices']);
}
public function testMonthsOption()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(6, 7),
'format' => \IntlDateFormatter::SHORT,
));
$view = $form->createView();
$this->assertEquals(array(
new ChoiceView(6, '6', '06'),
new ChoiceView(7, '7', '07'),
), $view['month']->vars['choices']);
}
public function testMonthsOptionShortFormat()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, '57.1');
\Locale::setDefault('de_AT');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(1, 4),
'format' => 'dd.MMM.yy',
));
$view = $form->createView();
$this->assertEquals(array(
new ChoiceView(1, '1', 'Jän.'),
new ChoiceView(4, '4', 'Apr.'),
), $view['month']->vars['choices']);
}
public function testMonthsOptionLongFormat()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(1, 4),
'format' => 'dd.MMMM.yy',
))
->createView();
$this->assertEquals(array(
new ChoiceView(1, '1', 'Jänner'),
new ChoiceView(4, '4', 'April'),
), $view['month']->vars['choices']);
}
public function testMonthsOptionLongFormatWithDifferentTimezone()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'months' => array(1, 4),
'format' => 'dd.MMMM.yy',
))
->createView();
$this->assertEquals(array(
new ChoiceView(1, '1', 'Jänner'),
new ChoiceView(4, '4', 'April'),
), $view['month']->vars['choices']);
}
public function testIsDayWithinRangeReturnsTrueIfWithin()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'days' => array(6, 7),
))
->createView();
$this->assertEquals(array(
new ChoiceView(6, '6', '06'),
new ChoiceView(7, '7', '07'),
), $view['day']->vars['choices']);
}
public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyEmpty()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
));
$form->submit(array(
'day' => '',
'month' => '',
'year' => '',
));
$this->assertTrue($form->isSynchronized());
}
public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyFilled()
{
$form = $this->factory->create(static::TESTED_TYPE, new \DateTime(), array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
));
$form->submit(array(
'day' => '1',
'month' => '6',
'year' => '2010',
));
$this->assertTrue($form->isSynchronized());
}
public function testIsSynchronizedReturnsFalseIfChoiceAndDayEmpty()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'model_timezone' => 'UTC',
'view_timezone' => 'UTC',
'widget' => 'choice',
));
$form->submit(array(
'day' => '',
'month' => '6',
'year' => '2010',
));
$this->assertFalse($form->isSynchronized());
}
public function testPassDatePatternToView()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE)
->createView();
$this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
}
public function testPassDatePatternToViewDifferentFormat()
{
// we test against "de_AT", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('de_AT');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => \IntlDateFormatter::LONG,
))
->createView();
$this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
}
public function testPassDatePatternToViewDifferentPattern()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => 'MMyyyydd',
))
->createView();
$this->assertSame('{{ month }}{{ year }}{{ day }}', $view->vars['date_pattern']);
}
public function testPassDatePatternToViewDifferentPatternWithSeparators()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'format' => 'MM*yyyy*dd',
))
->createView();
$this->assertSame('{{ month }}*{{ year }}*{{ day }}', $view->vars['date_pattern']);
}
public function testDontPassDatePatternIfText()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertFalse(isset($view->vars['date_pattern']));
}
public function testDatePatternFormatWithQuotedStrings()
{
// we test against "es_ES", so we need the full implementation
IntlTestHelper::requireFullIntl($this, false);
\Locale::setDefault('es_ES');
$view = $this->factory->create(static::TESTED_TYPE, null, array(
// EEEE, d 'de' MMMM 'de' y
'format' => \IntlDateFormatter::FULL,
))
->createView();
$this->assertEquals('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
}
public function testPassWidgetToView()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertSame('single_text', $view->vars['widget']);
}
public function testInitializeWithDateTime()
{
// Throws an exception if "data_class" option is not explicitly set
// to null in the type
$this->assertInstanceOf('Symfony\Component\Form\FormInterface', $this->factory->create(static::TESTED_TYPE, new \DateTime()));
}
public function testSingleTextWidgetShouldUseTheRightInputType()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertEquals('date', $view->vars['type']);
}
public function testPassDefaultPlaceholderToViewIfNotRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => false,
))
->createView();
$this->assertSame('', $view['year']->vars['placeholder']);
$this->assertSame('', $view['month']->vars['placeholder']);
$this->assertSame('', $view['day']->vars['placeholder']);
}
public function testPassNoPlaceholderToViewIfRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => true,
))
->createView();
$this->assertNull($view['year']->vars['placeholder']);
$this->assertNull($view['month']->vars['placeholder']);
$this->assertNull($view['day']->vars['placeholder']);
}
public function testPassPlaceholderAsString()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'placeholder' => 'Empty',
))
->createView();
$this->assertSame('Empty', $view['year']->vars['placeholder']);
$this->assertSame('Empty', $view['month']->vars['placeholder']);
$this->assertSame('Empty', $view['day']->vars['placeholder']);
}
/**
* @group legacy
*/
public function testPassEmptyValueBC()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'empty_value' => 'Empty',
))
->createView();
$this->assertSame('Empty', $view['year']->vars['placeholder']);
$this->assertSame('Empty', $view['month']->vars['placeholder']);
$this->assertSame('Empty', $view['day']->vars['placeholder']);
$this->assertSame('Empty', $view['year']->vars['empty_value']);
$this->assertSame('Empty', $view['month']->vars['empty_value']);
$this->assertSame('Empty', $view['day']->vars['empty_value']);
}
public function testPassPlaceholderAsArray()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'placeholder' => array(
'year' => 'Empty year',
'month' => 'Empty month',
'day' => 'Empty day',
),
))
->createView();
$this->assertSame('Empty year', $view['year']->vars['placeholder']);
$this->assertSame('Empty month', $view['month']->vars['placeholder']);
$this->assertSame('Empty day', $view['day']->vars['placeholder']);
}
public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => false,
'placeholder' => array(
'year' => 'Empty year',
'day' => 'Empty day',
),
))
->createView();
$this->assertSame('Empty year', $view['year']->vars['placeholder']);
$this->assertSame('', $view['month']->vars['placeholder']);
$this->assertSame('Empty day', $view['day']->vars['placeholder']);
}
public function testPassPlaceholderAsPartialArrayAddNullIfRequired()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'required' => true,
'placeholder' => array(
'year' => 'Empty year',
'day' => 'Empty day',
),
))
->createView();
$this->assertSame('Empty year', $view['year']->vars['placeholder']);
$this->assertNull($view['month']->vars['placeholder']);
$this->assertSame('Empty day', $view['day']->vars['placeholder']);
}
public function testPassHtml5TypeIfSingleTextAndHtml5Format()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
))
->createView();
$this->assertSame('date', $view->vars['type']);
}
public function testDontPassHtml5TypeIfHtml5NotAllowed()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
'html5' => false,
))
->createView();
$this->assertFalse(isset($view->vars['type']));
}
public function testDontPassHtml5TypeIfNotHtml5Format()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
'format' => \IntlDateFormatter::MEDIUM,
))
->createView();
$this->assertFalse(isset($view->vars['type']));
}
public function testDontPassHtml5TypeIfNotSingleText()
{
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'text',
))
->createView();
$this->assertFalse(isset($view->vars['type']));
}
public function provideCompoundWidgets()
{
return array(
array('text'),
array('choice'),
);
}
/**
* @dataProvider provideCompoundWidgets
*/
public function testYearErrorsBubbleUp($widget)
{
$error = new FormError('Invalid!');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => $widget,
));
$form['year']->addError($error);
$this->assertSame(array(), iterator_to_array($form['year']->getErrors()));
$this->assertSame(array($error), iterator_to_array($form->getErrors()));
}
/**
* @dataProvider provideCompoundWidgets
*/
public function testMonthErrorsBubbleUp($widget)
{
$error = new FormError('Invalid!');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => $widget,
));
$form['month']->addError($error);
$this->assertSame(array(), iterator_to_array($form['month']->getErrors()));
$this->assertSame(array($error), iterator_to_array($form->getErrors()));
}
/**
* @dataProvider provideCompoundWidgets
*/
public function testDayErrorsBubbleUp($widget)
{
$error = new FormError('Invalid!');
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => $widget,
));
$form['day']->addError($error);
$this->assertSame(array(), iterator_to_array($form['day']->getErrors()));
$this->assertSame(array($error), iterator_to_array($form->getErrors()));
}
public function testYearsFor32BitsMachines()
{
if (4 !== PHP_INT_SIZE) {
$this->markTestSkipped('PHP 32 bit is required.');
}
$view = $this->factory->create(static::TESTED_TYPE, null, array(
'years' => range(1900, 2040),
))
->createView();
$listChoices = array();
foreach (range(1902, 2037) as $y) {
$listChoices[] = new ChoiceView($y, $y, $y);
}
$this->assertEquals($listChoices, $view['year']->vars['choices']);
}
public function testSubmitNull($expected = null, $norm = null, $view = null)
{
parent::testSubmitNull($expected, $norm, array('year' => '', 'month' => '', 'day' => ''));
}
public function testSubmitNullWithSingleText()
{
$form = $this->factory->create(static::TESTED_TYPE, null, array(
'widget' => 'single_text',
));
$form->submit(null);
$this->assertNull($form->getData());
$this->assertNull($form->getNormData());
$this->assertSame('', $form->getViewData());
}
}
| Java |
/*
* CCITT Fax Group 3 and 4 decompression
* Copyright (c) 2008 Konstantin Shishkov
*
* This file is part of Libav.
*
* Libav 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.
*
* Libav 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 Libav; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* CCITT Fax Group 3 and 4 decompression
* @file
* @author Konstantin Shishkov
*/
#ifndef AVCODEC_FAXCOMPR_H
#define AVCODEC_FAXCOMPR_H
#include "avcodec.h"
#include "tiff.h"
/**
* initialize upacker code
*/
void ff_ccitt_unpack_init(void);
/**
* unpack data compressed with CCITT Group 3 1/2-D or Group 4 method
*/
int ff_ccitt_unpack(AVCodecContext *avctx,
const uint8_t *src, int srcsize,
uint8_t *dst, int height, int stride,
enum TiffCompr compr, int opts);
#endif /* AVCODEC_FAXCOMPR_H */
| Java |
module Katello
module UINotifications
module Subscriptions
class SCADisableSuccess < UINotifications::AbstractNotification
private
def blueprint
@blueprint ||= NotificationBlueprint.find_by(name: 'sca_disable_success')
end
end
end
end
end
| Java |
<?php
namespace TYPO3\CMS\Workspaces\Controller;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Workspaces\Service\WorkspaceService;
/**
* Review controller.
*/
class ReviewController extends AbstractController
{
/**
* Set up the doc header properly here
*
* @param ViewInterface $view
*/
protected function initializeView(ViewInterface $view)
{
parent::initializeView($view);
$this->registerButtons();
$this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
}
/**
* Registers the DocHeader buttons
*/
protected function registerButtons()
{
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$currentRequest = $this->request;
$moduleName = $currentRequest->getPluginName();
$getVars = $this->request->getArguments();
$extensionName = $currentRequest->getControllerExtensionName();
if (count($getVars) === 0) {
$modulePrefix = strtolower('tx_' . $extensionName . '_' . $moduleName);
$getVars = array('id', 'M', $modulePrefix);
}
$shortcutButton = $buttonBar->makeShortcutButton()
->setModuleName($moduleName)
->setGetVariables($getVars);
$buttonBar->addButton($shortcutButton);
}
/**
* Renders the review module user dependent with all workspaces.
* The module will show all records of one workspace.
*
* @return void
*/
public function indexAction()
{
/** @var WorkspaceService $wsService */
$wsService = GeneralUtility::makeInstance(WorkspaceService::class);
$this->view->assign('showGrid', !($GLOBALS['BE_USER']->workspace === 0 && !$GLOBALS['BE_USER']->isAdmin()));
$this->view->assign('showAllWorkspaceTab', true);
$this->view->assign('pageUid', GeneralUtility::_GP('id'));
if (GeneralUtility::_GP('id')) {
$pageRecord = BackendUtility::getRecord('pages', GeneralUtility::_GP('id'));
if ($pageRecord) {
$this->view->getModuleTemplate()->getDocHeaderComponent()->setMetaInformation($pageRecord);
$this->view->assign('pageTitle', BackendUtility::getRecordTitle('pages', $pageRecord));
}
}
$this->view->assign('showLegend', !($GLOBALS['BE_USER']->workspace === 0 && !$GLOBALS['BE_USER']->isAdmin()));
$wsList = $wsService->getAvailableWorkspaces();
$activeWorkspace = $GLOBALS['BE_USER']->workspace;
$performWorkspaceSwitch = false;
// Only admins see multiple tabs, we decided to use it this
// way for usability reasons. Regular users might be confused
// by switching workspaces with the tabs in a module.
if (!$GLOBALS['BE_USER']->isAdmin()) {
$wsCur = array($activeWorkspace => true);
$wsList = array_intersect_key($wsList, $wsCur);
} else {
if ((string)GeneralUtility::_GP('workspace') !== '') {
$switchWs = (int)GeneralUtility::_GP('workspace');
if (in_array($switchWs, array_keys($wsList)) && $activeWorkspace != $switchWs) {
$activeWorkspace = $switchWs;
$GLOBALS['BE_USER']->setWorkspace($activeWorkspace);
$performWorkspaceSwitch = true;
BackendUtility::setUpdateSignal('updatePageTree');
} elseif ($switchWs == WorkspaceService::SELECT_ALL_WORKSPACES) {
$this->redirect('fullIndex');
}
}
}
$this->pageRenderer->addInlineSetting('Workspaces', 'isLiveWorkspace', (int)$GLOBALS['BE_USER']->workspace === 0);
$this->pageRenderer->addInlineSetting('Workspaces', 'workspaceTabs', $this->prepareWorkspaceTabs($wsList, $activeWorkspace));
$this->pageRenderer->addInlineSetting('Workspaces', 'activeWorkspaceId', $activeWorkspace);
$this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit'));
$this->view->assign('performWorkspaceSwitch', $performWorkspaceSwitch);
$this->view->assign('workspaceList', $wsList);
$this->view->assign('activeWorkspaceUid', $activeWorkspace);
$this->view->assign('activeWorkspaceTitle', WorkspaceService::getWorkspaceTitle($activeWorkspace));
if ($wsService->canCreatePreviewLink(GeneralUtility::_GP('id'), $activeWorkspace)) {
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$iconFactory = $this->view->getModuleTemplate()->getIconFactory();
$showButton = $buttonBar->makeLinkButton()
->setHref('#')
->setOnClick('TYPO3.Workspaces.Actions.generateWorkspacePreviewLinksForAllLanguages();return false;')
->setTitle($this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang.xlf:tooltip.generatePagePreview'))
->setIcon($iconFactory->getIcon('module-workspaces-action-preview-link', Icon::SIZE_SMALL));
$buttonBar->addButton($showButton);
}
$this->view->assign('showPreviewLink', $wsService->canCreatePreviewLink(GeneralUtility::_GP('id'), $activeWorkspace));
$GLOBALS['BE_USER']->setAndSaveSessionData('tx_workspace_activeWorkspace', $activeWorkspace);
}
/**
* Renders the review module user dependent.
* The module will show all records of all workspaces.
*
* @return void
*/
public function fullIndexAction()
{
$wsService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
$wsList = $wsService->getAvailableWorkspaces();
if (!$GLOBALS['BE_USER']->isAdmin()) {
$activeWorkspace = $GLOBALS['BE_USER']->workspace;
$wsCur = array($activeWorkspace => true);
$wsList = array_intersect_key($wsList, $wsCur);
}
$this->pageRenderer->addInlineSetting('Workspaces', 'workspaceTabs', $this->prepareWorkspaceTabs($wsList, WorkspaceService::SELECT_ALL_WORKSPACES));
$this->pageRenderer->addInlineSetting('Workspaces', 'activeWorkspaceId', WorkspaceService::SELECT_ALL_WORKSPACES);
$this->view->assign('pageUid', GeneralUtility::_GP('id'));
$this->view->assign('showGrid', true);
$this->view->assign('showLegend', true);
$this->view->assign('showAllWorkspaceTab', true);
$this->view->assign('workspaceList', $wsList);
$this->view->assign('activeWorkspaceUid', WorkspaceService::SELECT_ALL_WORKSPACES);
$this->view->assign('showPreviewLink', false);
$GLOBALS['BE_USER']->setAndSaveSessionData('tx_workspace_activeWorkspace', WorkspaceService::SELECT_ALL_WORKSPACES);
// set flag for javascript
$this->pageRenderer->addInlineSetting('Workspaces', 'allView', '1');
}
/**
* Renders the review module for a single page. This is used within the
* workspace-preview frame.
*
* @return void
*/
public function singleIndexAction()
{
$wsService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
$wsList = $wsService->getAvailableWorkspaces();
$activeWorkspace = $GLOBALS['BE_USER']->workspace;
$wsCur = array($activeWorkspace => true);
$wsList = array_intersect_key($wsList, $wsCur);
$backendDomain = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
$this->view->assign('pageUid', GeneralUtility::_GP('id'));
$this->view->assign('showGrid', true);
$this->view->assign('showAllWorkspaceTab', false);
$this->view->assign('workspaceList', $wsList);
$this->view->assign('backendDomain', $backendDomain);
// Setting the document.domain early before JavScript
// libraries are loaded, try to access top frame reference
// and possibly run into some CORS issue
$this->pageRenderer->setMetaCharsetTag(
$this->pageRenderer->getMetaCharsetTag() . LF
. GeneralUtility::wrapJS('document.domain = ' . GeneralUtility::quoteJSvalue($backendDomain) . ';')
);
$this->pageRenderer->addInlineSetting('Workspaces', 'singleView', '1');
}
/**
* Initializes the controller before invoking an action method.
*
* @return void
*/
protected function initializeAction()
{
parent::initializeAction();
$backendRelPath = ExtensionManagementUtility::extRelPath('backend');
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/ExtDirect.StateProvider.js');
if (WorkspaceService::isOldStyleWorkspaceUsed()) {
$flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $GLOBALS['LANG']->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang.xlf:warning.oldStyleWorkspaceInUser'), '', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING);
/** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
$flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
/** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
$defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
$defaultFlashMessageQueue->enqueue($flashMessage);
}
$this->pageRenderer->loadExtJS();
$states = $GLOBALS['BE_USER']->uc['moduleData']['Workspaces']['States'];
$this->pageRenderer->addInlineSetting('Workspaces', 'States', $states);
// Load JavaScript:
$this->pageRenderer->addExtDirectCode(array(
'TYPO3.Workspaces'
));
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.grid.RowExpander.js');
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.app.SearchField.js');
$this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.ux.FitToParent.js');
$resourcePath = ExtensionManagementUtility::extRelPath('workspaces') . 'Resources/Public/JavaScript/';
// @todo Integrate additional stylesheet resources
$this->pageRenderer->addCssFile($resourcePath . 'gridfilters/css/GridFilters.css');
$this->pageRenderer->addCssFile($resourcePath . 'gridfilters/css/RangeMenu.css');
$filters = array(
$resourcePath . 'gridfilters/menu/RangeMenu.js',
$resourcePath . 'gridfilters/menu/ListMenu.js',
$resourcePath . 'gridfilters/GridFilters.js',
$resourcePath . 'gridfilters/filter/Filter.js',
$resourcePath . 'gridfilters/filter/StringFilter.js',
$resourcePath . 'gridfilters/filter/DateFilter.js',
$resourcePath . 'gridfilters/filter/ListFilter.js',
$resourcePath . 'gridfilters/filter/NumericFilter.js',
$resourcePath . 'gridfilters/filter/BooleanFilter.js',
$resourcePath . 'gridfilters/filter/BooleanFilter.js',
);
$custom = $this->getAdditionalResourceService()->getJavaScriptResources();
$resources = array(
$resourcePath . 'Component/RowDetailTemplate.js',
$resourcePath . 'Component/RowExpander.js',
$resourcePath . 'Component/TabPanel.js',
$resourcePath . 'Store/mainstore.js',
$resourcePath . 'configuration.js',
$resourcePath . 'helpers.js',
$resourcePath . 'actions.js',
$resourcePath . 'component.js',
$resourcePath . 'toolbar.js',
$resourcePath . 'grid.js',
$resourcePath . 'workspaces.js'
);
$javaScriptFiles = array_merge($filters, $custom, $resources);
foreach ($javaScriptFiles as $javaScriptFile) {
$this->pageRenderer->addJsFile($javaScriptFile);
}
foreach ($this->getAdditionalResourceService()->getLocalizationResources() as $localizationResource) {
$this->pageRenderer->addInlineLanguageLabelFile($localizationResource);
}
$this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit'));
$this->pageRenderer->addInlineSetting('RecordHistory', 'moduleUrl', BackendUtility::getModuleUrl('record_history'));
}
/**
* Prepares available workspace tabs.
*
* @param array $workspaceList
* @param int $activeWorkspace
* @return array
*/
protected function prepareWorkspaceTabs(array $workspaceList, $activeWorkspace)
{
$tabs = array();
if ($activeWorkspace !== WorkspaceService::SELECT_ALL_WORKSPACES) {
$tabs[] = array(
'title' => $workspaceList[$activeWorkspace],
'itemId' => 'workspace-' . $activeWorkspace,
'workspaceId' => $activeWorkspace,
'triggerUrl' => $this->getModuleUri($activeWorkspace),
);
}
$tabs[] = array(
'title' => 'All workspaces',
'itemId' => 'workspace-' . WorkspaceService::SELECT_ALL_WORKSPACES,
'workspaceId' => WorkspaceService::SELECT_ALL_WORKSPACES,
'triggerUrl' => $this->getModuleUri(WorkspaceService::SELECT_ALL_WORKSPACES),
);
foreach ($workspaceList as $workspaceId => $workspaceTitle) {
if ($workspaceId === $activeWorkspace) {
continue;
}
$tabs[] = array(
'title' => $workspaceTitle,
'itemId' => 'workspace-' . $workspaceId,
'workspaceId' => $workspaceId,
'triggerUrl' => $this->getModuleUri($workspaceId),
);
}
return $tabs;
}
/**
* Gets the module URI.
*
* @param int $workspaceId
* @return string
*/
protected function getModuleUri($workspaceId)
{
$parameters = array(
'id' => (int)$this->pageId,
'workspace' => (int)$workspaceId,
);
// The "all workspaces" tab is handled in fullIndexAction
// which is required as additional GET parameter in the URI then
if ($workspaceId === WorkspaceService::SELECT_ALL_WORKSPACES) {
$this->uriBuilder->reset()->uriFor('fullIndex');
$parameters = array_merge($parameters, $this->uriBuilder->getArguments());
}
return BackendUtility::getModuleUrl('web_WorkspacesWorkspaces', $parameters);
}
/**
* @return \TYPO3\CMS\Lang\LanguageService
*/
protected function getLanguageService()
{
return $GLOBALS['LANG'];
}
}
| Java |
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef MDSS_DSI_H
#define MDSS_DSI_H
#include <linux/list.h>
#include <linux/mdss_io_util.h>
#include <mach/scm-io.h>
#include <linux/irqreturn.h>
#include <linux/pinctrl/consumer.h>
#include "mdss_panel.h"
#include "mdss_dsi_cmd.h"
#define MMSS_SERDES_BASE_PHY 0x04f01000 /* mmss (De)Serializer CFG */
#define MIPI_OUTP(addr, data) writel_relaxed((data), (addr))
#define MIPI_INP(addr) readl_relaxed(addr)
#define MIPI_OUTP_SECURE(addr, data) writel_relaxed((data), (addr))
#define MIPI_INP_SECURE(addr) readl_relaxed(addr)
#define MIPI_DSI_PRIM 1
#define MIPI_DSI_SECD 2
#define MIPI_DSI_PANEL_VGA 0
#define MIPI_DSI_PANEL_WVGA 1
#define MIPI_DSI_PANEL_WVGA_PT 2
#define MIPI_DSI_PANEL_FWVGA_PT 3
#define MIPI_DSI_PANEL_WSVGA_PT 4
#define MIPI_DSI_PANEL_QHD_PT 5
#define MIPI_DSI_PANEL_WXGA 6
#define MIPI_DSI_PANEL_WUXGA 7
#define MIPI_DSI_PANEL_720P_PT 8
#define DSI_PANEL_MAX 8
enum { /* mipi dsi panel */
DSI_VIDEO_MODE,
DSI_CMD_MODE,
};
enum {
ST_DSI_CLK_OFF,
ST_DSI_SUSPEND,
ST_DSI_RESUME,
ST_DSI_PLAYING,
ST_DSI_NUM
};
enum {
EV_DSI_UPDATE,
EV_DSI_DONE,
EV_DSI_TOUT,
EV_DSI_NUM
};
enum {
LANDSCAPE = 1,
PORTRAIT = 2,
};
enum dsi_trigger_type {
DSI_CMD_MODE_DMA,
DSI_CMD_MODE_MDP,
};
enum dsi_panel_bl_ctrl {
UNKNOWN_CTRL,
BL_PWM,
BL_WLED,
BL_DCS_CMD,
BL_EXTERNAL,
};
enum dsi_ctrl_op_mode {
DSI_LP_MODE,
DSI_HS_MODE,
};
enum dsi_lane_map_type {
DSI_LANE_MAP_0123,
DSI_LANE_MAP_3012,
DSI_LANE_MAP_2301,
DSI_LANE_MAP_1230,
DSI_LANE_MAP_0321,
DSI_LANE_MAP_1032,
DSI_LANE_MAP_2103,
DSI_LANE_MAP_3210,
};
#define CTRL_STATE_UNKNOWN 0x00
#define CTRL_STATE_PANEL_INIT BIT(0)
#define CTRL_STATE_MDP_ACTIVE BIT(1)
#define DSI_NON_BURST_SYNCH_PULSE 0
#define DSI_NON_BURST_SYNCH_EVENT 1
#define DSI_BURST_MODE 2
#define DSI_RGB_SWAP_RGB 0
#define DSI_RGB_SWAP_RBG 1
#define DSI_RGB_SWAP_BGR 2
#define DSI_RGB_SWAP_BRG 3
#define DSI_RGB_SWAP_GRB 4
#define DSI_RGB_SWAP_GBR 5
#define DSI_VIDEO_DST_FORMAT_RGB565 0
#define DSI_VIDEO_DST_FORMAT_RGB666 1
#define DSI_VIDEO_DST_FORMAT_RGB666_LOOSE 2
#define DSI_VIDEO_DST_FORMAT_RGB888 3
#define DSI_CMD_DST_FORMAT_RGB111 0
#define DSI_CMD_DST_FORMAT_RGB332 3
#define DSI_CMD_DST_FORMAT_RGB444 4
#define DSI_CMD_DST_FORMAT_RGB565 6
#define DSI_CMD_DST_FORMAT_RGB666 7
#define DSI_CMD_DST_FORMAT_RGB888 8
#define DSI_INTR_ERROR_MASK BIT(25)
#define DSI_INTR_ERROR BIT(24)
#define DSI_INTR_BTA_DONE_MASK BIT(21)
#define DSI_INTR_BTA_DONE BIT(20)
#define DSI_INTR_VIDEO_DONE_MASK BIT(17)
#define DSI_INTR_VIDEO_DONE BIT(16)
#define DSI_INTR_CMD_MDP_DONE_MASK BIT(9)
#define DSI_INTR_CMD_MDP_DONE BIT(8)
#define DSI_INTR_CMD_DMA_DONE_MASK BIT(1)
#define DSI_INTR_CMD_DMA_DONE BIT(0)
#define DSI_CMD_TRIGGER_NONE 0x0 /* mdp trigger */
#define DSI_CMD_TRIGGER_TE 0x02
#define DSI_CMD_TRIGGER_SW 0x04
#define DSI_CMD_TRIGGER_SW_SEOF 0x05 /* cmd dma only */
#define DSI_CMD_TRIGGER_SW_TE 0x06
#define DSI_VIDEO_TERM BIT(16)
#define DSI_MDP_TERM BIT(8)
#define DSI_BTA_TERM BIT(1)
#define DSI_CMD_TERM BIT(0)
extern struct device dsi_dev;
extern u32 dsi_irq;
extern struct mdss_dsi_ctrl_pdata *ctrl_list[];
struct dsiphy_pll_divider_config {
u32 clk_rate;
u32 fb_divider;
u32 ref_divider_ratio;
u32 bit_clk_divider; /* oCLK1 */
u32 byte_clk_divider; /* oCLK2 */
u32 analog_posDiv;
u32 digital_posDiv;
};
extern struct dsiphy_pll_divider_config pll_divider_config;
struct dsi_clk_mnd_table {
u8 lanes;
u8 bpp;
u8 pll_digital_posDiv;
u8 pclk_m;
u8 pclk_n;
u8 pclk_d;
};
static const struct dsi_clk_mnd_table mnd_table[] = {
{ 1, 2, 8, 1, 1, 0},
{ 1, 3, 12, 1, 1, 0},
{ 2, 2, 4, 1, 1, 0},
{ 2, 3, 6, 1, 1, 0},
{ 3, 2, 1, 3, 8, 4},
{ 3, 3, 4, 1, 1, 0},
{ 4, 2, 2, 1, 1, 0},
{ 4, 3, 3, 1, 1, 0},
};
struct dsi_clk_desc {
u32 src;
u32 m;
u32 n;
u32 d;
u32 mnd_mode;
u32 pre_div_func;
};
struct dsi_panel_cmds {
char *buf;
int blen;
struct dsi_cmd_desc *cmds;
int cmd_cnt;
int link_state;
};
struct dsi_kickoff_action {
struct list_head act_entry;
void (*action) (void *);
void *data;
};
struct dsi_drv_cm_data {
struct regulator *vdd_vreg;
struct regulator *vdd_io_vreg;
struct regulator *vdda_vreg;
int broadcast_enable;
};
struct dsi_pinctrl_res {
struct pinctrl *pinctrl;
struct pinctrl_state *gpio_state_active;
struct pinctrl_state *gpio_state_suspend;
};
enum {
DSI_CTRL_0,
DSI_CTRL_1,
DSI_CTRL_MAX,
};
/* DSI controller #0 is always treated as a master in broadcast mode */
#define DSI_CTRL_MASTER DSI_CTRL_0
#define DSI_CTRL_SLAVE DSI_CTRL_1
#define DSI_BUS_CLKS BIT(0)
#define DSI_LINK_CLKS BIT(1)
#define DSI_ALL_CLKS ((DSI_BUS_CLKS) | (DSI_LINK_CLKS))
#define DSI_EV_PLL_UNLOCKED 0x0001
#define DSI_EV_MDP_FIFO_UNDERFLOW 0x0002
#define DSI_EV_MDP_BUSY_RELEASE 0x80000000
struct mdss_dsi_ctrl_pdata {
int ndx; /* panel_num */
int (*on) (struct mdss_panel_data *pdata);
int (*off) (struct mdss_panel_data *pdata);
int (*partial_update_fnc) (struct mdss_panel_data *pdata);
int (*check_status) (struct mdss_dsi_ctrl_pdata *pdata);
int (*cmdlist_commit)(struct mdss_dsi_ctrl_pdata *ctrl, int from_mdp);
struct mdss_panel_data panel_data;
unsigned char *ctrl_base;
struct dss_io_data ctrl_io;
struct dss_io_data mmss_misc_io;
struct dss_io_data phy_io;
int reg_size;
u32 bus_clk_cnt;
u32 link_clk_cnt;
u32 flags;
struct clk *mdp_core_clk;
struct clk *ahb_clk;
struct clk *axi_clk;
struct clk *mmss_misc_ahb_clk;
struct clk *byte_clk;
struct clk *esc_clk;
struct clk *pixel_clk;
u8 ctrl_state;
int panel_mode;
int irq_cnt;
int rst_gpio;
int disp_en_gpio;
int disp_te_gpio;
int bklt_en_gpio;
int mode_gpio;
int disp_te_gpio_requested;
int bklt_ctrl; /* backlight ctrl */
int pwm_period;
int pwm_pmic_gpio;
int pwm_lpg_chan;
int bklt_max;
int new_fps;
int pwm_enabled;
int idle;
bool blanked;
struct pwm_device *pwm_bl;
struct dsi_drv_cm_data shared_pdata;
u32 pclk_rate;
u32 byte_clk_rate;
struct dss_module_power power_data;
u32 dsi_irq_mask;
struct mdss_hw *dsi_hw;
struct mdss_panel_recovery *recovery;
struct dsi_panel_cmds on_cmds;
struct dsi_panel_cmds off_cmds;
struct dsi_panel_cmds idle_on_cmds;
struct dsi_panel_cmds idle_off_cmds;
struct dsi_panel_cmds low_fps_mode_on_cmds;
struct dsi_panel_cmds low_fps_mode_off_cmds;
struct dcs_cmd_list cmdlist;
struct completion dma_comp;
struct completion mdp_comp;
struct completion video_comp;
struct completion bta_comp;
spinlock_t irq_lock;
spinlock_t mdp_lock;
int mdp_busy;
struct mutex mutex;
struct mutex cmd_mutex;
struct mutex suspend_mutex;
bool ulps;
struct mutex ulps_lock;
unsigned int ulps_ref_count;
struct dsi_buf tx_buf;
struct dsi_buf rx_buf;
struct dsi_pinctrl_res pin_res;
};
int dsi_panel_device_register(struct device_node *pan_node,
struct mdss_dsi_ctrl_pdata *ctrl_pdata);
int mdss_dsi_cmds_tx(struct mdss_dsi_ctrl_pdata *ctrl,
struct dsi_cmd_desc *cmds, int cnt);
int mdss_dsi_cmds_rx(struct mdss_dsi_ctrl_pdata *ctrl,
struct dsi_cmd_desc *cmds, int rlen);
void mdss_dsi_host_init(struct mdss_panel_data *pdata);
void mdss_dsi_op_mode_config(int mode,
struct mdss_panel_data *pdata);
void mdss_dsi_cmd_mode_ctrl(int enable);
void mdp4_dsi_cmd_trigger(void);
void mdss_dsi_cmd_mdp_start(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_cmd_bta_sw_trigger(struct mdss_panel_data *pdata);
void mdss_dsi_ack_err_status(struct mdss_dsi_ctrl_pdata *ctrl);
int mdss_dsi_clk_ctrl(struct mdss_dsi_ctrl_pdata *ctrl,
u8 clk_type, int enable);
void mdss_dsi_clk_req(struct mdss_dsi_ctrl_pdata *ctrl,
int enable);
void mdss_dsi_controller_cfg(int enable,
struct mdss_panel_data *pdata);
void mdss_dsi_sw_reset(struct mdss_panel_data *pdata);
irqreturn_t mdss_dsi_isr(int irq, void *ptr);
void mdss_dsi_irq_handler_config(struct mdss_dsi_ctrl_pdata *ctrl_pdata);
void mdss_dsi_set_tx_power_mode(int mode, struct mdss_panel_data *pdata);
int mdss_dsi_clk_div_config(struct mdss_panel_info *panel_info,
int frame_rate);
int mdss_dsi_clk_init(struct platform_device *pdev,
struct mdss_dsi_ctrl_pdata *ctrl_pdata);
void mdss_dsi_clk_deinit(struct mdss_dsi_ctrl_pdata *ctrl_pdata);
int mdss_dsi_enable_bus_clocks(struct mdss_dsi_ctrl_pdata *ctrl_pdata);
void mdss_dsi_disable_bus_clocks(struct mdss_dsi_ctrl_pdata *ctrl_pdata);
int mdss_dsi_panel_reset(struct mdss_panel_data *pdata, int enable);
void mdss_dsi_phy_disable(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_phy_init(struct mdss_panel_data *pdata);
void mdss_dsi_phy_sw_reset(unsigned char *ctrl_base);
void mdss_dsi_cmd_test_pattern(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_video_test_pattern(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_panel_pwm_cfg(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_ctrl_init(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_cmd_mdp_busy(struct mdss_dsi_ctrl_pdata *ctrl);
void mdss_dsi_wait4video_done(struct mdss_dsi_ctrl_pdata *ctrl);
int mdss_dsi_cmdlist_commit(struct mdss_dsi_ctrl_pdata *ctrl, int from_mdp);
void mdss_dsi_cmdlist_kickoff(int intf);
int mdss_dsi_bta_status_check(struct mdss_dsi_ctrl_pdata *ctrl);
bool __mdss_dsi_clk_enabled(struct mdss_dsi_ctrl_pdata *ctrl, u8 clk_type);
int mdss_dsi_ulps_config(struct mdss_dsi_ctrl_pdata *ctrl, int enable);
int mdss_dsi_panel_init(struct device_node *node,
struct mdss_dsi_ctrl_pdata *ctrl_pdata,
bool cmd_cfg_cont_splash);
void mdss_dsi_panel_low_fps_mode(struct mdss_dsi_ctrl_pdata *ctrl, int enable);
static inline bool mdss_dsi_broadcast_mode_enabled(void)
{
return ctrl_list[DSI_CTRL_MASTER]->shared_pdata.broadcast_enable &&
ctrl_list[DSI_CTRL_SLAVE] &&
ctrl_list[DSI_CTRL_SLAVE]->shared_pdata.broadcast_enable;
}
static inline struct mdss_dsi_ctrl_pdata *mdss_dsi_get_master_ctrl(void)
{
if (mdss_dsi_broadcast_mode_enabled())
return ctrl_list[DSI_CTRL_MASTER];
else
return NULL;
}
static inline struct mdss_dsi_ctrl_pdata *mdss_dsi_get_slave_ctrl(void)
{
if (mdss_dsi_broadcast_mode_enabled())
return ctrl_list[DSI_CTRL_SLAVE];
else
return NULL;
}
static inline bool mdss_dsi_is_master_ctrl(struct mdss_dsi_ctrl_pdata *ctrl)
{
return mdss_dsi_broadcast_mode_enabled() &&
(ctrl->ndx == DSI_CTRL_MASTER);
}
static inline bool mdss_dsi_is_slave_ctrl(struct mdss_dsi_ctrl_pdata *ctrl)
{
return mdss_dsi_broadcast_mode_enabled() &&
(ctrl->ndx == DSI_CTRL_SLAVE);
}
static inline struct mdss_dsi_ctrl_pdata *mdss_dsi_get_ctrl_by_index(int ndx)
{
if (ndx >= DSI_CTRL_MAX)
return NULL;
return ctrl_list[ndx];
}
#endif /* MDSS_DSI_H */
| Java |
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
namespace Lcc.Entrada.Articulos
{
public partial class DetalleComprobante : ControlSeleccionElemento
{
protected bool m_MostrarExistencias, m_DiscriminarIva = false, m_AplicarIva = true;
protected Precios m_Precio = Precios.Pvp;
protected ControlesSock m_ControlStock = ControlesSock.Ambos;
protected Lbl.Articulos.ColeccionDatosSeguimiento m_DatosSeguimiento = new Lbl.Articulos.ColeccionDatosSeguimiento();
protected Lbl.Impuestos.Alicuota m_Alicuota = null;
protected decimal m_ImporteUnitarioIva = 0m;
new public event System.Windows.Forms.KeyEventHandler KeyDown;
public event System.EventHandler ImportesChanged;
public event System.EventHandler ObtenerDatosSeguimiento;
public DetalleComprobante()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (Lfx.Workspace.Master != null) {
switch (m_Precio) {
case Precios.Costo:
EntradaUnitario.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesCosto;
EntradaImporte.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesCosto;
break;
case Precios.Pvp:
EntradaUnitario.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales;
EntradaImporte.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales;
break;
}
}
}
public ControlesSock ControlStock
{
get
{
return m_ControlStock;
}
set
{
m_ControlStock = value;
PonerFiltros();
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
override public bool ShowChanged
{
set
{
base.ShowChanged = value;
EntradaArticulo.ShowChanged = value;
EntradaDescuento.ShowChanged = value;
EntradaCantidad.ShowChanged = value;
EntradaUnitario.ShowChanged = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
System.ComponentModel.Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoUpdate
{
get
{
return EntradaArticulo.AutoUpdate;
}
set
{
EntradaArticulo.AutoUpdate = value;
}
}
public bool PermiteCrear
{
get
{
return EntradaArticulo.CanCreate;
}
set
{
EntradaArticulo.CanCreate = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
System.ComponentModel.Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool IsEmpty
{
get
{
return EntradaArticulo.IsEmpty;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
new public int ValueInt
{
get
{
return EntradaArticulo.ValueInt;
}
set
{
if (EntradaArticulo.ValueInt != value)
EntradaArticulo.ValueInt = value;
}
}
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Lbl.Articulos.ColeccionDatosSeguimiento DatosSeguimiento
{
get
{
return m_DatosSeguimiento;
}
set
{
if (m_DatosSeguimiento != value) {
this.Changed = true;
}
m_DatosSeguimiento = value;
if (m_DatosSeguimiento == null || m_DatosSeguimiento.Count == 0) {
LabelSerials.Visible = false;
} else {
LabelSerials.Text = "Seguimiento: " + m_DatosSeguimiento.ToString();
LabelSerials.Visible = true;
if (this.Cantidad != m_DatosSeguimiento.CantidadTotal)
this.Cantidad = m_DatosSeguimiento.CantidadTotal;
}
}
}
public bool MuestraPrecio
{
get
{
return EntradaUnitario.Visible;
}
set
{
EntradaUnitario.Visible = value;
EntradaIva.Visible = value;
EntradaCantidad.Visible = value;
EntradaDescuento.Visible = value;
EntradaImporte.Visible = value;
if (value)
EntradaArticulo.Width = EntradaUnitario.Left - 1;
else
EntradaArticulo.Width = this.Width;
}
}
// Oculta al changed de abajo
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
new public bool Changed
{
get
{
return EntradaArticulo.Changed || EntradaCantidad.Changed || EntradaUnitario.Changed || EntradaDescuento.Changed;
}
set
{
EntradaArticulo.Changed = value;
EntradaDescuento.Changed = value;
EntradaCantidad.Changed = value;
EntradaUnitario.Changed = value;
}
}
public Precios UsarPrecio
{
get
{
return m_Precio;
}
set
{
m_Precio = value;
this.CambiarArticulo(this.Articulo);
this.Changed = false;
}
}
public bool BloquearAtriculo
{
get
{
return EntradaArticulo.TemporaryReadOnly;
}
set
{
EntradaArticulo.TemporaryReadOnly = value;
}
}
public bool BloquearCantidad
{
get
{
return EntradaCantidad.TemporaryReadOnly;
}
set
{
EntradaCantidad.TemporaryReadOnly = value;
}
}
public bool BloquearPrecio
{
get
{
return EntradaUnitario.TemporaryReadOnly;
}
set
{
EntradaUnitario.ReadOnly = value;
EntradaDescuento.ReadOnly = value || this.BloquearDescuento;
}
}
public bool BloquearDescuento
{
get
{
return EntradaDescuento.TemporaryReadOnly;
}
set
{
EntradaDescuento.ReadOnly = value || this.BloquearPrecio;
}
}
public bool MostrarExistencias
{
get
{
return m_MostrarExistencias;
}
set
{
m_MostrarExistencias = value;
VerificarStock();
}
}
/// <summary>
/// Indica si los precios se muestran con IVA discriminado.
/// </summary>
public bool DiscriminarIva
{
get
{
return m_DiscriminarIva;
}
set
{
bool AntesDiscriminaba = m_DiscriminarIva;
m_DiscriminarIva = value;
EntradaIva.Enabled = this.DiscriminarIva && this.AplicarIva;
if (m_DiscriminarIva != AntesDiscriminaba && m_AplicarIva && m_Alicuota != null) {
if (value) {
// Antes no discriminaba y ahora sí
this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario / (1 + m_Alicuota.Porcentaje / 100m));
} else {
// Antes discriminaba y ahora no
this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario);
}
this.RecalcularImporteFinal();
if (null != ImportesChanged) {
ImportesChanged(this, null);
}
}
this.RecalcularImporteFinal();
}
}
/// <summary>
/// Indica si debe aplicar IVA al cliente.
/// </summary>
public bool AplicarIva
{
get
{
return m_AplicarIva;
}
set
{
bool AntesAplicaba = m_AplicarIva;
m_AplicarIva = value;
EntradaIva.Enabled = this.DiscriminarIva && this.AplicarIva;
if (m_AplicarIva != AntesAplicaba && m_Alicuota != null) {
decimal NuevoImporteUnitarioIva = this.ImporteUnitario * (m_Alicuota.Porcentaje / 100m);
if (value) {
// Antes no aplicaba y ahora sí
this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario);
} else {
// Antes aplicaba y ahora no
this.EstablecerImporteUnitarioOriginal((this.ImporteUnitario + this.ImporteIvaDiscriminadoUnitario) / (1m + m_Alicuota.Porcentaje / 100m));
}
this.RecalcularImporteFinal();
if (null != ImportesChanged) {
ImportesChanged(this, null);
}
}
}
}
public bool Required
{
get
{
return EntradaArticulo.Required;
}
set
{
EntradaArticulo.Required = value;
}
}
[System.ComponentModel.Category("Datos")]
public string FreeTextCode
{
get
{
return EntradaArticulo.FreeTextCode;
}
set
{
EntradaArticulo.FreeTextCode = value;
}
}
public int UnitarioLeft
{
get
{
return EntradaUnitario.Left;
}
}
public int DescuentoLeft
{
get
{
return EntradaDescuento.Left;
}
}
public int CantidadLeft
{
get
{
return EntradaCantidad.Left;
}
}
public int IvaLeft
{
get
{
return EntradaIva.Left;
}
}
public int ImporteLeft
{
get
{
return EntradaImporte.Left;
}
}
public override string Text
{
get
{
if (EntradaArticulo.Text == EntradaArticulo.FreeTextCode && EntradaArticulo.FreeTextCode.Length > 0)
return EntradaArticulo.Text;
else
return EntradaArticulo.ValueInt.ToString();
}
set
{
if (EntradaArticulo.Text != value) {
EntradaArticulo.Text = value;
}
this.Changed = false;
}
}
public string TextDetail
{
get
{
return EntradaArticulo.TextDetail;
}
set
{
EntradaArticulo.TextDetail = value;
this.Changed = false;
}
}
/// <summary>
/// El importe final, con IVA, por cantidad y con descuento.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteFinal
{
get
{
return EntradaImporte.ValueDecimal;
}
set
{
EntradaImporte.ValueDecimal = value;
this.Changed = false;
}
}
/// <summary>
/// El importe de IVA unitario (sin descuento).
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteIvaUnitario
{
get
{
return this.m_ImporteUnitarioIva;
}
set
{
this.m_ImporteUnitarioIva = value;
if(this.DiscriminarIva) {
this.EntradaUnitarioIvaDescuentoCantidad_TextChanged(this, null);
}
this.Changed = false;
}
}
/// <summary>
/// El importe de IVA discriminado unitario (sin descuento), o 0 si el IVA no está discriminado.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteIvaDiscriminadoUnitario
{
get
{
return EntradaIva.ValueDecimal;
}
set
{
EntradaIva.ValueDecimal = value;
this.Changed = false;
}
}
/// <summary>
/// El importe de IVA final, por cantidad y con descuento.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteIvaUnitarioFinal
{
get
{
return this.ImporteIvaUnitario * this.Cantidad * (1m - this.Descuento / 100m);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteUnitario
{
get
{
return EntradaUnitario.ValueDecimal;
}
set
{
EntradaUnitario.ValueDecimal = value;
this.Changed = false;
}
}
/// <summary>
/// El importe unitario final, por cantidad y con descuento.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal ImporteUnitarioFinal
{
get
{
return this.ImporteUnitario * this.Cantidad * (1m - this.Descuento / 100m);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal Descuento
{
get
{
return EntradaDescuento.ValueDecimal;
}
set
{
EntradaDescuento.ValueDecimal = value;
this.Changed = false;
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Lbl.Articulos.Articulo Articulo
{
get
{
return EntradaArticulo.Elemento as Lbl.Articulos.Articulo;
}
set
{
EntradaArticulo.Elemento = value;
this.Elemento = value;
if(value == null) {
this.m_Alicuota = null;
} else {
this.m_Alicuota = value.ObtenerAlicuota();
}
EntradaArticulo_TextChanged(this, null);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Lbl.Impuestos.Alicuota Alicuota
{
get
{
return m_Alicuota;
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public decimal Cantidad
{
get
{
if (this.EstoyUsandoUnidadPrimaria())
return EntradaCantidad.ValueDecimal;
else
return EntradaCantidad.ValueDecimal / Articulo.Rendimiento;
}
set
{
if (this.EstoyUsandoUnidadPrimaria())
EntradaCantidad.ValueDecimal = value;
else
EntradaCantidad.ValueDecimal = value * this.Articulo.Rendimiento;
this.Changed = false;
}
}
private bool EstoyUsandoUnidadPrimaria()
{
return (this.Articulo == null || Articulo.Unidad == null || EntradaCantidad.Sufijo == Articulo.Unidad || (EntradaCantidad.Sufijo.Length == 0 && Articulo.Unidad == "u") || Articulo.Rendimiento == 0);
}
private void EntradaArticulo_TextChanged(object sender, System.EventArgs e)
{
if (this.Connection == null)
return;
EntradaUnitario.TabStop = EntradaArticulo.IsFreeText;
if (this.Elemento != EntradaArticulo.Elemento || EntradaArticulo.IsFreeText) {
this.Elemento = EntradaArticulo.Elemento;
if (this.Articulo != null) {
this.m_Alicuota = this.Articulo.ObtenerAlicuota();
}
this.CambiarArticulo(this.Articulo);
}
this.DatosSeguimiento = null;
this.Changed = true;
this.OnTextChanged(EventArgs.Empty);
}
private void EntradaUnitarioIvaDescuentoCantidad_TextChanged(object sender, System.EventArgs e)
{
if (this.Connection != null) {
decimal ValorAnterior = EntradaImporte.ValueDecimal;
this.RecalcularImporteFinal();
this.VerificarStock();
if (EntradaImporte.ValueDecimal != ValorAnterior) {
this.Changed = true;
if (null != ImportesChanged) {
ImportesChanged(this, null);
}
}
}
}
private void VerificarStock()
{
if (m_MostrarExistencias && Articulo != null) {
if (this.TemporaryReadOnly == false && this.Articulo.TipoDeArticulo != Lbl.Articulos.TiposDeArticulo.Servicio && this.Articulo.Existencias < this.Cantidad) {
if (this.Articulo.Existencias + this.Articulo.Pedido >= this.Cantidad) {
//EntradaArticulo.Font = null;
EntradaArticulo.ForeColor = Color.OrangeRed;
} else {
//EntradaArticulo.Font = new Font(this.Font, FontStyle.Strikeout);
EntradaArticulo.ForeColor = Color.Red;
}
} else {
//EntradaArticulo.Font = null;
EntradaArticulo.ForeColor = this.DisplayStyle.TextColor;
}
} else {
//EntradaArticulo.Font = null;
EntradaArticulo.ForeColor = this.DisplayStyle.TextColor;
}
}
public override bool TemporaryReadOnly
{
get
{
return base.TemporaryReadOnly;
}
set
{
base.TemporaryReadOnly = value;
if (value) {
EntradaArticulo.TemporaryReadOnly = true;
EntradaUnitario.TemporaryReadOnly = true;
EntradaDescuento.TemporaryReadOnly = true;
EntradaCantidad.TemporaryReadOnly = true;
}
this.VerificarStock();
}
}
private void EntradaArticulo_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.Alt == false && e.Control == false && e.Shift == false) {
switch (e.KeyCode) {
case Keys.Right:
case Keys.Return:
e.Handled = true;
if (EntradaUnitario.Visible && this.ReadOnly == false && this.TemporaryReadOnly == false) {
if (this.BloquearPrecio)
EntradaCantidad.Focus();
else
EntradaUnitario.Focus();
} else {
System.Windows.Forms.SendKeys.Send("{tab}");
}
break;
default:
if (KeyDown != null)
KeyDown(sender, e);
this.AutoUpdate = true;
break;
}
}
if (e.Alt == false && e.Control == true && e.Shift == false) {
switch (e.KeyCode) {
case Keys.S:
this.ObtenerDatosSeguimientoSiEsNecesario();
break;
}
}
}
protected void ObtenerDatosSeguimientoSiEsNecesario()
{
if (this.Articulo != null && this.Articulo.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno && this.ObtenerDatosSeguimiento != null)
this.ObtenerDatosSeguimiento(this, new EventArgs());
}
protected override void OnLeave(EventArgs e)
{
Lbl.Articulos.Articulo Art = this.Elemento as Lbl.Articulos.Articulo;
if (this.Cantidad != 0 && Art != null && Art.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno && (this.DatosSeguimiento == null || this.DatosSeguimiento.Count != this.Cantidad)) {
this.ObtenerDatosSeguimientoSiEsNecesario();
}
base.OnLeave(e);
}
private void EntradaUnitario_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.E:
if (e.Control) {
EntradaUnitario.SelectionLength = 0;
EntradaUnitario.SelectionStart = EntradaUnitario.Text.Length;
e.Handled = true;
}
break;
case Keys.Left:
if (EntradaUnitario.SelectionStart == 0) {
e.Handled = true;
EntradaArticulo.Focus();
}
break;
case Keys.Right:
case Keys.Return:
if (EntradaUnitario.SelectionStart >= EntradaUnitario.TextRaw.Length || EntradaUnitario.SelectionLength > 0) {
e.Handled = true;
EntradaCantidad.Focus();
}
break;
case Keys.Up:
System.Windows.Forms.SendKeys.Send("+{tab}");
break;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{tab}");
break;
default:
if (null != KeyDown)
KeyDown(sender, e);
break;
}
}
private void EntradaDescuento_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.Left:
if (EntradaDescuento.SelectionStart == 0) {
e.Handled = true;
EntradaCantidad.Focus();
}
break;
case Keys.Up:
System.Windows.Forms.SendKeys.Send("+{tab}");
break;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{tab}");
break;
default:
if (null != KeyDown)
KeyDown(sender, e);
break;
}
}
private void EntradaCantidad_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.Left:
e.Handled = true;
if (this.BloquearPrecio)
EntradaArticulo.Focus();
else
EntradaUnitario.Focus();
break;
case Keys.Right:
case Keys.Return:
if (EntradaCantidad.SelectionStart >= EntradaCantidad.TextRaw.Length || EntradaCantidad.SelectionLength > 0) {
if (this.BloquearPrecio == false) {
e.Handled = true;
EntradaDescuento.Focus();
}
}
break;
case Keys.Up:
System.Windows.Forms.SendKeys.Send("+{tab}");
break;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{tab}");
break;
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.Space:
e.Handled = true;
this.ObtenerDatosSeguimientoSiEsNecesario();
break;
default:
if (KeyDown != null)
KeyDown(sender, e);
break;
}
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
if (EntradaArticulo.Focused == false)
EntradaArticulo.Focus();
}
private void PonerFiltros()
{
string Filtros = "";
switch (m_ControlStock) {
case ControlesSock.ConControlStock:
Filtros += "control_stock=1";
break;
case ControlesSock.SinControlStock:
Filtros += "control_stock=0";
break;
}
EntradaArticulo.Filter = Filtros;
}
private void RecalcularAltura(object sender, System.EventArgs e)
{
LabelSerialsCruz.Visible = LabelSerials.Visible;
if (LabelSerials.Visible)
this.Height = this.LabelSerials.Bottom + this.EntradaArticulo.Top;
else
this.Height = this.EntradaArticulo.Bottom + this.EntradaArticulo.Top;
}
private void EntradaCantidad_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ') {
if (Articulo != null) {
if (this.EstoyUsandoUnidadPrimaria()) {
//Cambio a unidad secundaria
EntradaCantidad.Sufijo = Articulo.UnidadRendimiento;
EntradaCantidad.Text = Lfx.Types.Formatting.FormatStock(Lfx.Types.Parsing.ParseStock(EntradaCantidad.Text) * this.Articulo.Rendimiento);
} else {
//Cambio a unidad primaria
EntradaCantidad.Sufijo = Articulo.Unidad == "u" ? "" : Articulo.Unidad;
EntradaCantidad.Text = Lfx.Types.Formatting.FormatStock(Lfx.Types.Parsing.ParseStock(EntradaCantidad.Text) / this.Articulo.Rendimiento, 4);
}
e.Handled = true;
}
}
}
private void EntradaCantidad_Click(object sender, EventArgs e)
{
this.ObtenerDatosSeguimientoSiEsNecesario();
}
protected void CambiarArticulo(Lbl.Articulos.Articulo articulo)
{
if (this.Articulo != null) {
EntradaUnitario.Enabled = true;
EntradaUnitario.Enabled = true;
EntradaDescuento.Enabled = true;
EntradaCantidad.Enabled = true;
EntradaImporte.Enabled = true;
EntradaCantidad.TemporaryReadOnly = this.Articulo.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno || this.TemporaryReadOnly;
EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
if (this.AutoUpdate) {
if (this.Articulo == null) {
return;
}
if (this.Articulo.Unidad != "u") {
EntradaCantidad.Sufijo = Articulo.Unidad;
} else {
EntradaCantidad.Sufijo = "";
}
decimal UnitarioMostrar;
if (m_Precio == Precios.Costo) {
UnitarioMostrar = Articulo.Costo;
} else {
UnitarioMostrar = Articulo.Pvp;
}
if (this.Cantidad == 0) {
this.Cantidad = 1;
}
this.EstablecerImporteUnitarioOriginal(UnitarioMostrar);
this.RecalcularImporteFinal();
}
} else if (EntradaArticulo.IsFreeText) {
EntradaUnitario.Enabled = true;
EntradaDescuento.Enabled = true;
EntradaCantidad.Enabled = true;
EntradaCantidad.TemporaryReadOnly = this.TemporaryReadOnly;
EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaImporte.Enabled = true;
if (this.AutoUpdate) {
if (this.Cantidad == 0) {
this.Cantidad = 1;
}
}
} else if (EntradaArticulo.Text.Length == 0 || (EntradaArticulo.Text.IsNumericInt() && EntradaArticulo.ValueInt == 0)) {
EntradaUnitario.Enabled = false;
EntradaDescuento.Enabled = false;
EntradaCantidad.Enabled = false;
EntradaCantidad.TemporaryReadOnly = this.TemporaryReadOnly;
EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio;
EntradaImporte.Enabled = false;
if (this.AutoUpdate) {
EntradaCantidad.ValueDecimal = 0m;
EntradaImporte.ValueDecimal = 0m;
this.EstablecerImporteUnitarioOriginal(0m);
EntradaDescuento.ValueDecimal = 0m;
}
}
}
/// <summary>
/// Cambia el importe unitario original (sin IVA), y además recalcula el IVA y lo muestra discriminado si corresponde.
/// </summary>
/// <param name="unitario">El precio unitario a mostrar y usar como base para el cálculo de IVA e importe final.</param>
protected void EstablecerImporteUnitarioOriginal(decimal unitario)
{
if (this.AplicarIva && m_Alicuota != null) {
this.ImporteIvaUnitario = unitario * (m_Alicuota.Porcentaje / 100m);
if (this.DiscriminarIva) {
EntradaUnitario.ValueDecimal = unitario;
EntradaIva.ValueDecimal = this.ImporteIvaUnitario;
} else {
EntradaUnitario.ValueDecimal = unitario + this.ImporteIvaUnitario;
EntradaIva.ValueDecimal = 0m;
}
} else {
this.ImporteIvaUnitario = 0m;
EntradaUnitario.ValueDecimal = unitario;
EntradaIva.ValueDecimal = 0;
}
}
/// <summary>
/// Recalcula el importe final, según importe, IVA, cantidad y descuento.
/// </summary>
protected void RecalcularImporteFinal()
{
if(m_DiscriminarIva) {
if(m_AplicarIva && this.m_Alicuota != null) {
decimal Iva = this.ImporteUnitario * (this.m_Alicuota.Porcentaje / 100m);
if(Math.Abs(this.ImporteIvaUnitario - Iva) > 0.01m) {
this.ImporteIvaUnitario = Iva;
}
} else {
if(this.ImporteIvaUnitario != 0m) {
this.ImporteIvaUnitario = 0m;
}
}
EntradaIva.ValueDecimal = this.ImporteIvaUnitario;
} else {
EntradaIva.ValueDecimal = 0m;
}
try {
decimal ImporteFinal = (this.ImporteUnitario + this.ImporteIvaDiscriminadoUnitario) * this.Cantidad * (1m - this.Descuento / 100m);
EntradaImporte.ValueDecimal = ImporteFinal;
} catch {
EntradaImporte.ValueDecimal = 0m;
}
if (m_MostrarExistencias) {
VerificarStock();
}
}
}
} | Java |
#myGallery, #myGallerySet, #flickrGallery
{
width: 520px;
height: 300px;
z-index:5;
margin-bottom: 20px;
}
.jdGallery a
{
outline:0;
}
#flickrGallery
{
width: 500px;
height: 334px;
}
#myGallery img.thumbnail, #myGallerySet img.thumbnail
{
display: none;
}
.jdGallery
{
overflow: hidden;
position: relative;
}
.jdGallery img
{
border: 0;
margin: 0;
}
.jdGallery .slideElement
{
width: 100%;
height: 100%;
background-color: #000;
background-repeat: no-repeat;
background-position: center center;
background-image: url('img/loading-bar-black.gif');
}
.jdGallery .loadingElement
{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
background-color: #000;
background-repeat: no-repeat;
background-position: center center;
background-image: url('img/loading-bar-black.gif');
}
.jdGallery .slideInfoZone
{
position: absolute;
z-index: 10;
width: 100%;
margin: 0px;
left: 0;
bottom: 0;
height: 120px;
background: #181818;
color: #fff;
text-indent: 0;
overflow: hidden;
}
* html .jdGallery .slideInfoZone
{
bottom: -1px;
}
.jdGallery .slideInfoZone h2
{
padding: 0;
font-size: 14px;
margin: 0;
margin: 2px 5px;
font-weight: bold;
color: #fff !important;
}
.jdGallery .slideInfoZone p
{
padding: 0;
font-size: 12px;
margin: 2px 5px;
color: #eee;
}
.jdGallery div.carouselContainer
{
position: absolute;
height: 135px;
width: 100%;
z-index: 10;
margin: 0px;
left: 0;
top: 0;
}
.jdGallery a.carouselBtn
{
position: absolute;
bottom: 0;
right: 30px;
height: 20px;
/*width: 100px; background: url('img/carousel_btn.gif') no-repeat;*/
text-align: center;
padding: 0 10px;
font-size: 13px;
background: #333;
color: #fff;
cursor: pointer;
}
.jdGallery .carousel
{
position: absolute;
width: 100%;
margin: 0px;
left: 0;
top: 0;
height: 115px;
background: #333;
color: #fff;
text-indent: 0;
overflow: hidden;
}
.jdExtCarousel
{
overflow: hidden;
position: relative;
}
.jdGallery .carousel .carouselWrapper, .jdExtCarousel .carouselWrapper
{
position: absolute;
width: 100%;
height: 78px;
top: 10px;
left: 0;
overflow: hidden;
}
.jdGallery .carousel .carouselInner, .jdExtCarousel .carouselInner
{
position: relative;
}
.jdGallery .carousel .carouselInner .thumbnail, .jdExtCarousel .carouselInner .thumbnail
{
cursor: pointer;
background: #000;
background-position: center center;
float: left;
border: solid 1px #fff;
}
.jdGallery .wall .thumbnail, .jdExtCarousel .wall .thumbnail
{
margin-bottom: 10px;
}
.jdGallery .carousel .label, .jdExtCarousel .label
{
font-size: 13px;
position: absolute;
bottom: 5px;
left: 10px;
padding: 0;
margin: 0;
}
.jdGallery .carousel .wallButton, .jdExtCarousel .wallButton
{
font-size: 10px;
position: absolute;
bottom: 5px;
right: 10px;
padding: 1px 2px;
margin: 0;
background: #222;
border: 1px solid #888;
cursor: pointer;
}
.jdGallery .carousel .label .number, .jdExtCarousel .label .number
{
color: #b5b5b5;
}
.jdGallery a
{
font-size: 100%;
text-decoration: none;
color: #fff;
}
.jdGallery a.right, .jdGallery a.left
{
position: absolute;
height: 99%;
width: 25%;
cursor: pointer;
z-index:10;
filter:alpha(opacity=20);
-moz-opacity:0.2;
-khtml-opacity: 0.2;
opacity: 0.2;
}
* html .jdGallery a.right, * html .jdGallery a.left
{
filter:alpha(opacity=50);
}
.jdGallery a.right:hover, .jdGallery a.left:hover
{
filter:alpha(opacity=80);
-moz-opacity:0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
}
.jdGallery a.left
{
left: 0;
top: 0;
background: url('img/fleche1.png') no-repeat center left;
}
* html .jdGallery a.left { background: url('img/fleche1.gif') no-repeat center left; }
.jdGallery a.right
{
right: 0;
top: 0;
background: url('img/fleche2.png') no-repeat center right;
}
* html .jdGallery a.right { background: url('img/fleche2.gif') no-repeat center right; }
.jdGallery a.open
{
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.withArrows a.open
{
position: absolute;
top: 0;
left: 25%;
height: 99%;
width: 50%;
cursor: pointer;
z-index: 10;
background: none;
-moz-opacity:0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
}
.withArrows a.open:hover { background: url('img/open.png') no-repeat center center; }
* html .withArrows a.open:hover { background: url('img/open.gif') no-repeat center center;
filter:alpha(opacity=80); }
/* Gallery Sets */
.jdGallery a.gallerySelectorBtn
{
z-index: 15;
position: absolute;
top: 0;
left: 30px;
height: 20px;
/*width: 100px; background: url('img/carousel_btn.gif') no-repeat;*/
text-align: center;
padding: 0 10px;
font-size: 13px;
background: #333;
color: #fff;
cursor: pointer;
opacity: .4;
-moz-opacity: .4;
-khtml-opacity: 0.4;
filter:alpha(opacity=40);
}
.jdGallery .gallerySelector
{
z-index: 20;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: #000;
}
.jdGallery .gallerySelector h2
{
margin: 0;
padding: 10px 20px 10px 20px;
font-size: 20px;
line-height: 30px;
color: #fff !important;
}
.jdGallery .gallerySelector .gallerySelectorWrapper
{
overflow: hidden;
}
.jdGallery .gallerySelector .gallerySelectorInner div.galleryButton
{
margin-left: 10px;
margin-top: 10px;
border: 1px solid #888;
padding: 5px;
height: 40px;
color: #fff;
cursor: pointer;
float: left;
}
.jdGallery .gallerySelector .gallerySelectorInner div.hover
{
background: #333;
}
.jdGallery .gallerySelector .gallerySelectorInner div.galleryButton div.preview
{
background: #000;
background-position: center center;
float: left;
border: none;
width: 40px;
height: 40px;
margin-right: 5px;
}
.jdGallery .gallerySelector .gallerySelectorInner div.galleryButton h3
{
margin: 0;
padding: 0;
font-size: 12px;
font-weight: normal;
color: #fff;
}
.jdGallery .gallerySelector .gallerySelectorInner div.galleryButton p.info
{
margin: 0;
padding: 0;
font-size: 12px;
font-weight: normal;
color: #fff !important;
} | Java |
#include <stdio.h>
#include <l4/sys/kdebug.h>
void fork_to_background(void);
void fork_to_background(void)
{
printf("unimplemented: %s\n", __func__);
enter_kdebug();
}
| Java |
{{tpl:extends parent="__layout.html"}}
<tpl:Block name="head-title">
<title>{{tpl:lang Categories Page}} - {{tpl:BlogName encode_html="1"}}</title>
</tpl:Block>
<tpl:Block name="meta-robots">
<meta name="ROBOTS" content="{{tpl:BlogMetaRobots}}" />
</tpl:Block>
<tpl:Block name="dc-entry">
<meta name="dc.title" lang="{{tpl:BlogLanguage}}" content="{{tpl:EntryTitle encode_html="1"}} - {{tpl:BlogName encode_html="1"}}" />
<meta property="dc.language" content="{{tpl:BlogLanguage}}" />
</tpl:Block>
<tpl:Block name="head-linkrel">
<link rel="top" href="{{tpl:BlogURL}}" title="{{tpl:lang Home}}" />
<link rel="contents" href="{{tpl:BlogArchiveURL}}" title="{{tpl:lang Archives}}" />
<link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="{{tpl:BlogFeedURL type="atom"}}" />
</tpl:Block>
<tpl:Block name="body-tag"><body class="dc-page"></tpl:Block>
<tpl:Block name="main-breadcrumb">
{{tpl:Breadcrumb}}
</tpl:Block>
<tpl:Block name="main-content">
<div id="p{{tpl:EntryID}}" class="post" role="article">
<h2 class="post-title">{{tpl:EntryTitle encode_html="1"}}</h2>
<!-- # --BEHAVIOR-- publicEntryBeforeContent -->
{{tpl:SysBehavior behavior="publicEntryBeforeContent"}}
<tpl:EntryIf extended="1">
<div class="post-excerpt">{{tpl:EntryExcerpt}}</div>
</tpl:EntryIf>
<div class="post-content">{{tpl:EntryContent}}</div>
<p class="page-info">{{tpl:lang Published on}} {{tpl:EntryDate}}
{{tpl:lang by}} {{tpl:EntryAuthorLink}}</p>
<!-- # --BEHAVIOR-- publicEntryAfterContent -->
{{tpl:SysBehavior behavior="publicEntryAfterContent"}}
</div>
</tpl:Block>
| Java |
/*
* mm/page-writeback.c
*
* Copyright (C) 2002, Linus Torvalds.
* Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <[email protected]>
*
* Contains functions related to writing back dirty pages at the
* address_space level.
*
* 10Apr2002 Andrew Morton
* Initial version
*/
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/spinlock.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/writeback.h>
#include <linux/init.h>
#include <linux/backing-dev.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/blkdev.h>
#include <linux/mpage.h>
#include <linux/rmap.h>
#include <linux/percpu.h>
#include <linux/notifier.h>
#include <linux/smp.h>
#include <linux/sysctl.h>
#include <linux/cpu.h>
#include <linux/syscalls.h>
#include <linux/buffer_head.h> /* __set_page_dirty_buffers */
#include <linux/pagevec.h>
#include <linux/timer.h>
#include <linux/sched/rt.h>
#include <linux/mm_inline.h>
#include <trace/events/writeback.h>
#include "internal.h"
/*
* Sleep at most 200ms at a time in balance_dirty_pages().
*/
#define MAX_PAUSE max(HZ/5, 1)
/*
* Try to keep balance_dirty_pages() call intervals higher than this many pages
* by raising pause time to max_pause when falls below it.
*/
#define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
/*
* Estimate write bandwidth at 200ms intervals.
*/
#define BANDWIDTH_INTERVAL max(HZ/5, 1)
#define RATELIMIT_CALC_SHIFT 10
/*
* After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
* will look to see if it needs to force writeback or throttling.
*/
static long ratelimit_pages = 32;
/* The following parameters are exported via /proc/sys/vm */
/*
* Start background writeback (via writeback threads) at this percentage
*/
int dirty_background_ratio = 10;
/*
* dirty_background_bytes starts at 0 (disabled) so that it is a function of
* dirty_background_ratio * the amount of dirtyable memory
*/
unsigned long dirty_background_bytes;
/*
* free highmem will not be subtracted from the total free memory
* for calculating free ratios if vm_highmem_is_dirtyable is true
*/
int vm_highmem_is_dirtyable;
/*
* The generator of dirty data starts writeback at this percentage
*/
int vm_dirty_ratio = 20;
/*
* vm_dirty_bytes starts at 0 (disabled) so that it is a function of
* vm_dirty_ratio * the amount of dirtyable memory
*/
unsigned long vm_dirty_bytes;
/*
* The interval between `kupdate'-style writebacks
*/
unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
EXPORT_SYMBOL_GPL(dirty_writeback_interval);
/*
* The longest time for which data is allowed to remain dirty
*/
unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
/*
* Flag that makes the machine dump writes/reads and block dirtyings.
*/
int block_dump;
/*
* Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
* a full sync is triggered after this time elapses without any disk activity.
*/
int laptop_mode;
EXPORT_SYMBOL(laptop_mode);
/* End of sysctl-exported parameters */
unsigned long global_dirty_limit;
/*
* Scale the writeback cache size proportional to the relative writeout speeds.
*
* We do this by keeping a floating proportion between BDIs, based on page
* writeback completions [end_page_writeback()]. Those devices that write out
* pages fastest will get the larger share, while the slower will get a smaller
* share.
*
* We use page writeout completions because we are interested in getting rid of
* dirty pages. Having them written out is the primary goal.
*
* We introduce a concept of time, a period over which we measure these events,
* because demand can/will vary over time. The length of this period itself is
* measured in page writeback completions.
*
*/
static struct fprop_global writeout_completions;
static void writeout_period(unsigned long t);
/* Timer for aging of writeout_completions */
static struct timer_list writeout_period_timer =
TIMER_DEFERRED_INITIALIZER(writeout_period, 0, 0);
static unsigned long writeout_period_time = 0;
/*
* Length of period for aging writeout fractions of bdis. This is an
* arbitrarily chosen number. The longer the period, the slower fractions will
* reflect changes in current writeout rate.
*/
#define VM_COMPLETIONS_PERIOD_LEN (3*HZ)
/*
* Work out the current dirty-memory clamping and background writeout
* thresholds.
*
* The main aim here is to lower them aggressively if there is a lot of mapped
* memory around. To avoid stressing page reclaim with lots of unreclaimable
* pages. It is better to clamp down on writers than to start swapping, and
* performing lots of scanning.
*
* We only allow 1/2 of the currently-unmapped memory to be dirtied.
*
* We don't permit the clamping level to fall below 5% - that is getting rather
* excessive.
*
* We make sure that the background writeout level is below the adjusted
* clamping level.
*/
/*
* In a memory zone, there is a certain amount of pages we consider
* available for the page cache, which is essentially the number of
* free and reclaimable pages, minus some zone reserves to protect
* lowmem and the ability to uphold the zone's watermarks without
* requiring writeback.
*
* This number of dirtyable pages is the base value of which the
* user-configurable dirty ratio is the effictive number of pages that
* are allowed to be actually dirtied. Per individual zone, or
* globally by using the sum of dirtyable pages over all zones.
*
* Because the user is allowed to specify the dirty limit globally as
* absolute number of bytes, calculating the per-zone dirty limit can
* require translating the configured limit into a percentage of
* global dirtyable memory first.
*/
/**
* zone_dirtyable_memory - number of dirtyable pages in a zone
* @zone: the zone
*
* Returns the zone's number of pages potentially available for dirty
* page cache. This is the base value for the per-zone dirty limits.
*/
static unsigned long zone_dirtyable_memory(struct zone *zone)
{
unsigned long nr_pages;
nr_pages = zone_page_state(zone, NR_FREE_PAGES);
nr_pages -= min(nr_pages, zone->dirty_balance_reserve);
nr_pages += zone_page_state(zone, NR_INACTIVE_FILE);
nr_pages += zone_page_state(zone, NR_ACTIVE_FILE);
return nr_pages;
}
static unsigned long highmem_dirtyable_memory(unsigned long total)
{
#ifdef CONFIG_HIGHMEM
int node;
unsigned long x = 0;
for_each_node_state(node, N_HIGH_MEMORY) {
struct zone *z = &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
x += zone_dirtyable_memory(z);
}
/*
* Unreclaimable memory (kernel memory or anonymous memory
* without swap) can bring down the dirtyable pages below
* the zone's dirty balance reserve and the above calculation
* will underflow. However we still want to add in nodes
* which are below threshold (negative values) to get a more
* accurate calculation but make sure that the total never
* underflows.
*/
if ((long)x < 0)
x = 0;
/*
* Make sure that the number of highmem pages is never larger
* than the number of the total dirtyable memory. This can only
* occur in very strange VM situations but we want to make sure
* that this does not occur.
*/
return min(x, total);
#else
return 0;
#endif
}
/**
* global_dirtyable_memory - number of globally dirtyable pages
*
* Returns the global number of pages potentially available for dirty
* page cache. This is the base value for the global dirty limits.
*/
static unsigned long global_dirtyable_memory(void)
{
unsigned long x;
x = global_page_state(NR_FREE_PAGES);
x -= min(x, dirty_balance_reserve);
x += global_page_state(NR_INACTIVE_FILE);
x += global_page_state(NR_ACTIVE_FILE);
if (!vm_highmem_is_dirtyable)
x -= highmem_dirtyable_memory(x);
/* Subtract min_free_kbytes */
x -= min_t(unsigned long, x, min_free_kbytes >> (PAGE_SHIFT - 10));
return x + 1; /* Ensure that we never return 0 */
}
/*
* global_dirty_limits - background-writeback and dirty-throttling thresholds
*
* Calculate the dirty thresholds based on sysctl parameters
* - vm.dirty_background_ratio or vm.dirty_background_bytes
* - vm.dirty_ratio or vm.dirty_bytes
* The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
* real-time tasks.
*/
void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
{
unsigned long background;
unsigned long dirty;
unsigned long uninitialized_var(available_memory);
struct task_struct *tsk;
if (!vm_dirty_bytes || !dirty_background_bytes)
available_memory = global_dirtyable_memory();
if (vm_dirty_bytes)
dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
else
dirty = (vm_dirty_ratio * available_memory) / 100;
if (dirty_background_bytes)
background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE);
else
background = (dirty_background_ratio * available_memory) / 100;
if (background >= dirty)
background = dirty / 2;
tsk = current;
if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
background += background / 4;
dirty += dirty / 4;
}
*pbackground = background;
*pdirty = dirty;
trace_global_dirty_state(background, dirty);
}
/**
* zone_dirty_limit - maximum number of dirty pages allowed in a zone
* @zone: the zone
*
* Returns the maximum number of dirty pages allowed in a zone, based
* on the zone's dirtyable memory.
*/
static unsigned long zone_dirty_limit(struct zone *zone)
{
unsigned long zone_memory = zone_dirtyable_memory(zone);
struct task_struct *tsk = current;
unsigned long dirty;
if (vm_dirty_bytes)
dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
zone_memory / global_dirtyable_memory();
else
dirty = vm_dirty_ratio * zone_memory / 100;
if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk))
dirty += dirty / 4;
return dirty;
}
/**
* zone_dirty_ok - tells whether a zone is within its dirty limits
* @zone: the zone to check
*
* Returns %true when the dirty pages in @zone are within the zone's
* dirty limit, %false if the limit is exceeded.
*/
bool zone_dirty_ok(struct zone *zone)
{
unsigned long limit = zone_dirty_limit(zone);
return zone_page_state(zone, NR_FILE_DIRTY) +
zone_page_state(zone, NR_UNSTABLE_NFS) +
zone_page_state(zone, NR_WRITEBACK) <= limit;
}
int dirty_background_ratio_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
if (ret == 0 && write)
dirty_background_bytes = 0;
return ret;
}
int dirty_background_bytes_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
if (ret == 0 && write)
dirty_background_ratio = 0;
return ret;
}
int dirty_ratio_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int old_ratio = vm_dirty_ratio;
int ret;
ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
writeback_set_ratelimit();
vm_dirty_bytes = 0;
}
return ret;
}
int dirty_bytes_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
unsigned long old_bytes = vm_dirty_bytes;
int ret;
ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
writeback_set_ratelimit();
vm_dirty_ratio = 0;
}
return ret;
}
static unsigned long wp_next_time(unsigned long cur_time)
{
cur_time += VM_COMPLETIONS_PERIOD_LEN;
/* 0 has a special meaning... */
if (!cur_time)
return 1;
return cur_time;
}
/*
* Increment the BDI's writeout completion count and the global writeout
* completion count. Called from test_clear_page_writeback().
*/
static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
{
__inc_bdi_stat(bdi, BDI_WRITTEN);
__fprop_inc_percpu_max(&writeout_completions, &bdi->completions,
bdi->max_prop_frac);
/* First event after period switching was turned off? */
if (!unlikely(writeout_period_time)) {
/*
* We can race with other __bdi_writeout_inc calls here but
* it does not cause any harm since the resulting time when
* timer will fire and what is in writeout_period_time will be
* roughly the same.
*/
writeout_period_time = wp_next_time(jiffies);
mod_timer(&writeout_period_timer, writeout_period_time);
}
}
void bdi_writeout_inc(struct backing_dev_info *bdi)
{
unsigned long flags;
local_irq_save(flags);
__bdi_writeout_inc(bdi);
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(bdi_writeout_inc);
/*
* Obtain an accurate fraction of the BDI's portion.
*/
static void bdi_writeout_fraction(struct backing_dev_info *bdi,
long *numerator, long *denominator)
{
fprop_fraction_percpu(&writeout_completions, &bdi->completions,
numerator, denominator);
}
/*
* On idle system, we can be called long after we scheduled because we use
* deferred timers so count with missed periods.
*/
static void writeout_period(unsigned long t)
{
int miss_periods = (jiffies - writeout_period_time) /
VM_COMPLETIONS_PERIOD_LEN;
if (fprop_new_period(&writeout_completions, miss_periods + 1)) {
writeout_period_time = wp_next_time(writeout_period_time +
miss_periods * VM_COMPLETIONS_PERIOD_LEN);
mod_timer(&writeout_period_timer, writeout_period_time);
} else {
/*
* Aging has zeroed all fractions. Stop wasting CPU on period
* updates.
*/
writeout_period_time = 0;
}
}
/*
* bdi_min_ratio keeps the sum of the minimum dirty shares of all
* registered backing devices, which, for obvious reasons, can not
* exceed 100%.
*/
static unsigned int bdi_min_ratio = 5;
int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
{
int ret = 0;
spin_lock_bh(&bdi_lock);
if (min_ratio > bdi->max_ratio) {
ret = -EINVAL;
} else {
min_ratio -= bdi->min_ratio;
if (bdi_min_ratio + min_ratio < 100) {
bdi_min_ratio += min_ratio;
bdi->min_ratio += min_ratio;
} else {
ret = -EINVAL;
}
}
spin_unlock_bh(&bdi_lock);
return ret;
}
int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
{
int ret = 0;
if (max_ratio > 100)
return -EINVAL;
spin_lock_bh(&bdi_lock);
if (bdi->min_ratio > max_ratio) {
ret = -EINVAL;
} else {
bdi->max_ratio = max_ratio;
bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 100;
}
spin_unlock_bh(&bdi_lock);
return ret;
}
EXPORT_SYMBOL(bdi_set_max_ratio);
static unsigned long dirty_freerun_ceiling(unsigned long thresh,
unsigned long bg_thresh)
{
return (thresh + bg_thresh) / 2;
}
static unsigned long hard_dirty_limit(unsigned long thresh)
{
return max(thresh, global_dirty_limit);
}
/**
* bdi_dirty_limit - @bdi's share of dirty throttling threshold
* @bdi: the backing_dev_info to query
* @dirty: global dirty limit in pages
*
* Returns @bdi's dirty limit in pages. The term "dirty" in the context of
* dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
*
* Note that balance_dirty_pages() will only seriously take it as a hard limit
* when sleeping max_pause per page is not enough to keep the dirty pages under
* control. For example, when the device is completely stalled due to some error
* conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
* In the other normal situations, it acts more gently by throttling the tasks
* more (rather than completely block them) when the bdi dirty pages go high.
*
* It allocates high/low dirty limits to fast/slow devices, in order to prevent
* - starving fast devices
* - piling up dirty pages (that will take long time to sync) on slow devices
*
* The bdi's share of dirty limit will be adapting to its throughput and
* bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
*/
unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
{
u64 bdi_dirty;
long numerator, denominator;
/*
* Calculate this BDI's share of the dirty ratio.
*/
bdi_writeout_fraction(bdi, &numerator, &denominator);
bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
bdi_dirty *= numerator;
do_div(bdi_dirty, denominator);
bdi_dirty += (dirty * bdi->min_ratio) / 100;
if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
bdi_dirty = dirty * bdi->max_ratio / 100;
return bdi_dirty;
}
/*
* setpoint - dirty 3
* f(dirty) := 1.0 + (----------------)
* limit - setpoint
*
* it's a 3rd order polynomial that subjects to
*
* (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
* (2) f(setpoint) = 1.0 => the balance point
* (3) f(limit) = 0 => the hard limit
* (4) df/dx <= 0 => negative feedback control
* (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
* => fast response on large errors; small oscillation near setpoint
*/
static inline long long pos_ratio_polynom(unsigned long setpoint,
unsigned long dirty,
unsigned long limit)
{
long long pos_ratio;
long x;
x = div_s64(((s64)setpoint - (s64)dirty) << RATELIMIT_CALC_SHIFT,
limit - setpoint + 1);
pos_ratio = x;
pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
return clamp(pos_ratio, 0LL, 2LL << RATELIMIT_CALC_SHIFT);
}
/*
* Dirty position control.
*
* (o) global/bdi setpoints
*
* We want the dirty pages be balanced around the global/bdi setpoints.
* When the number of dirty pages is higher/lower than the setpoint, the
* dirty position control ratio (and hence task dirty ratelimit) will be
* decreased/increased to bring the dirty pages back to the setpoint.
*
* pos_ratio = 1 << RATELIMIT_CALC_SHIFT
*
* if (dirty < setpoint) scale up pos_ratio
* if (dirty > setpoint) scale down pos_ratio
*
* if (bdi_dirty < bdi_setpoint) scale up pos_ratio
* if (bdi_dirty > bdi_setpoint) scale down pos_ratio
*
* task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
*
* (o) global control line
*
* ^ pos_ratio
* |
* | |<===== global dirty control scope ======>|
* 2.0 .............*
* | .*
* | . *
* | . *
* | . *
* | . *
* | . *
* 1.0 ................................*
* | . . *
* | . . *
* | . . *
* | . . *
* | . . *
* 0 +------------.------------------.----------------------*------------->
* freerun^ setpoint^ limit^ dirty pages
*
* (o) bdi control line
*
* ^ pos_ratio
* |
* | *
* | *
* | *
* | *
* | * |<=========== span ============>|
* 1.0 .......................*
* | . *
* | . *
* | . *
* | . *
* | . *
* | . *
* | . *
* | . *
* | . *
* | . *
* | . *
* 1/4 ...............................................* * * * * * * * * * * *
* | . .
* | . .
* | . .
* 0 +----------------------.-------------------------------.------------->
* bdi_setpoint^ x_intercept^
*
* The bdi control line won't drop below pos_ratio=1/4, so that bdi_dirty can
* be smoothly throttled down to normal if it starts high in situations like
* - start writing to a slow SD card and a fast disk at the same time. The SD
* card's bdi_dirty may rush to many times higher than bdi_setpoint.
* - the bdi dirty thresh drops quickly due to change of JBOD workload
*/
static unsigned long bdi_position_ratio(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty)
{
unsigned long write_bw = bdi->avg_write_bandwidth;
unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
unsigned long limit = hard_dirty_limit(thresh);
unsigned long x_intercept;
unsigned long setpoint; /* dirty pages' target balance point */
unsigned long bdi_setpoint;
unsigned long span;
long long pos_ratio; /* for scaling up/down the rate limit */
long x;
if (unlikely(dirty >= limit))
return 0;
/*
* global setpoint
*
* See comment for pos_ratio_polynom().
*/
setpoint = (freerun + limit) / 2;
pos_ratio = pos_ratio_polynom(setpoint, dirty, limit);
/*
* The strictlimit feature is a tool preventing mistrusted filesystems
* from growing a large number of dirty pages before throttling. For
* such filesystems balance_dirty_pages always checks bdi counters
* against bdi limits. Even if global "nr_dirty" is under "freerun".
* This is especially important for fuse which sets bdi->max_ratio to
* 1% by default. Without strictlimit feature, fuse writeback may
* consume arbitrary amount of RAM because it is accounted in
* NR_WRITEBACK_TEMP which is not involved in calculating "nr_dirty".
*
* Here, in bdi_position_ratio(), we calculate pos_ratio based on
* two values: bdi_dirty and bdi_thresh. Let's consider an example:
* total amount of RAM is 16GB, bdi->max_ratio is equal to 1%, global
* limits are set by default to 10% and 20% (background and throttle).
* Then bdi_thresh is 1% of 20% of 16GB. This amounts to ~8K pages.
* bdi_dirty_limit(bdi, bg_thresh) is about ~4K pages. bdi_setpoint is
* about ~6K pages (as the average of background and throttle bdi
* limits). The 3rd order polynomial will provide positive feedback if
* bdi_dirty is under bdi_setpoint and vice versa.
*
* Note, that we cannot use global counters in these calculations
* because we want to throttle process writing to a strictlimit BDI
* much earlier than global "freerun" is reached (~23MB vs. ~2.3GB
* in the example above).
*/
if (unlikely(bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
long long bdi_pos_ratio;
unsigned long bdi_bg_thresh;
if (bdi_dirty < 8)
return min_t(long long, pos_ratio * 2,
2 << RATELIMIT_CALC_SHIFT);
if (bdi_dirty >= bdi_thresh)
return 0;
bdi_bg_thresh = div_u64((u64)bdi_thresh * bg_thresh, thresh);
bdi_setpoint = dirty_freerun_ceiling(bdi_thresh,
bdi_bg_thresh);
if (bdi_setpoint == 0 || bdi_setpoint == bdi_thresh)
return 0;
bdi_pos_ratio = pos_ratio_polynom(bdi_setpoint, bdi_dirty,
bdi_thresh);
/*
* Typically, for strictlimit case, bdi_setpoint << setpoint
* and pos_ratio >> bdi_pos_ratio. In the other words global
* state ("dirty") is not limiting factor and we have to
* make decision based on bdi counters. But there is an
* important case when global pos_ratio should get precedence:
* global limits are exceeded (e.g. due to activities on other
* BDIs) while given strictlimit BDI is below limit.
*
* "pos_ratio * bdi_pos_ratio" would work for the case above,
* but it would look too non-natural for the case of all
* activity in the system coming from a single strictlimit BDI
* with bdi->max_ratio == 100%.
*
* Note that min() below somewhat changes the dynamics of the
* control system. Normally, pos_ratio value can be well over 3
* (when globally we are at freerun and bdi is well below bdi
* setpoint). Now the maximum pos_ratio in the same situation
* is 2. We might want to tweak this if we observe the control
* system is too slow to adapt.
*/
return min(pos_ratio, bdi_pos_ratio);
}
/*
* We have computed basic pos_ratio above based on global situation. If
* the bdi is over/under its share of dirty pages, we want to scale
* pos_ratio further down/up. That is done by the following mechanism.
*/
/*
* bdi setpoint
*
* f(bdi_dirty) := 1.0 + k * (bdi_dirty - bdi_setpoint)
*
* x_intercept - bdi_dirty
* := --------------------------
* x_intercept - bdi_setpoint
*
* The main bdi control line is a linear function that subjects to
*
* (1) f(bdi_setpoint) = 1.0
* (2) k = - 1 / (8 * write_bw) (in single bdi case)
* or equally: x_intercept = bdi_setpoint + 8 * write_bw
*
* For single bdi case, the dirty pages are observed to fluctuate
* regularly within range
* [bdi_setpoint - write_bw/2, bdi_setpoint + write_bw/2]
* for various filesystems, where (2) can yield in a reasonable 12.5%
* fluctuation range for pos_ratio.
*
* For JBOD case, bdi_thresh (not bdi_dirty!) could fluctuate up to its
* own size, so move the slope over accordingly and choose a slope that
* yields 100% pos_ratio fluctuation on suddenly doubled bdi_thresh.
*/
if (unlikely(bdi_thresh > thresh))
bdi_thresh = thresh;
/*
* It's very possible that bdi_thresh is close to 0 not because the
* device is slow, but that it has remained inactive for long time.
* Honour such devices a reasonable good (hopefully IO efficient)
* threshold, so that the occasional writes won't be blocked and active
* writes can rampup the threshold quickly.
*/
bdi_thresh = max(bdi_thresh, (limit - dirty) / 8);
/*
* scale global setpoint to bdi's:
* bdi_setpoint = setpoint * bdi_thresh / thresh
*/
x = div_u64((u64)bdi_thresh << 16, thresh + 1);
bdi_setpoint = setpoint * (u64)x >> 16;
/*
* Use span=(8*write_bw) in single bdi case as indicated by
* (thresh - bdi_thresh ~= 0) and transit to bdi_thresh in JBOD case.
*
* bdi_thresh thresh - bdi_thresh
* span = ---------- * (8 * write_bw) + ------------------- * bdi_thresh
* thresh thresh
*/
span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16;
x_intercept = bdi_setpoint + span;
if (bdi_dirty < x_intercept - span / 4) {
pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty),
x_intercept - bdi_setpoint + 1);
} else
pos_ratio /= 4;
/*
* bdi reserve area, safeguard against dirty pool underrun and disk idle
* It may push the desired control point of global dirty pages higher
* than setpoint.
*/
x_intercept = bdi_thresh / 2;
if (bdi_dirty < x_intercept) {
if (bdi_dirty > x_intercept / 8)
pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty);
else
pos_ratio *= 8;
}
return pos_ratio;
}
static void bdi_update_write_bandwidth(struct backing_dev_info *bdi,
unsigned long elapsed,
unsigned long written)
{
const unsigned long period = roundup_pow_of_two(3 * HZ);
unsigned long avg = bdi->avg_write_bandwidth;
unsigned long old = bdi->write_bandwidth;
u64 bw;
/*
* bw = written * HZ / elapsed
*
* bw * elapsed + write_bandwidth * (period - elapsed)
* write_bandwidth = ---------------------------------------------------
* period
*
* @written may have decreased due to account_page_redirty().
* Avoid underflowing @bw calculation.
*/
bw = written - min(written, bdi->written_stamp);
bw *= HZ;
if (unlikely(elapsed > period)) {
do_div(bw, elapsed);
avg = bw;
goto out;
}
bw += (u64)bdi->write_bandwidth * (period - elapsed);
bw >>= ilog2(period);
/*
* one more level of smoothing, for filtering out sudden spikes
*/
if (avg > old && old >= (unsigned long)bw)
avg -= (avg - old) >> 3;
if (avg < old && old <= (unsigned long)bw)
avg += (old - avg) >> 3;
out:
bdi->write_bandwidth = bw;
bdi->avg_write_bandwidth = avg;
}
/*
* The global dirtyable memory and dirty threshold could be suddenly knocked
* down by a large amount (eg. on the startup of KVM in a swapless system).
* This may throw the system into deep dirty exceeded state and throttle
* heavy/light dirtiers alike. To retain good responsiveness, maintain
* global_dirty_limit for tracking slowly down to the knocked down dirty
* threshold.
*/
static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
{
unsigned long limit = global_dirty_limit;
/*
* Follow up in one step.
*/
if (limit < thresh) {
limit = thresh;
goto update;
}
/*
* Follow down slowly. Use the higher one as the target, because thresh
* may drop below dirty. This is exactly the reason to introduce
* global_dirty_limit which is guaranteed to lie above the dirty pages.
*/
thresh = max(thresh, dirty);
if (limit > thresh) {
limit -= (limit - thresh) >> 5;
goto update;
}
return;
update:
global_dirty_limit = limit;
}
static void global_update_bandwidth(unsigned long thresh,
unsigned long dirty,
unsigned long now)
{
static DEFINE_SPINLOCK(dirty_lock);
static unsigned long update_time = INITIAL_JIFFIES;
/*
* check locklessly first to optimize away locking for the most time
*/
if (time_before(now, update_time + BANDWIDTH_INTERVAL))
return;
spin_lock(&dirty_lock);
if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
update_dirty_limit(thresh, dirty);
update_time = now;
}
spin_unlock(&dirty_lock);
}
/*
* Maintain bdi->dirty_ratelimit, the base dirty throttle rate.
*
* Normal bdi tasks will be curbed at or below it in long term.
* Obviously it should be around (write_bw / N) when there are N dd tasks.
*/
static void bdi_update_dirty_ratelimit(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty,
unsigned long dirtied,
unsigned long elapsed)
{
unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
unsigned long limit = hard_dirty_limit(thresh);
unsigned long setpoint = (freerun + limit) / 2;
unsigned long write_bw = bdi->avg_write_bandwidth;
unsigned long dirty_ratelimit = bdi->dirty_ratelimit;
unsigned long dirty_rate;
unsigned long task_ratelimit;
unsigned long balanced_dirty_ratelimit;
unsigned long pos_ratio;
unsigned long step;
unsigned long x;
/*
* The dirty rate will match the writeout rate in long term, except
* when dirty pages are truncated by userspace or re-dirtied by FS.
*/
dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed;
pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty);
/*
* task_ratelimit reflects each dd's dirty rate for the past 200ms.
*/
task_ratelimit = (u64)dirty_ratelimit *
pos_ratio >> RATELIMIT_CALC_SHIFT;
task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
/*
* A linear estimation of the "balanced" throttle rate. The theory is,
* if there are N dd tasks, each throttled at task_ratelimit, the bdi's
* dirty_rate will be measured to be (N * task_ratelimit). So the below
* formula will yield the balanced rate limit (write_bw / N).
*
* Note that the expanded form is not a pure rate feedback:
* rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
* but also takes pos_ratio into account:
* rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
*
* (1) is not realistic because pos_ratio also takes part in balancing
* the dirty rate. Consider the state
* pos_ratio = 0.5 (3)
* rate = 2 * (write_bw / N) (4)
* If (1) is used, it will stuck in that state! Because each dd will
* be throttled at
* task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
* yielding
* dirty_rate = N * task_ratelimit = write_bw (6)
* put (6) into (1) we get
* rate_(i+1) = rate_(i) (7)
*
* So we end up using (2) to always keep
* rate_(i+1) ~= (write_bw / N) (8)
* regardless of the value of pos_ratio. As long as (8) is satisfied,
* pos_ratio is able to drive itself to 1.0, which is not only where
* the dirty count meet the setpoint, but also where the slope of
* pos_ratio is most flat and hence task_ratelimit is least fluctuated.
*/
balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
dirty_rate | 1);
/*
* balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw
*/
if (unlikely(balanced_dirty_ratelimit > write_bw))
balanced_dirty_ratelimit = write_bw;
/*
* We could safely do this and return immediately:
*
* bdi->dirty_ratelimit = balanced_dirty_ratelimit;
*
* However to get a more stable dirty_ratelimit, the below elaborated
* code makes use of task_ratelimit to filter out singular points and
* limit the step size.
*
* The below code essentially only uses the relative value of
*
* task_ratelimit - dirty_ratelimit
* = (pos_ratio - 1) * dirty_ratelimit
*
* which reflects the direction and size of dirty position error.
*/
/*
* dirty_ratelimit will follow balanced_dirty_ratelimit iff
* task_ratelimit is on the same side of dirty_ratelimit, too.
* For example, when
* - dirty_ratelimit > balanced_dirty_ratelimit
* - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
* lowering dirty_ratelimit will help meet both the position and rate
* control targets. Otherwise, don't update dirty_ratelimit if it will
* only help meet the rate target. After all, what the users ultimately
* feel and care are stable dirty rate and small position error.
*
* |task_ratelimit - dirty_ratelimit| is used to limit the step size
* and filter out the singular points of balanced_dirty_ratelimit. Which
* keeps jumping around randomly and can even leap far away at times
* due to the small 200ms estimation period of dirty_rate (we want to
* keep that period small to reduce time lags).
*/
step = 0;
/*
* For strictlimit case, calculations above were based on bdi counters
* and limits (starting from pos_ratio = bdi_position_ratio() and up to
* balanced_dirty_ratelimit = task_ratelimit * write_bw / dirty_rate).
* Hence, to calculate "step" properly, we have to use bdi_dirty as
* "dirty" and bdi_setpoint as "setpoint".
*
* We rampup dirty_ratelimit forcibly if bdi_dirty is low because
* it's possible that bdi_thresh is close to zero due to inactivity
* of backing device (see the implementation of bdi_dirty_limit()).
*/
if (unlikely(bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
dirty = bdi_dirty;
if (bdi_dirty < 8)
setpoint = bdi_dirty + 1;
else
setpoint = (bdi_thresh +
bdi_dirty_limit(bdi, bg_thresh)) / 2;
}
if (dirty < setpoint) {
x = min(bdi->balanced_dirty_ratelimit,
min(balanced_dirty_ratelimit, task_ratelimit));
if (dirty_ratelimit < x)
step = x - dirty_ratelimit;
} else {
x = max(bdi->balanced_dirty_ratelimit,
max(balanced_dirty_ratelimit, task_ratelimit));
if (dirty_ratelimit > x)
step = dirty_ratelimit - x;
}
/*
* Don't pursue 100% rate matching. It's impossible since the balanced
* rate itself is constantly fluctuating. So decrease the track speed
* when it gets close to the target. Helps eliminate pointless tremors.
*/
step >>= dirty_ratelimit / (2 * step + 1);
/*
* Limit the tracking speed to avoid overshooting.
*/
step = (step + 7) / 8;
if (dirty_ratelimit < balanced_dirty_ratelimit)
dirty_ratelimit += step;
else
dirty_ratelimit -= step;
bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
bdi->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
trace_bdi_dirty_ratelimit(bdi, dirty_rate, task_ratelimit);
}
void __bdi_update_bandwidth(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty,
unsigned long start_time)
{
unsigned long now = jiffies;
unsigned long elapsed = now - bdi->bw_time_stamp;
unsigned long dirtied;
unsigned long written;
/*
* rate-limit, only update once every 200ms.
*/
if (elapsed < BANDWIDTH_INTERVAL)
return;
dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]);
written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
/*
* Skip quiet periods when disk bandwidth is under-utilized.
* (at least 1s idle time between two flusher runs)
*/
if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
goto snapshot;
if (thresh) {
global_update_bandwidth(thresh, dirty, now);
bdi_update_dirty_ratelimit(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty,
dirtied, elapsed);
}
bdi_update_write_bandwidth(bdi, elapsed, written);
snapshot:
bdi->dirtied_stamp = dirtied;
bdi->written_stamp = written;
bdi->bw_time_stamp = now;
}
static void bdi_update_bandwidth(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty,
unsigned long start_time)
{
if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
return;
spin_lock(&bdi->wb.list_lock);
__bdi_update_bandwidth(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty, start_time);
spin_unlock(&bdi->wb.list_lock);
}
/*
* After a task dirtied this many pages, balance_dirty_pages_ratelimited()
* will look to see if it needs to start dirty throttling.
*
* If dirty_poll_interval is too low, big NUMA machines will call the expensive
* global_page_state() too often. So scale it near-sqrt to the safety margin
* (the number of pages we may dirty without exceeding the dirty limits).
*/
static unsigned long dirty_poll_interval(unsigned long dirty,
unsigned long thresh)
{
if (thresh > dirty)
return 1UL << (ilog2(thresh - dirty) >> 1);
return 1;
}
static unsigned long bdi_max_pause(struct backing_dev_info *bdi,
unsigned long bdi_dirty)
{
unsigned long bw = bdi->avg_write_bandwidth;
unsigned long t;
/*
* Limit pause time for small memory systems. If sleeping for too long
* time, a small pool of dirty/writeback pages may go empty and disk go
* idle.
*
* 8 serves as the safety ratio.
*/
t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
t++;
return min_t(unsigned long, t, MAX_PAUSE);
}
static long bdi_min_pause(struct backing_dev_info *bdi,
long max_pause,
unsigned long task_ratelimit,
unsigned long dirty_ratelimit,
int *nr_dirtied_pause)
{
long hi = ilog2(bdi->avg_write_bandwidth);
long lo = ilog2(bdi->dirty_ratelimit);
long t; /* target pause */
long pause; /* estimated next pause */
int pages; /* target nr_dirtied_pause */
/* target for 10ms pause on 1-dd case */
t = max(1, HZ / 100);
/*
* Scale up pause time for concurrent dirtiers in order to reduce CPU
* overheads.
*
* (N * 10ms) on 2^N concurrent tasks.
*/
if (hi > lo)
t += (hi - lo) * (10 * HZ) / 1024;
/*
* This is a bit convoluted. We try to base the next nr_dirtied_pause
* on the much more stable dirty_ratelimit. However the next pause time
* will be computed based on task_ratelimit and the two rate limits may
* depart considerably at some time. Especially if task_ratelimit goes
* below dirty_ratelimit/2 and the target pause is max_pause, the next
* pause time will be max_pause*2 _trimmed down_ to max_pause. As a
* result task_ratelimit won't be executed faithfully, which could
* eventually bring down dirty_ratelimit.
*
* We apply two rules to fix it up:
* 1) try to estimate the next pause time and if necessary, use a lower
* nr_dirtied_pause so as not to exceed max_pause. When this happens,
* nr_dirtied_pause will be "dancing" with task_ratelimit.
* 2) limit the target pause time to max_pause/2, so that the normal
* small fluctuations of task_ratelimit won't trigger rule (1) and
* nr_dirtied_pause will remain as stable as dirty_ratelimit.
*/
t = min(t, 1 + max_pause / 2);
pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
/*
* Tiny nr_dirtied_pause is found to hurt I/O performance in the test
* case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
* When the 16 consecutive reads are often interrupted by some dirty
* throttling pause during the async writes, cfq will go into idles
* (deadline is fine). So push nr_dirtied_pause as high as possible
* until reaches DIRTY_POLL_THRESH=32 pages.
*/
if (pages < DIRTY_POLL_THRESH) {
t = max_pause;
pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
if (pages > DIRTY_POLL_THRESH) {
pages = DIRTY_POLL_THRESH;
t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
}
}
pause = HZ * pages / (task_ratelimit + 1);
if (pause > max_pause) {
t = max_pause;
pages = task_ratelimit * t / roundup_pow_of_two(HZ);
}
*nr_dirtied_pause = pages;
/*
* The minimal pause time will normally be half the target pause time.
*/
return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
}
static inline void bdi_dirty_limits(struct backing_dev_info *bdi,
unsigned long dirty_thresh,
unsigned long background_thresh,
unsigned long *bdi_dirty,
unsigned long *bdi_thresh,
unsigned long *bdi_bg_thresh)
{
unsigned long bdi_reclaimable;
/*
* bdi_thresh is not treated as some limiting factor as
* dirty_thresh, due to reasons
* - in JBOD setup, bdi_thresh can fluctuate a lot
* - in a system with HDD and USB key, the USB key may somehow
* go into state (bdi_dirty >> bdi_thresh) either because
* bdi_dirty starts high, or because bdi_thresh drops low.
* In this case we don't want to hard throttle the USB key
* dirtiers for 100 seconds until bdi_dirty drops under
* bdi_thresh. Instead the auxiliary bdi control line in
* bdi_position_ratio() will let the dirtier task progress
* at some rate <= (write_bw / 2) for bringing down bdi_dirty.
*/
*bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
if (bdi_bg_thresh)
*bdi_bg_thresh = div_u64((u64)*bdi_thresh *
background_thresh,
dirty_thresh);
/*
* In order to avoid the stacked BDI deadlock we need
* to ensure we accurately count the 'dirty' pages when
* the threshold is low.
*
* Otherwise it would be possible to get thresh+n pages
* reported dirty, even though there are thresh-m pages
* actually dirty; with m+n sitting in the percpu
* deltas.
*/
if (*bdi_thresh < 2 * bdi_stat_error(bdi)) {
bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
*bdi_dirty = bdi_reclaimable +
bdi_stat_sum(bdi, BDI_WRITEBACK);
} else {
bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
*bdi_dirty = bdi_reclaimable +
bdi_stat(bdi, BDI_WRITEBACK);
}
}
/*
* balance_dirty_pages() must be called by processes which are generating dirty
* data. It looks at the number of dirty pages in the machine and will force
* the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
* If we're over `background_thresh' then the writeback threads are woken to
* perform some writeout.
*/
static void balance_dirty_pages(struct address_space *mapping,
unsigned long pages_dirtied)
{
unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
unsigned long background_thresh;
unsigned long dirty_thresh;
long period;
long pause;
long max_pause;
long min_pause;
int nr_dirtied_pause;
bool dirty_exceeded = false;
unsigned long task_ratelimit;
unsigned long dirty_ratelimit;
unsigned long pos_ratio;
struct backing_dev_info *bdi = mapping->backing_dev_info;
bool strictlimit = bdi->capabilities & BDI_CAP_STRICTLIMIT;
unsigned long start_time = jiffies;
for (;;) {
unsigned long now = jiffies;
unsigned long uninitialized_var(bdi_thresh);
unsigned long thresh;
unsigned long uninitialized_var(bdi_dirty);
unsigned long dirty;
unsigned long bg_thresh;
/*
* Unstable writes are a feature of certain networked
* filesystems (i.e. NFS) in which data may have been
* written to the server's write cache, but has not yet
* been flushed to permanent storage.
*/
nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS);
nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
global_dirty_limits(&background_thresh, &dirty_thresh);
if (unlikely(strictlimit)) {
bdi_dirty_limits(bdi, dirty_thresh, background_thresh,
&bdi_dirty, &bdi_thresh, &bg_thresh);
dirty = bdi_dirty;
thresh = bdi_thresh;
} else {
dirty = nr_dirty;
thresh = dirty_thresh;
bg_thresh = background_thresh;
}
/*
* Throttle it only when the background writeback cannot
* catch-up. This avoids (excessively) small writeouts
* when the bdi limits are ramping up in case of !strictlimit.
*
* In strictlimit case make decision based on the bdi counters
* and limits. Small writeouts when the bdi limits are ramping
* up are the price we consciously pay for strictlimit-ing.
*/
if (dirty <= dirty_freerun_ceiling(thresh, bg_thresh)) {
current->dirty_paused_when = now;
current->nr_dirtied = 0;
current->nr_dirtied_pause =
dirty_poll_interval(dirty, thresh);
break;
}
if (unlikely(!writeback_in_progress(bdi)))
bdi_start_background_writeback(bdi);
if (!strictlimit)
bdi_dirty_limits(bdi, dirty_thresh, background_thresh,
&bdi_dirty, &bdi_thresh, NULL);
dirty_exceeded = (bdi_dirty > bdi_thresh) &&
((nr_dirty > dirty_thresh) || strictlimit);
if (dirty_exceeded && !bdi->dirty_exceeded)
bdi->dirty_exceeded = 1;
bdi_update_bandwidth(bdi, dirty_thresh, background_thresh,
nr_dirty, bdi_thresh, bdi_dirty,
start_time);
dirty_ratelimit = bdi->dirty_ratelimit;
pos_ratio = bdi_position_ratio(bdi, dirty_thresh,
background_thresh, nr_dirty,
bdi_thresh, bdi_dirty);
task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >>
RATELIMIT_CALC_SHIFT;
max_pause = bdi_max_pause(bdi, bdi_dirty);
min_pause = bdi_min_pause(bdi, max_pause,
task_ratelimit, dirty_ratelimit,
&nr_dirtied_pause);
if (unlikely(task_ratelimit == 0)) {
period = max_pause;
pause = max_pause;
goto pause;
}
period = HZ * pages_dirtied / task_ratelimit;
pause = period;
if (current->dirty_paused_when)
pause -= now - current->dirty_paused_when;
/*
* For less than 1s think time (ext3/4 may block the dirtier
* for up to 800ms from time to time on 1-HDD; so does xfs,
* however at much less frequency), try to compensate it in
* future periods by updating the virtual time; otherwise just
* do a reset, as it may be a light dirtier.
*/
if (pause < min_pause) {
trace_balance_dirty_pages(bdi,
dirty_thresh,
background_thresh,
nr_dirty,
bdi_thresh,
bdi_dirty,
dirty_ratelimit,
task_ratelimit,
pages_dirtied,
period,
min(pause, 0L),
start_time);
if (pause < -HZ) {
current->dirty_paused_when = now;
current->nr_dirtied = 0;
} else if (period) {
current->dirty_paused_when += period;
current->nr_dirtied = 0;
} else if (current->nr_dirtied_pause <= pages_dirtied)
current->nr_dirtied_pause += pages_dirtied;
break;
}
if (unlikely(pause > max_pause)) {
/* for occasional dropped task_ratelimit */
now += min(pause - max_pause, max_pause);
pause = max_pause;
}
pause:
trace_balance_dirty_pages(bdi,
dirty_thresh,
background_thresh,
nr_dirty,
bdi_thresh,
bdi_dirty,
dirty_ratelimit,
task_ratelimit,
pages_dirtied,
period,
pause,
start_time);
__set_current_state(TASK_KILLABLE);
io_schedule_timeout(pause);
current->dirty_paused_when = now + pause;
current->nr_dirtied = 0;
current->nr_dirtied_pause = nr_dirtied_pause;
/*
* This is typically equal to (nr_dirty < dirty_thresh) and can
* also keep "1000+ dd on a slow USB stick" under control.
*/
if (task_ratelimit)
break;
/*
* In the case of an unresponding NFS server and the NFS dirty
* pages exceeds dirty_thresh, give the other good bdi's a pipe
* to go through, so that tasks on them still remain responsive.
*
* In theory 1 page is enough to keep the comsumer-producer
* pipe going: the flusher cleans 1 page => the task dirties 1
* more page. However bdi_dirty has accounting errors. So use
* the larger and more IO friendly bdi_stat_error.
*/
if (bdi_dirty <= bdi_stat_error(bdi))
break;
if (fatal_signal_pending(current))
break;
}
if (!dirty_exceeded && bdi->dirty_exceeded)
bdi->dirty_exceeded = 0;
if (writeback_in_progress(bdi))
return;
/*
* In laptop mode, we wait until hitting the higher threshold before
* starting background writeout, and then write out all the way down
* to the lower threshold. So slow writers cause minimal disk activity.
*
* In normal mode, we start background writeout at the lower
* background_thresh, to keep the amount of dirty memory low.
*/
if (laptop_mode)
return;
if (nr_reclaimable > background_thresh)
bdi_start_background_writeback(bdi);
}
void set_page_dirty_balance(struct page *page, int page_mkwrite)
{
if (set_page_dirty(page) || page_mkwrite) {
struct address_space *mapping = page_mapping(page);
if (mapping)
balance_dirty_pages_ratelimited(mapping);
}
}
static DEFINE_PER_CPU(int, bdp_ratelimits);
/*
* Normal tasks are throttled by
* loop {
* dirty tsk->nr_dirtied_pause pages;
* take a snap in balance_dirty_pages();
* }
* However there is a worst case. If every task exit immediately when dirtied
* (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
* called to throttle the page dirties. The solution is to save the not yet
* throttled page dirties in dirty_throttle_leaks on task exit and charge them
* randomly into the running tasks. This works well for the above worst case,
* as the new task will pick up and accumulate the old task's leaked dirty
* count and eventually get throttled.
*/
DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
/**
* balance_dirty_pages_ratelimited - balance dirty memory state
* @mapping: address_space which was dirtied
*
* Processes which are dirtying memory should call in here once for each page
* which was newly dirtied. The function will periodically check the system's
* dirty state and will initiate writeback if needed.
*
* On really big machines, get_writeback_state is expensive, so try to avoid
* calling it too often (ratelimiting). But once we're over the dirty memory
* limit we decrease the ratelimiting by a lot, to prevent individual processes
* from overshooting the limit by (ratelimit_pages) each.
*/
void balance_dirty_pages_ratelimited(struct address_space *mapping)
{
struct backing_dev_info *bdi = mapping->backing_dev_info;
int ratelimit;
int *p;
if (!bdi_cap_account_dirty(bdi))
return;
ratelimit = current->nr_dirtied_pause;
if (bdi->dirty_exceeded)
ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
preempt_disable();
/*
* This prevents one CPU to accumulate too many dirtied pages without
* calling into balance_dirty_pages(), which can happen when there are
* 1000+ tasks, all of them start dirtying pages at exactly the same
* time, hence all honoured too large initial task->nr_dirtied_pause.
*/
p = &__get_cpu_var(bdp_ratelimits);
if (unlikely(current->nr_dirtied >= ratelimit))
*p = 0;
else if (unlikely(*p >= ratelimit_pages)) {
*p = 0;
ratelimit = 0;
}
/*
* Pick up the dirtied pages by the exited tasks. This avoids lots of
* short-lived tasks (eg. gcc invocations in a kernel build) escaping
* the dirty throttling and livelock other long-run dirtiers.
*/
p = &__get_cpu_var(dirty_throttle_leaks);
if (*p > 0 && current->nr_dirtied < ratelimit) {
unsigned long nr_pages_dirtied;
nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
*p -= nr_pages_dirtied;
current->nr_dirtied += nr_pages_dirtied;
}
preempt_enable();
if (unlikely(current->nr_dirtied >= ratelimit))
balance_dirty_pages(mapping, current->nr_dirtied);
}
EXPORT_SYMBOL(balance_dirty_pages_ratelimited);
void throttle_vm_writeout(gfp_t gfp_mask)
{
unsigned long background_thresh;
unsigned long dirty_thresh;
for ( ; ; ) {
global_dirty_limits(&background_thresh, &dirty_thresh);
dirty_thresh = hard_dirty_limit(dirty_thresh);
/*
* Boost the allowable dirty threshold a bit for page
* allocators so they don't get DoS'ed by heavy writers
*/
dirty_thresh += dirty_thresh / 10; /* wheeee... */
if (global_page_state(NR_UNSTABLE_NFS) +
global_page_state(NR_WRITEBACK) <= dirty_thresh)
break;
/* Try safe version */
else if (unlikely(global_page_state_snapshot(NR_UNSTABLE_NFS) +
global_page_state_snapshot(NR_WRITEBACK) <=
dirty_thresh))
break;
congestion_wait(BLK_RW_ASYNC, HZ/10);
/*
* The caller might hold locks which can prevent IO completion
* or progress in the filesystem. So we cannot just sit here
* waiting for IO to complete.
*/
if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
break;
}
}
/*
* sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
*/
int dirty_writeback_centisecs_handler(ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
proc_dointvec(table, write, buffer, length, ppos);
return 0;
}
#ifdef CONFIG_BLOCK
void laptop_mode_timer_fn(unsigned long data)
{
struct request_queue *q = (struct request_queue *)data;
int nr_pages = global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS);
/*
* We want to write everything out, not just down to the dirty
* threshold
*/
if (bdi_has_dirty_io(&q->backing_dev_info))
bdi_start_writeback(&q->backing_dev_info, nr_pages,
WB_REASON_LAPTOP_TIMER);
}
/*
* We've spun up the disk and we're in laptop mode: schedule writeback
* of all dirty data a few seconds from now. If the flush is already scheduled
* then push it back - the user is still using the disk.
*/
void laptop_io_completion(struct backing_dev_info *info)
{
mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
}
/*
* We're in laptop mode and we've just synced. The sync's writes will have
* caused another writeback to be scheduled by laptop_io_completion.
* Nothing needs to be written back anymore, so we unschedule the writeback.
*/
void laptop_sync_completion(void)
{
struct backing_dev_info *bdi;
rcu_read_lock();
list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
del_timer(&bdi->laptop_mode_wb_timer);
rcu_read_unlock();
}
#endif
/*
* If ratelimit_pages is too high then we can get into dirty-data overload
* if a large number of processes all perform writes at the same time.
* If it is too low then SMP machines will call the (expensive)
* get_writeback_state too often.
*
* Here we set ratelimit_pages to a level which ensures that when all CPUs are
* dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
* thresholds.
*/
void writeback_set_ratelimit(void)
{
unsigned long background_thresh;
unsigned long dirty_thresh;
global_dirty_limits(&background_thresh, &dirty_thresh);
global_dirty_limit = dirty_thresh;
ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
if (ratelimit_pages < 16)
ratelimit_pages = 16;
}
static int __cpuinit
ratelimit_handler(struct notifier_block *self, unsigned long action,
void *hcpu)
{
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_ONLINE:
case CPU_DEAD:
writeback_set_ratelimit();
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
static struct notifier_block __cpuinitdata ratelimit_nb = {
.notifier_call = ratelimit_handler,
.next = NULL,
};
/*
* Called early on to tune the page writeback dirty limits.
*
* We used to scale dirty pages according to how total memory
* related to pages that could be allocated for buffers (by
* comparing nr_free_buffer_pages() to vm_total_pages.
*
* However, that was when we used "dirty_ratio" to scale with
* all memory, and we don't do that any more. "dirty_ratio"
* is now applied to total non-HIGHPAGE memory (by subtracting
* totalhigh_pages from vm_total_pages), and as such we can't
* get into the old insane situation any more where we had
* large amounts of dirty pages compared to a small amount of
* non-HIGHMEM memory.
*
* But we might still want to scale the dirty_ratio by how
* much memory the box has..
*/
void __init page_writeback_init(void)
{
writeback_set_ratelimit();
register_cpu_notifier(&ratelimit_nb);
fprop_global_init(&writeout_completions);
}
/**
* tag_pages_for_writeback - tag pages to be written by write_cache_pages
* @mapping: address space structure to write
* @start: starting page index
* @end: ending page index (inclusive)
*
* This function scans the page range from @start to @end (inclusive) and tags
* all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
* that write_cache_pages (or whoever calls this function) will then use
* TOWRITE tag to identify pages eligible for writeback. This mechanism is
* used to avoid livelocking of writeback by a process steadily creating new
* dirty pages in the file (thus it is important for this function to be quick
* so that it can tag pages faster than a dirtying process can create them).
*/
/*
* We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
*/
void tag_pages_for_writeback(struct address_space *mapping,
pgoff_t start, pgoff_t end)
{
#define WRITEBACK_TAG_BATCH 4096
unsigned long tagged;
do {
spin_lock_irq(&mapping->tree_lock);
tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
&start, end, WRITEBACK_TAG_BATCH,
PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
spin_unlock_irq(&mapping->tree_lock);
WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
cond_resched();
/* We check 'start' to handle wrapping when end == ~0UL */
} while (tagged >= WRITEBACK_TAG_BATCH && start);
}
EXPORT_SYMBOL(tag_pages_for_writeback);
/**
* write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
* @mapping: address space structure to write
* @wbc: subtract the number of written pages from *@wbc->nr_to_write
* @writepage: function called for each page
* @data: data passed to writepage function
*
* If a page is already under I/O, write_cache_pages() skips it, even
* if it's dirty. This is desirable behaviour for memory-cleaning writeback,
* but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
* and msync() need to guarantee that all the data which was dirty at the time
* the call was made get new I/O started against them. If wbc->sync_mode is
* WB_SYNC_ALL then we were called for data integrity and we must wait for
* existing IO to complete.
*
* To avoid livelocks (when other process dirties new pages), we first tag
* pages which should be written back with TOWRITE tag and only then start
* writing them. For data-integrity sync we have to be careful so that we do
* not miss some pages (e.g., because some other process has cleared TOWRITE
* tag we set). The rule we follow is that TOWRITE tag can be cleared only
* by the process clearing the DIRTY tag (and submitting the page for IO).
*/
int write_cache_pages(struct address_space *mapping,
struct writeback_control *wbc, writepage_t writepage,
void *data)
{
int ret = 0;
int done = 0;
struct pagevec pvec;
int nr_pages;
pgoff_t uninitialized_var(writeback_index);
pgoff_t index;
pgoff_t end; /* Inclusive */
pgoff_t done_index;
int cycled;
int range_whole = 0;
int tag;
pagevec_init(&pvec, 0);
if (wbc->range_cyclic) {
writeback_index = mapping->writeback_index; /* prev offset */
index = writeback_index;
if (index == 0)
cycled = 1;
else
cycled = 0;
end = -1;
} else {
index = wbc->range_start >> PAGE_CACHE_SHIFT;
end = wbc->range_end >> PAGE_CACHE_SHIFT;
if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
range_whole = 1;
cycled = 1; /* ignore range_cyclic tests */
}
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag = PAGECACHE_TAG_TOWRITE;
else
tag = PAGECACHE_TAG_DIRTY;
retry:
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag_pages_for_writeback(mapping, index, end);
done_index = index;
while (!done && (index <= end)) {
int i;
nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
/*
* At this point, the page may be truncated or
* invalidated (changing page->mapping to NULL), or
* even swizzled back from swapper_space to tmpfs file
* mapping. However, page->index will not change
* because we have a reference on the page.
*/
if (page->index > end) {
/*
* can't be range_cyclic (1st pass) because
* end == -1 in that case.
*/
done = 1;
break;
}
done_index = page->index;
lock_page(page);
/*
* Page truncated or invalidated. We can freely skip it
* then, even for data integrity operations: the page
* has disappeared concurrently, so there could be no
* real expectation of this data interity operation
* even if there is now a new, dirty page at the same
* pagecache address.
*/
if (unlikely(page->mapping != mapping)) {
continue_unlock:
unlock_page(page);
continue;
}
if (!PageDirty(page)) {
/* someone wrote it for us */
goto continue_unlock;
}
if (PageWriteback(page)) {
if (wbc->sync_mode != WB_SYNC_NONE)
wait_on_page_writeback(page);
else
goto continue_unlock;
}
BUG_ON(PageWriteback(page));
if (!clear_page_dirty_for_io(page))
goto continue_unlock;
trace_wbc_writepage(wbc, mapping->backing_dev_info);
ret = (*writepage)(page, wbc, data);
if (unlikely(ret)) {
if (ret == AOP_WRITEPAGE_ACTIVATE) {
unlock_page(page);
ret = 0;
} else {
/*
* done_index is set past this page,
* so media errors will not choke
* background writeout for the entire
* file. This has consequences for
* range_cyclic semantics (ie. it may
* not be suitable for data integrity
* writeout).
*/
done_index = page->index + 1;
done = 1;
break;
}
}
/*
* We stop writing back only if we are not doing
* integrity sync. In case of integrity sync we have to
* keep going until we have written all the pages
* we tagged for writeback prior to entering this loop.
*/
if (--wbc->nr_to_write <= 0 &&
wbc->sync_mode == WB_SYNC_NONE) {
done = 1;
break;
}
}
pagevec_release(&pvec);
cond_resched();
}
if (!cycled && !done) {
/*
* range_cyclic:
* We hit the last page and there is more work to be done: wrap
* back to the start of the file
*/
cycled = 1;
index = 0;
end = writeback_index - 1;
goto retry;
}
if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
mapping->writeback_index = done_index;
return ret;
}
EXPORT_SYMBOL(write_cache_pages);
/*
* Function used by generic_writepages to call the real writepage
* function and set the mapping flags on error
*/
static int __writepage(struct page *page, struct writeback_control *wbc,
void *data)
{
struct address_space *mapping = data;
int ret = mapping->a_ops->writepage(page, wbc);
mapping_set_error(mapping, ret);
return ret;
}
/**
* generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
* @mapping: address space structure to write
* @wbc: subtract the number of written pages from *@wbc->nr_to_write
*
* This is a library function, which implements the writepages()
* address_space_operation.
*/
int generic_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct blk_plug plug;
int ret;
/* deal with chardevs and other special file */
if (!mapping->a_ops->writepage)
return 0;
blk_start_plug(&plug);
ret = write_cache_pages(mapping, wbc, __writepage, mapping);
blk_finish_plug(&plug);
return ret;
}
EXPORT_SYMBOL(generic_writepages);
int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
int ret;
if (wbc->nr_to_write <= 0)
return 0;
if (mapping->a_ops->writepages)
ret = mapping->a_ops->writepages(mapping, wbc);
else
ret = generic_writepages(mapping, wbc);
return ret;
}
/**
* write_one_page - write out a single page and optionally wait on I/O
* @page: the page to write
* @wait: if true, wait on writeout
*
* The page must be locked by the caller and will be unlocked upon return.
*
* write_one_page() returns a negative error code if I/O failed.
*/
int write_one_page(struct page *page, int wait)
{
struct address_space *mapping = page->mapping;
int ret = 0;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = 1,
};
BUG_ON(!PageLocked(page));
if (wait)
wait_on_page_writeback(page);
if (clear_page_dirty_for_io(page)) {
page_cache_get(page);
ret = mapping->a_ops->writepage(page, &wbc);
if (ret == 0 && wait) {
wait_on_page_writeback(page);
if (PageError(page))
ret = -EIO;
}
page_cache_release(page);
} else {
unlock_page(page);
}
return ret;
}
EXPORT_SYMBOL(write_one_page);
/*
* For address_spaces which do not use buffers nor write back.
*/
int __set_page_dirty_no_writeback(struct page *page)
{
if (!PageDirty(page))
return !TestSetPageDirty(page);
return 0;
}
/*
* Helper function for set_page_dirty family.
* NOTE: This relies on being atomic wrt interrupts.
*/
void account_page_dirtied(struct page *page, struct address_space *mapping)
{
trace_writeback_dirty_page(page, mapping);
if (mapping_cap_account_dirty(mapping)) {
__inc_zone_page_state(page, NR_FILE_DIRTY);
__inc_zone_page_state(page, NR_DIRTIED);
__inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
__inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
task_io_account_write(PAGE_CACHE_SIZE);
current->nr_dirtied++;
this_cpu_inc(bdp_ratelimits);
}
}
EXPORT_SYMBOL(account_page_dirtied);
/*
* Helper function for set_page_writeback family.
* NOTE: Unlike account_page_dirtied this does not rely on being atomic
* wrt interrupts.
*/
void account_page_writeback(struct page *page)
{
inc_zone_page_state(page, NR_WRITEBACK);
}
EXPORT_SYMBOL(account_page_writeback);
/*
* For address_spaces which do not use buffers. Just tag the page as dirty in
* its radix tree.
*
* This is also used when a single buffer is being dirtied: we want to set the
* page dirty in that case, but not all the buffers. This is a "bottom-up"
* dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
*
* Most callers have locked the page, which pins the address_space in memory.
* But zap_pte_range() does not lock the page, however in that case the
* mapping is pinned by the vma's ->vm_file reference.
*
* We take care to handle the case where the page was truncated from the
* mapping by re-checking page_mapping() inside tree_lock.
*/
int __set_page_dirty_nobuffers(struct page *page)
{
if (!TestSetPageDirty(page)) {
struct address_space *mapping = page_mapping(page);
struct address_space *mapping2;
unsigned long flags;
if (!mapping)
return 1;
spin_lock_irqsave(&mapping->tree_lock, flags);
mapping2 = page_mapping(page);
if (mapping2) { /* Race with truncate? */
BUG_ON(mapping2 != mapping);
WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
account_page_dirtied(page, mapping);
radix_tree_tag_set(&mapping->page_tree,
page_index(page), PAGECACHE_TAG_DIRTY);
}
spin_unlock_irqrestore(&mapping->tree_lock, flags);
if (mapping->host) {
/* !PageAnon && !swapper_space */
__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
}
return 1;
}
return 0;
}
EXPORT_SYMBOL(__set_page_dirty_nobuffers);
/*
* Call this whenever redirtying a page, to de-account the dirty counters
* (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written
* counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to
* systematic errors in balanced_dirty_ratelimit and the dirty pages position
* control.
*/
void account_page_redirty(struct page *page)
{
struct address_space *mapping = page->mapping;
if (mapping && mapping_cap_account_dirty(mapping)) {
current->nr_dirtied--;
dec_zone_page_state(page, NR_DIRTIED);
dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
}
}
EXPORT_SYMBOL(account_page_redirty);
/*
* When a writepage implementation decides that it doesn't want to write this
* page for some reason, it should redirty the locked page via
* redirty_page_for_writepage() and it should then unlock the page and return 0
*/
int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
{
wbc->pages_skipped++;
account_page_redirty(page);
return __set_page_dirty_nobuffers(page);
}
EXPORT_SYMBOL(redirty_page_for_writepage);
/*
* Dirty a page.
*
* For pages with a mapping this should be done under the page lock
* for the benefit of asynchronous memory errors who prefer a consistent
* dirty state. This rule can be broken in some special cases,
* but should be better not to.
*
* If the mapping doesn't provide a set_page_dirty a_op, then
* just fall through and assume that it wants buffer_heads.
*/
int set_page_dirty(struct page *page)
{
struct address_space *mapping = page_mapping(page);
if (likely(mapping)) {
int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
/*
* readahead/lru_deactivate_page could remain
* PG_readahead/PG_reclaim due to race with end_page_writeback
* About readahead, if the page is written, the flags would be
* reset. So no problem.
* About lru_deactivate_page, if the page is redirty, the flag
* will be reset. So no problem. but if the page is used by readahead
* it will confuse readahead and make it restart the size rampup
* process. But it's a trivial problem.
*/
ClearPageReclaim(page);
#ifdef CONFIG_BLOCK
if (!spd)
spd = __set_page_dirty_buffers;
#endif
return (*spd)(page);
}
if (!PageDirty(page)) {
if (!TestSetPageDirty(page))
return 1;
}
return 0;
}
EXPORT_SYMBOL(set_page_dirty);
/*
* set_page_dirty() is racy if the caller has no reference against
* page->mapping->host, and if the page is unlocked. This is because another
* CPU could truncate the page off the mapping and then free the mapping.
*
* Usually, the page _is_ locked, or the caller is a user-space process which
* holds a reference on the inode by having an open file.
*
* In other cases, the page should be locked before running set_page_dirty().
*/
int set_page_dirty_lock(struct page *page)
{
int ret;
lock_page(page);
ret = set_page_dirty(page);
unlock_page(page);
return ret;
}
EXPORT_SYMBOL(set_page_dirty_lock);
/*
* Clear a page's dirty flag, while caring for dirty memory accounting.
* Returns true if the page was previously dirty.
*
* This is for preparing to put the page under writeout. We leave the page
* tagged as dirty in the radix tree so that a concurrent write-for-sync
* can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
* implementation will run either set_page_writeback() or set_page_dirty(),
* at which stage we bring the page's dirty flag and radix-tree dirty tag
* back into sync.
*
* This incoherency between the page's dirty flag and radix-tree tag is
* unfortunate, but it only exists while the page is locked.
*/
int clear_page_dirty_for_io(struct page *page)
{
struct address_space *mapping = page_mapping(page);
BUG_ON(!PageLocked(page));
if (mapping && mapping_cap_account_dirty(mapping)) {
/*
* Yes, Virginia, this is indeed insane.
*
* We use this sequence to make sure that
* (a) we account for dirty stats properly
* (b) we tell the low-level filesystem to
* mark the whole page dirty if it was
* dirty in a pagetable. Only to then
* (c) clean the page again and return 1 to
* cause the writeback.
*
* This way we avoid all nasty races with the
* dirty bit in multiple places and clearing
* them concurrently from different threads.
*
* Note! Normally the "set_page_dirty(page)"
* has no effect on the actual dirty bit - since
* that will already usually be set. But we
* need the side effects, and it can help us
* avoid races.
*
* We basically use the page "master dirty bit"
* as a serialization point for all the different
* threads doing their things.
*/
if (page_mkclean(page))
set_page_dirty(page);
/*
* We carefully synchronise fault handlers against
* installing a dirty pte and marking the page dirty
* at this point. We do this by having them hold the
* page lock at some point after installing their
* pte, but before marking the page dirty.
* Pages are always locked coming in here, so we get
* the desired exclusion. See mm/memory.c:do_wp_page()
* for more comments.
*/
if (TestClearPageDirty(page)) {
dec_zone_page_state(page, NR_FILE_DIRTY);
dec_bdi_stat(mapping->backing_dev_info,
BDI_RECLAIMABLE);
return 1;
}
return 0;
}
return TestClearPageDirty(page);
}
EXPORT_SYMBOL(clear_page_dirty_for_io);
int test_clear_page_writeback(struct page *page)
{
struct address_space *mapping = page_mapping(page);
int ret;
if (mapping) {
struct backing_dev_info *bdi = mapping->backing_dev_info;
unsigned long flags;
spin_lock_irqsave(&mapping->tree_lock, flags);
ret = TestClearPageWriteback(page);
if (ret) {
radix_tree_tag_clear(&mapping->page_tree,
page_index(page),
PAGECACHE_TAG_WRITEBACK);
if (bdi_cap_account_writeback(bdi)) {
__dec_bdi_stat(bdi, BDI_WRITEBACK);
__bdi_writeout_inc(bdi);
}
}
spin_unlock_irqrestore(&mapping->tree_lock, flags);
} else {
ret = TestClearPageWriteback(page);
}
if (ret) {
dec_zone_page_state(page, NR_WRITEBACK);
inc_zone_page_state(page, NR_WRITTEN);
}
return ret;
}
int test_set_page_writeback(struct page *page)
{
struct address_space *mapping = page_mapping(page);
int ret;
if (mapping) {
struct backing_dev_info *bdi = mapping->backing_dev_info;
unsigned long flags;
spin_lock_irqsave(&mapping->tree_lock, flags);
ret = TestSetPageWriteback(page);
if (!ret) {
radix_tree_tag_set(&mapping->page_tree,
page_index(page),
PAGECACHE_TAG_WRITEBACK);
if (bdi_cap_account_writeback(bdi))
__inc_bdi_stat(bdi, BDI_WRITEBACK);
}
if (!PageDirty(page))
radix_tree_tag_clear(&mapping->page_tree,
page_index(page),
PAGECACHE_TAG_DIRTY);
radix_tree_tag_clear(&mapping->page_tree,
page_index(page),
PAGECACHE_TAG_TOWRITE);
spin_unlock_irqrestore(&mapping->tree_lock, flags);
} else {
ret = TestSetPageWriteback(page);
}
if (!ret)
account_page_writeback(page);
return ret;
}
EXPORT_SYMBOL(test_set_page_writeback);
/*
* Return true if any of the pages in the mapping are marked with the
* passed tag.
*/
int mapping_tagged(struct address_space *mapping, int tag)
{
return radix_tree_tagged(&mapping->page_tree, tag);
}
EXPORT_SYMBOL(mapping_tagged);
/**
* wait_for_stable_page() - wait for writeback to finish, if necessary.
* @page: The page to wait on.
*
* This function determines if the given page is related to a backing device
* that requires page contents to be held stable during writeback. If so, then
* it will wait for any pending writeback to complete.
*/
void wait_for_stable_page(struct page *page)
{
struct address_space *mapping = page_mapping(page);
struct backing_dev_info *bdi = mapping->backing_dev_info;
if (!bdi_cap_stable_pages_required(bdi))
return;
wait_on_page_writeback(page);
}
EXPORT_SYMBOL_GPL(wait_for_stable_page);
| Java |
<?php
/**
* Чистый Шаблон для разработки
* Шаблон вывода поста
* http://dontforget.pro
* @package WordPress
* @subpackage clean
*/
get_header(); // Подключаем хедер?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); // Начало цикла ?>
<h1><?php the_title(); // Заголовок ?></h1>
<?php the_content(); // Содержимое страницы ?>
<?php echo 'Рубрики: '; the_category( ' | ' ); // Выводим категории поста ?>
<?php the_tags( 'Тэги: ', ' | ', '' ); // Выводим тэги(метки) поста ?>
<?php endwhile; // Конец цикла ?>
<?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'twentyten' ) . '</span> %title' ); // Ссылка на предидущий пост?>
<?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'twentyten' ) . '</span>' ); // Ссылка на следующий пост?>
<?php comments_template( '', true ); // Комментарии ?>
<?php get_sidebar(); // Подключаем сайдбар ?>
<?php get_footer(); // Подключаем футер ?> | Java |
/*
* This file is part of wl1271
*
* Copyright (C) 2008-2010 Nokia Corporation
*
* Contact: Luciano Coelho <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/module.h>
#include <linux/firmware.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/crc32.h>
#include <linux/etherdevice.h>
#include <linux/vmalloc.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/wl12xx.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include "wl12xx.h"
#include "debug.h"
#include "wl12xx_80211.h"
#include "reg.h"
#include "io.h"
#include "event.h"
#include "tx.h"
#include "rx.h"
#include "ps.h"
#include "init.h"
#include "debugfs.h"
#include "cmd.h"
#include "boot.h"
#include "testmode.h"
#include "scan.h"
#define WL1271_BOOT_RETRIES 3
static struct conf_drv_settings default_conf = {
.sg = {
.params = {
[CONF_SG_ACL_BT_MASTER_MIN_BR] = 10,
[CONF_SG_ACL_BT_MASTER_MAX_BR] = 180,
[CONF_SG_ACL_BT_SLAVE_MIN_BR] = 10,
[CONF_SG_ACL_BT_SLAVE_MAX_BR] = 180,
[CONF_SG_ACL_BT_MASTER_MIN_EDR] = 10,
[CONF_SG_ACL_BT_MASTER_MAX_EDR] = 80,
[CONF_SG_ACL_BT_SLAVE_MIN_EDR] = 10,
[CONF_SG_ACL_BT_SLAVE_MAX_EDR] = 80,
[CONF_SG_ACL_WLAN_PS_MASTER_BR] = 8,
[CONF_SG_ACL_WLAN_PS_SLAVE_BR] = 8,
[CONF_SG_ACL_WLAN_PS_MASTER_EDR] = 20,
[CONF_SG_ACL_WLAN_PS_SLAVE_EDR] = 20,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_BR] = 20,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_BR] = 35,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_BR] = 16,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_BR] = 35,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_EDR] = 32,
[CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_EDR] = 50,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_EDR] = 28,
[CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_EDR] = 50,
[CONF_SG_ACL_ACTIVE_SCAN_WLAN_BR] = 10,
[CONF_SG_ACL_ACTIVE_SCAN_WLAN_EDR] = 20,
[CONF_SG_ACL_PASSIVE_SCAN_BT_BR] = 75,
[CONF_SG_ACL_PASSIVE_SCAN_WLAN_BR] = 15,
[CONF_SG_ACL_PASSIVE_SCAN_BT_EDR] = 27,
[CONF_SG_ACL_PASSIVE_SCAN_WLAN_EDR] = 17,
/* active scan params */
[CONF_SG_AUTO_SCAN_PROBE_REQ] = 170,
[CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_HV3] = 50,
[CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_A2DP] = 100,
/* passive scan params */
[CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_BR] = 800,
[CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_EDR] = 200,
[CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_HV3] = 200,
/* passive scan in dual antenna params */
[CONF_SG_CONSECUTIVE_HV3_IN_PASSIVE_SCAN] = 0,
[CONF_SG_BCN_HV3_COLLISION_THRESH_IN_PASSIVE_SCAN] = 0,
[CONF_SG_TX_RX_PROTECTION_BWIDTH_IN_PASSIVE_SCAN] = 0,
/* general params */
[CONF_SG_STA_FORCE_PS_IN_BT_SCO] = 1,
[CONF_SG_ANTENNA_CONFIGURATION] = 0,
[CONF_SG_BEACON_MISS_PERCENT] = 60,
[CONF_SG_DHCP_TIME] = 5000,
[CONF_SG_RXT] = 1200,
[CONF_SG_TXT] = 1000,
[CONF_SG_ADAPTIVE_RXT_TXT] = 1,
[CONF_SG_GENERAL_USAGE_BIT_MAP] = 3,
[CONF_SG_HV3_MAX_SERVED] = 6,
[CONF_SG_PS_POLL_TIMEOUT] = 10,
[CONF_SG_UPSD_TIMEOUT] = 10,
[CONF_SG_CONSECUTIVE_CTS_THRESHOLD] = 2,
[CONF_SG_STA_RX_WINDOW_AFTER_DTIM] = 5,
[CONF_SG_STA_CONNECTION_PROTECTION_TIME] = 30,
/* AP params */
[CONF_AP_BEACON_MISS_TX] = 3,
[CONF_AP_RX_WINDOW_AFTER_BEACON] = 10,
[CONF_AP_BEACON_WINDOW_INTERVAL] = 2,
[CONF_AP_CONNECTION_PROTECTION_TIME] = 0,
[CONF_AP_BT_ACL_VAL_BT_SERVE_TIME] = 25,
[CONF_AP_BT_ACL_VAL_WL_SERVE_TIME] = 25,
/* CTS Diluting params */
[CONF_SG_CTS_DILUTED_BAD_RX_PACKETS_TH] = 0,
[CONF_SG_CTS_CHOP_IN_DUAL_ANT_SCO_MASTER] = 0,
},
.state = CONF_SG_PROTECTIVE,
},
.rx = {
.rx_msdu_life_time = 512000,
.packet_detection_threshold = 0,
.ps_poll_timeout = 15,
.upsd_timeout = 15,
.rts_threshold = IEEE80211_MAX_RTS_THRESHOLD,
.rx_cca_threshold = 0,
.irq_blk_threshold = 0xFFFF,
.irq_pkt_threshold = 0,
.irq_timeout = 600,
.queue_type = CONF_RX_QUEUE_TYPE_LOW_PRIORITY,
},
.tx = {
.tx_energy_detection = 0,
.sta_rc_conf = {
.enabled_rates = 0,
.short_retry_limit = 10,
.long_retry_limit = 10,
.aflags = 0,
},
.ac_conf_count = 4,
.ac_conf = {
[CONF_TX_AC_BE] = {
.ac = CONF_TX_AC_BE,
.cw_min = 15,
.cw_max = 63,
.aifsn = 3,
.tx_op_limit = 0,
},
[CONF_TX_AC_BK] = {
.ac = CONF_TX_AC_BK,
.cw_min = 15,
.cw_max = 63,
.aifsn = 7,
.tx_op_limit = 0,
},
[CONF_TX_AC_VI] = {
.ac = CONF_TX_AC_VI,
.cw_min = 15,
.cw_max = 63,
.aifsn = CONF_TX_AIFS_PIFS,
.tx_op_limit = 3008,
},
[CONF_TX_AC_VO] = {
.ac = CONF_TX_AC_VO,
.cw_min = 15,
.cw_max = 63,
.aifsn = CONF_TX_AIFS_PIFS,
.tx_op_limit = 1504,
},
},
.max_tx_retries = 100,
.ap_aging_period = 300,
.tid_conf_count = 4,
.tid_conf = {
[CONF_TX_AC_BE] = {
.queue_id = CONF_TX_AC_BE,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_BE,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_BK] = {
.queue_id = CONF_TX_AC_BK,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_BK,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_VI] = {
.queue_id = CONF_TX_AC_VI,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_VI,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_VO] = {
.queue_id = CONF_TX_AC_VO,
.channel_type = CONF_CHANNEL_TYPE_EDCF,
.tsid = CONF_TX_AC_VO,
.ps_scheme = CONF_PS_SCHEME_LEGACY,
.ack_policy = CONF_ACK_POLICY_LEGACY,
.apsd_conf = {0, 0},
},
},
.frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD,
.tx_compl_timeout = 700,
.tx_compl_threshold = 4,
.basic_rate = CONF_HW_BIT_RATE_1MBPS,
.basic_rate_5 = CONF_HW_BIT_RATE_6MBPS,
.tmpl_short_retry_limit = 10,
.tmpl_long_retry_limit = 10,
.tx_watchdog_timeout = 5000,
},
.conn = {
.wake_up_event = CONF_WAKE_UP_EVENT_DTIM,
.listen_interval = 1,
.suspend_wake_up_event = CONF_WAKE_UP_EVENT_N_DTIM,
.suspend_listen_interval = 3,
.bcn_filt_mode = CONF_BCN_FILT_MODE_ENABLED,
.bcn_filt_ie_count = 2,
.bcn_filt_ie = {
[0] = {
.ie = WLAN_EID_CHANNEL_SWITCH,
.rule = CONF_BCN_RULE_PASS_ON_APPEARANCE,
},
[1] = {
.ie = WLAN_EID_HT_INFORMATION,
.rule = CONF_BCN_RULE_PASS_ON_CHANGE,
},
},
.synch_fail_thold = 10,
.bss_lose_timeout = 100,
.beacon_rx_timeout = 10000,
.broadcast_timeout = 20000,
.rx_broadcast_in_ps = 1,
.ps_poll_threshold = 10,
.bet_enable = CONF_BET_MODE_ENABLE,
.bet_max_consecutive = 50,
.psm_entry_retries = 8,
.psm_exit_retries = 16,
.psm_entry_nullfunc_retries = 3,
.dynamic_ps_timeout = 200,
.forced_ps = false,
.keep_alive_interval = 55000,
.max_listen_interval = 20,
},
.itrim = {
.enable = false,
.timeout = 50000,
},
.pm_config = {
.host_clk_settling_time = 5000,
.host_fast_wakeup_support = false
},
.roam_trigger = {
.trigger_pacing = 1,
.avg_weight_rssi_beacon = 20,
.avg_weight_rssi_data = 10,
.avg_weight_snr_beacon = 20,
.avg_weight_snr_data = 10,
},
.scan = {
.min_dwell_time_active = 7500,
.max_dwell_time_active = 30000,
.min_dwell_time_passive = 100000,
.max_dwell_time_passive = 100000,
.num_probe_reqs = 2,
.split_scan_timeout = 50000,
},
.sched_scan = {
/* sched_scan requires dwell times in TU instead of TU/1000 */
.min_dwell_time_active = 30,
.max_dwell_time_active = 60,
.dwell_time_passive = 100,
.dwell_time_dfs = 150,
.num_probe_reqs = 2,
.rssi_threshold = -90,
.snr_threshold = 0,
},
.rf = {
.tx_per_channel_power_compensation_2 = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
.tx_per_channel_power_compensation_5 = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
},
.ht = {
.rx_ba_win_size = 8,
.tx_ba_win_size = 64,
.inactivity_timeout = 10000,
.tx_ba_tid_bitmap = CONF_TX_BA_ENABLED_TID_BITMAP,
},
.mem_wl127x = {
.num_stations = 1,
.ssid_profiles = 1,
.rx_block_num = 70,
.tx_min_block_num = 40,
.dynamic_memory = 1,
.min_req_tx_blocks = 100,
.min_req_rx_blocks = 22,
.tx_min = 27,
},
.mem_wl128x = {
.num_stations = 1,
.ssid_profiles = 1,
.rx_block_num = 40,
.tx_min_block_num = 40,
.dynamic_memory = 1,
.min_req_tx_blocks = 45,
.min_req_rx_blocks = 22,
.tx_min = 27,
},
.fm_coex = {
.enable = true,
.swallow_period = 5,
.n_divider_fref_set_1 = 0xff, /* default */
.n_divider_fref_set_2 = 12,
.m_divider_fref_set_1 = 148,
.m_divider_fref_set_2 = 0xffff, /* default */
.coex_pll_stabilization_time = 0xffffffff, /* default */
.ldo_stabilization_time = 0xffff, /* default */
.fm_disturbed_band_margin = 0xff, /* default */
.swallow_clk_diff = 0xff, /* default */
},
.rx_streaming = {
.duration = 150,
.queues = 0x1,
.interval = 20,
.always = 0,
},
.fwlog = {
.mode = WL12XX_FWLOG_ON_DEMAND,
.mem_blocks = 2,
.severity = 0,
.timestamp = WL12XX_FWLOG_TIMESTAMP_DISABLED,
.output = WL12XX_FWLOG_OUTPUT_HOST,
.threshold = 0,
},
.hci_io_ds = HCI_IO_DS_6MA,
.rate = {
.rate_retry_score = 32000,
.per_add = 8192,
.per_th1 = 2048,
.per_th2 = 4096,
.max_per = 8100,
.inverse_curiosity_factor = 5,
.tx_fail_low_th = 4,
.tx_fail_high_th = 10,
.per_alpha_shift = 4,
.per_add_shift = 13,
.per_beta1_shift = 10,
.per_beta2_shift = 8,
.rate_check_up = 2,
.rate_check_down = 12,
.rate_retry_policy = {
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00,
},
},
.hangover = {
.recover_time = 0,
.hangover_period = 20,
.dynamic_mode = 1,
.early_termination_mode = 1,
.max_period = 20,
.min_period = 1,
.increase_delta = 1,
.decrease_delta = 2,
.quiet_time = 4,
.increase_time = 1,
.window_size = 16,
},
};
static char *fwlog_param;
static bool bug_on_recovery;
static void __wl1271_op_remove_interface(struct wl1271 *wl,
struct ieee80211_vif *vif,
bool reset_tx_queues);
static void wl1271_op_stop(struct ieee80211_hw *hw);
static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif);
static int wl12xx_set_authorized(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret;
if (WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS))
return -EINVAL;
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
return 0;
if (test_and_set_bit(WLVIF_FLAG_STA_STATE_SENT, &wlvif->flags))
return 0;
ret = wl12xx_cmd_set_peer_state(wl, wlvif->sta.hlid);
if (ret < 0)
return ret;
wl12xx_croc(wl, wlvif->role_id);
wl1271_info("Association completed.");
return 0;
}
static int wl1271_reg_notify(struct wiphy *wiphy,
struct regulatory_request *request)
{
struct ieee80211_supported_band *band;
struct ieee80211_channel *ch;
int i;
band = wiphy->bands[IEEE80211_BAND_5GHZ];
for (i = 0; i < band->n_channels; i++) {
ch = &band->channels[i];
if (ch->flags & IEEE80211_CHAN_DISABLED)
continue;
if (ch->flags & IEEE80211_CHAN_RADAR)
ch->flags |= IEEE80211_CHAN_NO_IBSS |
IEEE80211_CHAN_PASSIVE_SCAN;
}
return 0;
}
static int wl1271_set_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool enable)
{
int ret = 0;
/* we should hold wl->mutex */
ret = wl1271_acx_ps_rx_streaming(wl, wlvif, enable);
if (ret < 0)
goto out;
if (enable)
set_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags);
else
clear_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags);
out:
return ret;
}
/*
* this function is being called when the rx_streaming interval
* has beed changed or rx_streaming should be disabled
*/
int wl1271_recalc_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int ret = 0;
int period = wl->conf.rx_streaming.interval;
/* don't reconfigure if rx_streaming is disabled */
if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags))
goto out;
/* reconfigure/disable according to new streaming_period */
if (period &&
test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) &&
(wl->conf.rx_streaming.always ||
test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags)))
ret = wl1271_set_rx_streaming(wl, wlvif, true);
else {
ret = wl1271_set_rx_streaming(wl, wlvif, false);
/* don't cancel_work_sync since we might deadlock */
del_timer_sync(&wlvif->rx_streaming_timer);
}
out:
return ret;
}
static void wl1271_rx_streaming_enable_work(struct work_struct *work)
{
int ret;
struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif,
rx_streaming_enable_work);
struct wl1271 *wl = wlvif->wl;
mutex_lock(&wl->mutex);
if (test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags) ||
!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) ||
(!wl->conf.rx_streaming.always &&
!test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags)))
goto out;
if (!wl->conf.rx_streaming.interval)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_set_rx_streaming(wl, wlvif, true);
if (ret < 0)
goto out_sleep;
/* stop it after some time of inactivity */
mod_timer(&wlvif->rx_streaming_timer,
jiffies + msecs_to_jiffies(wl->conf.rx_streaming.duration));
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1271_rx_streaming_disable_work(struct work_struct *work)
{
int ret;
struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif,
rx_streaming_disable_work);
struct wl1271 *wl = wlvif->wl;
mutex_lock(&wl->mutex);
if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_set_rx_streaming(wl, wlvif, false);
if (ret)
goto out_sleep;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1271_rx_streaming_timer(unsigned long data)
{
struct wl12xx_vif *wlvif = (struct wl12xx_vif *)data;
struct wl1271 *wl = wlvif->wl;
ieee80211_queue_work(wl->hw, &wlvif->rx_streaming_disable_work);
}
/* wl->mutex must be taken */
void wl12xx_rearm_tx_watchdog_locked(struct wl1271 *wl)
{
/* if the watchdog is not armed, don't do anything */
if (wl->tx_allocated_blocks == 0)
return;
cancel_delayed_work(&wl->tx_watchdog_work);
ieee80211_queue_delayed_work(wl->hw, &wl->tx_watchdog_work,
msecs_to_jiffies(wl->conf.tx.tx_watchdog_timeout));
}
static void wl12xx_tx_watchdog_work(struct work_struct *work)
{
struct delayed_work *dwork;
struct wl1271 *wl;
dwork = container_of(work, struct delayed_work, work);
wl = container_of(dwork, struct wl1271, tx_watchdog_work);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
/* Tx went out in the meantime - everything is ok */
if (unlikely(wl->tx_allocated_blocks == 0))
goto out;
/*
* if a ROC is in progress, we might not have any Tx for a long
* time (e.g. pending Tx on the non-ROC channels)
*/
if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to ROC",
wl->conf.tx.tx_watchdog_timeout);
wl12xx_rearm_tx_watchdog_locked(wl);
goto out;
}
/*
* if a scan is in progress, we might not have any Tx for a long
* time
*/
if (wl->scan.state != WL1271_SCAN_STATE_IDLE) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to scan",
wl->conf.tx.tx_watchdog_timeout);
wl12xx_rearm_tx_watchdog_locked(wl);
goto out;
}
/*
* AP might cache a frame for a long time for a sleeping station,
* so rearm the timer if there's an AP interface with stations. If
* Tx is genuinely stuck we will most hopefully discover it when all
* stations are removed due to inactivity.
*/
if (wl->active_sta_count) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms. AP has "
" %d stations",
wl->conf.tx.tx_watchdog_timeout,
wl->active_sta_count);
wl12xx_rearm_tx_watchdog_locked(wl);
goto out;
}
wl1271_error("Tx stuck (in FW) for %d ms. Starting recovery",
wl->conf.tx.tx_watchdog_timeout);
wl12xx_queue_recovery_work(wl);
out:
mutex_unlock(&wl->mutex);
}
static void wl1271_conf_init(struct wl1271 *wl)
{
/*
* This function applies the default configuration to the driver. This
* function is invoked upon driver load (spi probe.)
*
* The configuration is stored in a run-time structure in order to
* facilitate for run-time adjustment of any of the parameters. Making
* changes to the configuration structure will apply the new values on
* the next interface up (wl1271_op_start.)
*/
/* apply driver default configuration */
memcpy(&wl->conf, &default_conf, sizeof(default_conf));
/* Adjust settings according to optional module parameters */
if (fwlog_param) {
if (!strcmp(fwlog_param, "continuous")) {
wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS;
} else if (!strcmp(fwlog_param, "ondemand")) {
wl->conf.fwlog.mode = WL12XX_FWLOG_ON_DEMAND;
} else if (!strcmp(fwlog_param, "dbgpins")) {
wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS;
wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_DBG_PINS;
} else if (!strcmp(fwlog_param, "disable")) {
wl->conf.fwlog.mem_blocks = 0;
wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_NONE;
} else {
wl1271_error("Unknown fwlog parameter %s", fwlog_param);
}
}
}
static int wl1271_plt_init(struct wl1271 *wl)
{
int ret;
if (wl->chip.id == CHIP_ID_1283_PG20)
ret = wl128x_cmd_general_parms(wl);
else
ret = wl1271_cmd_general_parms(wl);
if (ret < 0)
return ret;
if (wl->chip.id == CHIP_ID_1283_PG20)
ret = wl128x_cmd_radio_parms(wl);
else
ret = wl1271_cmd_radio_parms(wl);
if (ret < 0)
return ret;
if (wl->chip.id != CHIP_ID_1283_PG20) {
ret = wl1271_cmd_ext_radio_parms(wl);
if (ret < 0)
return ret;
}
/* Chip-specific initializations */
ret = wl1271_chip_specific_init(wl);
if (ret < 0)
return ret;
ret = wl1271_acx_init_mem_config(wl);
if (ret < 0)
return ret;
ret = wl12xx_acx_mem_cfg(wl);
if (ret < 0)
goto out_free_memmap;
/* Enable data path */
ret = wl1271_cmd_data_path(wl, 1);
if (ret < 0)
goto out_free_memmap;
/* Configure for CAM power saving (ie. always active) */
ret = wl1271_acx_sleep_auth(wl, WL1271_PSM_CAM);
if (ret < 0)
goto out_free_memmap;
/* configure PM */
ret = wl1271_acx_pm_config(wl);
if (ret < 0)
goto out_free_memmap;
return 0;
out_free_memmap:
kfree(wl->target_mem_map);
wl->target_mem_map = NULL;
return ret;
}
static void wl12xx_irq_ps_regulate_link(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
u8 hlid, u8 tx_pkts)
{
bool fw_ps, single_sta;
fw_ps = test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map);
single_sta = (wl->active_sta_count == 1);
/*
* Wake up from high level PS if the STA is asleep with too little
* packets in FW or if the STA is awake.
*/
if (!fw_ps || tx_pkts < WL1271_PS_STA_MAX_PACKETS)
wl12xx_ps_link_end(wl, wlvif, hlid);
/*
* Start high-level PS if the STA is asleep with enough blocks in FW.
* Make an exception if this is the only connected station. In this
* case FW-memory congestion is not a problem.
*/
else if (!single_sta && fw_ps && tx_pkts >= WL1271_PS_STA_MAX_PACKETS)
wl12xx_ps_link_start(wl, wlvif, hlid, true);
}
static void wl12xx_irq_update_links_status(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct wl12xx_fw_status *status)
{
struct wl1271_link *lnk;
u32 cur_fw_ps_map;
u8 hlid, cnt;
/* TODO: also use link_fast_bitmap here */
cur_fw_ps_map = le32_to_cpu(status->link_ps_bitmap);
if (wl->ap_fw_ps_map != cur_fw_ps_map) {
wl1271_debug(DEBUG_PSM,
"link ps prev 0x%x cur 0x%x changed 0x%x",
wl->ap_fw_ps_map, cur_fw_ps_map,
wl->ap_fw_ps_map ^ cur_fw_ps_map);
wl->ap_fw_ps_map = cur_fw_ps_map;
}
for_each_set_bit(hlid, wlvif->ap.sta_hlid_map, WL12XX_MAX_LINKS) {
lnk = &wl->links[hlid];
cnt = status->tx_lnk_free_pkts[hlid] - lnk->prev_freed_pkts;
lnk->prev_freed_pkts = status->tx_lnk_free_pkts[hlid];
lnk->allocated_pkts -= cnt;
wl12xx_irq_ps_regulate_link(wl, wlvif, hlid,
lnk->allocated_pkts);
}
}
static void wl12xx_fw_status(struct wl1271 *wl,
struct wl12xx_fw_status *status)
{
struct wl12xx_vif *wlvif;
struct timespec ts;
u32 old_tx_blk_count = wl->tx_blocks_available;
int avail, freed_blocks;
int i;
wl1271_raw_read(wl, FW_STATUS_ADDR, status, sizeof(*status), false);
wl1271_debug(DEBUG_IRQ, "intr: 0x%x (fw_rx_counter = %d, "
"drv_rx_counter = %d, tx_results_counter = %d)",
status->intr,
status->fw_rx_counter,
status->drv_rx_counter,
status->tx_results_counter);
for (i = 0; i < NUM_TX_QUEUES; i++) {
/* prevent wrap-around in freed-packets counter */
wl->tx_allocated_pkts[i] -=
(status->tx_released_pkts[i] -
wl->tx_pkts_freed[i]) & 0xff;
wl->tx_pkts_freed[i] = status->tx_released_pkts[i];
}
/* prevent wrap-around in total blocks counter */
if (likely(wl->tx_blocks_freed <=
le32_to_cpu(status->total_released_blks)))
freed_blocks = le32_to_cpu(status->total_released_blks) -
wl->tx_blocks_freed;
else
freed_blocks = 0x100000000LL - wl->tx_blocks_freed +
le32_to_cpu(status->total_released_blks);
wl->tx_blocks_freed = le32_to_cpu(status->total_released_blks);
wl->tx_allocated_blocks -= freed_blocks;
/*
* If the FW freed some blocks:
* If we still have allocated blocks - re-arm the timer, Tx is
* not stuck. Otherwise, cancel the timer (no Tx currently).
*/
if (freed_blocks) {
if (wl->tx_allocated_blocks)
wl12xx_rearm_tx_watchdog_locked(wl);
else
cancel_delayed_work(&wl->tx_watchdog_work);
}
avail = le32_to_cpu(status->tx_total) - wl->tx_allocated_blocks;
/*
* The FW might change the total number of TX memblocks before
* we get a notification about blocks being released. Thus, the
* available blocks calculation might yield a temporary result
* which is lower than the actual available blocks. Keeping in
* mind that only blocks that were allocated can be moved from
* TX to RX, tx_blocks_available should never decrease here.
*/
wl->tx_blocks_available = max((int)wl->tx_blocks_available,
avail);
/* if more blocks are available now, tx work can be scheduled */
if (wl->tx_blocks_available > old_tx_blk_count)
clear_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags);
/* for AP update num of allocated TX blocks per link and ps status */
wl12xx_for_each_wlvif_ap(wl, wlvif) {
wl12xx_irq_update_links_status(wl, wlvif, status);
}
/* update the host-chipset time offset */
getnstimeofday(&ts);
wl->time_offset = (timespec_to_ns(&ts) >> 10) -
(s64)le32_to_cpu(status->fw_localtime);
}
static void wl1271_flush_deferred_work(struct wl1271 *wl)
{
struct sk_buff *skb;
/* Pass all received frames to the network stack */
while ((skb = skb_dequeue(&wl->deferred_rx_queue)))
ieee80211_rx_ni(wl->hw, skb);
/* Return sent skbs to the network stack */
while ((skb = skb_dequeue(&wl->deferred_tx_queue)))
ieee80211_tx_status_ni(wl->hw, skb);
}
static void wl1271_netstack_work(struct work_struct *work)
{
struct wl1271 *wl =
container_of(work, struct wl1271, netstack_work);
do {
wl1271_flush_deferred_work(wl);
} while (skb_queue_len(&wl->deferred_rx_queue));
}
#define WL1271_IRQ_MAX_LOOPS 256
static irqreturn_t wl1271_irq(int irq, void *cookie)
{
int ret;
u32 intr;
int loopcount = WL1271_IRQ_MAX_LOOPS;
struct wl1271 *wl = (struct wl1271 *)cookie;
bool done = false;
unsigned int defer_count;
unsigned long flags;
/* TX might be handled here, avoid redundant work */
set_bit(WL1271_FLAG_TX_PENDING, &wl->flags);
cancel_work_sync(&wl->tx_work);
/*
* In case edge triggered interrupt must be used, we cannot iterate
* more than once without introducing race conditions with the hardirq.
*/
if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ)
loopcount = 1;
mutex_lock(&wl->mutex);
wl1271_debug(DEBUG_IRQ, "IRQ work");
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
while (!done && loopcount--) {
/*
* In order to avoid a race with the hardirq, clear the flag
* before acknowledging the chip. Since the mutex is held,
* wl1271_ps_elp_wakeup cannot be called concurrently.
*/
clear_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags);
smp_mb__after_clear_bit();
wl12xx_fw_status(wl, wl->fw_status);
intr = le32_to_cpu(wl->fw_status->intr);
intr &= WL1271_INTR_MASK;
if (!intr) {
done = true;
continue;
}
if (unlikely(intr & WL1271_ACX_INTR_WATCHDOG)) {
wl1271_error("watchdog interrupt received! "
"starting recovery.");
wl12xx_queue_recovery_work(wl);
/* restarting the chip. ignore any other interrupt. */
goto out;
}
if (likely(intr & WL1271_ACX_INTR_DATA)) {
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_DATA");
wl12xx_rx(wl, wl->fw_status);
/* Check if any tx blocks were freed */
spin_lock_irqsave(&wl->wl_lock, flags);
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) &&
wl1271_tx_total_queue_count(wl) > 0) {
spin_unlock_irqrestore(&wl->wl_lock, flags);
/*
* In order to avoid starvation of the TX path,
* call the work function directly.
*/
wl1271_tx_work_locked(wl);
} else {
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
/* check for tx results */
if (wl->fw_status->tx_results_counter !=
(wl->tx_results_count & 0xff))
wl1271_tx_complete(wl);
/* Make sure the deferred queues don't get too long */
defer_count = skb_queue_len(&wl->deferred_tx_queue) +
skb_queue_len(&wl->deferred_rx_queue);
if (defer_count > WL1271_DEFERRED_QUEUE_LIMIT)
wl1271_flush_deferred_work(wl);
}
if (intr & WL1271_ACX_INTR_EVENT_A) {
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_A");
wl1271_event_handle(wl, 0);
}
if (intr & WL1271_ACX_INTR_EVENT_B) {
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_B");
wl1271_event_handle(wl, 1);
}
if (intr & WL1271_ACX_INTR_INIT_COMPLETE)
wl1271_debug(DEBUG_IRQ,
"WL1271_ACX_INTR_INIT_COMPLETE");
if (intr & WL1271_ACX_INTR_HW_AVAILABLE)
wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_HW_AVAILABLE");
}
wl1271_ps_elp_sleep(wl);
out:
spin_lock_irqsave(&wl->wl_lock, flags);
/* In case TX was not handled here, queue TX work */
clear_bit(WL1271_FLAG_TX_PENDING, &wl->flags);
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) &&
wl1271_tx_total_queue_count(wl) > 0)
ieee80211_queue_work(wl->hw, &wl->tx_work);
spin_unlock_irqrestore(&wl->wl_lock, flags);
mutex_unlock(&wl->mutex);
return IRQ_HANDLED;
}
struct vif_counter_data {
u8 counter;
struct ieee80211_vif *cur_vif;
bool cur_vif_running;
};
static void wl12xx_vif_count_iter(void *data, u8 *mac,
struct ieee80211_vif *vif)
{
struct vif_counter_data *counter = data;
counter->counter++;
if (counter->cur_vif == vif)
counter->cur_vif_running = true;
}
/* caller must not hold wl->mutex, as it might deadlock */
static void wl12xx_get_vif_count(struct ieee80211_hw *hw,
struct ieee80211_vif *cur_vif,
struct vif_counter_data *data)
{
memset(data, 0, sizeof(*data));
data->cur_vif = cur_vif;
ieee80211_iterate_active_interfaces(hw,
wl12xx_vif_count_iter, data);
}
static int wl12xx_fetch_firmware(struct wl1271 *wl, bool plt)
{
const struct firmware *fw;
const char *fw_name;
enum wl12xx_fw_type fw_type;
int ret;
if (plt) {
fw_type = WL12XX_FW_TYPE_PLT;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = WL128X_PLT_FW_NAME;
else
fw_name = WL127X_PLT_FW_NAME;
} else {
/*
* we can't call wl12xx_get_vif_count() here because
* wl->mutex is taken, so use the cached last_vif_count value
*/
if (wl->last_vif_count > 1) {
fw_type = WL12XX_FW_TYPE_MULTI;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = WL128X_FW_NAME_MULTI;
else
fw_name = WL127X_FW_NAME_MULTI;
} else {
fw_type = WL12XX_FW_TYPE_NORMAL;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = WL128X_FW_NAME_SINGLE;
else
fw_name = WL127X_FW_NAME_SINGLE;
}
}
if (wl->fw_type == fw_type)
return 0;
wl1271_debug(DEBUG_BOOT, "booting firmware %s", fw_name);
ret = request_firmware(&fw, fw_name, wl->dev);
if (ret < 0) {
wl1271_error("could not get firmware %s: %d", fw_name, ret);
return ret;
}
if (fw->size % 4) {
wl1271_error("firmware size is not multiple of 32 bits: %zu",
fw->size);
ret = -EILSEQ;
goto out;
}
vfree(wl->fw);
wl->fw_type = WL12XX_FW_TYPE_NONE;
wl->fw_len = fw->size;
wl->fw = vmalloc(wl->fw_len);
if (!wl->fw) {
wl1271_error("could not allocate memory for the firmware");
ret = -ENOMEM;
goto out;
}
memcpy(wl->fw, fw->data, wl->fw_len);
ret = 0;
wl->fw_type = fw_type;
out:
release_firmware(fw);
return ret;
}
static int wl1271_fetch_nvs(struct wl1271 *wl)
{
const struct firmware *fw;
int ret;
ret = request_firmware(&fw, WL12XX_NVS_NAME, wl->dev);
if (ret < 0) {
wl1271_error("could not get nvs file %s: %d", WL12XX_NVS_NAME,
ret);
return ret;
}
wl->nvs = kmemdup(fw->data, fw->size, GFP_KERNEL);
if (!wl->nvs) {
wl1271_error("could not allocate memory for the nvs file");
ret = -ENOMEM;
goto out;
}
wl->nvs_len = fw->size;
out:
release_firmware(fw);
return ret;
}
void wl12xx_queue_recovery_work(struct wl1271 *wl)
{
if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags))
ieee80211_queue_work(wl->hw, &wl->recovery_work);
}
size_t wl12xx_copy_fwlog(struct wl1271 *wl, u8 *memblock, size_t maxlen)
{
size_t len = 0;
/* The FW log is a length-value list, find where the log end */
while (len < maxlen) {
if (memblock[len] == 0)
break;
if (len + memblock[len] + 1 > maxlen)
break;
len += memblock[len] + 1;
}
/* Make sure we have enough room */
len = min(len, (size_t)(PAGE_SIZE - wl->fwlog_size));
/* Fill the FW log file, consumed by the sysfs fwlog entry */
memcpy(wl->fwlog + wl->fwlog_size, memblock, len);
wl->fwlog_size += len;
return len;
}
static void wl12xx_read_fwlog_panic(struct wl1271 *wl)
{
u32 addr;
u32 first_addr;
u8 *block;
if ((wl->quirks & WL12XX_QUIRK_FWLOG_NOT_IMPLEMENTED) ||
(wl->conf.fwlog.mode != WL12XX_FWLOG_ON_DEMAND) ||
(wl->conf.fwlog.mem_blocks == 0))
return;
wl1271_info("Reading FW panic log");
block = kmalloc(WL12XX_HW_BLOCK_SIZE, GFP_KERNEL);
if (!block)
return;
/*
* Make sure the chip is awake and the logger isn't active.
* This might fail if the firmware hanged.
*/
if (!wl1271_ps_elp_wakeup(wl))
wl12xx_cmd_stop_fwlog(wl);
/* Read the first memory block address */
wl12xx_fw_status(wl, wl->fw_status);
first_addr = le32_to_cpu(wl->fw_status->log_start_addr);
if (!first_addr)
goto out;
/* Traverse the memory blocks linked list */
addr = first_addr;
do {
memset(block, 0, WL12XX_HW_BLOCK_SIZE);
wl1271_read_hwaddr(wl, addr, block, WL12XX_HW_BLOCK_SIZE,
false);
/*
* Memory blocks are linked to one another. The first 4 bytes
* of each memory block hold the hardware address of the next
* one. The last memory block points to the first one.
*/
addr = le32_to_cpup((__le32 *)block);
if (!wl12xx_copy_fwlog(wl, block + sizeof(addr),
WL12XX_HW_BLOCK_SIZE - sizeof(addr)))
break;
} while (addr && (addr != first_addr));
wake_up_interruptible(&wl->fwlog_waitq);
out:
kfree(block);
}
static void wl1271_recovery_work(struct work_struct *work)
{
struct wl1271 *wl =
container_of(work, struct wl1271, recovery_work);
struct wl12xx_vif *wlvif;
struct ieee80211_vif *vif;
mutex_lock(&wl->mutex);
if (wl->state != WL1271_STATE_ON || wl->plt)
goto out_unlock;
/* Avoid a recursive recovery */
set_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags);
wl12xx_read_fwlog_panic(wl);
wl1271_info("Hardware recovery in progress. FW ver: %s pc: 0x%x",
wl->chip.fw_ver_str, wl1271_read32(wl, SCR_PAD4));
BUG_ON(bug_on_recovery &&
!test_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags));
/*
* Advance security sequence number to overcome potential progress
* in the firmware during recovery. This doens't hurt if the network is
* not encrypted.
*/
wl12xx_for_each_wlvif(wl, wlvif) {
if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) ||
test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags))
wlvif->tx_security_seq +=
WL1271_TX_SQN_POST_RECOVERY_PADDING;
}
/* Prevent spurious TX during FW restart */
ieee80211_stop_queues(wl->hw);
if (wl->sched_scanning) {
ieee80211_sched_scan_stopped(wl->hw);
wl->sched_scanning = false;
}
/* reboot the chipset */
while (!list_empty(&wl->wlvif_list)) {
wlvif = list_first_entry(&wl->wlvif_list,
struct wl12xx_vif, list);
vif = wl12xx_wlvif_to_vif(wlvif);
__wl1271_op_remove_interface(wl, vif, false);
}
mutex_unlock(&wl->mutex);
wl1271_op_stop(wl->hw);
clear_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags);
ieee80211_restart_hw(wl->hw);
/*
* Its safe to enable TX now - the queues are stopped after a request
* to restart the HW.
*/
ieee80211_wake_queues(wl->hw);
return;
out_unlock:
mutex_unlock(&wl->mutex);
}
static void wl1271_fw_wakeup(struct wl1271 *wl)
{
u32 elp_reg;
elp_reg = ELPCTRL_WAKE_UP;
wl1271_raw_write32(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, elp_reg);
}
static int wl1271_setup(struct wl1271 *wl)
{
wl->fw_status = kmalloc(sizeof(*wl->fw_status), GFP_KERNEL);
if (!wl->fw_status)
return -ENOMEM;
wl->tx_res_if = kmalloc(sizeof(*wl->tx_res_if), GFP_KERNEL);
if (!wl->tx_res_if) {
kfree(wl->fw_status);
return -ENOMEM;
}
return 0;
}
static int wl12xx_set_power_on(struct wl1271 *wl)
{
int ret;
msleep(WL1271_PRE_POWER_ON_SLEEP);
ret = wl1271_power_on(wl);
if (ret < 0)
goto out;
msleep(WL1271_POWER_ON_SLEEP);
wl1271_io_reset(wl);
wl1271_io_init(wl);
wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]);
/* ELP module wake up */
wl1271_fw_wakeup(wl);
out:
return ret;
}
static int wl12xx_chip_wakeup(struct wl1271 *wl, bool plt)
{
int ret = 0;
ret = wl12xx_set_power_on(wl);
if (ret < 0)
goto out;
/*
* For wl127x based devices we could use the default block
* size (512 bytes), but due to a bug in the sdio driver, we
* need to set it explicitly after the chip is powered on. To
* simplify the code and since the performance impact is
* negligible, we use the same block size for all different
* chip types.
*/
if (!wl1271_set_block_size(wl))
wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT;
switch (wl->chip.id) {
case CHIP_ID_1271_PG10:
wl1271_warning("chip id 0x%x (1271 PG10) support is obsolete",
wl->chip.id);
ret = wl1271_setup(wl);
if (ret < 0)
goto out;
wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT;
break;
case CHIP_ID_1271_PG20:
wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1271 PG20)",
wl->chip.id);
ret = wl1271_setup(wl);
if (ret < 0)
goto out;
wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT;
break;
case CHIP_ID_1283_PG20:
wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1283 PG20)",
wl->chip.id);
ret = wl1271_setup(wl);
if (ret < 0)
goto out;
break;
case CHIP_ID_1283_PG10:
default:
wl1271_warning("unsupported chip id: 0x%x", wl->chip.id);
ret = -ENODEV;
goto out;
}
ret = wl12xx_fetch_firmware(wl, plt);
if (ret < 0)
goto out;
/* No NVS from netlink, try to get it from the filesystem */
if (wl->nvs == NULL) {
ret = wl1271_fetch_nvs(wl);
if (ret < 0)
goto out;
}
out:
return ret;
}
int wl1271_plt_start(struct wl1271 *wl)
{
int retries = WL1271_BOOT_RETRIES;
struct wiphy *wiphy = wl->hw->wiphy;
int ret;
mutex_lock(&wl->mutex);
wl1271_notice("power up");
if (wl->state != WL1271_STATE_OFF) {
wl1271_error("cannot go into PLT state because not "
"in off state: %d", wl->state);
ret = -EBUSY;
goto out;
}
while (retries) {
retries--;
ret = wl12xx_chip_wakeup(wl, true);
if (ret < 0)
goto power_off;
ret = wl1271_boot(wl);
if (ret < 0)
goto power_off;
ret = wl1271_plt_init(wl);
if (ret < 0)
goto irq_disable;
wl->plt = true;
wl->state = WL1271_STATE_ON;
wl1271_notice("firmware booted in PLT mode (%s)",
wl->chip.fw_ver_str);
/* update hw/fw version info in wiphy struct */
wiphy->hw_version = wl->chip.id;
strncpy(wiphy->fw_version, wl->chip.fw_ver_str,
sizeof(wiphy->fw_version));
goto out;
irq_disable:
mutex_unlock(&wl->mutex);
/* Unlocking the mutex in the middle of handling is
inherently unsafe. In this case we deem it safe to do,
because we need to let any possibly pending IRQ out of
the system (and while we are WL1271_STATE_OFF the IRQ
work function will not do anything.) Also, any other
possible concurrent operations will fail due to the
current state, hence the wl1271 struct should be safe. */
wl1271_disable_interrupts(wl);
wl1271_flush_deferred_work(wl);
cancel_work_sync(&wl->netstack_work);
mutex_lock(&wl->mutex);
power_off:
wl1271_power_off(wl);
}
wl1271_error("firmware boot in PLT mode failed despite %d retries",
WL1271_BOOT_RETRIES);
out:
mutex_unlock(&wl->mutex);
return ret;
}
int wl1271_plt_stop(struct wl1271 *wl)
{
int ret = 0;
wl1271_notice("power down");
/*
* Interrupts must be disabled before setting the state to OFF.
* Otherwise, the interrupt handler might be called and exit without
* reading the interrupt status.
*/
wl1271_disable_interrupts(wl);
mutex_lock(&wl->mutex);
if (!wl->plt) {
mutex_unlock(&wl->mutex);
/*
* This will not necessarily enable interrupts as interrupts
* may have been disabled when op_stop was called. It will,
* however, balance the above call to disable_interrupts().
*/
wl1271_enable_interrupts(wl);
wl1271_error("cannot power down because not in PLT "
"state: %d", wl->state);
ret = -EBUSY;
goto out;
}
mutex_unlock(&wl->mutex);
wl1271_flush_deferred_work(wl);
cancel_work_sync(&wl->netstack_work);
cancel_work_sync(&wl->recovery_work);
cancel_delayed_work_sync(&wl->elp_work);
cancel_delayed_work_sync(&wl->tx_watchdog_work);
mutex_lock(&wl->mutex);
wl1271_power_off(wl);
wl->flags = 0;
wl->state = WL1271_STATE_OFF;
wl->plt = false;
wl->rx_counter = 0;
mutex_unlock(&wl->mutex);
out:
return ret;
}
static void wl1271_op_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct wl1271 *wl = hw->priv;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_vif *vif = info->control.vif;
struct wl12xx_vif *wlvif = NULL;
unsigned long flags;
int q, mapping;
u8 hlid;
if (vif)
wlvif = wl12xx_vif_to_data(vif);
mapping = skb_get_queue_mapping(skb);
q = wl1271_tx_get_queue(mapping);
hlid = wl12xx_tx_get_hlid(wl, wlvif, skb);
spin_lock_irqsave(&wl->wl_lock, flags);
/* queue the packet */
if (hlid == WL12XX_INVALID_LINK_ID ||
(wlvif && !test_bit(hlid, wlvif->links_map))) {
wl1271_debug(DEBUG_TX, "DROP skb hlid %d q %d", hlid, q);
ieee80211_free_txskb(hw, skb);
goto out;
}
wl1271_debug(DEBUG_TX, "queue skb hlid %d q %d len %d",
hlid, q, skb->len);
skb_queue_tail(&wl->links[hlid].tx_queue[q], skb);
wl->tx_queue_count[q]++;
/*
* The workqueue is slow to process the tx_queue and we need stop
* the queue here, otherwise the queue will get too long.
*/
if (wl->tx_queue_count[q] >= WL1271_TX_QUEUE_HIGH_WATERMARK) {
wl1271_debug(DEBUG_TX, "op_tx: stopping queues for q %d", q);
ieee80211_stop_queue(wl->hw, mapping);
set_bit(q, &wl->stopped_queues_map);
}
/*
* The chip specific setup must run before the first TX packet -
* before that, the tx_work will not be initialized!
*/
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) &&
!test_bit(WL1271_FLAG_TX_PENDING, &wl->flags))
ieee80211_queue_work(wl->hw, &wl->tx_work);
out:
spin_unlock_irqrestore(&wl->wl_lock, flags);
}
int wl1271_tx_dummy_packet(struct wl1271 *wl)
{
unsigned long flags;
int q;
/* no need to queue a new dummy packet if one is already pending */
if (test_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags))
return 0;
q = wl1271_tx_get_queue(skb_get_queue_mapping(wl->dummy_packet));
spin_lock_irqsave(&wl->wl_lock, flags);
set_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags);
wl->tx_queue_count[q]++;
spin_unlock_irqrestore(&wl->wl_lock, flags);
/* The FW is low on RX memory blocks, so send the dummy packet asap */
if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags))
wl1271_tx_work_locked(wl);
/*
* If the FW TX is busy, TX work will be scheduled by the threaded
* interrupt handler function
*/
return 0;
}
/*
* The size of the dummy packet should be at least 1400 bytes. However, in
* order to minimize the number of bus transactions, aligning it to 512 bytes
* boundaries could be beneficial, performance wise
*/
#define TOTAL_TX_DUMMY_PACKET_SIZE (ALIGN(1400, 512))
static struct sk_buff *wl12xx_alloc_dummy_packet(struct wl1271 *wl)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr *hdr;
unsigned int dummy_packet_size;
dummy_packet_size = TOTAL_TX_DUMMY_PACKET_SIZE -
sizeof(struct wl1271_tx_hw_descr) - sizeof(*hdr);
skb = dev_alloc_skb(TOTAL_TX_DUMMY_PACKET_SIZE);
if (!skb) {
wl1271_warning("Failed to allocate a dummy packet skb");
return NULL;
}
skb_reserve(skb, sizeof(struct wl1271_tx_hw_descr));
hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr));
memset(hdr, 0, sizeof(*hdr));
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC |
IEEE80211_FCTL_TODS);
memset(skb_put(skb, dummy_packet_size), 0, dummy_packet_size);
/* Dummy packets require the TID to be management */
skb->priority = WL1271_TID_MGMT;
/* Initialize all fields that might be used */
skb_set_queue_mapping(skb, 0);
memset(IEEE80211_SKB_CB(skb), 0, sizeof(struct ieee80211_tx_info));
return skb;
}
#ifdef CONFIG_PM
static int wl1271_configure_suspend_sta(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
mutex_lock(&wl->mutex);
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
goto out_unlock;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
ret = wl1271_acx_wake_up_conditions(wl, wlvif,
wl->conf.conn.suspend_wake_up_event,
wl->conf.conn.suspend_listen_interval);
if (ret < 0)
wl1271_error("suspend: set wake up conditions failed: %d", ret);
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_configure_suspend_ap(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
mutex_lock(&wl->mutex);
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags))
goto out_unlock;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
ret = wl1271_acx_beacon_filter_opt(wl, wlvif, true);
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_configure_suspend(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
if (wlvif->bss_type == BSS_TYPE_STA_BSS)
return wl1271_configure_suspend_sta(wl, wlvif);
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
return wl1271_configure_suspend_ap(wl, wlvif);
return 0;
}
static void wl1271_configure_resume(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS;
bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS;
if ((!is_ap) && (!is_sta))
return;
mutex_lock(&wl->mutex);
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (is_sta) {
ret = wl1271_acx_wake_up_conditions(wl, wlvif,
wl->conf.conn.wake_up_event,
wl->conf.conn.listen_interval);
if (ret < 0)
wl1271_error("resume: wake up conditions failed: %d",
ret);
} else if (is_ap) {
ret = wl1271_acx_beacon_filter_opt(wl, wlvif, false);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_op_suspend(struct ieee80211_hw *hw,
struct cfg80211_wowlan *wow)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 suspend wow=%d", !!wow);
WARN_ON(!wow || !wow->any);
wl1271_tx_flush(wl);
wl->wow_enabled = true;
wl12xx_for_each_wlvif(wl, wlvif) {
ret = wl1271_configure_suspend(wl, wlvif);
if (ret < 0) {
wl1271_warning("couldn't prepare device to suspend");
return ret;
}
}
/* flush any remaining work */
wl1271_debug(DEBUG_MAC80211, "flushing remaining works");
/*
* disable and re-enable interrupts in order to flush
* the threaded_irq
*/
wl1271_disable_interrupts(wl);
/*
* set suspended flag to avoid triggering a new threaded_irq
* work. no need for spinlock as interrupts are disabled.
*/
set_bit(WL1271_FLAG_SUSPENDED, &wl->flags);
wl1271_enable_interrupts(wl);
flush_work(&wl->tx_work);
flush_delayed_work(&wl->elp_work);
return 0;
}
static int wl1271_op_resume(struct ieee80211_hw *hw)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
unsigned long flags;
bool run_irq_work = false;
wl1271_debug(DEBUG_MAC80211, "mac80211 resume wow=%d",
wl->wow_enabled);
WARN_ON(!wl->wow_enabled);
/*
* re-enable irq_work enqueuing, and call irq_work directly if
* there is a pending work.
*/
spin_lock_irqsave(&wl->wl_lock, flags);
clear_bit(WL1271_FLAG_SUSPENDED, &wl->flags);
if (test_and_clear_bit(WL1271_FLAG_PENDING_WORK, &wl->flags))
run_irq_work = true;
spin_unlock_irqrestore(&wl->wl_lock, flags);
if (run_irq_work) {
wl1271_debug(DEBUG_MAC80211,
"run postponed irq_work directly");
wl1271_irq(0, wl);
wl1271_enable_interrupts(wl);
}
wl12xx_for_each_wlvif(wl, wlvif) {
wl1271_configure_resume(wl, wlvif);
}
wl->wow_enabled = false;
return 0;
}
#endif
static int wl1271_op_start(struct ieee80211_hw *hw)
{
wl1271_debug(DEBUG_MAC80211, "mac80211 start");
/*
* We have to delay the booting of the hardware because
* we need to know the local MAC address before downloading and
* initializing the firmware. The MAC address cannot be changed
* after boot, and without the proper MAC address, the firmware
* will not function properly.
*
* The MAC address is first known when the corresponding interface
* is added. That is where we will initialize the hardware.
*/
return 0;
}
static void wl1271_op_stop(struct ieee80211_hw *hw)
{
struct wl1271 *wl = hw->priv;
int i;
wl1271_debug(DEBUG_MAC80211, "mac80211 stop");
/*
* Interrupts must be disabled before setting the state to OFF.
* Otherwise, the interrupt handler might be called and exit without
* reading the interrupt status.
*/
wl1271_disable_interrupts(wl);
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
mutex_unlock(&wl->mutex);
/*
* This will not necessarily enable interrupts as interrupts
* may have been disabled when op_stop was called. It will,
* however, balance the above call to disable_interrupts().
*/
wl1271_enable_interrupts(wl);
return;
}
/*
* this must be before the cancel_work calls below, so that the work
* functions don't perform further work.
*/
wl->state = WL1271_STATE_OFF;
mutex_unlock(&wl->mutex);
wl1271_flush_deferred_work(wl);
cancel_delayed_work_sync(&wl->scan_complete_work);
cancel_work_sync(&wl->netstack_work);
cancel_work_sync(&wl->tx_work);
cancel_delayed_work_sync(&wl->elp_work);
cancel_delayed_work_sync(&wl->tx_watchdog_work);
/* let's notify MAC80211 about the remaining pending TX frames */
wl12xx_tx_reset(wl, true);
mutex_lock(&wl->mutex);
wl1271_power_off(wl);
wl->band = IEEE80211_BAND_2GHZ;
wl->rx_counter = 0;
wl->power_level = WL1271_DEFAULT_POWER_LEVEL;
wl->tx_blocks_available = 0;
wl->tx_allocated_blocks = 0;
wl->tx_results_count = 0;
wl->tx_packets_count = 0;
wl->time_offset = 0;
wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
wl->ap_fw_ps_map = 0;
wl->ap_ps_map = 0;
wl->sched_scanning = false;
memset(wl->roles_map, 0, sizeof(wl->roles_map));
memset(wl->links_map, 0, sizeof(wl->links_map));
memset(wl->roc_map, 0, sizeof(wl->roc_map));
wl->active_sta_count = 0;
/* The system link is always allocated */
__set_bit(WL12XX_SYSTEM_HLID, wl->links_map);
/*
* this is performed after the cancel_work calls and the associated
* mutex_lock, so that wl1271_op_add_interface does not accidentally
* get executed before all these vars have been reset.
*/
wl->flags = 0;
wl->tx_blocks_freed = 0;
for (i = 0; i < NUM_TX_QUEUES; i++) {
wl->tx_pkts_freed[i] = 0;
wl->tx_allocated_pkts[i] = 0;
}
wl1271_debugfs_reset(wl);
kfree(wl->fw_status);
wl->fw_status = NULL;
kfree(wl->tx_res_if);
wl->tx_res_if = NULL;
kfree(wl->target_mem_map);
wl->target_mem_map = NULL;
mutex_unlock(&wl->mutex);
}
static int wl12xx_allocate_rate_policy(struct wl1271 *wl, u8 *idx)
{
u8 policy = find_first_zero_bit(wl->rate_policies_map,
WL12XX_MAX_RATE_POLICIES);
if (policy >= WL12XX_MAX_RATE_POLICIES)
return -EBUSY;
__set_bit(policy, wl->rate_policies_map);
*idx = policy;
return 0;
}
static void wl12xx_free_rate_policy(struct wl1271 *wl, u8 *idx)
{
if (WARN_ON(*idx >= WL12XX_MAX_RATE_POLICIES))
return;
__clear_bit(*idx, wl->rate_policies_map);
*idx = WL12XX_MAX_RATE_POLICIES;
}
static u8 wl12xx_get_role_type(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
switch (wlvif->bss_type) {
case BSS_TYPE_AP_BSS:
if (wlvif->p2p)
return WL1271_ROLE_P2P_GO;
else
return WL1271_ROLE_AP;
case BSS_TYPE_STA_BSS:
if (wlvif->p2p)
return WL1271_ROLE_P2P_CL;
else
return WL1271_ROLE_STA;
case BSS_TYPE_IBSS:
return WL1271_ROLE_IBSS;
default:
wl1271_error("invalid bss_type: %d", wlvif->bss_type);
}
return WL12XX_INVALID_ROLE_TYPE;
}
static int wl12xx_init_vif_data(struct wl1271 *wl, struct ieee80211_vif *vif)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int i;
/* clear everything but the persistent data */
memset(wlvif, 0, offsetof(struct wl12xx_vif, persistent));
switch (ieee80211_vif_type_p2p(vif)) {
case NL80211_IFTYPE_P2P_CLIENT:
wlvif->p2p = 1;
/* fall-through */
case NL80211_IFTYPE_STATION:
wlvif->bss_type = BSS_TYPE_STA_BSS;
break;
case NL80211_IFTYPE_ADHOC:
wlvif->bss_type = BSS_TYPE_IBSS;
break;
case NL80211_IFTYPE_P2P_GO:
wlvif->p2p = 1;
/* fall-through */
case NL80211_IFTYPE_AP:
wlvif->bss_type = BSS_TYPE_AP_BSS;
break;
default:
wlvif->bss_type = MAX_BSS_TYPE;
return -EOPNOTSUPP;
}
wlvif->role_id = WL12XX_INVALID_ROLE_ID;
wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID;
wlvif->dev_hlid = WL12XX_INVALID_LINK_ID;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
/* init sta/ibss data */
wlvif->sta.hlid = WL12XX_INVALID_LINK_ID;
wl12xx_allocate_rate_policy(wl, &wlvif->sta.basic_rate_idx);
wl12xx_allocate_rate_policy(wl, &wlvif->sta.ap_rate_idx);
wl12xx_allocate_rate_policy(wl, &wlvif->sta.p2p_rate_idx);
} else {
/* init ap data */
wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID;
wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID;
wl12xx_allocate_rate_policy(wl, &wlvif->ap.mgmt_rate_idx);
wl12xx_allocate_rate_policy(wl, &wlvif->ap.bcast_rate_idx);
for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++)
wl12xx_allocate_rate_policy(wl,
&wlvif->ap.ucast_rate_idx[i]);
}
wlvif->bitrate_masks[IEEE80211_BAND_2GHZ] = wl->conf.tx.basic_rate;
wlvif->bitrate_masks[IEEE80211_BAND_5GHZ] = wl->conf.tx.basic_rate_5;
wlvif->basic_rate_set = CONF_TX_RATE_MASK_BASIC;
wlvif->basic_rate = CONF_TX_RATE_MASK_BASIC;
wlvif->rate_set = CONF_TX_RATE_MASK_BASIC;
wlvif->beacon_int = WL1271_DEFAULT_BEACON_INT;
/*
* mac80211 configures some values globally, while we treat them
* per-interface. thus, on init, we have to copy them from wl
*/
wlvif->band = wl->band;
wlvif->channel = wl->channel;
wlvif->power_level = wl->power_level;
INIT_WORK(&wlvif->rx_streaming_enable_work,
wl1271_rx_streaming_enable_work);
INIT_WORK(&wlvif->rx_streaming_disable_work,
wl1271_rx_streaming_disable_work);
INIT_LIST_HEAD(&wlvif->list);
setup_timer(&wlvif->rx_streaming_timer, wl1271_rx_streaming_timer,
(unsigned long) wlvif);
return 0;
}
static bool wl12xx_init_fw(struct wl1271 *wl)
{
int retries = WL1271_BOOT_RETRIES;
bool booted = false;
struct wiphy *wiphy = wl->hw->wiphy;
int ret;
while (retries) {
retries--;
ret = wl12xx_chip_wakeup(wl, false);
if (ret < 0)
goto power_off;
ret = wl1271_boot(wl);
if (ret < 0)
goto power_off;
ret = wl1271_hw_init(wl);
if (ret < 0)
goto irq_disable;
booted = true;
break;
irq_disable:
mutex_unlock(&wl->mutex);
/* Unlocking the mutex in the middle of handling is
inherently unsafe. In this case we deem it safe to do,
because we need to let any possibly pending IRQ out of
the system (and while we are WL1271_STATE_OFF the IRQ
work function will not do anything.) Also, any other
possible concurrent operations will fail due to the
current state, hence the wl1271 struct should be safe. */
wl1271_disable_interrupts(wl);
wl1271_flush_deferred_work(wl);
cancel_work_sync(&wl->netstack_work);
mutex_lock(&wl->mutex);
power_off:
wl1271_power_off(wl);
}
if (!booted) {
wl1271_error("firmware boot failed despite %d retries",
WL1271_BOOT_RETRIES);
goto out;
}
wl1271_info("firmware booted (%s)", wl->chip.fw_ver_str);
/* update hw/fw version info in wiphy struct */
wiphy->hw_version = wl->chip.id;
strncpy(wiphy->fw_version, wl->chip.fw_ver_str,
sizeof(wiphy->fw_version));
/*
* Now we know if 11a is supported (info from the NVS), so disable
* 11a channels if not supported
*/
if (!wl->enable_11a)
wiphy->bands[IEEE80211_BAND_5GHZ]->n_channels = 0;
wl1271_debug(DEBUG_MAC80211, "11a is %ssupported",
wl->enable_11a ? "" : "not ");
wl->state = WL1271_STATE_ON;
out:
return booted;
}
static bool wl12xx_dev_role_started(struct wl12xx_vif *wlvif)
{
return wlvif->dev_hlid != WL12XX_INVALID_LINK_ID;
}
/*
* Check whether a fw switch (i.e. moving from one loaded
* fw to another) is needed. This function is also responsible
* for updating wl->last_vif_count, so it must be called before
* loading a non-plt fw (so the correct fw (single-role/multi-role)
* will be used).
*/
static bool wl12xx_need_fw_change(struct wl1271 *wl,
struct vif_counter_data vif_counter_data,
bool add)
{
enum wl12xx_fw_type current_fw = wl->fw_type;
u8 vif_count = vif_counter_data.counter;
if (test_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags))
return false;
/* increase the vif count if this is a new vif */
if (add && !vif_counter_data.cur_vif_running)
vif_count++;
wl->last_vif_count = vif_count;
/* no need for fw change if the device is OFF */
if (wl->state == WL1271_STATE_OFF)
return false;
if (vif_count > 1 && current_fw == WL12XX_FW_TYPE_NORMAL)
return true;
if (vif_count <= 1 && current_fw == WL12XX_FW_TYPE_MULTI)
return true;
return false;
}
/*
* Enter "forced psm". Make sure the sta is in psm against the ap,
* to make the fw switch a bit more disconnection-persistent.
*/
static void wl12xx_force_active_psm(struct wl1271 *wl)
{
struct wl12xx_vif *wlvif;
wl12xx_for_each_wlvif_sta(wl, wlvif) {
wl1271_ps_set_mode(wl, wlvif, STATION_POWER_SAVE_MODE);
}
}
static int wl1271_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct vif_counter_data vif_count;
int ret = 0;
u8 role_type;
bool booted = false;
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER |
IEEE80211_VIF_SUPPORTS_CQM_RSSI;
wl1271_debug(DEBUG_MAC80211, "mac80211 add interface type %d mac %pM",
ieee80211_vif_type_p2p(vif), vif->addr);
wl12xx_get_vif_count(hw, vif, &vif_count);
mutex_lock(&wl->mutex);
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
/*
* in some very corner case HW recovery scenarios its possible to
* get here before __wl1271_op_remove_interface is complete, so
* opt out if that is the case.
*/
if (test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags) ||
test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) {
ret = -EBUSY;
goto out;
}
ret = wl12xx_init_vif_data(wl, vif);
if (ret < 0)
goto out;
wlvif->wl = wl;
role_type = wl12xx_get_role_type(wl, wlvif);
if (role_type == WL12XX_INVALID_ROLE_TYPE) {
ret = -EINVAL;
goto out;
}
if (wl12xx_need_fw_change(wl, vif_count, true)) {
wl12xx_force_active_psm(wl);
set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags);
mutex_unlock(&wl->mutex);
wl1271_recovery_work(&wl->recovery_work);
return 0;
}
/*
* TODO: after the nvs issue will be solved, move this block
* to start(), and make sure here the driver is ON.
*/
if (wl->state == WL1271_STATE_OFF) {
/*
* we still need this in order to configure the fw
* while uploading the nvs
*/
memcpy(wl->addresses[0].addr, vif->addr, ETH_ALEN);
booted = wl12xx_init_fw(wl);
if (!booted) {
ret = -EINVAL;
goto out;
}
}
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
/*
* The device role is a special role used for
* rx and tx frames prior to association (as
* the STA role can get packets only from
* its associated bssid)
*/
ret = wl12xx_cmd_role_enable(wl, vif->addr,
WL1271_ROLE_DEVICE,
&wlvif->dev_role_id);
if (ret < 0)
goto out;
}
ret = wl12xx_cmd_role_enable(wl, vif->addr,
role_type, &wlvif->role_id);
if (ret < 0)
goto out;
ret = wl1271_init_vif_specific(wl, vif);
if (ret < 0)
goto out;
list_add(&wlvif->list, &wl->wlvif_list);
set_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags);
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
wl->ap_count++;
else
wl->sta_count++;
out:
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static void __wl1271_op_remove_interface(struct wl1271 *wl,
struct ieee80211_vif *vif,
bool reset_tx_queues)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int i, ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 remove interface");
if (!test_and_clear_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))
return;
/* because of hardware recovery, we may get here twice */
if (wl->state != WL1271_STATE_ON)
return;
wl1271_info("down");
if (wl->scan.state != WL1271_SCAN_STATE_IDLE &&
wl->scan_vif == vif) {
/*
* Rearm the tx watchdog just before idling scan. This
* prevents just-finished scans from triggering the watchdog
*/
wl12xx_rearm_tx_watchdog_locked(wl);
wl->scan.state = WL1271_SCAN_STATE_IDLE;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan_vif = NULL;
wl->scan.req = NULL;
ieee80211_scan_completed(wl->hw, true);
}
if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags)) {
/* disable active roles */
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto deinit;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
if (wl12xx_dev_role_started(wlvif))
wl12xx_stop_dev(wl, wlvif);
ret = wl12xx_cmd_role_disable(wl, &wlvif->dev_role_id);
if (ret < 0)
goto deinit;
}
ret = wl12xx_cmd_role_disable(wl, &wlvif->role_id);
if (ret < 0)
goto deinit;
wl1271_ps_elp_sleep(wl);
}
deinit:
/* clear all hlids (except system_hlid) */
wlvif->dev_hlid = WL12XX_INVALID_LINK_ID;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
wlvif->sta.hlid = WL12XX_INVALID_LINK_ID;
wl12xx_free_rate_policy(wl, &wlvif->sta.basic_rate_idx);
wl12xx_free_rate_policy(wl, &wlvif->sta.ap_rate_idx);
wl12xx_free_rate_policy(wl, &wlvif->sta.p2p_rate_idx);
} else {
wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID;
wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID;
wl12xx_free_rate_policy(wl, &wlvif->ap.mgmt_rate_idx);
wl12xx_free_rate_policy(wl, &wlvif->ap.bcast_rate_idx);
for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++)
wl12xx_free_rate_policy(wl,
&wlvif->ap.ucast_rate_idx[i]);
}
wl12xx_tx_reset_wlvif(wl, wlvif);
wl1271_free_ap_keys(wl, wlvif);
if (wl->last_wlvif == wlvif)
wl->last_wlvif = NULL;
list_del(&wlvif->list);
memset(wlvif->ap.sta_hlid_map, 0, sizeof(wlvif->ap.sta_hlid_map));
wlvif->role_id = WL12XX_INVALID_ROLE_ID;
wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID;
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
wl->ap_count--;
else
wl->sta_count--;
mutex_unlock(&wl->mutex);
del_timer_sync(&wlvif->rx_streaming_timer);
cancel_work_sync(&wlvif->rx_streaming_enable_work);
cancel_work_sync(&wlvif->rx_streaming_disable_work);
mutex_lock(&wl->mutex);
}
static void wl1271_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct wl12xx_vif *iter;
struct vif_counter_data vif_count;
bool cancel_recovery = true;
wl12xx_get_vif_count(hw, vif, &vif_count);
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF ||
!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))
goto out;
/*
* wl->vif can be null here if someone shuts down the interface
* just when hardware recovery has been started.
*/
wl12xx_for_each_wlvif(wl, iter) {
if (iter != wlvif)
continue;
__wl1271_op_remove_interface(wl, vif, true);
break;
}
WARN_ON(iter != wlvif);
if (wl12xx_need_fw_change(wl, vif_count, false)) {
wl12xx_force_active_psm(wl);
set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags);
wl12xx_queue_recovery_work(wl);
cancel_recovery = false;
}
out:
mutex_unlock(&wl->mutex);
if (cancel_recovery)
cancel_work_sync(&wl->recovery_work);
}
static int wl12xx_op_change_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype new_type, bool p2p)
{
struct wl1271 *wl = hw->priv;
int ret;
set_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags);
wl1271_op_remove_interface(hw, vif);
vif->type = new_type;
vif->p2p = p2p;
ret = wl1271_op_add_interface(hw, vif);
clear_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags);
return ret;
}
static int wl1271_join(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool set_assoc)
{
int ret;
bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS);
/*
* One of the side effects of the JOIN command is that is clears
* WPA/WPA2 keys from the chipset. Performing a JOIN while associated
* to a WPA/WPA2 access point will therefore kill the data-path.
* Currently the only valid scenario for JOIN during association
* is on roaming, in which case we will also be given new keys.
* Keep the below message for now, unless it starts bothering
* users who really like to roam a lot :)
*/
if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
wl1271_info("JOIN while associated.");
/* clear encryption type */
wlvif->encryption_type = KEY_NONE;
if (set_assoc)
set_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags);
if (is_ibss)
ret = wl12xx_cmd_role_start_ibss(wl, wlvif);
else
ret = wl12xx_cmd_role_start_sta(wl, wlvif);
if (ret < 0)
goto out;
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
goto out;
/*
* The join command disable the keep-alive mode, shut down its process,
* and also clear the template config, so we need to reset it all after
* the join. The acx_aid starts the keep-alive process, and the order
* of the commands below is relevant.
*/
ret = wl1271_acx_keep_alive_mode(wl, wlvif, true);
if (ret < 0)
goto out;
ret = wl1271_acx_aid(wl, wlvif, wlvif->aid);
if (ret < 0)
goto out;
ret = wl12xx_cmd_build_klv_null_data(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_acx_keep_alive_config(wl, wlvif,
CMD_TEMPL_KLV_IDX_NULL_DATA,
ACX_KEEP_ALIVE_TPL_VALID);
if (ret < 0)
goto out;
out:
return ret;
}
static int wl1271_unjoin(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int ret;
if (test_and_clear_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags)) {
struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif);
wl12xx_cmd_stop_channel_switch(wl);
ieee80211_chswitch_done(vif, false);
}
/* to stop listening to a channel, we disconnect */
ret = wl12xx_cmd_role_stop_sta(wl, wlvif);
if (ret < 0)
goto out;
/* reset TX security counters on a clean disconnect */
wlvif->tx_security_last_seq_lsb = 0;
wlvif->tx_security_seq = 0;
out:
return ret;
}
static void wl1271_set_band_rate(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
wlvif->basic_rate_set = wlvif->bitrate_masks[wlvif->band];
wlvif->rate_set = wlvif->basic_rate_set;
}
static int wl1271_sta_handle_idle(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool idle)
{
int ret;
bool cur_idle = !test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags);
if (idle == cur_idle)
return 0;
if (idle) {
/* no need to croc if we weren't busy (e.g. during boot) */
if (wl12xx_dev_role_started(wlvif)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
goto out;
}
wlvif->rate_set =
wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_acx_keep_alive_config(
wl, wlvif, CMD_TEMPL_KLV_IDX_NULL_DATA,
ACX_KEEP_ALIVE_TPL_INVALID);
if (ret < 0)
goto out;
clear_bit(WLVIF_FLAG_IN_USE, &wlvif->flags);
} else {
/* The current firmware only supports sched_scan in idle */
if (wl->sched_scanning) {
wl1271_scan_sched_scan_stop(wl);
ieee80211_sched_scan_stopped(wl->hw);
}
ret = wl12xx_start_dev(wl, wlvif);
if (ret < 0)
goto out;
set_bit(WLVIF_FLAG_IN_USE, &wlvif->flags);
}
out:
return ret;
}
static int wl12xx_config_vif(struct wl1271 *wl, struct wl12xx_vif *wlvif,
struct ieee80211_conf *conf, u32 changed)
{
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
int channel, ret;
channel = ieee80211_frequency_to_channel(conf->channel->center_freq);
/* if the channel changes while joined, join again */
if (changed & IEEE80211_CONF_CHANGE_CHANNEL &&
((wlvif->band != conf->channel->band) ||
(wlvif->channel != channel))) {
/* send all pending packets */
wl1271_tx_work_locked(wl);
wlvif->band = conf->channel->band;
wlvif->channel = channel;
if (!is_ap) {
/*
* FIXME: the mac80211 should really provide a fixed
* rate to use here. for now, just use the smallest
* possible rate for the band as a fixed rate for
* association frames and other control messages.
*/
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags))
wl1271_set_band_rate(wl, wlvif);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
wl1271_warning("rate policy for channel "
"failed %d", ret);
/*
* change the ROC channel. do it only if we are
* not idle. otherwise, CROC will be called
* anyway.
*/
if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED,
&wlvif->flags) &&
wl12xx_dev_role_started(wlvif) &&
!(conf->flags & IEEE80211_CONF_IDLE)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
return ret;
ret = wl12xx_start_dev(wl, wlvif);
if (ret < 0)
return ret;
}
}
}
if ((changed & IEEE80211_CONF_CHANGE_PS) && !is_ap) {
if ((conf->flags & IEEE80211_CONF_PS) &&
test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) &&
!test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) {
int ps_mode;
char *ps_mode_str;
if (wl->conf.conn.forced_ps) {
ps_mode = STATION_POWER_SAVE_MODE;
ps_mode_str = "forced";
} else {
ps_mode = STATION_AUTO_PS_MODE;
ps_mode_str = "auto";
}
wl1271_debug(DEBUG_PSM, "%s ps enabled", ps_mode_str);
ret = wl1271_ps_set_mode(wl, wlvif, ps_mode);
if (ret < 0)
wl1271_warning("enter %s ps failed %d",
ps_mode_str, ret);
} else if (!(conf->flags & IEEE80211_CONF_PS) &&
test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) {
wl1271_debug(DEBUG_PSM, "auto ps disabled");
ret = wl1271_ps_set_mode(wl, wlvif,
STATION_ACTIVE_MODE);
if (ret < 0)
wl1271_warning("exit auto ps failed %d", ret);
}
}
if (conf->power_level != wlvif->power_level) {
ret = wl1271_acx_tx_power(wl, wlvif, conf->power_level);
if (ret < 0)
return ret;
wlvif->power_level = conf->power_level;
}
return 0;
}
static int wl1271_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
struct ieee80211_conf *conf = &hw->conf;
int channel, ret = 0;
channel = ieee80211_frequency_to_channel(conf->channel->center_freq);
wl1271_debug(DEBUG_MAC80211, "mac80211 config ch %d psm %s power %d %s"
" changed 0x%x",
channel,
conf->flags & IEEE80211_CONF_PS ? "on" : "off",
conf->power_level,
conf->flags & IEEE80211_CONF_IDLE ? "idle" : "in use",
changed);
/*
* mac80211 will go to idle nearly immediately after transmitting some
* frames, such as the deauth. To make sure those frames reach the air,
* wait here until the TX queue is fully flushed.
*/
if ((changed & IEEE80211_CONF_CHANGE_IDLE) &&
(conf->flags & IEEE80211_CONF_IDLE))
wl1271_tx_flush(wl);
mutex_lock(&wl->mutex);
/* we support configuring the channel and band even while off */
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
wl->band = conf->channel->band;
wl->channel = channel;
}
if (changed & IEEE80211_CONF_CHANGE_POWER)
wl->power_level = conf->power_level;
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
/* configure each interface */
wl12xx_for_each_wlvif(wl, wlvif) {
ret = wl12xx_config_vif(wl, wlvif, conf, changed);
if (ret < 0)
goto out_sleep;
}
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
struct wl1271_filter_params {
bool enabled;
int mc_list_length;
u8 mc_list[ACX_MC_ADDRESS_GROUP_MAX][ETH_ALEN];
};
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw,
struct netdev_hw_addr_list *mc_list)
#else
static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw, int mc_count,
struct dev_addr_list *mc_list)
#endif
{
struct wl1271_filter_params *fp;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
struct netdev_hw_addr *ha;
#else
int i;
#endif
struct wl1271 *wl = hw->priv;
if (unlikely(wl->state == WL1271_STATE_OFF))
return 0;
fp = kzalloc(sizeof(*fp), GFP_ATOMIC);
if (!fp) {
wl1271_error("Out of memory setting filters.");
return 0;
}
/* update multicast filtering parameters */
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
fp->mc_list_length = 0;
if (netdev_hw_addr_list_count(mc_list) > ACX_MC_ADDRESS_GROUP_MAX) {
#else
fp->enabled = true;
if (mc_count > ACX_MC_ADDRESS_GROUP_MAX) {
mc_count = 0;
#endif
fp->enabled = false;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
} else {
fp->enabled = true;
netdev_hw_addr_list_for_each(ha, mc_list) {
#else
}
fp->mc_list_length = 0;
for (i = 0; i < mc_count; i++) {
if (mc_list->da_addrlen == ETH_ALEN) {
#endif
memcpy(fp->mc_list[fp->mc_list_length],
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
ha->addr, ETH_ALEN);
#else
mc_list->da_addr, ETH_ALEN);
#endif
fp->mc_list_length++;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
}
#else
} else
wl1271_warning("Unknown mc address length.");
mc_list = mc_list->next;
#endif
}
return (u64)(unsigned long)fp;
}
#define WL1271_SUPPORTED_FILTERS (FIF_PROMISC_IN_BSS | \
FIF_ALLMULTI | \
FIF_FCSFAIL | \
FIF_BCN_PRBRESP_PROMISC | \
FIF_CONTROL | \
FIF_OTHER_BSS)
static void wl1271_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed,
unsigned int *total, u64 multicast)
{
struct wl1271_filter_params *fp = (void *)(unsigned long)multicast;
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 configure filter changed %x"
" total %x", changed, *total);
mutex_lock(&wl->mutex);
*total &= WL1271_SUPPORTED_FILTERS;
changed &= WL1271_SUPPORTED_FILTERS;
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl12xx_for_each_wlvif(wl, wlvif) {
if (wlvif->bss_type != BSS_TYPE_AP_BSS) {
if (*total & FIF_ALLMULTI)
ret = wl1271_acx_group_address_tbl(wl, wlvif,
false,
NULL, 0);
else if (fp)
ret = wl1271_acx_group_address_tbl(wl, wlvif,
fp->enabled,
fp->mc_list,
fp->mc_list_length);
if (ret < 0)
goto out_sleep;
}
}
/*
* the fw doesn't provide an api to configure the filters. instead,
* the filters configuration is based on the active roles / ROC
* state.
*/
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
kfree(fp);
}
static int wl1271_record_ap_key(struct wl1271 *wl, struct wl12xx_vif *wlvif,
u8 id, u8 key_type, u8 key_size,
const u8 *key, u8 hlid, u32 tx_seq_32,
u16 tx_seq_16)
{
struct wl1271_ap_key *ap_key;
int i;
wl1271_debug(DEBUG_CRYPT, "record ap key id %d", (int)id);
if (key_size > MAX_KEY_SIZE)
return -EINVAL;
/*
* Find next free entry in ap_keys. Also check we are not replacing
* an existing key.
*/
for (i = 0; i < MAX_NUM_KEYS; i++) {
if (wlvif->ap.recorded_keys[i] == NULL)
break;
if (wlvif->ap.recorded_keys[i]->id == id) {
wl1271_warning("trying to record key replacement");
return -EINVAL;
}
}
if (i == MAX_NUM_KEYS)
return -EBUSY;
ap_key = kzalloc(sizeof(*ap_key), GFP_KERNEL);
if (!ap_key)
return -ENOMEM;
ap_key->id = id;
ap_key->key_type = key_type;
ap_key->key_size = key_size;
memcpy(ap_key->key, key, key_size);
ap_key->hlid = hlid;
ap_key->tx_seq_32 = tx_seq_32;
ap_key->tx_seq_16 = tx_seq_16;
wlvif->ap.recorded_keys[i] = ap_key;
return 0;
}
static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int i;
for (i = 0; i < MAX_NUM_KEYS; i++) {
kfree(wlvif->ap.recorded_keys[i]);
wlvif->ap.recorded_keys[i] = NULL;
}
}
static int wl1271_ap_init_hwenc(struct wl1271 *wl, struct wl12xx_vif *wlvif)
{
int i, ret = 0;
struct wl1271_ap_key *key;
bool wep_key_added = false;
for (i = 0; i < MAX_NUM_KEYS; i++) {
u8 hlid;
if (wlvif->ap.recorded_keys[i] == NULL)
break;
key = wlvif->ap.recorded_keys[i];
hlid = key->hlid;
if (hlid == WL12XX_INVALID_LINK_ID)
hlid = wlvif->ap.bcast_hlid;
ret = wl1271_cmd_set_ap_key(wl, wlvif, KEY_ADD_OR_REPLACE,
key->id, key->key_type,
key->key_size, key->key,
hlid, key->tx_seq_32,
key->tx_seq_16);
if (ret < 0)
goto out;
if (key->key_type == KEY_WEP)
wep_key_added = true;
}
if (wep_key_added) {
ret = wl12xx_cmd_set_default_wep_key(wl, wlvif->default_key,
wlvif->ap.bcast_hlid);
if (ret < 0)
goto out;
}
out:
wl1271_free_ap_keys(wl, wlvif);
return ret;
}
static int wl1271_set_key(struct wl1271 *wl, struct wl12xx_vif *wlvif,
u16 action, u8 id, u8 key_type,
u8 key_size, const u8 *key, u32 tx_seq_32,
u16 tx_seq_16, struct ieee80211_sta *sta)
{
int ret;
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
if (is_ap) {
struct wl1271_station *wl_sta;
u8 hlid;
if (sta) {
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
} else {
hlid = wlvif->ap.bcast_hlid;
}
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) {
/*
* We do not support removing keys after AP shutdown.
* Pretend we do to make mac80211 happy.
*/
if (action != KEY_ADD_OR_REPLACE)
return 0;
ret = wl1271_record_ap_key(wl, wlvif, id,
key_type, key_size,
key, hlid, tx_seq_32,
tx_seq_16);
} else {
ret = wl1271_cmd_set_ap_key(wl, wlvif, action,
id, key_type, key_size,
key, hlid, tx_seq_32,
tx_seq_16);
}
if (ret < 0)
return ret;
} else {
const u8 *addr;
static const u8 bcast_addr[ETH_ALEN] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
/*
* A STA set to GEM cipher requires 2 tx spare blocks.
* Return to default value when GEM cipher key is removed
*/
if (key_type == KEY_GEM) {
if (action == KEY_ADD_OR_REPLACE)
wl->tx_spare_blocks = 2;
else if (action == KEY_REMOVE)
wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
}
addr = sta ? sta->addr : bcast_addr;
if (is_zero_ether_addr(addr)) {
/* We dont support TX only encryption */
return -EOPNOTSUPP;
}
/* The wl1271 does not allow to remove unicast keys - they
will be cleared automatically on next CMD_JOIN. Ignore the
request silently, as we dont want the mac80211 to emit
an error message. */
if (action == KEY_REMOVE && !is_broadcast_ether_addr(addr))
return 0;
/* don't remove key if hlid was already deleted */
if (action == KEY_REMOVE &&
wlvif->sta.hlid == WL12XX_INVALID_LINK_ID)
return 0;
ret = wl1271_cmd_set_sta_key(wl, wlvif, action,
id, key_type, key_size,
key, addr, tx_seq_32,
tx_seq_16);
if (ret < 0)
return ret;
/* the default WEP key needs to be configured at least once */
if (key_type == KEY_WEP) {
ret = wl12xx_cmd_set_default_wep_key(wl,
wlvif->default_key,
wlvif->sta.hlid);
if (ret < 0)
return ret;
}
}
return 0;
}
static int wl1271_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct ieee80211_key_conf *key_conf)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
u32 tx_seq_32 = 0;
u16 tx_seq_16 = 0;
u8 key_type;
wl1271_debug(DEBUG_MAC80211, "mac80211 set key");
wl1271_debug(DEBUG_CRYPT, "CMD: 0x%x sta: %p", cmd, sta);
wl1271_debug(DEBUG_CRYPT, "Key: algo:0x%x, id:%d, len:%d flags 0x%x",
key_conf->cipher, key_conf->keyidx,
key_conf->keylen, key_conf->flags);
wl1271_dump(DEBUG_CRYPT, "KEY: ", key_conf->key, key_conf->keylen);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out_unlock;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out_unlock;
switch (key_conf->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
key_type = KEY_WEP;
key_conf->hw_key_idx = key_conf->keyidx;
break;
case WLAN_CIPHER_SUITE_TKIP:
key_type = KEY_TKIP;
key_conf->hw_key_idx = key_conf->keyidx;
tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq);
tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq);
break;
case WLAN_CIPHER_SUITE_CCMP:
key_type = KEY_AES;
key_conf->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE;
tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq);
tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq);
break;
case WL1271_CIPHER_SUITE_GEM:
key_type = KEY_GEM;
tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq);
tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq);
break;
default:
wl1271_error("Unknown key algo 0x%x", key_conf->cipher);
ret = -EOPNOTSUPP;
goto out_sleep;
}
switch (cmd) {
case SET_KEY:
ret = wl1271_set_key(wl, wlvif, KEY_ADD_OR_REPLACE,
key_conf->keyidx, key_type,
key_conf->keylen, key_conf->key,
tx_seq_32, tx_seq_16, sta);
if (ret < 0) {
wl1271_error("Could not add or replace key");
goto out_sleep;
}
/*
* reconfiguring arp response if the unicast (or common)
* encryption key type was changed
*/
if (wlvif->bss_type == BSS_TYPE_STA_BSS &&
(sta || key_type == KEY_WEP) &&
wlvif->encryption_type != key_type) {
wlvif->encryption_type = key_type;
ret = wl1271_cmd_build_arp_rsp(wl, wlvif);
if (ret < 0) {
wl1271_warning("build arp rsp failed: %d", ret);
goto out_sleep;
}
}
break;
case DISABLE_KEY:
ret = wl1271_set_key(wl, wlvif, KEY_REMOVE,
key_conf->keyidx, key_type,
key_conf->keylen, key_conf->key,
0, 0, sta);
if (ret < 0) {
wl1271_error("Could not remove key");
goto out_sleep;
}
break;
default:
wl1271_error("Unsupported key cmd 0x%x", cmd);
ret = -EOPNOTSUPP;
break;
}
out_sleep:
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_op_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_scan_request *req)
{
struct wl1271 *wl = hw->priv;
int ret;
u8 *ssid = NULL;
size_t len = 0;
wl1271_debug(DEBUG_MAC80211, "mac80211 hw scan");
if (req->n_ssids) {
ssid = req->ssids[0].ssid;
len = req->ssids[0].ssid_len;
}
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
/*
* We cannot return -EBUSY here because cfg80211 will expect
* a call to ieee80211_scan_completed if we do - in this case
* there won't be any call.
*/
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
/* fail if there is any role in ROC */
if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) {
/* don't allow scanning right now */
ret = -EBUSY;
goto out_sleep;
}
ret = wl1271_scan(hw->priv, vif, ssid, len, req);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1271_op_cancel_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 cancel hw scan");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF)
goto out;
if (wl->scan.state == WL1271_SCAN_STATE_IDLE)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (wl->scan.state != WL1271_SCAN_STATE_DONE) {
ret = wl1271_scan_stop(wl);
if (ret < 0)
goto out_sleep;
}
/*
* Rearm the tx watchdog just before idling scan. This
* prevents just-finished scans from triggering the watchdog
*/
wl12xx_rearm_tx_watchdog_locked(wl);
wl->scan.state = WL1271_SCAN_STATE_IDLE;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan_vif = NULL;
wl->scan.req = NULL;
ieee80211_scan_completed(wl->hw, true);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
cancel_delayed_work_sync(&wl->scan_complete_work);
}
static int wl1271_op_sched_scan_start(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_sched_scan_request *req,
struct ieee80211_sched_scan_ies *ies)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_start");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_scan_sched_scan_config(wl, wlvif, req, ies);
if (ret < 0)
goto out_sleep;
ret = wl1271_scan_sched_scan_start(wl, wlvif);
if (ret < 0)
goto out_sleep;
wl->sched_scanning = true;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl1271_op_sched_scan_stop(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
int ret;
wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_stop");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_scan_sched_scan_stop(wl);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_op_set_frag_threshold(struct ieee80211_hw *hw, u32 value)
{
struct wl1271 *wl = hw->priv;
int ret = 0;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl1271_acx_frag_threshold(wl, value);
if (ret < 0)
wl1271_warning("wl1271_op_set_frag_threshold failed: %d", ret);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_op_set_rts_threshold(struct ieee80211_hw *hw, u32 value)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret = 0;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl12xx_for_each_wlvif(wl, wlvif) {
ret = wl1271_acx_rts_threshold(wl, wlvif, value);
if (ret < 0)
wl1271_warning("set rts threshold failed: %d", ret);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl1271_ssid_set(struct ieee80211_vif *vif, struct sk_buff *skb,
int offset)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
u8 ssid_len;
const u8 *ptr = cfg80211_find_ie(WLAN_EID_SSID, skb->data + offset,
skb->len - offset);
if (!ptr) {
wl1271_error("No SSID in IEs!");
return -ENOENT;
}
ssid_len = ptr[1];
if (ssid_len > IEEE80211_MAX_SSID_LEN) {
wl1271_error("SSID is too long!");
return -EINVAL;
}
wlvif->ssid_len = ssid_len;
memcpy(wlvif->ssid, ptr+2, ssid_len);
return 0;
}
static void wl12xx_remove_ie(struct sk_buff *skb, u8 eid, int ieoffset)
{
int len;
const u8 *next, *end = skb->data + skb->len;
u8 *ie = (u8 *)cfg80211_find_ie(eid, skb->data + ieoffset,
skb->len - ieoffset);
if (!ie)
return;
len = ie[1] + 2;
next = ie + len;
memmove(ie, next, end - next);
skb_trim(skb, skb->len - len);
}
static void wl12xx_remove_vendor_ie(struct sk_buff *skb,
unsigned int oui, u8 oui_type,
int ieoffset)
{
int len;
const u8 *next, *end = skb->data + skb->len;
u8 *ie = (u8 *)cfg80211_find_vendor_ie(oui, oui_type,
skb->data + ieoffset,
skb->len - ieoffset);
if (!ie)
return;
len = ie[1] + 2;
next = ie + len;
memmove(ie, next, end - next);
skb_trim(skb, skb->len - len);
}
static int wl1271_ap_set_probe_resp_tmpl(struct wl1271 *wl, u32 rates,
struct ieee80211_vif *vif)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct sk_buff *skb;
int ret;
skb = ieee80211_proberesp_get(wl->hw, vif);
if (!skb)
return -EOPNOTSUPP;
ret = wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_AP_PROBE_RESPONSE,
skb->data,
skb->len, 0,
rates);
dev_kfree_skb(skb);
return ret;
}
static int wl1271_ap_set_probe_resp_tmpl_legacy(struct wl1271 *wl,
struct ieee80211_vif *vif,
u8 *probe_rsp_data,
size_t probe_rsp_len,
u32 rates)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct ieee80211_bss_conf *bss_conf = &vif->bss_conf;
u8 probe_rsp_templ[WL1271_CMD_TEMPL_MAX_SIZE];
int ssid_ie_offset, ie_offset, templ_len;
const u8 *ptr;
/* no need to change probe response if the SSID is set correctly */
if (wlvif->ssid_len > 0)
return wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_AP_PROBE_RESPONSE,
probe_rsp_data,
probe_rsp_len, 0,
rates);
if (probe_rsp_len + bss_conf->ssid_len > WL1271_CMD_TEMPL_MAX_SIZE) {
wl1271_error("probe_rsp template too big");
return -EINVAL;
}
/* start searching from IE offset */
ie_offset = offsetof(struct ieee80211_mgmt, u.probe_resp.variable);
ptr = cfg80211_find_ie(WLAN_EID_SSID, probe_rsp_data + ie_offset,
probe_rsp_len - ie_offset);
if (!ptr) {
wl1271_error("No SSID in beacon!");
return -EINVAL;
}
ssid_ie_offset = ptr - probe_rsp_data;
ptr += (ptr[1] + 2);
memcpy(probe_rsp_templ, probe_rsp_data, ssid_ie_offset);
/* insert SSID from bss_conf */
probe_rsp_templ[ssid_ie_offset] = WLAN_EID_SSID;
probe_rsp_templ[ssid_ie_offset + 1] = bss_conf->ssid_len;
memcpy(probe_rsp_templ + ssid_ie_offset + 2,
bss_conf->ssid, bss_conf->ssid_len);
templ_len = ssid_ie_offset + 2 + bss_conf->ssid_len;
memcpy(probe_rsp_templ + ssid_ie_offset + 2 + bss_conf->ssid_len,
ptr, probe_rsp_len - (ptr - probe_rsp_data));
templ_len += probe_rsp_len - (ptr - probe_rsp_data);
return wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_AP_PROBE_RESPONSE,
probe_rsp_templ,
templ_len, 0,
rates);
}
static int wl1271_bss_erp_info_changed(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret = 0;
if (changed & BSS_CHANGED_ERP_SLOT) {
if (bss_conf->use_short_slot)
ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_SHORT);
else
ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_LONG);
if (ret < 0) {
wl1271_warning("Set slot time failed %d", ret);
goto out;
}
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
if (bss_conf->use_short_preamble)
wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_SHORT);
else
wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_LONG);
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
if (bss_conf->use_cts_prot)
ret = wl1271_acx_cts_protect(wl, wlvif,
CTSPROTECT_ENABLE);
else
ret = wl1271_acx_cts_protect(wl, wlvif,
CTSPROTECT_DISABLE);
if (ret < 0) {
wl1271_warning("Set ctsprotect failed %d", ret);
goto out;
}
}
out:
return ret;
}
static int wl1271_bss_beacon_info_changed(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
int ret = 0;
if ((changed & BSS_CHANGED_BEACON_INT)) {
wl1271_debug(DEBUG_MASTER, "beacon interval updated: %d",
bss_conf->beacon_int);
wlvif->beacon_int = bss_conf->beacon_int;
}
if ((changed & BSS_CHANGED_AP_PROBE_RESP) && is_ap) {
u32 rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
if (!wl1271_ap_set_probe_resp_tmpl(wl, rate, vif)) {
wl1271_debug(DEBUG_AP, "probe response updated");
set_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags);
}
}
if ((changed & BSS_CHANGED_BEACON)) {
struct ieee80211_hdr *hdr;
u32 min_rate;
int ieoffset = offsetof(struct ieee80211_mgmt,
u.beacon.variable);
struct sk_buff *beacon = ieee80211_beacon_get(wl->hw, vif);
u16 tmpl_id;
if (!beacon) {
ret = -EINVAL;
goto out;
}
wl1271_debug(DEBUG_MASTER, "beacon updated");
ret = wl1271_ssid_set(vif, beacon, ieoffset);
if (ret < 0) {
dev_kfree_skb(beacon);
goto out;
}
min_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
tmpl_id = is_ap ? CMD_TEMPL_AP_BEACON :
CMD_TEMPL_BEACON;
ret = wl1271_cmd_template_set(wl, wlvif->role_id, tmpl_id,
beacon->data,
beacon->len, 0,
min_rate);
if (ret < 0) {
dev_kfree_skb(beacon);
goto out;
}
/*
* In case we already have a probe-resp beacon set explicitly
* by usermode, don't use the beacon data.
*/
if (test_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags))
goto end_bcn;
/* remove TIM ie from probe response */
wl12xx_remove_ie(beacon, WLAN_EID_TIM, ieoffset);
/*
* remove p2p ie from probe response.
* the fw reponds to probe requests that don't include
* the p2p ie. probe requests with p2p ie will be passed,
* and will be responded by the supplicant (the spec
* forbids including the p2p ie when responding to probe
* requests that didn't include it).
*/
wl12xx_remove_vendor_ie(beacon, WLAN_OUI_WFA,
WLAN_OUI_TYPE_WFA_P2P, ieoffset);
hdr = (struct ieee80211_hdr *) beacon->data;
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_PROBE_RESP);
if (is_ap)
ret = wl1271_ap_set_probe_resp_tmpl_legacy(wl, vif,
beacon->data,
beacon->len,
min_rate);
else
ret = wl1271_cmd_template_set(wl, wlvif->role_id,
CMD_TEMPL_PROBE_RESPONSE,
beacon->data,
beacon->len, 0,
min_rate);
end_bcn:
dev_kfree_skb(beacon);
if (ret < 0)
goto out;
}
out:
if (ret != 0)
wl1271_error("beacon info change failed: %d", ret);
return ret;
}
/* AP mode changes */
static void wl1271_bss_info_changed_ap(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret = 0;
if ((changed & BSS_CHANGED_BASIC_RATES)) {
u32 rates = bss_conf->basic_rates;
wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates,
wlvif->band);
wlvif->basic_rate = wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
ret = wl1271_init_ap_rates(wl, wlvif);
if (ret < 0) {
wl1271_error("AP rate policy change failed %d", ret);
goto out;
}
ret = wl1271_ap_init_templates(wl, vif);
if (ret < 0)
goto out;
}
ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
if ((changed & BSS_CHANGED_BEACON_ENABLED)) {
if (bss_conf->enable_beacon) {
if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) {
ret = wl12xx_cmd_role_start_ap(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_ap_init_hwenc(wl, wlvif);
if (ret < 0)
goto out;
set_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags);
wl1271_debug(DEBUG_AP, "started AP");
}
} else {
if (test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) {
ret = wl12xx_cmd_role_stop_ap(wl, wlvif);
if (ret < 0)
goto out;
clear_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags);
clear_bit(WLVIF_FLAG_AP_PROBE_RESP_SET,
&wlvif->flags);
wl1271_debug(DEBUG_AP, "stopped AP");
}
}
}
ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
/* Handle HT information change */
if ((changed & BSS_CHANGED_HT) &&
(bss_conf->channel_type != NL80211_CHAN_NO_HT)) {
ret = wl1271_acx_set_ht_information(wl, wlvif,
bss_conf->ht_operation_mode);
if (ret < 0) {
wl1271_warning("Set ht information failed %d", ret);
goto out;
}
}
out:
return;
}
/* STA/IBSS mode changes */
static void wl1271_bss_info_changed_sta(struct wl1271 *wl,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
bool do_join = false, set_assoc = false;
bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS);
bool ibss_joined = false;
u32 sta_rate_set = 0;
int ret;
struct ieee80211_sta *sta;
bool sta_exists = false;
struct ieee80211_sta_ht_cap sta_ht_cap;
if (is_ibss) {
ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf,
changed);
if (ret < 0)
goto out;
}
if (changed & BSS_CHANGED_IBSS) {
if (bss_conf->ibss_joined) {
set_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags);
ibss_joined = true;
} else {
if (test_and_clear_bit(WLVIF_FLAG_IBSS_JOINED,
&wlvif->flags))
wl1271_unjoin(wl, wlvif);
}
}
if ((changed & BSS_CHANGED_BEACON_INT) && ibss_joined)
do_join = true;
/* Need to update the SSID (for filtering etc) */
if ((changed & BSS_CHANGED_BEACON) && ibss_joined)
do_join = true;
if ((changed & BSS_CHANGED_BEACON_ENABLED) && ibss_joined) {
wl1271_debug(DEBUG_ADHOC, "ad-hoc beaconing: %s",
bss_conf->enable_beacon ? "enabled" : "disabled");
do_join = true;
}
if (changed & BSS_CHANGED_IDLE && !is_ibss) {
ret = wl1271_sta_handle_idle(wl, wlvif, bss_conf->idle);
if (ret < 0)
wl1271_warning("idle mode change failed %d", ret);
}
if ((changed & BSS_CHANGED_CQM)) {
bool enable = false;
if (bss_conf->cqm_rssi_thold)
enable = true;
ret = wl1271_acx_rssi_snr_trigger(wl, wlvif, enable,
bss_conf->cqm_rssi_thold,
bss_conf->cqm_rssi_hyst);
if (ret < 0)
goto out;
wlvif->rssi_thold = bss_conf->cqm_rssi_thold;
}
if (changed & BSS_CHANGED_BSSID &&
(is_ibss || bss_conf->assoc))
if (!is_zero_ether_addr(bss_conf->bssid)) {
ret = wl12xx_cmd_build_null_data(wl, wlvif);
if (ret < 0)
goto out;
ret = wl1271_build_qos_null_data(wl, vif);
if (ret < 0)
goto out;
/* Need to update the BSSID (for filtering etc) */
do_join = true;
}
if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_HT)) {
rcu_read_lock();
sta = ieee80211_find_sta(vif, bss_conf->bssid);
if (!sta)
goto sta_not_found;
/* save the supp_rates of the ap */
sta_rate_set = sta->supp_rates[wl->hw->conf.channel->band];
if (sta->ht_cap.ht_supported)
sta_rate_set |=
(sta->ht_cap.mcs.rx_mask[0] << HW_HT_RATES_OFFSET);
sta_ht_cap = sta->ht_cap;
sta_exists = true;
sta_not_found:
rcu_read_unlock();
}
if ((changed & BSS_CHANGED_ASSOC)) {
if (bss_conf->assoc) {
u32 rates;
int ieoffset;
wlvif->aid = bss_conf->aid;
wlvif->beacon_int = bss_conf->beacon_int;
set_assoc = true;
/*
* use basic rates from AP, and determine lowest rate
* to use with control frames.
*/
rates = bss_conf->basic_rates;
wlvif->basic_rate_set =
wl1271_tx_enabled_rates_get(wl, rates,
wlvif->band);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
if (sta_rate_set)
wlvif->rate_set =
wl1271_tx_enabled_rates_get(wl,
sta_rate_set,
wlvif->band);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
/*
* with wl1271, we don't need to update the
* beacon_int and dtim_period, because the firmware
* updates it by itself when the first beacon is
* received after a join.
*/
ret = wl1271_cmd_build_ps_poll(wl, wlvif, wlvif->aid);
if (ret < 0)
goto out;
/*
* Get a template for hardware connection maintenance
*/
dev_kfree_skb(wlvif->probereq);
wlvif->probereq = wl1271_cmd_build_ap_probe_req(wl,
wlvif,
NULL);
ieoffset = offsetof(struct ieee80211_mgmt,
u.probe_req.variable);
wl1271_ssid_set(vif, wlvif->probereq, ieoffset);
/* enable the connection monitoring feature */
ret = wl1271_acx_conn_monit_params(wl, wlvif, true);
if (ret < 0)
goto out;
} else {
/* use defaults when not associated */
bool was_assoc =
!!test_and_clear_bit(WLVIF_FLAG_STA_ASSOCIATED,
&wlvif->flags);
bool was_ifup =
!!test_and_clear_bit(WLVIF_FLAG_STA_STATE_SENT,
&wlvif->flags);
wlvif->aid = 0;
/* free probe-request template */
dev_kfree_skb(wlvif->probereq);
wlvif->probereq = NULL;
/* revert back to minimum rates for the current band */
wl1271_set_band_rate(wl, wlvif);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
/* disable connection monitor features */
ret = wl1271_acx_conn_monit_params(wl, wlvif, false);
/* Disable the keep-alive feature */
ret = wl1271_acx_keep_alive_mode(wl, wlvif, false);
if (ret < 0)
goto out;
/* restore the bssid filter and go to dummy bssid */
if (was_assoc) {
/*
* we might have to disable roc, if there was
* no IF_OPER_UP notification.
*/
if (!was_ifup) {
ret = wl12xx_croc(wl, wlvif->role_id);
if (ret < 0)
goto out;
}
/*
* (we also need to disable roc in case of
* roaming on the same channel. until we will
* have a better flow...)
*/
if (test_bit(wlvif->dev_role_id, wl->roc_map)) {
ret = wl12xx_croc(wl,
wlvif->dev_role_id);
if (ret < 0)
goto out;
}
wl1271_unjoin(wl, wlvif);
if (!bss_conf->idle)
wl12xx_start_dev(wl, wlvif);
}
}
}
if (changed & BSS_CHANGED_IBSS) {
wl1271_debug(DEBUG_ADHOC, "ibss_joined: %d",
bss_conf->ibss_joined);
if (bss_conf->ibss_joined) {
u32 rates = bss_conf->basic_rates;
wlvif->basic_rate_set =
wl1271_tx_enabled_rates_get(wl, rates,
wlvif->band);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl,
wlvif->basic_rate_set);
/* by default, use 11b + OFDM rates */
wlvif->rate_set = CONF_TX_IBSS_DEFAULT_RATES;
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
if (ret < 0)
goto out;
}
}
ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
if (do_join) {
ret = wl1271_join(wl, wlvif, set_assoc);
if (ret < 0) {
wl1271_warning("cmd join failed %d", ret);
goto out;
}
/* ROC until connected (after EAPOL exchange) */
if (!is_ibss) {
ret = wl12xx_roc(wl, wlvif, wlvif->role_id);
if (ret < 0)
goto out;
if (test_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags))
wl12xx_set_authorized(wl, wlvif);
}
/*
* stop device role if started (we might already be in
* STA/IBSS role).
*/
if (wl12xx_dev_role_started(wlvif)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
goto out;
}
}
/* Handle new association with HT. Do this after join. */
if (sta_exists) {
if ((changed & BSS_CHANGED_HT) &&
(bss_conf->channel_type != NL80211_CHAN_NO_HT)) {
ret = wl1271_acx_set_ht_capabilities(wl,
&sta_ht_cap,
true,
wlvif->sta.hlid);
if (ret < 0) {
wl1271_warning("Set ht cap true failed %d",
ret);
goto out;
}
}
/* handle new association without HT and disassociation */
else if (changed & BSS_CHANGED_ASSOC) {
ret = wl1271_acx_set_ht_capabilities(wl,
&sta_ht_cap,
false,
wlvif->sta.hlid);
if (ret < 0) {
wl1271_warning("Set ht cap false failed %d",
ret);
goto out;
}
}
}
/* Handle HT information change. Done after join. */
if ((changed & BSS_CHANGED_HT) &&
(bss_conf->channel_type != NL80211_CHAN_NO_HT)) {
ret = wl1271_acx_set_ht_information(wl, wlvif,
bss_conf->ht_operation_mode);
if (ret < 0) {
wl1271_warning("Set ht information failed %d", ret);
goto out;
}
}
/* Handle arp filtering. Done after join. */
if ((changed & BSS_CHANGED_ARP_FILTER) ||
(!is_ibss && (changed & BSS_CHANGED_QOS))) {
__be32 addr = bss_conf->arp_addr_list[0];
wlvif->sta.qos = bss_conf->qos;
WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS);
if (bss_conf->arp_addr_cnt == 1 &&
bss_conf->arp_filter_enabled) {
wlvif->ip_addr = addr;
/*
* The template should have been configured only upon
* association. however, it seems that the correct ip
* isn't being set (when sending), so we have to
* reconfigure the template upon every ip change.
*/
ret = wl1271_cmd_build_arp_rsp(wl, wlvif);
if (ret < 0) {
wl1271_warning("build arp rsp failed: %d", ret);
goto out;
}
ret = wl1271_acx_arp_ip_filter(wl, wlvif,
(ACX_ARP_FILTER_ARP_FILTERING |
ACX_ARP_FILTER_AUTO_ARP),
addr);
} else {
wlvif->ip_addr = 0;
ret = wl1271_acx_arp_ip_filter(wl, wlvif, 0, addr);
}
if (ret < 0)
goto out;
}
out:
return;
}
static void wl1271_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS);
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 bss info changed 0x%x",
(int)changed);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
if (unlikely(!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (is_ap)
wl1271_bss_info_changed_ap(wl, vif, bss_conf, changed);
else
wl1271_bss_info_changed_sta(wl, vif, bss_conf, changed);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int wl1271_op_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
u8 ps_scheme;
int ret = 0;
mutex_lock(&wl->mutex);
wl1271_debug(DEBUG_MAC80211, "mac80211 conf tx %d", queue);
if (params->uapsd)
ps_scheme = CONF_PS_SCHEME_UPSD_TRIGGER;
else
ps_scheme = CONF_PS_SCHEME_LEGACY;
if (!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
/*
* the txop is confed in units of 32us by the mac80211,
* we need us
*/
ret = wl1271_acx_ac_cfg(wl, wlvif, wl1271_tx_get_queue(queue),
params->cw_min, params->cw_max,
params->aifs, params->txop << 5);
if (ret < 0)
goto out_sleep;
ret = wl1271_acx_tid_cfg(wl, wlvif, wl1271_tx_get_queue(queue),
CONF_CHANNEL_TYPE_EDCF,
wl1271_tx_get_queue(queue),
ps_scheme, CONF_ACK_POLICY_LEGACY,
0, 0);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static u64 wl1271_op_get_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
u64 mactime = ULLONG_MAX;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 get tsf");
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl12xx_acx_tsf_info(wl, wlvif, &mactime);
if (ret < 0)
goto out_sleep;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return mactime;
}
static int wl1271_op_get_survey(struct ieee80211_hw *hw, int idx,
struct survey_info *survey)
{
struct wl1271 *wl = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
if (idx != 0)
return -ENOENT;
survey->channel = conf->channel;
survey->filled = SURVEY_INFO_NOISE_DBM;
survey->noise = wl->noise;
return 0;
}
static int wl1271_allocate_sta(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta)
{
struct wl1271_station *wl_sta;
int ret;
if (wl->active_sta_count >= AP_MAX_STATIONS) {
wl1271_warning("could not allocate HLID - too much stations");
return -EBUSY;
}
wl_sta = (struct wl1271_station *)sta->drv_priv;
ret = wl12xx_allocate_link(wl, wlvif, &wl_sta->hlid);
if (ret < 0) {
wl1271_warning("could not allocate HLID - too many links");
return -EBUSY;
}
set_bit(wl_sta->hlid, wlvif->ap.sta_hlid_map);
memcpy(wl->links[wl_sta->hlid].addr, sta->addr, ETH_ALEN);
wl->active_sta_count++;
return 0;
}
void wl1271_free_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid)
{
if (!test_bit(hlid, wlvif->ap.sta_hlid_map))
return;
clear_bit(hlid, wlvif->ap.sta_hlid_map);
memset(wl->links[hlid].addr, 0, ETH_ALEN);
wl->links[hlid].ba_bitmap = 0;
__clear_bit(hlid, &wl->ap_ps_map);
__clear_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map);
wl12xx_free_link(wl, wlvif, &hlid);
wl->active_sta_count--;
/*
* rearm the tx watchdog when the last STA is freed - give the FW a
* chance to return STA-buffered packets before complaining.
*/
if (wl->active_sta_count == 0)
wl12xx_rearm_tx_watchdog_locked(wl);
}
static int wl12xx_sta_add(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta)
{
struct wl1271_station *wl_sta;
int ret = 0;
u8 hlid;
wl1271_debug(DEBUG_MAC80211, "mac80211 add sta %d", (int)sta->aid);
ret = wl1271_allocate_sta(wl, wlvif, sta);
if (ret < 0)
return ret;
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
ret = wl12xx_cmd_add_peer(wl, wlvif, sta, hlid);
if (ret < 0)
wl1271_free_sta(wl, wlvif, hlid);
return ret;
}
static int wl12xx_sta_remove(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta)
{
struct wl1271_station *wl_sta;
int ret = 0, id;
wl1271_debug(DEBUG_MAC80211, "mac80211 remove sta %d", (int)sta->aid);
wl_sta = (struct wl1271_station *)sta->drv_priv;
id = wl_sta->hlid;
if (WARN_ON(!test_bit(id, wlvif->ap.sta_hlid_map)))
return -EINVAL;
ret = wl12xx_cmd_remove_peer(wl, wl_sta->hlid);
if (ret < 0)
return ret;
wl1271_free_sta(wl, wlvif, wl_sta->hlid);
return ret;
}
static int wl12xx_update_sta_state(struct wl1271 *wl,
struct wl12xx_vif *wlvif,
struct ieee80211_sta *sta,
enum ieee80211_sta_state old_state,
enum ieee80211_sta_state new_state)
{
struct wl1271_station *wl_sta;
u8 hlid;
bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS;
bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS;
int ret;
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
/* Add station (AP mode) */
if (is_ap &&
old_state == IEEE80211_STA_NOTEXIST &&
new_state == IEEE80211_STA_NONE)
return wl12xx_sta_add(wl, wlvif, sta);
/* Remove station (AP mode) */
if (is_ap &&
old_state == IEEE80211_STA_NONE &&
new_state == IEEE80211_STA_NOTEXIST) {
/* must not fail */
wl12xx_sta_remove(wl, wlvif, sta);
return 0;
}
/* Authorize station (AP mode) */
if (is_ap &&
new_state == IEEE80211_STA_AUTHORIZED) {
ret = wl12xx_cmd_set_peer_state(wl, hlid);
if (ret < 0)
return ret;
ret = wl1271_acx_set_ht_capabilities(wl, &sta->ht_cap, true,
hlid);
return ret;
}
/* Authorize station */
if (is_sta &&
new_state == IEEE80211_STA_AUTHORIZED) {
set_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags);
return wl12xx_set_authorized(wl, wlvif);
}
if (is_sta &&
old_state == IEEE80211_STA_AUTHORIZED &&
new_state == IEEE80211_STA_ASSOC) {
clear_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags);
return 0;
}
return 0;
}
static int wl12xx_op_sta_state(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
enum ieee80211_sta_state old_state,
enum ieee80211_sta_state new_state)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 sta %d state=%d->%d",
sta->aid, old_state, new_state);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EBUSY;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
ret = wl12xx_update_sta_state(wl, wlvif, sta, old_state, new_state);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
if (new_state < old_state)
return 0;
return ret;
}
static int wl1271_op_ampdu_action(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid, u16 *ssn,
u8 buf_size)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
u8 hlid, *ba_bitmap;
wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu action %d tid %d", action,
tid);
/* sanity check - the fields in FW are only 8bits wide */
if (WARN_ON(tid > 0xFF))
return -ENOTSUPP;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
ret = -EAGAIN;
goto out;
}
if (wlvif->bss_type == BSS_TYPE_STA_BSS) {
hlid = wlvif->sta.hlid;
ba_bitmap = &wlvif->sta.ba_rx_bitmap;
} else if (wlvif->bss_type == BSS_TYPE_AP_BSS) {
struct wl1271_station *wl_sta;
wl_sta = (struct wl1271_station *)sta->drv_priv;
hlid = wl_sta->hlid;
ba_bitmap = &wl->links[hlid].ba_bitmap;
} else {
ret = -EINVAL;
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu: Rx tid %d action %d",
tid, action);
switch (action) {
case IEEE80211_AMPDU_RX_START:
if (!wlvif->ba_support || !wlvif->ba_allowed) {
ret = -ENOTSUPP;
break;
}
if (wl->ba_rx_session_count >= RX_BA_MAX_SESSIONS) {
ret = -EBUSY;
wl1271_error("exceeded max RX BA sessions");
break;
}
if (*ba_bitmap & BIT(tid)) {
ret = -EINVAL;
wl1271_error("cannot enable RX BA session on active "
"tid: %d", tid);
break;
}
ret = wl12xx_acx_set_ba_receiver_session(wl, tid, *ssn, true,
hlid);
if (!ret) {
*ba_bitmap |= BIT(tid);
wl->ba_rx_session_count++;
}
break;
case IEEE80211_AMPDU_RX_STOP:
if (!(*ba_bitmap & BIT(tid))) {
ret = -EINVAL;
wl1271_error("no active RX BA session on tid: %d",
tid);
break;
}
ret = wl12xx_acx_set_ba_receiver_session(wl, tid, 0, false,
hlid);
if (!ret) {
*ba_bitmap &= ~BIT(tid);
wl->ba_rx_session_count--;
}
break;
/*
* The BA initiator session management in FW independently.
* Falling break here on purpose for all TX APDU commands.
*/
case IEEE80211_AMPDU_TX_START:
case IEEE80211_AMPDU_TX_STOP:
case IEEE80211_AMPDU_TX_OPERATIONAL:
ret = -EINVAL;
break;
default:
wl1271_error("Incorrect ampdu action id=%x\n", action);
ret = -EINVAL;
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int wl12xx_set_bitrate_mask(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const struct cfg80211_bitrate_mask *mask)
{
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
struct wl1271 *wl = hw->priv;
int i, ret = 0;
wl1271_debug(DEBUG_MAC80211, "mac80211 set_bitrate_mask 0x%x 0x%x",
mask->control[NL80211_BAND_2GHZ].legacy,
mask->control[NL80211_BAND_5GHZ].legacy);
mutex_lock(&wl->mutex);
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
wlvif->bitrate_masks[i] =
wl1271_tx_enabled_rates_get(wl,
mask->control[i].legacy,
i);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
if (wlvif->bss_type == BSS_TYPE_STA_BSS &&
!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) {
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_set_band_rate(wl, wlvif);
wlvif->basic_rate =
wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set);
ret = wl1271_acx_sta_rate_policies(wl, wlvif);
wl1271_ps_elp_sleep(wl);
}
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void wl12xx_op_channel_switch(struct ieee80211_hw *hw,
struct ieee80211_channel_switch *ch_switch)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif;
int ret;
wl1271_debug(DEBUG_MAC80211, "mac80211 channel switch");
wl1271_tx_flush(wl);
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF)) {
wl12xx_for_each_wlvif_sta(wl, wlvif) {
struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif);
ieee80211_chswitch_done(vif, false);
}
goto out;
}
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
/* TODO: change mac80211 to pass vif as param */
wl12xx_for_each_wlvif_sta(wl, wlvif) {
ret = wl12xx_cmd_channel_switch(wl, wlvif, ch_switch);
if (!ret)
set_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static bool wl1271_tx_frames_pending(struct ieee80211_hw *hw)
{
struct wl1271 *wl = hw->priv;
bool ret = false;
mutex_lock(&wl->mutex);
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
/* packets are considered pending if in the TX queue or the FW */
ret = (wl1271_tx_total_queue_count(wl) > 0) || (wl->tx_frames_cnt > 0);
out:
mutex_unlock(&wl->mutex);
return ret;
}
/* can't be const, mac80211 writes to this */
static struct ieee80211_rate wl1271_rates[] = {
{ .bitrate = 10,
.hw_value = CONF_HW_BIT_RATE_1MBPS,
.hw_value_short = CONF_HW_BIT_RATE_1MBPS, },
{ .bitrate = 20,
.hw_value = CONF_HW_BIT_RATE_2MBPS,
.hw_value_short = CONF_HW_BIT_RATE_2MBPS,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 55,
.hw_value = CONF_HW_BIT_RATE_5_5MBPS,
.hw_value_short = CONF_HW_BIT_RATE_5_5MBPS,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 110,
.hw_value = CONF_HW_BIT_RATE_11MBPS,
.hw_value_short = CONF_HW_BIT_RATE_11MBPS,
.flags = IEEE80211_RATE_SHORT_PREAMBLE },
{ .bitrate = 60,
.hw_value = CONF_HW_BIT_RATE_6MBPS,
.hw_value_short = CONF_HW_BIT_RATE_6MBPS, },
{ .bitrate = 90,
.hw_value = CONF_HW_BIT_RATE_9MBPS,
.hw_value_short = CONF_HW_BIT_RATE_9MBPS, },
{ .bitrate = 120,
.hw_value = CONF_HW_BIT_RATE_12MBPS,
.hw_value_short = CONF_HW_BIT_RATE_12MBPS, },
{ .bitrate = 180,
.hw_value = CONF_HW_BIT_RATE_18MBPS,
.hw_value_short = CONF_HW_BIT_RATE_18MBPS, },
{ .bitrate = 240,
.hw_value = CONF_HW_BIT_RATE_24MBPS,
.hw_value_short = CONF_HW_BIT_RATE_24MBPS, },
{ .bitrate = 360,
.hw_value = CONF_HW_BIT_RATE_36MBPS,
.hw_value_short = CONF_HW_BIT_RATE_36MBPS, },
{ .bitrate = 480,
.hw_value = CONF_HW_BIT_RATE_48MBPS,
.hw_value_short = CONF_HW_BIT_RATE_48MBPS, },
{ .bitrate = 540,
.hw_value = CONF_HW_BIT_RATE_54MBPS,
.hw_value_short = CONF_HW_BIT_RATE_54MBPS, },
};
/* can't be const, mac80211 writes to this */
static struct ieee80211_channel wl1271_channels[] = {
{ .hw_value = 1, .center_freq = 2412, .max_power = 25 },
{ .hw_value = 2, .center_freq = 2417, .max_power = 25 },
{ .hw_value = 3, .center_freq = 2422, .max_power = 25 },
{ .hw_value = 4, .center_freq = 2427, .max_power = 25 },
{ .hw_value = 5, .center_freq = 2432, .max_power = 25 },
{ .hw_value = 6, .center_freq = 2437, .max_power = 25 },
{ .hw_value = 7, .center_freq = 2442, .max_power = 25 },
{ .hw_value = 8, .center_freq = 2447, .max_power = 25 },
{ .hw_value = 9, .center_freq = 2452, .max_power = 25 },
{ .hw_value = 10, .center_freq = 2457, .max_power = 25 },
{ .hw_value = 11, .center_freq = 2462, .max_power = 25 },
{ .hw_value = 12, .center_freq = 2467, .max_power = 25 },
{ .hw_value = 13, .center_freq = 2472, .max_power = 25 },
{ .hw_value = 14, .center_freq = 2484, .max_power = 25 },
};
/* mapping to indexes for wl1271_rates */
static const u8 wl1271_rate_to_idx_2ghz[] = {
/* MCS rates are used only with 11n */
7, /* CONF_HW_RXTX_RATE_MCS7_SGI */
7, /* CONF_HW_RXTX_RATE_MCS7 */
6, /* CONF_HW_RXTX_RATE_MCS6 */
5, /* CONF_HW_RXTX_RATE_MCS5 */
4, /* CONF_HW_RXTX_RATE_MCS4 */
3, /* CONF_HW_RXTX_RATE_MCS3 */
2, /* CONF_HW_RXTX_RATE_MCS2 */
1, /* CONF_HW_RXTX_RATE_MCS1 */
0, /* CONF_HW_RXTX_RATE_MCS0 */
11, /* CONF_HW_RXTX_RATE_54 */
10, /* CONF_HW_RXTX_RATE_48 */
9, /* CONF_HW_RXTX_RATE_36 */
8, /* CONF_HW_RXTX_RATE_24 */
/* TI-specific rate */
CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_22 */
7, /* CONF_HW_RXTX_RATE_18 */
6, /* CONF_HW_RXTX_RATE_12 */
3, /* CONF_HW_RXTX_RATE_11 */
5, /* CONF_HW_RXTX_RATE_9 */
4, /* CONF_HW_RXTX_RATE_6 */
2, /* CONF_HW_RXTX_RATE_5_5 */
1, /* CONF_HW_RXTX_RATE_2 */
0 /* CONF_HW_RXTX_RATE_1 */
};
/* 11n STA capabilities */
#define HW_RX_HIGHEST_RATE 72
#define WL12XX_HT_CAP { \
.cap = IEEE80211_HT_CAP_GRN_FLD | IEEE80211_HT_CAP_SGI_20 | \
(1 << IEEE80211_HT_CAP_RX_STBC_SHIFT), \
.ht_supported = true, \
.ampdu_factor = IEEE80211_HT_MAX_AMPDU_8K, \
.ampdu_density = IEEE80211_HT_MPDU_DENSITY_8, \
.mcs = { \
.rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, \
.rx_highest = cpu_to_le16(HW_RX_HIGHEST_RATE), \
.tx_params = IEEE80211_HT_MCS_TX_DEFINED, \
}, \
}
/* can't be const, mac80211 writes to this */
static struct ieee80211_supported_band wl1271_band_2ghz = {
.channels = wl1271_channels,
.n_channels = ARRAY_SIZE(wl1271_channels),
.bitrates = wl1271_rates,
.n_bitrates = ARRAY_SIZE(wl1271_rates),
.ht_cap = WL12XX_HT_CAP,
};
/* 5 GHz data rates for WL1273 */
static struct ieee80211_rate wl1271_rates_5ghz[] = {
{ .bitrate = 60,
.hw_value = CONF_HW_BIT_RATE_6MBPS,
.hw_value_short = CONF_HW_BIT_RATE_6MBPS, },
{ .bitrate = 90,
.hw_value = CONF_HW_BIT_RATE_9MBPS,
.hw_value_short = CONF_HW_BIT_RATE_9MBPS, },
{ .bitrate = 120,
.hw_value = CONF_HW_BIT_RATE_12MBPS,
.hw_value_short = CONF_HW_BIT_RATE_12MBPS, },
{ .bitrate = 180,
.hw_value = CONF_HW_BIT_RATE_18MBPS,
.hw_value_short = CONF_HW_BIT_RATE_18MBPS, },
{ .bitrate = 240,
.hw_value = CONF_HW_BIT_RATE_24MBPS,
.hw_value_short = CONF_HW_BIT_RATE_24MBPS, },
{ .bitrate = 360,
.hw_value = CONF_HW_BIT_RATE_36MBPS,
.hw_value_short = CONF_HW_BIT_RATE_36MBPS, },
{ .bitrate = 480,
.hw_value = CONF_HW_BIT_RATE_48MBPS,
.hw_value_short = CONF_HW_BIT_RATE_48MBPS, },
{ .bitrate = 540,
.hw_value = CONF_HW_BIT_RATE_54MBPS,
.hw_value_short = CONF_HW_BIT_RATE_54MBPS, },
};
/* 5 GHz band channels for WL1273 */
static struct ieee80211_channel wl1271_channels_5ghz[] = {
{ .hw_value = 7, .center_freq = 5035, .max_power = 25 },
{ .hw_value = 8, .center_freq = 5040, .max_power = 25 },
{ .hw_value = 9, .center_freq = 5045, .max_power = 25 },
{ .hw_value = 11, .center_freq = 5055, .max_power = 25 },
{ .hw_value = 12, .center_freq = 5060, .max_power = 25 },
{ .hw_value = 16, .center_freq = 5080, .max_power = 25 },
{ .hw_value = 34, .center_freq = 5170, .max_power = 25 },
{ .hw_value = 36, .center_freq = 5180, .max_power = 25 },
{ .hw_value = 38, .center_freq = 5190, .max_power = 25 },
{ .hw_value = 40, .center_freq = 5200, .max_power = 25 },
{ .hw_value = 42, .center_freq = 5210, .max_power = 25 },
{ .hw_value = 44, .center_freq = 5220, .max_power = 25 },
{ .hw_value = 46, .center_freq = 5230, .max_power = 25 },
{ .hw_value = 48, .center_freq = 5240, .max_power = 25 },
{ .hw_value = 52, .center_freq = 5260, .max_power = 25 },
{ .hw_value = 56, .center_freq = 5280, .max_power = 25 },
{ .hw_value = 60, .center_freq = 5300, .max_power = 25 },
{ .hw_value = 64, .center_freq = 5320, .max_power = 25 },
{ .hw_value = 100, .center_freq = 5500, .max_power = 25 },
{ .hw_value = 104, .center_freq = 5520, .max_power = 25 },
{ .hw_value = 108, .center_freq = 5540, .max_power = 25 },
{ .hw_value = 112, .center_freq = 5560, .max_power = 25 },
{ .hw_value = 116, .center_freq = 5580, .max_power = 25 },
{ .hw_value = 120, .center_freq = 5600, .max_power = 25 },
{ .hw_value = 124, .center_freq = 5620, .max_power = 25 },
{ .hw_value = 128, .center_freq = 5640, .max_power = 25 },
{ .hw_value = 132, .center_freq = 5660, .max_power = 25 },
{ .hw_value = 136, .center_freq = 5680, .max_power = 25 },
{ .hw_value = 140, .center_freq = 5700, .max_power = 25 },
{ .hw_value = 149, .center_freq = 5745, .max_power = 25 },
{ .hw_value = 153, .center_freq = 5765, .max_power = 25 },
{ .hw_value = 157, .center_freq = 5785, .max_power = 25 },
{ .hw_value = 161, .center_freq = 5805, .max_power = 25 },
{ .hw_value = 165, .center_freq = 5825, .max_power = 25 },
};
/* mapping to indexes for wl1271_rates_5ghz */
static const u8 wl1271_rate_to_idx_5ghz[] = {
/* MCS rates are used only with 11n */
7, /* CONF_HW_RXTX_RATE_MCS7_SGI */
7, /* CONF_HW_RXTX_RATE_MCS7 */
6, /* CONF_HW_RXTX_RATE_MCS6 */
5, /* CONF_HW_RXTX_RATE_MCS5 */
4, /* CONF_HW_RXTX_RATE_MCS4 */
3, /* CONF_HW_RXTX_RATE_MCS3 */
2, /* CONF_HW_RXTX_RATE_MCS2 */
1, /* CONF_HW_RXTX_RATE_MCS1 */
0, /* CONF_HW_RXTX_RATE_MCS0 */
7, /* CONF_HW_RXTX_RATE_54 */
6, /* CONF_HW_RXTX_RATE_48 */
5, /* CONF_HW_RXTX_RATE_36 */
4, /* CONF_HW_RXTX_RATE_24 */
/* TI-specific rate */
CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_22 */
3, /* CONF_HW_RXTX_RATE_18 */
2, /* CONF_HW_RXTX_RATE_12 */
CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_11 */
1, /* CONF_HW_RXTX_RATE_9 */
0, /* CONF_HW_RXTX_RATE_6 */
CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_5_5 */
CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_2 */
CONF_HW_RXTX_RATE_UNSUPPORTED /* CONF_HW_RXTX_RATE_1 */
};
static struct ieee80211_supported_band wl1271_band_5ghz = {
.channels = wl1271_channels_5ghz,
.n_channels = ARRAY_SIZE(wl1271_channels_5ghz),
.bitrates = wl1271_rates_5ghz,
.n_bitrates = ARRAY_SIZE(wl1271_rates_5ghz),
.ht_cap = WL12XX_HT_CAP,
};
static const u8 *wl1271_band_rate_to_idx[] = {
[IEEE80211_BAND_2GHZ] = wl1271_rate_to_idx_2ghz,
[IEEE80211_BAND_5GHZ] = wl1271_rate_to_idx_5ghz
};
static const struct ieee80211_ops wl1271_ops = {
.start = wl1271_op_start,
.stop = wl1271_op_stop,
.add_interface = wl1271_op_add_interface,
.remove_interface = wl1271_op_remove_interface,
.change_interface = wl12xx_op_change_interface,
#ifdef CONFIG_PM
.suspend = wl1271_op_suspend,
.resume = wl1271_op_resume,
#endif
.config = wl1271_op_config,
.prepare_multicast = wl1271_op_prepare_multicast,
.configure_filter = wl1271_op_configure_filter,
.tx = wl1271_op_tx,
.set_key = wl1271_op_set_key,
.hw_scan = wl1271_op_hw_scan,
.cancel_hw_scan = wl1271_op_cancel_hw_scan,
.sched_scan_start = wl1271_op_sched_scan_start,
.sched_scan_stop = wl1271_op_sched_scan_stop,
.bss_info_changed = wl1271_op_bss_info_changed,
.set_frag_threshold = wl1271_op_set_frag_threshold,
.set_rts_threshold = wl1271_op_set_rts_threshold,
.conf_tx = wl1271_op_conf_tx,
.get_tsf = wl1271_op_get_tsf,
.get_survey = wl1271_op_get_survey,
.sta_state = wl12xx_op_sta_state,
.ampdu_action = wl1271_op_ampdu_action,
.tx_frames_pending = wl1271_tx_frames_pending,
.set_bitrate_mask = wl12xx_set_bitrate_mask,
.channel_switch = wl12xx_op_channel_switch,
CFG80211_TESTMODE_CMD(wl1271_tm_cmd)
};
u8 wl1271_rate_to_idx(int rate, enum ieee80211_band band)
{
u8 idx;
BUG_ON(band >= sizeof(wl1271_band_rate_to_idx)/sizeof(u8 *));
if (unlikely(rate >= CONF_HW_RXTX_RATE_MAX)) {
wl1271_error("Illegal RX rate from HW: %d", rate);
return 0;
}
idx = wl1271_band_rate_to_idx[band][rate];
if (unlikely(idx == CONF_HW_RXTX_RATE_UNSUPPORTED)) {
wl1271_error("Unsupported RX rate from HW: %d", rate);
return 0;
}
return idx;
}
static ssize_t wl1271_sysfs_show_bt_coex_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct wl1271 *wl = dev_get_drvdata(dev);
ssize_t len;
len = PAGE_SIZE;
mutex_lock(&wl->mutex);
len = snprintf(buf, len, "%d\n\n0 - off\n1 - on\n",
wl->sg_enabled);
mutex_unlock(&wl->mutex);
return len;
}
static ssize_t wl1271_sysfs_store_bt_coex_state(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct wl1271 *wl = dev_get_drvdata(dev);
unsigned long res;
int ret;
ret = kstrtoul(buf, 10, &res);
if (ret < 0) {
wl1271_warning("incorrect value written to bt_coex_mode");
return count;
}
mutex_lock(&wl->mutex);
res = !!res;
if (res == wl->sg_enabled)
goto out;
wl->sg_enabled = res;
if (wl->state == WL1271_STATE_OFF)
goto out;
ret = wl1271_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
wl1271_acx_sg_enable(wl, wl->sg_enabled);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return count;
}
static DEVICE_ATTR(bt_coex_state, S_IRUGO | S_IWUSR,
wl1271_sysfs_show_bt_coex_state,
wl1271_sysfs_store_bt_coex_state);
static ssize_t wl1271_sysfs_show_hw_pg_ver(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct wl1271 *wl = dev_get_drvdata(dev);
ssize_t len;
len = PAGE_SIZE;
mutex_lock(&wl->mutex);
if (wl->hw_pg_ver >= 0)
len = snprintf(buf, len, "%d\n", wl->hw_pg_ver);
else
len = snprintf(buf, len, "n/a\n");
mutex_unlock(&wl->mutex);
return len;
}
static DEVICE_ATTR(hw_pg_ver, S_IRUGO,
wl1271_sysfs_show_hw_pg_ver, NULL);
static ssize_t wl1271_sysfs_read_fwlog(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buffer, loff_t pos, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct wl1271 *wl = dev_get_drvdata(dev);
ssize_t len;
int ret;
ret = mutex_lock_interruptible(&wl->mutex);
if (ret < 0)
return -ERESTARTSYS;
/* Let only one thread read the log at a time, blocking others */
while (wl->fwlog_size == 0) {
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(&wl->fwlog_waitq,
&wait,
TASK_INTERRUPTIBLE);
if (wl->fwlog_size != 0) {
finish_wait(&wl->fwlog_waitq, &wait);
break;
}
mutex_unlock(&wl->mutex);
schedule();
finish_wait(&wl->fwlog_waitq, &wait);
if (signal_pending(current))
return -ERESTARTSYS;
ret = mutex_lock_interruptible(&wl->mutex);
if (ret < 0)
return -ERESTARTSYS;
}
/* Check if the fwlog is still valid */
if (wl->fwlog_size < 0) {
mutex_unlock(&wl->mutex);
return 0;
}
/* Seeking is not supported - old logs are not kept. Disregard pos. */
len = min(count, (size_t)wl->fwlog_size);
wl->fwlog_size -= len;
memcpy(buffer, wl->fwlog, len);
/* Make room for new messages */
memmove(wl->fwlog, wl->fwlog + len, wl->fwlog_size);
mutex_unlock(&wl->mutex);
return len;
}
static struct bin_attribute fwlog_attr = {
.attr = {.name = "fwlog", .mode = S_IRUSR},
.read = wl1271_sysfs_read_fwlog,
};
static bool wl12xx_mac_in_fuse(struct wl1271 *wl)
{
bool supported = false;
u8 major, minor;
if (wl->chip.id == CHIP_ID_1283_PG20) {
major = WL128X_PG_GET_MAJOR(wl->hw_pg_ver);
minor = WL128X_PG_GET_MINOR(wl->hw_pg_ver);
/* in wl128x we have the MAC address if the PG is >= (2, 1) */
if (major > 2 || (major == 2 && minor >= 1))
supported = true;
} else {
major = WL127X_PG_GET_MAJOR(wl->hw_pg_ver);
minor = WL127X_PG_GET_MINOR(wl->hw_pg_ver);
/* in wl127x we have the MAC address if the PG is >= (3, 1) */
if (major == 3 && minor >= 1)
supported = true;
}
wl1271_debug(DEBUG_PROBE,
"PG Ver major = %d minor = %d, MAC %s present",
major, minor, supported ? "is" : "is not");
return supported;
}
static void wl12xx_derive_mac_addresses(struct wl1271 *wl,
u32 oui, u32 nic, int n)
{
int i;
wl1271_debug(DEBUG_PROBE, "base address: oui %06x nic %06x, n %d",
oui, nic, n);
if (nic + n - 1 > 0xffffff)
wl1271_warning("NIC part of the MAC address wraps around!");
for (i = 0; i < n; i++) {
wl->addresses[i].addr[0] = (u8)(oui >> 16);
wl->addresses[i].addr[1] = (u8)(oui >> 8);
wl->addresses[i].addr[2] = (u8) oui;
wl->addresses[i].addr[3] = (u8)(nic >> 16);
wl->addresses[i].addr[4] = (u8)(nic >> 8);
wl->addresses[i].addr[5] = (u8) nic;
nic++;
}
wl->hw->wiphy->n_addresses = n;
wl->hw->wiphy->addresses = wl->addresses;
}
static void wl12xx_get_fuse_mac(struct wl1271 *wl)
{
u32 mac1, mac2;
wl1271_set_partition(wl, &wl12xx_part_table[PART_DRPW]);
mac1 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_1);
mac2 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_2);
/* these are the two parts of the BD_ADDR */
wl->fuse_oui_addr = ((mac2 & 0xffff) << 8) +
((mac1 & 0xff000000) >> 24);
wl->fuse_nic_addr = mac1 & 0xffffff;
wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]);
}
static int wl12xx_get_hw_info(struct wl1271 *wl)
{
int ret;
u32 die_info;
ret = wl12xx_set_power_on(wl);
if (ret < 0)
goto out;
wl->chip.id = wl1271_read32(wl, CHIP_ID_B);
if (wl->chip.id == CHIP_ID_1283_PG20)
die_info = wl1271_top_reg_read(wl, WL128X_REG_FUSE_DATA_2_1);
else
die_info = wl1271_top_reg_read(wl, WL127X_REG_FUSE_DATA_2_1);
wl->hw_pg_ver = (s8) (die_info & PG_VER_MASK) >> PG_VER_OFFSET;
if (!wl12xx_mac_in_fuse(wl)) {
wl->fuse_oui_addr = 0;
wl->fuse_nic_addr = 0;
} else {
wl12xx_get_fuse_mac(wl);
}
wl1271_power_off(wl);
out:
return ret;
}
static int wl1271_register_hw(struct wl1271 *wl)
{
int ret;
u32 oui_addr = 0, nic_addr = 0;
if (wl->mac80211_registered)
return 0;
ret = wl12xx_get_hw_info(wl);
if (ret < 0) {
wl1271_error("couldn't get hw info");
goto out;
}
ret = wl1271_fetch_nvs(wl);
if (ret == 0) {
/* NOTE: The wl->nvs->nvs element must be first, in
* order to simplify the casting, we assume it is at
* the beginning of the wl->nvs structure.
*/
u8 *nvs_ptr = (u8 *)wl->nvs;
oui_addr =
(nvs_ptr[11] << 16) + (nvs_ptr[10] << 8) + nvs_ptr[6];
nic_addr =
(nvs_ptr[5] << 16) + (nvs_ptr[4] << 8) + nvs_ptr[3];
}
/* if the MAC address is zeroed in the NVS derive from fuse */
if (oui_addr == 0 && nic_addr == 0) {
oui_addr = wl->fuse_oui_addr;
/* fuse has the BD_ADDR, the WLAN addresses are the next two */
nic_addr = wl->fuse_nic_addr + 1;
}
wl12xx_derive_mac_addresses(wl, oui_addr, nic_addr, 2);
ret = ieee80211_register_hw(wl->hw);
if (ret < 0) {
wl1271_error("unable to register mac80211 hw: %d", ret);
goto out;
}
wl->mac80211_registered = true;
wl1271_debugfs_init(wl);
wl1271_notice("loaded");
out:
return ret;
}
static void wl1271_unregister_hw(struct wl1271 *wl)
{
if (wl->plt)
wl1271_plt_stop(wl);
ieee80211_unregister_hw(wl->hw);
wl->mac80211_registered = false;
}
static int wl1271_init_ieee80211(struct wl1271 *wl)
{
static const u32 cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
WL1271_CIPHER_SUITE_GEM,
};
/* The tx descriptor buffer and the TKIP space. */
wl->hw->extra_tx_headroom = WL1271_EXTRA_SPACE_TKIP +
sizeof(struct wl1271_tx_hw_descr);
/* unit us */
/* FIXME: find a proper value */
wl->hw->channel_change_time = 10000;
wl->hw->max_listen_interval = wl->conf.conn.max_listen_interval;
wl->hw->flags = IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_SUPPORTS_DYNAMIC_PS |
IEEE80211_HW_SUPPORTS_UAPSD |
IEEE80211_HW_HAS_RATE_CONTROL |
IEEE80211_HW_CONNECTION_MONITOR |
IEEE80211_HW_REPORTS_TX_ACK_STATUS |
IEEE80211_HW_SPECTRUM_MGMT |
IEEE80211_HW_AP_LINK_PS |
IEEE80211_HW_AMPDU_AGGREGATION |
IEEE80211_HW_TX_AMPDU_SETUP_IN_HW |
IEEE80211_HW_SCAN_WHILE_IDLE;
wl->hw->wiphy->cipher_suites = cipher_suites;
wl->hw->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites);
wl->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_CLIENT) | BIT(NL80211_IFTYPE_P2P_GO);
wl->hw->wiphy->max_scan_ssids = 1;
wl->hw->wiphy->max_sched_scan_ssids = 16;
wl->hw->wiphy->max_match_sets = 16;
/*
* Maximum length of elements in scanning probe request templates
* should be the maximum length possible for a template, without
* the IEEE80211 header of the template
*/
wl->hw->wiphy->max_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE -
sizeof(struct ieee80211_header);
wl->hw->wiphy->max_sched_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE -
sizeof(struct ieee80211_header);
wl->hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD;
/* make sure all our channels fit in the scanned_ch bitmask */
BUILD_BUG_ON(ARRAY_SIZE(wl1271_channels) +
ARRAY_SIZE(wl1271_channels_5ghz) >
WL1271_MAX_CHANNELS);
/*
* We keep local copies of the band structs because we need to
* modify them on a per-device basis.
*/
memcpy(&wl->bands[IEEE80211_BAND_2GHZ], &wl1271_band_2ghz,
sizeof(wl1271_band_2ghz));
memcpy(&wl->bands[IEEE80211_BAND_5GHZ], &wl1271_band_5ghz,
sizeof(wl1271_band_5ghz));
wl->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
&wl->bands[IEEE80211_BAND_2GHZ];
wl->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
&wl->bands[IEEE80211_BAND_5GHZ];
wl->hw->queues = 4;
wl->hw->max_rates = 1;
wl->hw->wiphy->reg_notifier = wl1271_reg_notify;
/* the FW answers probe-requests in AP-mode */
wl->hw->wiphy->flags |= WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD;
wl->hw->wiphy->probe_resp_offload =
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS |
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2 |
NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P;
SET_IEEE80211_DEV(wl->hw, wl->dev);
wl->hw->sta_data_size = sizeof(struct wl1271_station);
wl->hw->vif_data_size = sizeof(struct wl12xx_vif);
wl->hw->max_rx_aggregation_subframes = 8;
return 0;
}
#define WL1271_DEFAULT_CHANNEL 0
static struct ieee80211_hw *wl1271_alloc_hw(void)
{
struct ieee80211_hw *hw;
struct wl1271 *wl;
int i, j, ret;
unsigned int order;
BUILD_BUG_ON(AP_MAX_STATIONS > WL12XX_MAX_LINKS);
hw = ieee80211_alloc_hw(sizeof(*wl), &wl1271_ops);
if (!hw) {
wl1271_error("could not alloc ieee80211_hw");
ret = -ENOMEM;
goto err_hw_alloc;
}
wl = hw->priv;
memset(wl, 0, sizeof(*wl));
INIT_LIST_HEAD(&wl->wlvif_list);
wl->hw = hw;
for (i = 0; i < NUM_TX_QUEUES; i++)
for (j = 0; j < WL12XX_MAX_LINKS; j++)
skb_queue_head_init(&wl->links[j].tx_queue[i]);
skb_queue_head_init(&wl->deferred_rx_queue);
skb_queue_head_init(&wl->deferred_tx_queue);
INIT_DELAYED_WORK(&wl->elp_work, wl1271_elp_work);
INIT_WORK(&wl->netstack_work, wl1271_netstack_work);
INIT_WORK(&wl->tx_work, wl1271_tx_work);
INIT_WORK(&wl->recovery_work, wl1271_recovery_work);
INIT_DELAYED_WORK(&wl->scan_complete_work, wl1271_scan_complete_work);
INIT_DELAYED_WORK(&wl->tx_watchdog_work, wl12xx_tx_watchdog_work);
wl->freezable_wq = create_freezable_workqueue("wl12xx_wq");
if (!wl->freezable_wq) {
ret = -ENOMEM;
goto err_hw;
}
wl->channel = WL1271_DEFAULT_CHANNEL;
wl->rx_counter = 0;
wl->power_level = WL1271_DEFAULT_POWER_LEVEL;
wl->band = IEEE80211_BAND_2GHZ;
wl->flags = 0;
wl->sg_enabled = true;
wl->hw_pg_ver = -1;
wl->ap_ps_map = 0;
wl->ap_fw_ps_map = 0;
wl->quirks = 0;
wl->platform_quirks = 0;
wl->sched_scanning = false;
wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT;
wl->system_hlid = WL12XX_SYSTEM_HLID;
wl->active_sta_count = 0;
wl->fwlog_size = 0;
init_waitqueue_head(&wl->fwlog_waitq);
/* The system link is always allocated */
__set_bit(WL12XX_SYSTEM_HLID, wl->links_map);
memset(wl->tx_frames_map, 0, sizeof(wl->tx_frames_map));
for (i = 0; i < ACX_TX_DESCRIPTORS; i++)
wl->tx_frames[i] = NULL;
spin_lock_init(&wl->wl_lock);
wl->state = WL1271_STATE_OFF;
wl->fw_type = WL12XX_FW_TYPE_NONE;
mutex_init(&wl->mutex);
/* Apply default driver configuration. */
wl1271_conf_init(wl);
order = get_order(WL1271_AGGR_BUFFER_SIZE);
wl->aggr_buf = (u8 *)__get_free_pages(GFP_KERNEL, order);
if (!wl->aggr_buf) {
ret = -ENOMEM;
goto err_wq;
}
wl->dummy_packet = wl12xx_alloc_dummy_packet(wl);
if (!wl->dummy_packet) {
ret = -ENOMEM;
goto err_aggr;
}
/* Allocate one page for the FW log */
wl->fwlog = (u8 *)get_zeroed_page(GFP_KERNEL);
if (!wl->fwlog) {
ret = -ENOMEM;
goto err_dummy_packet;
}
return hw;
err_dummy_packet:
dev_kfree_skb(wl->dummy_packet);
err_aggr:
free_pages((unsigned long)wl->aggr_buf, order);
err_wq:
destroy_workqueue(wl->freezable_wq);
err_hw:
wl1271_debugfs_exit(wl);
ieee80211_free_hw(hw);
err_hw_alloc:
return ERR_PTR(ret);
}
static int wl1271_free_hw(struct wl1271 *wl)
{
/* Unblock any fwlog readers */
mutex_lock(&wl->mutex);
wl->fwlog_size = -1;
wake_up_interruptible_all(&wl->fwlog_waitq);
mutex_unlock(&wl->mutex);
device_remove_bin_file(wl->dev, &fwlog_attr);
device_remove_file(wl->dev, &dev_attr_hw_pg_ver);
device_remove_file(wl->dev, &dev_attr_bt_coex_state);
free_page((unsigned long)wl->fwlog);
dev_kfree_skb(wl->dummy_packet);
free_pages((unsigned long)wl->aggr_buf,
get_order(WL1271_AGGR_BUFFER_SIZE));
wl1271_debugfs_exit(wl);
vfree(wl->fw);
wl->fw = NULL;
wl->fw_type = WL12XX_FW_TYPE_NONE;
kfree(wl->nvs);
wl->nvs = NULL;
kfree(wl->fw_status);
kfree(wl->tx_res_if);
destroy_workqueue(wl->freezable_wq);
ieee80211_free_hw(wl->hw);
return 0;
}
static irqreturn_t wl12xx_hardirq(int irq, void *cookie)
{
struct wl1271 *wl = cookie;
unsigned long flags;
wl1271_debug(DEBUG_IRQ, "IRQ");
/* complete the ELP completion */
spin_lock_irqsave(&wl->wl_lock, flags);
set_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags);
if (wl->elp_compl) {
complete(wl->elp_compl);
wl->elp_compl = NULL;
}
if (test_bit(WL1271_FLAG_SUSPENDED, &wl->flags)) {
/* don't enqueue a work right now. mark it as pending */
set_bit(WL1271_FLAG_PENDING_WORK, &wl->flags);
wl1271_debug(DEBUG_IRQ, "should not enqueue work");
disable_irq_nosync(wl->irq);
pm_wakeup_event(wl->dev, 0);
spin_unlock_irqrestore(&wl->wl_lock, flags);
return IRQ_HANDLED;
}
spin_unlock_irqrestore(&wl->wl_lock, flags);
return IRQ_WAKE_THREAD;
}
static int __devinit wl12xx_probe(struct platform_device *pdev)
{
struct wl12xx_platform_data *pdata = pdev->dev.platform_data;
struct ieee80211_hw *hw;
struct wl1271 *wl;
unsigned long irqflags;
int ret = -ENODEV;
hw = wl1271_alloc_hw();
if (IS_ERR(hw)) {
wl1271_error("can't allocate hw");
ret = PTR_ERR(hw);
goto out;
}
wl = hw->priv;
wl->irq = platform_get_irq(pdev, 0);
wl->ref_clock = pdata->board_ref_clock;
wl->tcxo_clock = pdata->board_tcxo_clock;
wl->platform_quirks = pdata->platform_quirks;
wl->set_power = pdata->set_power;
wl->dev = &pdev->dev;
wl->if_ops = pdata->ops;
platform_set_drvdata(pdev, wl);
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32)
irqflags = IRQF_TRIGGER_RISING;
#else
if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ)
irqflags = IRQF_TRIGGER_RISING;
else
irqflags = IRQF_TRIGGER_HIGH | IRQF_ONESHOT;
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31)
ret = compat_request_threaded_irq(&wl->irq_compat, wl->irq,
wl12xx_hardirq, wl1271_irq,
irqflags,
pdev->name, wl);
#else
ret = request_threaded_irq(wl->irq, wl12xx_hardirq, wl1271_irq,
irqflags,
pdev->name, wl);
#endif
if (ret < 0) {
wl1271_error("request_irq() failed: %d", ret);
goto out_free_hw;
}
ret = enable_irq_wake(wl->irq);
if (!ret) {
wl->irq_wake_enabled = true;
device_init_wakeup(wl->dev, 1);
if (pdata->pwr_in_suspend)
hw->wiphy->wowlan.flags = WIPHY_WOWLAN_ANY;
}
disable_irq(wl->irq);
ret = wl1271_init_ieee80211(wl);
if (ret)
goto out_irq;
ret = wl1271_register_hw(wl);
if (ret)
goto out_irq;
/* Create sysfs file to control bt coex state */
ret = device_create_file(wl->dev, &dev_attr_bt_coex_state);
if (ret < 0) {
wl1271_error("failed to create sysfs file bt_coex_state");
goto out_irq;
}
/* Create sysfs file to get HW PG version */
ret = device_create_file(wl->dev, &dev_attr_hw_pg_ver);
if (ret < 0) {
wl1271_error("failed to create sysfs file hw_pg_ver");
goto out_bt_coex_state;
}
/* Create sysfs file for the FW log */
ret = device_create_bin_file(wl->dev, &fwlog_attr);
if (ret < 0) {
wl1271_error("failed to create sysfs file fwlog");
goto out_hw_pg_ver;
}
return 0;
out_hw_pg_ver:
device_remove_file(wl->dev, &dev_attr_hw_pg_ver);
out_bt_coex_state:
device_remove_file(wl->dev, &dev_attr_bt_coex_state);
out_irq:
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31)
compat_free_threaded_irq(&wl->irq_compat);
#else
free_irq(wl->irq, wl);
#endif
out_free_hw:
wl1271_free_hw(wl);
out:
return ret;
}
static int __devexit wl12xx_remove(struct platform_device *pdev)
{
struct wl1271 *wl = platform_get_drvdata(pdev);
if (wl->irq_wake_enabled) {
device_init_wakeup(wl->dev, 0);
disable_irq_wake(wl->irq);
}
wl1271_unregister_hw(wl);
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31)
compat_free_threaded_irq(&wl->irq_compat);
compat_destroy_threaded_irq(&wl->irq_compat);
#else
free_irq(wl->irq, wl);
#endif
wl1271_free_hw(wl);
return 0;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30)
static const struct platform_device_id wl12xx_id_table[] __devinitconst = {
{ "wl12xx", 0 },
{ } /* Terminating Entry */
};
MODULE_DEVICE_TABLE(platform, wl12xx_id_table);
#endif
static struct platform_driver wl12xx_driver = {
.probe = wl12xx_probe,
.remove = __devexit_p(wl12xx_remove),
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30)
.id_table = wl12xx_id_table,
#endif
.driver = {
.name = "wl12xx_driver",
.owner = THIS_MODULE,
}
};
static int __init wl12xx_init(void)
{
return platform_driver_register(&wl12xx_driver);
}
module_init(wl12xx_init);
static void __exit wl12xx_exit(void)
{
platform_driver_unregister(&wl12xx_driver);
}
module_exit(wl12xx_exit);
u32 wl12xx_debug_level = DEBUG_NONE;
EXPORT_SYMBOL_GPL(wl12xx_debug_level);
module_param_named(debug_level, wl12xx_debug_level, uint, S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(debug_level, "wl12xx debugging level");
module_param_named(fwlog, fwlog_param, charp, 0);
MODULE_PARM_DESC(fwlog,
"FW logger options: continuous, ondemand, dbgpins or disable");
module_param(bug_on_recovery, bool, S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(bug_on_recovery, "BUG() on fw recovery");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Luciano Coelho <[email protected]>");
MODULE_AUTHOR("Juuso Oikarinen <[email protected]>");
| Java |
/*
* CDE - Common Desktop Environment
*
* Copyright (c) 1993-2012, The Open Group. All rights reserved.
*
* These libraries and programs are free software; you can
* redistribute them and/or modify them under the terms of the GNU
* Lesser General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* These libraries and programs are distributed in the hope that
* they 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 these librararies and programs; if not, write
* to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*/
/*
* File: Symbolic.c $XConsortium: Symbolic.c /main/5 1996/09/27 19:00:23 drk $
* Language: C
*
* (c) Copyright 1988, Hewlett-Packard Company, all rights reserved.
*
* (c) Copyright 1993, 1994 Hewlett-Packard Company *
* (c) Copyright 1993, 1994 International Business Machines Corp. *
* (c) Copyright 1993, 1994 Sun Microsystems, Inc. *
* (c) Copyright 1993, 1994 Novell, Inc. *
*/
#ifdef __osf__
#define SBSTDINC_H_NO_REDEFINE
#endif
#include <Dt/UserMsg.h>
#include <bms/sbport.h> /* NOTE: sbport.h must be the first include. */
#include <assert.h>
#include <bms/bms.h>
#include <bms/XeUserMsg.h>
#include <bms/MemoryMgr.h>
#include <bms/Symbolic.h>
#include <codelibs/stringx.h> /* strhash */
#include "DtSvcLock.h"
/******************************************************************************/
/* HASHING */
/* This is the default symbol table to use */
/* --------------------------------------- */
#define XE_END_OF_HASH_TABLE (XeSymtabList) -1
static XeSymTable D_sym_table = NULL;
typedef struct _unknown_entry_data {
XeString name;
} *unknown_entry_data;
/******************************************************************************/
/* Symbol (hash) Table */
/*------------------------------------------------------------------------+*/
static unsigned int
keyhash(XeSymTable t, void *key)
/*------------------------------------------------------------------------+*/
{
unsigned int hash;
if (t->hash_fn)
{
hash = t->hash_fn( key, t->hashsize );
if (hash >= t->hashsize)
_DtSimpleError(XeProgName, XeInternalError, NULL,
(XeString) "Symbolic.c: Hash value from user hash function out of range",
NULL);
/* We don't come back from the error routine */
}
else
{
hash = strhash( (const char *) key );
hash = hash & (t->hashsize - 1);
}
return hash;
}
/*------------------------------------------------------------------------+*/
static unsigned int
trap_bad_hash_fn(void * UNUSED_PARM(ptr), unsigned int UNUSED_PARM(size))
/*------------------------------------------------------------------------+*/
{
_DtSimpleError(XeProgName, XeInternalError, NULL,
(XeString) "Symbolic.c: Hash table at must be power of 2",
NULL);
/* We don't come back from the error routine */
return 1;
}
/*------------------------------------------------------------------------+*/
XeSymTable
Xe_new_symtab(unsigned int hashsize)
/*------------------------------------------------------------------------+*/
/* Note, hashsize must be power of 2 if using default hash function */
{
int i;
XeSymTable t = (XeSymTable) XeMalloc( sizeof (struct _XeSymTable) );
t->hashsize = hashsize;
t->list = (XeSymtabList *)XeMalloc( sizeof( XeSymtabList ) * hashsize );
for (i = 0; i < hashsize; i++)
t->list[i] = (XeSymtabList)NULL;
t->curr_list = XE_END_OF_HASH_TABLE;
t->curr_hash = 0;
Xe_set_sym_fns(t,
(XeSymFn_cmp)NULL,
(XeSymFn_init)NULL,
(XeSymFn_clean)NULL,
(XeSymFn_hash)NULL);
/* If not a power of two, user better have a hash function */
/* that handles that. Install hash function trap so that if */
/* he does not install one, we catch it. */
/* --------------------------------------------------------- */
if (hashsize & (hashsize - 1))
t->hash_fn = trap_bad_hash_fn;
return t;
}
/*------------------------------------------------------------------------+*/
XeSymTable
Xe_default_symtab(void)
/*------------------------------------------------------------------------+*/
{
#define D_HASHSIZE 256
_DtSvcProcessLock();
if (D_sym_table) {
_DtSvcProcessUnlock();
return D_sym_table;
}
D_sym_table = Xe_new_symtab(D_HASHSIZE);
_DtSvcProcessUnlock();
return(D_sym_table);
}
/*------------------------------------------------------------------------+*/
static XeSymtabList
NukeOneItem(XeSymTable t, XeSymtabList l)
/*------------------------------------------------------------------------+*/
{
XeSymtabList next;
/* For standard XeSymbols: */
/* 1) Free the name */
/* 2) Call free function if configured */
/* 3) Free the XeSymbol entry */
/* ---------------------------------------- */
if (l->data_is_XeSymbol)
{
XeFree( ((XeSymbol)l->data)->name );
if (t->clean_fn)
t->clean_fn( ((XeSymbol)l->data)->value );
XeFree( l->data );
}
/* For "anysym" symbols: */
/* 1) Call free function if configured */
/* 2) If we malloced the data, free it */
/* ---------------------------------------- */
else
{
if (t->clean_fn)
t->clean_fn( l->data );
if (l->data_is_malloc_mem)
XeFree(l->data);
}
next = l->rest;
XeFree(l);
return next;
}
/*------------------------------------------------------------------------+*/
XeSymTable
Xe_set_sym_fns(XeSymTable t,
XeSymFn_cmp cmp_fn,
XeSymFn_init init_fn,
XeSymFn_clean clean_fn,
XeSymFn_hash hash_fn)
/*------------------------------------------------------------------------+*/
{
if (!t) t = Xe_default_symtab();
t->cmp_fn = cmp_fn;
t->init_fn = init_fn;
t->clean_fn = clean_fn;
t->hash_fn = hash_fn;
return(t);
}
/*------------------------------------------------------------------------+*/
static XeSymbol
make_sym(XeString name)
/*------------------------------------------------------------------------+*/
{
XeSymbol sym = Xe_make_struct(_XeSymbol);
sym->name = strdup( name );
sym->value = (void*)NULL;
return sym;
}
/*------------------------------------------------------------------------+*/
static void *
intern_something(XeSymTable t,
void * data,
unsigned int size,
Boolean is_XeSymbol,
Boolean lookup_only,
int *bucket)
/*------------------------------------------------------------------------+*/
{
unsigned int hash;
XeSymtabList l;
XeSymtabList l0;
Boolean match;
void * hash_key;
/* If no cmp function assume first item of "data" is a string pointer */
/* ------------------------------------------------------------------ */
if (is_XeSymbol)
hash_key = data;
else
hash_key = (t->hash_fn) ? data : ((unknown_entry_data) data)->name;
hash = keyhash( t, hash_key );
l = t->list[hash];
if (bucket)
*bucket = hash;
for (l0 = NULL; l; l0 = l, l = l->rest)
{
void * cmp_key;
void * cmp_key2;
if (is_XeSymbol)
cmp_key = data;
else
cmp_key = (t->cmp_fn) ? data : ((unknown_entry_data) data)->name;
if (l->data_is_XeSymbol)
cmp_key2 = ((XeSymbol) l->data)->name;
else
cmp_key2 = (t->cmp_fn) ? l->data : ((unknown_entry_data) l->data)->name;
/* Use the "compare" function to see if we have a match on our key */
/* --------------------------------------------------------------- */
if (t->cmp_fn)
match = (t->cmp_fn( cmp_key, cmp_key2 ) == 0);
else
match = (strcmp((const char *) cmp_key, (const char *)cmp_key2 ) == 0);
if (match)
return l->data;
}
/* If just doing a lookup, don't add a new symbol */
/* ---------------------------------------------- */
if (lookup_only) return (void *) NULL;
/* There was no match. We need to create an entry in the hash table. */
/* ------------------------------------------------------------------ */
l = (XeSymtabList) XeMalloc( sizeof(struct _XeSymtabList) );
l->rest = (XeSymtabList)NULL;
l->data_is_XeSymbol = is_XeSymbol;
l->data_is_malloc_mem = FALSE;
if (l0)
l0->rest = l;
else
t->list[hash] = l;
/* If we have a standard symbol, make the XeSymbol entry. */
/* -------------------------------------------------------- */
if (is_XeSymbol)
{
XeSymbol sym = make_sym((XeString)data);
l->data = (void*) sym;
if (t->init_fn)
sym->value = t->init_fn( l->data, size /* will be 0 */ );
}
else
{
/* 1) If "size" != 0, */
/* - malloc "size" bytes, */
/* - copy "data" into malloced space, */
/* - Save pointer to malloc space as user's data pointer */
/* Else */
/* - Save "data" as pointer to user's data */
/* 2) If a "init_fn" is configured, */
/* - call init_fn( user's data pointer, "size" ) */
/* - set user's data pointer to return value of init_fn */
/* ONLY if "size" was zero. */
/* */
/* If size is non zero AND there is a user's malloc function, */
/* beware that the return value from the malloc function is not*/
/* save anywhere by these routines. If size was zero, the */
/* return value of the user's function is kept. */
/* ------------------------------------------------------------------ */
if (size)
{
l->data = XeMalloc( size );
memcpy(l->data, data, size);
l->data_is_malloc_mem = TRUE;
}
else
l->data = data;
if (t->init_fn)
{
void * new_data = t->init_fn( l->data, size );
if (!size)
l->data = new_data;
}
}
/* appended to the end of the hash chain (if any). */
/* --------------------------------------------------------------- */
t->curr_list = l;
t->curr_hash = hash;
#ifdef DEBUG
printf("Added data %p in list[%d] @ %p\n", l->data, hash, l);
#endif
return l->data;
}
/*------------------------------------------------------------------------+*/
XeSymbol
Xe_intern(XeSymTable t, ConstXeString const name)
/*------------------------------------------------------------------------+*/
{
if (!name) return (XeSymbol)NULL;
if (!t) t = Xe_default_symtab();
return (XeSymbol)intern_something(t, (void *)name, 0, TRUE, FALSE, (int*)NULL);
}
/*------------------------------------------------------------------------+*/
XeSymbol
Xe_lookup(XeSymTable t, ConstXeString const name)
/*------------------------------------------------------------------------+*/
{
if (!name) return (XeSymbol)NULL;
if (!t) t = Xe_default_symtab();
return (XeSymbol)intern_something(t, (void *)name, 0, TRUE, TRUE, (int*)NULL);
}
/******************************************************************************/
/* LISTS */
/*------------------------------------------------------------------------+*/
XeList
Xe_make_list(void * data, XeList rest)
/*------------------------------------------------------------------------+*/
{
XeList temp = Xe_make_struct(_XeList);
temp->data = data;
temp->rest = rest;
return temp;
}
/******************************************************************************/
/* QUEUES */
/*------------------------------------------------------------------------+*/
XeQueue
Xe_init_queue(XeQueue q, void * nullval)
/*------------------------------------------------------------------------+*/
{
q->head = 0;
q->null = nullval;
return q;
}
/*------------------------------------------------------------------------+*/
XeQueue
Xe_make_queue(void * nullval)
/*------------------------------------------------------------------------+*/
{
return Xe_init_queue(Xe_make_struct(_XeQueue), nullval);
}
/*------------------------------------------------------------------------+*/
void *
Xe_pop_queue(XeQueue q)
/*------------------------------------------------------------------------+*/
{
XeList head = q->head;
if (head) {
void * val = head->data;
q->head = head->rest;
XeFree(head);
return val;
} else
return q->null;
}
/*------------------------------------------------------------------------+*/
void *
Xe_delete_queue_element(XeQueue q, void * val)
/*------------------------------------------------------------------------+*/
{
XeList last = 0, head = q->head;
while (head)
if (head->data == val) {
if (last)
last->rest = head->rest;
else
q->head = head->rest;
if (q->tail == head)
q->tail = last;
XeFree(head);
return val;
} else
last = head, head = head->rest;
return q->null;
}
/*------------------------------------------------------------------------+*/
void
Xe_push_queue(XeQueue q, void * val)
/*------------------------------------------------------------------------+*/
{
XeList new_ptr = Xe_make_list(val, 0);
if (q->head)
q->tail->rest = new_ptr;
else
q->head = new_ptr;
q->tail = new_ptr;
}
/*------------------------------------------------------------------------+*/
void
Xe_release_queue(XeQueue q)
/*------------------------------------------------------------------------+*/
{
if (q) {
while (q->head)
Xe_pop_queue(q);
XeFree(q);
}
}
| Java |
/*
* Copyright (C) 2011-2014 MediaTek Inc.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
/*
** Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/os/linux/gl_init.c#7
*/
/*! \file gl_init.c
\brief Main routines of Linux driver
This file contains the main routines of Linux driver for MediaTek Inc. 802.11
Wireless LAN Adapters.
*/
/*
** Log: gl_init.c
**
** 09 03 2013 cp.wu
** add path for reassociation
*
* 07 17 2012 yuche.tsai
* NULL
* Fix compile error.
*
* 07 17 2012 yuche.tsai
* NULL
* Fix compile error for JB.
*
* 07 17 2012 yuche.tsai
* NULL
* Let netdev bring up.
*
* 07 17 2012 yuche.tsai
* NULL
* Compile no error before trial run.
*
* 06 13 2012 yuche.tsai
* NULL
* Update maintrunk driver.
* Add support for driver compose assoc request frame.
*
* 05 25 2012 yuche.tsai
* NULL
* Fix reset KE issue.
*
* 05 11 2012 cp.wu
* [WCXRP00001237] [MT6620 Wi-Fi][Driver] Show MAC address and MAC address source for ACS's convenience
* show MAC address & source while initiliazation
*
* 03 02 2012 terry.wu
* NULL
* EXPORT_SYMBOL(rsnParseCheckForWFAInfoElem);.
*
* 03 02 2012 terry.wu
* NULL
* Snc CFG80211 modification for ICS migration from branch 2.2.
*
* 03 02 2012 terry.wu
* NULL
* Sync CFG80211 modification from branch 2,2.
*
* 03 02 2012 terry.wu
* NULL
* Enable CFG80211 Support.
*
* 12 22 2011 george.huang
* [WCXRP00000905] [MT6628 Wi-Fi][FW] Code refinement for ROM/ RAM module dependency
* using global variable instead of stack for setting wlanoidSetNetworkAddress(), due to buffer may be released before
* TX thread handling
*
* 11 18 2011 yuche.tsai
* NULL
* CONFIG P2P support RSSI query, default turned off.
*
* 11 14 2011 yuche.tsai
* [WCXRP00001107] [Volunteer Patch][Driver] Large Network Type index assert in FW issue.
* Fix large network type index assert in FW issue.
*
* 11 14 2011 cm.chang
* NULL
* Fix compiling warning
*
* 11 11 2011 yuche.tsai
* NULL
* Fix work thread cancel issue.
*
* 11 10 2011 cp.wu
* [WCXRP00001098] [MT6620 Wi-Fi][Driver] Replace printk by DBG LOG macros in linux porting layer
* 1. eliminaite direct calls to printk in porting layer.
* 2. replaced by DBGLOG, which would be XLOG on ALPS platforms.
*
* 10 06 2011 eddie.chen
* [WCXRP00001027] [MT6628 Wi-Fi][Firmware/Driver] Tx fragmentation
* Add rlmDomainGetChnlList symbol.
*
* 09 22 2011 cm.chang
* NULL
* Safer writng stype to avoid unitialized regitry structure
*
* 09 21 2011 cm.chang
* [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code
* Avoid possible structure alignment problem
*
* 09 20 2011 chinglan.wang
* [WCXRP00000989] [WiFi Direct] [Driver] Add a new io control API to start the formation for the sigma test.
* .
*
* 09 08 2011 cm.chang
* [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code
* Use new fields ucChannelListMap and ucChannelListIndex in NVRAM
*
* 08 31 2011 cm.chang
* [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code
* .
*
* 08 11 2011 cp.wu
* [WCXRP00000830] [MT6620 Wi-Fi][Firmware] Use MDRDY counter to detect empty channel for shortening scan time
* expose scnQuerySparseChannel() for P2P-FSM.
*
* 08 11 2011 cp.wu
* [WCXRP00000830] [MT6620 Wi-Fi][Firmware] Use MDRDY counter to detect empty channel for shortening scan time
* sparse channel detection:
* driver: collect sparse channel information with scan-done event
*
* 08 02 2011 yuche.tsai
* [WCXRP00000896] [Volunteer Patch][WiFi Direct][Driver] GO with multiple client, TX deauth to a disconnecting
* device issue.
* Fix GO send deauth frame issue.
*
* 07 07 2011 wh.su
* [WCXRP00000839] [MT6620 Wi-Fi][Driver] Add the dumpMemory8 and dumpMemory32 EXPORT_SYMBOL
* Add the dumpMemory8 symbol export for debug mode.
*
* 07 06 2011 terry.wu
* [WCXRP00000735] [MT6620 Wi-Fi][BoW][FW/Driver] Protect BoW connection establishment
* Improve BoW connection establishment speed.
*
* 07 05 2011 yuche.tsai
* [WCXRP00000821] [Volunteer Patch][WiFi Direct][Driver] WiFi Direct Connection Speed Issue
* Export one symbol for enhancement.
*
* 06 13 2011 eddie.chen
* [WCXRP00000779] [MT6620 Wi-Fi][DRV] Add tx rx statistics in linux and use netif_rx_ni
* Add tx rx statistics and netif_rx_ni.
*
* 05 27 2011 cp.wu
* [WCXRP00000749] [MT6620 Wi-Fi][Driver] Add band edge tx power control to Wi-Fi NVRAM
* invoke CMD_ID_SET_EDGE_TXPWR_LIMIT when there is valid data exist in NVRAM content.
*
* 05 18 2011 cp.wu
* [WCXRP00000734] [MT6620 Wi-Fi][Driver] Pass PHY_PARAM in NVRAM to firmware domain
* pass PHY_PARAM in NVRAM from driver to firmware.
*
* 05 09 2011 jeffrey.chang
* [WCXRP00000710] [MT6620 Wi-Fi] Support pattern filter update function on IP address change
* support ARP filter through kernel notifier
*
* 05 03 2011 chinghwa.yu
* [WCXRP00000065] Update BoW design and settings
* Use kalMemAlloc to allocate event buffer for kalIndicateBOWEvent.
*
* 04 27 2011 george.huang
* [WCXRP00000684] [MT6620 Wi-Fi][Driver] Support P2P setting ARP filter
* Support P2P ARP filter setting on early suspend/ late resume
*
* 04 18 2011 terry.wu
* [WCXRP00000660] [MT6620 Wi-Fi][Driver] Remove flag CFG_WIFI_DIRECT_MOVED
* Remove flag CFG_WIFI_DIRECT_MOVED.
*
* 04 15 2011 chinghwa.yu
* [WCXRP00000065] Update BoW design and settings
* Add BOW short range mode.
*
* 04 14 2011 yuche.tsai
* [WCXRP00000646] [Volunteer Patch][MT6620][FW/Driver] Sigma Test Modification for some test case.
* Modify some driver connection flow or behavior to pass Sigma test more easier..
*
* 04 12 2011 cm.chang
* [WCXRP00000634] [MT6620 Wi-Fi][Driver][FW] 2nd BSS will not support 40MHz bandwidth for concurrency
* .
*
* 04 11 2011 george.huang
* [WCXRP00000621] [MT6620 Wi-Fi][Driver] Support P2P supplicant to set power mode
* export wlan functions to p2p
*
* 04 08 2011 pat.lu
* [WCXRP00000623] [MT6620 Wi-Fi][Driver] use ARCH define to distinguish PC Linux driver
* Use CONFIG_X86 instead of PC_LINUX_DRIVER_USE option to have proper compile setting for PC Linux driver
*
* 04 08 2011 cp.wu
* [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer
* glBusFreeIrq() should use the same pvCookie as glBusSetIrq() or request_irq()/free_irq() won't work as a pair.
*
* 04 08 2011 eddie.chen
* [WCXRP00000617] [MT6620 Wi-Fi][DRV/FW] Fix for sigma
* Fix for sigma
*
* 04 06 2011 cp.wu
* [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer
* 1. do not check for pvData inside wlanNetCreate() due to it is NULL for eHPI port
* 2. update perm_addr as well for MAC address
* 3. not calling check_mem_region() anymore for eHPI
* 4. correct MSC_CS macro for 0-based notation
*
* 03 29 2011 cp.wu
* [WCXRP00000598] [MT6620 Wi-Fi][Driver] Implementation of interface for communicating with user space process for
* RESET_START and RESET_END events
* fix typo.
*
* 03 29 2011 cp.wu
* [WCXRP00000598] [MT6620 Wi-Fi][Driver] Implementation of interface for communicating with user space process for
* RESET_START and RESET_END events
* implement kernel-to-userspace communication via generic netlink socket for whole-chip resetting mechanism
*
* 03 23 2011 cp.wu
* [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer
* apply multi-queue operation only for linux kernel > 2.6.26
*
* 03 22 2011 pat.lu
* [WCXRP00000592] [MT6620 Wi-Fi][Driver] Support PC Linux Environment Driver Build
* Add a compiler option "PC_LINUX_DRIVER_USE" for building driver in PC Linux environment.
*
* 03 21 2011 cp.wu
* [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer
* portability for compatible with linux 2.6.12.
*
* 03 21 2011 cp.wu
* [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer
* improve portability for awareness of early version of linux kernel and wireless extension.
*
* 03 21 2011 cp.wu
* [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer
* portability improvement
*
* 03 18 2011 jeffrey.chang
* [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue
* remove early suspend functions
*
* 03 17 2011 cp.wu
* [WCXRP00000562] [MT6620 Wi-Fi][Driver] I/O buffer pre-allocation to avoid physically continuous memory shortage
* after system running for a long period
* reverse order to prevent probing racing.
*
* 03 16 2011 cp.wu
* [WCXRP00000562] [MT6620 Wi-Fi][Driver] I/O buffer pre-allocation to avoid physically continuous memory shortage
* after system running for a long period
* 1. pre-allocate physical continuous buffer while module is being loaded
* 2. use pre-allocated physical continuous buffer for TX/RX DMA transfer
*
* The windows part remained the same as before, but added similar APIs to hide the difference.
*
* 03 15 2011 jeffrey.chang
* [WCXRP00000558] [MT6620 Wi-Fi][MT6620 Wi-Fi][Driver] refine the queue selection algorithm for WMM
* refine the queue_select function
*
* 03 10 2011 cp.wu
* [WCXRP00000532] [MT6620 Wi-Fi][Driver] Migrate NVRAM configuration procedures from MT6620 E2 to MT6620 E3
* deprecate configuration used by MT6620 E2
*
* 03 10 2011 terry.wu
* [WCXRP00000505] [MT6620 Wi-Fi][Driver/FW] WiFi Direct Integration
* Remove unnecessary assert and message.
*
* 03 08 2011 terry.wu
* [WCXRP00000505] [MT6620 Wi-Fi][Driver/FW] WiFi Direct Integration
* Export nicQmUpdateWmmParms.
*
* 03 03 2011 jeffrey.chang
* [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue
* support concurrent network
*
* 03 03 2011 jeffrey.chang
* [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue
* modify net device relative functions to support multiple H/W queues
*
* 02 24 2011 george.huang
* [WCXRP00000495] [MT6620 Wi-Fi][FW] Support pattern filter for unwanted ARP frames
* Support ARP filter during suspended
*
* 02 21 2011 cp.wu
* [WCXRP00000482] [MT6620 Wi-Fi][Driver] Simplify logic for checking NVRAM existence in driver domain
* simplify logic for checking NVRAM existence only once.
*
* 02 17 2011 terry.wu
* [WCXRP00000459] [MT6620 Wi-Fi][Driver] Fix deference null pointer problem in wlanRemove
* Fix deference a null pointer problem in wlanRemove.
*
* 02 16 2011 jeffrey.chang
* NULL
* fix compilig error
*
* 02 16 2011 jeffrey.chang
* NULL
* Add query ipv4 and ipv6 address during early suspend and late resume
*
* 02 15 2011 jeffrey.chang
* NULL
* to support early suspend in android
*
* 02 11 2011 yuche.tsai
* [WCXRP00000431] [Volunteer Patch][MT6620][Driver] Add MLME support for deauthentication under AP(Hot-Spot) mode.
* Add one more export symbol.
*
* 02 10 2011 yuche.tsai
* [WCXRP00000431] [Volunteer Patch][MT6620][Driver] Add MLME support for deauthentication under AP(Hot-Spot) mode.
* Add RX deauthentication & disassociation process under Hot-Spot mode.
*
* 02 09 2011 terry.wu
* [WCXRP00000383] [MT6620 Wi-Fi][Driver] Separate WiFi and P2P driver into two modules
* Halt p2p module init and exit until TxThread finished p2p register and unregister.
*
* 02 08 2011 george.huang
* [WCXRP00000422] [MT6620 Wi-Fi][Driver] support query power mode OID handler
* Support querying power mode OID.
*
* 02 08 2011 yuche.tsai
* [WCXRP00000421] [Volunteer Patch][MT6620][Driver] Fix incorrect SSID length Issue
* Export Deactivation Network.
*
* 02 01 2011 jeffrey.chang
* [WCXRP00000414] KAL Timer is not unregistered when driver not loaded
* Unregister the KAL timer during driver unloading
*
* 01 26 2011 cm.chang
* [WCXRP00000395] [MT6620 Wi-Fi][Driver][FW] Search STA_REC with additional net type index argument
* Allocate system RAM if fixed message or mgmt buffer is not available
*
* 01 19 2011 cp.wu
* [WCXRP00000371] [MT6620 Wi-Fi][Driver] make linux glue layer portable for Android 2.3.1 with Linux 2.6.35.7
* add compile option to check linux version 2.6.35 for different usage of system API to improve portability
*
* 01 12 2011 cp.wu
* [WCXRP00000357] [MT6620 Wi-Fi][Driver][Bluetooth over Wi-Fi] add another net device interface for BT AMP
* implementation of separate BT_OVER_WIFI data path.
*
* 01 10 2011 cp.wu
* [WCXRP00000349] [MT6620 Wi-Fi][Driver] make kalIoctl() of linux port as a thread safe API to avoid potential issues
* due to multiple access
* use mutex to protect kalIoctl() for thread safe.
*
* 01 04 2011 cp.wu
* [WCXRP00000338] [MT6620 Wi-Fi][Driver] Separate kalMemAlloc into kmalloc and vmalloc implementations to ease
* physically continuous memory demands
* separate kalMemAlloc() into virtually-continuous and physically-continuous type to ease slab system pressure
*
* 12 15 2010 cp.wu
* [WCXRP00000265] [MT6620 Wi-Fi][Driver] Remove set_mac_address routine from legacy Wi-Fi Android driver
* remove set MAC address. MAC address is always loaded from NVRAM instead.
*
* 12 10 2010 kevin.huang
* [WCXRP00000128] [MT6620 Wi-Fi][Driver] Add proc support to Android Driver for debug and driver status check
* Add Linux Proc Support
*
* 11 01 2010 yarco.yang
* [WCXRP00000149] [MT6620 WI-Fi][Driver]Fine tune performance on MT6516 platform
* Add GPIO debug function
*
* 11 01 2010 cp.wu
* [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000150] [MT6620 Wi-Fi][Driver]
* Add implementation for querying current TX rate from firmware auto rate module
* 1) Query link speed (TX rate) from firmware directly with buffering mechanism to reduce overhead
* 2) Remove CNM CH-RECOVER event handling
* 3) cfg read/write API renamed with kal prefix for unified naming rules.
*
* 10 26 2010 cp.wu
* [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000137] [MT6620 Wi-Fi] [FW]
* Support NIC capability query command
* 1) update NVRAM content template to ver 1.02
* 2) add compile option for querying NIC capability (default: off)
* 3) modify AIS 5GHz support to run-time option, which could be turned on by registry or NVRAM setting
* 4) correct auto-rate compiler error under linux (treat warning as error)
* 5) simplify usage of NVRAM and REG_INFO_T
* 6) add version checking between driver and firmware
*
* 10 21 2010 chinghwa.yu
* [WCXRP00000065] Update BoW design and settings
* .
*
* 10 19 2010 jeffrey.chang
* [WCXRP00000120] [MT6620 Wi-Fi][Driver] Refine linux kernel module to the license of MTK propietary and enable MTK
* HIF by default
* Refine linux kernel module to the license of MTK and enable MTK HIF
*
* 10 18 2010 jeffrey.chang
* [WCXRP00000106] [MT6620 Wi-Fi][Driver] Enable setting multicast callback in Android
* .
*
* 10 18 2010 cp.wu
* [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000086] [MT6620 Wi-Fi][Driver]
* The mac address is all zero at android
* complete implementation of Android NVRAM access
*
* 09 27 2010 chinghwa.yu
* [WCXRP00000063] Update BCM CoEx design and settings[WCXRP00000065] Update BoW design and settings
* Update BCM/BoW design and settings.
*
* 09 23 2010 cp.wu
* [WCXRP00000051] [MT6620 Wi-Fi][Driver] WHQL test fail in MAC address changed item
* use firmware reported mac address right after wlanAdapterStart() as permanent address
*
* 09 21 2010 kevin.huang
* [WCXRP00000052] [MT6620 Wi-Fi][Driver] Eliminate Linux Compile Warning
* Eliminate Linux Compile Warning
*
* 09 03 2010 kevin.huang
* NULL
* Refine #include sequence and solve recursive/nested #include issue
*
* 09 01 2010 wh.su
* NULL
* adding the wapi support for integration test.
*
* 08 18 2010 yarco.yang
* NULL
* 1. Fixed HW checksum offload function not work under Linux issue.
* 2. Add debug message.
*
* 08 16 2010 yarco.yang
* NULL
* Support Linux x86
*
* 08 02 2010 jeffrey.chang
* NULL
* 1) modify tx service thread to avoid busy looping
* 2) add spin lock declartion for linux build
*
* 07 29 2010 jeffrey.chang
* NULL
* fix memory leak for module unloading
*
* 07 28 2010 jeffrey.chang
* NULL
* 1) remove unused spinlocks
* 2) enable encyption ioctls
* 3) fix scan ioctl which may cause supplicant to hang
*
* 07 23 2010 jeffrey.chang
*
* bug fix: allocate regInfo when disabling firmware download
*
* 07 23 2010 jeffrey.chang
*
* use glue layer api to decrease or increase counter atomically
*
* 07 22 2010 jeffrey.chang
*
* add new spinlock
*
* 07 19 2010 jeffrey.chang
*
* modify cmd/data path for new design
*
* 07 08 2010 cp.wu
*
* [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository.
*
* 06 06 2010 kevin.huang
* [WPD00003832][MT6620 5931] Create driver base
* [MT6620 5931] Create driver base
*
* 05 26 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* 1) Modify set mac address code
* 2) remove power management macro
*
* 05 10 2010 cp.wu
* [WPD00003831][MT6620 Wi-Fi] Add framework for Wi-Fi Direct support
* implement basic wi-fi direct framework
*
* 05 07 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* prevent supplicant accessing driver during resume
*
* 05 07 2010 cp.wu
* [WPD00003831][MT6620 Wi-Fi] Add framework for Wi-Fi Direct support
* add basic framework for implementating P2P driver hook.
*
* 04 27 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* 1) fix firmware download bug
* 2) remove query statistics for acelerating firmware download
*
* 04 27 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* follow Linux's firmware framework, and remove unused kal API
*
* 04 21 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* add for private ioctl support
*
* 04 19 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* Query statistics from firmware
*
* 04 19 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* modify tcp/ip checksum offload flags
*
* 04 16 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* fix tcp/ip checksum offload bug
*
* 04 13 2010 cp.wu
* [WPD00003823][MT6620 Wi-Fi] Add Bluetooth-over-Wi-Fi support
* add framework for BT-over-Wi-Fi support.
* * * * * * * * * * * * * * * * * 1) prPendingCmdInfo is replaced by queue for multiple handler
* * * * * * * * * * * * * * * * * capability
* * * * * * * * * * * * * * * * * 2) command sequence number is now increased atomically
* * * * * * * * * * * * * * * * * 3) private data could be hold and taken use for other purpose
*
* 04 09 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* fix spinlock usage
*
* 04 07 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* Set MAC address from firmware
*
* 04 07 2010 cp.wu
* [WPD00001943]Create WiFi test driver framework on WinXP
* rWlanInfo should be placed at adapter rather than glue due to most operations
* * * * * * are done in adapter layer.
*
* 04 07 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* (1)improve none-glue code portability
* * (2) disable set Multicast address during atomic context
*
* 04 06 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* adding debug module
*
* 03 31 2010 wh.su
* [WPD00003816][MT6620 Wi-Fi] Adding the security support
* modify the wapi related code for new driver's design.
*
* 03 30 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* emulate NDIS Pending OID facility
*
* 03 26 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* fix f/w download start and load address by using config.h
*
* 03 26 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* [WPD00003826] Initial import for Linux port
* adding firmware download support
*
* 03 24 2010 jeffrey.chang
* [WPD00003826]Initial import for Linux port
* initial import for Linux port
** \main\maintrunk.MT5921\52 2009-10-27 22:49:59 GMT mtk01090
** Fix compile error for Linux EHPI driver
** \main\maintrunk.MT5921\51 2009-10-20 17:38:22 GMT mtk01090
** Refine driver unloading and clean up procedure. Block requests, stop main thread and clean up queued requests,
** and then stop hw.
** \main\maintrunk.MT5921\50 2009-10-08 10:33:11 GMT mtk01090
** Avoid accessing private data of net_device directly. Replace with netdev_priv(). Add more checking for input
** parameters and pointers.
** \main\maintrunk.MT5921\49 2009-09-28 20:19:05 GMT mtk01090
** Add private ioctl to carry OID structures. Restructure public/private ioctl interfaces to Linux kernel.
** \main\maintrunk.MT5921\48 2009-09-03 13:58:46 GMT mtk01088
** remove non-used code
** \main\maintrunk.MT5921\47 2009-09-03 11:40:25 GMT mtk01088
** adding the module parameter for wapi
** \main\maintrunk.MT5921\46 2009-08-18 22:56:41 GMT mtk01090
** Add Linux SDIO (with mmc core) support.
** Add Linux 2.6.21, 2.6.25, 2.6.26.
** Fix compile warning in Linux.
** \main\maintrunk.MT5921\45 2009-07-06 20:53:00 GMT mtk01088
** adding the code to check the wapi 1x frame
** \main\maintrunk.MT5921\44 2009-06-23 23:18:55 GMT mtk01090
** Add build option BUILD_USE_EEPROM and compile option CFG_SUPPORT_EXT_CONFIG for NVRAM support
** \main\maintrunk.MT5921\43 2009-02-16 23:46:51 GMT mtk01461
** Revise the order of increasing u4TxPendingFrameNum because of CFG_TX_RET_TX_CTRL_EARLY
** \main\maintrunk.MT5921\42 2009-01-22 13:11:59 GMT mtk01088
** set the tid and 1x value at same packet reserved field
** \main\maintrunk.MT5921\41 2008-10-20 22:43:53 GMT mtk01104
** Fix wrong variable name "prDev" in wlanStop()
** \main\maintrunk.MT5921\40 2008-10-16 15:37:10 GMT mtk01461
** add handle WLAN_STATUS_SUCCESS in wlanHardStartXmit() for CFG_TX_RET_TX_CTRL_EARLY
** \main\maintrunk.MT5921\39 2008-09-25 15:56:21 GMT mtk01461
** Update driver for Code review
** \main\maintrunk.MT5921\38 2008-09-05 17:25:07 GMT mtk01461
** Update Driver for Code Review
** \main\maintrunk.MT5921\37 2008-09-02 10:57:06 GMT mtk01461
** Update driver for code review
** \main\maintrunk.MT5921\36 2008-08-05 01:53:28 GMT mtk01461
** Add support for linux statistics
** \main\maintrunk.MT5921\35 2008-08-04 16:52:58 GMT mtk01461
** Fix ASSERT if removing module in BG_SSID_SCAN state
** \main\maintrunk.MT5921\34 2008-06-13 22:52:24 GMT mtk01461
** Revise status code handling in wlanHardStartXmit() for WLAN_STATUS_SUCCESS
** \main\maintrunk.MT5921\33 2008-05-30 18:56:53 GMT mtk01461
** Not use wlanoidSetCurrentAddrForLinux()
** \main\maintrunk.MT5921\32 2008-05-30 14:39:40 GMT mtk01461
** Remove WMM Assoc Flag
** \main\maintrunk.MT5921\31 2008-05-23 10:26:40 GMT mtk01084
** modify wlanISR interface
** \main\maintrunk.MT5921\30 2008-05-03 18:52:36 GMT mtk01461
** Fix Unset Broadcast filter when setMulticast
** \main\maintrunk.MT5921\29 2008-05-03 15:17:26 GMT mtk01461
** Move Query Media Status to GLUE
** \main\maintrunk.MT5921\28 2008-04-24 22:48:21 GMT mtk01461
** Revise set multicast function by using windows oid style for LP own back
** \main\maintrunk.MT5921\27 2008-04-24 12:00:08 GMT mtk01461
** Fix multicast setting in Linux and add comment
** \main\maintrunk.MT5921\26 2008-03-28 10:40:22 GMT mtk01461
** Fix set mac address func in Linux
** \main\maintrunk.MT5921\25 2008-03-26 15:37:26 GMT mtk01461
** Add set MAC Address
** \main\maintrunk.MT5921\24 2008-03-26 14:24:53 GMT mtk01461
** For Linux, set net_device has feature with checksum offload by default
** \main\maintrunk.MT5921\23 2008-03-11 14:50:52 GMT mtk01461
** Fix typo
** \main\maintrunk.MT5921\22 2008-02-29 15:35:20 GMT mtk01088
** add 1x decide code for sw port control
** \main\maintrunk.MT5921\21 2008-02-21 15:01:54 GMT mtk01461
** Rearrange the set off place of GLUE spin lock in HardStartXmit
** \main\maintrunk.MT5921\20 2008-02-12 23:26:50 GMT mtk01461
** Add debug option - Packet Order for Linux and add debug level - Event
** \main\maintrunk.MT5921\19 2007-12-11 00:11:12 GMT mtk01461
** Fix SPIN_LOCK protection
** \main\maintrunk.MT5921\18 2007-11-30 17:02:25 GMT mtk01425
** 1. Set Rx multicast packets mode before setting the address list
** \main\maintrunk.MT5921\17 2007-11-26 19:44:24 GMT mtk01461
** Add OS_TIMESTAMP to packet
** \main\maintrunk.MT5921\16 2007-11-21 15:47:20 GMT mtk01088
** fixed the unload module issue
** \main\maintrunk.MT5921\15 2007-11-07 18:37:38 GMT mtk01461
** Fix compile warnning
** \main\maintrunk.MT5921\14 2007-11-02 01:03:19 GMT mtk01461
** Unify TX Path for Normal and IBSS Power Save + IBSS neighbor learning
** \main\maintrunk.MT5921\13 2007-10-30 10:42:33 GMT mtk01425
** 1. Refine for multicast list
** \main\maintrunk.MT5921\12 2007-10-25 18:08:13 GMT mtk01461
** Add VOIP SCAN Support & Refine Roaming
** Revision 1.4 2007/07/05 07:25:33 MTK01461
** Add Linux initial code, modify doc, add 11BB, RF init code
**
** Revision 1.3 2007/06/27 02:18:50 MTK01461
** Update SCAN_FSM, Initial(Can Load Module), Proc(Can do Reg R/W), TX API
**
** Revision 1.2 2007/06/25 06:16:24 MTK01461
** Update illustrations, gl_init.c, gl_kal.c, gl_kal.h, gl_os.h and RX API
**
*/
/*******************************************************************************
* C O M P I L E R F L A G S
********************************************************************************
*/
/*******************************************************************************
* E X T E R N A L R E F E R E N C E S
********************************************************************************
*/
#include "gl_os.h"
#include "debug.h"
#include "wlan_lib.h"
#include "gl_wext.h"
#include "gl_cfg80211.h"
#include "precomp.h"
#if CFG_SUPPORT_AGPS_ASSIST
#include "gl_kal.h"
#endif
#if defined(CONFIG_MTK_TC1_FEATURE)
#include <tc1_partition.h>
#endif
#include "gl_vendor.h"
/*******************************************************************************
* C O N S T A N T S
********************************************************************************
*/
/* #define MAX_IOREQ_NUM 10 */
BOOLEAN fgIsUnderSuspend = false;
struct semaphore g_halt_sem;
int g_u4HaltFlag = 1;
#if CFG_ENABLE_WIFI_DIRECT
spinlock_t g_p2p_lock;
int g_u4P2PEnding = 0;
int g_u4P2POnOffing = 0;
#endif
/*******************************************************************************
* D A T A T Y P E S
********************************************************************************
*/
/* Tasklet mechanism is like buttom-half in Linux. We just want to
* send a signal to OS for interrupt defer processing. All resources
* are NOT allowed reentry, so txPacket, ISR-DPC and ioctl must avoid preempty.
*/
typedef struct _WLANDEV_INFO_T {
struct net_device *prDev;
} WLANDEV_INFO_T, *P_WLANDEV_INFO_T;
/*******************************************************************************
* P U B L I C D A T A
********************************************************************************
*/
MODULE_AUTHOR(NIC_AUTHOR);
MODULE_DESCRIPTION(NIC_DESC);
MODULE_SUPPORTED_DEVICE(NIC_NAME);
MODULE_LICENSE("GPL");
#define NIC_INF_NAME "wlan%d" /* interface name */
#if CFG_TC1_FEATURE
#define NIC_INF_NAME_IN_AP_MODE "legacy%d"
#endif
/* support to change debug module info dynamically */
UINT_8 aucDebugModule[DBG_MODULE_NUM];
UINT_32 u4DebugModule = 0;
/* 4 2007/06/26, mikewu, now we don't use this, we just fix the number of wlan device to 1 */
static WLANDEV_INFO_T arWlanDevInfo[CFG_MAX_WLAN_DEVICES] = { {0} };
static UINT_32 u4WlanDevNum; /* How many NICs coexist now */
/**20150205 added work queue for sched_scan to avoid cfg80211 stop schedule scan dead loack**/
struct delayed_work sched_workq;
/*******************************************************************************
* P R I V A T E D A T A
********************************************************************************
*/
#if CFG_ENABLE_WIFI_DIRECT
static SUB_MODULE_HANDLER rSubModHandler[SUB_MODULE_NUM] = { {NULL} };
#endif
#define CHAN2G(_channel, _freq, _flags) \
{ \
.band = IEEE80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel mtk_2ghz_channels[] = {
CHAN2G(1, 2412, 0),
CHAN2G(2, 2417, 0),
CHAN2G(3, 2422, 0),
CHAN2G(4, 2427, 0),
CHAN2G(5, 2432, 0),
CHAN2G(6, 2437, 0),
CHAN2G(7, 2442, 0),
CHAN2G(8, 2447, 0),
CHAN2G(9, 2452, 0),
CHAN2G(10, 2457, 0),
CHAN2G(11, 2462, 0),
CHAN2G(12, 2467, 0),
CHAN2G(13, 2472, 0),
CHAN2G(14, 2484, 0),
};
#define CHAN5G(_channel, _flags) \
{ \
.band = IEEE80211_BAND_5GHZ, \
.center_freq = 5000 + (5 * (_channel)), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel mtk_5ghz_channels[] = {
CHAN5G(34, 0), CHAN5G(36, 0),
CHAN5G(38, 0), CHAN5G(40, 0),
CHAN5G(42, 0), CHAN5G(44, 0),
CHAN5G(46, 0), CHAN5G(48, 0),
CHAN5G(52, 0), CHAN5G(56, 0),
CHAN5G(60, 0), CHAN5G(64, 0),
CHAN5G(100, 0), CHAN5G(104, 0),
CHAN5G(108, 0), CHAN5G(112, 0),
CHAN5G(116, 0), CHAN5G(120, 0),
CHAN5G(124, 0), CHAN5G(128, 0),
CHAN5G(132, 0), CHAN5G(136, 0),
CHAN5G(140, 0), CHAN5G(149, 0),
CHAN5G(153, 0), CHAN5G(157, 0),
CHAN5G(161, 0), CHAN5G(165, 0),
CHAN5G(169, 0), CHAN5G(173, 0),
CHAN5G(184, 0), CHAN5G(188, 0),
CHAN5G(192, 0), CHAN5G(196, 0),
CHAN5G(200, 0), CHAN5G(204, 0),
CHAN5G(208, 0), CHAN5G(212, 0),
CHAN5G(216, 0),
};
/* for cfg80211 - rate table */
static struct ieee80211_rate mtk_rates[] = {
RATETAB_ENT(10, 0x1000, 0),
RATETAB_ENT(20, 0x1001, 0),
RATETAB_ENT(55, 0x1002, 0),
RATETAB_ENT(110, 0x1003, 0), /* 802.11b */
RATETAB_ENT(60, 0x2000, 0),
RATETAB_ENT(90, 0x2001, 0),
RATETAB_ENT(120, 0x2002, 0),
RATETAB_ENT(180, 0x2003, 0),
RATETAB_ENT(240, 0x2004, 0),
RATETAB_ENT(360, 0x2005, 0),
RATETAB_ENT(480, 0x2006, 0),
RATETAB_ENT(540, 0x2007, 0), /* 802.11a/g */
};
#define mtk_a_rates (mtk_rates + 4)
#define mtk_a_rates_size (sizeof(mtk_rates) / sizeof(mtk_rates[0]) - 4)
#define mtk_g_rates (mtk_rates + 0)
#define mtk_g_rates_size (sizeof(mtk_rates) / sizeof(mtk_rates[0]) - 0)
#define MT6620_MCS_INFO \
{ \
.rx_mask = {0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0},\
.rx_highest = 0, \
.tx_params = IEEE80211_HT_MCS_TX_DEFINED, \
}
#define MT6620_HT_CAP \
{ \
.ht_supported = true, \
.cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 \
| IEEE80211_HT_CAP_SM_PS \
| IEEE80211_HT_CAP_GRN_FLD \
| IEEE80211_HT_CAP_SGI_20 \
| IEEE80211_HT_CAP_SGI_40, \
.ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K, \
.ampdu_density = IEEE80211_HT_MPDU_DENSITY_NONE, \
.mcs = MT6620_MCS_INFO, \
}
/* public for both Legacy Wi-Fi / P2P access */
struct ieee80211_supported_band mtk_band_2ghz = {
.band = IEEE80211_BAND_2GHZ,
.channels = mtk_2ghz_channels,
.n_channels = ARRAY_SIZE(mtk_2ghz_channels),
.bitrates = mtk_g_rates,
.n_bitrates = mtk_g_rates_size,
.ht_cap = MT6620_HT_CAP,
};
/* public for both Legacy Wi-Fi / P2P access */
struct ieee80211_supported_band mtk_band_5ghz = {
.band = IEEE80211_BAND_5GHZ,
.channels = mtk_5ghz_channels,
.n_channels = ARRAY_SIZE(mtk_5ghz_channels),
.bitrates = mtk_a_rates,
.n_bitrates = mtk_a_rates_size,
.ht_cap = MT6620_HT_CAP,
};
static const UINT_32 mtk_cipher_suites[] = {
/* keep WEP first, it may be removed below */
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
/* keep last -- depends on hw flags! */
WLAN_CIPHER_SUITE_AES_CMAC
};
static struct cfg80211_ops mtk_wlan_ops = {
.suspend = mtk_cfg80211_suspend,
.resume = mtk_cfg80211_resume,
.change_virtual_intf = mtk_cfg80211_change_iface,
.add_key = mtk_cfg80211_add_key,
.get_key = mtk_cfg80211_get_key,
.del_key = mtk_cfg80211_del_key,
.set_default_key = mtk_cfg80211_set_default_key,
.set_default_mgmt_key = mtk_cfg80211_set_default_mgmt_key,
.get_station = mtk_cfg80211_get_station,
.change_station = mtk_cfg80211_change_station,
.add_station = mtk_cfg80211_add_station,
.del_station = mtk_cfg80211_del_station,
.scan = mtk_cfg80211_scan,
.connect = mtk_cfg80211_connect,
.disconnect = mtk_cfg80211_disconnect,
.join_ibss = mtk_cfg80211_join_ibss,
.leave_ibss = mtk_cfg80211_leave_ibss,
.set_power_mgmt = mtk_cfg80211_set_power_mgmt,
.set_pmksa = mtk_cfg80211_set_pmksa,
.del_pmksa = mtk_cfg80211_del_pmksa,
.flush_pmksa = mtk_cfg80211_flush_pmksa,
.assoc = mtk_cfg80211_assoc,
/* Action Frame TX/RX */
.remain_on_channel = mtk_cfg80211_remain_on_channel,
.cancel_remain_on_channel = mtk_cfg80211_cancel_remain_on_channel,
.mgmt_tx = mtk_cfg80211_mgmt_tx,
/* .mgmt_tx_cancel_wait = mtk_cfg80211_mgmt_tx_cancel_wait, */
.mgmt_frame_register = mtk_cfg80211_mgmt_frame_register,
#ifdef CONFIG_NL80211_TESTMODE
.testmode_cmd = mtk_cfg80211_testmode_cmd,
#endif
#if (CFG_SUPPORT_TDLS == 1)
.tdls_mgmt = TdlsexCfg80211TdlsMgmt,
.tdls_oper = TdlsexCfg80211TdlsOper,
#endif /* CFG_SUPPORT_TDLS */
#if 1 /* Remove schedule_scan because we need more verification for NLO */
.sched_scan_start = mtk_cfg80211_sched_scan_start,
.sched_scan_stop = mtk_cfg80211_sched_scan_stop,
#endif
};
static const struct wiphy_vendor_command mtk_wlan_vendor_ops[] = {
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_GET_CAPABILITIES},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_get_gscan_capabilities},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_SET_CONFIG},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_set_config},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_SET_SCAN_CONFIG},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV,
.doit = mtk_cfg80211_vendor_set_scan_config},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_ENABLE_GSCAN},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_enable_scan},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_ENABLE_FULL_SCAN_RESULTS},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_enable_full_scan_results},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_GET_SCAN_RESULTS},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_get_scan_results},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_GET_CHANNEL_LIST},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_get_channel_list},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_SET_SIGNIFICANT_CHANGE_CONFIG},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_set_significant_change},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_SUBCMD_SET_HOTLIST},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_set_hotlist},
/*Link Layer Statistics */
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = LSTATS_SUBCMD_GET_INFO},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_llstats_get_info},
{
{
.vendor_id = GOOGLE_OUI,
.subcmd = RTT_SUBCMD_GETCAPABILITY},
.flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV,
.doit = mtk_cfg80211_vendor_get_rtt_capabilities},
};
static const struct nl80211_vendor_cmd_info mtk_wlan_vendor_events[] = {
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_EVENT_SIGNIFICANT_CHANGE_RESULTS},
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_EVENT_HOTLIST_RESULTS_FOUND},
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_EVENT_SCAN_RESULTS_AVAILABLE},
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_EVENT_FULL_SCAN_RESULTS},
{
.vendor_id = GOOGLE_OUI,
.subcmd = RTT_EVENT_COMPLETE},
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_EVENT_COMPLETE_SCAN},
{
.vendor_id = GOOGLE_OUI,
.subcmd = GSCAN_EVENT_HOTLIST_RESULTS_LOST},
};
/* There isn't a lot of sense in it, but you can transmit anything you like */
static const struct ieee80211_txrx_stypes
mtk_cfg80211_ais_default_mgmt_stypes[NUM_NL80211_IFTYPES] = {
[NL80211_IFTYPE_ADHOC] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_STATION] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_AP] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_AP_VLAN] = {
/* copy AP */
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_P2P_CLIENT] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_GO] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4)
}
};
/*******************************************************************************
* M A C R O S
********************************************************************************
*/
/*******************************************************************************
* F U N C T I O N D E C L A R A T I O N S
********************************************************************************
*/
/*******************************************************************************
* F U N C T I O N S
********************************************************************************
*/
/*----------------------------------------------------------------------------*/
/*!
* \brief Override the implementation of select queue
*
* \param[in] dev Pointer to struct net_device
* \param[in] skb Pointer to struct skb_buff
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
unsigned int _cfg80211_classify8021d(struct sk_buff *skb)
{
unsigned int dscp = 0;
/* skb->priority values from 256->263 are magic values
* directly indicate a specific 802.1d priority. This is
* to allow 802.1d priority to be passed directly in from
* tags
*/
if (skb->priority >= 256 && skb->priority <= 263)
return skb->priority - 256;
switch (skb->protocol) {
case htons(ETH_P_IP):
dscp = ip_hdr(skb)->tos & 0xfc;
break;
}
return dscp >> 5;
}
static const UINT_16 au16Wlan1dToQueueIdx[8] = { 1, 0, 0, 1, 2, 2, 3, 3 };
static UINT_16 wlanSelectQueue(struct net_device *dev, struct sk_buff *skb,
void *accel_priv, select_queue_fallback_t fallback)
{
skb->priority = _cfg80211_classify8021d(skb);
return au16Wlan1dToQueueIdx[skb->priority];
}
/*----------------------------------------------------------------------------*/
/*!
* \brief Load NVRAM data and translate it into REG_INFO_T
*
* \param[in] prGlueInfo Pointer to struct GLUE_INFO_T
* \param[out] prRegInfo Pointer to struct REG_INFO_T
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static void glLoadNvram(IN P_GLUE_INFO_T prGlueInfo, OUT P_REG_INFO_T prRegInfo)
{
UINT_32 i, j;
UINT_8 aucTmp[2];
PUINT_8 pucDest;
ASSERT(prGlueInfo);
ASSERT(prRegInfo);
if ((!prGlueInfo) || (!prRegInfo))
return;
if (kalCfgDataRead16(prGlueInfo, sizeof(WIFI_CFG_PARAM_STRUCT) - sizeof(UINT_16), (PUINT_16) aucTmp) == TRUE) {
prGlueInfo->fgNvramAvailable = TRUE;
/* load MAC Address */
#if !defined(CONFIG_MTK_TC1_FEATURE)
for (i = 0; i < PARAM_MAC_ADDR_LEN; i += sizeof(UINT_16)) {
kalCfgDataRead16(prGlueInfo,
OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucMacAddress) + i,
(PUINT_16) (((PUINT_8) prRegInfo->aucMacAddr) + i));
}
#else
TC1_FAC_NAME(FacReadWifiMacAddr) ((unsigned char *)prRegInfo->aucMacAddr);
#endif
/* load country code */
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucCountryCode[0]), (PUINT_16) aucTmp);
/* cast to wide characters */
prRegInfo->au2CountryCode[0] = (UINT_16) aucTmp[0];
prRegInfo->au2CountryCode[1] = (UINT_16) aucTmp[1];
/* load default normal TX power */
for (i = 0; i < sizeof(TX_PWR_PARAM_T); i += sizeof(UINT_16)) {
kalCfgDataRead16(prGlueInfo,
OFFSET_OF(WIFI_CFG_PARAM_STRUCT, rTxPwr) + i,
(PUINT_16) (((PUINT_8) &(prRegInfo->rTxPwr)) + i));
}
/* load feature flags */
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucTxPwrValid), (PUINT_16) aucTmp);
prRegInfo->ucTxPwrValid = aucTmp[0];
prRegInfo->ucSupport5GBand = aucTmp[1];
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, uc2G4BwFixed20M), (PUINT_16) aucTmp);
prRegInfo->uc2G4BwFixed20M = aucTmp[0];
prRegInfo->uc5GBwFixed20M = aucTmp[1];
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucEnable5GBand), (PUINT_16) aucTmp);
prRegInfo->ucEnable5GBand = aucTmp[0];
/* load EFUSE overriding part */
for (i = 0; i < sizeof(prRegInfo->aucEFUSE); i += sizeof(UINT_16)) {
kalCfgDataRead16(prGlueInfo,
OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucEFUSE) + i,
(PUINT_16) (((PUINT_8) &(prRegInfo->aucEFUSE)) + i));
}
/* load band edge tx power control */
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, fg2G4BandEdgePwrUsed), (PUINT_16) aucTmp);
prRegInfo->fg2G4BandEdgePwrUsed = (BOOLEAN) aucTmp[0];
if (aucTmp[0]) {
prRegInfo->cBandEdgeMaxPwrCCK = (INT_8) aucTmp[1];
kalCfgDataRead16(prGlueInfo,
OFFSET_OF(WIFI_CFG_PARAM_STRUCT, cBandEdgeMaxPwrOFDM20), (PUINT_16) aucTmp);
prRegInfo->cBandEdgeMaxPwrOFDM20 = (INT_8) aucTmp[0];
prRegInfo->cBandEdgeMaxPwrOFDM40 = (INT_8) aucTmp[1];
}
/* load regulation subbands */
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucRegChannelListMap), (PUINT_16) aucTmp);
prRegInfo->eRegChannelListMap = (ENUM_REG_CH_MAP_T) aucTmp[0];
prRegInfo->ucRegChannelListIndex = aucTmp[1];
if (prRegInfo->eRegChannelListMap == REG_CH_MAP_CUSTOMIZED) {
for (i = 0; i < MAX_SUBBAND_NUM; i++) {
pucDest = (PUINT_8) &prRegInfo->rDomainInfo.rSubBand[i];
for (j = 0; j < 6; j += sizeof(UINT_16)) {
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucRegSubbandInfo)
+ (i * 6 + j), (PUINT_16) aucTmp);
*pucDest++ = aucTmp[0];
*pucDest++ = aucTmp[1];
}
}
}
/* load RSSI compensation */
kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, uc2GRssiCompensation), (PUINT_16) aucTmp);
prRegInfo->uc2GRssiCompensation = aucTmp[0];
prRegInfo->uc5GRssiCompensation = aucTmp[1];
kalCfgDataRead16(prGlueInfo,
OFFSET_OF(WIFI_CFG_PARAM_STRUCT, fgRssiCompensationValidbit), (PUINT_16) aucTmp);
prRegInfo->fgRssiCompensationValidbit = aucTmp[0];
prRegInfo->ucRxAntennanumber = aucTmp[1];
} else {
prGlueInfo->fgNvramAvailable = FALSE;
}
}
#if CFG_ENABLE_WIFI_DIRECT
/*----------------------------------------------------------------------------*/
/*!
* \brief called by txthread, run sub module init function
*
* \param[in] prGlueInfo Pointer to struct GLUE_INFO_T
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
VOID wlanSubModRunInit(P_GLUE_INFO_T prGlueInfo)
{
/*now, we only have p2p module */
if (rSubModHandler[P2P_MODULE].fgIsInited == FALSE) {
rSubModHandler[P2P_MODULE].subModInit(prGlueInfo);
rSubModHandler[P2P_MODULE].fgIsInited = TRUE;
}
}
/*----------------------------------------------------------------------------*/
/*!
* \brief called by txthread, run sub module exit function
*
* \param[in] prGlueInfo Pointer to struct GLUE_INFO_T
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
VOID wlanSubModRunExit(P_GLUE_INFO_T prGlueInfo)
{
/*now, we only have p2p module */
if (rSubModHandler[P2P_MODULE].fgIsInited == TRUE) {
rSubModHandler[P2P_MODULE].subModExit(prGlueInfo);
rSubModHandler[P2P_MODULE].fgIsInited = FALSE;
}
}
/*----------------------------------------------------------------------------*/
/*!
* \brief set sub module init flag, force TxThread to run sub modle init
*
* \param[in] prGlueInfo Pointer to struct GLUE_INFO_T
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
BOOLEAN wlanSubModInit(P_GLUE_INFO_T prGlueInfo)
{
/* 4 Mark HALT, notify main thread to finish current job */
prGlueInfo->ulFlag |= GLUE_FLAG_SUB_MOD_INIT;
/* wake up main thread */
wake_up_interruptible(&prGlueInfo->waitq);
/* wait main thread finish sub module INIT */
wait_for_completion_interruptible(&prGlueInfo->rSubModComp);
#if 0
if (prGlueInfo->prAdapter->fgIsP2PRegistered)
p2pNetRegister(prGlueInfo);
#endif
return TRUE;
}
/*----------------------------------------------------------------------------*/
/*!
* \brief set sub module exit flag, force TxThread to run sub modle exit
*
* \param[in] prGlueInfo Pointer to struct GLUE_INFO_T
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
BOOLEAN wlanSubModExit(P_GLUE_INFO_T prGlueInfo)
{
#if 0
if (prGlueInfo->prAdapter->fgIsP2PRegistered)
p2pNetUnregister(prGlueInfo);
#endif
/* 4 Mark HALT, notify main thread to finish current job */
prGlueInfo->ulFlag |= GLUE_FLAG_SUB_MOD_EXIT;
/* wake up main thread */
wake_up_interruptible(&prGlueInfo->waitq);
/* wait main thread finish sub module EXIT */
wait_for_completion_interruptible(&prGlueInfo->rSubModComp);
return TRUE;
}
/*----------------------------------------------------------------------------*/
/*!
* \brief set by sub module, indicate sub module is already inserted
*
* \param[in] rSubModInit, function pointer point to sub module init function
* \param[in] rSubModExit, function pointer point to sub module exit function
* \param[in] eSubModIdx, sub module index
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
VOID
wlanSubModRegisterInitExit(SUB_MODULE_INIT rSubModInit, SUB_MODULE_EXIT rSubModExit, ENUM_SUB_MODULE_IDX_T eSubModIdx)
{
rSubModHandler[eSubModIdx].subModInit = rSubModInit;
rSubModHandler[eSubModIdx].subModExit = rSubModExit;
rSubModHandler[eSubModIdx].fgIsInited = FALSE;
}
#if 0
/*----------------------------------------------------------------------------*/
/*!
* \brief check wlan is launched or not
*
* \param[in] (none)
*
* \return TRUE, wlan is already started
* FALSE, wlan is not started yet
*/
/*----------------------------------------------------------------------------*/
BOOLEAN wlanIsLaunched(VOID)
{
struct net_device *prDev = NULL;
P_GLUE_INFO_T prGlueInfo = NULL;
/* 4 <0> Sanity check */
ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES);
if (0 == u4WlanDevNum)
return FALSE;
prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev;
ASSERT(prDev);
if (NULL == prDev)
return FALSE;
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
ASSERT(prGlueInfo);
if (NULL == prGlueInfo)
return FALSE;
return prGlueInfo->prAdapter->fgIsWlanLaunched;
}
#endif
/*----------------------------------------------------------------------------*/
/*!
* \brief Export wlan GLUE_INFO_T pointer to p2p module
*
* \param[in] prGlueInfo Pointer to struct GLUE_INFO_T
*
* \return TRUE: get GlueInfo pointer successfully
* FALSE: wlan is not started yet
*/
/*---------------------------------------------------------------------------*/
BOOLEAN wlanExportGlueInfo(P_GLUE_INFO_T *prGlueInfoExpAddr)
{
struct net_device *prDev = NULL;
P_GLUE_INFO_T prGlueInfo = NULL;
if (0 == u4WlanDevNum)
return FALSE;
prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev;
if (NULL == prDev)
return FALSE;
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
if (NULL == prGlueInfo)
return FALSE;
if (FALSE == prGlueInfo->prAdapter->fgIsWlanLaunched)
return FALSE;
*prGlueInfoExpAddr = prGlueInfo;
return TRUE;
}
#endif
/*----------------------------------------------------------------------------*/
/*!
* \brief Release prDev from wlandev_array and free tasklet object related to it.
*
* \param[in] prDev Pointer to struct net_device
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static void wlanClearDevIdx(struct net_device *prDev)
{
int i;
ASSERT(prDev);
for (i = 0; i < CFG_MAX_WLAN_DEVICES; i++) {
if (arWlanDevInfo[i].prDev == prDev) {
arWlanDevInfo[i].prDev = NULL;
u4WlanDevNum--;
}
}
} /* end of wlanClearDevIdx() */
/*----------------------------------------------------------------------------*/
/*!
* \brief Allocate an unique interface index, net_device::ifindex member for this
* wlan device. Store the net_device in wlandev_array, and initialize
* tasklet object related to it.
*
* \param[in] prDev Pointer to struct net_device
*
* \retval >= 0 The device number.
* \retval -1 Fail to get index.
*/
/*----------------------------------------------------------------------------*/
static int wlanGetDevIdx(struct net_device *prDev)
{
int i;
ASSERT(prDev);
for (i = 0; i < CFG_MAX_WLAN_DEVICES; i++) {
if (arWlanDevInfo[i].prDev == (struct net_device *)NULL) {
/* Reserve 2 bytes space to store one digit of
* device number and NULL terminator.
*/
arWlanDevInfo[i].prDev = prDev;
u4WlanDevNum++;
return i;
}
}
return -1;
} /* end of wlanGetDevIdx() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A method of struct net_device, a primary SOCKET interface to configure
* the interface lively. Handle an ioctl call on one of our devices.
* Everything Linux ioctl specific is done here. Then we pass the contents
* of the ifr->data to the request message handler.
*
* \param[in] prDev Linux kernel netdevice
*
* \param[in] prIFReq Our private ioctl request structure, typed for the generic
* struct ifreq so we can use ptr to function
*
* \param[in] cmd Command ID
*
* \retval WLAN_STATUS_SUCCESS The IOCTL command is executed successfully.
* \retval OTHER The execution of IOCTL command is failed.
*/
/*----------------------------------------------------------------------------*/
int wlanDoIOCTL(struct net_device *prDev, struct ifreq *prIFReq, int i4Cmd)
{
P_GLUE_INFO_T prGlueInfo = NULL;
int ret = 0;
/* Verify input parameters for the following functions */
ASSERT(prDev && prIFReq);
if (!prDev || !prIFReq) {
DBGLOG(INIT, WARN, "%s Invalid input data\n", __func__);
return -EINVAL;
}
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
ASSERT(prGlueInfo);
if (!prGlueInfo) {
DBGLOG(INIT, WARN, "%s No glue info\n", __func__);
return -EFAULT;
}
if (prGlueInfo->u4ReadyFlag == 0)
return -EINVAL;
/* printk ("ioctl %x\n", i4Cmd); */
if (i4Cmd == SIOCGIWPRIV) {
/* 0x8B0D, get private ioctl table */
ret = wext_get_priv(prDev, prIFReq);
} else if ((i4Cmd >= SIOCIWFIRST) && (i4Cmd < SIOCIWFIRSTPRIV)) {
/* 0x8B00 ~ 0x8BDF, wireless extension region */
ret = wext_support_ioctl(prDev, prIFReq, i4Cmd);
} else if ((i4Cmd >= SIOCIWFIRSTPRIV) && (i4Cmd < SIOCIWLASTPRIV)) {
/* 0x8BE0 ~ 0x8BFF, private ioctl region */
ret = priv_support_ioctl(prDev, prIFReq, i4Cmd);
} else if (i4Cmd == SIOCDEVPRIVATE + 1) {
ret = priv_support_driver_cmd(prDev, prIFReq, i4Cmd);
} else {
DBGLOG(INIT, WARN, "Unexpected ioctl command: 0x%04x\n", i4Cmd);
/* return 0 for safe? */
}
return ret;
} /* end of wlanDoIOCTL() */
/*----------------------------------------------------------------------------*/
/*!
* \brief This function is to set multicast list and set rx mode.
*
* \param[in] prDev Pointer to struct net_device
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static struct delayed_work workq;
static struct net_device *gPrDev;
static BOOLEAN fgIsWorkMcStart = FALSE;
static BOOLEAN fgIsWorkMcEverInit = FALSE;
static struct wireless_dev *gprWdev;
#ifdef CONFIG_PM
static const struct wiphy_wowlan_support wlan_wowlan_support = {
.flags = WIPHY_WOWLAN_DISCONNECT | WIPHY_WOWLAN_ANY,
};
#endif
static void createWirelessDevice(void)
{
struct wiphy *prWiphy = NULL;
struct wireless_dev *prWdev = NULL;
#if CFG_SUPPORT_PERSIST_NETDEV
struct net_device *prNetDev = NULL;
#endif
/* <1.1> Create wireless_dev */
prWdev = kzalloc(sizeof(struct wireless_dev), GFP_KERNEL);
if (!prWdev) {
DBGLOG(INIT, ERROR, "Allocating memory to wireless_dev context failed\n");
return;
}
/* initialize semaphore for ioctl */
sema_init(&g_halt_sem, 1);
g_u4HaltFlag = 1;
/* <1.2> Create wiphy */
prWiphy = wiphy_new(&mtk_wlan_ops, sizeof(GLUE_INFO_T));
if (!prWiphy) {
DBGLOG(INIT, ERROR, "Allocating memory to wiphy device failed\n");
goto free_wdev;
}
/* <1.3> configure wireless_dev & wiphy */
prWdev->iftype = NL80211_IFTYPE_STATION;
prWiphy->max_scan_ssids = 1; /* FIXME: for combo scan */
prWiphy->max_scan_ie_len = 512;
prWiphy->max_sched_scan_ssids = CFG_SCAN_SSID_MAX_NUM;
prWiphy->max_match_sets = CFG_SCAN_SSID_MATCH_MAX_NUM;
prWiphy->max_sched_scan_ie_len = CFG_CFG80211_IE_BUF_LEN;
prWiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_ADHOC);
prWiphy->bands[IEEE80211_BAND_2GHZ] = &mtk_band_2ghz;
/* always assign 5Ghz bands here, if the chip is not support 5Ghz,
bands[IEEE80211_BAND_5GHZ] will be assign to NULL */
prWiphy->bands[IEEE80211_BAND_5GHZ] = &mtk_band_5ghz;
prWiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
prWiphy->cipher_suites = (const u32 *)mtk_cipher_suites;
prWiphy->n_cipher_suites = ARRAY_SIZE(mtk_cipher_suites);
prWiphy->flags = WIPHY_FLAG_SUPPORTS_FW_ROAM
| WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL
| WIPHY_FLAG_SUPPORTS_SCHED_SCAN;
prWiphy->regulatory_flags = REGULATORY_CUSTOM_REG;
#if (CFG_SUPPORT_TDLS == 1)
TDLSEX_WIPHY_FLAGS_INIT(prWiphy->flags);
#endif /* CFG_SUPPORT_TDLS */
prWiphy->max_remain_on_channel_duration = 5000;
prWiphy->mgmt_stypes = mtk_cfg80211_ais_default_mgmt_stypes;
prWiphy->vendor_commands = mtk_wlan_vendor_ops;
prWiphy->n_vendor_commands = sizeof(mtk_wlan_vendor_ops) / sizeof(struct wiphy_vendor_command);
prWiphy->vendor_events = mtk_wlan_vendor_events;
prWiphy->n_vendor_events = ARRAY_SIZE(mtk_wlan_vendor_events);
/* <1.4> wowlan support */
#ifdef CONFIG_PM
prWiphy->wowlan = &wlan_wowlan_support;
#endif
#ifdef CONFIG_CFG80211_WEXT
/* <1.5> Use wireless extension to replace IOCTL */
prWiphy->wext = &wext_handler_def;
#endif
if (wiphy_register(prWiphy) < 0) {
DBGLOG(INIT, ERROR, "wiphy_register error\n");
goto free_wiphy;
}
prWdev->wiphy = prWiphy;
#if CFG_SUPPORT_PERSIST_NETDEV
/* <2> allocate and register net_device */
#if CFG_TC1_FEATURE
if (wlan_if_changed)
prNetDev = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME_IN_AP_MODE, NET_NAME_PREDICTABLE,
ether_setup, CFG_MAX_TXQ_NUM);
else
#else
prNetDev = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE,
ether_setup, CFG_MAX_TXQ_NUM);
#endif
if (!prNetDev) {
DBGLOG(INIT, ERROR, "Allocating memory to net_device context failed\n");
goto unregister_wiphy;
}
*((P_GLUE_INFO_T *) netdev_priv(prNetDev)) = (P_GLUE_INFO_T) wiphy_priv(prWiphy);
prNetDev->netdev_ops = &wlan_netdev_ops;
#ifdef CONFIG_WIRELESS_EXT
prNetDev->wireless_handlers = &wext_handler_def;
#endif
netif_carrier_off(prNetDev);
netif_tx_stop_all_queues(prNetDev);
/* <2.1> co-relate with wireless_dev bi-directionally */
prNetDev->ieee80211_ptr = prWdev;
prWdev->netdev = prNetDev;
#if CFG_TCP_IP_CHKSUM_OFFLOAD
prNetDev->features = NETIF_F_HW_CSUM;
#endif
/* <2.2> co-relate net device & device tree */
SET_NETDEV_DEV(prNetDev, wiphy_dev(prWiphy));
/* <2.3> register net_device */
if (register_netdev(prWdev->netdev) < 0) {
DBGLOG(INIT, ERROR, "wlanNetRegister: net_device context is not registered.\n");
goto unregister_wiphy;
}
#endif /* CFG_SUPPORT_PERSIST_NETDEV */
gprWdev = prWdev;
DBGLOG(INIT, INFO, "create wireless device success\n");
return;
#if CFG_SUPPORT_PERSIST_NETDEV
unregister_wiphy:
wiphy_unregister(prWiphy);
#endif
free_wiphy:
wiphy_free(prWiphy);
free_wdev:
kfree(prWdev);
}
static void destroyWirelessDevice(void)
{
#if CFG_SUPPORT_PERSIST_NETDEV
unregister_netdev(gprWdev->netdev);
free_netdev(gprWdev->netdev);
#endif
wiphy_unregister(gprWdev->wiphy);
wiphy_free(gprWdev->wiphy);
kfree(gprWdev);
gprWdev = NULL;
}
static void wlanSetMulticastList(struct net_device *prDev)
{
gPrDev = prDev;
schedule_delayed_work(&workq, 0);
}
/* FIXME: Since we cannot sleep in the wlanSetMulticastList, we arrange
* another workqueue for sleeping. We don't want to block
* tx_thread, so we can't let tx_thread to do this */
static void wlanSetMulticastListWorkQueue(struct work_struct *work)
{
P_GLUE_INFO_T prGlueInfo = NULL;
UINT_32 u4PacketFilter = 0;
UINT_32 u4SetInfoLen;
struct net_device *prDev = gPrDev;
fgIsWorkMcStart = TRUE;
DBGLOG(INIT, INFO, "wlanSetMulticastListWorkQueue start...\n");
down(&g_halt_sem);
if (g_u4HaltFlag) {
fgIsWorkMcStart = FALSE;
up(&g_halt_sem);
return;
}
prGlueInfo = (NULL != prDev) ? *((P_GLUE_INFO_T *) netdev_priv(prDev)) : NULL;
ASSERT(prDev);
ASSERT(prGlueInfo);
if (!prDev || !prGlueInfo) {
DBGLOG(INIT, WARN, "abnormal dev or skb: prDev(0x%p), prGlueInfo(0x%p)\n", prDev, prGlueInfo);
fgIsWorkMcStart = FALSE;
up(&g_halt_sem);
return;
}
if (prDev->flags & IFF_PROMISC)
u4PacketFilter |= PARAM_PACKET_FILTER_PROMISCUOUS;
if (prDev->flags & IFF_BROADCAST)
u4PacketFilter |= PARAM_PACKET_FILTER_BROADCAST;
if (prDev->flags & IFF_MULTICAST) {
if ((prDev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(prDev) > MAX_NUM_GROUP_ADDR)) {
u4PacketFilter |= PARAM_PACKET_FILTER_ALL_MULTICAST;
} else {
u4PacketFilter |= PARAM_PACKET_FILTER_MULTICAST;
}
}
up(&g_halt_sem);
if (kalIoctl(prGlueInfo,
wlanoidSetCurrentPacketFilter,
&u4PacketFilter,
sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) {
fgIsWorkMcStart = FALSE;
return;
}
if (u4PacketFilter & PARAM_PACKET_FILTER_MULTICAST) {
/* Prepare multicast address list */
struct netdev_hw_addr *ha;
PUINT_8 prMCAddrList = NULL;
UINT_32 i = 0;
down(&g_halt_sem);
if (g_u4HaltFlag) {
fgIsWorkMcStart = FALSE;
up(&g_halt_sem);
return;
}
prMCAddrList = kalMemAlloc(MAX_NUM_GROUP_ADDR * ETH_ALEN, VIR_MEM_TYPE);
netdev_for_each_mc_addr(ha, prDev) {
if (i < MAX_NUM_GROUP_ADDR) {
memcpy((prMCAddrList + i * ETH_ALEN), ha->addr, ETH_ALEN);
i++;
}
}
up(&g_halt_sem);
kalIoctl(prGlueInfo,
wlanoidSetMulticastList,
prMCAddrList, (i * ETH_ALEN), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen);
kalMemFree(prMCAddrList, VIR_MEM_TYPE, MAX_NUM_GROUP_ADDR * ETH_ALEN);
}
fgIsWorkMcStart = FALSE;
DBGLOG(INIT, INFO, "wlanSetMulticastListWorkQueue end\n");
} /* end of wlanSetMulticastList() */
/*----------------------------------------------------------------------------*/
/*!
* \brief To indicate scheduled scan has been stopped
*
* \param[in]
* prGlueInfo
*
* \return
* None
*/
/*----------------------------------------------------------------------------*/
VOID wlanSchedScanStoppedWorkQueue(struct work_struct *work)
{
P_GLUE_INFO_T prGlueInfo = NULL;
struct net_device *prDev = gPrDev;
prGlueInfo = (NULL != prDev) ? *((P_GLUE_INFO_T *) netdev_priv(prDev)) : NULL;
if (!prGlueInfo) {
DBGLOG(SCN, ERROR, "prGlueInfo == NULL unexpected\n");
return;
}
/* 2. indication to cfg80211 */
/* 20150205 change cfg80211_sched_scan_stopped to work queue due to sched_scan_mtx dead lock issue */
cfg80211_sched_scan_stopped(priv_to_wiphy(prGlueInfo));
DBGLOG(SCN, INFO,
"cfg80211_sched_scan_stopped event send done\n");
}
/* FIXME: Since we cannot sleep in the wlanSetMulticastList, we arrange
* another workqueue for sleeping. We don't want to block
* tx_thread, so we can't let tx_thread to do this */
void p2pSetMulticastListWorkQueueWrapper(P_GLUE_INFO_T prGlueInfo)
{
ASSERT(prGlueInfo);
if (!prGlueInfo) {
DBGLOG(INIT, WARN, "abnormal dev or skb: prGlueInfo(0x%p)\n", prGlueInfo);
return;
}
#if CFG_ENABLE_WIFI_DIRECT
if (prGlueInfo->prAdapter->fgIsP2PRegistered)
mtk_p2p_wext_set_Multicastlist(prGlueInfo);
#endif
} /* end of p2pSetMulticastListWorkQueueWrapper() */
/*----------------------------------------------------------------------------*/
/*!
* \brief This function is TX entry point of NET DEVICE.
*
* \param[in] prSkb Pointer of the sk_buff to be sent
* \param[in] prDev Pointer to struct net_device
*
* \retval NETDEV_TX_OK - on success.
* \retval NETDEV_TX_BUSY - on failure, packet will be discarded by upper layer.
*/
/*----------------------------------------------------------------------------*/
int wlanHardStartXmit(struct sk_buff *prSkb, struct net_device *prDev)
{
P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
P_QUE_ENTRY_T prQueueEntry = NULL;
P_QUE_T prTxQueue = NULL;
UINT_16 u2QueueIdx = 0;
#if (CFG_SUPPORT_TDLS_DBG == 1)
UINT16 u2Identifier = 0;
#endif
#if CFG_BOW_TEST
UINT_32 i;
#endif
GLUE_SPIN_LOCK_DECLARATION();
ASSERT(prSkb);
ASSERT(prDev);
ASSERT(prGlueInfo);
#if (CFG_SUPPORT_TDLS_DBG == 1)
{
UINT8 *pkt = prSkb->data;
if ((*(pkt + 12) == 0x08) && (*(pkt + 13) == 0x00)) {
/* ip */
u2Identifier = ((*(pkt + 18)) << 8) | (*(pkt + 19));
/* u2TdlsTxSeq[u4TdlsTxSeqId ++] = u2Identifier; */
DBGLOG(INIT, INFO, "<s> %d\n", u2Identifier);
}
}
#endif
/* check if WiFi is halt */
if (prGlueInfo->ulFlag & GLUE_FLAG_HALT) {
DBGLOG(INIT, INFO, "GLUE_FLAG_HALT skip tx\n");
dev_kfree_skb(prSkb);
return NETDEV_TX_OK;
}
#if CFG_SUPPORT_HOTSPOT_2_0
if (prGlueInfo->fgIsDad) {
/* kalPrint("[Passpoint R2] Due to ipv4_dad...TX is forbidden\n"); */
dev_kfree_skb(prSkb);
return NETDEV_TX_OK;
}
if (prGlueInfo->fgIs6Dad) {
/* kalPrint("[Passpoint R2] Due to ipv6_dad...TX is forbidden\n"); */
dev_kfree_skb(prSkb);
return NETDEV_TX_OK;
}
#endif
STATS_TX_TIME_ARRIVE(prSkb);
prQueueEntry = (P_QUE_ENTRY_T) GLUE_GET_PKT_QUEUE_ENTRY(prSkb);
prTxQueue = &prGlueInfo->rTxQueue;
#if CFG_BOW_TEST
DBGLOG(BOW, TRACE, "sk_buff->len: %d\n", prSkb->len);
DBGLOG(BOW, TRACE, "sk_buff->data_len: %d\n", prSkb->data_len);
DBGLOG(BOW, TRACE, "sk_buff->data:\n");
for (i = 0; i < prSkb->len; i++) {
DBGLOG(BOW, TRACE, "%4x", prSkb->data[i]);
if ((i + 1) % 16 == 0)
DBGLOG(BOW, TRACE, "\n");
}
DBGLOG(BOW, TRACE, "\n");
#endif
if (wlanProcessSecurityFrame(prGlueInfo->prAdapter, (P_NATIVE_PACKET) prSkb) == FALSE) {
/* non-1x packets */
#if CFG_DBG_GPIO_PINS
{
/* TX request from OS */
mtk_wcn_stp_debug_gpio_assert(IDX_TX_REQ, DBG_TIE_LOW);
kalUdelay(1);
mtk_wcn_stp_debug_gpio_assert(IDX_TX_REQ, DBG_TIE_HIGH);
}
#endif
u2QueueIdx = skb_get_queue_mapping(prSkb);
ASSERT(u2QueueIdx < CFG_MAX_TXQ_NUM);
#if CFG_ENABLE_PKT_LIFETIME_PROFILE
GLUE_SET_PKT_ARRIVAL_TIME(prSkb, kalGetTimeTick());
#endif
GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingFrameNum);
if (u2QueueIdx < CFG_MAX_TXQ_NUM)
GLUE_INC_REF_CNT(prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx]);
GLUE_ACQUIRE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_TX_QUE);
QUEUE_INSERT_TAIL(prTxQueue, prQueueEntry);
GLUE_RELEASE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_TX_QUE);
/* GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingFrameNum); */
/* GLUE_INC_REF_CNT(prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx]); */
if (u2QueueIdx < CFG_MAX_TXQ_NUM) {
if (prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx] >=
CFG_TX_STOP_NETIF_PER_QUEUE_THRESHOLD) {
netif_stop_subqueue(prDev, u2QueueIdx);
#if (CONF_HIF_LOOPBACK_AUTO == 1)
prGlueInfo->rHifInfo.HifLoopbkFlg |= 0x01;
#endif /* CONF_HIF_LOOPBACK_AUTO */
}
}
} else {
/* printk("is security frame\n"); */
GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingSecurityFrameNum);
}
DBGLOG(TX, EVENT, "\n+++++ pending frame %d len = %d +++++\n", prGlueInfo->i4TxPendingFrameNum, prSkb->len);
prGlueInfo->rNetDevStats.tx_bytes += prSkb->len;
prGlueInfo->rNetDevStats.tx_packets++;
if (netif_carrier_ok(prDev))
kalPerMonStart(prGlueInfo);
/* set GLUE_FLAG_TXREQ_BIT */
/* pr->u4Flag |= GLUE_FLAG_TXREQ; */
/* wake_up_interruptible(&prGlueInfo->waitq); */
kalSetEvent(prGlueInfo);
/* For Linux, we'll always return OK FLAG, because we'll free this skb by ourself */
return NETDEV_TX_OK;
} /* end of wlanHardStartXmit() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A method of struct net_device, to get the network interface statistical
* information.
*
* Whenever an application needs to get statistics for the interface, this method
* is called. This happens, for example, when ifconfig or netstat -i is run.
*
* \param[in] prDev Pointer to struct net_device.
*
* \return net_device_stats buffer pointer.
*/
/*----------------------------------------------------------------------------*/
struct net_device_stats *wlanGetStats(IN struct net_device *prDev)
{
P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
#if 0
WLAN_STATUS rStatus;
UINT_32 u4XmitError = 0;
UINT_32 u4XmitOk = 0;
UINT_32 u4RecvError = 0;
UINT_32 u4RecvOk = 0;
UINT_32 u4BufLen;
ASSERT(prDev);
/* @FIX ME: need a more clear way to do this */
rStatus = kalIoctl(prGlueInfo,
wlanoidQueryXmitError, &u4XmitError, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen);
rStatus = kalIoctl(prGlueInfo, wlanoidQueryXmitOk, &u4XmitOk, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen);
rStatus = kalIoctl(prGlueInfo, wlanoidQueryRcvOk, &u4RecvOk, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen);
rStatus = kalIoctl(prGlueInfo,
wlanoidQueryRcvError, &u4RecvError, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen);
prGlueInfo->rNetDevStats.rx_packets = u4RecvOk;
prGlueInfo->rNetDevStats.tx_packets = u4XmitOk;
prGlueInfo->rNetDevStats.tx_errors = u4XmitError;
prGlueInfo->rNetDevStats.rx_errors = u4RecvError;
/* prGlueInfo->rNetDevStats.rx_bytes = rCustomNetDevStats.u4RxBytes; */
/* prGlueInfo->rNetDevStats.tx_bytes = rCustomNetDevStats.u4TxBytes; */
/* prGlueInfo->rNetDevStats.rx_errors = rCustomNetDevStats.u4RxErrors; */
/* prGlueInfo->rNetDevStats.multicast = rCustomNetDevStats.u4Multicast; */
#endif
/* prGlueInfo->rNetDevStats.rx_packets = 0; */
/* prGlueInfo->rNetDevStats.tx_packets = 0; */
prGlueInfo->rNetDevStats.tx_errors = 0;
prGlueInfo->rNetDevStats.rx_errors = 0;
/* prGlueInfo->rNetDevStats.rx_bytes = 0; */
/* prGlueInfo->rNetDevStats.tx_bytes = 0; */
prGlueInfo->rNetDevStats.rx_errors = 0;
prGlueInfo->rNetDevStats.multicast = 0;
return &prGlueInfo->rNetDevStats;
} /* end of wlanGetStats() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A function for prDev->init
*
* \param[in] prDev Pointer to struct net_device.
*
* \retval 0 The execution of wlanInit succeeds.
* \retval -ENXIO No such device.
*/
/*----------------------------------------------------------------------------*/
static int wlanInit(struct net_device *prDev)
{
P_GLUE_INFO_T prGlueInfo = NULL;
if (fgIsWorkMcEverInit == FALSE) {
if (!prDev)
return -ENXIO;
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
INIT_DELAYED_WORK(&workq, wlanSetMulticastListWorkQueue);
/* 20150205 work queue for sched_scan */
INIT_DELAYED_WORK(&sched_workq, wlanSchedScanStoppedWorkQueue);
fgIsWorkMcEverInit = TRUE;
}
return 0; /* success */
} /* end of wlanInit() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A function for prDev->uninit
*
* \param[in] prDev Pointer to struct net_device.
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static void wlanUninit(struct net_device *prDev)
{
} /* end of wlanUninit() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A function for prDev->open
*
* \param[in] prDev Pointer to struct net_device.
*
* \retval 0 The execution of wlanOpen succeeds.
* \retval < 0 The execution of wlanOpen failed.
*/
/*----------------------------------------------------------------------------*/
static int wlanOpen(struct net_device *prDev)
{
ASSERT(prDev);
netif_tx_start_all_queues(prDev);
return 0; /* success */
} /* end of wlanOpen() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A function for prDev->stop
*
* \param[in] prDev Pointer to struct net_device.
*
* \retval 0 The execution of wlanStop succeeds.
* \retval < 0 The execution of wlanStop failed.
*/
/*----------------------------------------------------------------------------*/
static int wlanStop(struct net_device *prDev)
{
P_GLUE_INFO_T prGlueInfo = NULL;
struct cfg80211_scan_request *prScanRequest = NULL;
GLUE_SPIN_LOCK_DECLARATION();
ASSERT(prDev);
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
/* CFG80211 down */
GLUE_ACQUIRE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_NET_DEV);
if (prGlueInfo->prScanRequest != NULL) {
prScanRequest = prGlueInfo->prScanRequest;
prGlueInfo->prScanRequest = NULL;
}
GLUE_RELEASE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_NET_DEV);
if (prScanRequest)
cfg80211_scan_done(prScanRequest, TRUE);
netif_tx_stop_all_queues(prDev);
return 0; /* success */
} /* end of wlanStop() */
/*----------------------------------------------------------------------------*/
/*!
* \brief Update Channel table for cfg80211 for Wi-Fi Direct based on current country code
*
* \param[in] prGlueInfo Pointer to glue info
*
* \return none
*/
/*----------------------------------------------------------------------------*/
VOID wlanUpdateChannelTable(P_GLUE_INFO_T prGlueInfo)
{
UINT_8 i, j;
UINT_8 ucNumOfChannel;
RF_CHANNEL_INFO_T aucChannelList[ARRAY_SIZE(mtk_2ghz_channels) + ARRAY_SIZE(mtk_5ghz_channels)];
/* 1. Disable all channel */
for (i = 0; i < ARRAY_SIZE(mtk_2ghz_channels); i++) {
mtk_2ghz_channels[i].flags |= IEEE80211_CHAN_DISABLED;
mtk_2ghz_channels[i].orig_flags |= IEEE80211_CHAN_DISABLED;
}
for (i = 0; i < ARRAY_SIZE(mtk_5ghz_channels); i++) {
mtk_5ghz_channels[i].flags |= IEEE80211_CHAN_DISABLED;
mtk_5ghz_channels[i].orig_flags |= IEEE80211_CHAN_DISABLED;
}
/* 2. Get current domain channel list */
rlmDomainGetChnlList(prGlueInfo->prAdapter,
BAND_NULL,
ARRAY_SIZE(mtk_2ghz_channels) + ARRAY_SIZE(mtk_5ghz_channels),
&ucNumOfChannel, aucChannelList);
/* 3. Enable specific channel based on domain channel list */
for (i = 0; i < ucNumOfChannel; i++) {
switch (aucChannelList[i].eBand) {
case BAND_2G4:
for (j = 0; j < ARRAY_SIZE(mtk_2ghz_channels); j++) {
if (mtk_2ghz_channels[j].hw_value == aucChannelList[i].ucChannelNum) {
mtk_2ghz_channels[j].flags &= ~IEEE80211_CHAN_DISABLED;
mtk_2ghz_channels[j].orig_flags &= ~IEEE80211_CHAN_DISABLED;
break;
}
}
break;
case BAND_5G:
for (j = 0; j < ARRAY_SIZE(mtk_5ghz_channels); j++) {
if (mtk_5ghz_channels[j].hw_value == aucChannelList[i].ucChannelNum) {
mtk_5ghz_channels[j].flags &= ~IEEE80211_CHAN_DISABLED;
mtk_5ghz_channels[j].orig_flags &= ~IEEE80211_CHAN_DISABLED;
break;
}
}
break;
default:
break;
}
}
}
/*----------------------------------------------------------------------------*/
/*!
* \brief Register the device to the kernel and return the index.
*
* \param[in] prDev Pointer to struct net_device.
*
* \retval 0 The execution of wlanNetRegister succeeds.
* \retval < 0 The execution of wlanNetRegister failed.
*/
/*----------------------------------------------------------------------------*/
static INT_32 wlanNetRegister(struct wireless_dev *prWdev)
{
P_GLUE_INFO_T prGlueInfo;
INT_32 i4DevIdx = -1;
ASSERT(prWdev);
do {
if (!prWdev)
break;
prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy);
i4DevIdx = wlanGetDevIdx(prWdev->netdev);
if (i4DevIdx < 0) {
DBGLOG(INIT, ERROR, "wlanNetRegister: net_device number exceeds.\n");
break;
}
/* adjust channel support status */
wlanUpdateChannelTable(prGlueInfo);
#if !CFG_SUPPORT_PERSIST_NETDEV
if (register_netdev(prWdev->netdev) < 0) {
DBGLOG(INIT, ERROR, "wlanNetRegister: net_device context is not registered.\n");
wiphy_unregister(prWdev->wiphy);
wlanClearDevIdx(prWdev->netdev);
i4DevIdx = -1;
}
#endif
if (i4DevIdx != -1)
prGlueInfo->fgIsRegistered = TRUE;
} while (FALSE);
return i4DevIdx; /* success */
} /* end of wlanNetRegister() */
/*----------------------------------------------------------------------------*/
/*!
* \brief Unregister the device from the kernel
*
* \param[in] prWdev Pointer to struct net_device.
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static VOID wlanNetUnregister(struct wireless_dev *prWdev)
{
P_GLUE_INFO_T prGlueInfo;
if (!prWdev) {
DBGLOG(INIT, ERROR, "wlanNetUnregister: The device context is NULL\n");
return;
}
DBGLOG(INIT, TRACE, "unregister net_dev(0x%p)\n", prWdev->netdev);
prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy);
wlanClearDevIdx(prWdev->netdev);
#if !CFG_SUPPORT_PERSIST_NETDEV
unregister_netdev(prWdev->netdev);
#endif
prGlueInfo->fgIsRegistered = FALSE;
DBGLOG(INIT, INFO, "unregister wireless_dev(0x%p), ifindex=%d\n", prWdev, prWdev->netdev->ifindex);
} /* end of wlanNetUnregister() */
static const struct net_device_ops wlan_netdev_ops = {
.ndo_open = wlanOpen,
.ndo_stop = wlanStop,
.ndo_set_rx_mode = wlanSetMulticastList,
.ndo_get_stats = wlanGetStats,
.ndo_do_ioctl = wlanDoIOCTL,
.ndo_start_xmit = wlanHardStartXmit,
.ndo_init = wlanInit,
.ndo_uninit = wlanUninit,
.ndo_select_queue = wlanSelectQueue,
};
/*----------------------------------------------------------------------------*/
/*!
* \brief A method for creating Linux NET4 struct net_device object and the
* private data(prGlueInfo and prAdapter). Setup the IO address to the HIF.
* Assign the function pointer to the net_device object
*
* \param[in] pvData Memory address for the device
*
* \retval Not null The wireless_dev object.
* \retval NULL Fail to create wireless_dev object
*/
/*----------------------------------------------------------------------------*/
static struct lock_class_key rSpinKey[SPIN_LOCK_NUM];
static struct wireless_dev *wlanNetCreate(PVOID pvData)
{
P_GLUE_INFO_T prGlueInfo = NULL;
struct wireless_dev *prWdev = gprWdev;
UINT_32 i;
struct device *prDev;
if (!prWdev) {
DBGLOG(INIT, ERROR, "Allocating memory to wireless_dev context failed\n");
return NULL;
}
/* 4 <1> co-relate wiphy & prDev */
#if MTK_WCN_HIF_SDIO
mtk_wcn_hif_sdio_get_dev(*((MTK_WCN_HIF_SDIO_CLTCTX *) pvData), &prDev);
#else
/* prDev = &((struct sdio_func *) pvData)->dev; //samp */
prDev = pvData; /* samp */
#endif
if (!prDev)
DBGLOG(INIT, WARN, "unable to get struct dev for wlan\n");
/* don't set prDev as parent of wiphy->dev, because we have done device_add
in driver init. if we set parent here, parent will be not able to know this child,
and may occurs a KE in device_shutdown, to free wiphy->dev, because his parent
has been freed. */
/*set_wiphy_dev(prWdev->wiphy, prDev);*/
#if !CFG_SUPPORT_PERSIST_NETDEV
/* 4 <3> Initial Glue structure */
prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy);
kalMemZero(prGlueInfo, sizeof(GLUE_INFO_T));
/* 4 <3.1> Create net device */
#if CFG_TC1_FEATURE
if (wlan_if_changed) {
prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME_IN_AP_MODE,
NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM);
} else {
prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE,
ether_setup, CFG_MAX_TXQ_NUM);
}
#else
prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE,
ether_setup, CFG_MAX_TXQ_NUM);
#endif
if (!prGlueInfo->prDevHandler) {
DBGLOG(INIT, ERROR, "Allocating memory to net_device context failed\n");
return NULL;
}
DBGLOG(INIT, INFO, "net_device prDev(0x%p) allocated ifindex=%d\n",
prGlueInfo->prDevHandler, prGlueInfo->prDevHandler->ifindex);
/* 4 <3.1.1> initialize net device varaiables */
*((P_GLUE_INFO_T *) netdev_priv(prGlueInfo->prDevHandler)) = prGlueInfo;
prGlueInfo->prDevHandler->netdev_ops = &wlan_netdev_ops;
#ifdef CONFIG_WIRELESS_EXT
prGlueInfo->prDevHandler->wireless_handlers = &wext_handler_def;
#endif
netif_carrier_off(prGlueInfo->prDevHandler);
netif_tx_stop_all_queues(prGlueInfo->prDevHandler);
/* 4 <3.1.2> co-relate with wiphy bi-directionally */
prGlueInfo->prDevHandler->ieee80211_ptr = prWdev;
#if CFG_TCP_IP_CHKSUM_OFFLOAD
prGlueInfo->prDevHandler->features = NETIF_F_HW_CSUM;
#endif
prWdev->netdev = prGlueInfo->prDevHandler;
/* 4 <3.1.3> co-relate net device & prDev */
/*SET_NETDEV_DEV(prGlueInfo->prDevHandler, wiphy_dev(prWdev->wiphy));*/
SET_NETDEV_DEV(prGlueInfo->prDevHandler, prDev);
#else /* CFG_SUPPORT_PERSIST_NETDEV */
prGlueInfo->prDevHandler = gprWdev->netdev;
#endif /* CFG_SUPPORT_PERSIST_NETDEV */
/* 4 <3.2> initiali glue variables */
prGlueInfo->eParamMediaStateIndicated = PARAM_MEDIA_STATE_DISCONNECTED;
prGlueInfo->ePowerState = ParamDeviceStateD0;
prGlueInfo->fgIsMacAddrOverride = FALSE;
prGlueInfo->fgIsRegistered = FALSE;
prGlueInfo->prScanRequest = NULL;
#if CFG_SUPPORT_HOTSPOT_2_0
/* Init DAD */
prGlueInfo->fgIsDad = FALSE;
prGlueInfo->fgIs6Dad = FALSE;
kalMemZero(prGlueInfo->aucDADipv4, 4);
kalMemZero(prGlueInfo->aucDADipv6, 16);
#endif
init_completion(&prGlueInfo->rScanComp);
init_completion(&prGlueInfo->rHaltComp);
init_completion(&prGlueInfo->rPendComp);
#if CFG_ENABLE_WIFI_DIRECT
init_completion(&prGlueInfo->rSubModComp);
#endif
/* initialize timer for OID timeout checker */
kalOsTimerInitialize(prGlueInfo, kalTimeoutHandler);
for (i = 0; i < SPIN_LOCK_NUM; i++) {
spin_lock_init(&prGlueInfo->rSpinLock[i]);
lockdep_set_class(&prGlueInfo->rSpinLock[i], &rSpinKey[i]);
}
/* initialize semaphore for ioctl */
sema_init(&prGlueInfo->ioctl_sem, 1);
glSetHifInfo(prGlueInfo, (ULONG) pvData);
/* 4 <8> Init Queues */
init_waitqueue_head(&prGlueInfo->waitq);
QUEUE_INITIALIZE(&prGlueInfo->rCmdQueue);
QUEUE_INITIALIZE(&prGlueInfo->rTxQueue);
/* 4 <4> Create Adapter structure */
prGlueInfo->prAdapter = (P_ADAPTER_T) wlanAdapterCreate(prGlueInfo);
if (!prGlueInfo->prAdapter) {
DBGLOG(INIT, ERROR, "Allocating memory to adapter failed\n");
return NULL;
}
KAL_WAKE_LOCK_INIT(prAdapter, &prGlueInfo->rAhbIsrWakeLock, "WLAN AHB ISR");
#if CFG_SUPPORT_PERSIST_NETDEV
dev_open(prGlueInfo->prDevHandler);
netif_carrier_off(prGlueInfo->prDevHandler);
netif_tx_stop_all_queues(prGlueInfo->prDevHandler);
#endif
return prWdev;
} /* end of wlanNetCreate() */
/*----------------------------------------------------------------------------*/
/*!
* \brief Destroying the struct net_device object and the private data.
*
* \param[in] prWdev Pointer to struct wireless_dev.
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static VOID wlanNetDestroy(struct wireless_dev *prWdev)
{
P_GLUE_INFO_T prGlueInfo = NULL;
ASSERT(prWdev);
if (!prWdev) {
DBGLOG(INIT, ERROR, "wlanNetDestroy: The device context is NULL\n");
return;
}
/* prGlueInfo is allocated with net_device */
prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy);
ASSERT(prGlueInfo);
/* destroy kal OS timer */
kalCancelTimer(prGlueInfo);
glClearHifInfo(prGlueInfo);
wlanAdapterDestroy(prGlueInfo->prAdapter);
prGlueInfo->prAdapter = NULL;
#if CFG_SUPPORT_PERSIST_NETDEV
/* take the net_device to down state */
dev_close(prGlueInfo->prDevHandler);
#else
/* Free net_device and private data prGlueInfo, which are allocated by alloc_netdev(). */
free_netdev(prWdev->netdev);
#endif
} /* end of wlanNetDestroy() */
#ifndef CONFIG_X86
UINT_8 g_aucBufIpAddr[32] = { 0 };
static void wlanNotifyFwSuspend(P_GLUE_INFO_T prGlueInfo, BOOLEAN fgSuspend)
{
WLAN_STATUS rStatus = WLAN_STATUS_FAILURE;
UINT_32 u4SetInfoLen;
rStatus = kalIoctl(prGlueInfo,
wlanoidNotifyFwSuspend,
(PVOID)&fgSuspend,
sizeof(fgSuspend),
FALSE,
FALSE,
TRUE,
FALSE,
&u4SetInfoLen);
if (rStatus != WLAN_STATUS_SUCCESS)
DBGLOG(INIT, INFO, "wlanNotifyFwSuspend fail\n");
}
void wlanHandleSystemSuspend(void)
{
WLAN_STATUS rStatus = WLAN_STATUS_FAILURE;
struct net_device *prDev = NULL;
P_GLUE_INFO_T prGlueInfo = NULL;
UINT_8 ip[4] = { 0 };
UINT_32 u4NumIPv4 = 0;
#ifdef CONFIG_IPV6
UINT_8 ip6[16] = { 0 }; /* FIX ME: avoid to allocate large memory in stack */
UINT_32 u4NumIPv6 = 0;
#endif
UINT_32 i;
P_PARAM_NETWORK_ADDRESS_IP prParamIpAddr;
#if CFG_SUPPORT_DROP_MC_PACKET
UINT_32 u4PacketFilter = 0;
UINT_32 u4SetInfoLen = 0;
#endif
/* <1> Sanity check and acquire the net_device */
ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES);
if (u4WlanDevNum == 0) {
DBGLOG(INIT, ERROR, "wlanEarlySuspend u4WlanDevNum==0 invalid!!\n");
return;
}
prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev;
fgIsUnderSuspend = true;
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
ASSERT(prGlueInfo);
#if CFG_SUPPORT_DROP_MC_PACKET
/* new filter should not include p2p mask */
#if CFG_ENABLE_WIFI_DIRECT_CFG_80211
u4PacketFilter = prGlueInfo->prAdapter->u4OsPacketFilter & (~PARAM_PACKET_FILTER_P2P_MASK);
#endif
if (kalIoctl(prGlueInfo,
wlanoidSetCurrentPacketFilter,
&u4PacketFilter,
sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) {
DBGLOG(INIT, ERROR, "set packet filter failed.\n");
}
#endif
if (!prDev || !(prDev->ip_ptr) ||
!((struct in_device *)(prDev->ip_ptr))->ifa_list ||
!(&(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local))) {
goto notify_suspend;
}
kalMemCopy(ip, &(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local), sizeof(ip));
/* todo: traverse between list to find whole sets of IPv4 addresses */
if (!((ip[0] == 0) && (ip[1] == 0) && (ip[2] == 0) && (ip[3] == 0)))
u4NumIPv4++;
#ifdef CONFIG_IPV6
if (!prDev || !(prDev->ip6_ptr) ||
!((struct in_device *)(prDev->ip6_ptr))->ifa_list ||
!(&(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local))) {
goto notify_suspend;
}
kalMemCopy(ip6, &(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local), sizeof(ip6));
DBGLOG(INIT, INFO, "ipv6 is %d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d\n",
ip6[0], ip6[1], ip6[2], ip6[3],
ip6[4], ip6[5], ip6[6], ip6[7],
ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15]
);
/* todo: traverse between list to find whole sets of IPv6 addresses */
if (!((ip6[0] == 0) && (ip6[1] == 0) && (ip6[2] == 0) && (ip6[3] == 0) && (ip6[4] == 0) && (ip6[5] == 0))) {
/* Do nothing */
/* u4NumIPv6++; */
}
#endif
/* <7> set up the ARP filter */
{
UINT_32 u4SetInfoLen = 0;
UINT_32 u4Len = OFFSET_OF(PARAM_NETWORK_ADDRESS_LIST, arAddress);
P_PARAM_NETWORK_ADDRESS_LIST prParamNetAddrList = (P_PARAM_NETWORK_ADDRESS_LIST) g_aucBufIpAddr;
P_PARAM_NETWORK_ADDRESS prParamNetAddr = prParamNetAddrList->arAddress;
kalMemZero(g_aucBufIpAddr, sizeof(g_aucBufIpAddr));
prParamNetAddrList->u4AddressCount = u4NumIPv4 + u4NumIPv6;
prParamNetAddrList->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP;
for (i = 0; i < u4NumIPv4; i++) {
prParamNetAddr->u2AddressLength = sizeof(PARAM_NETWORK_ADDRESS_IP); /* 4;; */
prParamNetAddr->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP;
prParamIpAddr = (P_PARAM_NETWORK_ADDRESS_IP) prParamNetAddr->aucAddress;
kalMemCopy(&prParamIpAddr->in_addr, ip, sizeof(ip));
prParamNetAddr =
(P_PARAM_NETWORK_ADDRESS) ((ULONG) prParamNetAddr + sizeof(PARAM_NETWORK_ADDRESS));
u4Len += OFFSET_OF(PARAM_NETWORK_ADDRESS, aucAddress) + sizeof(PARAM_NETWORK_ADDRESS);
}
#ifdef CONFIG_IPV6
for (i = 0; i < u4NumIPv6; i++) {
prParamNetAddr->u2AddressLength = 6;
prParamNetAddr->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP;
kalMemCopy(prParamNetAddr->aucAddress, ip6, sizeof(ip6));
prParamNetAddr = (P_PARAM_NETWORK_ADDRESS) ((ULONG) prParamNetAddr + sizeof(ip6));
u4Len += OFFSET_OF(PARAM_NETWORK_ADDRESS, aucAddress) + sizeof(ip6);
}
#endif
ASSERT(u4Len <= sizeof(g_aucBufIpAddr));
rStatus = kalIoctl(prGlueInfo,
wlanoidSetNetworkAddress,
(PVOID) prParamNetAddrList, u4Len, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen);
}
notify_suspend:
DBGLOG(INIT, INFO, "IP: %d.%d.%d.%d, rStatus: %u\n", ip[0], ip[1], ip[2], ip[3], rStatus);
if (rStatus != WLAN_STATUS_SUCCESS)
wlanNotifyFwSuspend(prGlueInfo, TRUE);
}
void wlanHandleSystemResume(void)
{
struct net_device *prDev = NULL;
P_GLUE_INFO_T prGlueInfo = NULL;
WLAN_STATUS rStatus = WLAN_STATUS_FAILURE;
UINT_8 ip[4] = { 0 };
#ifdef CONFIG_IPV6
UINT_8 ip6[16] = { 0 }; /* FIX ME: avoid to allocate large memory in stack */
#endif
EVENT_AIS_BSS_INFO_T rParam;
UINT_32 u4BufLen = 0;
#if CFG_SUPPORT_DROP_MC_PACKET
UINT_32 u4PacketFilter = 0;
UINT_32 u4SetInfoLen = 0;
#endif
/* <1> Sanity check and acquire the net_device */
ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES);
if (u4WlanDevNum == 0) {
DBGLOG(INIT, ERROR, "wlanLateResume u4WlanDevNum==0 invalid!!\n");
return;
}
prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev;
/* ASSERT(prDev); */
fgIsUnderSuspend = false;
if (!prDev) {
DBGLOG(INIT, INFO, "prDev == NULL!!!\n");
return;
}
/* <3> acquire the prGlueInfo */
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
ASSERT(prGlueInfo);
#if CFG_SUPPORT_DROP_MC_PACKET
/* new filter should not include p2p mask */
#if CFG_ENABLE_WIFI_DIRECT_CFG_80211
u4PacketFilter = prGlueInfo->prAdapter->u4OsPacketFilter & (~PARAM_PACKET_FILTER_P2P_MASK);
#endif
if (kalIoctl(prGlueInfo,
wlanoidSetCurrentPacketFilter,
&u4PacketFilter,
sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) {
DBGLOG(INIT, ERROR, "set packet filter failed.\n");
}
#endif
/*
We will receive the event in rx, we will check if the status is the same in driver
and FW, if not the same, trigger disconnetion procedure.
*/
kalMemZero(&rParam, sizeof(EVENT_AIS_BSS_INFO_T));
rStatus = kalIoctl(prGlueInfo,
wlanoidQueryBSSInfo,
&rParam, sizeof(EVENT_AIS_BSS_INFO_T), TRUE, TRUE, TRUE, FALSE, &u4BufLen);
if (rStatus != WLAN_STATUS_SUCCESS) {
DBGLOG(INIT, ERROR, "Query BSSinfo fail 0x%x!!\n", rStatus);
}
/* <2> get the IPv4 address */
if (!(prDev->ip_ptr) ||
!((struct in_device *)(prDev->ip_ptr))->ifa_list ||
!(&(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local))) {
goto notify_resume;
}
/* <4> copy the IPv4 address */
kalMemCopy(ip, &(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local), sizeof(ip));
#ifdef CONFIG_IPV6
/* <5> get the IPv6 address */
if (!prDev || !(prDev->ip6_ptr) ||
!((struct in_device *)(prDev->ip6_ptr))->ifa_list ||
!(&(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local))) {
goto notify_resume;
}
/* <6> copy the IPv6 address */
kalMemCopy(ip6, &(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local), sizeof(ip6));
DBGLOG(INIT, INFO, "ipv6 is %d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d\n",
ip6[0], ip6[1], ip6[2], ip6[3],
ip6[4], ip6[5], ip6[6], ip6[7],
ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15]
);
#endif
/* <7> clear the ARP filter */
{
UINT_32 u4SetInfoLen = 0;
/* UINT_8 aucBuf[32] = {0}; */
UINT_32 u4Len = sizeof(PARAM_NETWORK_ADDRESS_LIST);
P_PARAM_NETWORK_ADDRESS_LIST prParamNetAddrList = (P_PARAM_NETWORK_ADDRESS_LIST) g_aucBufIpAddr;
/* aucBuf; */
kalMemZero(g_aucBufIpAddr, sizeof(g_aucBufIpAddr));
prParamNetAddrList->u4AddressCount = 0;
prParamNetAddrList->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP;
ASSERT(u4Len <= sizeof(g_aucBufIpAddr /*aucBuf */));
rStatus = kalIoctl(prGlueInfo,
wlanoidSetNetworkAddress,
(PVOID) prParamNetAddrList, u4Len, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen);
}
notify_resume:
DBGLOG(INIT, INFO, "Query BSS result: %d %d %d, IP: %d.%d.%d.%d, rStatus: %u\n",
rParam.eConnectionState, rParam.eCurrentOPMode, rParam.fgIsNetActive,
ip[0], ip[1], ip[2], ip[3], rStatus);
if (rStatus != WLAN_STATUS_SUCCESS) {
wlanNotifyFwSuspend(prGlueInfo, FALSE);
}
}
#endif /* ! CONFIG_X86 */
int set_p2p_mode_handler(struct net_device *netdev, PARAM_CUSTOM_P2P_SET_STRUCT_T p2pmode)
{
#if 0
P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(netdev));
PARAM_CUSTOM_P2P_SET_STRUCT_T rSetP2P;
WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS;
UINT_32 u4BufLen = 0;
rSetP2P.u4Enable = p2pmode.u4Enable;
rSetP2P.u4Mode = p2pmode.u4Mode;
if (!rSetP2P.u4Enable)
p2pNetUnregister(prGlueInfo, TRUE);
rWlanStatus = kalIoctl(prGlueInfo,
wlanoidSetP2pMode,
(PVOID) &rSetP2P,
sizeof(PARAM_CUSTOM_P2P_SET_STRUCT_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen);
DBGLOG(INIT, INFO, "ret = %d\n", rWlanStatus);
if (rSetP2P.u4Enable)
p2pNetRegister(prGlueInfo, TRUE);
return 0;
#else
P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(netdev));
PARAM_CUSTOM_P2P_SET_STRUCT_T rSetP2P;
WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS;
BOOLEAN fgIsP2PEnding;
UINT_32 u4BufLen = 0;
GLUE_SPIN_LOCK_DECLARATION();
DBGLOG(INIT, INFO, "%u %u\n", (UINT_32) p2pmode.u4Enable, (UINT_32) p2pmode.u4Mode);
/* avoid remove & p2p off command simultaneously */
GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock);
fgIsP2PEnding = g_u4P2PEnding;
g_u4P2POnOffing = 1;
GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock);
if (fgIsP2PEnding == 1) {
/* skip the command if we are removing */
GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock);
g_u4P2POnOffing = 0;
GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock);
return 0;
}
rSetP2P.u4Enable = p2pmode.u4Enable;
rSetP2P.u4Mode = p2pmode.u4Mode;
#if !CFG_SUPPORT_PERSIST_NETDEV
if ((!rSetP2P.u4Enable) && (fgIsResetting == FALSE))
p2pNetUnregister(prGlueInfo, TRUE);
#endif
/* move out to caller to avoid kalIoctrl & suspend/resume deadlock problem ALPS00844864 */
/*
Scenario:
1. System enters suspend/resume but not yet enter wlanearlysuspend()
or wlanlateresume();
2. System switches to do PRIV_CMD_P2P_MODE and execute kalIoctl()
and get g_halt_sem then do glRegisterEarlySuspend() or
glUnregisterEarlySuspend();
But system suspend/resume procedure is not yet finished so we
suspend;
3. System switches back to do suspend/resume procedure and execute
kalIoctl(). But driver does not yet release g_halt_sem so system
suspend in wlanearlysuspend() or wlanlateresume();
==> deadlock occurs.
*/
rWlanStatus = kalIoctl(prGlueInfo, wlanoidSetP2pMode, (PVOID) &rSetP2P,/* pu4IntBuf[0]is used as input SubCmd */
sizeof(PARAM_CUSTOM_P2P_SET_STRUCT_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen);
#if !CFG_SUPPORT_PERSIST_NETDEV
/* Need to check fgIsP2PRegistered, in case of whole chip reset.
* in this case, kalIOCTL return success always,
* and prGlueInfo->prP2pInfo may be NULL */
if ((rSetP2P.u4Enable) && (prGlueInfo->prAdapter->fgIsP2PRegistered) && (fgIsResetting == FALSE))
p2pNetRegister(prGlueInfo, TRUE);
#endif
GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock);
g_u4P2POnOffing = 0;
GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock);
return 0;
#endif
}
static void set_dbg_level_handler(unsigned char dbg_lvl[DBG_MODULE_NUM])
{
kalMemCopy(aucDebugModule, dbg_lvl, sizeof(aucDebugModule));
kalPrint("[wlan] change debug level");
}
/*----------------------------------------------------------------------------*/
/*!
* \brief Wlan probe function. This function probes and initializes the device.
*
* \param[in] pvData data passed by bus driver init function
* _HIF_EHPI: NULL
* _HIF_SDIO: sdio bus driver handle
*
* \retval 0 Success
* \retval negative value Failed
*/
/*----------------------------------------------------------------------------*/
static INT_32 wlanProbe(PVOID pvData)
{
struct wireless_dev *prWdev = NULL;
enum probe_fail_reason {
BUS_INIT_FAIL,
NET_CREATE_FAIL,
BUS_SET_IRQ_FAIL,
ADAPTER_START_FAIL,
NET_REGISTER_FAIL,
PROC_INIT_FAIL,
FAIL_REASON_NUM
} eFailReason;
P_WLANDEV_INFO_T prWlandevInfo = NULL;
INT_32 i4DevIdx = 0;
P_GLUE_INFO_T prGlueInfo = NULL;
P_ADAPTER_T prAdapter = NULL;
INT_32 i4Status = 0;
BOOLEAN bRet = FALSE;
eFailReason = FAIL_REASON_NUM;
do {
/* 4 <1> Initialize the IO port of the interface */
/* GeorgeKuo: pData has different meaning for _HIF_XXX:
* _HIF_EHPI: pointer to memory base variable, which will be
* initialized by glBusInit().
* _HIF_SDIO: bus driver handle
*/
bRet = glBusInit(pvData);
wlanDebugInit();
/* Cannot get IO address from interface */
if (FALSE == bRet) {
DBGLOG(INIT, ERROR, KERN_ALERT "wlanProbe: glBusInit() fail\n");
i4Status = -EIO;
eFailReason = BUS_INIT_FAIL;
break;
}
/* 4 <2> Create network device, Adapter, KalInfo, prDevHandler(netdev) */
prWdev = wlanNetCreate(pvData);
if (prWdev == NULL) {
DBGLOG(INIT, ERROR, "wlanProbe: No memory for dev and its private\n");
i4Status = -ENOMEM;
eFailReason = NET_CREATE_FAIL;
break;
}
/* 4 <2.5> Set the ioaddr to HIF Info */
prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy);
gPrDev = prGlueInfo->prDevHandler;
/* 4 <4> Setup IRQ */
prWlandevInfo = &arWlanDevInfo[i4DevIdx];
i4Status = glBusSetIrq(prWdev->netdev, NULL, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev)));
if (i4Status != WLAN_STATUS_SUCCESS) {
DBGLOG(INIT, ERROR, "wlanProbe: Set IRQ error\n");
eFailReason = BUS_SET_IRQ_FAIL;
break;
}
prGlueInfo->i4DevIdx = i4DevIdx;
prAdapter = prGlueInfo->prAdapter;
prGlueInfo->u4ReadyFlag = 0;
#if CFG_TCP_IP_CHKSUM_OFFLOAD
prAdapter->u4CSUMFlags = (CSUM_OFFLOAD_EN_TX_TCP | CSUM_OFFLOAD_EN_TX_UDP | CSUM_OFFLOAD_EN_TX_IP);
#endif
#if CFG_SUPPORT_CFG_FILE
{
PUINT_8 pucConfigBuf;
UINT_32 u4ConfigReadLen;
wlanCfgInit(prAdapter, NULL, 0, 0);
pucConfigBuf = (PUINT_8) kalMemAlloc(WLAN_CFG_FILE_BUF_SIZE, VIR_MEM_TYPE);
u4ConfigReadLen = 0;
DBGLOG(INIT, LOUD, "CFG_FILE: Read File...\n");
if (pucConfigBuf) {
kalMemZero(pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE);
if (kalReadToFile("/data/misc/wifi.cfg",
pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) {
DBGLOG(INIT, LOUD, "CFG_FILE: Read /data/misc/wifi.cfg\n");
} else if (kalReadToFile("/data/misc/wifi/wifi.cfg",
pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) {
DBGLOG(INIT, LOUD, "CFG_FILE: Read /data/misc/wifi/wifi.cfg\n");
} else if (kalReadToFile("/etc/firmware/wifi.cfg",
pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) {
DBGLOG(INIT, LOUD, "CFG_FILE: Read /etc/firmware/wifi.cfg\n");
}
if (pucConfigBuf[0] != '\0' && u4ConfigReadLen > 0)
wlanCfgInit(prAdapter, pucConfigBuf, u4ConfigReadLen, 0);
kalMemFree(pucConfigBuf, VIR_MEM_TYPE, WLAN_CFG_FILE_BUF_SIZE);
} /* pucConfigBuf */
}
#endif
/* 4 <5> Start Device */
/* */
#if CFG_ENABLE_FW_DOWNLOAD
DBGLOG(INIT, TRACE, "start to download firmware...\n");
/* before start adapter, we need to open and load firmware */
{
UINT_32 u4FwSize = 0;
PVOID prFwBuffer = NULL;
P_REG_INFO_T prRegInfo = &prGlueInfo->rRegInfo;
/* P_REG_INFO_T prRegInfo = (P_REG_INFO_T) kmalloc(sizeof(REG_INFO_T), GFP_KERNEL); */
kalMemSet(prRegInfo, 0, sizeof(REG_INFO_T));
prRegInfo->u4StartAddress = CFG_FW_START_ADDRESS;
prRegInfo->u4LoadAddress = CFG_FW_LOAD_ADDRESS;
/* Load NVRAM content to REG_INFO_T */
glLoadNvram(prGlueInfo, prRegInfo);
#if CFG_SUPPORT_CFG_FILE
wlanCfgApply(prAdapter);
#endif
/* kalMemCopy(&prGlueInfo->rRegInfo, prRegInfo, sizeof(REG_INFO_T)); */
prRegInfo->u4PowerMode = CFG_INIT_POWER_SAVE_PROF;
prRegInfo->fgEnArpFilter = TRUE;
if (kalFirmwareImageMapping(prGlueInfo, &prFwBuffer, &u4FwSize) == NULL) {
i4Status = -EIO;
DBGLOG(INIT, ERROR, "kalFirmwareImageMapping fail!\n");
goto bailout;
} else {
if (wlanAdapterStart(prAdapter, prRegInfo, prFwBuffer,
u4FwSize) != WLAN_STATUS_SUCCESS) {
i4Status = -EIO;
}
}
kalFirmwareImageUnmapping(prGlueInfo, NULL, prFwBuffer);
bailout:
/* kfree(prRegInfo); */
DBGLOG(INIT, TRACE, "download firmware status = %d\n", i4Status);
if (i4Status < 0) {
GL_HIF_INFO_T *HifInfo;
UINT_32 u4FwCnt;
DBGLOG(INIT, WARN, "CONNSYS FW CPUINFO:\n");
HifInfo = &prAdapter->prGlueInfo->rHifInfo;
for (u4FwCnt = 0; u4FwCnt < 16; u4FwCnt++)
DBGLOG(INIT, WARN, "0x%08x ", MCU_REG_READL(HifInfo, CONN_MCU_CPUPCR));
/* CONSYS_REG_READ(CONSYS_CPUPCR_REG) */
/* dump HIF/DMA registers, if fgIsBusAccessFailed is FALSE, otherwise, */
/* dump HIF register may be hung */
if (!fgIsBusAccessFailed)
HifRegDump(prGlueInfo->prAdapter);
/* if (prGlueInfo->rHifInfo.DmaOps->DmaRegDump != NULL) */
/* prGlueInfo->rHifInfo.DmaOps->DmaRegDump(&prGlueInfo->rHifInfo); */
eFailReason = ADAPTER_START_FAIL;
break;
}
}
#else
/* P_REG_INFO_T prRegInfo = (P_REG_INFO_T) kmalloc(sizeof(REG_INFO_T), GFP_KERNEL); */
kalMemSet(&prGlueInfo->rRegInfo, 0, sizeof(REG_INFO_T));
P_REG_INFO_T prRegInfo = &prGlueInfo->rRegInfo;
/* Load NVRAM content to REG_INFO_T */
glLoadNvram(prGlueInfo, prRegInfo);
prRegInfo->u4PowerMode = CFG_INIT_POWER_SAVE_PROF;
if (wlanAdapterStart(prAdapter, prRegInfo, NULL, 0) != WLAN_STATUS_SUCCESS) {
i4Status = -EIO;
eFailReason = ADAPTER_START_FAIL;
break;
}
#endif
if (FALSE == prAdapter->fgEnable5GBand)
prWdev->wiphy->bands[IEEE80211_BAND_5GHZ] = NULL;
prGlueInfo->main_thread = kthread_run(tx_thread, prGlueInfo->prDevHandler, "tx_thread");
g_u4HaltFlag = 0;
#if CFG_SUPPORT_ROAMING_ENC
/* adjust roaming threshold */
{
WLAN_STATUS rStatus = WLAN_STATUS_FAILURE;
CMD_ROAMING_INFO_T rRoamingInfo;
UINT_32 u4SetInfoLen = 0;
prAdapter->fgIsRoamingEncEnabled = TRUE;
/* suggestion from Tsaiyuan.Hsu */
kalMemZero(&rRoamingInfo, sizeof(CMD_ROAMING_INFO_T));
rRoamingInfo.fgIsFastRoamingApplied = TRUE;
DBGLOG(INIT, TRACE, "Enable roaming enhance function\n");
rStatus = kalIoctl(prGlueInfo,
wlanoidSetRoamingInfo,
&rRoamingInfo, sizeof(rRoamingInfo), TRUE, TRUE, TRUE, FALSE, &u4SetInfoLen);
if (rStatus != WLAN_STATUS_SUCCESS)
DBGLOG(INIT, ERROR, "set roaming advance info fail 0x%x\n", rStatus);
}
#endif /* CFG_SUPPORT_ROAMING_ENC */
#if (CFG_SUPPORT_TXR_ENC == 1)
/* adjust tx rate switch threshold */
rlmTxRateEnhanceConfig(prGlueInfo->prAdapter);
#endif /* CFG_SUPPORT_TXR_ENC */
/* set MAC address */
{
WLAN_STATUS rStatus = WLAN_STATUS_FAILURE;
struct sockaddr MacAddr;
UINT_32 u4SetInfoLen = 0;
kalMemZero(MacAddr.sa_data, sizeof(MacAddr.sa_data));
rStatus = kalIoctl(prGlueInfo,
wlanoidQueryCurrentAddr,
&MacAddr.sa_data,
PARAM_MAC_ADDR_LEN, TRUE, TRUE, TRUE, FALSE, &u4SetInfoLen);
if (rStatus != WLAN_STATUS_SUCCESS) {
DBGLOG(INIT, WARN, "set MAC addr fail 0x%x\n", rStatus);
prGlueInfo->u4ReadyFlag = 0;
} else {
ether_addr_copy(prGlueInfo->prDevHandler->dev_addr, (const u8 *)&(MacAddr.sa_data));
ether_addr_copy(prGlueInfo->prDevHandler->perm_addr,
prGlueInfo->prDevHandler->dev_addr);
/* card is ready */
prGlueInfo->u4ReadyFlag = 1;
#if CFG_SHOW_MACADDR_SOURCE
DBGLOG(INIT, INFO, "MAC address: %pM ", (&MacAddr.sa_data));
#endif
}
}
#if CFG_TCP_IP_CHKSUM_OFFLOAD
/* set HW checksum offload */
{
WLAN_STATUS rStatus = WLAN_STATUS_FAILURE;
UINT_32 u4CSUMFlags = CSUM_OFFLOAD_EN_ALL;
UINT_32 u4SetInfoLen = 0;
rStatus = kalIoctl(prGlueInfo,
wlanoidSetCSUMOffload,
(PVOID) &u4CSUMFlags,
sizeof(UINT_32), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen);
if (rStatus != WLAN_STATUS_SUCCESS)
DBGLOG(INIT, WARN, "set HW checksum offload fail 0x%x\n", rStatus);
}
#endif
/* 4 <3> Register the card */
DBGLOG(INIT, TRACE, "wlanNetRegister...\n");
i4DevIdx = wlanNetRegister(prWdev);
if (i4DevIdx < 0) {
i4Status = -ENXIO;
DBGLOG(INIT, ERROR, "wlanProbe: Cannot register the net_device context to the kernel\n");
eFailReason = NET_REGISTER_FAIL;
break;
}
wlanRegisterNotifier();
/* 4 <6> Initialize /proc filesystem */
#ifdef WLAN_INCLUDE_PROC
DBGLOG(INIT, TRACE, "init procfs...\n");
i4Status = procCreateFsEntry(prGlueInfo);
if (i4Status < 0) {
DBGLOG(INIT, ERROR, "wlanProbe: init procfs failed\n");
eFailReason = PROC_INIT_FAIL;
break;
}
#endif /* WLAN_INCLUDE_PROC */
#if CFG_ENABLE_BT_OVER_WIFI
prGlueInfo->rBowInfo.fgIsNetRegistered = FALSE;
prGlueInfo->rBowInfo.fgIsRegistered = FALSE;
glRegisterAmpc(prGlueInfo);
#endif
#if CFG_ENABLE_WIFI_DIRECT
DBGLOG(INIT, TRACE, "wlanSubModInit...\n");
/* wlan is launched */
prGlueInfo->prAdapter->fgIsWlanLaunched = TRUE;
/* if p2p module is inserted, notify tx_thread to init p2p network */
if (rSubModHandler[P2P_MODULE].subModInit)
wlanSubModInit(prGlueInfo);
/* register set_p2p_mode handler to mtk_wmt_wifi */
register_set_p2p_mode_handler(set_p2p_mode_handler);
#endif
#if CFG_SPM_WORKAROUND_FOR_HOTSPOT
if (glIsChipNeedWakelock(prGlueInfo))
KAL_WAKE_LOCK_INIT(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rApWakeLock, "WLAN AP");
#endif
} while (FALSE);
if (i4Status != WLAN_STATUS_SUCCESS) {
switch (eFailReason) {
case PROC_INIT_FAIL:
wlanNetUnregister(prWdev);
set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag);
/* wake up main thread */
wake_up_interruptible(&prGlueInfo->waitq);
/* wait main thread stops */
wait_for_completion_interruptible(&prGlueInfo->rHaltComp);
KAL_WAKE_LOCK_DESTROY(prAdapter, &prAdapter->rTxThreadWakeLock);
wlanAdapterStop(prAdapter);
glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev)));
KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock);
wlanNetDestroy(prWdev);
break;
case NET_REGISTER_FAIL:
set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag);
/* wake up main thread */
wake_up_interruptible(&prGlueInfo->waitq);
/* wait main thread stops */
wait_for_completion_interruptible(&prGlueInfo->rHaltComp);
KAL_WAKE_LOCK_DESTROY(prAdapter, &prAdapter->rTxThreadWakeLock);
wlanAdapterStop(prAdapter);
glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev)));
KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock);
wlanNetDestroy(prWdev);
break;
case ADAPTER_START_FAIL:
glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev)));
KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock);
wlanNetDestroy(prWdev);
break;
case BUS_SET_IRQ_FAIL:
KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock);
wlanNetDestroy(prWdev);
break;
case NET_CREATE_FAIL:
break;
case BUS_INIT_FAIL:
break;
default:
break;
}
}
#if CFG_ENABLE_WIFI_DIRECT
{
GLUE_SPIN_LOCK_DECLARATION();
GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock);
g_u4P2PEnding = 0;
GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock);
}
#endif
#if CFG_SUPPORT_AGPS_ASSIST
if (i4Status == WLAN_STATUS_SUCCESS)
kalIndicateAgpsNotify(prAdapter, AGPS_EVENT_WLAN_ON, NULL, 0);
#endif
#if (CFG_SUPPORT_MET_PROFILING == 1)
{
int iMetInitRet = WLAN_STATUS_FAILURE;
if (i4Status == WLAN_STATUS_SUCCESS) {
DBGLOG(INIT, TRACE, "init MET procfs...\n");
iMetInitRet = kalMetInitProcfs(prGlueInfo);
if (iMetInitRet < 0)
DBGLOG(INIT, ERROR, "wlanProbe: init MET procfs failed\n");
}
}
#endif
if (i4Status == WLAN_STATUS_SUCCESS) {
/*Init performance monitor structure */
kalPerMonInit(prGlueInfo);
/* probe ok */
DBGLOG(INIT, TRACE, "wlanProbe ok\n");
} else {
/* we don't care the return value of mtk_wcn_set_connsys_power_off_flag,
* because even this function returns
* error, we can also call core dump but only core dump failed. */
if (g_IsNeedDoChipReset)
mtk_wcn_set_connsys_power_off_flag(0);
/* probe failed */
DBGLOG(INIT, ERROR, "wlanProbe failed\n");
}
return i4Status;
} /* end of wlanProbe() */
/*----------------------------------------------------------------------------*/
/*!
* \brief A method to stop driver operation and release all resources. Following
* this call, no frame should go up or down through this interface.
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
static VOID wlanRemove(VOID)
{
struct net_device *prDev = NULL;
P_WLANDEV_INFO_T prWlandevInfo = NULL;
P_GLUE_INFO_T prGlueInfo = NULL;
P_ADAPTER_T prAdapter = NULL;
DBGLOG(INIT, LOUD, "Remove wlan!\n");
/* 4 <0> Sanity check */
ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES);
if (0 == u4WlanDevNum) {
DBGLOG(INIT, ERROR, "0 == u4WlanDevNum\n");
return;
}
/* unregister set_p2p_mode handler to mtk_wmt_wifi */
register_set_p2p_mode_handler(NULL);
prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev;
prWlandevInfo = &arWlanDevInfo[u4WlanDevNum - 1];
ASSERT(prDev);
if (NULL == prDev) {
DBGLOG(INIT, ERROR, "NULL == prDev\n");
return;
}
prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev));
ASSERT(prGlueInfo);
if (NULL == prGlueInfo) {
DBGLOG(INIT, ERROR, "NULL == prGlueInfo\n");
free_netdev(prDev);
return;
}
kalPerMonDestroy(prGlueInfo);
/* 4 <3> Remove /proc filesystem. */
#ifdef WLAN_INCLUDE_PROC
procRemoveProcfs();
#endif /* WLAN_INCLUDE_PROC */
#if CFG_ENABLE_WIFI_DIRECT
/* avoid remove & p2p off command simultaneously */
{
BOOLEAN fgIsP2POnOffing;
GLUE_SPIN_LOCK_DECLARATION();
GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock);
g_u4P2PEnding = 1;
fgIsP2POnOffing = g_u4P2POnOffing;
GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock);
DBGLOG(INIT, TRACE, "waiting for fgIsP2POnOffing...\n");
/* History: cannot use down() here, sometimes we cannot come back here */
/* waiting for p2p off command finishes, we cannot skip the remove */
while (1) {
if (fgIsP2POnOffing == 0)
break;
GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock);
fgIsP2POnOffing = g_u4P2POnOffing;
GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock);
}
}
#endif
#if CFG_ENABLE_BT_OVER_WIFI
if (prGlueInfo->rBowInfo.fgIsNetRegistered) {
bowNotifyAllLinkDisconnected(prGlueInfo->prAdapter);
/* wait 300ms for BoW module to send deauth */
kalMsleep(300);
}
#endif
/* 4 <1> Stopping handling interrupt and free IRQ */
DBGLOG(INIT, TRACE, "free IRQ...\n");
glBusFreeIrq(prDev, *((P_GLUE_INFO_T *) netdev_priv(prDev)));
kalMemSet(&(prGlueInfo->prAdapter->rWlanInfo), 0, sizeof(WLAN_INFO_T));
g_u4HaltFlag = 1; /* before flush_delayed_work() */
if (fgIsWorkMcStart == TRUE) {
DBGLOG(INIT, TRACE, "flush_delayed_work...\n");
flush_delayed_work(&workq); /* flush_delayed_work_sync is deprecated */
}
flush_delayed_work(&sched_workq);
DBGLOG(INIT, INFO, "down g_halt_sem...\n");
down(&g_halt_sem);
#if CFG_SPM_WORKAROUND_FOR_HOTSPOT
if (glIsChipNeedWakelock(prGlueInfo))
KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rApWakeLock);
#endif
/* flush_delayed_work_sync(&workq); */
/* flush_delayed_work(&workq); */ /* flush_delayed_work_sync is deprecated */
/* 4 <2> Mark HALT, notify main thread to stop, and clean up queued requests */
/* prGlueInfo->u4Flag |= GLUE_FLAG_HALT; */
set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag);
DBGLOG(INIT, TRACE, "waiting for tx_thread stop...\n");
/* wake up main thread */
wake_up_interruptible(&prGlueInfo->waitq);
DBGLOG(INIT, TRACE, "wait_for_completion_interruptible\n");
/* wait main thread stops */
wait_for_completion_interruptible(&prGlueInfo->rHaltComp);
DBGLOG(INIT, TRACE, "mtk_sdiod stopped\n");
KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rTxThreadWakeLock);
KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->rAhbIsrWakeLock);
/* prGlueInfo->rHifInfo.main_thread = NULL; */
prGlueInfo->main_thread = NULL;
#if CFG_ENABLE_BT_OVER_WIFI
if (prGlueInfo->rBowInfo.fgIsRegistered)
glUnregisterAmpc(prGlueInfo);
#endif
#if (CFG_SUPPORT_MET_PROFILING == 1)
kalMetRemoveProcfs();
#endif
/* Force to do DMA reset */
DBGLOG(INIT, TRACE, "glResetHif\n");
glResetHif(prGlueInfo);
/* 4 <4> wlanAdapterStop */
prAdapter = prGlueInfo->prAdapter;
#if CFG_SUPPORT_AGPS_ASSIST
kalIndicateAgpsNotify(prAdapter, AGPS_EVENT_WLAN_OFF, NULL, 0);
#endif
wlanAdapterStop(prAdapter);
DBGLOG(INIT, TRACE, "Number of Stalled Packets = %d\n", prGlueInfo->i4TxPendingFrameNum);
#if CFG_ENABLE_WIFI_DIRECT
prGlueInfo->prAdapter->fgIsWlanLaunched = FALSE;
if (prGlueInfo->prAdapter->fgIsP2PRegistered) {
DBGLOG(INIT, TRACE, "p2pNetUnregister...\n");
#if !CFG_SUPPORT_PERSIST_NETDEV
p2pNetUnregister(prGlueInfo, FALSE);
#endif
DBGLOG(INIT, INFO, "p2pRemove...\n");
p2pRemove(prGlueInfo);
}
#endif
/* 4 <5> Release the Bus */
glBusRelease(prDev);
up(&g_halt_sem);
wlanDebugUninit();
/* 4 <6> Unregister the card */
wlanNetUnregister(prDev->ieee80211_ptr);
/* 4 <7> Destroy the device */
wlanNetDestroy(prDev->ieee80211_ptr);
prDev = NULL;
DBGLOG(INIT, LOUD, "wlanUnregisterNotifier...\n");
wlanUnregisterNotifier();
DBGLOG(INIT, INFO, "wlanRemove ok\n");
} /* end of wlanRemove() */
/*----------------------------------------------------------------------------*/
/*!
* \brief Driver entry point when the driver is configured as a Linux Module, and
* is called once at module load time, by the user-level modutils
* application: insmod or modprobe.
*
* \retval 0 Success
*/
/*----------------------------------------------------------------------------*/
/* 1 Module Entry Point */
static int initWlan(void)
{
int ret = 0, i;
#if DBG
for (i = 0; i < DBG_MODULE_NUM; i++)
aucDebugModule[i] = DBG_CLASS_MASK; /* enable all */
#else
/* Initial debug level is D1 */
for (i = 0; i < DBG_MODULE_NUM; i++)
aucDebugModule[i] = DBG_CLASS_ERROR | DBG_CLASS_WARN | DBG_CLASS_INFO | DBG_CLASS_STATE;
#endif /* DBG */
DBGLOG(INIT, INFO, "initWlan\n");
spin_lock_init(&g_p2p_lock);
/* memory pre-allocation */
kalInitIOBuffer();
procInitFs();
createWirelessDevice();
if (gprWdev)
glP2pCreateWirelessDevice((P_GLUE_INFO_T) wiphy_priv(gprWdev->wiphy));
ret = ((glRegisterBus(wlanProbe, wlanRemove) == WLAN_STATUS_SUCCESS) ? 0 : -EIO);
if (ret == -EIO) {
kalUninitIOBuffer();
return ret;
}
#if (CFG_CHIP_RESET_SUPPORT)
glResetInit();
#endif
/* register set_dbg_level handler to mtk_wmt_wifi */
register_set_dbg_level_handler(set_dbg_level_handler);
/* Register framebuffer notifier client*/
kalFbNotifierReg((P_GLUE_INFO_T) wiphy_priv(gprWdev->wiphy));
/* Set the initial DEBUG CLASS of each module */
return ret;
} /* end of initWlan() */
/*----------------------------------------------------------------------------*/
/*!
* \brief Driver exit point when the driver as a Linux Module is removed. Called
* at module unload time, by the user level modutils application: rmmod.
* This is our last chance to clean up after ourselves.
*
* \return (none)
*/
/*----------------------------------------------------------------------------*/
/* 1 Module Leave Point */
static VOID exitWlan(void)
{
DBGLOG(INIT, INFO, "exitWlan\n");
/* Unregister framebuffer notifier client*/
kalFbNotifierUnReg();
/* unregister set_dbg_level handler to mtk_wmt_wifi */
register_set_dbg_level_handler(NULL);
#if CFG_CHIP_RESET_SUPPORT
glResetUninit();
#endif
destroyWirelessDevice();
glP2pDestroyWirelessDevice();
glUnregisterBus(wlanRemove);
/* free pre-allocated memory */
kalUninitIOBuffer();
DBGLOG(INIT, INFO, "exitWlan\n");
procUninitProcFs();
} /* end of exitWlan() */
#ifdef MTK_WCN_BUILT_IN_DRIVER
int mtk_wcn_wlan_gen2_init(void)
{
return initWlan();
}
EXPORT_SYMBOL(mtk_wcn_wlan_gen2_init);
void mtk_wcn_wlan_gen2_exit(void)
{
return exitWlan();
}
EXPORT_SYMBOL(mtk_wcn_wlan_gen2_exit);
#else
module_init(initWlan);
module_exit(exitWlan);
#endif
| Java |
#include "../../../../../../src/reports/processor/style/color.h"
| Java |
@CHARSET "UTF-8";
div.ose-action-edit {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-edit.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.ose-action-validate {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-links.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.ose-action-edit-date {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-calendar.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.ose-action-delete {
background-image: url("../../../../templates/bluestork/images/menu/icon-16-deny.png");
display: inline-block;
height: 16px;
width: 16px;
float:left;
margin-right:5px
}
div.btntips {
height: 16px;
float:left;
margin-right:10px
} | Java |
/*
* linux/fs/super.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* super.c contains code to handle: - mount structures
* - super-block tables
* - filesystem drivers list
* - mount system call
* - umount system call
* - ustat system call
*
* GK 2/5/95 - Changed to support mounting the root fs via NFS
*
* Added kerneld support: Jacques Gelinas and Bjorn Ekwall
* Added change_root: Werner Almesberger & Hans Lermen, Feb '96
* Added options to /proc/mounts:
* Torbjörn Lindh ([email protected]), April 14, 1996.
* Added devfs support: Richard Gooch <[email protected]>, 13-JAN-1998
* Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/acct.h>
#include <linux/blkdev.h>
#include <linux/mount.h>
#include <linux/security.h>
#include <linux/writeback.h> /* for the emergency remount stuff */
#include <linux/idr.h>
#include <linux/mutex.h>
#include <linux/backing-dev.h>
#include <linux/rculist_bl.h>
#include <linux/cleancache.h>
#include <linux/lockdep.h>
#include "internal.h"
LIST_HEAD(super_blocks);
DEFINE_SPINLOCK(sb_lock);
static struct lock_class_key sb_writers_key[SB_FREEZE_LEVELS-1];
static int init_sb_writers(struct super_block *s, int level, char *lockname)
{
struct sb_writers_level *sl = &s->s_writers[level-1];
int err;
err = percpu_counter_init(&sl->counter, 0);
if (err < 0)
return err;
init_waitqueue_head(&sl->wait);
lockdep_init_map(&sl->lock_map, lockname, &sb_writers_key[level-1], 0);
return 0;
}
static void destroy_sb_writers(struct super_block *s, int level)
{
percpu_counter_destroy(&s->s_writers[level-1].counter);
}
/**
* alloc_super - create new superblock
* @type: filesystem type superblock should belong to
*
* Allocates and initializes a new &struct super_block. alloc_super()
* returns a pointer new superblock or %NULL if allocation had failed.
*/
static struct super_block *alloc_super(struct file_system_type *type)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
if (s) {
if (security_sb_alloc(s)) {
/*
* We cannot call security_sb_free() without
* security_sb_alloc() succeeding. So bail out manually
*/
kfree(s);
s = NULL;
goto out;
}
#ifdef CONFIG_SMP
s->s_files = alloc_percpu(struct list_head);
if (!s->s_files)
goto err_out;
else {
int i;
for_each_possible_cpu(i)
INIT_LIST_HEAD(per_cpu_ptr(s->s_files, i));
}
#else
INIT_LIST_HEAD(&s->s_files);
#endif
if (init_sb_writers(s, SB_FREEZE_WRITE, "sb_writers_write"))
goto err_out;
if (init_sb_writers(s, SB_FREEZE_TRANS, "sb_writers_trans"))
goto err_out;
s->s_bdi = &default_backing_dev_info;
INIT_LIST_HEAD(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
INIT_LIST_HEAD(&s->s_dentry_lru);
init_rwsem(&s->s_umount);
mutex_init(&s->s_lock);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* The locking rules for s_lock are up to the
* filesystem. For example ext3fs has different
* lock ordering than usbfs:
*/
lockdep_set_class(&s->s_lock, &type->s_lock_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
init_rwsem(&s->s_dquot.dqptr_sem);
init_waitqueue_head(&s->s_wait_unfrozen);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = -1;
}
out:
return s;
err_out:
security_sb_free(s);
#ifdef CONFIG_SMP
if (s->s_files)
free_percpu(s->s_files);
#endif
destroy_sb_writers(s, SB_FREEZE_WRITE);
destroy_sb_writers(s, SB_FREEZE_TRANS);
kfree(s);
s = NULL;
goto out;
}
/**
* destroy_super - frees a superblock
* @s: superblock to free
*
* Frees a superblock.
*/
static inline void destroy_super(struct super_block *s)
{
#ifdef CONFIG_SMP
free_percpu(s->s_files);
#endif
security_sb_free(s);
kfree(s->s_subtype);
kfree(s->s_options);
kfree(s);
}
/* Superblock refcounting */
/*
* Drop a superblock's refcount. The caller must hold sb_lock.
*/
void __put_super(struct super_block *sb)
{
if (!--sb->s_count) {
list_del_init(&sb->s_list);
destroy_super(sb);
}
}
/**
* put_super - drop a temporary reference to superblock
* @sb: superblock in question
*
* Drops a temporary reference, frees superblock if there's no
* references left.
*/
void put_super(struct super_block *sb)
{
spin_lock(&sb_lock);
__put_super(sb);
spin_unlock(&sb_lock);
}
/**
* deactivate_locked_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Drops an active reference to superblock, converting it into a temprory
* one if there is no other active references left. In that case we
* tell fs driver to shut it down and drop the temporary reference we
* had just acquired.
*
* Caller holds exclusive lock on superblock; that lock is released.
*/
void deactivate_locked_super(struct super_block *s)
{
struct file_system_type *fs = s->s_type;
if (atomic_dec_and_test(&s->s_active)) {
cleancache_flush_fs(s);
fs->kill_sb(s);
/*
* We need to call rcu_barrier so all the delayed rcu free
* inodes are flushed before we release the fs module.
*/
rcu_barrier();
put_filesystem(fs);
put_super(s);
} else {
up_write(&s->s_umount);
}
}
EXPORT_SYMBOL(deactivate_locked_super);
/**
* deactivate_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Variant of deactivate_locked_super(), except that superblock is *not*
* locked by caller. If we are going to drop the final active reference,
* lock will be acquired prior to that.
*/
void deactivate_super(struct super_block *s)
{
if (!atomic_add_unless(&s->s_active, -1, 1)) {
down_write(&s->s_umount);
deactivate_locked_super(s);
}
}
EXPORT_SYMBOL(deactivate_super);
/**
* grab_super - acquire an active reference
* @s: reference we are trying to make active
*
* Tries to acquire an active reference. grab_super() is used when we
* had just found a superblock in super_blocks or fs_type->fs_supers
* and want to turn it into a full-blown active reference. grab_super()
* is called with sb_lock held and drops it. Returns 1 in case of
* success, 0 if we had failed (superblock contents was already dead or
* dying when grab_super() had been called).
*/
static int grab_super(struct super_block *s) __releases(sb_lock)
{
if (atomic_inc_not_zero(&s->s_active)) {
spin_unlock(&sb_lock);
return 1;
}
/* it's going away */
s->s_count++;
spin_unlock(&sb_lock);
/* wait for it to die */
down_write(&s->s_umount);
up_write(&s->s_umount);
put_super(s);
return 0;
}
/*
* grab_super_passive - acquire a passive reference
* @s: reference we are trying to grab
*
* Tries to acquire a passive reference. This is used in places where we
* cannot take an active reference but we need to ensure that the
* superblock does not go away while we are working on it. It returns
* false if a reference was not gained, and returns true with the s_umount
* lock held in read mode if a reference is gained. On successful return,
* the caller must drop the s_umount lock and the passive reference when
* done.
*/
bool grab_super_passive(struct super_block *sb)
{
spin_lock(&sb_lock);
if (list_empty(&sb->s_instances)) {
spin_unlock(&sb_lock);
return false;
}
sb->s_count++;
spin_unlock(&sb_lock);
if (down_read_trylock(&sb->s_umount)) {
if (sb->s_root)
return true;
up_read(&sb->s_umount);
}
put_super(sb);
return false;
}
/*
* Superblock locking. We really ought to get rid of these two.
*/
void lock_super(struct super_block * sb)
{
mutex_lock(&sb->s_lock);
}
void unlock_super(struct super_block * sb)
{
mutex_unlock(&sb->s_lock);
}
EXPORT_SYMBOL(lock_super);
EXPORT_SYMBOL(unlock_super);
/**
* generic_shutdown_super - common helper for ->kill_sb()
* @sb: superblock to kill
*
* generic_shutdown_super() does all fs-independent work on superblock
* shutdown. Typical ->kill_sb() should pick all fs-specific objects
* that need destruction out of superblock, call generic_shutdown_super()
* and release aforementioned objects. Note: dentries and inodes _are_
* taken care of and do not need specific handling.
*
* Upon calling this function, the filesystem may no longer alter or
* rearrange the set of dentries belonging to this super_block, nor may it
* change the attachments of dentries to inodes.
*/
void generic_shutdown_super(struct super_block *sb)
{
const struct super_operations *sop = sb->s_op;
if (sb->s_root) {
shrink_dcache_for_umount(sb);
sync_filesystem(sb);
get_fs_excl();
sb->s_flags &= ~MS_ACTIVE;
fsnotify_unmount_inodes(&sb->s_inodes);
evict_inodes(sb);
if (sop->put_super)
sop->put_super(sb);
if (!list_empty(&sb->s_inodes)) {
printk("VFS: Busy inodes after unmount of %s. "
"Self-destruct in 5 seconds. Have a nice day...\n",
sb->s_id);
}
put_fs_excl();
}
spin_lock(&sb_lock);
/* should be initialized for __put_super_and_need_restart() */
list_del_init(&sb->s_instances);
spin_unlock(&sb_lock);
up_write(&sb->s_umount);
}
EXPORT_SYMBOL(generic_shutdown_super);
/**
* sget - find or create a superblock
* @type: filesystem type superblock should belong to
* @test: comparison callback
* @set: setup callback
* @data: argument to each of them
*/
struct super_block *sget(struct file_system_type *type,
int (*test)(struct super_block *,void *),
int (*set)(struct super_block *,void *),
void *data)
{
struct super_block *s = NULL;
struct super_block *old;
int err;
retry:
spin_lock(&sb_lock);
if (test) {
list_for_each_entry(old, &type->fs_supers, s_instances) {
if (!test(old, data))
continue;
if (!grab_super(old))
goto retry;
if (s) {
up_write(&s->s_umount);
destroy_super(s);
s = NULL;
}
down_write(&old->s_umount);
if (unlikely(!(old->s_flags & MS_BORN))) {
deactivate_locked_super(old);
goto retry;
}
return old;
}
}
if (!s) {
spin_unlock(&sb_lock);
s = alloc_super(type);
if (!s)
return ERR_PTR(-ENOMEM);
goto retry;
}
err = set(s, data);
if (err) {
spin_unlock(&sb_lock);
up_write(&s->s_umount);
destroy_super(s);
return ERR_PTR(err);
}
s->s_type = type;
strlcpy(s->s_id, type->name, sizeof(s->s_id));
list_add_tail(&s->s_list, &super_blocks);
list_add(&s->s_instances, &type->fs_supers);
spin_unlock(&sb_lock);
get_filesystem(type);
return s;
}
EXPORT_SYMBOL(sget);
void drop_super(struct super_block *sb)
{
up_read(&sb->s_umount);
put_super(sb);
}
EXPORT_SYMBOL(drop_super);
/**
* sync_supers - helper for periodic superblock writeback
*
* Call the write_super method if present on all dirty superblocks in
* the system. This is for the periodic writeback used by most older
* filesystems. For data integrity superblock writeback use
* sync_filesystems() instead.
*
* Note: check the dirty flag before waiting, so we don't
* hold up the sync while mounting a device. (The newly
* mounted device won't need syncing.)
*/
void sync_supers(void)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_op->write_super && sb->s_dirt) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
if (sb->s_root && sb->s_dirt)
sb->s_op->write_super(sb);
up_read(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
}
/**
* iterate_supers - call function for all active superblocks
* @f: function to call
* @arg: argument to pass to it
*
* Scans the superblock list and calls given function, passing it
* locked superblock and given argument.
*/
void iterate_supers(void (*f)(struct super_block *, void *), void *arg)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
if (sb->s_root)
f(sb, arg);
up_read(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
}
/**
* get_super - get the superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device given. %NULL is returned if no match is found.
*/
struct super_block *get_super(struct block_device *bdev)
{
struct super_block *sb;
if (!bdev)
return NULL;
spin_lock(&sb_lock);
rescan:
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_bdev == bdev) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
/* still alive? */
if (sb->s_root)
return sb;
up_read(&sb->s_umount);
/* nope, got unmounted */
spin_lock(&sb_lock);
__put_super(sb);
goto rescan;
}
}
spin_unlock(&sb_lock);
return NULL;
}
EXPORT_SYMBOL(get_super);
/**
* get_active_super - get an active reference to the superblock of a device
* @bdev: device to get the superblock for
*
* Scans the superblock list and finds the superblock of the file system
* mounted on the device given. Returns the superblock with an active
* reference or %NULL if none was found.
*/
struct super_block *get_active_super(struct block_device *bdev)
{
struct super_block *sb;
if (!bdev)
return NULL;
restart:
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_bdev == bdev) {
if (grab_super(sb)) /* drops sb_lock */
return sb;
else
goto restart;
}
}
spin_unlock(&sb_lock);
return NULL;
}
struct super_block *user_get_super(dev_t dev)
{
struct super_block *sb;
spin_lock(&sb_lock);
rescan:
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
if (sb->s_dev == dev) {
sb->s_count++;
spin_unlock(&sb_lock);
down_read(&sb->s_umount);
/* still alive? */
if (sb->s_root)
return sb;
up_read(&sb->s_umount);
/* nope, got unmounted */
spin_lock(&sb_lock);
__put_super(sb);
goto rescan;
}
}
spin_unlock(&sb_lock);
return NULL;
}
/**
* do_remount_sb - asks filesystem to change mount options.
* @sb: superblock in question
* @flags: numeric part of options
* @data: the rest of options
* @force: whether or not to force the change
*
* Alters the mount options of a mounted file system.
*/
int do_remount_sb(struct super_block *sb, int flags, void *data, int force)
{
int retval;
int remount_ro;
if (sb->s_frozen != SB_UNFROZEN)
return -EBUSY;
#ifdef CONFIG_BLOCK
if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev))
return -EACCES;
#endif
if (flags & MS_RDONLY)
acct_auto_close(sb);
shrink_dcache_sb(sb);
sync_filesystem(sb);
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
/* If we are remounting RDONLY and current sb is read/write,
make sure there are no rw files opened */
if (remount_ro) {
if (force)
mark_files_ro(sb);
else if (!fs_may_remount_ro(sb))
return -EBUSY;
}
if (sb->s_op->remount_fs) {
retval = sb->s_op->remount_fs(sb, &flags, data);
if (retval)
return retval;
}
sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
/*
* Some filesystems modify their metadata via some other path than the
* bdev buffer cache (eg. use a private mapping, or directories in
* pagecache, etc). Also file data modifications go via their own
* mappings. So If we try to mount readonly then copy the filesystem
* from bdev, we could get stale data, so invalidate it to give a best
* effort at coherency.
*/
if (remount_ro && sb->s_bdev)
invalidate_bdev(sb->s_bdev);
return 0;
}
static void do_emergency_remount(struct work_struct *work)
{
struct super_block *sb, *p = NULL;
spin_lock(&sb_lock);
list_for_each_entry(sb, &super_blocks, s_list) {
if (list_empty(&sb->s_instances))
continue;
sb->s_count++;
spin_unlock(&sb_lock);
down_write(&sb->s_umount);
if (sb->s_root && sb->s_bdev && !(sb->s_flags & MS_RDONLY)) {
/*
* What lock protects sb->s_flags??
*/
do_remount_sb(sb, MS_RDONLY, NULL, 1);
}
up_write(&sb->s_umount);
spin_lock(&sb_lock);
if (p)
__put_super(p);
p = sb;
}
if (p)
__put_super(p);
spin_unlock(&sb_lock);
kfree(work);
printk("Emergency Remount complete\n");
}
void emergency_remount(void)
{
struct work_struct *work;
work = kmalloc(sizeof(*work), GFP_ATOMIC);
if (work) {
INIT_WORK(work, do_emergency_remount);
schedule_work(work);
}
}
/*
* Unnamed block devices are dummy devices used by virtual
* filesystems which don't use real block-devices. -- jrs
*/
static DEFINE_IDA(unnamed_dev_ida);
static DEFINE_SPINLOCK(unnamed_dev_lock);/* protects the above */
static int unnamed_dev_start = 0; /* don't bother trying below it */
int set_anon_super(struct super_block *s, void *data)
{
int dev;
int error;
retry:
if (ida_pre_get(&unnamed_dev_ida, GFP_ATOMIC) == 0)
return -ENOMEM;
spin_lock(&unnamed_dev_lock);
error = ida_get_new_above(&unnamed_dev_ida, unnamed_dev_start, &dev);
if (!error)
unnamed_dev_start = dev + 1;
spin_unlock(&unnamed_dev_lock);
if (error == -EAGAIN)
/* We raced and lost with another CPU. */
goto retry;
else if (error)
return -EAGAIN;
if ((dev & MAX_ID_MASK) == (1 << MINORBITS)) {
spin_lock(&unnamed_dev_lock);
ida_remove(&unnamed_dev_ida, dev);
if (unnamed_dev_start > dev)
unnamed_dev_start = dev;
spin_unlock(&unnamed_dev_lock);
return -EMFILE;
}
s->s_dev = MKDEV(0, dev & MINORMASK);
s->s_bdi = &noop_backing_dev_info;
return 0;
}
EXPORT_SYMBOL(set_anon_super);
void kill_anon_super(struct super_block *sb)
{
int slot = MINOR(sb->s_dev);
generic_shutdown_super(sb);
spin_lock(&unnamed_dev_lock);
ida_remove(&unnamed_dev_ida, slot);
if (slot < unnamed_dev_start)
unnamed_dev_start = slot;
spin_unlock(&unnamed_dev_lock);
}
EXPORT_SYMBOL(kill_anon_super);
void kill_litter_super(struct super_block *sb)
{
if (sb->s_root)
d_genocide(sb->s_root);
kill_anon_super(sb);
}
EXPORT_SYMBOL(kill_litter_super);
static int ns_test_super(struct super_block *sb, void *data)
{
return sb->s_fs_info == data;
}
static int ns_set_super(struct super_block *sb, void *data)
{
sb->s_fs_info = data;
return set_anon_super(sb, NULL);
}
struct dentry *mount_ns(struct file_system_type *fs_type, int flags,
void *data, int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *sb;
sb = sget(fs_type, ns_test_super, ns_set_super, data);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!sb->s_root) {
int err;
sb->s_flags = flags;
err = fill_super(sb, data, flags & MS_SILENT ? 1 : 0);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
}
return dget(sb->s_root);
}
EXPORT_SYMBOL(mount_ns);
#ifdef CONFIG_BLOCK
static int set_bdev_super(struct super_block *s, void *data)
{
s->s_bdev = data;
s->s_dev = s->s_bdev->bd_dev;
/*
* We set the bdi here to the queue backing, file systems can
* overwrite this in ->fill_super()
*/
s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info;
return 0;
}
static int test_bdev_super(struct super_block *s, void *data)
{
return (void *)s->s_bdev == data;
}
struct dentry *mount_bdev(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
struct block_device *bdev;
struct super_block *s;
fmode_t mode = FMODE_READ | FMODE_EXCL;
int error = 0;
if (!(flags & MS_RDONLY))
mode |= FMODE_WRITE;
bdev = blkdev_get_by_path(dev_name, mode, fs_type);
if (IS_ERR(bdev))
return ERR_CAST(bdev);
/*
* once the super is inserted into the list by sget, s_umount
* will protect the lockfs code from trying to start a snapshot
* while we are mounting
*/
mutex_lock(&bdev->bd_fsfreeze_mutex);
if (bdev->bd_fsfreeze_count > 0) {
mutex_unlock(&bdev->bd_fsfreeze_mutex);
error = -EBUSY;
goto error_bdev;
}
s = sget(fs_type, test_bdev_super, set_bdev_super, bdev);
mutex_unlock(&bdev->bd_fsfreeze_mutex);
if (IS_ERR(s))
goto error_s;
if (s->s_root) {
if ((flags ^ s->s_flags) & MS_RDONLY) {
deactivate_locked_super(s);
error = -EBUSY;
goto error_bdev;
}
/*
* s_umount nests inside bd_mutex during
* __invalidate_device(). blkdev_put() acquires
* bd_mutex and can't be called under s_umount. Drop
* s_umount temporarily. This is safe as we're
* holding an active reference.
*/
up_write(&s->s_umount);
blkdev_put(bdev, mode);
down_write(&s->s_umount);
} else {
char b[BDEVNAME_SIZE];
s->s_flags = flags;
s->s_mode = mode;
strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id));
sb_set_blocksize(s, block_size(bdev));
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
goto error;
}
s->s_flags |= MS_ACTIVE;
bdev->bd_super = s;
}
return dget(s->s_root);
error_s:
error = PTR_ERR(s);
error_bdev:
blkdev_put(bdev, mode);
error:
return ERR_PTR(error);
}
EXPORT_SYMBOL(mount_bdev);
void kill_block_super(struct super_block *sb)
{
struct block_device *bdev = sb->s_bdev;
fmode_t mode = sb->s_mode;
bdev->bd_super = NULL;
generic_shutdown_super(sb);
sync_blockdev(bdev);
WARN_ON_ONCE(!(mode & FMODE_EXCL));
blkdev_put(bdev, mode | FMODE_EXCL);
}
EXPORT_SYMBOL(kill_block_super);
#endif
struct dentry *mount_nodev(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
int error;
struct super_block *s = sget(fs_type, NULL, set_anon_super, NULL);
if (IS_ERR(s))
return ERR_CAST(s);
s->s_flags = flags;
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
return ERR_PTR(error);
}
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
}
EXPORT_SYMBOL(mount_nodev);
static int compare_single(struct super_block *s, void *p)
{
return 1;
}
struct dentry *mount_single(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int))
{
struct super_block *s;
int error;
s = sget(fs_type, compare_single, set_anon_super, NULL);
if (IS_ERR(s))
return ERR_CAST(s);
if (!s->s_root) {
s->s_flags = flags;
error = fill_super(s, data, flags & MS_SILENT ? 1 : 0);
if (error) {
deactivate_locked_super(s);
return ERR_PTR(error);
}
s->s_flags |= MS_ACTIVE;
} else {
do_remount_sb(s, flags, data, 0);
}
return dget(s->s_root);
}
EXPORT_SYMBOL(mount_single);
struct dentry *
mount_fs(struct file_system_type *type, int flags, const char *name, void *data)
{
struct dentry *root;
struct super_block *sb;
char *secdata = NULL;
int error = -ENOMEM;
if (data && !(type->fs_flags & FS_BINARY_MOUNTDATA)) {
secdata = alloc_secdata();
if (!secdata)
goto out;
error = security_sb_copy_data(data, secdata);
if (error)
goto out_free_secdata;
}
root = type->mount(type, flags, name, data);
if (IS_ERR(root)) {
error = PTR_ERR(root);
goto out_free_secdata;
}
sb = root->d_sb;
BUG_ON(!sb);
WARN_ON(!sb->s_bdi);
WARN_ON(sb->s_bdi == &default_backing_dev_info);
sb->s_flags |= MS_BORN;
error = security_sb_kern_mount(sb, flags, secdata);
if (error)
goto out_sb;
/*
* filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE
* but s_maxbytes was an unsigned long long for many releases. Throw
* this warning for a little while to try and catch filesystems that
* violate this rule.
*/
WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to "
"negative value (%lld)\n", type->name, sb->s_maxbytes);
up_write(&sb->s_umount);
free_secdata(secdata);
return root;
out_sb:
dput(root);
deactivate_locked_super(sb);
out_free_secdata:
free_secdata(secdata);
out:
return ERR_PTR(error);
}
/**
* sb_end_write - drop write access to a superblock
* @sb: the super we wrote to
* @level: the lowest level of freezing which we blocked
*
* Decrement number of writers to the filesystem preventing freezing of
* given level. Wake up possible waiters wanting to freeze the filesystem.
*/
void sb_end_write(struct super_block *sb, int level)
{
struct sb_writers_level *sl = &sb->s_writers[level-1];
percpu_counter_dec(&sl->counter);
/*
* Make sure s_writers are updated before we wake up waiters in
* freeze_super().
*/
smp_mb();
if (waitqueue_active(&sl->wait))
wake_up(&sl->wait);
rwsem_release(&sl->lock_map, 1, _RET_IP_);
}
EXPORT_SYMBOL(sb_end_write);
/**
* sb_start_write - get write access to a superblock
* @sb: the super we write to
* @level: the lowest level of freezing which we block
*
* When a process wants to write data to a filesystem (i.e. dirty a page), it
* should embed the operation in a sb_start_write() - sb_end_write() pair to
* get exclusion against filesystem freezing. This function increments number
* of writers preventing freezing of given level to proceed. If the file
* system is already frozen it waits until it is thawed.
*
* The lock orderding constraints of sb_start_write() for level SB_FREEZE_WRITE
* are following:
* mmap_sem (page-fault)
* -> s_writers (block_page_mkwrite or equivalent)
*
* i_mutex (do_truncate, __generic_file_aio_write)
* -> s_writers
*
* s_umount (freeze_super)
* -> s_writers
*
* For level SB_FREEZE_TRANS lock constraints are rather file system dependent,
* in most cases equivalent to constraints for starting a fs transaction.
*/
void sb_start_write(struct super_block *sb, int level)
{
retry:
rwsem_acquire_read(&sb->s_writers[level-1].lock_map, 0, 0, _RET_IP_);
vfs_check_frozen(sb, level);
percpu_counter_inc(&sb->s_writers[level-1].counter);
/*
* Make sure s_writers are updated before we check s_frozen.
* freeze_super() first sets s_frozen and then checks s_writers.
*/
smp_mb();
if (sb->s_frozen >= level) {
sb_end_write(sb, level);
goto retry;
}
}
EXPORT_SYMBOL(sb_start_write);
/**
* sb_dup_write - get write access to a superblock without blocking
* @sb: the super we write to
* @level: the lowest level of freezing which we block
*
* This function is like sb_start_write() only that it does not check s_frozen
* in the superblock. The caller can call this function only when it already
* holds write access to the superblock at this level (i.e., called
* sb_start_write(sb, level) previously).
*/
void sb_dup_write(struct super_block *sb, int level)
{
/*
* Trick lockdep into acquiring read lock again without complaining
* about lock recursion
*/
rwsem_acquire_read(&sb->s_writers[level-1].lock_map, 0, 1, _RET_IP_);
percpu_counter_inc(&sb->s_writers[level-1].counter);
}
EXPORT_SYMBOL(sb_dup_write);
/**
* sb_wait_write - wait until all writers at given level finish
* @sb: the super for which we wait
* @level: the level at which we wait for writers
*
* This function waits until there are no writers at given level. Caller
* of this function should make sure there can be no new writers at required
* level before calling this function. Otherwise this function can livelock.
*/
void sb_wait_write(struct super_block *sb, int level)
{
s64 writers;
struct sb_writers_level *sl = &sb->s_writers[level-1];
do {
DEFINE_WAIT(wait);
/*
* We use a barrier in prepare_to_wait() to separate setting
* of s_frozen and checking of s_writers
*/
prepare_to_wait(&sl->wait, &wait, TASK_UNINTERRUPTIBLE);
writers = percpu_counter_sum(&sl->counter);
if (writers)
schedule();
finish_wait(&sl->wait, &wait);
} while (writers);
}
EXPORT_SYMBOL(sb_wait_write);
/*
* Freeze superblock to given level, wait for writers at given level
* to finish.
*/
static void sb_freeze_to_level(struct super_block *sb, int level)
{
sb->s_frozen = level;
/*
* We just cycle-through lockdep here so that it does not complain
* about returning with lock to userspace
*/
rwsem_acquire(&sb->s_writers[level-1].lock_map, 0, 0, _THIS_IP_);
rwsem_release(&sb->s_writers[level-1].lock_map, 1, _THIS_IP_);
/*
* Now wait for writers to finish. As s_frozen is already set to
* 'level' we are guaranteed there are no new writers at given level.
*/
sb_wait_write(sb, level);
}
/**
* freeze_super - lock the filesystem and force it into a consistent state
* @sb: the super to lock
*
* Syncs the super to make sure the filesystem is consistent and calls the fs's
* freeze_fs. Subsequent calls to this without first thawing the fs will return
* -EBUSY.
*/
int freeze_super(struct super_block *sb)
{
int ret;
atomic_inc(&sb->s_active);
down_write(&sb->s_umount);
if (sb->s_frozen) {
deactivate_locked_super(sb);
return -EBUSY;
}
if (sb->s_flags & MS_RDONLY) {
sb->s_frozen = SB_FREEZE_TRANS;
smp_wmb();
up_write(&sb->s_umount);
return 0;
}
sb_freeze_to_level(sb, SB_FREEZE_WRITE);
sync_filesystem(sb);
sb_freeze_to_level(sb, SB_FREEZE_TRANS);
sync_blockdev(sb->s_bdev);
if (sb->s_op->freeze_fs) {
ret = sb->s_op->freeze_fs(sb);
if (ret) {
printk(KERN_ERR
"VFS:Filesystem freeze failed\n");
sb->s_frozen = SB_UNFROZEN;
deactivate_locked_super(sb);
return ret;
}
}
up_write(&sb->s_umount);
return 0;
}
EXPORT_SYMBOL(freeze_super);
/**
* thaw_super -- unlock filesystem
* @sb: the super to thaw
*
* Unlocks the filesystem and marks it writeable again after freeze_super().
*/
int thaw_super(struct super_block *sb)
{
int error;
down_write(&sb->s_umount);
if (sb->s_frozen == SB_UNFROZEN) {
up_write(&sb->s_umount);
return -EINVAL;
}
if (sb->s_flags & MS_RDONLY)
goto out;
if (sb->s_op->unfreeze_fs) {
error = sb->s_op->unfreeze_fs(sb);
if (error) {
printk(KERN_ERR
"VFS:Filesystem thaw failed\n");
sb->s_frozen = SB_FREEZE_TRANS;
up_write(&sb->s_umount);
return error;
}
}
out:
sb->s_frozen = SB_UNFROZEN;
smp_wmb();
wake_up(&sb->s_wait_unfrozen);
deactivate_locked_super(sb);
return 0;
}
EXPORT_SYMBOL(thaw_super);
| Java |
#include "cmdq_platform.h"
#include "cmdq_core.h"
#include "cmdq_reg.h"
#include <linux/vmalloc.h>
#include <mach/mt_clkmgr.h>
#include <linux/seq_file.h>
#include "smi_debug.h"
#include "m4u.h"
#define MMSYS_CONFIG_BASE cmdq_dev_get_module_base_VA_MMSYS_CONFIG()
typedef struct RegDef {
int offset;
const char *name;
} RegDef;
const bool cmdq_core_support_sync_non_suspendable(void)
{
return true;
}
const bool cmdq_core_support_wait_and_receive_event_in_same_tick(void)
{
return true;
}
const uint32_t cmdq_core_get_subsys_LSB_in_argA(void)
{
return 16;
}
int32_t cmdq_subsys_from_phys_addr(uint32_t physAddr)
{
const int32_t msb = (physAddr & 0x0FFFF0000) >> 16;
#undef DECLARE_CMDQ_SUBSYS
#define DECLARE_CMDQ_SUBSYS(addr, id, grp, base) case addr: return id;
switch (msb) {
#include "cmdq_subsys.h"
}
CMDQ_ERR("unrecognized subsys, msb=0x%04x, physAddr:0x%08x\n", msb, physAddr);
return -1;
#undef DECLARE_CMDQ_SUBSYS
}
void cmdq_core_fix_command_desc_scenario_for_user_space_request(cmdqCommandStruct *pCommand)
{
if ((CMDQ_SCENARIO_USER_DISP_COLOR == pCommand->scenario) || (CMDQ_SCENARIO_USER_MDP == pCommand->scenario)) {
CMDQ_VERBOSE("user space request, scenario:%d\n", pCommand->scenario);
} else {
CMDQ_VERBOSE("[WARNING]fix user space request to CMDQ_SCENARIO_USER_SPACE\n");
pCommand->scenario = CMDQ_SCENARIO_USER_SPACE;
}
}
bool cmdq_core_is_request_from_user_space(const CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_USER_DISP_COLOR:
case CMDQ_SCENARIO_USER_MDP:
case CMDQ_SCENARIO_USER_SPACE: /* phased out */
return true;
default:
return false;
}
return false;
}
bool cmdq_core_is_disp_scenario(const CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_MEMOUT:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
case CMDQ_SCENARIO_RDMA1_DISP:
case CMDQ_SCENARIO_TRIGGER_LOOP:
case CMDQ_SCENARIO_DISP_ESD_CHECK:
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
/* color path */
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
/* secure path */
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
return true;
default:
return false;
}
/* freely dispatch */
return false;
}
bool cmdq_core_should_enable_prefetch(CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_DEBUG_PREFETCH: /* HACK: force debug into 0/1 thread */
/* any path that connects to Primary DISP HW */
/* should enable prefetch. */
/* MEMOUT scenarios does not. */
/* Also, since thread 0/1 shares one prefetch buffer, */
/* we allow only PRIMARY path to use prefetch. */
return true;
default:
return false;
}
return false;
}
bool cmdq_core_should_profile(CMDQ_SCENARIO_ENUM scenario)
{
#ifdef CMDQ_GPR_SUPPORT
switch (scenario) {
default:
return false;
}
return false;
#else
/* note command profile method depends on GPR */
CMDQ_ERR("func:%s failed since CMDQ dosen't support GPR\n", __func__);
return false;
#endif
}
const bool cmdq_core_is_a_secure_thread(const int32_t thread)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if ((CMDQ_MIN_SECURE_THREAD_ID <= thread) &&
(CMDQ_MIN_SECURE_THREAD_ID + CMDQ_MAX_SECURE_THREAD_COUNT > thread)){
return true;
}
#endif
return false;
}
const bool cmdq_core_is_valid_notify_thread_for_secure_path(const int32_t thread)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
return (15 == thread) ? (true) : (false);
#else
return false;
#endif
}
int cmdq_core_get_thread_index_from_scenario_and_secure_data(CMDQ_SCENARIO_ENUM scenario, const bool secure)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if (!secure && CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) {
return 15;
}
#endif
if (!secure) {
return cmdq_core_disp_thread_index_from_scenario(scenario);
}
/* dispatch secure thread according to scenario */
switch (scenario) {
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_DEBUG_PREFETCH:
/* CMDQ_MIN_SECURE_THREAD_ID */
return 12;
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_MHL_DISP:
/* because mirror mode and sub disp never use at the same time in secure path, */
/* dispatch to same HW thread */
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
return 13;
case CMDQ_SCENARIO_USER_MDP:
case CMDQ_SCENARIO_USER_SPACE:
case CMDQ_SCENARIO_DEBUG:
/* because there is one input engine for MDP, reserve one secure thread is enough */
return 14;
default:
CMDQ_ERR("no dedicated secure thread for senario:%d\n", scenario);
return CMDQ_INVALID_THREAD;
}
}
int cmdq_core_disp_thread_index_from_scenario(CMDQ_SCENARIO_ENUM scenario)
{
if (cmdq_core_should_enable_prefetch(scenario)) {
return 0;
}
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
case CMDQ_SCENARIO_DEBUG_PREFETCH: /* HACK: force debug into 0/1 thread */
/* primary config: thread 0 */
return 0;
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_SUB_MEMOUT:
case CMDQ_SCENARIO_RDMA1_DISP:
/* when HW thread 0 enables pre-fetch, any thread 1 operation will let HW thread 0's behavior abnormally */
/* forbid thread 1 */
return 5;
case CMDQ_SCENARIO_DISP_ESD_CHECK:
return 2;
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
return 3;
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
return 4;
default:
/* freely dispatch */
return CMDQ_INVALID_THREAD;
}
/* freely dispatch */
return CMDQ_INVALID_THREAD;
}
CMDQ_HW_THREAD_PRIORITY_ENUM cmdq_core_priority_from_scenario(CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case CMDQ_SCENARIO_PRIMARY_DISP:
case CMDQ_SCENARIO_PRIMARY_ALL:
case CMDQ_SCENARIO_SUB_MEMOUT:
case CMDQ_SCENARIO_SUB_DISP:
case CMDQ_SCENARIO_SUB_ALL:
case CMDQ_SCENARIO_RDMA1_DISP:
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_RDMA0_DISP:
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
/* color path */
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
/* secure path **/
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
/* currently, a prefetch thread is always in high priority. */
return CMDQ_THR_PRIO_DISPLAY_CONFIG;
/* HACK: force debug into 0/1 thread */
case CMDQ_SCENARIO_DEBUG_PREFETCH:
return CMDQ_THR_PRIO_DISPLAY_CONFIG;
case CMDQ_SCENARIO_DISP_ESD_CHECK:
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
return CMDQ_THR_PRIO_DISPLAY_ESD;
default:
/* other cases need exta logic, see below. */
break;
}
if (cmdq_platform_is_loop_scenario(scenario, true)) {
return CMDQ_THR_PRIO_DISPLAY_TRIGGER;
} else {
return CMDQ_THR_PRIO_NORMAL;
}
}
bool cmdq_platform_force_loop_irq_from_scenario(CMDQ_SCENARIO_ENUM scenario)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if (CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) {
/* For secure notify loop, we need IRQ to update secure task */
return true;
}
#endif
return false;
}
bool cmdq_platform_is_loop_scenario(CMDQ_SCENARIO_ENUM scenario, bool displayOnly)
{
#ifdef CMDQ_SECURE_PATH_SUPPORT
if (!displayOnly && CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) {
return true;
}
#endif
if (CMDQ_SCENARIO_TRIGGER_LOOP == scenario) {
return true;
}
return false;
}
void cmdq_core_get_reg_id_from_hwflag(uint64_t hwflag, CMDQ_DATA_REGISTER_ENUM *valueRegId,
CMDQ_DATA_REGISTER_ENUM *destRegId,
CMDQ_EVENT_ENUM *regAccessToken)
{
*regAccessToken = CMDQ_SYNC_TOKEN_INVALID;
if (hwflag & (1LL << CMDQ_ENG_JPEG_ENC)) {
*valueRegId = CMDQ_DATA_REG_JPEG;
*destRegId = CMDQ_DATA_REG_JPEG_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_0;
} else if (hwflag & (1LL << CMDQ_ENG_MDP_TDSHP0)) {
*valueRegId = CMDQ_DATA_REG_2D_SHARPNESS_0;
*destRegId = CMDQ_DATA_REG_2D_SHARPNESS_0_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_1;
} else if (hwflag & (1LL << CMDQ_ENG_DISP_COLOR0)) {
*valueRegId = CMDQ_DATA_REG_PQ_COLOR;
*destRegId = CMDQ_DATA_REG_PQ_COLOR_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_3;
} else {
/* assume others are debug cases */
*valueRegId = CMDQ_DATA_REG_DEBUG;
*destRegId = CMDQ_DATA_REG_DEBUG_DST;
*regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_4;
}
return;
}
const char *cmdq_core_module_from_event_id(CMDQ_EVENT_ENUM event, uint32_t instA, uint32_t instB)
{
const char *module = "CMDQ";
switch (event) {
case CMDQ_EVENT_DISP_RDMA0_SOF:
case CMDQ_EVENT_DISP_RDMA1_SOF:
case CMDQ_EVENT_DISP_RDMA0_EOF:
case CMDQ_EVENT_DISP_RDMA1_EOF:
case CMDQ_EVENT_DISP_RDMA0_UNDERRUN:
case CMDQ_EVENT_DISP_RDMA1_UNDERRUN:
module = "DISP_RDMA";
break;
case CMDQ_EVENT_DISP_WDMA0_SOF:
case CMDQ_EVENT_DISP_WDMA1_SOF:
case CMDQ_EVENT_DISP_WDMA0_EOF:
case CMDQ_EVENT_DISP_WDMA1_EOF:
module = "DISP_WDMA";
break;
case CMDQ_EVENT_DISP_OVL0_SOF:
case CMDQ_EVENT_DISP_OVL1_SOF:
case CMDQ_EVENT_DISP_OVL0_EOF:
case CMDQ_EVENT_DISP_OVL1_EOF:
module = "DISP_OVL";
break;
case CMDQ_EVENT_DSI_TE:
case CMDQ_EVENT_DISP_COLOR_SOF...CMDQ_EVENT_DISP_PWM0_SOF:
case CMDQ_EVENT_DISP_COLOR_EOF...CMDQ_EVENT_DISP_DPI0_EOF:
case CMDQ_EVENT_MUTEX0_STREAM_EOF...CMDQ_EVENT_MUTEX4_STREAM_EOF:
case CMDQ_SYNC_TOKEN_CONFIG_DIRTY:
case CMDQ_SYNC_TOKEN_STREAM_EOF:
module = "DISP";
break;
case CMDQ_EVENT_UFOD_RAMA0_L0_SOF...CMDQ_EVENT_UFOD_RAMA1_L3_SOF:
case CMDQ_EVENT_UFOD_RAMA0_L0_EOF...CMDQ_EVENT_UFOD_RAMA1_L3_EOF:
module = "DISP_UFOD";
break;
case CMDQ_EVENT_MDP_RDMA0_SOF...CMDQ_EVENT_MDP_WROT_SOF:
case CMDQ_EVENT_MDP_RDMA0_EOF...CMDQ_EVENT_MDP_WROT_READ_EOF:
case CMDQ_EVENT_MUTEX5_STREAM_EOF...CMDQ_EVENT_MUTEX9_STREAM_EOF:
module = "MDP";
break;
case CMDQ_EVENT_ISP_PASS2_2_EOF...CMDQ_EVENT_ISP_PASS1_0_EOF:
case CMDQ_EVENT_ISP_CAMSV_2_PASS1_DONE...CMDQ_EVENT_ISP_SENINF_CAM0_FULL:
module = "ISP";
break;
case CMDQ_EVENT_JPEG_ENC_EOF:
case CMDQ_EVENT_JPEG_DEC_EOF:
module = "JPGE";
break;
case CMDQ_EVENT_VENC_EOF:
case CMDQ_EVENT_VENC_MB_DONE:
case CMDQ_EVENT_VENC_128BYTE_CNT_DONE:
module = "VENC";
break;
default:
module = "CMDQ";
break;
}
return module;
}
const char *cmdq_core_parse_module_from_reg_addr(uint32_t reg_addr)
{
const uint32_t addr_base_and_page = (reg_addr & 0xFFFFF000);
const uint32_t addr_base_shifted = (reg_addr & 0xFFFF0000) >> 16;
const char *module = "CMDQ";
/* for well-known base, we check them with 12-bit mask */
/* defined in mt_reg_base.h */
/* TODO: comfirm with SS if IO_VIRT_TO_PHYS workable when enable device tree? */
#define DECLARE_REG_RANGE(base, name) case base: return #name;
switch (addr_base_and_page) {
DECLARE_REG_RANGE(0x14001000, MDP); /* MDP_RDMA */
DECLARE_REG_RANGE(0x14002000, MDP); /* MDP_RSZ0 */
DECLARE_REG_RANGE(0x14003000, MDP); /* MDP_RSZ1 */
DECLARE_REG_RANGE(0x14004000, MDP); /* MDP_WDMA */
DECLARE_REG_RANGE(0x14005000, MDP); /* MDP_WROT */
DECLARE_REG_RANGE(0x14006000, MDP); /* MDP_TDSHP */
DECLARE_REG_RANGE(0x1400C000, COLOR); /* DISP_COLOR */
DECLARE_REG_RANGE(0x1400D000, CCORR); /* DISP_CCORR */
DECLARE_REG_RANGE(0x14007000, OVL0); /* DISP_OVL0 */
DECLARE_REG_RANGE(0x14008000, OVL1); /* DISP_OVL1 */
DECLARE_REG_RANGE(0x1400E000, AAL); /* DISP_AAL */
DECLARE_REG_RANGE(0x1400F000, AAL); /* DISP_GAMMA */
DECLARE_REG_RANGE(0x17002FFF, VENC); /* VENC */
DECLARE_REG_RANGE(0x17003FFF, JPGENC); /* JPGENC */
DECLARE_REG_RANGE(0x17004FFF, JPGDEC); /* JPGDEC */
}
#undef DECLARE_REG_RANGE
/* for other register address we rely on GCE subsys to group them with */
/* 16-bit mask. */
#undef DECLARE_CMDQ_SUBSYS
#define DECLARE_CMDQ_SUBSYS(msb, id, grp, base) case msb: return #grp;
switch (addr_base_shifted) {
#include "cmdq_subsys.h"
}
#undef DECLARE_CMDQ_SUBSYS
return module;
}
const int32_t cmdq_core_can_module_entry_suspend(EngineStruct *engineList)
{
int32_t status = 0;
int i;
CMDQ_ENG_ENUM e = 0;
CMDQ_ENG_ENUM mdpEngines[] = {
CMDQ_ENG_ISP_IMGI,
CMDQ_ENG_MDP_RDMA0,
CMDQ_ENG_MDP_RSZ0,
CMDQ_ENG_MDP_RSZ1,
CMDQ_ENG_MDP_TDSHP0,
CMDQ_ENG_MDP_WROT0,
CMDQ_ENG_MDP_WDMA
};
for (i = 0; i < (sizeof(mdpEngines) / sizeof(CMDQ_ENG_ENUM)); ++i) {
e = mdpEngines[i];
if (0 != engineList[e].userCount) {
CMDQ_ERR("suspend but engine %d has userCount %d, owner=%d\n",
e, engineList[e].userCount, engineList[e].currOwner);
status = -EBUSY;
}
}
return status;
}
ssize_t cmdq_core_print_status_clock(char *buf)
{
int32_t length = 0;
char *pBuffer = buf;
#ifdef CMDQ_PWR_AWARE
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
pBuffer += sprintf(pBuffer, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE));
#endif
length = pBuffer - buf;
return length;
}
void cmdq_core_print_status_seq_clock(struct seq_file *m)
{
#ifdef CMDQ_PWR_AWARE
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
seq_printf(m, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE));
#endif
}
void cmdq_core_enable_common_clock_locked_impl(bool enable)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
CMDQ_VERBOSE("[CLOCK] Enable SMI & LARB0 Clock\n");
enable_clock(MT_CG_DISP0_SMI_COMMON, "CMDQ_MDP");
//enable_clock(MT_CG_DISP0_SMI_LARB0, "CMDQ_MDP");
m4u_larb0_enable("CMDQ_MDP");
#if 0
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
CMDQ_LOG("[CLOCK] enable MT_CG_DISP0_MUTEX_32K\n");
enable_clock(MT_CG_DISP0_MUTEX_32K, "CMDQ_MDP");
#endif
} else {
CMDQ_VERBOSE("[CLOCK] Disable SMI & LARB0 Clock\n");
/* disable, reverse the sequence */
//disable_clock(MT_CG_DISP0_SMI_LARB0, "CMDQ_MDP");
m4u_larb0_disable("CMDQ_MDP");
disable_clock(MT_CG_DISP0_SMI_COMMON, "CMDQ_MDP");
#if 0
/* MT_CG_DISP0_MUTEX_32K is removed in this platform */
CMDQ_LOG("[CLOCK] disable MT_CG_DISP0_MUTEX_32K\n");
disable_clock(MT_CG_DISP0_MUTEX_32K, "CMDQ_MDP");
#endif
}
#endif /* CMDQ_PWR_AWARE */
}
void cmdq_core_enable_gce_clock_locked_impl(bool enable)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
CMDQ_VERBOSE("[CLOCK] Enable CMDQ(GCE) Clock\n");
cmdq_core_enable_cmdq_clock_locked_impl(enable, CMDQ_DRIVER_DEVICE_NAME);
} else {
CMDQ_VERBOSE("[CLOCK] Disable CMDQ(GCE) Clock\n");
cmdq_core_enable_cmdq_clock_locked_impl(enable, CMDQ_DRIVER_DEVICE_NAME);
}
#endif /* CMDQ_PWR_AWARE */
}
void cmdq_core_enable_cmdq_clock_locked_impl(bool enable, char *deviceName)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
enable_clock(MT_CG_INFRA_GCE, deviceName);
} else {
disable_clock(MT_CG_INFRA_GCE, deviceName);
}
#endif /* CMDQ_PWR_AWARE */
}
const char* cmdq_core_parse_error_module_by_hwflag_impl(struct TaskStruct *pTask)
{
const char *module = NULL;
const uint32_t ISP_ONLY[2] = {
((1LL << CMDQ_ENG_ISP_IMGI) | (1LL << CMDQ_ENG_ISP_IMG2O)),
((1LL << CMDQ_ENG_ISP_IMGI) | (1LL << CMDQ_ENG_ISP_IMG2O) | (1LL << CMDQ_ENG_ISP_IMGO))};
/* common part for both normal and secure path */
/* for JPEG scenario, use HW flag is sufficient */
if (pTask->engineFlag & (1LL << CMDQ_ENG_JPEG_ENC)) {
module = "JPGENC";
} else if (pTask->engineFlag & (1LL << CMDQ_ENG_JPEG_DEC)) {
module = "JPGDEC";
} else if ((ISP_ONLY[0] == pTask->engineFlag) || (ISP_ONLY[1] == pTask->engineFlag)) {
module = "ISP_ONLY";
} else if (cmdq_core_is_disp_scenario(pTask->scenario)) {
module = "DISP";
}
/* for secure path, use HW flag is sufficient */
do {
if (NULL != module) {
break;
}
if (false == pTask->secData.isSecure) {
/* normal path, need parse current running instruciton for more detail */
break;
}
else if (CMDQ_ENG_MDP_GROUP_FLAG(pTask->engineFlag)) {
module = "MDP";
break;
}
module = "CMDQ";
} while(0);
/* other case, we need to analysis instruction for more detail */
return module;
}
void cmdq_core_dump_mmsys_config(void)
{
int i = 0;
uint32_t value = 0;
const static struct RegDef configRegisters[] = {
{0x01c, "ISP_MOUT_EN"},
{0x020, "MDP_RDMA_MOUT_EN"},
{0x024, "MDP_PRZ0_MOUT_EN"},
{0x028, "MDP_PRZ1_MOUT_EN"},
{0x02C, "MDP_TDSHP_MOUT_EN"},
{0x030, "DISP_OVL0_MOUT_EN"},
{0x034, "DISP_OVL1_MOUT_EN"},
{0x038, "DISP_DITHER_MOUT_EN"},
{0x03C, "DISP_UFOE_MOUT_EN"},
/* {0x040, "MMSYS_MOUT_RST"}, */
{0x044, "MDP_PRZ0_SEL_IN"},
{0x048, "MDP_PRZ1_SEL_IN"},
{0x04C, "MDP_TDSHP_SEL_IN"},
{0x050, "MDP_WDMA_SEL_IN"},
{0x054, "MDP_WROT_SEL_IN"},
{0x058, "DISP_COLOR_SEL_IN"},
{0x05C, "DISP_WDMA_SEL_IN"},
{0x060, "DISP_UFOE_SEL_IN"},
{0x064, "DSI0_SEL_IN"},
{0x068, "DPI0_SEL_IN"},
{0x06C, "DISP_RDMA0_SOUT_SEL_IN"},
{0x070, "DISP_RDMA1_SOUT_SEL_IN"},
{0x0F0, "MMSYS_MISC"},
/* ACK and REQ related */
{0x8a0, "DISP_DL_VALID_0"},
{0x8a4, "DISP_DL_VALID_1"},
{0x8a8, "DISP_DL_READY_0"},
{0x8ac, "DISP_DL_READY_1"},
{0x8b0, "MDP_DL_VALID_0"},
{0x8b4, "MDP_DL_READY_0"}
};
for (i = 0; i < sizeof(configRegisters) / sizeof(configRegisters[0]); ++i) {
value = CMDQ_REG_GET16(MMSYS_CONFIG_BASE + configRegisters[i].offset);
CMDQ_ERR("%s: 0x%08x\n", configRegisters[i].name, value);
}
return;
}
void cmdq_core_dump_clock_gating(void)
{
uint32_t value[3] = { 0 };
value[0] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x100);
value[1] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x110);
/* value[2] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x890); */
CMDQ_ERR("MMSYS_CG_CON0(deprecated): 0x%08x, MMSYS_CG_CON1: 0x%08x\n", value[0], value[1]);
/* CMDQ_ERR("MMSYS_DUMMY_REG: 0x%08x\n", value[2]); */
#ifndef CONFIG_MTK_FPGA
CMDQ_ERR("ISPSys clock state %d\n", subsys_is_on(SYS_ISP));
CMDQ_ERR("DisSys clock state %d\n", subsys_is_on(SYS_DIS));
CMDQ_ERR("VDESys clock state %d\n", subsys_is_on(SYS_VDE));
#endif
}
int cmdq_core_dump_smi(const int showSmiDump)
{
#if 0
int isSMIHang = 0;
#ifndef CONFIG_MTK_FPGA
isSMIHang = smi_debug_bus_hanging_detect(
SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC,
showSmiDump);
isSMIHang = smi_debug_bus_hanging_detect_ext(
SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC,
showSmiDump, 1);
CMDQ_ERR("SMI Hang? = %d\n", isSMIHang);
#endif
return isSMIHang;
#else
CMDQ_LOG("[WARNING]not enable SMI dump now\n");
return 0;
#endif
}
void cmdq_core_dump_secure_metadata(cmdqSecDataStruct *pSecData)
{
uint32_t i = 0;
cmdqSecAddrMetadataStruct *pAddr = NULL;
if (NULL == pSecData) {
return;
}
pAddr = (cmdqSecAddrMetadataStruct *)(CMDQ_U32_PTR(pSecData->addrMetadatas));
CMDQ_LOG("========= pSecData: %p dump =========\n", pSecData);
CMDQ_LOG("count:%d(%d), enginesNeedDAPC:0x%llx, enginesPortSecurity:0x%llx\n",
pSecData->addrMetadataCount, pSecData->addrMetadataMaxCount,
pSecData->enginesNeedDAPC, pSecData->enginesNeedPortSecurity);
if (NULL == pAddr) {
return;
}
for (i = 0; i < pSecData->addrMetadataCount; i++) {
CMDQ_LOG("idx:%d, type:%d, baseHandle:%x, offset:%d, size:%d, port:%d\n",
i, pAddr[i].type, pAddr[i].baseHandle, pAddr[i].offset, pAddr[i].size, pAddr[i].port);
}
}
uint64_t cmdq_rec_flag_from_scenario(CMDQ_SCENARIO_ENUM scn)
{
uint64_t flag = 0;
switch (scn) {
case CMDQ_SCENARIO_JPEG_DEC:
flag = (1LL << CMDQ_ENG_JPEG_DEC);
break;
case CMDQ_SCENARIO_PRIMARY_DISP:
flag = (1LL << CMDQ_ENG_DISP_OVL0) |
(1LL << CMDQ_ENG_DISP_COLOR0) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD);
break;
case CMDQ_SCENARIO_PRIMARY_MEMOUT:
flag = 0LL;
break;
case CMDQ_SCENARIO_PRIMARY_ALL:
flag = ((1LL << CMDQ_ENG_DISP_OVL0) |
(1LL << CMDQ_ENG_DISP_WDMA0) |
(1LL << CMDQ_ENG_DISP_COLOR0) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD));
break;
case CMDQ_SCENARIO_SUB_DISP:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) |
(1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case CMDQ_SCENARIO_SUB_MEMOUT:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) | (1LL << CMDQ_ENG_DISP_WDMA1));
break;
case CMDQ_SCENARIO_SUB_ALL:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) |
(1LL << CMDQ_ENG_DISP_WDMA1) |
(1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case CMDQ_SCENARIO_RDMA0_DISP:
flag = ((1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << CMDQ_ENG_DISP_DSI0_CMD));
break;
case CMDQ_SCENARIO_RDMA0_COLOR0_DISP:
flag = ((1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_COLOR0) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD));
break;
case CMDQ_SCENARIO_MHL_DISP:
case CMDQ_SCENARIO_RDMA1_DISP:
flag = ((1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case CMDQ_SCENARIO_TRIGGER_LOOP:
/* Trigger loop does not related to any HW by itself. */
flag = 0LL;
break;
case CMDQ_SCENARIO_USER_SPACE:
/* user space case, engine flag is passed seprately */
flag = 0LL;
break;
case CMDQ_SCENARIO_DEBUG:
case CMDQ_SCENARIO_DEBUG_PREFETCH:
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_ESD_CHECK:
case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE:
/* ESD check uses separate thread (not config, not trigger) */
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_COLOR:
case CMDQ_SCENARIO_USER_DISP_COLOR:
/* color path */
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_MIRROR_MODE:
flag = 0LL;
break;
case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH:
case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH:
/* secure path */
flag = 0LL;
break;
case CMDQ_SCENARIO_SECURE_NOTIFY_LOOP:
flag = 0LL;
break;
default:
CMDQ_ERR("Unknown scenario type %d\n", scn);
flag = 0LL;
break;
}
return flag;
}
void cmdq_core_gpr_dump(void)
{
int i = 0;
long offset = 0;
uint32_t value = 0;
CMDQ_LOG("========= GPR dump ========= \n");
for (i = 0; i < 16; i++) {
offset = CMDQ_GPR_R32(i);
value = CMDQ_REG_GET32(offset);
CMDQ_LOG("[GPR %2d]+0x%lx = 0x%08x\n", i, offset, value);
}
CMDQ_LOG("========= GPR dump ========= \n");
return;
}
void cmdq_test_setup(void)
{
/* unconditionally set CMDQ_SYNC_TOKEN_CONFIG_ALLOW and mutex STREAM_DONE */
/* so that DISPSYS scenarios may pass check. */
cmdqCoreSetEvent(CMDQ_SYNC_TOKEN_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX0_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX1_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX2_STREAM_EOF);
cmdqCoreSetEvent(CMDQ_EVENT_MUTEX3_STREAM_EOF);
}
void cmdq_test_cleanup(void)
{
return; /* do nothing */
}
| Java |
/* Copyright (c) 2008-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/ratelimit.h>
#include <linux/workqueue.h>
#include <linux/pm_runtime.h>
#include <linux/diagchar.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/of.h>
#include <linux/kmemleak.h>
#ifdef CONFIG_DIAG_OVER_USB
#include <mach/usbdiag.h>
#endif
#include <mach/msm_smd.h>
#include <mach/socinfo.h>
#include <mach/restart.h>
#include "diagmem.h"
#include "diagchar.h"
#include "diagfwd.h"
#include "diagfwd_cntl.h"
#include "diagfwd_hsic.h"
#include "diagchar_hdlc.h"
#ifdef CONFIG_DIAG_SDIO_PIPE
#include "diagfwd_sdio.h"
#endif
#include "diag_dci.h"
#include "diag_masks.h"
#include "diagfwd_bridge.h"
#define MODE_CMD 41
#define RESET_ID 2
int diag_debug_buf_idx;
unsigned char diag_debug_buf[1024];
static unsigned int buf_tbl_size = 8; /*Number of entries in table of buffers */
struct diag_master_table entry;
struct diag_send_desc_type send = { NULL, NULL, DIAG_STATE_START, 0 };
struct diag_hdlc_dest_type enc = { NULL, NULL, 0 };
int wrap_enabled;
uint16_t wrap_count;
void encode_rsp_and_send(int buf_length)
{
struct diag_smd_info *data = &(driver->smd_data[MODEM_DATA]);
send.state = DIAG_STATE_START;
send.pkt = driver->apps_rsp_buf;
send.last = (void *)(driver->apps_rsp_buf + buf_length);
send.terminate = 1;
if (!data->in_busy_1) {
enc.dest = data->buf_in_1;
enc.dest_last = (void *)(data->buf_in_1 + APPS_BUF_SIZE - 1);
diag_hdlc_encode(&send, &enc);
data->write_ptr_1->buf = data->buf_in_1;
data->write_ptr_1->length = (int)(enc.dest -
(void *)(data->buf_in_1));
data->in_busy_1 = 1;
diag_device_write(data->buf_in_1, data->peripheral,
data->write_ptr_1);
memset(driver->apps_rsp_buf, '\0', APPS_BUF_SIZE);
}
}
/* Determine if this device uses a device tree */
#ifdef CONFIG_OF
static int has_device_tree(void)
{
struct device_node *node;
node = of_find_node_by_path("/");
if (node) {
of_node_put(node);
return 1;
}
return 0;
}
#else
static int has_device_tree(void)
{
return 0;
}
#endif
int chk_config_get_id(void)
{
/* For all Fusion targets, Modem will always be present */
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa())
return 0;
if (driver->use_device_tree) {
if (machine_is_msm8974())
return MSM8974_TOOLS_ID;
else
return 0;
} else {
switch (socinfo_get_msm_cpu()) {
case MSM_CPU_8X60:
return APQ8060_TOOLS_ID;
case MSM_CPU_8960:
case MSM_CPU_8960AB:
return AO8960_TOOLS_ID;
case MSM_CPU_8064:
case MSM_CPU_8064AB:
case MSM_CPU_8064AA:
return APQ8064_TOOLS_ID;
case MSM_CPU_8930:
case MSM_CPU_8930AA:
case MSM_CPU_8930AB:
return MSM8930_TOOLS_ID;
case MSM_CPU_8974:
return MSM8974_TOOLS_ID;
case MSM_CPU_8625:
return MSM8625_TOOLS_ID;
default:
return 0;
}
}
}
/*
* This will return TRUE for targets which support apps only mode and hence SSR.
* This applies to 8960 and newer targets.
*/
int chk_apps_only(void)
{
if (driver->use_device_tree)
return 1;
switch (socinfo_get_msm_cpu()) {
case MSM_CPU_8960:
case MSM_CPU_8960AB:
case MSM_CPU_8064:
case MSM_CPU_8064AB:
case MSM_CPU_8064AA:
case MSM_CPU_8930:
case MSM_CPU_8930AA:
case MSM_CPU_8930AB:
case MSM_CPU_8627:
case MSM_CPU_9615:
case MSM_CPU_8974:
return 1;
default:
return 0;
}
}
/*
* This will return TRUE for targets which support apps as master.
* Thus, SW DLOAD and Mode Reset are supported on apps processor.
* This applies to 8960 and newer targets.
*/
int chk_apps_master(void)
{
if (driver->use_device_tree)
return 1;
else if (soc_class_is_msm8960() || soc_class_is_msm8930() ||
soc_class_is_apq8064() || cpu_is_msm9615())
return 1;
else
return 0;
}
int chk_polling_response(void)
{
if (!(driver->polling_reg_flag) && chk_apps_master())
/*
* If the apps processor is master and no other processor
* has registered to respond for polling
*/
return 1;
else if (!(driver->smd_data[MODEM_DATA].ch) &&
!(chk_apps_master()))
/*
* If the apps processor is not the master and the modem
* is not up
*/
return 1;
else
return 0;
}
/*
* This function should be called if you feel that the logging process may
* need to be woken up. For instance, if the logging mode is MEMORY_DEVICE MODE
* and while trying to read data from a SMD data channel there are no buffers
* available to read the data into, then this function should be called to
* determine if the logging process needs to be woken up.
*/
void chk_logging_wakeup(void)
{
int i;
/* Find the index of the logging process */
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid ==
driver->logging_process_id)
break;
if (i < driver->num_clients) {
/* At very high logging rates a race condition can
* occur where the buffers containing the data from
* an smd channel are all in use, but the data_ready
* flag is cleared. In this case, the buffers never
* have their data read/logged. Detect and remedy this
* situation.
*/
if ((driver->data_ready[i] & USER_SPACE_DATA_TYPE) == 0) {
driver->data_ready[i] |= USER_SPACE_DATA_TYPE;
pr_debug("diag: Force wakeup of logging process\n");
wake_up_interruptible(&driver->wait_q);
}
}
}
/* Process the data read from the smd data channel */
int diag_process_smd_read_data(struct diag_smd_info *smd_info, void *buf,
int total_recd)
{
struct diag_request *write_ptr_modem = NULL;
int *in_busy_ptr = 0;
if (smd_info->buf_in_1 == buf) {
write_ptr_modem = smd_info->write_ptr_1;
in_busy_ptr = &smd_info->in_busy_1;
} else if (smd_info->buf_in_2 == buf) {
write_ptr_modem = smd_info->write_ptr_2;
in_busy_ptr = &smd_info->in_busy_2;
} else {
pr_err("diag: In %s, no match for in_busy_1\n", __func__);
}
if (write_ptr_modem) {
write_ptr_modem->length = total_recd;
*in_busy_ptr = 1;
diag_device_write(buf, smd_info->peripheral, write_ptr_modem);
}
return 0;
}
void diag_smd_send_req(struct diag_smd_info *smd_info)
{
void *buf = NULL, *temp_buf = NULL;
int total_recd = 0, r = 0, pkt_len;
int loop_count = 0;
int notify = 0;
if (!smd_info) {
pr_err("diag: In %s, no smd info. Not able to read.\n",
__func__);
return;
}
if (!smd_info->in_busy_1)
buf = smd_info->buf_in_1;
else if ((smd_info->type == SMD_DATA_TYPE) && !smd_info->in_busy_2)
buf = smd_info->buf_in_2;
if (smd_info->ch && buf) {
temp_buf = buf;
pkt_len = smd_cur_packet_size(smd_info->ch);
while (pkt_len && (pkt_len != total_recd)) {
loop_count++;
r = smd_read_avail(smd_info->ch);
pr_debug("diag: In %s, received pkt %d %d\n",
__func__, r, total_recd);
if (!r) {
/* Nothing to read from SMD */
wait_event(driver->smd_wait_q,
((smd_info->ch == 0) ||
smd_read_avail(smd_info->ch)));
/* If the smd channel is open */
if (smd_info->ch) {
pr_debug("diag: In %s, return from wait_event\n",
__func__);
continue;
} else {
pr_debug("diag: In %s, return from wait_event ch closed\n",
__func__);
return;
}
}
total_recd += r;
if (total_recd > IN_BUF_SIZE) {
if (total_recd < MAX_IN_BUF_SIZE) {
pr_err("diag: In %s, SMD sending in packets up to %d bytes\n",
__func__, total_recd);
buf = krealloc(buf, total_recd,
GFP_KERNEL);
} else {
pr_err("diag: In %s, SMD sending in packets more than %d bytes\n",
__func__, MAX_IN_BUF_SIZE);
return;
}
}
if (pkt_len < r) {
pr_err("diag: In %s, SMD sending incorrect pkt\n",
__func__);
return;
}
if (pkt_len > r) {
pr_err("diag: In %s, SMD sending partial pkt %d %d %d %d %d %d\n",
__func__, pkt_len, r, total_recd, loop_count,
smd_info->peripheral, smd_info->type);
}
/* keep reading for complete packet */
smd_read(smd_info->ch, temp_buf, r);
temp_buf += r;
}
if (total_recd > 0) {
if (!buf) {
pr_err("diag: Out of diagmem for Modem\n");
} else if (smd_info->process_smd_read_data) {
notify = smd_info->process_smd_read_data(
smd_info, buf, total_recd);
/* Poll SMD channels to check for data */
if (notify)
diag_smd_notify(smd_info,
SMD_EVENT_DATA);
}
}
} else if (smd_info->ch && !buf &&
(driver->logging_mode == MEMORY_DEVICE_MODE)) {
chk_logging_wakeup();
}
}
void diag_read_smd_work_fn(struct work_struct *work)
{
struct diag_smd_info *smd_info = container_of(work,
struct diag_smd_info,
diag_read_smd_work);
diag_smd_send_req(smd_info);
}
int diag_device_write(void *buf, int data_type, struct diag_request *write_ptr)
{
int i, err = 0, index;
index = 0;
if (driver->logging_mode == MEMORY_DEVICE_MODE) {
if (data_type == APPS_DATA) {
for (i = 0; i < driver->poolsize_write_struct; i++)
if (driver->buf_tbl[i].length == 0) {
driver->buf_tbl[i].buf = buf;
driver->buf_tbl[i].length =
driver->used;
#ifdef DIAG_DEBUG
pr_debug("diag: ENQUEUE buf ptr"
" and length is %x , %d\n",
(unsigned int)(driver->buf_
tbl[i].buf), driver->buf_tbl[i].length);
#endif
break;
}
}
#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) {
unsigned long flags;
int foundIndex = -1;
index = data_type - HSIC_DATA;
spin_lock_irqsave(&diag_hsic[index].hsic_spinlock,
flags);
for (i = 0; i < diag_hsic[index].poolsize_hsic_write;
i++) {
if (diag_hsic[index].hsic_buf_tbl[i].length
== 0) {
diag_hsic[index].hsic_buf_tbl[i].buf
= buf;
diag_hsic[index].hsic_buf_tbl[i].length
= diag_bridge[index].write_len;
diag_hsic[index].
num_hsic_buf_tbl_entries++;
foundIndex = i;
break;
}
}
spin_unlock_irqrestore(&diag_hsic[index].hsic_spinlock,
flags);
if (foundIndex == -1)
err = -1;
else
pr_debug("diag: ENQUEUE HSIC buf ptr and length is %x , %d, ch %d\n",
(unsigned int)buf,
diag_bridge[index].write_len, index);
}
#endif
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid ==
driver->logging_process_id)
break;
if (i < driver->num_clients) {
driver->data_ready[i] |= USER_SPACE_DATA_TYPE;
pr_debug("diag: wake up logging process\n");
wake_up_interruptible(&driver->wait_q);
} else
return -EINVAL;
} else if (driver->logging_mode == NO_LOGGING_MODE) {
if ((data_type >= 0) && (data_type < NUM_SMD_DATA_CHANNELS)) {
driver->smd_data[data_type].in_busy_1 = 0;
driver->smd_data[data_type].in_busy_2 = 0;
queue_work(driver->diag_wq,
&(driver->smd_data[data_type].
diag_read_smd_work));
}
#ifdef CONFIG_DIAG_SDIO_PIPE
else if (data_type == SDIO_DATA) {
driver->in_busy_sdio = 0;
queue_work(driver->diag_sdio_wq,
&(driver->diag_read_sdio_work));
}
#endif
#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) {
index = data_type - HSIC_DATA;
if (diag_hsic[index].hsic_ch)
queue_work(diag_bridge[index].wq,
&(diag_hsic[index].
diag_read_hsic_work));
}
#endif
err = -1;
}
#ifdef CONFIG_DIAG_OVER_USB
else if (driver->logging_mode == USB_MODE) {
if (data_type == APPS_DATA) {
driver->write_ptr_svc = (struct diag_request *)
(diagmem_alloc(driver, sizeof(struct diag_request),
POOL_TYPE_WRITE_STRUCT));
if (driver->write_ptr_svc) {
driver->write_ptr_svc->length = driver->used;
driver->write_ptr_svc->buf = buf;
err = usb_diag_write(driver->legacy_ch,
driver->write_ptr_svc);
} else
err = -1;
} else if ((data_type >= 0) &&
(data_type < NUM_SMD_DATA_CHANNELS)) {
write_ptr->buf = buf;
#ifdef DIAG_DEBUG
printk(KERN_INFO "writing data to USB,"
"pkt length %d\n", write_ptr->length);
print_hex_dump(KERN_DEBUG, "Written Packet Data to"
" USB: ", 16, 1, DUMP_PREFIX_ADDRESS,
buf, write_ptr->length, 1);
#endif /* DIAG DEBUG */
err = usb_diag_write(driver->legacy_ch, write_ptr);
}
#ifdef CONFIG_DIAG_SDIO_PIPE
else if (data_type == SDIO_DATA) {
if (machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa()) {
write_ptr->buf = buf;
err = usb_diag_write(driver->mdm_ch, write_ptr);
} else
pr_err("diag: Incorrect sdio data "
"while USB write\n");
}
#endif
#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) {
index = data_type - HSIC_DATA;
if (diag_hsic[index].hsic_device_enabled) {
struct diag_request *write_ptr_mdm;
write_ptr_mdm = (struct diag_request *)
diagmem_alloc(driver,
sizeof(struct diag_request),
index +
POOL_TYPE_HSIC_WRITE);
if (write_ptr_mdm) {
write_ptr_mdm->buf = buf;
write_ptr_mdm->length =
diag_bridge[index].write_len;
write_ptr_mdm->context = (void *)index;
err = usb_diag_write(
diag_bridge[index].ch, write_ptr_mdm);
/* Return to the pool immediately */
if (err) {
diagmem_free(driver,
write_ptr_mdm,
index +
POOL_TYPE_HSIC_WRITE);
pr_err_ratelimited("diag: HSIC write failure, err: %d, ch %d\n",
err, index);
}
} else {
pr_err("diag: allocate write fail\n");
err = -1;
}
} else {
pr_err("diag: Incorrect HSIC data "
"while USB write\n");
err = -1;
}
} else if (data_type == SMUX_DATA) {
write_ptr->buf = buf;
write_ptr->context = (void *)SMUX;
pr_debug("diag: writing SMUX data\n");
err = usb_diag_write(diag_bridge[SMUX].ch,
write_ptr);
}
#endif
APPEND_DEBUG('d');
}
#endif /* DIAG OVER USB */
return err;
}
static void diag_update_pkt_buffer(unsigned char *buf)
{
unsigned char *ptr = driver->pkt_buf;
unsigned char *temp = buf;
mutex_lock(&driver->diagchar_mutex);
if (CHK_OVERFLOW(ptr, ptr, ptr + PKT_SIZE, driver->pkt_length))
memcpy(ptr, temp , driver->pkt_length);
else
printk(KERN_CRIT " Not enough buffer space for PKT_RESP\n");
mutex_unlock(&driver->diagchar_mutex);
}
void diag_update_userspace_clients(unsigned int type)
{
int i;
mutex_lock(&driver->diagchar_mutex);
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid != 0)
driver->data_ready[i] |= type;
wake_up_interruptible(&driver->wait_q);
mutex_unlock(&driver->diagchar_mutex);
}
void diag_update_sleeping_process(int process_id, int data_type)
{
int i;
mutex_lock(&driver->diagchar_mutex);
for (i = 0; i < driver->num_clients; i++)
if (driver->client_map[i].pid == process_id) {
driver->data_ready[i] |= data_type;
break;
}
wake_up_interruptible(&driver->wait_q);
mutex_unlock(&driver->diagchar_mutex);
}
static int diag_check_mode_reset(unsigned char *buf)
{
int is_mode_reset = 0;
if (chk_apps_master() && (int)(*(char *)buf) == MODE_CMD)
if ((int)(*(char *)(buf+1)) == RESET_ID)
is_mode_reset = 1;
return is_mode_reset;
}
void diag_send_data(struct diag_master_table entry, unsigned char *buf,
int len, int type)
{
driver->pkt_length = len;
if (entry.process_id != NON_APPS_PROC && type != MODEM_DATA) {
diag_update_pkt_buffer(buf);
diag_update_sleeping_process(entry.process_id, PKT_TYPE);
} else {
if (len > 0) {
if ((entry.client_id >= 0) &&
(entry.client_id < NUM_SMD_DATA_CHANNELS)) {
int index = entry.client_id;
if (driver->smd_data[index].ch) {
if ((index == MODEM_DATA) &&
diag_check_mode_reset(buf)) {
return;
}
smd_write(driver->smd_data[index].ch,
buf, len);
} else {
pr_err("diag: In %s, smd channel %d not open\n",
__func__, index);
}
} else {
pr_alert("diag: In %s, incorrect channel: %d",
__func__, entry.client_id);
}
}
}
}
static int diag_process_apps_pkt(unsigned char *buf, int len)
{
uint16_t subsys_cmd_code;
int subsys_id, ssid_first, ssid_last, ssid_range;
int packet_type = 1, i, cmd_code;
unsigned char *temp = buf;
int data_type;
int mask_ret;
#if defined(CONFIG_DIAG_OVER_USB)
unsigned char *ptr;
#endif
/* Check if the command is a supported mask command */
mask_ret = diag_process_apps_masks(buf, len);
if (mask_ret <= 0)
return mask_ret;
/* Check for registered clients and forward packet to apropriate proc */
cmd_code = (int)(*(char *)buf);
temp++;
subsys_id = (int)(*(char *)temp);
temp++;
subsys_cmd_code = *(uint16_t *)temp;
temp += 2;
data_type = APPS_DATA;
/* Dont send any command other than mode reset */
if (chk_apps_master() && cmd_code == MODE_CMD) {
if (subsys_id != RESET_ID)
data_type = MODEM_DATA;
}
pr_debug("diag: %d %d %d", cmd_code, subsys_id, subsys_cmd_code);
for (i = 0; i < diag_max_reg; i++) {
entry = driver->table[i];
if (entry.process_id != NO_PROCESS) {
if (entry.cmd_code == cmd_code && entry.subsys_id ==
subsys_id && entry.cmd_code_lo <=
subsys_cmd_code &&
entry.cmd_code_hi >= subsys_cmd_code) {
diag_send_data(entry, buf, len, data_type);
packet_type = 0;
} else if (entry.cmd_code == 255
&& cmd_code == 75) {
if (entry.subsys_id ==
subsys_id &&
entry.cmd_code_lo <=
subsys_cmd_code &&
entry.cmd_code_hi >=
subsys_cmd_code) {
diag_send_data(entry, buf, len,
data_type);
packet_type = 0;
}
} else if (entry.cmd_code == 255 &&
entry.subsys_id == 255) {
if (entry.cmd_code_lo <=
cmd_code &&
entry.
cmd_code_hi >= cmd_code) {
diag_send_data(entry, buf, len,
data_type);
packet_type = 0;
}
}
}
}
#if defined(CONFIG_DIAG_OVER_USB)
/* Check for the command/respond msg for the maximum packet length */
if ((*buf == 0x4b) && (*(buf+1) == 0x12) &&
(*(uint16_t *)(buf+2) == 0x0055)) {
for (i = 0; i < 4; i++)
*(driver->apps_rsp_buf+i) = *(buf+i);
*(uint32_t *)(driver->apps_rsp_buf+4) = PKT_SIZE;
encode_rsp_and_send(7);
return 0;
}
/* Check for Apps Only & get event mask request */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only() &&
*buf == 0x81) {
driver->apps_rsp_buf[0] = 0x81;
driver->apps_rsp_buf[1] = 0x0;
*(uint16_t *)(driver->apps_rsp_buf + 2) = 0x0;
*(uint16_t *)(driver->apps_rsp_buf + 4) = EVENT_LAST_ID + 1;
for (i = 0; i < EVENT_LAST_ID/8 + 1; i++)
*(unsigned char *)(driver->apps_rsp_buf + 6 + i) = 0x0;
encode_rsp_and_send(6 + EVENT_LAST_ID/8);
return 0;
}
/* Get log ID range & Check for Apps Only */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only()
&& (*buf == 0x73) && *(int *)(buf+4) == 1) {
driver->apps_rsp_buf[0] = 0x73;
*(int *)(driver->apps_rsp_buf + 4) = 0x1; /* operation ID */
*(int *)(driver->apps_rsp_buf + 8) = 0x0; /* success code */
*(int *)(driver->apps_rsp_buf + 12) = LOG_GET_ITEM_NUM(LOG_0);
*(int *)(driver->apps_rsp_buf + 16) = LOG_GET_ITEM_NUM(LOG_1);
*(int *)(driver->apps_rsp_buf + 20) = LOG_GET_ITEM_NUM(LOG_2);
*(int *)(driver->apps_rsp_buf + 24) = LOG_GET_ITEM_NUM(LOG_3);
*(int *)(driver->apps_rsp_buf + 28) = LOG_GET_ITEM_NUM(LOG_4);
*(int *)(driver->apps_rsp_buf + 32) = LOG_GET_ITEM_NUM(LOG_5);
*(int *)(driver->apps_rsp_buf + 36) = LOG_GET_ITEM_NUM(LOG_6);
*(int *)(driver->apps_rsp_buf + 40) = LOG_GET_ITEM_NUM(LOG_7);
*(int *)(driver->apps_rsp_buf + 44) = LOG_GET_ITEM_NUM(LOG_8);
*(int *)(driver->apps_rsp_buf + 48) = LOG_GET_ITEM_NUM(LOG_9);
*(int *)(driver->apps_rsp_buf + 52) = LOG_GET_ITEM_NUM(LOG_10);
*(int *)(driver->apps_rsp_buf + 56) = LOG_GET_ITEM_NUM(LOG_11);
*(int *)(driver->apps_rsp_buf + 60) = LOG_GET_ITEM_NUM(LOG_12);
*(int *)(driver->apps_rsp_buf + 64) = LOG_GET_ITEM_NUM(LOG_13);
*(int *)(driver->apps_rsp_buf + 68) = LOG_GET_ITEM_NUM(LOG_14);
*(int *)(driver->apps_rsp_buf + 72) = LOG_GET_ITEM_NUM(LOG_15);
encode_rsp_and_send(75);
return 0;
}
/* Respond to Get SSID Range request message */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only()
&& (*buf == 0x7d) && (*(buf+1) == 0x1)) {
driver->apps_rsp_buf[0] = 0x7d;
driver->apps_rsp_buf[1] = 0x1;
driver->apps_rsp_buf[2] = 0x1;
driver->apps_rsp_buf[3] = 0x0;
/* -1 to un-account for OEM SSID range */
*(int *)(driver->apps_rsp_buf + 4) = MSG_MASK_TBL_CNT - 1;
*(uint16_t *)(driver->apps_rsp_buf + 8) = MSG_SSID_0;
*(uint16_t *)(driver->apps_rsp_buf + 10) = MSG_SSID_0_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 12) = MSG_SSID_1;
*(uint16_t *)(driver->apps_rsp_buf + 14) = MSG_SSID_1_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 16) = MSG_SSID_2;
*(uint16_t *)(driver->apps_rsp_buf + 18) = MSG_SSID_2_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 20) = MSG_SSID_3;
*(uint16_t *)(driver->apps_rsp_buf + 22) = MSG_SSID_3_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 24) = MSG_SSID_4;
*(uint16_t *)(driver->apps_rsp_buf + 26) = MSG_SSID_4_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 28) = MSG_SSID_5;
*(uint16_t *)(driver->apps_rsp_buf + 30) = MSG_SSID_5_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 32) = MSG_SSID_6;
*(uint16_t *)(driver->apps_rsp_buf + 34) = MSG_SSID_6_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 36) = MSG_SSID_7;
*(uint16_t *)(driver->apps_rsp_buf + 38) = MSG_SSID_7_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 40) = MSG_SSID_8;
*(uint16_t *)(driver->apps_rsp_buf + 42) = MSG_SSID_8_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 44) = MSG_SSID_9;
*(uint16_t *)(driver->apps_rsp_buf + 46) = MSG_SSID_9_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 48) = MSG_SSID_10;
*(uint16_t *)(driver->apps_rsp_buf + 50) = MSG_SSID_10_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 52) = MSG_SSID_11;
*(uint16_t *)(driver->apps_rsp_buf + 54) = MSG_SSID_11_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 56) = MSG_SSID_12;
*(uint16_t *)(driver->apps_rsp_buf + 58) = MSG_SSID_12_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 60) = MSG_SSID_13;
*(uint16_t *)(driver->apps_rsp_buf + 62) = MSG_SSID_13_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 64) = MSG_SSID_14;
*(uint16_t *)(driver->apps_rsp_buf + 66) = MSG_SSID_14_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 68) = MSG_SSID_15;
*(uint16_t *)(driver->apps_rsp_buf + 70) = MSG_SSID_15_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 72) = MSG_SSID_16;
*(uint16_t *)(driver->apps_rsp_buf + 74) = MSG_SSID_16_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 76) = MSG_SSID_17;
*(uint16_t *)(driver->apps_rsp_buf + 78) = MSG_SSID_17_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 80) = MSG_SSID_18;
*(uint16_t *)(driver->apps_rsp_buf + 82) = MSG_SSID_18_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 84) = MSG_SSID_19;
*(uint16_t *)(driver->apps_rsp_buf + 86) = MSG_SSID_19_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 88) = MSG_SSID_20;
*(uint16_t *)(driver->apps_rsp_buf + 90) = MSG_SSID_20_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 92) = MSG_SSID_21;
*(uint16_t *)(driver->apps_rsp_buf + 94) = MSG_SSID_21_LAST;
*(uint16_t *)(driver->apps_rsp_buf + 96) = MSG_SSID_22;
*(uint16_t *)(driver->apps_rsp_buf + 98) = MSG_SSID_22_LAST;
encode_rsp_and_send(99);
return 0;
}
/* Check for Apps Only Respond to Get Subsys Build mask */
else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only()
&& (*buf == 0x7d) && (*(buf+1) == 0x2)) {
ssid_first = *(uint16_t *)(buf + 2);
ssid_last = *(uint16_t *)(buf + 4);
ssid_range = 4 * (ssid_last - ssid_first + 1);
/* frame response */
driver->apps_rsp_buf[0] = 0x7d;
driver->apps_rsp_buf[1] = 0x2;
*(uint16_t *)(driver->apps_rsp_buf + 2) = ssid_first;
*(uint16_t *)(driver->apps_rsp_buf + 4) = ssid_last;
driver->apps_rsp_buf[6] = 0x1;
driver->apps_rsp_buf[7] = 0x0;
ptr = driver->apps_rsp_buf + 8;
/* bld time masks */
switch (ssid_first) {
case MSG_SSID_0:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_0[i/4];
break;
case MSG_SSID_1:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_1[i/4];
break;
case MSG_SSID_2:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_2[i/4];
break;
case MSG_SSID_3:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_3[i/4];
break;
case MSG_SSID_4:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_4[i/4];
break;
case MSG_SSID_5:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_5[i/4];
break;
case MSG_SSID_6:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_6[i/4];
break;
case MSG_SSID_7:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_7[i/4];
break;
case MSG_SSID_8:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_8[i/4];
break;
case MSG_SSID_9:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_9[i/4];
break;
case MSG_SSID_10:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_10[i/4];
break;
case MSG_SSID_11:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_11[i/4];
break;
case MSG_SSID_12:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_12[i/4];
break;
case MSG_SSID_13:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_13[i/4];
break;
case MSG_SSID_14:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_14[i/4];
break;
case MSG_SSID_15:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_15[i/4];
break;
case MSG_SSID_16:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_16[i/4];
break;
case MSG_SSID_17:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_17[i/4];
break;
case MSG_SSID_18:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_18[i/4];
break;
case MSG_SSID_19:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_19[i/4];
break;
case MSG_SSID_20:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_20[i/4];
break;
case MSG_SSID_21:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_21[i/4];
break;
case MSG_SSID_22:
for (i = 0; i < ssid_range; i += 4)
*(int *)(ptr + i) = msg_bld_masks_22[i/4];
break;
}
encode_rsp_and_send(8 + ssid_range - 1);
return 0;
}
/* Check for download command */
else if ((cpu_is_msm8x60() || chk_apps_master()) && (*buf == 0x3A)) {
/* send response back */
driver->apps_rsp_buf[0] = *buf;
encode_rsp_and_send(0);
msleep(5000);
/* call download API */
msm_set_restart_mode(RESTART_DLOAD);
printk(KERN_CRIT "diag: download mode set, Rebooting SoC..\n");
kernel_restart(NULL);
/* Not required, represents that command isnt sent to modem */
return 0;
}
/* Check for polling for Apps only DIAG */
else if ((*buf == 0x4b) && (*(buf+1) == 0x32) &&
(*(buf+2) == 0x03)) {
/* If no one has registered for polling */
if (chk_polling_response()) {
/* Respond to polling for Apps only DIAG */
for (i = 0; i < 3; i++)
driver->apps_rsp_buf[i] = *(buf+i);
for (i = 0; i < 13; i++)
driver->apps_rsp_buf[i+3] = 0;
encode_rsp_and_send(15);
return 0;
}
}
/* Return the Delayed Response Wrap Status */
else if ((*buf == 0x4b) && (*(buf+1) == 0x32) &&
(*(buf+2) == 0x04) && (*(buf+3) == 0x0)) {
memcpy(driver->apps_rsp_buf, buf, 4);
driver->apps_rsp_buf[4] = wrap_enabled;
encode_rsp_and_send(4);
return 0;
}
/* Wrap the Delayed Rsp ID */
else if ((*buf == 0x4b) && (*(buf+1) == 0x32) &&
(*(buf+2) == 0x05) && (*(buf+3) == 0x0)) {
wrap_enabled = true;
memcpy(driver->apps_rsp_buf, buf, 4);
driver->apps_rsp_buf[4] = wrap_count;
encode_rsp_and_send(5);
return 0;
}
/* Check for ID for NO MODEM present */
else if (chk_polling_response()) {
/* respond to 0x0 command */
if (*buf == 0x00) {
for (i = 0; i < 55; i++)
driver->apps_rsp_buf[i] = 0;
encode_rsp_and_send(54);
return 0;
}
/* respond to 0x7c command */
else if (*buf == 0x7c) {
driver->apps_rsp_buf[0] = 0x7c;
for (i = 1; i < 8; i++)
driver->apps_rsp_buf[i] = 0;
/* Tools ID for APQ 8060 */
*(int *)(driver->apps_rsp_buf + 8) =
chk_config_get_id();
*(unsigned char *)(driver->apps_rsp_buf + 12) = '\0';
*(unsigned char *)(driver->apps_rsp_buf + 13) = '\0';
encode_rsp_and_send(13);
return 0;
}
}
#endif
return packet_type;
}
#ifdef CONFIG_DIAG_OVER_USB
void diag_send_error_rsp(int index)
{
int i;
if (index > 490) {
pr_err("diag: error response too huge, aborting\n");
return;
}
driver->apps_rsp_buf[0] = 0x13; /* error code 13 */
for (i = 0; i < index; i++)
driver->apps_rsp_buf[i+1] = *(driver->hdlc_buf+i);
encode_rsp_and_send(index - 3);
}
#else
static inline void diag_send_error_rsp(int index) {}
#endif
void diag_process_hdlc(void *data, unsigned len)
{
struct diag_hdlc_decode_type hdlc;
int ret, type = 0;
pr_debug("diag: HDLC decode fn, len of data %d\n", len);
hdlc.dest_ptr = driver->hdlc_buf;
hdlc.dest_size = USB_MAX_OUT_BUF;
hdlc.src_ptr = data;
hdlc.src_size = len;
hdlc.src_idx = 0;
hdlc.dest_idx = 0;
hdlc.escaping = 0;
ret = diag_hdlc_decode(&hdlc);
if (hdlc.dest_idx < 3) {
pr_err("diag: Integer underflow in hdlc processing\n");
return;
}
if (ret) {
type = diag_process_apps_pkt(driver->hdlc_buf,
hdlc.dest_idx - 3);
if (type < 0)
return;
} else if (driver->debug_flag) {
printk(KERN_ERR "Packet dropped due to bad HDLC coding/CRC"
" errors or partial packet received, packet"
" length = %d\n", len);
print_hex_dump(KERN_DEBUG, "Dropped Packet Data: ", 16, 1,
DUMP_PREFIX_ADDRESS, data, len, 1);
driver->debug_flag = 0;
}
/* send error responses from APPS for Central Routing */
if (type == 1 && chk_apps_only()) {
diag_send_error_rsp(hdlc.dest_idx);
type = 0;
}
/* implies this packet is NOT meant for apps */
if (!(driver->smd_data[MODEM_DATA].ch) && type == 1) {
if (chk_apps_only()) {
diag_send_error_rsp(hdlc.dest_idx);
} else { /* APQ 8060, Let Q6 respond */
if (driver->smd_data[LPASS_DATA].ch)
smd_write(driver->smd_data[LPASS_DATA].ch,
driver->hdlc_buf,
hdlc.dest_idx - 3);
}
type = 0;
}
#ifdef DIAG_DEBUG
pr_debug("diag: hdlc.dest_idx = %d", hdlc.dest_idx);
for (i = 0; i < hdlc.dest_idx; i++)
printk(KERN_DEBUG "\t%x", *(((unsigned char *)
driver->hdlc_buf)+i));
#endif /* DIAG DEBUG */
/* ignore 2 bytes for CRC, one for 7E and send */
if ((driver->smd_data[MODEM_DATA].ch) && (ret) && (type) &&
(hdlc.dest_idx > 3)) {
APPEND_DEBUG('g');
smd_write(driver->smd_data[MODEM_DATA].ch,
driver->hdlc_buf, hdlc.dest_idx - 3);
APPEND_DEBUG('h');
#ifdef DIAG_DEBUG
printk(KERN_INFO "writing data to SMD, pkt length %d\n", len);
print_hex_dump(KERN_DEBUG, "Written Packet Data to SMD: ", 16,
1, DUMP_PREFIX_ADDRESS, data, len, 1);
#endif /* DIAG DEBUG */
}
}
#ifdef CONFIG_DIAG_OVER_USB
/* 2+1 for modem ; 2 for LPASS ; 1 for WCNSS */
#define N_LEGACY_WRITE (driver->poolsize + 6)
#define N_LEGACY_READ 1
int diagfwd_connect(void)
{
int err;
int i;
printk(KERN_DEBUG "diag: USB connected\n");
err = usb_diag_alloc_req(driver->legacy_ch, N_LEGACY_WRITE,
N_LEGACY_READ);
if (err)
printk(KERN_ERR "diag: unable to alloc USB req on legacy ch");
driver->usb_connected = 1;
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) {
driver->smd_data[i].in_busy_1 = 0;
driver->smd_data[i].in_busy_2 = 0;
/* Poll SMD data channels to check for data */
queue_work(driver->diag_wq,
&(driver->smd_data[i].diag_read_smd_work));
/* Poll SMD CNTL channels to check for data */
diag_smd_notify(&(driver->smd_cntl[i]), SMD_EVENT_DATA);
}
/* Poll USB channel to check for data*/
queue_work(driver->diag_wq, &(driver->diag_read_work));
#ifdef CONFIG_DIAG_SDIO_PIPE
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) {
if (driver->mdm_ch && !IS_ERR(driver->mdm_ch))
diagfwd_connect_sdio();
else
printk(KERN_INFO "diag: No USB MDM ch");
}
#endif
return 0;
}
int diagfwd_disconnect(void)
{
int i;
printk(KERN_DEBUG "diag: USB disconnected\n");
driver->usb_connected = 0;
driver->debug_flag = 1;
usb_diag_free_req(driver->legacy_ch);
if (driver->logging_mode == USB_MODE) {
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) {
driver->smd_data[i].in_busy_1 = 1;
driver->smd_data[i].in_busy_2 = 1;
}
}
#ifdef CONFIG_DIAG_SDIO_PIPE
if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa())
if (driver->mdm_ch && !IS_ERR(driver->mdm_ch))
diagfwd_disconnect_sdio();
#endif
/* TBD - notify and flow control SMD */
return 0;
}
int diagfwd_write_complete(struct diag_request *diag_write_ptr)
{
unsigned char *buf = diag_write_ptr->buf;
int found_it = 0;
int i;
/* Determine if the write complete is for data from modem/apps/q6 */
/* Need a context variable here instead */
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) {
struct diag_smd_info *data = &(driver->smd_data[i]);
if (buf == (void *)data->buf_in_1) {
data->in_busy_1 = 0;
queue_work(driver->diag_wq,
&(data->diag_read_smd_work));
found_it = 1;
break;
} else if (buf == (void *)data->buf_in_2) {
data->in_busy_2 = 0;
queue_work(driver->diag_wq,
&(data->diag_read_smd_work));
found_it = 1;
break;
}
}
#ifdef CONFIG_DIAG_SDIO_PIPE
if (!found_it) {
if (buf == (void *)driver->buf_in_sdio) {
if (machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa())
diagfwd_write_complete_sdio();
else
pr_err("diag: Incorrect buffer pointer while WRITE");
found_it = 1;
}
}
#endif
if (!found_it) {
diagmem_free(driver, (unsigned char *)buf,
POOL_TYPE_HDLC);
diagmem_free(driver, (unsigned char *)diag_write_ptr,
POOL_TYPE_WRITE_STRUCT);
}
return 0;
}
int diagfwd_read_complete(struct diag_request *diag_read_ptr)
{
int status = diag_read_ptr->status;
unsigned char *buf = diag_read_ptr->buf;
/* Determine if the read complete is for data on legacy/mdm ch */
if (buf == (void *)driver->usb_buf_out) {
driver->read_len_legacy = diag_read_ptr->actual;
APPEND_DEBUG('s');
#ifdef DIAG_DEBUG
printk(KERN_INFO "read data from USB, pkt length %d",
diag_read_ptr->actual);
print_hex_dump(KERN_DEBUG, "Read Packet Data from USB: ", 16, 1,
DUMP_PREFIX_ADDRESS, diag_read_ptr->buf,
diag_read_ptr->actual, 1);
#endif /* DIAG DEBUG */
if (driver->logging_mode == USB_MODE) {
if (status != -ECONNRESET && status != -ESHUTDOWN)
queue_work(driver->diag_wq,
&(driver->diag_proc_hdlc_work));
else
queue_work(driver->diag_wq,
&(driver->diag_read_work));
}
}
#ifdef CONFIG_DIAG_SDIO_PIPE
else if (buf == (void *)driver->usb_buf_mdm_out) {
if (machine_is_msm8x60_fusion() ||
machine_is_msm8x60_fusn_ffa()) {
driver->read_len_mdm = diag_read_ptr->actual;
diagfwd_read_complete_sdio();
} else
pr_err("diag: Incorrect buffer pointer while READ");
}
#endif
else
printk(KERN_ERR "diag: Unknown buffer ptr from USB");
return 0;
}
void diag_read_work_fn(struct work_struct *work)
{
APPEND_DEBUG('d');
driver->usb_read_ptr->buf = driver->usb_buf_out;
driver->usb_read_ptr->length = USB_MAX_OUT_BUF;
usb_diag_read(driver->legacy_ch, driver->usb_read_ptr);
APPEND_DEBUG('e');
}
void diag_process_hdlc_fn(struct work_struct *work)
{
APPEND_DEBUG('D');
diag_process_hdlc(driver->usb_buf_out, driver->read_len_legacy);
diag_read_work_fn(work);
APPEND_DEBUG('E');
}
void diag_usb_legacy_notifier(void *priv, unsigned event,
struct diag_request *d_req)
{
switch (event) {
case USB_DIAG_CONNECT:
diagfwd_connect();
break;
case USB_DIAG_DISCONNECT:
diagfwd_disconnect();
break;
case USB_DIAG_READ_DONE:
diagfwd_read_complete(d_req);
break;
case USB_DIAG_WRITE_DONE:
diagfwd_write_complete(d_req);
break;
default:
printk(KERN_ERR "Unknown event from USB diag\n");
break;
}
}
#endif /* DIAG OVER USB */
void diag_smd_notify(void *ctxt, unsigned event)
{
struct diag_smd_info *smd_info = (struct diag_smd_info *)ctxt;
if (!smd_info)
return;
if (event == SMD_EVENT_CLOSE) {
smd_info->ch = 0;
wake_up(&driver->smd_wait_q);
if (smd_info->type == SMD_DATA_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_cntl_wq,
&(smd_info->diag_notify_update_smd_work));
} else if (smd_info->type == SMD_DCI_TYPE) {
/* Notify the clients of the close */
diag_dci_notify_client(smd_info->peripheral_mask,
DIAG_STATUS_CLOSED);
}
return;
} else if (event == SMD_EVENT_OPEN) {
if (smd_info->ch_save)
smd_info->ch = smd_info->ch_save;
if (smd_info->type == SMD_CNTL_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_cntl_wq,
&(smd_info->diag_notify_update_smd_work));
} else if (smd_info->type == SMD_DCI_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_dci_wq,
&(smd_info->diag_notify_update_smd_work));
/* Notify the clients of the open */
diag_dci_notify_client(smd_info->peripheral_mask,
DIAG_STATUS_OPEN);
}
}
wake_up(&driver->smd_wait_q);
if (smd_info->type == SMD_DCI_TYPE)
queue_work(driver->diag_dci_wq,
&(smd_info->diag_read_smd_work));
else
queue_work(driver->diag_wq, &(smd_info->diag_read_smd_work));
}
static int diag_smd_probe(struct platform_device *pdev)
{
int r = 0;
int index = -1;
if (pdev->id == SMD_APPS_MODEM) {
index = MODEM_DATA;
r = smd_open("DIAG", &driver->smd_data[index].ch,
&driver->smd_data[index],
diag_smd_notify);
driver->smd_data[index].ch_save =
driver->smd_data[index].ch;
}
#if defined(CONFIG_MSM_N_WAY_SMD)
if (pdev->id == SMD_APPS_QDSP) {
index = LPASS_DATA;
r = smd_named_open_on_edge("DIAG", SMD_APPS_QDSP,
&driver->smd_data[index].ch,
&driver->smd_data[index],
diag_smd_notify);
driver->smd_data[index].ch_save =
driver->smd_data[index].ch;
}
#endif
if (pdev->id == SMD_APPS_WCNSS) {
index = WCNSS_DATA;
r = smd_named_open_on_edge("APPS_RIVA_DATA",
SMD_APPS_WCNSS,
&driver->smd_data[index].ch,
&driver->smd_data[index],
diag_smd_notify);
driver->smd_data[index].ch_save =
driver->smd_data[index].ch;
}
pm_runtime_set_active(&pdev->dev);
pm_runtime_enable(&pdev->dev);
pr_debug("diag: open SMD port, Id = %d, r = %d\n", pdev->id, r);
return 0;
}
static int diag_smd_runtime_suspend(struct device *dev)
{
dev_dbg(dev, "pm_runtime: suspending...\n");
return 0;
}
static int diag_smd_runtime_resume(struct device *dev)
{
dev_dbg(dev, "pm_runtime: resuming...\n");
return 0;
}
static const struct dev_pm_ops diag_smd_dev_pm_ops = {
.runtime_suspend = diag_smd_runtime_suspend,
.runtime_resume = diag_smd_runtime_resume,
};
static struct platform_driver msm_smd_ch1_driver = {
.probe = diag_smd_probe,
.driver = {
.name = "DIAG",
.owner = THIS_MODULE,
.pm = &diag_smd_dev_pm_ops,
},
};
static struct platform_driver diag_smd_lite_driver = {
.probe = diag_smd_probe,
.driver = {
.name = "APPS_RIVA_DATA",
.owner = THIS_MODULE,
.pm = &diag_smd_dev_pm_ops,
},
};
void diag_smd_destructor(struct diag_smd_info *smd_info)
{
if (smd_info->ch)
smd_close(smd_info->ch);
smd_info->ch = 0;
smd_info->ch_save = 0;
kfree(smd_info->buf_in_1);
kfree(smd_info->buf_in_2);
kfree(smd_info->write_ptr_1);
kfree(smd_info->write_ptr_2);
}
int diag_smd_constructor(struct diag_smd_info *smd_info, int peripheral,
int type)
{
smd_info->peripheral = peripheral;
smd_info->type = type;
switch (peripheral) {
case MODEM_DATA:
smd_info->peripheral_mask = DIAG_CON_MPSS;
break;
case LPASS_DATA:
smd_info->peripheral_mask = DIAG_CON_LPASS;
break;
case WCNSS_DATA:
smd_info->peripheral_mask = DIAG_CON_WCNSS;
break;
default:
pr_err("diag: In %s, unknown peripheral, peripheral: %d\n",
__func__, peripheral);
goto err;
}
smd_info->ch = 0;
smd_info->ch_save = 0;
if (smd_info->buf_in_1 == NULL) {
smd_info->buf_in_1 = kzalloc(IN_BUF_SIZE, GFP_KERNEL);
if (smd_info->buf_in_1 == NULL)
goto err;
kmemleak_not_leak(smd_info->buf_in_1);
}
if (smd_info->write_ptr_1 == NULL) {
smd_info->write_ptr_1 = kzalloc(sizeof(struct diag_request),
GFP_KERNEL);
if (smd_info->write_ptr_1 == NULL)
goto err;
kmemleak_not_leak(smd_info->write_ptr_1);
}
/* The smd data type needs two buffers */
if (smd_info->type == SMD_DATA_TYPE) {
if (smd_info->buf_in_2 == NULL) {
smd_info->buf_in_2 = kzalloc(IN_BUF_SIZE, GFP_KERNEL);
if (smd_info->buf_in_2 == NULL)
goto err;
kmemleak_not_leak(smd_info->buf_in_2);
}
if (smd_info->write_ptr_2 == NULL) {
smd_info->write_ptr_2 =
kzalloc(sizeof(struct diag_request),
GFP_KERNEL);
if (smd_info->write_ptr_2 == NULL)
goto err;
kmemleak_not_leak(smd_info->write_ptr_2);
}
}
INIT_WORK(&(smd_info->diag_read_smd_work), diag_read_smd_work_fn);
/*
* The update function assigned to the diag_notify_update_smd_work
* work_struct is meant to be used for updating that is not to
* be done in the context of the smd notify function. The
* notify_context variable can be used for passing additional
* information to the update function.
*/
smd_info->notify_context = 0;
if (type == SMD_DATA_TYPE)
INIT_WORK(&(smd_info->diag_notify_update_smd_work),
diag_clean_reg_fn);
else if (type == SMD_CNTL_TYPE)
INIT_WORK(&(smd_info->diag_notify_update_smd_work),
diag_mask_update_fn);
else if (type == SMD_DCI_TYPE)
INIT_WORK(&(smd_info->diag_notify_update_smd_work),
diag_update_smd_dci_work_fn);
else {
pr_err("diag: In %s, unknown type, type: %d\n", __func__, type);
goto err;
}
/*
* Set function ptr for function to call to process the data that
* was just read from the smd channel
*/
if (type == SMD_DATA_TYPE)
smd_info->process_smd_read_data = diag_process_smd_read_data;
else if (type == SMD_CNTL_TYPE)
smd_info->process_smd_read_data =
diag_process_smd_cntl_read_data;
else if (type == SMD_DCI_TYPE)
smd_info->process_smd_read_data =
diag_process_smd_dci_read_data;
else {
pr_err("diag: In %s, unknown type, type: %d\n", __func__, type);
goto err;
}
return 1;
err:
kfree(smd_info->buf_in_1);
kfree(smd_info->buf_in_2);
kfree(smd_info->write_ptr_1);
kfree(smd_info->write_ptr_2);
return 0;
}
void diagfwd_init(void)
{
int success;
int i;
wrap_enabled = 0;
wrap_count = 0;
diag_debug_buf_idx = 0;
driver->read_len_legacy = 0;
driver->use_device_tree = has_device_tree();
mutex_init(&driver->diag_cntl_mutex);
success = diag_smd_constructor(&driver->smd_data[MODEM_DATA],
MODEM_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
success = diag_smd_constructor(&driver->smd_data[LPASS_DATA],
LPASS_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
success = diag_smd_constructor(&driver->smd_data[WCNSS_DATA],
WCNSS_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
if (driver->usb_buf_out == NULL &&
(driver->usb_buf_out = kzalloc(USB_MAX_OUT_BUF,
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->usb_buf_out);
if (driver->hdlc_buf == NULL
&& (driver->hdlc_buf = kzalloc(HDLC_MAX, GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->hdlc_buf);
if (driver->user_space_data == NULL)
driver->user_space_data = kzalloc(USER_SPACE_DATA, GFP_KERNEL);
if (driver->user_space_data == NULL)
goto err;
kmemleak_not_leak(driver->user_space_data);
if (driver->client_map == NULL &&
(driver->client_map = kzalloc
((driver->num_clients) * sizeof(struct diag_client_map),
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->client_map);
if (driver->buf_tbl == NULL)
driver->buf_tbl = kzalloc(buf_tbl_size *
sizeof(struct diag_write_device), GFP_KERNEL);
if (driver->buf_tbl == NULL)
goto err;
kmemleak_not_leak(driver->buf_tbl);
if (driver->data_ready == NULL &&
(driver->data_ready = kzalloc(driver->num_clients * sizeof(int)
, GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->data_ready);
if (driver->table == NULL &&
(driver->table = kzalloc(diag_max_reg*
sizeof(struct diag_master_table),
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->table);
if (driver->usb_read_ptr == NULL) {
driver->usb_read_ptr = kzalloc(
sizeof(struct diag_request), GFP_KERNEL);
if (driver->usb_read_ptr == NULL)
goto err;
kmemleak_not_leak(driver->usb_read_ptr);
}
if (driver->pkt_buf == NULL &&
(driver->pkt_buf = kzalloc(PKT_SIZE,
GFP_KERNEL)) == NULL)
goto err;
kmemleak_not_leak(driver->pkt_buf);
if (driver->apps_rsp_buf == NULL) {
driver->apps_rsp_buf = kzalloc(APPS_BUF_SIZE, GFP_KERNEL);
if (driver->apps_rsp_buf == NULL)
goto err;
kmemleak_not_leak(driver->apps_rsp_buf);
}
driver->diag_wq = create_singlethread_workqueue("diag_wq");
#ifdef CONFIG_DIAG_OVER_USB
INIT_WORK(&(driver->diag_proc_hdlc_work), diag_process_hdlc_fn);
INIT_WORK(&(driver->diag_read_work), diag_read_work_fn);
driver->legacy_ch = usb_diag_open(DIAG_LEGACY, driver,
diag_usb_legacy_notifier);
if (IS_ERR(driver->legacy_ch)) {
printk(KERN_ERR "Unable to open USB diag legacy channel\n");
goto err;
}
#endif
platform_driver_register(&msm_smd_ch1_driver);
platform_driver_register(&diag_smd_lite_driver);
return;
err:
pr_err("diag: Could not initialize diag buffers");
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++)
diag_smd_destructor(&driver->smd_data[i]);
kfree(driver->buf_msg_mask_update);
kfree(driver->buf_log_mask_update);
kfree(driver->buf_event_mask_update);
kfree(driver->usb_buf_out);
kfree(driver->hdlc_buf);
kfree(driver->client_map);
kfree(driver->buf_tbl);
kfree(driver->data_ready);
kfree(driver->table);
kfree(driver->pkt_buf);
kfree(driver->usb_read_ptr);
kfree(driver->apps_rsp_buf);
kfree(driver->user_space_data);
if (driver->diag_wq)
destroy_workqueue(driver->diag_wq);
}
void diagfwd_exit(void)
{
int i;
for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++)
diag_smd_destructor(&driver->smd_data[i]);
#ifdef CONFIG_DIAG_OVER_USB
if (driver->usb_connected)
usb_diag_free_req(driver->legacy_ch);
usb_diag_close(driver->legacy_ch);
#endif
platform_driver_unregister(&msm_smd_ch1_driver);
platform_driver_unregister(&msm_diag_dci_driver);
platform_driver_unregister(&diag_smd_lite_driver);
kfree(driver->buf_msg_mask_update);
kfree(driver->buf_log_mask_update);
kfree(driver->buf_event_mask_update);
kfree(driver->usb_buf_out);
kfree(driver->hdlc_buf);
kfree(driver->client_map);
kfree(driver->buf_tbl);
kfree(driver->data_ready);
kfree(driver->table);
kfree(driver->pkt_buf);
kfree(driver->usb_read_ptr);
kfree(driver->apps_rsp_buf);
kfree(driver->user_space_data);
destroy_workqueue(driver->diag_wq);
}
| Java |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import HasGrampsId
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class HasIdOf(HasGrampsId):
"""Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID")
| Java |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of 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 Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.expr;
import java.io.IOException;
import java.util.ArrayList;
import com.caucho.quercus.Location;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.MethodIntern;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.StringValue;
import com.caucho.quercus.env.QuercusClass;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.env.Var;
import com.caucho.quercus.parser.QuercusParser;
import com.caucho.util.L10N;
/**
* Represents a PHP static field reference.
*/
public class ClassVirtualFieldExpr extends AbstractVarExpr {
private static final L10N L = new L10N(ClassVirtualFieldExpr.class);
protected final StringValue _varName;
public ClassVirtualFieldExpr(String varName)
{
_varName = MethodIntern.intern(varName);
}
//
// function call creation
//
/**
* Creates a function call expression
*/
@Override
public Expr createCall(QuercusParser parser,
Location location,
ArrayList<Expr> args)
throws IOException
{
ExprFactory factory = parser.getExprFactory();
Expr var = parser.createVar(_varName.toString());
return factory.createClassVirtualMethodCall(location, var, args);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value eval(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL;
}
return qClass.getStaticFieldValue(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Var evalVar(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.getStaticFieldVar(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value evalAssignRef(Env env, Value value)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.setStaticFieldRef(env, _varName, value);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
public void evalUnset(Env env)
{
env.error(getLocation(),
L.l("{0}::${1}: Cannot unset static variables.",
env.getCallingClass().getName(), _varName));
}
public String toString()
{
return "static::$" + _varName;
}
}
| Java |
#include "punchestableview.h"
#include <qf/core/log.h>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QPainter>
#include <QPixmap>
PunchesTableView::PunchesTableView(QWidget *parent)
: Super(parent)
{
setDropIndicatorShown(false);
}
bool PunchesTableView::edit(const QModelIndex &index, QAbstractItemView::EditTrigger trigger, QEvent *event)
{
Q_UNUSED(event)
if(trigger == QAbstractItemView::EditTrigger::DoubleClicked
|| trigger == QAbstractItemView::EditTrigger::EditKeyPressed) {
qf::core::utils::TableRow row = tableRow(index.row());
int class_id = row.value("classes.id").toInt();
int code = row.value("punches.code").toInt();
qfDebug() << "codeClassActivated:" << class_id << code;
emit codeClassActivated(class_id, code);
}
return false;
}
/*
void PunchesTableView::mousePressEvent(QMouseEvent *event)
{
qfInfo() << Q_FUNC_INFO;
QModelIndex ix = indexAt(event->pos());
if (!ix.isValid())
return;
qf::core::utils::TableRow row = tableRow(ix.row());
QString class_name = row.value(QStringLiteral("classes.name")).toString();
int code = row.value(QStringLiteral("punches.code")).toInt();
QByteArray item_data;
QDataStream data_stream(&item_data, QIODevice::WriteOnly);
data_stream << ix.row() << ix.column();
QMimeData *mime_data = new QMimeData;
mime_data->setData("application/x-quickevent", item_data);
QDrag *drag = new QDrag(this);
drag->setMimeData(mime_data);
//drag->setPixmap(pixmap);
//drag->setHotSpot(event->pos() - child->pos());
QPixmap px{QSize{10, 10}};
QPainter painter;
QFont f = font();
QFontMetrics fm(f, &px);
QString s = QString("%1 - %2").arg(class_name).arg(code);
QRect bounding_rect = fm.boundingRect(s);
static constexpr int inset = 5;
bounding_rect.adjust(-inset, -inset, inset, inset);
px = QPixmap{bounding_rect.size()};
painter.begin(&px);
painter.setFont(f);
//painter.setPen(Qt::black);
//painter.setBrush(Qt::black);
painter.fillRect(px.rect(), QColor("khaki"));
painter.drawRect(QRect(QPoint(), bounding_rect.size() - QSize(1, 1)));
painter.drawText(QPoint{inset, inset + fm.ascent()}, s);
painter.end();
drag->setPixmap(px);
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
//child->close();
} else {
//child->show();
//child->setPixmap(pixmap);
}
}
void PunchesTableView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-quickevent")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void PunchesTableView::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-quickevent")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
*/
| Java |
// prng.cpp or pseudo-random number generator (prng)
// Generates some pseudo-random numbers.
#include <iostream>
#include <iomanip>
using std::cout; // iostream
using std::endl;
using std::setw; // iomanip
// function generates random number
unsigned pseudoRNG() {
static unsigned seed = 5493; // some (any) initial starting seed; initialized only once!
// Take the current seed and generate new value from it
// Due to larg numbers used to generate numbers is difficult to
// predict next value from previous one.
// Static keyword has program scope and is terminated at the end of
// program. Seed value is stored every time in memory using previous
// value.
seed = (3852591 * seed + 5180347);
// return value between 0 and 65535
return (seed % 65535);
}
int main()
{
// generate 100 random numbers - print in separate fields
for (int i = 1; i <= 100; i++) {
cout << setw(8) << pseudoRNG();
// new line every fifth number
if (i % 5 == 0)
cout << endl;
}
return 0;
}
| Java |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class System
{
function System()
{
if (!isset($this->CI))
{
$this->CI =& get_instance();
}
$this->settings_table = 'settings';
$this->template_table = 'templates';
$this->languages_table = 'languages';
$this->CI->config->set_item('language', $this->get_default_language());
$this->get_site_info();
}
function get_default_template()
{
$this->CI->db->select('path');
$this->CI->db->where('is_default', '1');
$query = $this->CI->db->get($this->template_table, 1);
if ($query->num_rows() == 1)
{
$row = $query->row_array();
}
return $row['path'];
}
function get_default_language()
{
$this->CI->db->select('language');
$this->CI->db->where('is_default', '1');
$query = $this->CI->db->get($this->languages_table, 1);
if ($query->num_rows() == 1)
{
$row = $query->row_array();
}
return $row['language'];
}
function get_site_info()
{
$this->CI->db->select('blog_title, blog_description, meta_keywords, allow_registrations, enable_rss, enable_atom, links_per_box, months_per_archive');
$this->CI->db->where('id', '1');
$query = $this->CI->db->get($this->settings_table, 1);
if ($query->num_rows() == 1)
{
$result = $query->row_array();
foreach ($result as $key => $value)
{
$this->settings[$key] = $value;
}
}
}
function check_site_status()
{
$this->CI->db->select('enabled, offline_reason');
$this->CI->db->where('id', '1');
$query = $this->CI->db->get($this->settings_table, 1);
if ($query->num_rows() == 1)
{
$result = $query->row_array();
if ($result['enabled'] == 0)
{
echo lang('site_disabled') . "<br />";
echo lang('reason') . " <strong>" . $result['offline_reason'] . "</strong>";
die();
}
}
}
function load($page, $data = null, $admin = false)
{
$data['page'] = $page;
if ($admin == true)
{
$this->CI->load->view('admin/layout/container', $data);
}
else
{
$template = $this->get_default_template();
$this->CI->load->view('templates/' . $template . '/layout/container', $data);
}
}
function load_normal($page, $data = null)
{
$template = $this->get_default_template();
$this->CI->load->view('templates/' . $template . '/layout/pages/' . $page, $data);
}
}
/* End of file System.php */
/* Location: ./application/libraries/System.php */ | Java |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb"
| Java |
\documentclass{article}
\begin{filecontents}{mybib.bib}
\begin{document}
here is some text
more text
here
\end{document}
\end{filecontents}
\begin{filecontents}{another.bib}
\begin{document}
some more text
more text
here
\end{document}
\end{filecontents}
\begin{document}
\begin{myotherenvironment}
some text goes here
some text goes here
some text goes here
some text goes here
\end{myotherenvironment}
\end{document}
| Java |
using System;
using Server;
using Server.Items;
namespace Server.Mobiles
{
public class Kurlem : BaseCreature
{
[Constructable]
public Kurlem()
: base( AIType.AI_Melee, FightMode.Aggressor, 22, 1, 0.2, 1.0 )
{
Name = "Kurlem";
Title = "the Caretaker";
Race = Race.Gargoyle;
Blessed = true;
Hue = 0x86DF;
HairItemID = 0x4258;
HairHue = 0x31C;
AddItem( new GargishLeatherArms() );
AddItem( new GargishFancyRobe( 0x3B3 ) );
}
public override bool CanTeach { get { return false; } }
public Kurlem( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */
reader.ReadInt();
}
}
} | Java |
package instance
import (
"encoding/json"
)
// ID is the identifier for an instance.
type ID string
// Description contains details about an instance.
type Description struct {
ID ID
LogicalID *LogicalID
Tags map[string]string
}
// LogicalID is the logical identifier to associate with an instance.
type LogicalID string
// Attachment is an identifier for a resource to attach to an instance.
type Attachment struct {
// ID is the unique identifier for the attachment.
ID string
// Type is the kind of attachment. This allows multiple attachments of different types, with the supported
// types defined by the plugin.
Type string
}
// Spec is a specification of an instance to be provisioned
type Spec struct {
// Properties is the opaque instance plugin configuration.
Properties *json.RawMessage
// Tags are metadata that describes an instance.
Tags map[string]string
// Init is the boot script to execute when the instance is created.
Init string
// LogicalID is the logical identifier assigned to this instance, which may be absent.
LogicalID *LogicalID
// Attachments are instructions for external entities that should be attached to the instance.
Attachments []Attachment
}
| Java |
#ifndef _XmDataF_h
#define _XmDataF_h
#include <Xm/Xm.h>
#include <Xm/TextF.h>
#include <Xm/Ext.h>
#if defined(__cplusplus)
extern "C" {
#endif
typedef struct _XmDataFieldClassRec *XmDataFieldWidgetClass;
typedef struct _XmDataFieldRec *XmDataFieldWidget;
/* Function Name: XmCreateDataField
* Description: Creation Routine for UIL and ADA.
* Arguments: parent - the parent widget.
* name - the name of the widget.
* args, num_args - the number and list of args.
* Returns: The Widget created.
*/
Widget XmCreateDataField(
#ifndef _NO_PROTO
Widget, String, ArgList, Cardinal
#endif
);
/*
* Variable argument list functions
*/
extern Widget XmVaCreateDataField(
Widget parent,
char *name,
...);
extern Widget XmVaCreateManagedDataField(
Widget parent,
char *name,
...);
Boolean _XmDataFieldReplaceText(
#ifndef _NO_PROTO
XmDataFieldWidget, XEvent*, XmTextPosition, XmTextPosition, char*, int, Boolean
#endif
);
void XmDataFieldSetString(
#ifndef _NO_PROTO
Widget, char*
#endif
);
extern char * XmDataFieldGetString(
#ifndef _NO_PROTO
Widget
#endif
);
extern wchar_t * XmDataFieldGetStringWcs(
#ifndef _NO_PROTO
Widget
#endif
);
void _XmDataFieldSetClipRect(
#ifndef _NO_PROTO
XmDataFieldWidget
#endif
);
void _XmDataFieldDrawInsertionPoint(
#ifndef _NO_PROTO
XmDataFieldWidget, Boolean
#endif
);
void XmDataFieldSetHighlight(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, XmHighlightMode
#endif
);
void XmDataFieldSetAddMode(
#ifndef _NO_PROTO
Widget, Boolean
#endif
);
char * XmDataFieldGetSelection(
#ifndef _NO_PROTO
Widget
#endif
);
void XmDataFieldSetSelection(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, Time
#endif
);
void _XmDataFieldSetSel2(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, Boolean, Time
#endif
);
Boolean XmDataFieldGetSelectionPosition(
#ifndef _NO_PROTO
Widget, XmTextPosition *, XmTextPosition *
#endif
);
XmTextPosition XmDataFieldXYToPos(
#ifndef _NO_PROTO
Widget, Position, Position
#endif
);
void XmDataFieldShowPosition(
#ifndef _NO_PROTO
Widget, XmTextPosition
#endif
);
Boolean XmDataFieldCut(
#ifndef _NO_PROTO
Widget, Time
#endif
);
Boolean XmDataFieldCopy(
#ifndef _NO_PROTO
Widget, Time
#endif
);
Boolean XmDataFieldPaste(
#ifndef _NO_PROTO
Widget
#endif
);
void XmDataFieldSetEditable(
#ifndef _NO_PROTO
Widget, Boolean
#endif
);
void XmDataFieldSetInsertionPosition(
#ifndef _NO_PROTO
Widget, XmTextPosition
#endif
);
extern WidgetClass xmDataFieldWidgetClass;
typedef struct _XmDataFieldCallbackStruct {
Widget w; /* The XmDataField */
String text; /* Proposed string */
Boolean accept; /* Accept return value, for validation */
} XmDataFieldCallbackStruct;
#if defined(__cplusplus)
} /* extern "C" */
#endif
#endif /* _XmDataF_h */
| Java |
#ifndef OFP_VERSION_H
#define OFP_VERSION_H 1
#include <openflow/openflow-common.h>
#include "util.h"
#include "openvswitch/ofp-util.h"
#define OFP_VERSION_LONG_OPTIONS \
{"version", no_argument, NULL, 'V'}, \
{"protocols", required_argument, NULL, 'O'}
#define OFP_VERSION_OPTION_HANDLERS \
case 'V': \
ovs_print_version(OFP10_VERSION, OFP13_VERSION); \
exit(EXIT_SUCCESS); \
\
case 'O': \
set_allowed_ofp_versions(optarg); \
break;
uint32_t get_allowed_ofp_versions(void);
void set_allowed_ofp_versions(const char *string);
void mask_allowed_ofp_versions(uint32_t);
void add_allowed_ofp_versions(uint32_t);
void ofp_version_usage(void);
#endif
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2014 René Samselnig
#
# This file is part of Database Navigator.
#
# Database Navigator 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.
#
# Database Navigator 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 Database Navigator. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import re
import codecs
from collections import Counter
filename = sys.argv[1]
with codecs.open(filename, encoding='utf-8') as f:
text = f.read()
m = re.findall(r'^#{2,3} .*$', text, re.MULTILINE)
def title(s):
return re.sub(r'#+ ', '', s)
def fragment(s):
return '#' + re.sub(r'[^a-z-]', '', re.sub(r'#+ ', '', s).replace(' ', '-').lower())
def depth(s):
return len(re.match(r'(#*)', s).group(0))
c = Counter()
toc = []
for header in m:
t = title(header)
f = fragment(header)
d = depth(header)
if c[f] > 0:
toc.append('{}- [{}]({}-{})'.format('\t'*(d-2), t, f, c[f]))
else:
toc.append('{}- [{}]({})'.format('\t'*(d-2), t, f))
c[f] += 1
with codecs.open(filename, 'w', encoding='utf-8') as f:
f.write(text.replace('[TOC]', '\n'.join(toc)))
| Java |
# -*- coding: utf-8 -*-
"""
pygments.plugin
~~~~~~~~~~~~~~~
Pygments setuptools plugin interface. The methods defined
here also work if setuptools isn't installed but they just
return nothing.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.formatters]
yourformatter = yourformatter:YourFormatter
/.ext = yourformatter:YourFormatter
As you can see, you can define extensions for the formatter
with a leading slash.
syntax plugins::
[pygments.styles]
yourstyle = yourstyle:YourStyle
filter plugin::
[pygments.filter]
yourfilter = yourfilter:YourFilter
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
try:
import pkg_resources
except ImportError:
pkg_resources = None
LEXER_ENTRY_POINT = 'pygments.lexers'
FORMATTER_ENTRY_POINT = 'pygments.formatters'
STYLE_ENTRY_POINT = 'pygments.styles'
FILTER_ENTRY_POINT = 'pygments.filters'
def find_plugin_lexers():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT):
yield entrypoint.load()
def find_plugin_formatters():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_styles():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
def find_plugin_filters():
if pkg_resources is None:
return
for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT):
yield entrypoint.name, entrypoint.load()
| Java |
/*QMainWindow, QMenuBar, QToolBar, QPushButton {
background-color: #000000;
color: #ffffff;
}
QDockWidget::title, QDockWidget::float-button, QDockWidget::close-button {
background-color: #999999;
color: #ffffff;
}*/
/****************************************************/
/* http://tech-artists.org/forum/showthread.php?2359-Release-Qt-dark-orange-stylesheet */
QToolTip
{
border: 1px solid black;
background-color: %ACCENT3%;
/*padding: 2px;*/
/*border-radius: 3px;*/
opacity: 100;
color: black;
}
QWidget
{
color: #c0c0c0;
background-color: #323232;
}
QWidget:item:hover
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT4%);
color: #000000;
}
QWidget:item:selected
{
background-color: %ACCENT2%; /*QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);*/
}
QDockWidget {
border: 5px solid black;
}
/* MENUS */
/***********************************************/
QMenuBar::item
{
background: transparent;
}
QMenuBar::item:selected
{
background: transparent;
border: 1px solid %ACCENT%;
}
QMenuBar::item:pressed
{
background: #444;
border: 1px solid #000;
background-color: QLinearGradient(
x1:0, y1:0,
x2:0, y2:1,
stop:1 #212121,
stop:0.4 #343434/*,
stop:0.2 #343434,
stop:0.1 %ACCENT%*/
);
margin-bottom:-1px;
padding-bottom:1px;
}
QMenu
{
border: 1px solid #000;
}
QMenu::item
{
padding: 2px 20px 2px 20px;
}
QMenu::item:selected
{
color: #000000;
}
QWidget:disabled
{
color: #808080;
/*background-color: #606060;*/
}
QAbstractItemView
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0.1 #646464, stop: 1 #5d5d5d);
}
QWidget:focus
{
/*border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);*/
}
QLineEdit
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #5d5d5d);
padding: 1px;
border-style: solid;
border: 1px solid #1e1e1e;
border-radius: 5;
}
/* CONTROLS */
/***********************************************/
QPushButton
{
/*color: #b1b1b1;*/
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);
border-width: 1px;
border-color: #1e1e1e;
border-style: solid;
/*border-radius: 6;*/
/*font-size: 12px;*/
/*padding: 5px;*/
/*padding-left: 5px;
padding-right: 5px;*/
}
QPushButton:pressed
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
}
QPushButton:checked
{
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
}
QComboBox
{
selection-background-color: %ACCENT%;
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);
border-style: solid;
border: 1px solid #1e1e1e;
/*border-radius: 5;*/
}
QComboBox:hover,QPushButton:hover
{
border: 1px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
}
QComboBox:on
{
padding-top: 3px;
padding-left: 4px;
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
selection-background-color: %ACCENT%;
}
QComboBox QAbstractItemView
{
border: 1px solid darkgray;
selection-background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
selection-color: #000000;
}
QComboBox::drop-down
{
subcontrol-origin: padding;
subcontrol-position: top right;
width: 15px;
border-left-width: 0px;
border-left-color: darkgray;
border-left-style: solid;
/*border-top-right-radius: 3px;
border-bottom-right-radius: 3px;*/
}
QComboBox::down-arrow
{
image: url(:/icons/down_arrow.png);
}
QGroupBox:focus
{
border: 1px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
}
QTextEdit:focus
{
border: 1px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
}
/* SCROLL BAR */
/***********************************************/
QScrollBar:horizontal {
border: 1px solid #222222;
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);
height: 20px;
margin: 0px 16px 0 16px;
}
QScrollBar::handle:horizontal
{
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 %ACCENT3%, stop: 0.5 %ACCENT2%, stop: 1 %ACCENT3%);
min-height: 20px;
border-radius: 2px;
}
QScrollBar::add-line:horizontal {
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
width: 14px;
subcontrol-position: right;
subcontrol-origin: margin;
}
QScrollBar::sub-line:horizontal {
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
width: 14px;
subcontrol-position: left;
subcontrol-origin: margin;
}
/*
QScrollBar::right-arrow:horizontal, QScrollBar::left-arrow:horizontal
{
border: 1px solid black;
width: 10px;
height: 10px;
background: white;
}*/
QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal
{
background: none;
}
QScrollBar:vertical
{
background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848);
width: 20px;
margin: 16px 0 16px 0;
border: 1px solid #222222;
}
QScrollBar::handle:vertical
{
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 0.5 %ACCENT2%, stop: 1 %ACCENT3%);
min-height: 20px;
border-radius: 2px;
}
QScrollBar::add-line:vertical
{
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT3%, stop: 1 %ACCENT2%);
height: 14px;
subcontrol-position: bottom;
subcontrol-origin: margin;
}
QScrollBar::sub-line:vertical
{
border: 1px solid #1b1b19;
border-radius: 2px;
background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 %ACCENT2%, stop: 1 %ACCENT3%);
height: 14px;
subcontrol-position: top;
subcontrol-origin: margin;
}
QScrollBar::add-line:vertical:hover,
QScrollBar::sub-line:vertical:hover,
QScrollBar::add-line:horizontal:hover,
QScrollBar::sub-line:horizontal:hover
{
background-color: #909090;
}
QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical
{
image: url(':/icons/up.png');
}
QScrollBar::down-arrow:vertical, QScrollBar::down-arrow:vertical
{
image: url(':/icons/down.png');
}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical
{
background: none;
}
/* TEXT */
/***********************************************/
QTextEdit
{
background-color: #242424;
font-family: "Courier New";
}
QPlainTextEdit
{
background-color: #242424;
font-family: "Courier New";
}
QHeaderView::section
{
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);
color: #b1b1b1;
padding-left: 4px;
border: 1px solid #6c6c6c;
}
QCheckBox:disabled
{
color: #414141;
}
/* DOCK WIDGET */
/***********************************************/
QDockWidget::title
{
text-align: center;
spacing: 3px; /* spacing between items in the tool bar */
border-color: #343434;
/*background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232);*/
}
QDockWidget::close-button, QDockWidget::float-button
{
/*text-align: center;*/
/*spacing: 10px;*/
background-color: #707070;
}
QDockWidget::close-button:hover, QDockWidget::float-button:hover
{
/*background: #242424;*/
background-color: #b1b1b1;
border: none;
}
/*
QDockWidget::close-button:pressed, QDockWidget::float-button:pressed
{
padding: 1px -1px -1px 1px;
}
*/
QMainWindow::separator
{
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);
color: white;
padding-left: 4px;
border: 1px solid #4c4c4c;
spacing: 3px; /* spacing between items in the tool bar */
}
QMainWindow::separator:hover
{
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 %ACCENT2%, stop:0.5 %ACCENT4% stop:1 %ACCENT3%);
color: white;
padding-left: 4px;
border: 1px solid #6c6c6c;
spacing: 3px; /* spacing between items in the tool bar */
}
QToolBar
{
border-color: #323232;
}
QToolBar::handle
{
spacing: 3px; /* spacing between items in the tool bar */
background: url(':/icons/handle.png');
}
QToolButton:hover
{
background-color: #202020;
}
QMenu::separator
{
height: 2px;
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434);
color: white;
padding-left: 4px;
margin-left: 10px;
margin-right: 5px;
}
QProgressBar
{
border: 2px solid grey;
/*border-radius: 5px;*/
text-align: center;
}
QProgressBar::chunk
{
background-color: %ACCENT2%;
width: 2.15px;
margin: 0.5px;
}
QTabBar::tab {
color: #b1b1b1;
border: 1px solid #444;
border-bottom-style: none;
background-color: #323232;
padding-left: 10px;
padding-right: 10px;
padding-top: 3px;
padding-bottom: 2px;
margin-right: -1px;
}
QTabWidget::pane {
border: 1px solid #444;
top: 1px;
}
QTabBar::tab:last
{
margin-right: 0; /* the last selected tab has nothing to overlap with on the right */
border-top-right-radius: 3px;
}
QTabBar::tab:first:!selected
{
margin-left: 0px; /* the last selected tab has nothing to overlap with on the right */
border-top-left-radius: 3px;
}
QTabBar::tab:!selected
{
color: #b1b1b1;
border-bottom-style: solid;
margin-top: 3px;
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:.4 #343434);
}
QTabBar::tab:selected
{
border-top-left-radius: 3px;
border-top-right-radius: 3px;
margin-bottom: 0px;
}
QTabBar::tab:!selected:hover
{
/*border-top: 2px solid %ACCENT%;
padding-bottom: 3px;*/
border-top-left-radius: 3px;
border-top-right-radius: 3px;
background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434, stop:0.2 #343434, stop:0.1 %ACCENT%);
}
QRadioButton::indicator:checked, QRadioButton::indicator:unchecked{
color: #b1b1b1;
background-color: #323232;
border: 1px solid #b1b1b1;
border-radius: 6px;
}
QRadioButton::indicator:checked
{
background-color: qradialgradient(
cx: 0.5, cy: 0.5,
fx: 0.5, fy: 0.5,
radius: 1.0,
stop: 0.25 %ACCENT%,
stop: 0.3 #323232
);
}
QCheckBox::indicator{
color: #b1b1b1;
background-color: #323232;
border: 1px solid #b1b1b1;
width: 9px;
height: 9px;
}
QRadioButton::indicator
{
border-radius: 6px;
}
QRadioButton::indicator:hover, QCheckBox::indicator:hover
{
border: 1px solid %ACCENT%;
}
QCheckBox::indicator:checked
{
image:url(:/icons/checkbox.png);
}
QCheckBox::indicator:disabled, QRadioButton::indicator:disabled
{
border: 1px solid #444;
}
/****************************************************/
QStatusBar::item
{
border: none;
}
QTreeView {
background-color: #000000;
/*color: #b1b1b1;*/
}
QTreeView::item {
/*color: #b1b1b1;*/
}
QTreeView::item:hover {
background-color: #7a7a7a;
color: #000000;
}
QTreeView::item:selected {
background-color: #b1b1b1;
color: #000000;
}
| Java |
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add("lang/dial",function(e){e.Intl.add("dial","",{label:"My label",resetStr:"Reset",tooltipHandle:"Drag to set value"})},"3.9.0pr1");
| Java |
package com.amaze.filemanager.filesystem;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.provider.DocumentFile;
import com.amaze.filemanager.exceptions.RootNotPermittedException;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.cloud.CloudUtil;
import com.amaze.filemanager.utils.Logger;
import com.amaze.filemanager.utils.MainActivityHelper;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.OpenMode;
import com.amaze.filemanager.utils.RootUtils;
import com.cloudrail.si.interfaces.CloudStorage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
/**
* Created by arpitkh996 on 13-01-2016, modified by Emmanuel Messulam<[email protected]>
*/
public class Operations {
// reserved characters by OS, shall not be allowed in file names
private static final String FOREWARD_SLASH = "/";
private static final String BACKWARD_SLASH = "\\";
private static final String COLON = ":";
private static final String ASTERISK = "*";
private static final String QUESTION_MARK = "?";
private static final String QUOTE = "\"";
private static final String GREATER_THAN = ">";
private static final String LESS_THAN = "<";
private static final String FAT = "FAT";
private DataUtils dataUtils = DataUtils.getInstance();
public interface ErrorCallBack {
/**
* Callback fired when file being created in process already exists
*
* @param file
*/
void exists(HFile file);
/**
* Callback fired when creating new file/directory and required storage access framework permission
* to access SD Card is not available
*
* @param file
*/
void launchSAF(HFile file);
/**
* Callback fired when renaming file and required storage access framework permission to access
* SD Card is not available
*
* @param file
* @param file1
*/
void launchSAF(HFile file, HFile file1);
/**
* Callback fired when we're done processing the operation
*
* @param hFile
* @param b defines whether operation was successful
*/
void done(HFile hFile, boolean b);
/**
* Callback fired when an invalid file name is found.
*
* @param file
*/
void invalidName(HFile file);
}
public static void mkdir(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// checking whether filename is valid or a recursive call possible
if (MainActivityHelper.isNewDirectoryRecursive(file) ||
!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).mkdirs();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isOtgFile()) {
// first check whether new directory already exists
DocumentFile directoryToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (directoryToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createDirectory(file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.createFolder(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.createFolder(CloudUtil.stripPath(OpenMode.BOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.createFolder(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.createFolder(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
FileUtil.mkdir(file.getFile(), context);
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkDir(file.getParent(context), file.getName(context));
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void mkfile(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether filename is valid or not
if (!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).createNewFile();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageOneDrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOtgFile()) {
// first check whether new file already exists
DocumentFile fileToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (fileToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createFile(file.getName(context).substring(file.getName().lastIndexOf(".")),
file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
try {
FileUtil.mkfile(file.getFile(), context);
} catch (IOException e) {
}
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkFile(file.getPath());
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void rename(final HFile oldFile, final HFile newFile, final boolean rootMode,
final Context context, final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether file names for new file are valid or recursion occurs
if (MainActivityHelper.isNewDirectoryRecursive(newFile) ||
!Operations.isFileNameValid(newFile.getName(context))) {
errorCallBack.invalidName(newFile);
return null;
}
if (newFile.exists()) {
errorCallBack.exists(newFile);
return null;
}
if (oldFile.isSmb()) {
try {
SmbFile smbFile = new SmbFile(oldFile.getPath());
SmbFile smbFile1 = new SmbFile(newFile.getPath());
if (smbFile1.exists()) {
errorCallBack.exists(newFile);
return null;
}
smbFile.renameTo(smbFile1);
if (!smbFile.exists() && smbFile1.exists())
errorCallBack.done(newFile, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
}
return null;
} else if (oldFile.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.move(CloudUtil.stripPath(OpenMode.DROPBOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.DROPBOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.move(CloudUtil.stripPath(OpenMode.BOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.BOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.move(CloudUtil.stripPath(OpenMode.ONEDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.ONEDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.move(CloudUtil.stripPath(OpenMode.GDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.GDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOtgFile()) {
DocumentFile oldDocumentFile = OTGUtil.getDocumentFile(oldFile.getPath(), context, false);
DocumentFile newDocumentFile = OTGUtil.getDocumentFile(newFile.getPath(), context, false);
if (newDocumentFile != null) {
errorCallBack.exists(newFile);
return null;
}
errorCallBack.done(newFile, oldDocumentFile.renameTo(newFile.getName(context)));
return null;
} else {
File file = new File(oldFile.getPath());
File file1 = new File(newFile.getPath());
switch (oldFile.getMode()) {
case FILE:
int mode = checkFolder(file.getParentFile(), context);
if (mode == 2) {
errorCallBack.launchSAF(oldFile, newFile);
} else if (mode == 1 || mode == 0) {
try {
FileUtil.renameFolder(file, file1, context);
} catch (RootNotPermittedException e) {
e.printStackTrace();
}
boolean a = !file.exists() && file1.exists();
if (!a && rootMode) {
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
oldFile.setMode(OpenMode.ROOT);
newFile.setMode(OpenMode.ROOT);
a = !file.exists() && file1.exists();
}
errorCallBack.done(newFile, a);
return null;
}
break;
case ROOT:
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
newFile.setMode(OpenMode.ROOT);
errorCallBack.done(newFile, true);
break;
}
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static int checkFolder(final File folder, Context context) {
boolean lol = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
if (lol) {
boolean ext = FileUtil.isOnExtSdCard(folder, context);
if (ext) {
if (!folder.exists() || !folder.isDirectory()) {
return 0;
}
// On Android 5, trigger storage access framework.
if (!FileUtil.isWritableNormalOrSaf(folder, context)) {
return 2;
}
return 1;
}
} else if (Build.VERSION.SDK_INT == 19) {
// Assume that Kitkat workaround works
if (FileUtil.isOnExtSdCard(folder, context)) return 1;
}
// file not on external sd card
if (FileUtil.isWritable(new File(folder, "DummyFile"))) {
return 1;
} else {
return 0;
}
}
/**
* Well, we wouldn't want to copy when the target is inside the source
* otherwise it'll end into a loop
*
* @param sourceFile
* @param targetFile
* @return true when copy loop is possible
*/
public static boolean isCopyLoopPossible(BaseFile sourceFile, HFile targetFile) {
return targetFile.getPath().contains(sourceFile.getPath());
}
/**
* Validates file name
* special reserved characters shall not be allowed in the file names on FAT filesystems
*
* @param fileName the filename, not the full path!
* @return boolean if the file name is valid or invalid
*/
public static boolean isFileNameValid(String fileName) {
//String fileName = builder.substring(builder.lastIndexOf("/")+1, builder.length());
// TODO: check file name validation only for FAT filesystems
return !(fileName.contains(ASTERISK) || fileName.contains(BACKWARD_SLASH) ||
fileName.contains(COLON) || fileName.contains(FOREWARD_SLASH) ||
fileName.contains(GREATER_THAN) || fileName.contains(LESS_THAN) ||
fileName.contains(QUESTION_MARK) || fileName.contains(QUOTE));
}
private static boolean isFileSystemFAT(String mountPoint) {
String[] args = new String[]{"/bin/bash", "-c", "df -DO_NOT_REPLACE | awk '{print $1,$2,$NF}' | grep \"^"
+ mountPoint + "\""};
try {
Process proc = new ProcessBuilder(args).start();
OutputStream outputStream = proc.getOutputStream();
String buffer = null;
outputStream.write(buffer.getBytes());
return buffer != null && buffer.contains(FAT);
} catch (IOException e) {
e.printStackTrace();
// process interrupted, returning true, as a word of cation
return true;
}
}
}
| Java |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "qmljstoolsplugin.h"
#include "qmljsmodelmanager.h"
#include "qmljsfunctionfilter.h"
#include "qmljslocatordata.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include "qmljstoolssettings.h"
#include "qmljsbundleprovider.h"
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <QMenu>
using namespace Core;
namespace QmlJSTools {
namespace Internal {
enum { debug = 0 };
class QmlJSToolsPluginPrivate : public QObject
{
public:
QmlJSToolsPluginPrivate();
QmlJSToolsSettings settings;
ModelManager modelManager;
QAction resetCodeModelAction{QmlJSToolsPlugin::tr("Reset Code Model"), nullptr};
LocatorData locatorData;
FunctionFilter functionFilter{&locatorData};
QmlJSCodeStyleSettingsPage codeStyleSettingsPage;
BasicBundleProvider basicBundleProvider;
};
QmlJSToolsPlugin::~QmlJSToolsPlugin()
{
delete d;
}
bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
Q_UNUSED(error)
d = new QmlJSToolsPluginPrivate;
return true;
}
QmlJSToolsPluginPrivate::QmlJSToolsPluginPrivate()
{
// Core::VcsManager *vcsManager = Core::VcsManager::instance();
// Core::DocumentManager *documentManager = Core::DocumentManager::instance();
// connect(vcsManager, &Core::VcsManager::repositoryChanged,
// &d->modelManager, &ModelManager::updateModifiedSourceFiles);
// connect(documentManager, &DocumentManager::filesChangedInternally,
// &d->modelManager, &ModelManager::updateSourceFiles);
// Menus
ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
ActionContainer *mqmljstools = ActionManager::createMenu(Constants::M_TOOLS_QMLJS);
QMenu *menu = mqmljstools->menu();
menu->setTitle(QmlJSToolsPlugin::tr("&QML/JS"));
menu->setEnabled(true);
mtools->addMenu(mqmljstools);
// Update context in global context
Command *cmd = ActionManager::registerAction(
&resetCodeModelAction, Constants::RESET_CODEMODEL);
connect(&resetCodeModelAction, &QAction::triggered,
&modelManager, &ModelManager::resetCodeModel);
mqmljstools->addAction(cmd);
// Watch task progress
connect(ProgressManager::instance(), &ProgressManager::taskStarted, this,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
resetCodeModelAction.setEnabled(false);
});
connect(ProgressManager::instance(), &ProgressManager::allTasksFinished,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
resetCodeModelAction.setEnabled(true);
});
}
void QmlJSToolsPlugin::extensionsInitialized()
{
d->modelManager.delayedInitialization();
}
} // Internal
} // QmlJSTools
| Java |
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-cen-xr-w32-bld/build/netwerk/base/public/nsPISocketTransportService.idl
*/
#ifndef __gen_nsPISocketTransportService_h__
#define __gen_nsPISocketTransportService_h__
#ifndef __gen_nsISocketTransportService_h__
#include "nsISocketTransportService.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsPISocketTransportService */
#define NS_PISOCKETTRANSPORTSERVICE_IID_STR "83123036-81c0-47cb-8d9c-bd85d29a1b3f"
#define NS_PISOCKETTRANSPORTSERVICE_IID \
{0x83123036, 0x81c0, 0x47cb, \
{ 0x8d, 0x9c, 0xbd, 0x85, 0xd2, 0x9a, 0x1b, 0x3f }}
/**
* This is a private interface used by the internals of the networking library.
* It will never be frozen. Do not use it in external code.
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsPISocketTransportService : public nsISocketTransportService {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_PISOCKETTRANSPORTSERVICE_IID)
/**
* init/shutdown routines.
*/
/* void init (); */
NS_SCRIPTABLE NS_IMETHOD Init(void) = 0;
/* void shutdown (); */
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) = 0;
/**
* controls whether or not the socket transport service should poke
* the autodialer on connection failure.
*/
/* attribute boolean autodialEnabled; */
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) = 0;
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) = 0;
/**
* controls the TCP sender window clamp
*/
/* readonly attribute long sendBufferSize; */
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsPISocketTransportService, NS_PISOCKETTRANSPORTSERVICE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSPISOCKETTRANSPORTSERVICE \
NS_SCRIPTABLE NS_IMETHOD Init(void); \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void); \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled); \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled); \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSPISOCKETTRANSPORTSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD Init(void) { return _to Init(); } \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) { return _to Shutdown(); } \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) { return _to GetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) { return _to SetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) { return _to GetSendBufferSize(aSendBufferSize); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSPISOCKETTRANSPORTSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD Init(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(); } \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Shutdown(); } \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSendBufferSize(aSendBufferSize); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class _MYCLASS_ : public nsPISocketTransportService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSPISOCKETTRANSPORTSERVICE
_MYCLASS_();
private:
~_MYCLASS_();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(_MYCLASS_, nsPISocketTransportService)
_MYCLASS_::_MYCLASS_()
{
/* member initializers and constructor code */
}
_MYCLASS_::~_MYCLASS_()
{
/* destructor code */
}
/* void init (); */
NS_IMETHODIMP _MYCLASS_::Init()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void shutdown (); */
NS_IMETHODIMP _MYCLASS_::Shutdown()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute boolean autodialEnabled; */
NS_IMETHODIMP _MYCLASS_::GetAutodialEnabled(PRBool *aAutodialEnabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP _MYCLASS_::SetAutodialEnabled(PRBool aAutodialEnabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute long sendBufferSize; */
NS_IMETHODIMP _MYCLASS_::GetSendBufferSize(PRInt32 *aSendBufferSize)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsPISocketTransportService_h__ */
| Java |
<div class="container profile">
<div class="row">
<div class="col-sm-10">
<div class="panel panel-default">
<div class="panel-body">
<h1>Adding new Value is the best</h1>
<legend>Contribution:</legend>
<div class="form-group">
<label class="control-label"><i class="ion-clipboard"></i> title</label>
<input type="text" id="title" class="form-control" ng-model="model.title" required/>
</div>
<div class="form-group">
<label class="control-label"><i class="ion-clipboard"></i> content</label>
<textarea class="form-control" id="title" ng-model="model.file" required rows="5"></textarea>
</div>
<legend>Contributers:</legend>
<div ng-repeat="contributer in model.contributers" >
<div class="row well-lg contributer-cell">
<div class = 'col-sm-2'>
<img class="img-rounded" ng-src="{{contributer.img}}" alt="" HEIGHT = 50 WIDTH=50>
</div>
<div class = 'col-sm-3'>
<select ng-model = "contributer.contributer_id" ng-options="user.id as user.name for user in contributer.usersList"
ng-change="contributer.img = updateContributer(contributer.contributer_id,$index)" data-placeholder="Choose Contributer">
</select>
</div>
<div class = 'col-sm-3'>
<input style="width: 200px;" type="range" min="0" max="100" step="1"
ng-disabled ="contributer.contributer_id == '0'" ng-model="contributer.contribution1" ng-change="changeContribution()">
</input>
</div>
<div class = 'col-sm-2'>
<input size = "5" type="text" disabled = "disabled" id="contributer_percentage" ng-model="contributer.contributer_percentage">
</input> %
</div>
<div class = 'col-sm-2'>
<button type="submit" class="btn btn-default" aria-label="Left Align" ng-click='removeCollaboratorItem($index)'>
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-default" aria-label="Left Align" ng-click='addCollaborator()'>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Collaborator
</button>
<div align="center" ><button type="submit" class="btn btn-warning submit-button"
ng-disabled="!model.title || !model.file || buttonDisabled" ng-click="onSubmit()">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div> | Java |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'theme_overlay', language 'es', branch 'MOODLE_22_STABLE'
*
* @package theme_overlay
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['configtitle'] = 'Ajustes Overlay';
$string['customcss'] = 'CSS personalizado';
$string['customcssdesc'] = 'Cualquier CSS que introduzca aquí será agregado a todas las páginas, permitiéndole personalizar con facilidad este tema.';
$string['footertext'] = 'Texto del pie de página';
$string['footertextdesc'] = 'Ajustar una nota o texto a pie de página.';
$string['headercolor'] = 'Color de la cabecera';
$string['headercolordesc'] = 'Color de fondo de la cabecera.';
$string['linkcolor'] = 'Color de los enlaces';
$string['linkcolordesc'] = 'Esta opción ajusta el color de los enlaces en el tema';
$string['pluginname'] = 'Overlay';
$string['region-side-post'] = 'Derecha';
$string['region-side-pre'] = 'Izquierda';
| Java |
package org.ovirt.engine.core.bll.scheduling.commands;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.scheduling.ClusterPolicy;
import org.ovirt.engine.core.common.scheduling.parameters.ClusterPolicyCRUDParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class ClusterPolicyCRUDCommandTest {
@Rule
public MockConfigRule mockConfigRule =
new MockConfigRule((MockConfigRule.mockConfig(ConfigValues.EnableVdsLoadBalancing, false)),
(MockConfigRule.mockConfig(ConfigValues.EnableVdsHaReservation, false)));
@Test
public void testCheckAddEditValidations() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertTrue(command.checkAddEditValidations());
}
@Test
public void testCheckAddEditValidationsFailOnParameters() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
HashMap<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("fail?", "sure, fail!");
clusterPolicy.setParameterMap(parameterMap);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertFalse(command.checkAddEditValidations());
}
}
| Java |
/*
Copyright (C) 2014-2019 [email protected]
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using dnSpy.Contracts.Images;
using dnSpy.Contracts.Menus;
using dnSpy.Contracts.ToolWindows;
using dnSpy.Contracts.ToolWindows.App;
namespace dnSpy.MainApp {
sealed class ToolWindowGroupContext {
public readonly IDsToolWindowService DsToolWindowService;
public readonly IToolWindowGroupService ToolWindowGroupService;
public readonly IToolWindowGroup ToolWindowGroup;
public ToolWindowGroupContext(IDsToolWindowService toolWindowService, IToolWindowGroup toolWindowGroup) {
DsToolWindowService = toolWindowService;
ToolWindowGroupService = toolWindowGroup.ToolWindowGroupService;
ToolWindowGroup = toolWindowGroup;
}
}
abstract class CtxMenuToolWindowGroupCommand : MenuItemBase<ToolWindowGroupContext> {
protected sealed override object CachedContextKey => ContextKey;
static readonly object ContextKey = new object();
protected sealed override ToolWindowGroupContext? CreateContext(IMenuItemContext context) => CreateContextInternal(context);
readonly IDsToolWindowService toolWindowService;
protected CtxMenuToolWindowGroupCommand(IDsToolWindowService toolWindowService) => this.toolWindowService = toolWindowService;
protected ToolWindowGroupContext? CreateContextInternal(IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_TOOLWINDOW_TABCONTROL_GUID))
return null;
var twg = context.Find<IToolWindowGroup>();
if (twg is null || !toolWindowService.Owns(twg))
return null;
return new ToolWindowGroupContext(toolWindowService, twg);
}
}
[ExportMenuItem(Header = "res:HideToolWindowCommand", InputGestureText = "res:ShortCutKeyShiftEsc", Icon = DsImagesAttribute.TableViewNameOnly, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 10)]
sealed class HideTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
HideTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroup.CloseActiveTabCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroup.CloseActiveTab();
}
[ExportMenuItem(Header = "res:HideAllToolWindowsCommand", Icon = DsImagesAttribute.CloseDocumentGroup, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 20)]
sealed class CloseAllTabsTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseAllTabsTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabs();
}
static class CmdConstants {
public const string MOVE_CONTENT_GUID = "D54D52CB-A6FC-408C-9A52-EA0D53AEEC3A";
public const string GROUP_MOVE_CONTENT = "0,92C51A9F-DE4B-4D7F-B1DC-AAA482936B5C";
public const string MOVE_GROUP_GUID = "047ECD64-82EF-4774-9C0A-330A61989432";
public const string GROUP_MOVE_GROUP = "0,174B60EE-279F-4DA4-9F07-44FFD03E4421";
}
[ExportMenuItem(Header = "res:MoveToolWindowCommand", Guid = CmdConstants.MOVE_CONTENT_GUID, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 30)]
sealed class MoveTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override void Execute(ToolWindowGroupContext context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(Header = "res:MoveToolWindowGroupCommand", Guid = CmdConstants.MOVE_GROUP_GUID, Group = MenuConstants.GROUP_CTX_TOOLWINS_CLOSE, Order = 40)]
sealed class MoveGroupTWCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroup.TabContents.Count() > 1;
public override void Execute(ToolWindowGroupContext context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 0)]
sealed class MoveTWTopCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWTopCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Top);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 10)]
sealed class MoveTWLeftCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWLeftCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Left);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 20)]
sealed class MoveTWRightCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWRightCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Right);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.ToolstripPanelBottom, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 30)]
sealed class MoveTWBottomCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTWBottomCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Bottom);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, AppToolWindowLocation.Bottom);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 0)]
sealed class MoveGroupTWTopCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWTopCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Top);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 10)]
sealed class MoveGroupTWLeftCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWLeftCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Left);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 20)]
sealed class MoveGroupTWRightCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWRightCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Right);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.ToolstripPanelBottom, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 30)]
sealed class MoveGroupTWBottomCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveGroupTWBottomCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(ToolWindowGroupContext context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, AppToolWindowLocation.Bottom);
public override void Execute(ToolWindowGroupContext context) => context.DsToolWindowService.Move(context.ToolWindowGroup, AppToolWindowLocation.Bottom);
}
[ExportMenuItem(Header = "res:NewHorizontalTabGroupCommand", Icon = DsImagesAttribute.SplitScreenHorizontally, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 0)]
sealed class NewHorizontalTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
NewHorizontalTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewHorizontalTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewHorizontalTabGroup();
}
[ExportMenuItem(Header = "res:NewVerticalTabGroupCommand", Icon = DsImagesAttribute.SplitScreenVertically, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 10)]
sealed class NewVerticalTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
NewVerticalTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewVerticalTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.NewVerticalTabGroup();
}
[ExportMenuItem(Header = "res:MoveToNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 20)]
sealed class MoveToNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveToNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveAllTabsToNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 30)]
sealed class MoveAllToNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveAllToNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveToPreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 40)]
sealed class MoveToPreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveToPreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToPreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveToPreviousTabGroup();
}
[ExportMenuItem(Header = "res:MoveAllToPreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPS, Order = 50)]
sealed class MoveAllToPreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveAllToPreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToPreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveAllToPreviousTabGroup();
}
[ExportMenuItem(Header = "res:CloseTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 0)]
sealed class CloseTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseTabGroup();
}
[ExportMenuItem(Header = "res:CloseAllTabGroupsButThisCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 10)]
sealed class CloseAllTabGroupsButThisCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
CloseAllTabGroupsButThisCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabGroupsButThisCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.CloseAllTabGroupsButThis();
}
[ExportMenuItem(Header = "res:MoveTabGroupAfterNextTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 20)]
sealed class MoveTabGroupAfterNextTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTabGroupAfterNextTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupAfterNextTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupAfterNextTabGroup();
}
[ExportMenuItem(Header = "res:MoveTabGroupBeforePreviousTabGroupCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 30)]
sealed class MoveTabGroupBeforePreviousTabGroupCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MoveTabGroupBeforePreviousTabGroupCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupBeforePreviousTabGroupCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MoveTabGroupBeforePreviousTabGroup();
}
[ExportMenuItem(Header = "res:MergeAllTabGroupsCommand", Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSCLOSE, Order = 40)]
sealed class MergeAllTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
MergeAllTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.MergeAllTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.MergeAllTabGroups();
}
[ExportMenuItem(Header = "res:UseVerticalTabGroupsCommand", Icon = DsImagesAttribute.SplitScreenVertically, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSVERT, Order = 0)]
sealed class UseVerticalTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
UseVerticalTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseVerticalTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseVerticalTabGroups();
}
[ExportMenuItem(Header = "res:UseHorizontalTabGroupsCommand", Icon = DsImagesAttribute.SplitScreenHorizontally, Group = MenuConstants.GROUP_CTX_TOOLWINS_GROUPSVERT, Order = 10)]
sealed class UseHorizontalTabGroupsCtxMenuCommand : CtxMenuToolWindowGroupCommand {
[ImportingConstructor]
UseHorizontalTabGroupsCtxMenuCommand(IDsToolWindowService toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseHorizontalTabGroupsCanExecute;
public override void Execute(ToolWindowGroupContext context) => context.ToolWindowGroupService.UseHorizontalTabGroups();
}
}
| Java |
'use strict';
/**
* Types of events
* @readonly
* @enum {number}
*/
var EventTypes = {
// Channel Events
/**
* A channel got connected
* @type {EventType}
*/
CONNECT: "connect",
/**
* A channel got disconnected
*/
DISCONNECT: "disconnect",
/**
* A channel got reconnected
*/
RECONNECT: "reconnect",
/**
* A channel is attempting to reconnect
*/
RECONNECTATTEMPT: "reconnect_attempt",
/**
* chatMode
*/
CHATMODE: "chatMode",
/**
* A list of current users in a channel
*/
CHANNELUSERS: "channelUsers",
/**
* A server message
*/
SERVERMESSAGE: "srvMsg",
/**
* A user message
*/
USERMESSAGE: "userMsg",
/**
* A /me message
*/
MEMESSAGE: "meMsg",
/**
* A /me message
*/
WHISPER: "whisper",
/**
* A global message
*/
GLOBALMESSAGE: "globalMsg",
/**
* An instruction/request to clear chat history
*/
CLEARCHAT: "clearChat",
/**
* A request for built-in command help
*/
COMMANDHELP: "commandHelp",
/**
* Whether or not mod tools should be visible
*/
MODTOOLSVISIBLE: "modToolsVisible",
/**
* A list of current mods in a channel
*/
MODLIST: "modList",
/**
* The color of the bot's name in chat
*/
COLOR: "color",
/**
* The online state of a stream
*/
ONLINESTATE: "onlineState",
/**
* A list of users included in a raffle
*/
RAFFLEUSERS: "raffleUsers",
/**
* The winner of a raffle
*/
WONRAFFLE: "wonRaffle",
/**
* runPoll
*/
RUNPOLL: "runPoll",
/**
* showPoll
*/
SHOWPOLL: "showPoll",
/**
* pollVotes
*/
POLLVOTES: "pollVotes",
/**
* voteResponse
*/
VOTERESPONSE: "voteResponse",
/**
* finishPoll
*/
FINISHPOLL: "finishPoll",
/**
* gameMode
*/
GAMEMODE: "gameMode",
/**
* adultMode
*/
ADULTMODE: "adultMode",
/**
* commissionsAvailable
*/
COMMISSIONSAVAILABLE: "commissionsAvailable",
/**
* clearUser
*/
CLEARUSER: "clearUser",
/**
* removeMsg
*/
REMOVEMESSAGE: "removeMsg",
/**
* A PTVAdmin? warning that a channel has adult content but is not in adult mode.
*/
WARNADULT: "warnAdult",
/**
* A PTVAdmin? warning that a channel has gaming content but is not in gaming mode.
*/
WARNGAMING: "warnGaming",
/**
* A PTVAdmin? warning that a channel has movie content.
*/
WARNMOVIES: "warnMovies",
/**
* The multistream status of a channel
*/
MULTISTATUS: "multiStatus",
/**
* Emitted after replaying chat history
*/
ENDHISTORY: "endHistory",
/**
* A list of people being ignored
*/
IGNORES: "ignores",
// Bot Events
/**
* The bot threw an exception
*/
EXCEPTION: "exception",
/**
* A bot command
*/
CHATCOMMAND: "chatCommand",
/**
* A console command
*/
CONSOLECOMMAND: "consoleCommand",
/**
* A command needs completing
*/
COMMANDCOMPLETION: "commandCompletion",
/**
* A plugin was loaded
*/
PLUGINLOADED: "pluginLoaded",
/**
* A plugin was started
*/
PLUGINSTARTED: "pluginStarted",
/**
* A plugin was loaded
*/
PLUGINUNLOADED: "pluginUnloaded",
/**
* A plugin was started
*/
PLUGINSTOPPED: "pluginStopped",
/**
* Used to query plugins if they want to add a cli option/flag
*/
CLIOPTIONS: "CLIOptions"
};
module.exports = EventTypes; | Java |
// Copyright 2015, 2016 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/>.
//! Ethcore basic typenames.
use util::hash::H2048;
/// Type for a 2048-bit log-bloom, as used by our blocks.
pub type LogBloom = H2048;
/// Constant 2048-bit datum for 0. Often used as a default.
pub static ZERO_LOGBLOOM: LogBloom = H2048([0x00; 256]);
#[cfg_attr(feature="dev", allow(enum_variant_names))]
/// Semantic boolean for when a seal/signature is included.
pub enum Seal {
/// The seal/signature is included.
With,
/// The seal/signature is not included.
Without,
}
| Java |
/****************************************************************************/
/// @file GUIColorScheme.h
/// @author Michael Behrisch
/// @author Daniel Krajzewicz
/// @date Mon, 20.07.2009
/// @version $Id: GUIColorScheme.h 14425 2013-08-16 20:11:47Z behrisch $
///
//
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
// Copyright (C) 2001-2013 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO 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.
//
/****************************************************************************/
#ifndef GUIColorScheme_h
#define GUIColorScheme_h
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <cassert>
#include <vector>
#include <utils/common/RGBColor.h>
#include <utils/iodevices/OutputDevice.h>
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class GUIColorScheme
* @brief
*/
class GUIColorScheme {
public:
/// Constructor
GUIColorScheme(const std::string& name, const RGBColor& baseColor,
const std::string& colName = "", const bool isFixed = false)
: myName(name), myIsInterpolated(!isFixed), myIsFixed(isFixed) {
addColor(baseColor, 0, colName);
}
void setThreshold(const size_t pos, const SUMOReal threshold) {
myThresholds[pos] = threshold;
}
void setColor(const size_t pos, const RGBColor& color) {
myColors[pos] = color;
}
bool setColor(const std::string& name, const RGBColor& color) {
std::vector<std::string>::iterator nameIt = myNames.begin();
std::vector<RGBColor>::iterator colIt = myColors.begin();
for (; nameIt != myNames.end(); ++nameIt, ++colIt) {
if (*nameIt == name) {
(*colIt) = color;
return true;
}
}
return false;
}
unsigned int addColor(const RGBColor& color, const SUMOReal threshold, const std::string& name = "") {
std::vector<RGBColor>::iterator colIt = myColors.begin();
std::vector<SUMOReal>::iterator threshIt = myThresholds.begin();
std::vector<std::string>::iterator nameIt = myNames.begin();
unsigned int pos = 0;
while (threshIt != myThresholds.end() && (*threshIt) < threshold) {
++threshIt;
++colIt;
++nameIt;
pos++;
}
myColors.insert(colIt, color);
myThresholds.insert(threshIt, threshold);
myNames.insert(nameIt, name);
return pos;
}
void removeColor(const size_t pos) {
assert(pos < myColors.size());
myColors.erase(myColors.begin() + pos);
myThresholds.erase(myThresholds.begin() + pos);
myNames.erase(myNames.begin() + pos);
}
void clear() {
myColors.clear();
myThresholds.clear();
myNames.clear();
}
const RGBColor getColor(const SUMOReal value) const {
if (myColors.size() == 1 || value < myThresholds.front()) {
return myColors.front();
}
std::vector<RGBColor>::const_iterator colIt = myColors.begin() + 1;
std::vector<SUMOReal>::const_iterator threshIt = myThresholds.begin() + 1;
while (threshIt != myThresholds.end() && (*threshIt) <= value) {
++threshIt;
++colIt;
}
if (threshIt == myThresholds.end()) {
return myColors.back();
}
if (!myIsInterpolated) {
return *(colIt - 1);
}
SUMOReal lowVal = *(threshIt - 1);
return RGBColor::interpolate(*(colIt - 1), *colIt, (value - lowVal) / ((*threshIt) - lowVal));
}
void setInterpolated(const bool interpolate, SUMOReal interpolationStart = 0.f) {
myIsInterpolated = interpolate;
if (interpolate) {
myThresholds[0] = interpolationStart;
}
}
const std::string& getName() const {
return myName;
}
const std::vector<RGBColor>& getColors() const {
return myColors;
}
const std::vector<SUMOReal>& getThresholds() const {
return myThresholds;
}
bool isInterpolated() const {
return myIsInterpolated;
}
const std::vector<std::string>& getNames() const {
return myNames;
}
bool isFixed() const {
return myIsFixed;
}
bool allowsNegativeValues() const {
return myAllowNegativeValues;
}
void setAllowsNegativeValues(bool value) {
myAllowNegativeValues = value;
}
void save(OutputDevice& dev) const {
dev << " <colorScheme name=\"" << myName;
if (!myIsFixed) {
dev << "\" interpolated=\"" << myIsInterpolated;
}
dev << "\">\n";
std::vector<RGBColor>::const_iterator colIt = myColors.begin();
std::vector<SUMOReal>::const_iterator threshIt = myThresholds.begin();
std::vector<std::string>::const_iterator nameIt = myNames.begin();
while (threshIt != myThresholds.end()) {
dev << " <entry color=\"" << (*colIt);
if (!myIsFixed) {
dev << "\" threshold=\"" << (*threshIt);
}
if ((*nameIt) != "") {
dev << "\" name=\"" << (*nameIt);
}
dev << "\"/>\n";
++threshIt;
++colIt;
++nameIt;
}
dev << " </colorScheme>\n";
}
bool operator==(const GUIColorScheme& c) const {
return myName == c.myName && myColors == c.myColors && myThresholds == c.myThresholds && myIsInterpolated == c.myIsInterpolated;
}
private:
std::string myName;
std::vector<RGBColor> myColors;
std::vector<SUMOReal> myThresholds;
bool myIsInterpolated;
std::vector<std::string> myNames;
bool myIsFixed;
bool myAllowNegativeValues;
};
#endif
/****************************************************************************/
| Java |
namespace Allors.Repository
{
using System;
using Attributes;
#region Allors
[Id("d0f9fc0d-a3c5-46cc-ab00-4c724995fc14")]
#endregion
public partial class FaceToFaceCommunication : CommunicationEvent, Versioned
{
#region inherited properties
public CommunicationEventState PreviousCommunicationEventState { get; set; }
public CommunicationEventState LastCommunicationEventState { get; set; }
public CommunicationEventState CommunicationEventState { get; set; }
public ObjectState[] PreviousObjectStates { get; set; }
public ObjectState[] LastObjectStates { get; set; }
public ObjectState[] ObjectStates { get; set; }
public SecurityToken OwnerSecurityToken { get; set; }
public AccessControl OwnerAccessControl { get; set; }
public DateTime ScheduledStart { get; set; }
public Party[] ToParties { get; set; }
public ContactMechanism[] ContactMechanisms { get; set; }
public Party[] InvolvedParties { get; set; }
public DateTime InitialScheduledStart { get; set; }
public CommunicationEventPurpose[] EventPurposes { get; set; }
public DateTime ScheduledEnd { get; set; }
public DateTime ActualEnd { get; set; }
public WorkEffort[] WorkEfforts { get; set; }
public string Description { get; set; }
public DateTime InitialScheduledEnd { get; set; }
public Party[] FromParties { get; set; }
public string Subject { get; set; }
public Media[] Documents { get; set; }
public Case Case { get; set; }
public Priority Priority { get; set; }
public Person Owner { get; set; }
public string Note { get; set; }
public DateTime ActualStart { get; set; }
public bool SendNotification { get; set; }
public bool SendReminder { get; set; }
public DateTime RemindAt { get; set; }
public Permission[] DeniedPermissions { get; set; }
public SecurityToken[] SecurityTokens { get; set; }
public string Comment { get; set; }
public LocalisedText[] LocalisedComments { get; set; }
public Guid UniqueId { get; set; }
public User CreatedBy { get; set; }
public User LastModifiedBy { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastModifiedDate { get; set; }
#endregion
#region Allors
[Id("52b8614b-799e-4aea-a012-ea8dbc23f8dd")]
[AssociationId("ac424847-d426-4614-99a2-37c70841c454")]
[RoleId("bcf4a8df-8b57-4b3c-a6e5-f9b56c71a13b")]
#endregion
[Multiplicity(Multiplicity.ManyToMany)]
[Indexed]
[Workspace]
public Party[] Participants { get; set; }
#region Allors
[Id("95ae979f-d549-4ea1-87f0-46aa55e4b14a")]
[AssociationId("d34e4203-0bd2-4fe4-a2ef-9f9f52b49cf9")]
[RoleId("9f67b296-953d-4e04-b94d-6ffece87ceef")]
#endregion
[Size(256)]
[Workspace]
public string Location { get; set; }
#region Versioning
#region Allors
[Id("4339C173-EEAA-4B11-8E54-D96C98B2AF01")]
[AssociationId("41DDA0ED-160D-41B7-A347-CD167A957555")]
[RoleId("DE4BD7DC-B219-4CE6-9F03-4E7F4681BFEC")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToOne)]
[Workspace]
public FaceToFaceCommunicationVersion CurrentVersion { get; set; }
#region Allors
[Id("B97DEBD2-482A-47A7-A7A2-FBC3FD20E7B4")]
[AssociationId("428849DB-9000-4107-A68E-27FA4828344E")]
[RoleId("4F9C3CE5-3418-484C-A770-48D2EDEB6E6A")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToMany)]
[Workspace]
public FaceToFaceCommunicationVersion[] AllVersions { get; set; }
#endregion
#region inherited methods
public void OnBuild(){}
public void OnPostBuild(){}
public void OnPreDerive(){}
public void OnDerive(){}
public void OnPostDerive(){}
public void Cancel(){}
public void Close(){}
public void Reopen(){}
public void Delete(){}
#endregion
}
} | Java |
package com.xxl.job.admin.core.route.strategy;
import com.xxl.job.admin.core.route.ExecutorRouter;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 单个JOB对应的每个执行器,使用频率最低的优先被选举
* a(*)、LFU(Least Frequently Used):最不经常使用,频率/次数
* b、LRU(Least Recently Used):最近最久未使用,时间
*
* Created by xuxueli on 17/3/10.
*/
public class ExecutorRouteLFU extends ExecutorRouter {
private static ConcurrentMap<Integer, HashMap<String, Integer>> jobLfuMap = new ConcurrentHashMap<Integer, HashMap<String, Integer>>();
private static long CACHE_VALID_TIME = 0;
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
// lfu item init
HashMap<String, Integer> lfuItemMap = jobLfuMap.get(jobId); // Key排序可以用TreeMap+构造入参Compare;Value排序暂时只能通过ArrayList;
if (lfuItemMap == null) {
lfuItemMap = new HashMap<String, Integer>();
jobLfuMap.putIfAbsent(jobId, lfuItemMap); // 避免重复覆盖
}
// put new
for (String address: addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次,缓解首次压力
}
}
// remove old
List<String> delKeys = new ArrayList<>();
for (String existKey: lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (String delKey: delKeys) {
lfuItemMap.remove(delKey);
}
}
// load least userd count address
List<Map.Entry<String, Integer>> lfuItemList = new ArrayList<Map.Entry<String, Integer>>(lfuItemMap.entrySet());
Collections.sort(lfuItemList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map.Entry<String, Integer> addressItem = lfuItemList.get(0);
String minAddress = addressItem.getKey();
addressItem.setValue(addressItem.getValue() + 1);
return addressItem.getKey();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = route(triggerParam.getJobId(), addressList);
return new ReturnT<String>(address);
}
}
| Java |
package com.bioxx.tfc2.gui;
import java.awt.Rectangle;
import java.util.Collection;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.stats.AchievementList;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc2.Core;
import com.bioxx.tfc2.Reference;
import com.bioxx.tfc2.core.PlayerInventory;
public class GuiInventoryTFC extends InventoryEffectRenderer
{
private float xSizeLow;
private float ySizeLow;
private boolean hasEffect;
protected static final ResourceLocation UPPER_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inventory.png");
protected static final ResourceLocation UPPER_TEXTURE_2X2 = new ResourceLocation(Reference.ModID+":textures/gui/gui_inventory2x2.png");
protected static final ResourceLocation EFFECTS_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inv_effects.png");
protected EntityPlayer player;
protected Slot activeSlot;
public GuiInventoryTFC(EntityPlayer player)
{
super(player.inventoryContainer);
this.allowUserInput = true;
player.addStat(AchievementList.OPEN_INVENTORY, 1);
xSize = 176;
ySize = 102 + PlayerInventory.invYSize;
this.player = player;
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if(player.getEntityData().hasKey("craftingTable"))
Core.bindTexture(UPPER_TEXTURE);
else
Core.bindTexture(UPPER_TEXTURE_2X2);
int k = this.guiLeft;
int l = this.guiTop;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, 102);
//Draw the player avatar
GuiInventory.drawEntityOnScreen(k + 51, l + 75, 30, k + 51 - this.xSizeLow, l + 75 - 50 - this.ySizeLow, this.mc.player);
PlayerInventory.drawInventory(this, width, height, ySize - PlayerInventory.invYSize);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
//this.fontRenderer.drawString(I18n.format("container.crafting", new Object[0]), 86, 7, 4210752);
}
@Override
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
if (this.mc.playerController.isInCreativeMode())
this.mc.displayGuiScreen(new GuiContainerCreative(player));
}
@Override
public void initGui()
{
super.buttonList.clear();
if (this.mc.playerController.isInCreativeMode())
{
this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.player));
}
else
super.initGui();
if (!this.mc.player.getActivePotionEffects().isEmpty())
{
//this.guiLeft = 160 + (this.width - this.xSize - 200) / 2;
this.guiLeft = (this.width - this.xSize) / 2;
this.hasEffect = true;
}
buttonList.clear();
buttonList.add(new GuiInventoryButton(0, new Rectangle(guiLeft+176, guiTop + 3, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Inventory"), new Rectangle(1,223,32,32)));
buttonList.add(new GuiInventoryButton(1, new Rectangle(guiLeft+176, guiTop + 22, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Skills"), new Rectangle(100,223,32,32)));
buttonList.add(new GuiInventoryButton(2, new Rectangle(guiLeft+176, guiTop + 41, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Calendar.Calendar"), new Rectangle(34,223,32,32)));
buttonList.add(new GuiInventoryButton(3, new Rectangle(guiLeft+176, guiTop + 60, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Health"), new Rectangle(67,223,32,32)));
}
@Override
protected void actionPerformed(GuiButton guibutton)
{
//Removed during port
if (guibutton.id == 1)
Minecraft.getMinecraft().displayGuiScreen(new GuiSkills(player));
/*else if (guibutton.id == 2)
Minecraft.getMinecraft().displayGuiScreen(new GuiCalendar(player));*/
else if (guibutton.id == 3)
Minecraft.getMinecraft().displayGuiScreen(new GuiHealth(player));
}
@Override
public void drawScreen(int par1, int par2, float par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
super.drawScreen(par1, par2, par3);
this.xSizeLow = par1;
this.ySizeLow = par2;
if(hasEffect)
displayDebuffEffects();
//removed during port
/*for (int j1 = 0; j1 < this.inventorySlots.inventorySlots.size(); ++j1)
{
Slot slot = (Slot)this.inventorySlots.inventorySlots.get(j1);
if (this.isMouseOverSlot(slot, par1, par2) && slot.func_111238_b())
this.activeSlot = slot;
}*/
}
protected boolean isMouseOverSlot(Slot par1Slot, int par2, int par3)
{
return this.isPointInRegion(par1Slot.xPos, par1Slot.yPos, 16, 16, par2, par3);
}
/**
* Displays debuff/potion effects that are currently being applied to the player
*/
private void displayDebuffEffects()
{
int var1 = this.guiLeft - 124;
int var2 = this.guiTop;
Collection var4 = this.mc.player.getActivePotionEffects();
//Remvoed during port
/*if (!var4.isEmpty())
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
int var6 = 33;
if (var4.size() > 5)
var6 = 132 / (var4.size() - 1);
for (Iterator var7 = this.mc.player.getActivePotionEffects().iterator(); var7.hasNext(); var2 += var6)
{
PotionEffect var8 = (PotionEffect)var7.next();
Potion var9 = Potion.potionTypes[var8.getPotionID()] instanceof TFCPotion ?
((TFCPotion) Potion.potionTypes[var8.getPotionID()]) :
Potion.potionTypes[var8.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
TFC_Core.bindTexture(EFFECTS_TEXTURE);
this.drawTexturedModalRect(var1, var2, 0, 166, 140, 32);
if (var9.hasStatusIcon())
{
int var10 = var9.getStatusIconIndex();
this.drawTexturedModalRect(var1 + 6, var2 + 7, 0 + var10 % 8 * 18, 198 + var10 / 8 * 18, 18, 18);
}
String var12 = Core.translate(var9.getName());
if (var8.getAmplifier() == 1)
var12 = var12 + " II";
else if (var8.getAmplifier() == 2)
var12 = var12 + " III";
else if (var8.getAmplifier() == 3)
var12 = var12 + " IV";
this.fontRenderer.drawStringWithShadow(var12, var1 + 10 + 18, var2 + 6, 16777215);
String var11 = Potion.getDurationString(var8);
this.fontRenderer.drawStringWithShadow(var11, var1 + 10 + 18, var2 + 6 + 10, 8355711);
}
}*/
}
private long spamTimer;
@Override
protected boolean checkHotbarKeys(int keycode)
{
/*if(this.activeSlot != null && this.activeSlot.slotNumber == 0 && this.activeSlot.getHasStack() &&
this.activeSlot.getStack().getItem() instanceof IFood)
return false;*/
return super.checkHotbarKeys(keycode);
}
private int getEmptyCraftSlot()
{
if(this.inventorySlots.getSlot(4).getStack() == null)
return 4;
if(this.inventorySlots.getSlot(1).getStack() == null)
return 1;
if(this.inventorySlots.getSlot(2).getStack() == null)
return 2;
if(this.inventorySlots.getSlot(3).getStack() == null)
return 3;
if(player.getEntityData().hasKey("craftingTable"))
{
if(this.inventorySlots.getSlot(45).getStack() == null)
return 45;
if(this.inventorySlots.getSlot(46).getStack() == null)
return 46;
if(this.inventorySlots.getSlot(47).getStack() == null)
return 47;
if(this.inventorySlots.getSlot(48).getStack() == null)
return 48;
if(this.inventorySlots.getSlot(49).getStack() == null)
return 49;
}
return -1;
}
}
| Java |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_show_tab.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pgritsen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/05 19:31:02 by pgritsen #+# #+# */
/* Updated: 2017/08/05 19:31:04 by pgritsen ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_stock_par.h"
void ft_putchar(char c);
void ft_putstr(char *str)
{
int it;
it = 0;
while (str[it] != 0)
ft_putchar(str[it++]);
}
void ft_putnbr(int nb)
{
long int mult;
long int nb_t;
mult = 1;
nb_t = nb;
if (nb_t < 0)
{
ft_putchar('-');
nb_t *= -1;
}
if (nb_t == 0)
ft_putchar('0');
while (nb_t / mult != 0)
mult *= 10;
while (mult > 1)
{
mult /= 10;
if (mult == 0)
ft_putchar(nb_t + 48);
else
ft_putchar(nb_t / mult + 48);
nb_t %= mult;
}
}
void ft_show_tab(struct s_stock_par *par)
{
int it;
int argv_it;
it = 0;
while (par[it].str)
{
ft_putstr(par[it].copy);
ft_putchar('\n');
ft_putnbr(par[it].size_param);
ft_putchar('\n');
argv_it = 0;
while (par[it].tab[argv_it])
{
ft_putstr(par[it].tab[argv_it]);
ft_putchar('\n');
argv_it++;
}
it++;
}
}
| Java |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=manga_ranobe_storage_app',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
]; | Java |
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_V8_DEBUG_H_
#define V8_V8_DEBUG_H_
#include "v8.h"
#ifdef _WIN32
typedef int int32_t;
typedef unsigned int uint32_t;
typedef unsigned short uint16_t; // NOLINT
typedef long long int64_t; // NOLINT
// Setup for Windows DLL export/import. See v8.h in this directory for
// information on how to build/use V8 as a DLL.
#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
build configuration to ensure that at most one of these is set
#endif
#ifdef BUILDING_V8_SHARED
#define EXPORT __declspec(dllexport)
#elif USING_V8_SHARED
#define EXPORT __declspec(dllimport)
#else
#define EXPORT
#endif
#else // _WIN32
// Setup for Linux shared library export. See v8.h in this directory for
// information on how to build/use V8 as shared library.
#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(V8_SHARED)
#define EXPORT __attribute__ ((visibility("default")))
#else // defined(__GNUC__) && (__GNUC__ >= 4)
#define EXPORT
#endif // defined(__GNUC__) && (__GNUC__ >= 4)
#endif // _WIN32
/**
* Debugger support for the V8 JavaScript engine.
*/
namespace v8 {
// Debug events which can occur in the V8 JavaScript engine.
enum DebugEvent {
Break = 1,
Exception = 2,
NewFunction = 3,
BeforeCompile = 4,
AfterCompile = 5,
ScriptCollected = 6,
BreakForCommand = 7
};
class EXPORT Debug {
public:
/**
* A client object passed to the v8 debugger whose ownership will be taken by
* it. v8 is always responsible for deleting the object.
*/
class ClientData {
public:
virtual ~ClientData() {}
};
/**
* A message object passed to the debug message handler.
*/
class Message {
public:
/**
* Check type of message.
*/
virtual bool IsEvent() const = 0;
virtual bool IsResponse() const = 0;
virtual DebugEvent GetEvent() const = 0;
/**
* Indicate whether this is a response to a continue command which will
* start the VM running after this is processed.
*/
virtual bool WillStartRunning() const = 0;
/**
* Access to execution state and event data. Don't store these cross
* callbacks as their content becomes invalid. These objects are from the
* debugger event that started the debug message loop.
*/
virtual Handle<Object> GetExecutionState() const = 0;
virtual Handle<Object> GetEventData() const = 0;
/**
* Get the debugger protocol JSON.
*/
virtual Handle<String> GetJSON() const = 0;
/**
* Get the context active when the debug event happened. Note this is not
* the current active context as the JavaScript part of the debugger is
* running in it's own context which is entered at this point.
*/
virtual Handle<Context> GetEventContext() const = 0;
/**
* Client data passed with the corresponding request if any. This is the
* client_data data value passed into Debug::SendCommand along with the
* request that led to the message or NULL if the message is an event. The
* debugger takes ownership of the data and will delete it even if there is
* no message handler.
*/
virtual ClientData* GetClientData() const = 0;
virtual ~Message() {}
};
/**
* An event details object passed to the debug event listener.
*/
class EventDetails {
public:
/**
* Event type.
*/
virtual DebugEvent GetEvent() const = 0;
/**
* Access to execution state and event data of the debug event. Don't store
* these cross callbacks as their content becomes invalid.
*/
virtual Handle<Object> GetExecutionState() const = 0;
virtual Handle<Object> GetEventData() const = 0;
/**
* Get the context active when the debug event happened. Note this is not
* the current active context as the JavaScript part of the debugger is
* running in it's own context which is entered at this point.
*/
virtual Handle<Context> GetEventContext() const = 0;
/**
* Client data passed with the corresponding callbak whet it was registered.
*/
virtual Handle<Value> GetCallbackData() const = 0;
/**
* Client data passed to DebugBreakForCommand function. The
* debugger takes ownership of the data and will delete it even if
* there is no message handler.
*/
virtual ClientData* GetClientData() const = 0;
virtual ~EventDetails() {}
};
/**
* Debug event callback function.
*
* \param event the type of the debug event that triggered the callback
* (enum DebugEvent)
* \param exec_state execution state (JavaScript object)
* \param event_data event specific data (JavaScript object)
* \param data value passed by the user to SetDebugEventListener
*/
typedef void (*EventCallback)(DebugEvent event,
Handle<Object> exec_state,
Handle<Object> event_data,
Handle<Value> data);
/**
* Debug event callback function.
*
* \param event_details object providing information about the debug event
*
* A EventCallback2 does not take possession of the event data,
* and must not rely on the data persisting after the handler returns.
*/
typedef void (*EventCallback2)(const EventDetails& event_details);
/**
* Debug message callback function.
*
* \param message the debug message handler message object
* \param length length of the message
* \param client_data the data value passed when registering the message handler
* A MessageHandler does not take possession of the message string,
* and must not rely on the data persisting after the handler returns.
*
* This message handler is deprecated. Use MessageHandler2 instead.
*/
typedef void (*MessageHandler)(const uint16_t* message, int length,
ClientData* client_data);
/**
* Debug message callback function.
*
* \param message the debug message handler message object
* A MessageHandler does not take possession of the message data,
* and must not rely on the data persisting after the handler returns.
*/
typedef void (*MessageHandler2)(const Message& message);
/**
* Debug host dispatch callback function.
*/
typedef void (*HostDispatchHandler)();
/**
* Callback function for the host to ensure debug messages are processed.
*/
typedef void (*DebugMessageDispatchHandler)();
// Set a C debug event listener.
static bool SetDebugEventListener(EventCallback that,
Handle<Value> data = Handle<Value>());
static bool SetDebugEventListener2(EventCallback2 that,
Handle<Value> data = Handle<Value>());
// Set a JavaScript debug event listener.
static bool SetDebugEventListener(v8::Handle<v8::Object> that,
Handle<Value> data = Handle<Value>());
// Schedule a debugger break to happen when JavaScript code is run.
static void DebugBreak();
// Remove scheduled debugger break if it has not happened yet.
static void CancelDebugBreak();
// Break execution of JavaScript (this method can be invoked from a
// non-VM thread) for further client command execution on a VM
// thread. Client data is then passed in EventDetails to
// EventCallback at the moment when the VM actually stops.
static void DebugBreakForCommand(ClientData* data = NULL);
// Message based interface. The message protocol is JSON. NOTE the message
// handler thread is not supported any more parameter must be false.
static void SetMessageHandler(MessageHandler handler,
bool message_handler_thread = false);
static void SetMessageHandler2(MessageHandler2 handler);
static void SendCommand(const uint16_t* command, int length,
ClientData* client_data = NULL);
// Dispatch interface.
static void SetHostDispatchHandler(HostDispatchHandler handler,
int period = 100);
/**
* Register a callback function to be called when a debug message has been
* received and is ready to be processed. For the debug messages to be
* processed V8 needs to be entered, and in certain embedding scenarios this
* callback can be used to make sure V8 is entered for the debug message to
* be processed. Note that debug messages will only be processed if there is
* a V8 break. This can happen automatically by using the option
* --debugger-auto-break.
* \param provide_locker requires that V8 acquires v8::Locker for you before
* calling handler
*/
static void SetDebugMessageDispatchHandler(
DebugMessageDispatchHandler handler, bool provide_locker = false);
/**
* Run a JavaScript function in the debugger.
* \param fun the function to call
* \param data passed as second argument to the function
* With this call the debugger is entered and the function specified is called
* with the execution state as the first argument. This makes it possible to
* get access to information otherwise not available during normal JavaScript
* execution e.g. details on stack frames. Receiver of the function call will
* be the debugger context global object, however this is a subject to change.
* The following example show a JavaScript function which when passed to
* v8::Debug::Call will return the current line of JavaScript execution.
*
* \code
* function frame_source_line(exec_state) {
* return exec_state.frame(0).sourceLine();
* }
* \endcode
*/
static Local<Value> Call(v8::Handle<v8::Function> fun,
Handle<Value> data = Handle<Value>());
/**
* Returns a mirror object for the given object.
*/
static Local<Value> GetMirror(v8::Handle<v8::Value> obj);
/**
* Enable the V8 builtin debug agent. The debugger agent will listen on the
* supplied TCP/IP port for remote debugger connection.
* \param name the name of the embedding application
* \param port the TCP/IP port to listen on
* \param wait_for_connection whether V8 should pause on a first statement
* allowing remote debugger to connect before anything interesting happened
*/
static bool EnableAgent(const char* name, int port,
bool wait_for_connection = false);
/**
* Makes V8 process all pending debug messages.
*
* From V8 point of view all debug messages come asynchronously (e.g. from
* remote debugger) but they all must be handled synchronously: V8 cannot
* do 2 things at one time so normal script execution must be interrupted
* for a while.
*
* Generally when message arrives V8 may be in one of 3 states:
* 1. V8 is running script; V8 will automatically interrupt and process all
* pending messages (however auto_break flag should be enabled);
* 2. V8 is suspended on debug breakpoint; in this state V8 is dedicated
* to reading and processing debug messages;
* 3. V8 is not running at all or has called some long-working C++ function;
* by default it means that processing of all debug message will be deferred
* until V8 gets control again; however, embedding application may improve
* this by manually calling this method.
*
* It makes sense to call this method whenever a new debug message arrived and
* V8 is not already running. Method v8::Debug::SetDebugMessageDispatchHandler
* should help with the former condition.
*
* Technically this method in many senses is equivalent to executing empty
* script:
* 1. It does nothing except for processing all pending debug messages.
* 2. It should be invoked with the same precautions and from the same context
* as V8 script would be invoked from, because:
* a. with "evaluate" command it can do whatever normal script can do,
* including all native calls;
* b. no other thread should call V8 while this method is running
* (v8::Locker may be used here).
*
* "Evaluate" debug command behavior currently is not specified in scope
* of this method.
*/
static void ProcessDebugMessages();
/**
* Debugger is running in it's own context which is entered while debugger
* messages are being dispatched. This is an explicit getter for this
* debugger context. Note that the content of the debugger context is subject
* to change.
*/
static Local<Context> GetDebugContext();
};
} // namespace v8
#undef EXPORT
#endif // V8_V8_DEBUG_H_
| Java |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* FUEL CMS
* http://www.getfuelcms.com
*
* An open source Content Management System based on the
* Codeigniter framework (http://codeigniter.com)
*
* @package FUEL CMS
* @author David McReynolds @ Daylight Studio
* @copyright Copyright (c) 2015, Run for Daylight LLC.
* @license http://docs.getfuelcms.com/general/license
* @link http://www.getfuelcms.com
*/
// ------------------------------------------------------------------------
/**
* An alternative to the CI Validation class
*
* This class is used in MY_Model and the Form class. Does not require
* post data and is a little more generic then the CI Validation class.
* The <a href="[user_guide_url]helpers/validator_helper">validator_helper</a>
* that contains many helpful rule functions is automatically loaded.
*
* @package FUEL CMS
* @subpackage Libraries
* @category Libraries
* @author David McReynolds @ Daylight Studio
* @link http://docs.getfuelcms.com/libraries/validator
*/
class Validator {
public $field_error_delimiter = "\n"; // delimiter for rendering multiple errors for a field
public $stack_field_errors = FALSE; // stack multiple field errors if any or just replace with the newest
public $register_to_global_errors = TRUE; // will add to the globals error array
public $load_helpers = TRUE; // will automatically load the validator helpers
protected $_fields = array(); // fields to validate
protected $_errors = array(); // errors after running validation
// --------------------------------------------------------------------
/**
* Constructor
*
* Accepts an associative array as input, containing preferences (optional)
*
* @access public
* @param array config preferences
* @return void
*/
public function __construct ($params = array()) {
if (!defined('GLOBAL_ERRORS'))
{
define('GLOBAL_ERRORS', '__ERRORS__');
}
if (!isset($GLOBALS[GLOBAL_ERRORS])) $GLOBALS[GLOBAL_ERRORS] = array();
if (function_exists('get_instance') && $this->load_helpers)
{
$CI =& get_instance();
$CI->load->helper('validator');
}
if (count($params) > 0)
{
$this->initialize($params);
}
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* @access public
* @param array
* @return void
*/
public function initialize($params = array())
{
$this->reset();
$this->set_params($params);
}
// --------------------------------------------------------------------
/**
* Set object parameters
*
* @access public
* @param array
* @return void
*/
function set_params($params)
{
if (is_array($params) AND count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Add processing rule (function) to an input variable.
* The <a href="[user_guide_url]helpers/validator_helper">validator_helper</a> contains many helpful rule functions you can use
*
* @access public
* @param string key in processing array to assign to rule. Often times its the same name as the field input
* @param string error message
* @param string function for processing
* @param mixed function arguments with the first usually being the posted value. If multiple arguments need to be passed, then you can use an array.
* @return void
*/
public function add_rule($field, $func, $msg, $params = array())
{
if (empty($fields[$field])) $fields[$field] = array();
settype($params, 'array');
// if params are emtpy then we will look in the $_POST
if (empty($params))
{
if (!empty($_POST[$field])) $params = $_POST[$field];
if (empty($params[$field]) AND !empty($_FILES[$field])) $params = $_FILES[$field];
}
$rule = new Validator_Rule($func, $msg, $params);
$this->_fields[$field][] = $rule;
}
// --------------------------------------------------------------------
/**
* Removes rule from validation
*
* @access public
* @param string field to remove
* @param string key for rule (can have more then one rule for a field) (optional)
* @return void
*/
public function remove_rule($field, $func = NULL)
{
if (!empty($func))
{
if (!isset($this->_fields[$field]))
{
return;
}
foreach($this->_fields[$field] as $key => $rule)
{
if ($rule->func == $func)
{
unset($this->_fields[$field][$key]);
}
}
}
else
{
// remove all rules
unset($this->_fields[$field]);
}
}
// --------------------------------------------------------------------
/**
* Runs through validation
*
* @access public
* @param array assoc array of values to validate (optional)
* @param boolean exit on first error? (optional)
* @param boolean reset validation errors (optional)
* @return boolean
*/
public function validate($values = array(), $stop_on_first = FALSE, $reset = TRUE)
{
// reset errors to start with a fresh validation
if ($reset) $this->_errors = array();
//if (empty($values)) $values = $_POST;
if (empty($values))
{
$values = array_keys($this->_fields);
}
else if (!array_key_exists(0, $values)) // detect if it is an associative array and if so just use keys
{
$values = array_keys($values);
}
foreach($values as $key)
{
if (!empty($this->_fields[$key]))
{
$rules = $this->_fields[$key];
foreach($rules as $key2 => $val2)
{
$ok = $val2->run();
if (!$ok)
{
$this->catch_error($val2->get_message(), $key);
if (!empty($stop_on_first)) return FALSE;
}
}
}
}
return $this->is_valid();
}
// --------------------------------------------------------------------
/**
* Checks to see if it validates
*
* @access public
* @return boolean
*/
public function is_valid()
{
return (count($this->_errors) <= 0);
}
// --------------------------------------------------------------------
/**
* Catches error into the global array
*
* @access public
* @param string msg error message
* @param mixed key to identify error message
* @return string key of variable input
*/
public function catch_error($msg, $key = NULL)
{
if (empty($key)) $key = count($this->_errors);
if ($this->stack_field_errors)
{
$this->_errors[$key] = (!empty($this->_errors[$key])) ? $this->_errors[$key] = $this->_errors[$key].$this->field_error_delimiter.$msg : $msg;
}
else
{
$this->_errors[$key] = $msg;
}
if ($this->register_to_global_errors)
{
$GLOBALS[GLOBAL_ERRORS][$key] = $this->_errors[$key];
}
return $key;
}
// --------------------------------------------------------------------
/**
* Catches multiple errors
*
* @access public
* @param array of error messages
* @param key of error message if a single message
* @return string key of variable input
*/
public function catch_errors($errors, $key = NULL)
{
if (is_array($errors))
{
foreach($errors as $key => $val)
{
if (is_int($key))
{
$this->catch_error($val);
}
else
{
$this->catch_error($val, $key);
}
}
}
else
{
return $this->catch_error($errors, $key);
}
}
// --------------------------------------------------------------------
/**
* Retrieve errors
*
* @access public
* @return assoc array of errors and messages
*/
public function get_errors()
{
return $this->_errors;
}
// --------------------------------------------------------------------
/**
* Retrieves a single error
*
* @access public
* @param mixed key to error message
* @return string error message
*/
public function get_error($key)
{
if (!empty($this->_errors[$key]))
{
return $this->_errors[$key];
}
else
{
return NULL;
}
}
// --------------------------------------------------------------------
/**
* Retrieves the last error message
*
* @access public
* @return string error message
*/
public function get_last_error()
{
if (!empty($this->_errors))
{
return end($this->_errors);
}
else
{
return NULL;
}
}
// --------------------------------------------------------------------
/**
* Returns the fields with rules
* @access public
* @return array
*/
public function fields()
{
return $this->_fields;
}
// --------------------------------------------------------------------
/**
* Same as reset
*
* @access public
* @return void
*/
public function clear()
{
$this->reset();
}
// --------------------------------------------------------------------
/**
* Resets rules and errors
* @access public
* @return void
*/
public function reset($remove_fields = TRUE)
{
$this->_errors = array();
if ($remove_fields)
{
$this->_fields = array();
}
}
}
// ------------------------------------------------------------------------
/**
* Validation rule object
*
* @package FUEL CMS
* @subpackage Libraries
* @category Libraries
* @author David McReynolds @ Daylight Studio
* @autodoc FALSE
*/
class Validator_Rule {
public $func; // function to execute that will return TRUE/FALSE
public $msg; // message to be display on error
public $args; // arguments to pass to the function
/**
* Validator rule constructor
*
* @param string function to execute that will return TRUE/FALSE
* @param string message to be display on error
* @param mixed arguments to pass to the function
*/
public function __construct($func, $msg, $args)
{
$this->func = $func;
$this->msg = $msg;
if (!is_array($args))
{
$this->args[] = $args;
}
else if (empty($args))
{ // create first argument
$this->args[] = '';
}
else
{
$this->args = $args;
}
}
/**
* Runs the rules function
*
* @access public
* @return boolean (should return TRUE/FALSE but it depends on the function of course)
*/
public function run()
{
return call_user_func_array($this->func, $this->args);
}
/**
* Retrieve errors
*
* @access public
* @return string error message
*/
public function get_message()
{
return $this->msg;
}
}
/* End of file Validator.php */
/* Location: ./modules/fuel/libraries/Validator.php */ | Java |
/*
* GPXParser.java
*
* Copyright (c) 2012, AlternativeVision. All rights reserved.
*
* This 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.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.alternativevision.gpx;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.alternativevision.gpx.beans.GPX;
import org.alternativevision.gpx.beans.Route;
import org.alternativevision.gpx.beans.Track;
import org.alternativevision.gpx.beans.Waypoint;
import org.alternativevision.gpx.extensions.IExtensionParser;
import org.alternativevision.gpx.types.FixType;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* <p>This class defines methods for parsing and writing gpx files.</p>
* <br>
* Usage for parsing a gpx file into a {@link GPX} object:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileInputStream in = new FileInputStream("inFile.gpx");<br>
* GPX gpx = p.parseGPX(in);<br>
* </code>
* <br>
* Usage for writing a {@link GPX} object to a file:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileOutputStream out = new FileOutputStream("outFile.gpx");<br>
* p.writeGPX(gpx, out);<br>
* out.close();<br>
* </code>
*/
public class GPXParser {
private ArrayList<IExtensionParser> extensionParsers = new ArrayList<IExtensionParser>();
private Logger logger = Logger.getLogger(this.getClass().getName());
private DocumentBuilderFactory docFactory= DocumentBuilderFactory.newInstance();
private TransformerFactory tFactory = TransformerFactory.newInstance();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss");
private SimpleDateFormat sdfZ = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'");
/**
* Adds a new extension parser to be used when parsing a gpx steam
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void addExtensionParser(IExtensionParser parser) {
extensionParsers.add(parser);
}
/**
* Removes an extension parser previously added
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void removeExtensionParser(IExtensionParser parser) {
extensionParsers.remove(parser);
}
public GPX parseGPX(File gpxFile) throws IOException, ParserConfigurationException, SAXException, IOException {
InputStream in = FileUtils.openInputStream(gpxFile);
GPX gpx = parseGPX(in);
in.close();
return gpx;
}
/**
* Parses a stream containing GPX data
*
* @param in the input stream
* @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.parse(in);
Node firstChild = doc.getFirstChild();
if( firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) {
GPX gpx = new GPX();
NamedNodeMap attrs = firstChild.getAttributes();
for(int idx = 0; idx < attrs.getLength(); idx++) {
Node attr = attrs.item(idx);
if(GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) {
gpx.setVersion(attr.getNodeValue());
} else if(GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) {
gpx.setCreator(attr.getNodeValue());
}
}
NodeList nodes = firstChild.getChildNodes();
if(logger.isDebugEnabled())logger.debug("Found " +nodes.getLength()+ " child nodes. Start parsing ...");
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found waypoint node. Start parsing...");
Waypoint w = parseWaypoint(currentNode);
if(w!= null) {
logger.info("Add waypoint to gpx data. [waypointName="+ w.getName() + "]");
gpx.addWaypoint(w);
}
} else if(GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found track node. Start parsing...");
Track trk = parseTrack(currentNode);
if(trk!= null) {
logger.info("Add track to gpx data. [trackName="+ trk.getName() + "]");
gpx.addTrack(trk);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found extensions node. Start parsing...");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseGPXExtension(currentNode);
gpx.addExtensionData(parser.getId(), data);
}
} else if(GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found route node. Start parsing...");
Route rte = parseRoute(currentNode);
if(rte!= null) {
logger.info("Add route to gpx data. [routeName="+ rte.getName() + "]");
gpx.addRoute(rte);
}
}
}
//TODO: parse route node
return gpx;
} else {
logger.error("FATAL!! - Root node is not gpx.");
}
return null;
}
/**
* Parses a wpt node into a Waypoint object
*
* @param node
* @return Waypoint object with info from the received node
*/
private Waypoint parseWaypoint(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Waypoint w = new Waypoint();
NamedNodeMap attrs = node.getAttributes();
//check for lat attribute
Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR);
if(latNode != null) {
Double latVal = null;
try {
latVal = Double.parseDouble(latNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lat value in waypoint data: " + latNode.getNodeValue());
}
w.setLatitude(latVal);
} else {
logger.warn("no lat value in waypoint data.");
}
//check for lon attribute
Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR);
if(lonNode != null) {
Double lonVal = null;
try {
lonVal = Double.parseDouble(lonNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue());
}
w.setLongitude(lonVal);
} else {
logger.warn("no lon value in waypoint data.");
}
NodeList childNodes = node.getChildNodes();
if(childNodes != null) {
for(int idx = 0; idx < childNodes.getLength(); idx++) {
Node currentNode = childNodes.item(idx);
if(GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ele node in waypoint data");
w.setElevation(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found time node in waypoint data");
w.setTime(getNodeValueAsDate(currentNode));
} else if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found name node in waypoint data");
w.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found cmt node in waypoint data");
w.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found desc node in waypoint data");
w.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found src node in waypoint data");
w.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found magvar node in waypoint data");
w.setMagneticDeclination(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found geoidheight node in waypoint data");
w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found link node in waypoint data");
//TODO: parse link
//w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sym node in waypoint data");
w.setSym(getNodeValueAsString(currentNode));
} else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found fix node in waypoint data");
w.setFix(getNodeValueAsFixType(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found type node in waypoint data");
w.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sat node in waypoint data");
w.setSat(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found hdop node in waypoint data");
w.setHdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found vdop node in waypoint data");
w.setVdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found pdop node in waypoint data");
w.setPdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ageofgpsdata node in waypoint data");
w.setAgeOfGPSData(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found dgpsid node in waypoint data");
w.setDgpsid(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found extensions node in waypoint data");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
w.addExtensionData(parser.getId(), data);
}
}
}
} else {
if(logger.isDebugEnabled())logger.debug("no child nodes found in waypoint");
}
return w;
}
private Track parseTrack(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Track trk = new Track();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
trk.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
trk.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
trk.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
trk.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//trk.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
trk.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
trk.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.TRKSEG_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node trkseg found");
trk.setTrackPoints(parseTrackSeg(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseTrackExtension(currentNode);
trk.addExtensionData(parser.getId(), data);
}
}
}
}
}
return trk;
}
private Route parseRoute(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Route rte = new Route();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
rte.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
rte.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
rte.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
rte.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//rte.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
rte.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
rte.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.RTEPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node rtept found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
rte.addRoutePoint(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseRouteExtension(currentNode);
rte.addExtensionData(parser.getId(), data);
}
}
}
}
}
return rte;
}
private ArrayList<Waypoint> parseTrackSeg(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
ArrayList<Waypoint> trkpts = new ArrayList<Waypoint>();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.TRKPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
trkpts.add(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
/*
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
//.addExtensionData(parser.getId(), data);
}
*/
}
}
}
return trkpts;
}
private Double getNodeValueAsDouble(Node node) {
Double val = null;
try {
val = Double.parseDouble(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Double value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
private Date getNodeValueAsDate(Node node) {
//2012-02-25T09:28:45Z
Date val = null;
try {
val = sdf.parse(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Date value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private String getNodeValueAsString(Node node) {
String val = null;
try {
val = node.getFirstChild().getNodeValue();
} catch (Exception ex) {
logger.error("error getting String value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private FixType getNodeValueAsFixType(Node node) {
FixType val = null;
try {
val = FixType.returnType(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error getting FixType value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private Integer getNodeValueAsInteger(Node node) {
Integer val = null;
try {
val = Integer.parseInt(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Integer value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
public void writeGPX(GPX gpx, File gpxFile) throws IOException, ParserConfigurationException, TransformerException {
OutputStream out = FileUtils.openOutputStream(gpxFile);
writeGPX(gpx,out);
out.flush();
out.close();
}
public void writeGPX(GPX gpx, OutputStream out) throws ParserConfigurationException, TransformerException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Node gpxNode = doc.createElement(GPXConstants.GPX_NODE);
addBasicGPXInfoToNode(gpx, gpxNode, doc);
if(gpx.getWaypoints() != null) {
Iterator<Waypoint> itW = gpx.getWaypoints().iterator();
while(itW.hasNext()) {
addWaypointToGPXNode(itW.next(), gpxNode, doc);
}
Iterator<Track> itT = gpx.getTracks().iterator();
while(itT.hasNext()) {
addTrackToGPXNode(itT.next(), gpxNode, doc);
}
Iterator<Route> itR = gpx.getRoutes().iterator();
while(itR.hasNext()) {
addRouteToGPXNode(itR.next(), gpxNode, doc);
}
}
doc.appendChild(gpxNode);
// Use a Transformer for output
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
private void addWaypointToGPXNode(Waypoint wpt, Node gpxNode, Document doc) {
addGenericWaypointToGPXNode(GPXConstants.WPT_NODE, wpt, gpxNode, doc);
}
private void addGenericWaypointToGPXNode(String tagName,Waypoint wpt, Node gpxNode, Document doc) {
Node wptNode = doc.createElement(tagName);
NamedNodeMap attrs = wptNode.getAttributes();
if(wpt.getLatitude() != null) {
Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR);
latNode.setNodeValue(wpt.getLatitude().toString());
attrs.setNamedItem(latNode);
}
if(wpt.getLongitude() != null) {
Node longNode = doc.createAttribute(GPXConstants.LON_ATTR);
longNode.setNodeValue(wpt.getLongitude().toString());
attrs.setNamedItem(longNode);
}
if(wpt.getElevation() != null) {
Node node = doc.createElement(GPXConstants.ELE_NODE);
node.appendChild(doc.createTextNode(wpt.getElevation().toString()));
wptNode.appendChild(node);
}
if(wpt.getTime() != null) {
Node node = doc.createElement(GPXConstants.TIME_NODE);
node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime())));
wptNode.appendChild(node);
}
if(wpt.getMagneticDeclination() != null) {
Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString()));
wptNode.appendChild(node);
}
if(wpt.getGeoidHeight() != null) {
Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE);
node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString()));
wptNode.appendChild(node);
}
if(wpt.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(wpt.getName()));
wptNode.appendChild(node);
}
if(wpt.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(wpt.getComment()));
wptNode.appendChild(node);
}
if(wpt.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(wpt.getDescription()));
wptNode.appendChild(node);
}
if(wpt.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(wpt.getSrc()));
wptNode.appendChild(node);
}
//TODO: write link node
if(wpt.getSym() != null) {
Node node = doc.createElement(GPXConstants.SYM_NODE);
node.appendChild(doc.createTextNode(wpt.getSym()));
wptNode.appendChild(node);
}
if(wpt.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(wpt.getType()));
wptNode.appendChild(node);
}
if(wpt.getFix() != null) {
Node node = doc.createElement(GPXConstants.FIX_NODE);
node.appendChild(doc.createTextNode(wpt.getFix().toString()));
wptNode.appendChild(node);
}
if(wpt.getSat() != null) {
Node node = doc.createElement(GPXConstants.SAT_NODE);
node.appendChild(doc.createTextNode(wpt.getSat().toString()));
wptNode.appendChild(node);
}
if(wpt.getHdop() != null) {
Node node = doc.createElement(GPXConstants.HDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getHdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getVdop() != null) {
Node node = doc.createElement(GPXConstants.VDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getVdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getPdop() != null) {
Node node = doc.createElement(GPXConstants.PDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getPdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getAgeOfGPSData() != null) {
Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE);
node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString()));
wptNode.appendChild(node);
}
if(wpt.getDgpsid() != null) {
Node node = doc.createElement(GPXConstants.DGPSID_NODE);
node.appendChild(doc.createTextNode(wpt.getDgpsid().toString()));
wptNode.appendChild(node);
}
if(wpt.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeWaypointExtensionData(node, wpt, doc);
}
wptNode.appendChild(node);
}
gpxNode.appendChild(wptNode);
}
private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(trk.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(trk.getName()));
trkNode.appendChild(node);
}
if(trk.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(trk.getComment()));
trkNode.appendChild(node);
}
if(trk.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(trk.getDescription()));
trkNode.appendChild(node);
}
if(trk.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(trk.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(trk.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(trk.getNumber().toString()));
trkNode.appendChild(node);
}
if(trk.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(trk.getType()));
trkNode.appendChild(node);
}
if(trk.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeTrackExtensionData(node, trk, doc);
}
trkNode.appendChild(node);
}
if(trk.getTrackPoints() != null) {
Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE);
Iterator<Waypoint> it = trk.getTrackPoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc);
}
trkNode.appendChild(trksegNode);
}
gpxNode.appendChild(trkNode);
}
private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(rte.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(rte.getName()));
trkNode.appendChild(node);
}
if(rte.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(rte.getComment()));
trkNode.appendChild(node);
}
if(rte.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(rte.getDescription()));
trkNode.appendChild(node);
}
if(rte.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(rte.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(rte.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(rte.getNumber().toString()));
trkNode.appendChild(node);
}
if(rte.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(rte.getType()));
trkNode.appendChild(node);
}
if(rte.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeRouteExtensionData(node, rte, doc);
}
trkNode.appendChild(node);
}
if(rte.getRoutePoints() != null) {
Iterator<Waypoint> it = rte.getRoutePoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc);
}
}
gpxNode.appendChild(trkNode);
}
private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) {
NamedNodeMap attrs = gpxNode.getAttributes();
if(gpx.getVersion() != null) {
Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR);
verNode.setNodeValue(gpx.getVersion());
attrs.setNamedItem(verNode);
}
if(gpx.getCreator() != null) {
Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR);
creatorNode.setNodeValue(gpx.getCreator());
attrs.setNamedItem(creatorNode);
}
if(gpx.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeGPXExtensionData(node, gpx, doc);
}
gpxNode.appendChild(node);
}
}
} | Java |
! RUN: %S/test_folding.sh %s %t %f18
! Test folding of array constructors with constant implied DO bounds;
! their indices are constant expressions and can be used as such.
module m1
integer, parameter :: kinds(*) = [1, 2, 4, 8]
integer(kind=8), parameter :: clipping(*) = [integer(kind=8) :: &
(int(z'100010101', kind=kinds(j)), j=1,4)]
integer(kind=8), parameter :: expected(*) = [ &
int(z'01',8), int(z'0101',8), int(z'00010101',8), int(z'100010101',8)]
logical, parameter :: test_clipping = all(clipping == expected)
end module
| Java |
// ************************************************************************** //
//
// BornAgain: simulate and fit scattering at grazing incidence
//
//! @file Core/StandardSamples/SizeDistributionModelsBuilder.h
//! @brief Defines various sample builder classes to test DA, LMA, SSCA approximations
//!
//! @homepage http://www.bornagainproject.org
//! @license GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
// ************************************************************************** //
#ifndef SIZEDISTRIBUTIONMODELSBUILDER_H
#define SIZEDISTRIBUTIONMODELSBUILDER_H
#include "IMultiLayerBuilder.h"
//! Creates the sample demonstrating size distribution model in decoupling approximation.
//! Equivalent of Examples/python/simulation/ex03_InterferenceFunctions/ApproximationDA.py
//! @ingroup standard_samples
class BA_CORE_API_ SizeDistributionDAModelBuilder : public IMultiLayerBuilder
{
public:
SizeDistributionDAModelBuilder(){}
MultiLayer* buildSample() const;
};
//! Creates the sample demonstrating size distribution model in local monodisperse approximation.
//! Equivalent of Examples/python/simulation/ex03_InterferenceFunctions/ApproximationLMA.py
//! @ingroup standard_samples
class BA_CORE_API_ SizeDistributionLMAModelBuilder : public IMultiLayerBuilder
{
public:
SizeDistributionLMAModelBuilder(){}
MultiLayer* buildSample() const;
};
//! Creates the sample demonstrating size distribution model in size space coupling approximation.
//! Equivalent of Examples/python/simulation/ex03_InterferenceFunctions/ApproximationSSCA.py
//! @ingroup standard_samples
class BA_CORE_API_ SizeDistributionSSCAModelBuilder : public IMultiLayerBuilder
{
public:
SizeDistributionSSCAModelBuilder(){}
MultiLayer* buildSample() const;
};
//! Builds sample: size spacing correlation approximation (IsGISAXS example #15).
//! @ingroup standard_samples
class BA_CORE_API_ CylindersInSSCABuilder : public IMultiLayerBuilder
{
public:
CylindersInSSCABuilder(){}
MultiLayer* buildSample() const;
};
#endif // SIZEDISTRIBUTIONMODELSBUILDER_H
| Java |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition 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.
*
* OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @package core
* @copyright (C) OXID eSales AG 2003-2012
* @version OXID eShop CE
* @version SVN: $Id: oxvoucherserie.php 47273 2012-07-12 12:47:43Z linas.kukulskis $
*/
/**
* Voucher serie manager.
* Manages list of available Vouchers (fetches, deletes, etc.).
*
* @package model
*/
class oxVoucherSerie extends oxBase
{
/**
* User groups array (default null).
* @var object
*/
protected $_oGroups = null;
/**
* @var string name of current class
*/
protected $_sClassName = 'oxvoucherserie';
/**
* Class constructor, initiates parent constructor (parent::oxBase()).
*/
public function __construct()
{
parent::__construct();
$this->init('oxvoucherseries');
}
/**
* Override delete function so we can delete user group and article or category relations first.
*
* @param string $sOxId object ID (default null)
*
* @return null
*/
public function delete( $sOxId = null )
{
if ( !$sOxId ) {
$sOxId = $this->getId();
}
$this->unsetDiscountRelations();
$this->unsetUserGroups();
$this->deleteVoucherList();
return parent::delete( $sOxId );
}
/**
* Collects and returns user group list.
*
* @return object
*/
public function setUserGroups()
{
if ( $this->_oGroups === null ) {
$this->_oGroups = oxNew( 'oxlist' );
$this->_oGroups->init( 'oxgroups' );
$sViewName = getViewName( "oxgroups" );
$sSelect = "select gr.* from {$sViewName} as gr, oxobject2group as o2g where
o2g.oxobjectid = ". oxDb::getDb()->quote( $this->getId() ) ." and gr.oxid = o2g.oxgroupsid ";
$this->_oGroups->selectString( $sSelect );
}
return $this->_oGroups;
}
/**
* Removes user groups relations.
*
* @return null
*/
public function unsetUserGroups()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxobject2group where oxobjectid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Removes product or dategory relations.
*
* @return null
*/
public function unsetDiscountRelations()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxobject2discount where oxobject2discount.oxdiscountid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Returns array of a vouchers assigned to this serie.
*
* @return array
*/
public function getVoucherList()
{
$oVoucherList = oxNew( 'oxvoucherlist' );
$sSelect = 'select * from oxvouchers where oxvoucherserieid = ' . oxDb::getDb()->quote( $this->getId() );
$oVoucherList->selectString( $sSelect );
return $oVoucherList;
}
/**
* Deletes assigned voucher list.
*
* @return null
*/
public function deleteVoucherList()
{
$oDb = oxDb::getDb();
$sDelete = 'delete from oxvouchers where oxvoucherserieid = ' . $oDb->quote( $this->getId() );
$oDb->execute( $sDelete );
}
/**
* Returns array of vouchers counts.
*
* @return array
*/
public function countVouchers()
{
$aStatus = array();
$oDb = oxDb::getDb();
$sQuery = 'select count(*) as total from oxvouchers where oxvoucherserieid = ' .$oDb->quote( $this->getId() );
$aStatus['total'] = $oDb->getOne( $sQuery );
$sQuery = 'select count(*) as used from oxvouchers where oxvoucherserieid = ' . $oDb->quote( $this->getId() ) . ' and ((oxorderid is not NULL and oxorderid != "") or (oxdateused is not NULL and oxdateused != 0))';
$aStatus['used'] = $oDb->getOne( $sQuery );
$aStatus['available'] = $aStatus['total'] - $aStatus['used'];
return $aStatus;
}
}
| Java |
var translations = {
'es': {
'One moment while we<br>log you in':
'Espera un momento mientras<br>iniciamos tu sesión',
'You are now connected to the network':
'Ahora estás conectado a la red',
'Account signups/purchases are disabled in preview mode':
'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.',
'Notice':
'Aviso',
'Day':
'Día',
'Days':
'Días',
'Hour':
'Hora',
'Hours':
'Horas',
'Minutes':
'Minutos',
'Continue':
'Continuar',
'Thank You for Trying TWC WiFi':
'Gracias por probar TWC WiFi',
'Please purchase a TWC Access Pass to continue using WiFi':
'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi',
'Your TWC Access Pass has expired. Please select a new Access Pass Now.':
'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.',
'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.':
'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.',
'Your Password':
'Tu contraseña',
'Proceed to Login':
'Proceder con el inicio de sesión',
'Payment portal is not available at this moment':
'',
'Redirecting to Payment portal...':
'',
'Could not log you into the network':
'No se pudo iniciar sesión en la red'
}
}
function translate(text, language) {
if (language == 'en')
return text;
if (!translations[language])
return text;
if (!translations[language][text])
return text;
return translations[language][text] || text;
}
| Java |
package it.ninjatech.kvo.async.job;
import it.ninjatech.kvo.model.ImageProvider;
import it.ninjatech.kvo.util.Logger;
import java.awt.Dimension;
import java.awt.Image;
import java.util.EnumSet;
public class CacheRemoteImageAsyncJob extends AbstractImageLoaderAsyncJob {
private static final long serialVersionUID = -8459315395025635686L;
private final String path;
private final String type;
private final Dimension size;
private Image image;
public CacheRemoteImageAsyncJob(String id, ImageProvider provider, String path, Dimension size, String type) {
super(id, EnumSet.of(LoadType.Cache, LoadType.Remote), provider);
this.path = path;
this.size = size;
this.type = type;
}
@Override
protected void execute() {
try {
Logger.log("-> executing cache-remote image %s\n", this.id);
this.image = getImage(null, null, this.id, this.path, this.size, this.type);
}
catch (Exception e) {
this.exception = e;
}
}
public Image getImage() {
return this.image;
}
}
| Java |
-----------------------------------
--
-- Zone: Bhaflau_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bhaflau_Remnants/TextIDs");
-----------------------------------
function onInitialize(zone)
end;
function onZoneIn(player,prevZone)
local cs = -1;
return cs;
end;
function onRegionEnter(player,region)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| Java |
#ifdef TI83P
# include <ti83pdefs.h>
# include <ti83p.h>
void YName() __naked
{
__asm
push af
push hl
push iy
ld iy,#flags___dw
BCALL(_YName___db)
pop iy
pop hl
pop af
ret
__endasm;
}
#endif
| Java |
/*
* UFTP - UDP based FTP with multicast
*
* Copyright (C) 2001-2013 Dennis A. Bush, Jr. [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/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the copyright holder
* grants you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef _CLIENT_FILEINFO_H
#define _CLIENT_FILEINFO_H
void handle_fileinfo(struct group_list_t *group, const unsigned char *message,
unsigned meslen, struct timeval rxtime);
void send_fileinfo_ack(struct group_list_t *group, int restart);
#endif // _CLIENT_FILEINFO_H
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.