answer
stringlengths 15
1.25M
|
|---|
{{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-- <API key> -->
{{tpl:SysBehavior behavior="<API key>"}}
<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-- <API key> -->
{{tpl:SysBehavior behavior="<API key>"}}
</div>
</tpl:Block>
|
#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/<API key>.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> /* <API key> */
#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 <API key> 10
/*
* After a CPU has dirtied this many pages, <API key>
* 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 <API key> = 10;
/*
* <API key> starts at 0 (disabled) so that it is a function of
* <API key> * the amount of dirtyable memory
*/
unsigned long <API key>;
/*
* free highmem will not be subtracted from the total free memory
* for calculating free ratios if <API key> is true
*/
int <API key>;
/*
* 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 <API key> = 5 * 100; /* centiseconds */
EXPORT_SYMBOL_GPL(<API key>);
/*
* The longest time for which data is allowed to remain dirty
*/
unsigned int <API key> = 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 <API key>;
static void writeout_period(unsigned long t);
/* Timer for aging of <API key> */
static struct timer_list <API key> =
<API key>(writeout_period, 0, 0);
static unsigned long <API key> = 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 <API key> (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.
*/
/**
* <API key> - 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 <API key>(struct zone *zone)
{
unsigned long nr_pages;
nr_pages = zone_page_state(zone, NR_FREE_PAGES);
nr_pages -= min(nr_pages, zone-><API key>);
nr_pages += zone_page_state(zone, NR_INACTIVE_FILE);
nr_pages += zone_page_state(zone, NR_ACTIVE_FILE);
return nr_pages;
}
static unsigned long <API key>(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 += <API key>(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
}
/**
* <API key> - 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 <API key>(void)
{
unsigned long x;
x = global_page_state(NR_FREE_PAGES);
x -= min(x, <API key>);
x += global_page_state(NR_INACTIVE_FILE);
x += global_page_state(NR_ACTIVE_FILE);
if (!<API key>)
x -= <API key>(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 - <API key> and dirty-throttling thresholds
*
* Calculate the dirty thresholds based on sysctl parameters
* - vm.<API key> or vm.<API key>
* - 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 || !<API key>)
available_memory = <API key>();
if (vm_dirty_bytes)
dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
else
dirty = (vm_dirty_ratio * available_memory) / 100;
if (<API key>)
background = DIV_ROUND_UP(<API key>, PAGE_SIZE);
else
background = (<API key> * 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;
<API key>(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 = <API key>(zone);
struct task_struct *tsk = current;
unsigned long dirty;
if (vm_dirty_bytes)
dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
zone_memory / <API key>();
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 <API key>(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
ret = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write)
<API key> = 0;
return ret;
}
int <API key>(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
ret = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write)
<API key> = 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 = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
<API key>();
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 = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
<API key>();
vm_dirty_ratio = 0;
}
return ret;
}
static unsigned long wp_next_time(unsigned long cur_time)
{
cur_time += <API key>;
/* 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 <API key>().
*/
static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
{
__inc_bdi_stat(bdi, BDI_WRITTEN);
<API key>(&<API key>, &bdi->completions,
bdi->max_prop_frac);
/* First event after period switching was turned off? */
if (!unlikely(<API key>)) {
/*
* 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 <API key> will be
* roughly the same.
*/
<API key> = wp_next_time(jiffies);
mod_timer(&<API key>, <API key>);
}
}
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 <API key>(struct backing_dev_info *bdi,
long *numerator, long *denominator)
{
<API key>(&<API key>, &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 - <API key>) /
<API key>;
if (fprop_new_period(&<API key>, miss_periods + 1)) {
<API key> = wp_next_time(<API key> +
miss_periods * <API key>);
mod_timer(&<API key>, <API key>);
} else {
/*
* Aging has zeroed all fractions. Stop wasting CPU on period
* updates.
*/
<API key> = 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 <API key>(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.
*/
<API key>(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;
}
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) << <API key>,
limit - setpoint + 1);
pos_ratio = x;
pos_ratio = pos_ratio * x >> <API key>;
pos_ratio = pos_ratio * x >> <API key>;
pos_ratio += 1 << <API key>;
return clamp(pos_ratio, 0LL, 2LL << <API key>);
}
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 = <API key>(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 << <API key>);
if (bdi_dirty >= bdi_thresh)
return 0;
bdi_bg_thresh = div_u64((u64)bdi_thresh * bg_thresh, thresh);
bdi_setpoint = <API key>(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.
*/
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;
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 <API key>(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 - 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 <API key>(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 <API key>(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 = <API key>(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 <API key>;
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 >> <API key>;
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.
*/
<API key> = div_u64((u64)task_ratelimit * write_bw,
dirty_rate | 1);
/*
* <API key> ~= (write_bw / N) <= write_bw
*/
if (unlikely(<API key> > write_bw))
<API key> = write_bw;
/*
* We could safely do this and return immediately:
*
* bdi->dirty_ratelimit = <API key>;
*
* 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 <API key> iff
* task_ratelimit is on the same side of dirty_ratelimit, too.
* For example, when
* - dirty_ratelimit > <API key>
* - 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 <API key>. 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
* <API key> = 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-><API key>,
min(<API key>, task_ratelimit));
if (dirty_ratelimit < x)
step = x - dirty_ratelimit;
} else {
x = max(bdi-><API key>,
max(<API key>, 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 < <API key>)
dirty_ratelimit += step;
else
dirty_ratelimit -= step;
bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
bdi-><API key> = <API key>;
<API key>(bdi, dirty_rate, task_ratelimit);
}
void <API key>(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) {
<API key>(thresh, dirty, now);
<API key>(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty,
dirtied, elapsed);
}
<API key>(bdi, elapsed, written);
snapshot:
bdi->dirtied_stamp = dirtied;
bdi->written_stamp = written;
bdi->bw_time_stamp = now;
}
static void <API key>(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 (<API key>(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
return;
spin_lock(&bdi->wb.list_lock);
<API key>(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty, start_time);
spin_unlock(&bdi->wb.list_lock);
}
/*
* After a task dirtied this many pages, <API key>()
* 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 <API key>, 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 <= <API key>(thresh, bg_thresh)) {
current->dirty_paused_when = now;
current->nr_dirtied = 0;
current->nr_dirtied_pause =
dirty_poll_interval(dirty, thresh);
break;
}
if (unlikely(!<API key>(bdi)))
<API key>(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;
<API key>(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) >>
<API key>;
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) {
<API key>(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:
<API key>(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 (<API key>(current))
break;
}
if (!dirty_exceeded && bdi->dirty_exceeded)
bdi->dirty_exceeded = 0;
if (<API key>(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)
<API key>(bdi);
}
void <API key>(struct page *page, int page_mkwrite)
{
if (set_page_dirty(page) || page_mkwrite) {
struct address_space *mapping = page_mapping(page);
if (mapping)
<API key>(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 <API key> 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, <API key>) = 0;
/**
* <API key> - 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 <API key>(struct address_space *mapping)
{
struct backing_dev_info *bdi = mapping->backing_dev_info;
int ratelimit;
int *p;
if (!<API key>(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(<API key>);
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(<API key>);
void <API key>(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(<API key>(NR_UNSTABLE_NFS) +
<API key>(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/<API key>
*/
int <API key>(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 <API key>(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,
<API key>);
}
/*
* 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 <API key>(struct backing_dev_info *info)
{
mod_timer(&info-><API key>, 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 <API key>.
* Nothing needs to be written back anymore, so we unschedule the writeback.
*/
void <API key>(void)
{
struct backing_dev_info *bdi;
rcu_read_lock();
<API key>(bdi, &bdi_list, bdi_list)
del_timer(&bdi-><API key>);
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 <API key>(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:
<API key>();
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 <API key>() 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)
{
<API key>();
<API key>(&ratelimit_nb);
fprop_global_init(&<API key>);
}
/**
* <API key> - 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 <API key>(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 = <API key>(&mapping->page_tree,
&start, end, WRITEBACK_TAG_BATCH,
PAGECACHE_TAG_DIRTY, <API key>);
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(<API key>);
/**
* 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 = <API key>;
else
tag = PAGECACHE_TAG_DIRTY;
retry:
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
<API key>(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)
<API key>(page);
else
goto continue_unlock;
}
BUG_ON(PageWriteback(page));
if (!<API key>(page))
goto continue_unlock;
trace_wbc_writepage(wbc, mapping->backing_dev_info);
ret = (*writepage)(page, wbc, data);
if (unlikely(ret)) {
if (ret == <API key>) {
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()
* <API key>.
*/
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)
<API key>(page);
if (<API key>(page)) {
page_cache_get(page);
ret = mapping->a_ops->writepage(page, &wbc);
if (ret == 0 && wait) {
<API key>(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 <API key>(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 <API key>(struct page *page, struct address_space *mapping)
{
<API key>(page, mapping);
if (<API key>(mapping)) {
<API key>(page, NR_FILE_DIRTY);
<API key>(page, NR_DIRTIED);
__inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
__inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
<API key>(PAGE_CACHE_SIZE);
current->nr_dirtied++;
this_cpu_inc(bdp_ratelimits);
}
}
EXPORT_SYMBOL(<API key>);
/*
* Helper function for set_page_writeback family.
* NOTE: Unlike <API key> this does not rely on being atomic
* wrt interrupts.
*/
void <API key>(struct page *page)
{
inc_zone_page_state(page, NR_WRITEBACK);
}
EXPORT_SYMBOL(<API key>);
/*
* 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 <API key>() 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 <API key>(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));
<API key>(page, mapping);
radix_tree_tag_set(&mapping->page_tree,
page_index(page), PAGECACHE_TAG_DIRTY);
}
<API key>(&mapping->tree_lock, flags);
if (mapping->host) {
/* !PageAnon && !swapper_space */
__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
}
return 1;
}
return 0;
}
EXPORT_SYMBOL(<API key>);
/*
* 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 <API key> and the dirty pages position
* control.
*/
void <API key>(struct page *page)
{
struct address_space *mapping = page->mapping;
if (mapping && <API key>(mapping)) {
current->nr_dirtied
dec_zone_page_state(page, NR_DIRTIED);
dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
}
}
EXPORT_SYMBOL(<API key>);
/*
* When a writepage implementation decides that it doesn't want to write this
* page for some reason, it should redirty the locked page via
* <API key>() and it should then unlock the page and return 0
*/
int <API key>(struct writeback_control *wbc, struct page *page)
{
wbc->pages_skipped++;
<API key>(page);
return <API key>(page);
}
EXPORT_SYMBOL(<API key>);
/*
* 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 = <API key>;
#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 <API key>(struct page *page)
{
struct address_space *mapping = page_mapping(page);
BUG_ON(!PageLocked(page));
if (mapping && <API key>(mapping)) {
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(<API key>);
int <API key>(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 = <API key>(page);
if (ret) {
<API key>(&mapping->page_tree,
page_index(page),
<API key>);
if (<API key>(bdi)) {
__dec_bdi_stat(bdi, BDI_WRITEBACK);
__bdi_writeout_inc(bdi);
}
}
<API key>(&mapping->tree_lock, flags);
} else {
ret = <API key>(page);
}
if (ret) {
dec_zone_page_state(page, NR_WRITEBACK);
inc_zone_page_state(page, NR_WRITTEN);
}
return ret;
}
int <API key>(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 = <API key>(page);
if (!ret) {
radix_tree_tag_set(&mapping->page_tree,
page_index(page),
<API key>);
if (<API key>(bdi))
__inc_bdi_stat(bdi, BDI_WRITEBACK);
}
if (!PageDirty(page))
<API key>(&mapping->page_tree,
page_index(page),
PAGECACHE_TAG_DIRTY);
<API key>(&mapping->page_tree,
page_index(page),
<API key>);
<API key>(&mapping->tree_lock, flags);
} else {
ret = <API key>(page);
}
if (!ret)
<API key>(page);
return ret;
}
EXPORT_SYMBOL(<API key>);
/*
* 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);
/**
* <API key>() - 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 <API key>(struct page *page)
{
struct address_space *mapping = page_mapping(page);
struct backing_dev_info *bdi = mapping->backing_dev_info;
if (!<API key>(bdi))
return;
<API key>(page);
}
EXPORT_SYMBOL_GPL(<API key>);
|
<?php
get_header();
<?php if ( have_posts() ) while ( have_posts() ) : the_post();
<h1><?php the_title();
<?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();
|
#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 = {
[<API key>] = 10,
[<API key>] = 180,
[<API key>] = 10,
[<API key>] = 180,
[<API key>] = 10,
[<API key>] = 80,
[<API key>] = 10,
[<API key>] = 80,
[<API key>] = 8,
[<API key>] = 8,
[<API key>] = 20,
[<API key>] = 20,
[<API key>] = 20,
[<API key>] = 35,
[<API key>] = 16,
[<API key>] = 35,
[<API key>] = 32,
[<API key>] = 50,
[<API key>] = 28,
[<API key>] = 50,
[<API key>] = 10,
[<API key>] = 20,
[<API key>] = 75,
[<API key>] = 15,
[<API key>] = 27,
[<API key>] = 17,
/* active scan params */
[<API key>] = 170,
[<API key>] = 50,
[<API key>] = 100,
/* passive scan params */
[<API key>] = 800,
[<API key>] = 200,
[<API key>] = 200,
/* passive scan in dual antenna params */
[<API key>] = 0,
[<API key>] = 0,
[<API key>] = 0,
/* general params */
[<API key>] = 1,
[<API key>] = 0,
[<API key>] = 60,
[CONF_SG_DHCP_TIME] = 5000,
[CONF_SG_RXT] = 1200,
[CONF_SG_TXT] = 1000,
[<API key>] = 1,
[<API key>] = 3,
[<API key>] = 6,
[<API key>] = 10,
[<API key>] = 10,
[<API key>] = 2,
[<API key>] = 5,
[<API key>] = 30,
/* AP params */
[<API key>] = 3,
[<API key>] = 10,
[<API key>] = 2,
[<API key>] = 0,
[<API key>] = 25,
[<API key>] = 25,
/* CTS Diluting params */
[<API key>] = 0,
[<API key>] = 0,
},
.state = CONF_SG_PROTECTIVE,
},
.rx = {
.rx_msdu_life_time = 512000,
.<API key> = 0,
.ps_poll_timeout = 15,
.upsd_timeout = 15,
.rts_threshold = <API key>,
.rx_cca_threshold = 0,
.irq_blk_threshold = 0xFFFF,
.irq_pkt_threshold = 0,
.irq_timeout = 600,
.queue_type = <API key>,
},
.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 = <API key>,
.tsid = CONF_TX_AC_BE,
.ps_scheme = <API key>,
.ack_policy = <API key>,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_BK] = {
.queue_id = CONF_TX_AC_BK,
.channel_type = <API key>,
.tsid = CONF_TX_AC_BK,
.ps_scheme = <API key>,
.ack_policy = <API key>,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_VI] = {
.queue_id = CONF_TX_AC_VI,
.channel_type = <API key>,
.tsid = CONF_TX_AC_VI,
.ps_scheme = <API key>,
.ack_policy = <API key>,
.apsd_conf = {0, 0},
},
[CONF_TX_AC_VO] = {
.queue_id = CONF_TX_AC_VO,
.channel_type = <API key>,
.tsid = CONF_TX_AC_VO,
.ps_scheme = <API key>,
.ack_policy = <API key>,
.apsd_conf = {0, 0},
},
},
.frag_threshold = <API key>,
.tx_compl_timeout = 700,
.tx_compl_threshold = 4,
.basic_rate = <API key>,
.basic_rate_5 = <API key>,
.<API key> = 10,
.<API key> = 10,
.tx_watchdog_timeout = 5000,
},
.conn = {
.wake_up_event = <API key>,
.listen_interval = 1,
.<API key> = <API key>,
.<API key> = 3,
.bcn_filt_mode = <API key>,
.bcn_filt_ie_count = 2,
.bcn_filt_ie = {
[0] = {
.ie = <API key>,
.rule = <API key>,
},
[1] = {
.ie = <API key>,
.rule = <API key>,
},
},
.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 = <API key>,
.bet_max_consecutive = 50,
.psm_entry_retries = 8,
.psm_exit_retries = 16,
.<API key> = 3,
.dynamic_ps_timeout = 200,
.forced_ps = false,
.keep_alive_interval = 55000,
.max_listen_interval = 20,
},
.itrim = {
.enable = false,
.timeout = 50000,
},
.pm_config = {
.<API key> = 5000,
.<API key> = false
},
.roam_trigger = {
.trigger_pacing = 1,
.<API key> = 20,
.<API key> = 10,
.<API key> = 20,
.avg_weight_snr_data = 10,
},
.scan = {
.<API key> = 7500,
.<API key> = 30000,
.<API key> = 100000,
.<API key> = 100000,
.num_probe_reqs = 2,
.split_scan_timeout = 50000,
},
.sched_scan = {
/* sched_scan requires dwell times in TU instead of TU/1000 */
.<API key> = 30,
.<API key> = 60,
.dwell_time_passive = 100,
.dwell_time_dfs = 150,
.num_probe_reqs = 2,
.rssi_threshold = -90,
.snr_threshold = 0,
},
.rf = {
.<API key> = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
},
.<API key> = {
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 = <API key>,
},
.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,
.<API key> = 0xff, /* default */
.<API key> = 12,
.<API key> = 148,
.<API key> = 0xffff, /* default */
.<API key> = 0xffffffff, /* default */
.<API key> = 0xffff, /* default */
.<API key> = 0xff, /* default */
.swallow_clk_diff = 0xff, /* default */
},
.rx_streaming = {
.duration = 150,
.queues = 0x1,
.interval = 20,
.always = 0,
},
.fwlog = {
.mode = <API key>,
.mem_blocks = 2,
.severity = 0,
.timestamp = <API key>,
.output = <API key>,
.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,
.<API key> = 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,
.<API key> = 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 <API key>(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 <API key>(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret;
if (WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS))
return -EINVAL;
if (!test_bit(<API key>, &wlvif->flags))
return 0;
if (test_and_set_bit(<API key>, &wlvif->flags))
return 0;
ret = <API key>(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 <API key> *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 & <API key>)
continue;
if (ch->flags & <API key>)
ch->flags |= <API key> |
<API key>;
}
return 0;
}
static int <API key>(struct wl1271 *wl, struct wl12xx_vif *wlvif,
bool enable)
{
int ret = 0;
/* we should hold wl->mutex */
ret = <API key>(wl, wlvif, enable);
if (ret < 0)
goto out;
if (enable)
set_bit(<API key>, &wlvif->flags);
else
clear_bit(<API key>, &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 <API key>(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(<API key>, &wlvif->flags))
goto out;
/* reconfigure/disable according to new streaming_period */
if (period &&
test_bit(<API key>, &wlvif->flags) &&
(wl->conf.rx_streaming.always ||
test_bit(<API key>, &wl->flags)))
ret = <API key>(wl, wlvif, true);
else {
ret = <API key>(wl, wlvif, false);
/* don't cancel_work_sync since we might deadlock */
del_timer_sync(&wlvif->rx_streaming_timer);
}
out:
return ret;
}
static void <API key>(struct work_struct *work)
{
int ret;
struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif,
<API key>);
struct wl1271 *wl = wlvif->wl;
mutex_lock(&wl->mutex);
if (test_bit(<API key>, &wlvif->flags) ||
!test_bit(<API key>, &wlvif->flags) ||
(!wl->conf.rx_streaming.always &&
!test_bit(<API key>, &wl->flags)))
goto out;
if (!wl->conf.rx_streaming.interval)
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
ret = <API key>(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 <API key>(struct work_struct *work)
{
int ret;
struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif,
<API key>);
struct wl1271 *wl = wlvif->wl;
mutex_lock(&wl->mutex);
if (!test_bit(<API key>, &wlvif->flags))
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
ret = <API key>(wl, wlvif, false);
if (ret)
goto out_sleep;
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static void <API key>(unsigned long data)
{
struct wl12xx_vif *wlvif = (struct wl12xx_vif *)data;
struct wl1271 *wl = wlvif->wl;
<API key>(wl->hw, &wlvif-><API key>);
}
/* wl->mutex must be taken */
void <API key>(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);
<API key>(wl->hw, &wl->tx_watchdog_work,
msecs_to_jiffies(wl->conf.tx.tx_watchdog_timeout));
}
static void <API key>(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);
<API key>(wl);
goto out;
}
/*
* if a scan is in progress, we might not have any Tx for a long
* time
*/
if (wl->scan.state != <API key>) {
wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to scan",
wl->conf.tx.tx_watchdog_timeout);
<API key>(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);
<API key>(wl);
goto out;
}
wl1271_error("Tx stuck (in FW) for %d ms. Starting recovery",
wl->conf.tx.tx_watchdog_timeout);
<API key>(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 = <API key>;
} else if (!strcmp(fwlog_param, "ondemand")) {
wl->conf.fwlog.mode = <API key>;
} else if (!strcmp(fwlog_param, "dbgpins")) {
wl->conf.fwlog.mode = <API key>;
wl->conf.fwlog.output = <API key>;
} else if (!strcmp(fwlog_param, "disable")) {
wl->conf.fwlog.mem_blocks = 0;
wl->conf.fwlog.output = <API key>;
} 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 = <API key>(wl);
else
ret = <API key>(wl);
if (ret < 0)
return ret;
if (wl->chip.id == CHIP_ID_1283_PG20)
ret = <API key>(wl);
else
ret = <API key>(wl);
if (ret < 0)
return ret;
if (wl->chip.id != CHIP_ID_1283_PG20) {
ret = <API key>(wl);
if (ret < 0)
return ret;
}
/* Chip-specific initializations */
ret = <API key>(wl);
if (ret < 0)
return ret;
ret = <API key>(wl);
if (ret < 0)
return ret;
ret = wl12xx_acx_mem_cfg(wl);
if (ret < 0)
goto out_free_memmap;
/* Enable data path */
ret = <API key>(wl, 1);
if (ret < 0)
goto out_free_memmap;
/* Configure for CAM power saving (ie. always active) */
ret = <API key>(wl, WL1271_PSM_CAM);
if (ret < 0)
goto out_free_memmap;
/* configure PM */
ret = <API key>(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 <API key>(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 < <API key>)
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 >= <API key>)
<API key>(wl, wlvif, hlid, true);
}
static void <API key>(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;
<API key>(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)
<API key>(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(<API key>, &wl->flags);
/* for AP update num of allocated TX blocks per link and ps status */
<API key>(wl, wlvif) {
<API key>(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 <API key>(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)))
<API key>(wl->hw, skb);
}
static void <API key>(struct work_struct *work)
{
struct wl1271 *wl =
container_of(work, struct wl1271, netstack_work);
do {
<API key>(wl);
} while (skb_queue_len(&wl->deferred_rx_queue));
}
#define <API key> 256
static irqreturn_t wl1271_irq(int irq, void *cookie)
{
int ret;
u32 intr;
int loopcount = <API key>;
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(<API key>, &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 & <API key>)
loopcount = 1;
mutex_lock(&wl->mutex);
wl1271_debug(DEBUG_IRQ, "IRQ work");
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = <API key>(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,
* <API key> cannot be called concurrently.
*/
clear_bit(<API key>, &wl->flags);
<API key>();
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 & <API key>)) {
wl1271_error("watchdog interrupt received! "
"starting recovery.");
<API key>(wl);
/* restarting the chip. ignore any other interrupt. */
goto out;
}
if (likely(intr & <API key>)) {
wl1271_debug(DEBUG_IRQ, "<API key>");
wl12xx_rx(wl, wl->fw_status);
/* Check if any tx blocks were freed */
spin_lock_irqsave(&wl->wl_lock, flags);
if (!test_bit(<API key>, &wl->flags) &&
<API key>(wl) > 0) {
<API key>(&wl->wl_lock, flags);
/*
* In order to avoid starvation of the TX path,
* call the work function directly.
*/
<API key>(wl);
} else {
<API key>(&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 > <API key>)
<API key>(wl);
}
if (intr & <API key>) {
wl1271_debug(DEBUG_IRQ, "<API key>");
wl1271_event_handle(wl, 0);
}
if (intr & <API key>) {
wl1271_debug(DEBUG_IRQ, "<API key>");
wl1271_event_handle(wl, 1);
}
if (intr & <API key>)
wl1271_debug(DEBUG_IRQ,
"<API key>");
if (intr & <API key>)
wl1271_debug(DEBUG_IRQ, "<API key>");
}
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(<API key>, &wl->flags);
if (!test_bit(<API key>, &wl->flags) &&
<API key>(wl) > 0)
<API key>(wl->hw, &wl->tx_work);
<API key>(&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 <API key>(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 <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *cur_vif,
struct vif_counter_data *data)
{
memset(data, 0, sizeof(*data));
data->cur_vif = cur_vif;
<API key>(hw,
<API key>, data);
}
static int <API key>(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 <API key>() here because
* wl->mutex is taken, so use the cached last_vif_count value
*/
if (wl->last_vif_count > 1) {
fw_type = <API key>;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = <API key>;
else
fw_name = <API key>;
} else {
fw_type = <API key>;
if (wl->chip.id == CHIP_ID_1283_PG20)
fw_name = <API key>;
else
fw_name = <API key>;
}
}
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 <API key>(struct wl1271 *wl)
{
if (!test_bit(<API key>, &wl->flags))
<API key>(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 <API key>(struct wl1271 *wl)
{
u32 addr;
u32 first_addr;
u8 *block;
if ((wl->quirks & <API key>) ||
(wl->conf.fwlog.mode != <API key>) ||
(wl->conf.fwlog.mem_blocks == 0))
return;
wl1271_info("Reading FW panic log");
block = kmalloc(<API key>, 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 (!<API key>(wl))
<API key>(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, <API key>);
wl1271_read_hwaddr(wl, addr, block, <API key>,
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),
<API key> - sizeof(addr)))
break;
} while (addr && (addr != first_addr));
<API key>(&wl->fwlog_waitq);
out:
kfree(block);
}
static void <API key>(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(<API key>, &wl->flags);
<API key>(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(<API key>, &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.
*/
<API key>(wl, wlvif) {
if (test_bit(<API key>, &wlvif->flags) ||
test_bit(<API key>, &wlvif->flags))
wlvif->tx_security_seq +=
<API key>;
}
/* Prevent spurious TX during FW restart */
<API key>(wl->hw);
if (wl->sched_scanning) {
<API key>(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);
<API key>(wl, vif, false);
}
mutex_unlock(&wl->mutex);
wl1271_op_stop(wl->hw);
clear_bit(<API key>, &wl->flags);
<API key>(wl->hw);
/*
* Its safe to enable TX now - the queues are stopped after a request
* to restart the HW.
*/
<API key>(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, <API key>, 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(<API key>);
ret = wl1271_power_on(wl);
if (ret < 0)
goto out;
msleep(<API key>);
wl1271_io_reset(wl);
wl1271_io_init(wl);
<API key>(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 (!<API key>(wl))
wl->quirks |= <API key>;
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 |= <API key>;
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 |= <API key>;
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 = <API key>(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. */
<API key>(wl);
<API key>(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.
*/
<API key>(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().
*/
<API key>(wl);
wl1271_error("cannot power down because not in PLT "
"state: %d", wl->state);
ret = -EBUSY;
goto out;
}
mutex_unlock(&wl->mutex);
<API key>(wl);
cancel_work_sync(&wl->netstack_work);
cancel_work_sync(&wl->recovery_work);
<API key>(&wl->elp_work);
<API key>(&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 = <API key>(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 == <API key> ||
(wlvif && !test_bit(hlid, wlvif->links_map))) {
wl1271_debug(DEBUG_TX, "DROP skb hlid %d q %d", hlid, q);
<API key>(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] >= <API key>) {
wl1271_debug(DEBUG_TX, "op_tx: stopping queues for q %d", q);
<API key>(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(<API key>, &wl->flags) &&
!test_bit(<API key>, &wl->flags))
<API key>(wl->hw, &wl->tx_work);
out:
<API key>(&wl->wl_lock, flags);
}
int <API key>(struct wl1271 *wl)
{
unsigned long flags;
int q;
/* no need to queue a new dummy packet if one is already pending */
if (test_bit(<API key>, &wl->flags))
return 0;
q = wl1271_tx_get_queue(<API key>(wl->dummy_packet));
spin_lock_irqsave(&wl->wl_lock, flags);
set_bit(<API key>, &wl->flags);
wl->tx_queue_count[q]++;
<API key>(&wl->wl_lock, flags);
/* The FW is low on RX memory blocks, so send the dummy packet asap */
if (!test_bit(<API key>, &wl->flags))
<API key>(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 <API key> (ALIGN(1400, 512))
static struct sk_buff *<API key>(struct wl1271 *wl)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr *hdr;
unsigned int dummy_packet_size;
dummy_packet_size = <API key> -
sizeof(struct wl1271_tx_hw_descr) - sizeof(*hdr);
skb = dev_alloc_skb(<API key>);
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(<API key> |
<API key> |
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 */
<API key>(skb, 0);
memset(IEEE80211_SKB_CB(skb), 0, sizeof(struct ieee80211_tx_info));
return skb;
}
#ifdef CONFIG_PM
static int <API key>(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
mutex_lock(&wl->mutex);
if (!test_bit(<API key>, &wlvif->flags))
goto out_unlock;
ret = <API key>(wl);
if (ret < 0)
goto out_unlock;
ret = <API key>(wl, wlvif,
wl->conf.conn.<API key>,
wl->conf.conn.<API key>);
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 <API key>(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
int ret = 0;
mutex_lock(&wl->mutex);
if (!test_bit(<API key>, &wlvif->flags))
goto out_unlock;
ret = <API key>(wl);
if (ret < 0)
goto out_unlock;
ret = <API key>(wl, wlvif, true);
wl1271_ps_elp_sleep(wl);
out_unlock:
mutex_unlock(&wl->mutex);
return ret;
}
static int <API key>(struct wl1271 *wl,
struct wl12xx_vif *wlvif)
{
if (wlvif->bss_type == BSS_TYPE_STA_BSS)
return <API key>(wl, wlvif);
if (wlvif->bss_type == BSS_TYPE_AP_BSS)
return <API key>(wl, wlvif);
return 0;
}
static void <API key>(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 = <API key>(wl);
if (ret < 0)
goto out;
if (is_sta) {
ret = <API key>(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 = <API key>(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;
<API key>(wl, wlvif) {
ret = <API key>(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
*/
<API key>(wl);
/*
* set suspended flag to avoid triggering a new threaded_irq
* work. no need for spinlock as interrupts are disabled.
*/
set_bit(<API key>, &wl->flags);
<API key>(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(<API key>, &wl->flags);
if (test_and_clear_bit(<API key>, &wl->flags))
run_irq_work = true;
<API key>(&wl->wl_lock, flags);
if (run_irq_work) {
wl1271_debug(DEBUG_MAC80211,
"run postponed irq_work directly");
wl1271_irq(0, wl);
<API key>(wl);
}
<API key>(wl, wlvif) {
<API key>(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.
*/
<API key>(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().
*/
<API key>(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);
<API key>(wl);
<API key>(&wl->scan_complete_work);
cancel_work_sync(&wl->netstack_work);
cancel_work_sync(&wl->tx_work);
<API key>(&wl->elp_work);
<API key>(&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 = <API key>;
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 = <API key>;
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 <API key> 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;
}
<API key>(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 <API key>(struct wl1271 *wl, u8 *idx)
{
u8 policy = find_first_zero_bit(wl->rate_policies_map,
<API key>);
if (policy >= <API key>)
return -EBUSY;
__set_bit(policy, wl->rate_policies_map);
*idx = policy;
return 0;
}
static void <API key>(struct wl1271 *wl, u8 *idx)
{
if (WARN_ON(*idx >= <API key>))
return;
__clear_bit(*idx, wl->rate_policies_map);
*idx = <API key>;
}
static u8 <API key>(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 <API key>;
}
static int <API key>(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 (<API key>(vif)) {
case <API key>:
wlvif->p2p = 1;
/* fall-through */
case <API key>:
wlvif->bss_type = BSS_TYPE_STA_BSS;
break;
case <API key>:
wlvif->bss_type = BSS_TYPE_IBSS;
break;
case <API key>:
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 = <API key>;
wlvif->dev_role_id = <API key>;
wlvif->dev_hlid = <API key>;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
/* init sta/ibss data */
wlvif->sta.hlid = <API key>;
<API key>(wl, &wlvif->sta.basic_rate_idx);
<API key>(wl, &wlvif->sta.ap_rate_idx);
<API key>(wl, &wlvif->sta.p2p_rate_idx);
} else {
/* init ap data */
wlvif->ap.bcast_hlid = <API key>;
wlvif->ap.global_hlid = <API key>;
<API key>(wl, &wlvif->ap.mgmt_rate_idx);
<API key>(wl, &wlvif->ap.bcast_rate_idx);
for (i = 0; i < <API key>; i++)
<API key>(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 = <API key>;
wlvif->basic_rate = <API key>;
wlvif->rate_set = <API key>;
wlvif->beacon_int = <API key>;
/*
* 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-><API key>,
<API key>);
INIT_WORK(&wlvif-><API key>,
<API key>);
INIT_LIST_HEAD(&wlvif->list);
setup_timer(&wlvif->rx_streaming_timer, <API key>,
(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. */
<API key>(wl);
<API key>(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 <API key>(struct wl12xx_vif *wlvif)
{
return wlvif->dev_hlid != <API key>;
}
/*
* 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 <API key>(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(<API key>, &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 == <API key>)
return true;
if (vif_count <= 1 && current_fw == <API key>)
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 <API key>.
*/
static void <API key>(struct wl1271 *wl)
{
struct wl12xx_vif *wlvif;
<API key>(wl, wlvif) {
wl1271_ps_set_mode(wl, wlvif, <API key>);
}
}
static int <API key>(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 |= <API key> |
<API key>;
wl1271_debug(DEBUG_MAC80211, "mac80211 add interface type %d mac %pM",
<API key>(vif), vif->addr);
<API key>(hw, vif, &vif_count);
mutex_lock(&wl->mutex);
ret = <API key>(wl);
if (ret < 0)
goto out_unlock;
/*
* in some very corner case HW recovery scenarios its possible to
* get here before <API key> is complete, so
* opt out if that is the case.
*/
if (test_bit(<API key>, &wl->flags) ||
test_bit(<API key>, &wlvif->flags)) {
ret = -EBUSY;
goto out;
}
ret = <API key>(wl, vif);
if (ret < 0)
goto out;
wlvif->wl = wl;
role_type = <API key>(wl, wlvif);
if (role_type == <API key>) {
ret = -EINVAL;
goto out;
}
if (<API key>(wl, vif_count, true)) {
<API key>(wl);
set_bit(<API key>, &wl->flags);
mutex_unlock(&wl->mutex);
<API key>(&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 = <API key>(wl, vif->addr,
WL1271_ROLE_DEVICE,
&wlvif->dev_role_id);
if (ret < 0)
goto out;
}
ret = <API key>(wl, vif->addr,
role_type, &wlvif->role_id);
if (ret < 0)
goto out;
ret = <API key>(wl, vif);
if (ret < 0)
goto out;
list_add(&wlvif->list, &wl->wlvif_list);
set_bit(<API key>, &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 <API key>(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(<API key>, &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 != <API key> &&
wl->scan_vif == vif) {
/*
* Rearm the tx watchdog just before idling scan. This
* prevents just-finished scans from triggering the watchdog
*/
<API key>(wl);
wl->scan.state = <API key>;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan_vif = NULL;
wl->scan.req = NULL;
<API key>(wl->hw, true);
}
if (!test_bit(<API key>, &wl->flags)) {
/* disable active roles */
ret = <API key>(wl);
if (ret < 0)
goto deinit;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
if (<API key>(wlvif))
wl12xx_stop_dev(wl, wlvif);
ret = <API key>(wl, &wlvif->dev_role_id);
if (ret < 0)
goto deinit;
}
ret = <API key>(wl, &wlvif->role_id);
if (ret < 0)
goto deinit;
wl1271_ps_elp_sleep(wl);
}
deinit:
/* clear all hlids (except system_hlid) */
wlvif->dev_hlid = <API key>;
if (wlvif->bss_type == BSS_TYPE_STA_BSS ||
wlvif->bss_type == BSS_TYPE_IBSS) {
wlvif->sta.hlid = <API key>;
<API key>(wl, &wlvif->sta.basic_rate_idx);
<API key>(wl, &wlvif->sta.ap_rate_idx);
<API key>(wl, &wlvif->sta.p2p_rate_idx);
} else {
wlvif->ap.bcast_hlid = <API key>;
wlvif->ap.global_hlid = <API key>;
<API key>(wl, &wlvif->ap.mgmt_rate_idx);
<API key>(wl, &wlvif->ap.bcast_rate_idx);
for (i = 0; i < <API key>; i++)
<API key>(wl,
&wlvif->ap.ucast_rate_idx[i]);
}
<API key>(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 = <API key>;
wlvif->dev_role_id = <API key>;
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-><API key>);
cancel_work_sync(&wlvif-><API key>);
mutex_lock(&wl->mutex);
}
static void <API key>(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;
<API key>(hw, vif, &vif_count);
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF ||
!test_bit(<API key>, &wlvif->flags))
goto out;
/*
* wl->vif can be null here if someone shuts down the interface
* just when hardware recovery has been started.
*/
<API key>(wl, iter) {
if (iter != wlvif)
continue;
<API key>(wl, vif, true);
break;
}
WARN_ON(iter != wlvif);
if (<API key>(wl, vif_count, false)) {
<API key>(wl);
set_bit(<API key>, &wl->flags);
<API key>(wl);
cancel_recovery = false;
}
out:
mutex_unlock(&wl->mutex);
if (cancel_recovery)
cancel_work_sync(&wl->recovery_work);
}
static int <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype new_type, bool p2p)
{
struct wl1271 *wl = hw->priv;
int ret;
set_bit(<API key>, &wl->flags);
<API key>(hw, vif);
vif->type = new_type;
vif->p2p = p2p;
ret = <API key>(hw, vif);
clear_bit(<API key>, &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(<API key>, &wlvif->flags))
wl1271_info("JOIN while associated.");
/* clear encryption type */
wlvif->encryption_type = KEY_NONE;
if (set_assoc)
set_bit(<API key>, &wlvif->flags);
if (is_ibss)
ret = <API key>(wl, wlvif);
else
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
if (!test_bit(<API key>, &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 = <API key>(wl, wlvif, true);
if (ret < 0)
goto out;
ret = wl1271_acx_aid(wl, wlvif, wlvif->aid);
if (ret < 0)
goto out;
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
ret = <API key>(wl, wlvif,
<API key>,
<API key>);
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(<API key>, &wlvif->flags)) {
struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif);
<API key>(wl);
<API key>(vif, false);
}
/* to stop listening to a channel, we disconnect */
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
/* reset TX security counters on a clean disconnect */
wlvif-><API key> = 0;
wlvif->tx_security_seq = 0;
out:
return ret;
}
static void <API key>(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 <API key>(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 (<API key>(wlvif)) {
ret = wl12xx_stop_dev(wl, wlvif);
if (ret < 0)
goto out;
}
wlvif->rate_set =
<API key>(wl, wlvif->basic_rate_set);
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
ret = <API key>(
wl, wlvif, <API key>,
<API key>);
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) {
<API key>(wl);
<API key>(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 = <API key>(conf->channel->center_freq);
/* if the channel changes while joined, join again */
if (changed & <API key> &&
((wlvif->band != conf->channel->band) ||
(wlvif->channel != channel))) {
/* send all pending packets */
<API key>(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(<API key>, &wlvif->flags))
<API key>(wl, wlvif);
wlvif->basic_rate =
<API key>(wl,
wlvif->basic_rate_set);
ret = <API key>(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(<API key>,
&wlvif->flags) &&
<API key>(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 & <API key>) && !is_ap) {
if ((conf->flags & IEEE80211_CONF_PS) &&
test_bit(<API key>, &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 = <API key>;
ps_mode_str = "forced";
} else {
ps_mode = <API key>;
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 = <API key>(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 & <API key>) &&
(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 & <API key>) {
wl->band = conf->channel->band;
wl->channel = channel;
}
if (changed & <API key>)
wl->power_level = conf->power_level;
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
/* configure each interface */
<API key>(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 <API key> {
bool enabled;
int mc_list_length;
u8 mc_list[<API key>][ETH_ALEN];
};
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
static u64 <API key>(struct ieee80211_hw *hw,
struct netdev_hw_addr_list *mc_list)
#else
static u64 <API key>(struct ieee80211_hw *hw, int mc_count,
struct dev_addr_list *mc_list)
#endif
{
struct <API key> *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 (<API key>(mc_list) > <API key>) {
#else
fp->enabled = true;
if (mc_count > <API key>) {
mc_count = 0;
#endif
fp->enabled = false;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35))
} else {
fp->enabled = true;
<API key>(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 <API key> (FIF_PROMISC_IN_BSS | \
FIF_ALLMULTI | \
FIF_FCSFAIL | \
<API key> | \
FIF_CONTROL | \
FIF_OTHER_BSS)
static void <API key>(struct ieee80211_hw *hw,
unsigned int changed,
unsigned int *total, u64 multicast)
{
struct <API key> *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 &= <API key>;
changed &= <API key>;
if (unlikely(wl->state == WL1271_STATE_OFF))
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
<API key>(wl, wlvif) {
if (wlvif->bss_type != BSS_TYPE_AP_BSS) {
if (*total & FIF_ALLMULTI)
ret = <API key>(wl, wlvif,
false,
NULL, 0);
else if (fp)
ret = <API key>(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 <API 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 <API key>(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 == <API key>)
hlid = wlvif->ap.bcast_hlid;
ret = <API 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 = <API 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(<API key>, &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 = <API key>(wl, wlvif, id,
key_type, key_size,
key, hlid, tx_seq_32,
tx_seq_16);
} else {
ret = <API 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 = <API key>;
}
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 && !<API key>(addr))
return 0;
/* don't remove key if hlid was already deleted */
if (action == KEY_REMOVE &&
wlvif->sta.hlid == <API key>)
return 0;
ret = <API 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 = <API 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 = <API key>(wl);
if (ret < 0)
goto out_unlock;
switch (key_conf->cipher) {
case <API key>:
case <API key>:
key_type = KEY_WEP;
key_conf->hw_key_idx = key_conf->keyidx;
break;
case <API key>:
key_type = KEY_TKIP;
key_conf->hw_key_idx = key_conf->keyidx;
tx_seq_32 = <API key>(wlvif->tx_security_seq);
tx_seq_16 = <API key>(wlvif->tx_security_seq);
break;
case <API key>:
key_type = KEY_AES;
key_conf->flags |= <API key>;
tx_seq_32 = <API key>(wlvif->tx_security_seq);
tx_seq_16 = <API key>(wlvif->tx_security_seq);
break;
case <API key>:
key_type = KEY_GEM;
tx_seq_32 = <API key>(wlvif->tx_security_seq);
tx_seq_16 = <API key>(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 = <API key>(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 <API key> *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 <API key> if we do - in this case
* there won't be any call.
*/
ret = -EAGAIN;
goto out;
}
ret = <API key>(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 <API key>(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 == <API key>)
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
if (wl->scan.state != <API key>) {
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
*/
<API key>(wl);
wl->scan.state = <API key>;
memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch));
wl->scan_vif = NULL;
wl->scan.req = NULL;
<API key>(wl->hw, true);
out_sleep:
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
<API key>(&wl->scan_complete_work);
}
static int <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct <API key> *req,
struct <API key> *ies)
{
struct wl1271 *wl = hw->priv;
struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif);
int ret;
wl1271_debug(DEBUG_MAC80211, "<API key>");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF) {
ret = -EAGAIN;
goto out;
}
ret = <API key>(wl);
if (ret < 0)
goto out;
ret = <API key>(wl, wlvif, req, ies);
if (ret < 0)
goto out_sleep;
ret = <API key>(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 <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct wl1271 *wl = hw->priv;
int ret;
wl1271_debug(DEBUG_MAC80211, "<API key>");
mutex_lock(&wl->mutex);
if (wl->state == WL1271_STATE_OFF)
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
<API key>(wl);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static int <API key>(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 = <API key>(wl);
if (ret < 0)
goto out;
ret = <API key>(wl, value);
if (ret < 0)
wl1271_warning("<API key> failed: %d", ret);
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
return ret;
}
static int <API key>(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 = <API key>(wl);
if (ret < 0)
goto out;
<API key>(wl, wlvif) {
ret = <API key>(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 > <API key>) {
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 <API key>(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 *)<API key>(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 <API key>(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 = <API key>(wl->hw, vif);
if (!skb)
return -EOPNOTSUPP;
ret = <API key>(wl, wlvif->role_id,
<API key>,
skb->data,
skb->len, 0,
rates);
dev_kfree_skb(skb);
return ret;
}
static int <API key>(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[<API key>];
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 <API key>(wl, wlvif->role_id,
<API key>,
probe_rsp_data,
probe_rsp_len, 0,
rates);
if (probe_rsp_len + bss_conf->ssid_len > <API key>) {
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 <API key>(wl, wlvif->role_id,
<API key>,
probe_rsp_templ,
templ_len, 0,
rates);
}
static int <API key>(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 & <API key>) {
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 & <API key>) {
if (bss_conf->use_short_preamble)
<API key>(wl, wlvif, ACX_PREAMBLE_SHORT);
else
<API key>(wl, wlvif, ACX_PREAMBLE_LONG);
}
if (changed & <API key>) {
if (bss_conf->use_cts_prot)
ret = <API key>(wl, wlvif,
CTSPROTECT_ENABLE);
else
ret = <API key>(wl, wlvif,
CTSPROTECT_DISABLE);
if (ret < 0) {
wl1271_warning("Set ctsprotect failed %d", ret);
goto out;
}
}
out:
return ret;
}
static int <API key>(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 & <API key>)) {
wl1271_debug(DEBUG_MASTER, "beacon interval updated: %d",
bss_conf->beacon_int);
wlvif->beacon_int = bss_conf->beacon_int;
}
if ((changed & <API key>) && is_ap) {
u32 rate = <API key>(wl, wlvif->basic_rate_set);
if (!<API key>(wl, rate, vif)) {
wl1271_debug(DEBUG_AP, "probe response updated");
set_bit(<API key>, &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 = <API key>(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 = <API key>(wl, wlvif->basic_rate_set);
tmpl_id = is_ap ? CMD_TEMPL_AP_BEACON :
CMD_TEMPL_BEACON;
ret = <API key>(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(<API key>, &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).
*/
<API key>(beacon, WLAN_OUI_WFA,
<API key>, ieoffset);
hdr = (struct ieee80211_hdr *) beacon->data;
hdr->frame_control = cpu_to_le16(<API key> |
<API key>);
if (is_ap)
ret = <API key>(wl, vif,
beacon->data,
beacon->len,
min_rate);
else
ret = <API key>(wl, wlvif->role_id,
<API key>,
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 <API key>(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 & <API key>)) {
u32 rates = bss_conf->basic_rates;
wlvif->basic_rate_set = <API key>(wl, rates,
wlvif->band);
wlvif->basic_rate = <API key>(wl,
wlvif->basic_rate_set);
ret = <API key>(wl, wlvif);
if (ret < 0) {
wl1271_error("AP rate policy change failed %d", ret);
goto out;
}
ret = <API key>(wl, vif);
if (ret < 0)
goto out;
}
ret = <API key>(wl, vif, bss_conf, changed);
if (ret < 0)
goto out;
if ((changed & <API key>)) {
if (bss_conf->enable_beacon) {
if (!test_bit(<API key>, &wlvif->flags)) {
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
set_bit(<API key>, &wlvif->flags);
wl1271_debug(DEBUG_AP, "started AP");
}
} else {
if (test_bit(<API key>, &wlvif->flags)) {
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
clear_bit(<API key>, &wlvif->flags);
clear_bit(<API key>,
&wlvif->flags);
wl1271_debug(DEBUG_AP, "stopped AP");
}
}
}
ret = <API key>(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 = <API key>(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 <API key>(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 <API key> sta_ht_cap;
if (is_ibss) {
ret = <API key>(wl, vif, bss_conf,
changed);
if (ret < 0)
goto out;
}
if (changed & BSS_CHANGED_IBSS) {
if (bss_conf->ibss_joined) {
set_bit(<API key>, &wlvif->flags);
ibss_joined = true;
} else {
if (test_and_clear_bit(<API key>,
&wlvif->flags))
wl1271_unjoin(wl, wlvif);
}
}
if ((changed & <API key>) && 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 & <API key>) && 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 = <API key>(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 = <API key>(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 = <API key>(wl, wlvif);
if (ret < 0)
goto out;
ret = <API key>(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 =
<API key>(wl, rates,
wlvif->band);
wlvif->basic_rate =
<API key>(wl,
wlvif->basic_rate_set);
if (sta_rate_set)
wlvif->rate_set =
<API key>(wl,
sta_rate_set,
wlvif->band);
ret = <API key>(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 = <API key>(wl, wlvif, wlvif->aid);
if (ret < 0)
goto out;
/*
* Get a template for hardware connection maintenance
*/
dev_kfree_skb(wlvif->probereq);
wlvif->probereq = <API key>(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 = <API key>(wl, wlvif, true);
if (ret < 0)
goto out;
} else {
/* use defaults when not associated */
bool was_assoc =
!!test_and_clear_bit(<API key>,
&wlvif->flags);
bool was_ifup =
!!test_and_clear_bit(<API key>,
&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 */
<API key>(wl, wlvif);
wlvif->basic_rate =
<API key>(wl,
wlvif->basic_rate_set);
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
/* disable connection monitor features */
ret = <API key>(wl, wlvif, false);
/* Disable the keep-alive feature */
ret = <API key>(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 =
<API key>(wl, rates,
wlvif->band);
wlvif->basic_rate =
<API key>(wl,
wlvif->basic_rate_set);
/* by default, use 11b + OFDM rates */
wlvif->rate_set = <API key>;
ret = <API key>(wl, wlvif);
if (ret < 0)
goto out;
}
}
ret = <API key>(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(<API key>, &wlvif->flags))
<API key>(wl, wlvif);
}
/*
* stop device role if started (we might already be in
* STA/IBSS role).
*/
if (<API key>(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 = <API key>(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 = <API key>(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 = <API key>(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 & <API key>) ||
(!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 = <API key>(wl, wlvif);
if (ret < 0) {
wl1271_warning("build arp rsp failed: %d", ret);
goto out;
}
ret = <API key>(wl, wlvif,
(<API key> |
<API key>),
addr);
} else {
wlvif->ip_addr = 0;
ret = <API key>(wl, wlvif, 0, addr);
}
if (ret < 0)
goto out;
}
out:
return;
}
static void <API key>(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(<API key>, &wlvif->flags)))
goto out;
ret = <API key>(wl);
if (ret < 0)
goto out;
if (is_ap)
<API key>(wl, vif, bss_conf, changed);
else
<API key>(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 <API key> *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 = <API key>;
else
ps_scheme = <API key>;
if (!test_bit(<API key>, &wlvif->flags))
goto out;
ret = <API key>(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),
<API key>,
wl1271_tx_get_queue(queue),
ps_scheme, <API key>,
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 = <API key>(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 <API key>(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 = <API key>;
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 = <API key>(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)
<API key>(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 = <API key>(wl, wl_sta->hlid);
if (ret < 0)
return ret;
wl1271_free_sta(wl, wlvif, wl_sta->hlid);
return ret;
}
static int <API key>(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 == <API key> &&
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 == <API key>) {
/* must not fail */
wl12xx_sta_remove(wl, wlvif, sta);
return 0;
}
/* Authorize station (AP mode) */
if (is_ap &&
new_state == <API key>) {
ret = <API key>(wl, hlid);
if (ret < 0)
return ret;
ret = <API key>(wl, &sta->ht_cap, true,
hlid);
return ret;
}
/* Authorize station */
if (is_sta &&
new_state == <API key>) {
set_bit(<API key>, &wlvif->flags);
return <API key>(wl, wlvif);
}
if (is_sta &&
old_state == <API key> &&
new_state == IEEE80211_STA_ASSOC) {
clear_bit(<API key>, &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 = <API key>(wl);
if (ret < 0)
goto out;
ret = <API key>(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 <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum <API key> 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 = <API key>(wl);
if (ret < 0)
goto out;
wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu: Rx tid %d action %d",
tid, action);
switch (action) {
case <API key>:
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 = <API key>(wl, tid, *ssn, true,
hlid);
if (!ret) {
*ba_bitmap |= BIT(tid);
wl->ba_rx_session_count++;
}
break;
case <API key>:
if (!(*ba_bitmap & BIT(tid))) {
ret = -EINVAL;
wl1271_error("no active RX BA session on tid: %d",
tid);
break;
}
ret = <API key>(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 <API key>:
case <API key>:
case <API key>:
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 <API key>(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const struct <API key> *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] =
<API key>(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(<API key>, &wlvif->flags)) {
ret = <API key>(wl);
if (ret < 0)
goto out;
<API key>(wl, wlvif);
wlvif->basic_rate =
<API key>(wl, wlvif->basic_rate_set);
ret = <API key>(wl, wlvif);
wl1271_ps_elp_sleep(wl);
}
out:
mutex_unlock(&wl->mutex);
return ret;
}
static void <API key>(struct ieee80211_hw *hw,
struct <API key> *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)) {
<API key>(wl, wlvif) {
struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif);
<API key>(vif, false);
}
goto out;
}
ret = <API key>(wl);
if (ret < 0)
goto out;
/* TODO: change mac80211 to pass vif as param */
<API key>(wl, wlvif) {
ret = <API key>(wl, wlvif, ch_switch);
if (!ret)
set_bit(<API key>, &wlvif->flags);
}
wl1271_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
static bool <API key>(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 = (<API key>(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 = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 20,
.hw_value = <API key>,
.hw_value_short = <API key>,
.flags = <API key> },
{ .bitrate = 55,
.hw_value = <API key>,
.hw_value_short = <API key>,
.flags = <API key> },
{ .bitrate = 110,
.hw_value = <API key>,
.hw_value_short = <API key>,
.flags = <API key> },
{ .bitrate = 60,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 90,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 120,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 180,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 240,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 360,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 480,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 540,
.hw_value = <API key>,
.hw_value_short = <API key>, },
};
/* 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 <API key>[] = {
/* MCS rates are used only with 11n */
7, /* <API key> */
7, /* <API key> */
6, /* <API key> */
5, /* <API key> */
4, /* <API key> */
3, /* <API key> */
2, /* <API key> */
1, /* <API key> */
0, /* <API key> */
11, /* <API key> */
10, /* <API key> */
9, /* <API key> */
8, /* <API key> */
/* TI-specific rate */
<API key>, /* <API key> */
7, /* <API key> */
6, /* <API key> */
3, /* <API key> */
5, /* CONF_HW_RXTX_RATE_9 */
4, /* CONF_HW_RXTX_RATE_6 */
2, /* <API key> */
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 = <API key> | <API key> | \
(1 << <API key>), \
.ht_supported = true, \
.ampdu_factor = <API key>, \
.ampdu_density = <API key>, \
.mcs = { \
.rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, \
.rx_highest = cpu_to_le16(HW_RX_HIGHEST_RATE), \
.tx_params = <API key>, \
}, \
}
/* can't be const, mac80211 writes to this */
static struct <API key> 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 = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 90,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 120,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 180,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 240,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 360,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 480,
.hw_value = <API key>,
.hw_value_short = <API key>, },
{ .bitrate = 540,
.hw_value = <API key>,
.hw_value_short = <API key>, },
};
/* 5 GHz band channels for WL1273 */
static struct ieee80211_channel <API key>[] = {
{ .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 <API key>[] = {
/* MCS rates are used only with 11n */
7, /* <API key> */
7, /* <API key> */
6, /* <API key> */
5, /* <API key> */
4, /* <API key> */
3, /* <API key> */
2, /* <API key> */
1, /* <API key> */
0, /* <API key> */
7, /* <API key> */
6, /* <API key> */
5, /* <API key> */
4, /* <API key> */
/* TI-specific rate */
<API key>, /* <API key> */
3, /* <API key> */
2, /* <API key> */
<API key>, /* <API key> */
1, /* CONF_HW_RXTX_RATE_9 */
0, /* CONF_HW_RXTX_RATE_6 */
<API key>, /* <API key> */
<API key>, /* CONF_HW_RXTX_RATE_2 */
<API key> /* CONF_HW_RXTX_RATE_1 */
};
static struct <API key> wl1271_band_5ghz = {
.channels = <API key>,
.n_channels = ARRAY_SIZE(<API key>),
.bitrates = wl1271_rates_5ghz,
.n_bitrates = ARRAY_SIZE(wl1271_rates_5ghz),
.ht_cap = WL12XX_HT_CAP,
};
static const u8 *<API key>[] = {
[IEEE80211_BAND_2GHZ] = <API key>,
[IEEE80211_BAND_5GHZ] = <API key>
};
static const struct ieee80211_ops wl1271_ops = {
.start = wl1271_op_start,
.stop = wl1271_op_stop,
.add_interface = <API key>,
.remove_interface = <API key>,
.change_interface = <API key>,
#ifdef CONFIG_PM
.suspend = wl1271_op_suspend,
.resume = wl1271_op_resume,
#endif
.config = wl1271_op_config,
.prepare_multicast = <API key>,
.configure_filter = <API key>,
.tx = wl1271_op_tx,
.set_key = wl1271_op_set_key,
.hw_scan = wl1271_op_hw_scan,
.cancel_hw_scan = <API key>,
.sched_scan_start = <API key>,
.sched_scan_stop = <API key>,
.bss_info_changed = <API key>,
.set_frag_threshold = <API key>,
.set_rts_threshold = <API key>,
.conf_tx = wl1271_op_conf_tx,
.get_tsf = wl1271_op_get_tsf,
.get_survey = <API key>,
.sta_state = wl12xx_op_sta_state,
.ampdu_action = <API key>,
.tx_frames_pending = <API key>,
.set_bitrate_mask = <API key>,
.channel_switch = <API key>,
<API key>(wl1271_tm_cmd)
};
u8 wl1271_rate_to_idx(int rate, enum ieee80211_band band)
{
u8 idx;
BUG_ON(band >= sizeof(<API key>)/sizeof(u8 *));
if (unlikely(rate >= <API key>)) {
wl1271_error("Illegal RX rate from HW: %d", rate);
return 0;
}
idx = <API key>[band][rate];
if (unlikely(idx == <API key>)) {
wl1271_error("Unsupported RX rate from HW: %d", rate);
return 0;
}
return idx;
}
static ssize_t <API key>(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 <API key>(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 = <API key>(wl);
if (ret < 0)
goto out;
<API key>(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,
<API key>,
<API key>);
static ssize_t <API key>(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,
<API key>, NULL);
static ssize_t <API key>(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 = <API key>(&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);
<API key>(&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 = <API key>(&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 = <API key>,
};
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 <API key>(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;
<API key>(wl, &wl12xx_part_table[PART_DRPW]);
mac1 = wl1271_read32(wl, <API key>);
mac2 = wl1271_read32(wl, <API key>);
/* 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;
<API key>(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, <API key>);
else
die_info = wl1271_top_reg_read(wl, <API key>);
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;
}
<API key>(wl, oui_addr, nic_addr, 2);
ret = <API key>(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 <API key>(struct wl1271 *wl)
{
if (wl->plt)
wl1271_plt_stop(wl);
<API key>(wl->hw);
wl->mac80211_registered = false;
}
static int <API key>(struct wl1271 *wl)
{
static const u32 cipher_suites[] = {
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
};
/* The tx descriptor buffer and the TKIP space. */
wl->hw->extra_tx_headroom = <API key> +
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 = <API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key> |
<API key>;
wl->hw->wiphy->cipher_suites = cipher_suites;
wl->hw->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites);
wl->hw->wiphy->interface_modes = BIT(<API key>) |
BIT(<API key>) | BIT(NL80211_IFTYPE_AP) |
BIT(<API key>) | BIT(<API key>);
wl->hw->wiphy->max_scan_ssids = 1;
wl->hw->wiphy-><API key> = 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 = <API key> -
sizeof(struct ieee80211_header);
wl->hw->wiphy-><API key> = <API key> -
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(<API key>) >
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 |= <API key>;
wl->hw->wiphy->probe_resp_offload =
<API key> |
<API key> |
<API key>;
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-><API key> = 8;
return 0;
}
#define <API key> 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, <API key>);
INIT_WORK(&wl->tx_work, wl1271_tx_work);
INIT_WORK(&wl->recovery_work, <API key>);
INIT_DELAYED_WORK(&wl->scan_complete_work, <API key>);
INIT_DELAYED_WORK(&wl->tx_watchdog_work, <API key>);
wl->freezable_wq = <API key>("wl12xx_wq");
if (!wl->freezable_wq) {
ret = -ENOMEM;
goto err_hw;
}
wl->channel = <API key>;
wl->rx_counter = 0;
wl->power_level = <API key>;
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 = <API key>;
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(<API key>);
wl->aggr_buf = (u8 *)__get_free_pages(GFP_KERNEL, order);
if (!wl->aggr_buf) {
ret = -ENOMEM;
goto err_wq;
}
wl->dummy_packet = <API key>(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;
<API key>(&wl->fwlog_waitq);
mutex_unlock(&wl->mutex);
<API key>(wl->dev, &fwlog_attr);
device_remove_file(wl->dev, &dev_attr_hw_pg_ver);
device_remove_file(wl->dev, &<API key>);
free_page((unsigned long)wl->fwlog);
dev_kfree_skb(wl->dummy_packet);
free_pages((unsigned long)wl->aggr_buf,
get_order(<API key>));
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(<API key>, &wl->flags);
if (wl->elp_compl) {
complete(wl->elp_compl);
wl->elp_compl = NULL;
}
if (test_bit(<API key>, &wl->flags)) {
/* don't enqueue a work right now. mark it as pending */
set_bit(<API key>, &wl->flags);
wl1271_debug(DEBUG_IRQ, "should not enqueue work");
disable_irq_nosync(wl->irq);
pm_wakeup_event(wl->dev, 0);
<API key>(&wl->wl_lock, flags);
return IRQ_HANDLED;
}
<API key>(&wl->wl_lock, flags);
return IRQ_WAKE_THREAD;
}
static int __devinit wl12xx_probe(struct platform_device *pdev)
{
struct <API key> *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;
<API key>(pdev, wl);
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32)
irqflags = IRQF_TRIGGER_RISING;
#else
if (wl->platform_quirks & <API key>)
irqflags = IRQF_TRIGGER_RISING;
else
irqflags = IRQF_TRIGGER_HIGH | IRQF_ONESHOT;
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31)
ret = <API key>(&wl->irq_compat, wl->irq,
wl12xx_hardirq, wl1271_irq,
irqflags,
pdev->name, wl);
#else
ret = <API key>(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 = <API key>(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, &<API key>);
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 = <API key>(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, &<API key>);
out_irq:
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31)
<API key>(&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 = <API key>(pdev);
if (wl->irq_wake_enabled) {
device_init_wakeup(wl->dev, 0);
disable_irq_wake(wl->irq);
}
<API key>(wl);
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31)
<API key>(&wl->irq_compat);
<API key>(&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 <API key>(&wl12xx_driver);
}
module_init(wl12xx_init);
static void __exit wl12xx_exit(void)
{
<API key>(&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 <coelho@ti.com>");
MODULE_AUTHOR("Juuso Oikarinen <juuso.oikarinen@nokia.com>");
|
#ifdef __osf__
#define <API key>
#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 <API key> (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 = <API key>;
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 *
<API key>(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);
}
}
|
@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.<API key> {
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
}
|
#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)
{
<API key>(&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;
<API key>(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 = &<API key>;
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, <API key>);
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);
}
/**
* <API key> - 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 <API key>(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(<API key>);
/**
* deactivate_super - drop an active reference to superblock
* @s: superblock to deactivate
*
* Variant of <API key>(), 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);
<API key>(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);
/**
* <API key> - common helper for ->kill_sb()
* @sb: superblock to kill
*
* <API key>() does all fs-independent work on superblock
* shutdown. Typical ->kill_sb() should pick all fs-specific objects
* that need destruction out of superblock, call <API key>()
* 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 <API key>(struct super_block *sb)
{
const struct super_operations *sop = sb->s_op;
if (sb->s_root) {
<API key>(sb);
sync_filesystem(sb);
get_fs_excl();
sb->s_flags &= ~MS_ACTIVE;
<API key>(&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 <API key>() */
list_del_init(&sb->s_instances);
spin_unlock(&sb_lock);
up_write(&sb->s_umount);
}
EXPORT_SYMBOL(<API key>);
/**
* 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))) {
<API key>(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 <API key>(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, <API key>);
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 = &<API key>;
return 0;
}
EXPORT_SYMBOL(set_anon_super);
void kill_anon_super(struct super_block *sb)
{
int slot = MINOR(sb->s_dev);
<API key>(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) {
<API key>(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) {
<API key>(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) {
<API key>(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;
<API key>(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) {
<API key>(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) {
<API key>(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 = <API key>(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 == &<API key>);
sb->s_flags |= MS_BORN;
error = <API key>(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);
<API key>(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, <API key>)
* -> 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, <API key>);
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) {
<API key>(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;
<API key>(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);
<API key>(sb);
return 0;
}
EXPORT_SYMBOL(thaw_super);
|
#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 <API key>()
typedef struct RegDef {
int offset;
const char *name;
} RegDef;
const bool <API key>(void)
{
return true;
}
const bool <API key>(void)
{
return true;
}
const uint32_t <API key>(void)
{
return 16;
}
int32_t <API key>(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 <API key>(cmdqCommandStruct *pCommand)
{
if ((<API key> == pCommand->scenario) || (<API key> == pCommand->scenario)) {
CMDQ_VERBOSE("user space request, scenario:%d\n", pCommand->scenario);
} else {
CMDQ_VERBOSE("[WARNING]fix user space request to <API key>\n");
pCommand->scenario = <API key>;
}
}
bool <API key>(const CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case <API key>:
case <API key>:
case <API key>: /* phased out */
return true;
default:
return false;
}
return false;
}
bool <API key>(const CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
/* color path */
case <API key>:
case <API key>:
/* secure path */
case <API key>:
case <API key>:
return true;
default:
return false;
}
/* freely dispatch */
return false;
}
bool <API key>(CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case <API key>:
case <API key>:
case <API key>: /* 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 <API key>(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 <API key>(const int32_t thread)
{
#ifdef <API key>
if ((<API key> <= thread) &&
(<API key> + <API key> > thread)){
return true;
}
#endif
return false;
}
const bool <API key>(const int32_t thread)
{
#ifdef <API key>
return (15 == thread) ? (true) : (false);
#else
return false;
#endif
}
int <API key>(CMDQ_SCENARIO_ENUM scenario, const bool secure)
{
#ifdef <API key>
if (!secure && <API key> == scenario) {
return 15;
}
#endif
if (!secure) {
return <API key>(scenario);
}
/* dispatch secure thread according to scenario */
switch (scenario) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
/* <API key> */
return 12;
case <API key>:
case <API key>:
case <API key>:
case <API key>:
/* because mirror mode and sub disp never use at the same time in secure path, */
/* dispatch to same HW thread */
case <API key>:
case <API key>:
case <API key>:
return 13;
case <API key>:
case <API key>:
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 <API key>(CMDQ_SCENARIO_ENUM scenario)
{
if (<API key>(scenario)) {
return 0;
}
switch (scenario) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>: /* HACK: force debug into 0/1 thread */
/* primary config: thread 0 */
return 0;
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
/* 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 <API key>:
return 2;
case <API key>:
case <API key>:
return 3;
case <API key>:
case <API key>:
case <API key>:
return 4;
default:
/* freely dispatch */
return CMDQ_INVALID_THREAD;
}
/* freely dispatch */
return CMDQ_INVALID_THREAD;
}
<API key> <API key>(CMDQ_SCENARIO_ENUM scenario)
{
switch (scenario) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
/* color path */
case <API key>:
case <API key>:
/* secure path **/
case <API key>:
case <API key>:
/* currently, a prefetch thread is always in high priority. */
return <API key>;
/* HACK: force debug into 0/1 thread */
case <API key>:
return <API key>;
case <API key>:
case <API key>:
return <API key>;
default:
/* other cases need exta logic, see below. */
break;
}
if (<API key>(scenario, true)) {
return <API key>;
} else {
return <API key>;
}
}
bool <API key>(CMDQ_SCENARIO_ENUM scenario)
{
#ifdef <API key>
if (<API key> == scenario) {
/* For secure notify loop, we need IRQ to update secure task */
return true;
}
#endif
return false;
}
bool <API key>(CMDQ_SCENARIO_ENUM scenario, bool displayOnly)
{
#ifdef <API key>
if (!displayOnly && <API key> == scenario) {
return true;
}
#endif
if (<API key> == scenario) {
return true;
}
return false;
}
void <API key>(uint64_t hwflag, <API key> *valueRegId,
<API key> *destRegId,
CMDQ_EVENT_ENUM *regAccessToken)
{
*regAccess<API key>;
if (hwflag & (1LL << CMDQ_ENG_JPEG_ENC)) {
*valueRegId = CMDQ_DATA_REG_JPEG;
*destRegId = <API key>;
*regAccess<API key>;
} else if (hwflag & (1LL << CMDQ_ENG_MDP_TDSHP0)) {
*valueRegId = <API key>;
*destRegId = <API key>;
*regAccess<API key>;
} else if (hwflag & (1LL << <API key>)) {
*valueRegId = <API key>;
*destRegId = <API key>;
*regAccess<API key>;
} else {
/* assume others are debug cases */
*valueRegId = CMDQ_DATA_REG_DEBUG;
*destRegId = <API key>;
*regAccess<API key>;
}
return;
}
const char *<API key>(CMDQ_EVENT_ENUM event, uint32_t instA, uint32_t instB)
{
const char *module = "CMDQ";
switch (event) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
module = "DISP_RDMA";
break;
case <API key>:
case <API key>:
case <API key>:
case <API key>:
module = "DISP_WDMA";
break;
case <API key>:
case <API key>:
case <API key>:
case <API key>:
module = "DISP_OVL";
break;
case CMDQ_EVENT_DSI_TE:
case <API key>...<API key>:
case <API key>...<API key>:
case <API key>...<API key>:
case <API key>:
case <API key>:
module = "DISP";
break;
case <API key>...<API key>:
case <API key>...<API key>:
module = "DISP_UFOD";
break;
case <API key>...<API key>:
case <API key>...<API key>:
case <API key>...<API key>:
module = "MDP";
break;
case <API key>...<API key>:
case <API key>...<API key>:
module = "ISP";
break;
case <API key>:
case <API key>:
module = "JPGE";
break;
case CMDQ_EVENT_VENC_EOF:
case <API key>:
case <API key>:
module = "VENC";
break;
default:
module = "CMDQ";
break;
}
return module;
}
const char *<API key>(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 <API key>(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 <API key>(char *buf)
{
int32_t length = 0;
char *pBuffer = buf;
#ifdef CMDQ_PWR_AWARE
/* <API key> 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 <API key>(struct seq_file *m)
{
#ifdef CMDQ_PWR_AWARE
/* <API key> is removed in this platform */
seq_printf(m, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE));
#endif
}
void <API key>(bool enable)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
CMDQ_VERBOSE("[CLOCK] Enable SMI & LARB0 Clock\n");
enable_clock(<API key>, "CMDQ_MDP");
//enable_clock(<API key>, "CMDQ_MDP");
m4u_larb0_enable("CMDQ_MDP");
#if 0
/* <API key> is removed in this platform */
CMDQ_LOG("[CLOCK] enable <API key>\n");
enable_clock(<API key>, "CMDQ_MDP");
#endif
} else {
CMDQ_VERBOSE("[CLOCK] Disable SMI & LARB0 Clock\n");
/* disable, reverse the sequence */
//disable_clock(<API key>, "CMDQ_MDP");
m4u_larb0_disable("CMDQ_MDP");
disable_clock(<API key>, "CMDQ_MDP");
#if 0
/* <API key> is removed in this platform */
CMDQ_LOG("[CLOCK] disable <API key>\n");
disable_clock(<API key>, "CMDQ_MDP");
#endif
}
#endif /* CMDQ_PWR_AWARE */
}
void <API key>(bool enable)
{
#ifdef CMDQ_PWR_AWARE
if (enable) {
CMDQ_VERBOSE("[CLOCK] Enable CMDQ(GCE) Clock\n");
<API key>(enable, <API key>);
} else {
CMDQ_VERBOSE("[CLOCK] Disable CMDQ(GCE) Clock\n");
<API key>(enable, <API key>);
}
#endif /* CMDQ_PWR_AWARE */
}
void <API key>(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* <API key>(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 (<API key>(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 (<API key>(pTask->engineFlag)) {
module = "MDP";
break;
}
module = "CMDQ";
} while(0);
/* other case, we need to analysis instruction for more detail */
return module;
}
void <API key>(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, "<API key>"},
{0x070, "<API key>"},
{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 <API key>(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 = <API key>(
SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC,
showSmiDump);
isSMIHang = <API key>(
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 <API key>(cmdqSecDataStruct *pSecData)
{
uint32_t i = 0;
<API key> *pAddr = NULL;
if (NULL == pSecData) {
return;
}
pAddr = (<API key> *)(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-><API key>,
pSecData->enginesNeedDAPC, pSecData-><API key>);
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 <API key>(CMDQ_SCENARIO_ENUM scn)
{
uint64_t flag = 0;
switch (scn) {
case <API key>:
flag = (1LL << CMDQ_ENG_JPEG_DEC);
break;
case <API key>:
flag = (1LL << CMDQ_ENG_DISP_OVL0) |
(1LL << <API key>) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << <API key>);
break;
case <API key>:
flag = 0LL;
break;
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_OVL0) |
(1LL << CMDQ_ENG_DISP_WDMA0) |
(1LL << <API key>) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << <API key>));
break;
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) |
(1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) | (1LL << CMDQ_ENG_DISP_WDMA1));
break;
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_OVL1) |
(1LL << CMDQ_ENG_DISP_WDMA1) |
(1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << <API key>));
break;
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_RDMA0) |
(1LL << <API key>) |
(1LL << CMDQ_ENG_DISP_AAL) |
(1LL << CMDQ_ENG_DISP_GAMMA) |
(1LL << CMDQ_ENG_DISP_UFOE) | (1LL << <API key>));
break;
case <API key>:
case <API key>:
flag = ((1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI));
break;
case <API key>:
/* Trigger loop does not related to any HW by itself. */
flag = 0LL;
break;
case <API key>:
/* user space case, engine flag is passed seprately */
flag = 0LL;
break;
case CMDQ_SCENARIO_DEBUG:
case <API key>:
flag = 0LL;
break;
case <API key>:
case <API key>:
/* ESD check uses separate thread (not config, not trigger) */
flag = 0LL;
break;
case <API key>:
case <API key>:
/* color path */
flag = 0LL;
break;
case <API key>:
flag = 0LL;
break;
case <API key>:
case <API key>:
/* secure path */
flag = 0LL;
break;
case <API key>:
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 <API key> and mutex STREAM_DONE */
/* so that DISPSYS scenarios may pass check. */
cmdqCoreSetEvent(<API key>);
cmdqCoreSetEvent(<API key>);
cmdqCoreSetEvent(<API key>);
cmdqCoreSetEvent(<API key>);
cmdqCoreSetEvent(<API key>);
}
void cmdq_test_cleanup(void)
{
return; /* do nothing */
}
|
#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 <API key>
#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 <API key>
#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 = <API key>("/");
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 (<API key>() || <API key>())
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 (<API key>() || <API key>() ||
<API key>() || cpu_is_msm9615())
return 1;
else
return 0;
}
int <API key>(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] & <API key>) == 0) {
driver->data_ready[i] |= <API key>;
pr_debug("diag: Force wakeup of logging process\n");
<API key>(&driver->wait_q);
}
}
}
/* Process the data read from the smd data channel */
int <API key>(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-><API key>) {
notify = smd_info-><API key>(
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 <API key>(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-><API key>; 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 <API key>
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].
<API key>++;
foundIndex = i;
break;
}
}
<API key>(&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] |= <API key>;
pr_debug("diag: wake up logging process\n");
<API key>(&driver->wait_q);
} else
return -EINVAL;
} else if (driver->logging_mode == NO_LOGGING_MODE) {
if ((data_type >= 0) && (data_type < <API key>)) {
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 <API key>
else if (data_type == SDIO_DATA) {
driver->in_busy_sdio = 0;
queue_work(driver->diag_sdio_wq,
&(driver->diag_read_sdio_work));
}
#endif
#ifdef <API key>
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 <API key>
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),
<API key>));
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 < <API key>)) {
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 <API key>
else if (data_type == SDIO_DATA) {
if (<API key>() ||
<API key>()) {
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 <API key>
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 +
<API key>);
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 +
<API key>);
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 <API key>(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 <API key>(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;
<API key>(&driver->wait_q);
mutex_unlock(&driver->diagchar_mutex);
}
void <API key>(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;
}
<API key>(&driver->wait_q);
mutex_unlock(&driver->diagchar_mutex);
}
static int <API key>(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) {
<API key>(buf);
<API key>(entry.process_id, PKT_TYPE);
} else {
if (len > 0) {
if ((entry.client_id >= 0) &&
(entry.client_id < <API key>)) {
int index = entry.client_id;
if (driver->smd_data[index].ch) {
if ((index == MODEM_DATA) &&
<API key>(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 <API key>(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(<API key>)
unsigned char *ptr;
#endif
/* Check if the command is a supported mask command */
mask_ret = <API key>(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(<API key>)
/* 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 */
<API key>(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 (<API key>()) {
/* 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 (<API key>()) {
/* 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 <API key>
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 <API key> 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 = <API key>(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 <API key>
/* 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 < <API key>; 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 <API key>
if (<API key>() || <API key>()) {
if (driver->mdm_ch && !IS_ERR(driver->mdm_ch))
<API key>();
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 < <API key>; i++) {
driver->smd_data[i].in_busy_1 = 1;
driver->smd_data[i].in_busy_2 = 1;
}
}
#ifdef <API key>
if (<API key>() || <API key>())
if (driver->mdm_ch && !IS_ERR(driver->mdm_ch))
<API key>();
#endif
/* TBD - notify and flow control SMD */
return 0;
}
int <API key>(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 < <API key>; 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 <API key>
if (!found_it) {
if (buf == (void *)driver->buf_in_sdio) {
if (<API key>() ||
<API key>())
<API key>();
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,
<API key>);
}
return 0;
}
int <API key>(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 <API key>
else if (buf == (void *)driver->usb_buf_mdm_out) {
if (<API key>() ||
<API key>()) {
driver->read_len_mdm = diag_read_ptr->actual;
<API key>();
} 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 <API key>(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 <API key>(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:
<API key>(d_req);
break;
case USB_DIAG_WRITE_DONE:
<API key>(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-><API key>));
} else if (smd_info->type == SMD_DCI_TYPE) {
/* Notify the clients of the close */
<API key>(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-><API key>));
} else if (smd_info->type == SMD_DCI_TYPE) {
smd_info->notify_context = event;
queue_work(driver->diag_dci_wq,
&(smd_info-><API key>));
/* Notify the clients of the open */
<API key>(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(<API key>)
if (pdev->id == SMD_APPS_QDSP) {
index = LPASS_DATA;
r = <API key>("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 = <API key>("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;
}
<API key>(&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 <API key>(struct device *dev)
{
dev_dbg(dev, "pm_runtime: suspending...\n");
return 0;
}
static int <API key>(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 = <API key>,
.runtime_resume = <API key>,
};
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 <API key> = {
.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 <API key>(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), <API key>);
/*
* The update function assigned to the <API key>
* 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-><API key>),
diag_clean_reg_fn);
else if (type == SMD_CNTL_TYPE)
INIT_WORK(&(smd_info-><API key>),
diag_mask_update_fn);
else if (type == SMD_DCI_TYPE)
INIT_WORK(&(smd_info-><API key>),
<API key>);
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-><API key> = <API key>;
else if (type == SMD_CNTL_TYPE)
smd_info-><API key> =
<API key>;
else if (type == SMD_DCI_TYPE)
smd_info-><API key> =
<API key>;
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 = <API key>(&driver->smd_data[MODEM_DATA],
MODEM_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
success = <API key>(&driver->smd_data[LPASS_DATA],
LPASS_DATA, SMD_DATA_TYPE);
if (!success)
goto err;
success = <API key>(&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 = <API key>("diag_wq");
#ifdef <API key>
INIT_WORK(&(driver->diag_proc_hdlc_work), <API key>);
INIT_WORK(&(driver->diag_read_work), diag_read_work_fn);
driver->legacy_ch = usb_diag_open(DIAG_LEGACY, driver,
<API key>);
if (IS_ERR(driver->legacy_ch)) {
printk(KERN_ERR "Unable to open USB diag legacy channel\n");
goto err;
}
#endif
<API key>(&msm_smd_ch1_driver);
<API key>(&<API key>);
return;
err:
pr_err("diag: Could not initialize diag buffers");
for (i = 0; i < <API key>; i++)
diag_smd_destructor(&driver->smd_data[i]);
kfree(driver->buf_msg_mask_update);
kfree(driver->buf_log_mask_update);
kfree(driver-><API key>);
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 < <API key>; i++)
diag_smd_destructor(&driver->smd_data[i]);
#ifdef <API key>
if (driver->usb_connected)
usb_diag_free_req(driver->legacy_ch);
usb_diag_close(driver->legacy_ch);
#endif
<API key>(&msm_smd_ch1_driver);
<API key>(&msm_diag_dci_driver);
<API key>(&<API key>);
kfree(driver->buf_msg_mask_update);
kfree(driver->buf_log_mask_update);
kfree(driver-><API key>);
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);
}
|
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 <API key> extends AbstractVarExpr {
private static final L10N L = new L10N(<API key>.class);
protected final StringValue _varName;
public <API key>(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.<API key>(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;
}
}
|
#include "punchestableview.h"
#include <qf/core/log.h>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QPainter>
#include <QPixmap>
PunchesTableView::PunchesTableView(QWidget *parent)
: Super(parent)
{
<API key>(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-><API key>();
}
} 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-><API key>();
}
} else {
event->ignore();
}
}
*/
|
// 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;
}
|
<?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-><API key>());
$this->get_site_info();
}
function <API key>()
{
$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 <API key>()
{
$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-><API key>();
$this->CI->load->view('templates/' . $template . '/layout/container', $data);
}
}
function load_normal($page, $data = null)
{
$template = $this-><API key>();
$this->CI->load->view('templates/' . $template . '/layout/pages/' . $page, $data);
}
}
/* End of file System.php */
/* Location: ./application/libraries/System.php */
|
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"
|
\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}
|
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();
}
}
}
|
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
}
|
#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 <API key> *<API key>;
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 <API key>(
Widget parent,
char *name,
);
Boolean <API key>(
#ifndef _NO_PROTO
XmDataFieldWidget, XEvent*, XmTextPosition, XmTextPosition, char*, int, Boolean
#endif
);
void <API key>(
#ifndef _NO_PROTO
Widget, char*
#endif
);
extern char * <API key>(
#ifndef _NO_PROTO
Widget
#endif
);
extern wchar_t * <API key>(
#ifndef _NO_PROTO
Widget
#endif
);
void <API key>(
#ifndef _NO_PROTO
XmDataFieldWidget
#endif
);
void <API key>(
#ifndef _NO_PROTO
XmDataFieldWidget, Boolean
#endif
);
void <API key>(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, XmHighlightMode
#endif
);
void <API key>(
#ifndef _NO_PROTO
Widget, Boolean
#endif
);
char * <API key>(
#ifndef _NO_PROTO
Widget
#endif
);
void <API key>(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, Time
#endif
);
void _XmDataFieldSetSel2(
#ifndef _NO_PROTO
Widget, XmTextPosition, XmTextPosition, Boolean, Time
#endif
);
Boolean <API key>(
#ifndef _NO_PROTO
Widget, XmTextPosition *, XmTextPosition *
#endif
);
XmTextPosition XmDataFieldXYToPos(
#ifndef _NO_PROTO
Widget, Position, Position
#endif
);
void <API key>(
#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 <API key>(
#ifndef _NO_PROTO
Widget, Boolean
#endif
);
void <API key>(
#ifndef _NO_PROTO
Widget, XmTextPosition
#endif
);
extern WidgetClass <API key>;
typedef struct <API key> {
Widget w; /* The XmDataField */
String text; /* Proposed string */
Boolean accept; /* Accept return value, for validation */
} <API key>;
#if defined(__cplusplus)
} /* extern "C" */
#endif
#endif /* _XmDataF_h */
|
#ifndef OFP_VERSION_H
#define OFP_VERSION_H 1
#include <openflow/openflow-common.h>
#include "util.h"
#include "openvswitch/ofp-util.h"
#define <API key> \
{"version", no_argument, NULL, 'V'}, \
{"protocols", required_argument, NULL, 'O'}
#define <API key> \
case 'V': \
ovs_print_version(OFP10_VERSION, OFP13_VERSION); \
exit(EXIT_SUCCESS); \
\
case 'O': \
<API key>(optarg); \
break;
uint32_t <API key>(void);
void <API key>(const char *string);
void <API key>(uint32_t);
void <API key>(uint32_t);
void ofp_version_usage(void);
#endif
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Database Navigator.
# Database Navigator is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Database Navigator is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
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'
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)))
|
/*QMainWindow, QMenuBar, QToolBar, QPushButton {
background-color: #000000;
color: #ffffff;
}
QDockWidget::title, QDockWidget::float-button, QDockWidget::close-button {
background-color: #999999;
color: #ffffff;
}*/
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
{
<API key>: %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);
<API key>: %ACCENT%;
}
QComboBox QAbstractItemView
{
border: 1px solid darkgray;
<API key>: 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;
/*<API key>: 3px;
<API key>: 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 */
<API key>: 3px;
}
QTabBar::tab:first:!selected
{
margin-left: 0px; /* the last selected tab has nothing to overlap with on the right */
<API key>: 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
{
<API key>: 3px;
<API key>: 3px;
margin-bottom: 0px;
}
QTabBar::tab:!selected:hover
{
/*border-top: 2px solid %ACCENT%;
padding-bottom: 3px;*/
<API key>: 3px;
<API key>: 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;
}
|
YUI.add("lang/dial",function(e){e.Intl.add("dial","",{label:"My label",resetStr:"Reset",tooltipHandle:"Drag to set value"})},"3.9.0pr1");
|
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.<API key>;
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.<API key>;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.<API key>;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
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);
void launchSAF(HFile file);
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.<API key>(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 <API key> = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
<API key>.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 (<API key> 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.<API key>);
}
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];
<API key> <API key> = new <API key>(tempBytes);
cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()),
<API key>, 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];
<API key> <API key> = new <API key>(tempBytes);
cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()),
<API key>, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage <API key> = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
byte[] tempBytes = new byte[0];
<API key> <API key> = new <API key>(tempBytes);
<API key>.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()),
<API key>, 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];
<API key> <API key> = new <API key>(tempBytes);
cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()),
<API key>, 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 (<API key> 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.<API key>);
}
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.<API key>(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 (<API key> 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 <API key> = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
<API key>.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 (<API key> 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.<API key>);
}
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.<API key>(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;
}
}
}
|
#include "qmljstoolsplugin.h"
#include "qmljsmodelmanager.h"
#include "qmljsfunctionfilter.h"
#include "qmljslocatordata.h"
#include "<API key>.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 <API key> : public QObject
{
public:
<API key>();
QmlJSToolsSettings settings;
ModelManager modelManager;
QAction <API key>{QmlJSToolsPlugin::tr("Reset Code Model"), nullptr};
LocatorData locatorData;
FunctionFilter functionFilter{&locatorData};
<API key> <API key>;
BasicBundleProvider basicBundleProvider;
};
QmlJSToolsPlugin::~QmlJSToolsPlugin()
{
delete d;
}
bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
Q_UNUSED(error)
d = new <API key>;
return true;
}
<API key>::<API key>()
{
// Core::VcsManager *vcsManager = Core::VcsManager::instance();
// Core::DocumentManager *documentManager = Core::DocumentManager::instance();
// connect(vcsManager, &Core::VcsManager::repositoryChanged,
// &d->modelManager, &ModelManager::<API key>);
// connect(documentManager, &DocumentManager::<API key>,
// &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(
&<API key>, Constants::RESET_CODEMODEL);
connect(&<API key>, &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)
<API key>.setEnabled(false);
});
connect(ProgressManager::instance(), &ProgressManager::allTasksFinished,
[this](Core::Id type) {
if (type == QmlJS::Constants::TASK_INDEX)
<API key>.setEnabled(true);
});
}
void QmlJSToolsPlugin::<API key>()
{
d->modelManager.<API key>();
}
} // Internal
} // QmlJSTools
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-cen-xr-w32-bld/build/netwerk/base/public/<API key>.idl
*/
#ifndef <API key>
#define <API key>
#ifndef <API key>
#include "<API key>.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: <API key> */
#define <API key> "<API key>"
#define <API key> \
{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 <API key> : public <API key> {
public:
<API key>(<API key>)
/**
* 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;
};
<API key>(<API key>, <API key>)
/* Use this macro when declaring classes that implement this interface. */
#define <API key> \
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 <API key>(_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 <API key>(_to) \
NS_SCRIPTABLE NS_IMETHOD Init(void) { return !_to ? <API key> : _to->Init(); } \
NS_SCRIPTABLE NS_IMETHOD Shutdown(void) { return !_to ? <API key> : _to->Shutdown(); } \
NS_SCRIPTABLE NS_IMETHOD GetAutodialEnabled(PRBool *aAutodialEnabled) { return !_to ? <API key> : _to->GetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD SetAutodialEnabled(PRBool aAutodialEnabled) { return !_to ? <API key> : _to->SetAutodialEnabled(aAutodialEnabled); } \
NS_SCRIPTABLE NS_IMETHOD GetSendBufferSize(PRInt32 *aSendBufferSize) { return !_to ? <API key> : _to->GetSendBufferSize(aSendBufferSize); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class _MYCLASS_ : public <API key>
{
public:
NS_DECL_ISUPPORTS
<API key>
_MYCLASS_();
private:
~_MYCLASS_();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(_MYCLASS_, <API key>)
_MYCLASS_::_MYCLASS_()
{
/* member initializers and constructor code */
}
_MYCLASS_::~_MYCLASS_()
{
/* destructor code */
}
/* void init (); */
NS_IMETHODIMP _MYCLASS_::Init()
{
return <API key>;
}
/* void shutdown (); */
NS_IMETHODIMP _MYCLASS_::Shutdown()
{
return <API key>;
}
/* attribute boolean autodialEnabled; */
NS_IMETHODIMP _MYCLASS_::GetAutodialEnabled(PRBool *aAutodialEnabled)
{
return <API key>;
}
NS_IMETHODIMP _MYCLASS_::SetAutodialEnabled(PRBool aAutodialEnabled)
{
return <API key>;
}
/* readonly attribute long sendBufferSize; */
NS_IMETHODIMP _MYCLASS_::GetSendBufferSize(PRInt32 *aSendBufferSize)
{
return <API key>;
}
/* End of implementation class template. */
#endif
#endif /* <API key> */
|
<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="<API key>" ng-model="contributer.<API key>">
</input> %
</div>
<div class = 'col-sm-2'>
<button type="submit" class="btn btn-default" aria-label="Left Align" ng-click='<API key>($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>
|
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
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';
|
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.<API key>;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class <API key> {
@Rule
public MockConfigRule mockConfigRule =
new MockConfigRule((MockConfigRule.mockConfig(ConfigValues.<API key>, false)),
(MockConfigRule.mockConfig(ConfigValues.<API key>, false)));
@Test
public void <API key>() {
Guid clusterPolicyId = new Guid("<API key>");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
<API key> command =
new <API key>(new <API key>(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertTrue(command.<API key>());
}
@Test
public void <API key>() {
Guid clusterPolicyId = new Guid("<API key>");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
HashMap<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("fail?", "sure, fail!");
clusterPolicy.setParameterMap(parameterMap);
<API key> command =
new <API key>(new <API key>(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertFalse(command.<API key>());
}
}
|
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 <API key> {
public readonly <API key> DsToolWindowService;
public readonly <API key> <API key>;
public readonly IToolWindowGroup ToolWindowGroup;
public <API key>(<API key> toolWindowService, IToolWindowGroup toolWindowGroup) {
DsToolWindowService = toolWindowService;
<API key> = toolWindowGroup.<API key>;
ToolWindowGroup = toolWindowGroup;
}
}
abstract class <API key> : MenuItemBase<<API key>> {
protected sealed override object CachedContextKey => ContextKey;
static readonly object ContextKey = new object();
protected sealed override <API key>? CreateContext(IMenuItemContext context) => <API key>(context);
readonly <API key> toolWindowService;
protected <API key>(<API key> toolWindowService) => this.toolWindowService = toolWindowService;
protected <API key>? <API key>(IMenuItemContext context) {
if (context.CreatorObject.Guid != new Guid(MenuConstants.<API key>))
return null;
var twg = context.Find<IToolWindowGroup>();
if (twg is null || !toolWindowService.Owns(twg))
return null;
return new <API key>(toolWindowService, twg);
}
}
[ExportMenuItem(Header = "res:<API key>", InputGestureText = "res:ShortCutKeyShiftEsc", Icon = DsImagesAttribute.TableViewNameOnly, Group = MenuConstants.<API key>, Order = 10)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.ToolWindowGroup.<API key>;
public override void Execute(<API key> context) => context.ToolWindowGroup.CloseActiveTab();
}
[ExportMenuItem(Header = "res:<API key>", Icon = DsImagesAttribute.CloseDocumentGroup, Group = MenuConstants.<API key>, Order = 20)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.CloseAllTabs();
}
static class CmdConstants {
public const string MOVE_CONTENT_GUID = "<API key>";
public const string GROUP_MOVE_CONTENT = "0,<API key>";
public const string MOVE_GROUP_GUID = "<API key>";
public const string GROUP_MOVE_GROUP = "0,<API key>";
}
[ExportMenuItem(Header = "res:<API key>", Guid = CmdConstants.MOVE_CONTENT_GUID, Group = MenuConstants.<API key>, Order = 30)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override void Execute(<API key> context) => Debug.Fail("Shouldn't be here");
}
[ExportMenuItem(Header = "res:<API key>", Guid = CmdConstants.MOVE_GROUP_GUID, Group = MenuConstants.<API key>, Order = 40)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.ToolWindowGroup.TabContents.Count() > 1;
public override void Execute(<API key> 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 <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, <API key>.Top);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, <API key>.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 10)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, <API key>.Left);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, <API key>.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 20)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, <API key>.Right);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, <API key>.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_CONTENT_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.<API key>, Group = CmdConstants.GROUP_MOVE_CONTENT, Order = 30)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup.ActiveTabContent, <API key>.Bottom);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup.ActiveTabContent, <API key>.Bottom);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveTopCommand", Icon = DsImagesAttribute.ToolstripPanelTop, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 0)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, <API key>.Top);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup, <API key>.Top);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveLeftCommand", Icon = DsImagesAttribute.ToolstripPanelLeft, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 10)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, <API key>.Left);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup, <API key>.Left);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveRightCommand", Icon = DsImagesAttribute.ToolstripPanelRight, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 20)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, <API key>.Right);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup, <API key>.Right);
}
[ExportMenuItem(OwnerGuid = CmdConstants.MOVE_GROUP_GUID, Header = "res:MoveBottomCommand", Icon = DsImagesAttribute.<API key>, Group = CmdConstants.GROUP_MOVE_GROUP, Order = 30)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsEnabled(<API key> context) => context.DsToolWindowService.CanMove(context.ToolWindowGroup, <API key>.Bottom);
public override void Execute(<API key> context) => context.DsToolWindowService.Move(context.ToolWindowGroup, <API key>.Bottom);
}
[ExportMenuItem(Header = "res:<API key>", Icon = DsImagesAttribute.<API key>, Group = MenuConstants.<API key>, Order = 0)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Icon = DsImagesAttribute.<API key>, Group = MenuConstants.<API key>, Order = 10)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.NewVerticalTabGroup();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 20)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.MoveToNextTabGroup();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 30)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 40)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 50)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 0)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.CloseTabGroup();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 10)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 20)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 30)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Group = MenuConstants.<API key>, Order = 40)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.MergeAllTabGroups();
}
[ExportMenuItem(Header = "res:<API key>", Icon = DsImagesAttribute.<API key>, Group = MenuConstants.<API key>, Order = 0)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
[ExportMenuItem(Header = "res:<API key>", Icon = DsImagesAttribute.<API key>, Group = MenuConstants.<API key>, Order = 10)]
sealed class <API key> : <API key> {
[<API key>]
<API key>(<API key> toolWindowService)
: base(toolWindowService) {
}
public override bool IsVisible(<API key> context) => context.<API key>.<API key>;
public override void Execute(<API key> context) => context.<API key>.<API key>();
}
}
|
'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",
/**
* <API key>
*/
<API key>: "<API key>",
/**
* 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;
|
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! 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,
}
|
@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 $
// This file is part of SUMO.
// SUMO is free software: you can redistribute it and/or modify
// (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 <API key>() const {
return <API key>;
}
void <API key>(bool value) {
<API key> = 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 <API key>;
};
#endif
|
namespace Allors.Repository
{
using System;
using Attributes;
#region Allors
[Id("<API key>")]
#endregion
public partial class <API key> : CommunicationEvent, Versioned
{
#region inherited properties
public <API key> <API key> { get; set; }
public <API key> <API key> { get; set; }
public <API key> <API key> { get; set; }
public ObjectState[] <API key> { get; set; }
public ObjectState[] LastObjectStates { get; set; }
public ObjectState[] ObjectStates { get; set; }
public Security<API key> { 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 <API key> { get; set; }
public <API key>[] 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("<API key>")]
[AssociationId("<API key>")]
[RoleId("<API key>")]
#endregion
[Multiplicity(Multiplicity.ManyToMany)]
[Indexed]
[Workspace]
public Party[] Participants { get; set; }
#region Allors
[Id("<API key>")]
[AssociationId("<API key>")]
[RoleId("<API key>")]
#endregion
[Size(256)]
[Workspace]
public string Location { get; set; }
#region Versioning
#region Allors
[Id("<API key>")]
[AssociationId("<API key>")]
[RoleId("<API key>")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToOne)]
[Workspace]
public <API key> CurrentVersion { get; set; }
#region Allors
[Id("<API key>")]
[AssociationId("<API key>")]
[RoleId("<API key>")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.OneToMany)]
[Workspace]
public <API key>[] 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
}
}
|
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;
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); // KeyTreeMap+CompareValueArrayList
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);
}
}
|
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.<API key>;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.renderer.<API key>;
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 <API key>
{
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 <API key>(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.<API key>(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 <API key>(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 <API key>(player));
}
@Override
public void initGui()
{
super.buttonList.clear();
if (this.mc.playerController.isInCreativeMode())
{
this.mc.displayGuiScreen(new <API key>(this.mc.player));
}
else
super.initGui();
if (!this.mc.player.<API key>().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)
<API key>();
//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 <API key>()
{
int var1 = this.guiLeft - 124;
int var2 = this.guiTop;
Collection var4 = this.mc.player.<API key>();
//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.<API key>().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.<API key>(var1, var2, 0, 166, 140, 32);
if (var9.hasStatusIcon())
{
int var10 = var9.getStatusIconIndex();
this.<API key>(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.<API key>(var12, var1 + 10 + 18, var2 + 6, 16777215);
String var11 = Potion.getDurationString(var8);
this.fontRenderer.<API key>(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;
}
}
|
/* ft_show_tab.c :+: :+: :+: */
/* By: pgritsen <marvin@42.fr> +#+ +:+ +#+ */
/* Created: 2017/08/05 19:31:02 by pgritsen #+# #+# */
#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++;
}
}
|
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=<API key>',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
];
|
// modification, are permitted provided that the following conditions are
// met:
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// 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 <API key> 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 <API key>
*/
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 (*<API key>)();
// Set a C debug event listener.
static bool <API key>(EventCallback that,
Handle<Value> data = Handle<Value>());
static bool <API key>(EventCallback2 that,
Handle<Value> data = Handle<Value>());
// Set a JavaScript debug event listener.
static bool <API key>(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 <API key>(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 <API key> = false);
static void SetMessageHandler2(MessageHandler2 handler);
static void SendCommand(const uint16_t* command, int length,
ClientData* client_data = NULL);
// Dispatch interface.
static void <API key>(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 <API key>(
<API key> 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::<API key>
* 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 <API key>();
/**
* 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_
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Validator {
public $<API key> = "\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 $<API key> = 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-><API key>.$msg : $msg;
}
else
{
$this->_errors[$key] = $msg;
}
if ($this-><API key>)
{
$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 <API key>($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 */
|
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.<API key>;
import javax.xml.parsers.<API key>;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.<API key>;
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 <API key> docFactory= <API key>.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 <API key>(IExtensionParser parser) {
extensionParsers.remove(parser);
}
public GPX parseGPX(File gpxFile) throws IOException, <API key>, 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 <API key>
* @throws SAXException
* @throws IOException
*/
public GPX parseGPX(InputStream in) throws <API key>, 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(<API key> 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(<API key> 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(<API key>(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(<API key>(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found cmt node in waypoint data");
w.setComment(<API key>(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found desc node in waypoint data");
w.setDescription(<API key>(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found src node in waypoint data");
w.setSrc(<API key>(currentNode));
} else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found magvar node in waypoint data");
w.<API key>(<API key>(currentNode));
} else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found geoidheight node in waypoint data");
w.setGeoidHeight(<API key>(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(<API key>(currentNode));
} else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sym node in waypoint data");
w.setSym(<API key>(currentNode));
} else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found fix node in waypoint data");
w.setFix(<API key>(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found type node in waypoint data");
w.setType(<API key>(currentNode));
} else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sat node in waypoint data");
w.setSat(<API key>(currentNode));
} else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found hdop node in waypoint data");
w.setHdop(<API key>(currentNode));
} else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found vdop node in waypoint data");
w.setVdop(<API key>(currentNode));
} else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found pdop node in waypoint data");
w.setPdop(<API key>(currentNode));
} else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ageofgpsdata node in waypoint data");
w.setAgeOfGPSData(<API key>(currentNode));
} else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found dgpsid node in waypoint data");
w.setDgpsid(<API key>(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.<API key>(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(<API key>(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
trk.setComment(<API key>(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
trk.setDescription(<API key>(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
trk.setSrc(<API key>(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(<API key>(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
trk.setType(<API key>(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(<API key>(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
rte.setComment(<API key>(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
rte.setDescription(<API key>(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
rte.setSrc(<API key>(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(<API key>(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
rte.setType(<API key>(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.<API key>(currentNode);
//.addExtensionData(parser.getId(), data);
}
*/
}
}
}
return trkpts;
}
private Double <API key>(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 <API key>(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 <API key>(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 <API key>(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, <API key>, <API key> {
OutputStream out = FileUtils.openOutputStream(gpxFile);
writeGPX(gpx,out);
out.flush();
out.close();
}
public void writeGPX(GPX gpx, OutputStream out) throws <API key>, <API key> {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Node gpxNode = doc.createElement(GPXConstants.GPX_NODE);
<API key>(gpx, gpxNode, doc);
if(gpx.getWaypoints() != null) {
Iterator<Waypoint> itW = gpx.getWaypoints().iterator();
while(itW.hasNext()) {
<API key>(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 <API key>(Waypoint wpt, Node gpxNode, Document doc) {
<API key>(GPXConstants.WPT_NODE, wpt, gpxNode, doc);
}
private void <API key>(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.<API key>() != null) {
Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
node.appendChild(doc.createTextNode(wpt.<API key>().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().<API key>(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().<API key>(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()) {
<API key>(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().<API key>(node, rte, doc);
}
trkNode.appendChild(node);
}
if(rte.getRoutePoints() != null) {
Iterator<Waypoint> it = rte.getRoutePoints().iterator();
while(it.hasNext()) {
<API key>(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc);
}
}
gpxNode.appendChild(trkNode);
}
private void <API key>(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().<API key>(node, gpx, doc);
}
gpxNode.appendChild(node);
}
}
}
|
! 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
|
// BornAgain: simulate and fit scattering at grazing incidence
//! @file Core/StandardSamples/<API key>.h
//! @brief Defines various sample builder classes to test DA, LMA, SSCA approximations
//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
#ifndef <API key>
#define <API key>
#include "IMultiLayerBuilder.h"
//! Creates the sample demonstrating size distribution model in decoupling approximation.
//! Equivalent of Examples/python/simulation/<API key>/ApproximationDA.py
//! @ingroup standard_samples
class BA_CORE_API_ <API key> : public IMultiLayerBuilder
{
public:
<API key>(){}
MultiLayer* buildSample() const;
};
//! Creates the sample demonstrating size distribution model in local monodisperse approximation.
//! Equivalent of Examples/python/simulation/<API key>/ApproximationLMA.py
//! @ingroup standard_samples
class BA_CORE_API_ <API key> : public IMultiLayerBuilder
{
public:
<API key>(){}
MultiLayer* buildSample() const;
};
//! Creates the sample demonstrating size distribution model in size space coupling approximation.
//! Equivalent of Examples/python/simulation/<API key>/ApproximationSSCA.py
//! @ingroup standard_samples
class BA_CORE_API_ <API key> : public IMultiLayerBuilder
{
public:
<API key>(){}
MultiLayer* buildSample() const;
};
//! Builds sample: size spacing correlation approximation (IsGISAXS example
//! @ingroup standard_samples
class BA_CORE_API_ <API key> : public IMultiLayerBuilder
{
public:
<API key>(){}
MultiLayer* buildSample() const;
};
#endif // <API key>
|
<?php
/**
* 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-><API key>();
$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 <API key>()
{
$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;
}
}
|
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;
}
|
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 <API key> extends <API key> {
private static final long serialVersionUID = -<API key>;
private final String path;
private final String type;
private final Dimension size;
private Image image;
public <API key>(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;
}
}
|
#ifdef TI83P
# include <ti83pdefs.h>
# include <ti83p.h>
void YName() __naked
{
__asm
push af
push hl
push iy
ld iy,
BCALL(_YName___db)
pop iy
pop hl
pop af
ret
__endasm;
}
#endif
|
#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
|
/* X r d C m s L o g i n . c c */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* This file is part of the XRootD software suite. */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* option) any later version. */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* be used to endorse or promote products derived from this software without */
#include <netinet/in.h>
#include "XProtocol/YProtocol.hh"
#include "Xrd/XrdLink.hh"
#include "XrdCms/XrdCmsLogin.hh"
#include "XrdCms/XrdCmsParser.hh"
#include "XrdCms/XrdCmsTalk.hh"
#include "XrdCms/XrdCmsSecurity.hh"
#include "XrdCms/XrdCmsTrace.hh"
#include "XrdOuc/XrdOucPup.hh"
#include "XrdSys/XrdSysError.hh"
#include "XrdSys/XrdSysPthread.hh"
using namespace XrdCms;
/* Public: A d m i t */
int XrdCmsLogin::Admit(XrdLink *Link, CmsLoginData &Data)
{
CmsRRHdr myHdr;
CmsLoginData myData;
const char *eText, *Token;
int myDlen, Toksz;
// Get complete request
if ((eText = XrdCmsTalk::Attend(Link, myHdr, myBuff, myBlen, myDlen)))
return Emsg(Link, eText, 0);
// If we need to do authentication, do so now
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host()))
&& !XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Fiddle with the login data structures
Data.SID = Data.Paths = 0;
memset(&myData, 0, sizeof(myData));
myData.Mode = Data.Mode;
myData.HoldTime = Data.HoldTime;
myData.Version = Data.Version = kYR_Version;
// Decode the data pointers ans grab the login data
if (!Parser.Parse(&Data, myBuff, myBuff+myDlen))
return Emsg(Link, "invalid login data", 0);
// Do authentication now, if needed
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host())))
if (!XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Send off login reply
return (sendData(Link, myData) ? 0 : 1);
}
/* Private: E m s g */
int XrdCmsLogin::Emsg(XrdLink *Link, const char *msg, int ecode)
{
Say.Emsg("Login", Link->Name(), "login failed;", msg);
return ecode;
}
/* Public: L o g i n */
int XrdCmsLogin::Login(XrdLink *Link, CmsLoginData &Data, int timeout)
{
CmsRRHdr LIHdr;
char WorkBuff[4096], *hList, *wP = WorkBuff;
int n, dataLen;
// Send the data
if (sendData(Link, Data)) return kYR_EINVAL;
// Get the response.
if ((n = Link->RecvAll((char *)&LIHdr, sizeof(LIHdr), timeout)) < 0)
return Emsg(Link, (n == -ETIMEDOUT ? "timed out" : "rejected"));
// Receive and decode the response. We apparently have protocol version 2.
if ((dataLen = static_cast<int>(ntohs(LIHdr.datalen))))
{if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
if (Link->RecvAll(WorkBuff, dataLen, timeout) < 0)
return Emsg(Link, "login receive error");
}
// Check if we are being asked to identify ourselves
if (LIHdr.rrCode == kYR_xauth)
{if (!XrdCmsSecurity::Identify(Link, LIHdr, WorkBuff, sizeof(WorkBuff)))
return kYR_EINVAL;
dataLen = static_cast<int>(ntohs(LIHdr.datalen));
if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
}
// The response can also be a login redirect (i.e., a try request).
if (!(Data.Mode & CmsLoginData::kYR_director)
&& LIHdr.rrCode == kYR_try)
{if (!XrdOucPup::Unpack(&wP, wP+dataLen, &hList, n))
return Emsg(Link, "malformed try host data");
Data.Paths = (kXR_char *)strdup(n ? hList : "");
return kYR_redirect;
}
// Process error reply
if (LIHdr.rrCode == kYR_error)
return (dataLen < (int)sizeof(kXR_unt32)+8
? Emsg(Link, "invalid error reply")
: Emsg(Link, WorkBuff+sizeof(kXR_unt32)));
// Process normal reply
if (LIHdr.rrCode != kYR_login
|| !Parser.Parse(&Data, WorkBuff, WorkBuff+dataLen))
return Emsg(Link, "invalid login response");
return 0;
}
/* Private: s e n d D a t a */
int XrdCmsLogin::sendData(XrdLink *Link, CmsLoginData &Data)
{
static const int xNum = 16;
int iovcnt;
char Work[xNum*12];
struct iovec Liov[xNum];
CmsRRHdr Resp={0, kYR_login, 0, 0};
// Pack the response (ignore the auth token for now)
if (!(iovcnt=Parser.Pack(kYR_login,&Liov[1],&Liov[xNum],(char *)&Data,Work)))
return Emsg(Link, "too much login reply data");
// Complete I/O vector
Resp.datalen = Data.Size;
Liov[0].iov_base = (char *)&Resp;
Liov[0].iov_len = sizeof(Resp);
// Send off the data
Link->Send(Liov, iovcnt+1);
// Return success
return 0;
}
|
#ifndef <API key>
#define <API key>
#ifdef _WIN32
#include "../msvc/msvc_compat.h"
#ifdef __cplusplus
extern "C" {
#endif
#undef strcasecmp
#undef strdup
#undef isblank
#undef strtok_r
#define strcasecmp(a, b) rarch_strcasecmp__(a, b)
#define strdup(orig) rarch_strdup__(orig)
#define isblank(c) rarch_isblank__(c)
#define strtok_r(str, delim, saveptr) rarch_strtok_r__(str, delim, saveptr)
int strcasecmp(const char *a, const char *b);
char *strdup(const char *orig);
int isblank(int c);
char *strtok_r(char *str, const char *delim, char **saveptr);
#ifdef __cplusplus
}
#endif
#endif
#endif
|
// Author : Toru Shiozaki
// Date : May 2009
#define NGRID 12
#define MAXT 64
#define NBOX 32
#define NBOXL 0
#define T_INFTY 11
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "mpreal.h"
#include <map>
#include <cmath>
#include <string>
#include <cassert>
#include <fstream>
#include "gmp_macros.h"
#include <boost/lexical_cast.hpp>
#include "../erirootlist.h"
extern "C" {
void dsyev_(const char*, const char*, const int*, double*, const int*, double*, double*, const int*, int*);
}
using namespace boost;
using namespace std;
using namespace mpfr;
using namespace bagel;
void rysroot_gmp(const vector<mpfr::mpreal>& ta, vector<mpfr::mpreal>& dx, vector<mpfr::mpreal>& dw, const int nrank, const int nbatch) ;
vector<mpreal> chebft(int n) {
mpfr::mpreal::set_default_prec(GMPPREC);
vector<mpreal> out(n);
const mpreal half = "0.5";
for (int k = 0; k != n; ++k) {
const mpreal y = mpfr::cos(GMPPI * (k + half) / n);
out[k] = y;
}
return out;
}
vector<vector<double>> get_C(const mpreal tbase, const mpreal stride, int rank, const bool asymp) {
mpfr::mpreal::set_default_prec(GMPPREC);
const int n = NGRID;
const mpreal zero = "0.0";
const mpreal half = "0.5";
const mpreal one = "1.0";
vector<mpreal> cheb = chebft(n);
const mpreal Tmin = tbase;
const mpreal Tmax = Tmin + stride;
const mpreal Tp = half * (Tmin + Tmax);
vector<mpreal> Tpoints(n);
for (int i = 0; i != n; ++i) {
Tpoints[i] = stride*half*cheb[i] + Tp;
}
#ifdef DAWSON
vector<mpreal> tt_infty(1); tt_infty[0] = Tmax;
vector<mpreal> dx_infty(rank);
vector<mpreal> dw_infty(rank);
if (asymp) rysroot_gmp(tt_infty, dx_infty, dw_infty, rank, 1);
#endif
vector<map<mpreal, mpreal>> table_reserve(n);
#pragma omp parallel for
for (int i = 0; i < n; ++i) {
vector<mpreal> ttt(1); ttt[0] = Tpoints[i];
vector<mpreal> dx(rank);
vector<mpreal> dw(rank);
rysroot_gmp(ttt, dx, dw, rank, 1);
// sort dx and dw using dx
#ifdef DAWSON
if (asymp) {
for (int j = 0; j != rank; ++j) {
table_reserve[i].insert(make_pair(-(1.0 - dx[j])*ttt[0]/((1.0 - dx_infty[j])*tt_infty[0]), dw[j]*ttt[0]/(dw_infty[j]*tt_infty[0])));
}
} else {
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
}
#else
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
#endif
}
vector<vector<double>> c;
for (int ii = 0; ii != rank; ++ii) {
vector<double> tc(n);
vector<double> tc2(n);
vector<mpreal> cdx, cdw;
for (int j = 0; j != n; ++j) {
auto iter = table_reserve[j].begin();
for (int i = 0; i != ii; ++i) ++iter;
cdx.push_back(iter->first);
cdw.push_back(iter->second);
}
const mpreal two = "2.0";
const mpreal half = "0.5";
const mpreal fac = two / n;
const mpreal pi = GMPPI;
for (int j = 0; j != n; ++j) {
mpreal sum = "0.0";
mpreal sum2 = "0.0";
for (int k = 0; k != n; ++k) {
sum += cdx[k] * mpfr::cos(pi * j * (k + half) / n);
sum2 += cdw[k] * mpfr::cos(pi * j * (k + half) / n);
}
tc[j] = (sum * fac).toDouble();
tc2[j] = (sum2 * fac).toDouble();
}
if (tc[n-1] > 1.0e-10 || tc2[n-1] > 1.0e-10) {
cout << " caution: cheb not converged " << ii << " " << setprecision(10) << fixed << Tmin.toDouble() << " " << Tmax.toDouble() << endl;
for (int i = 0; i != n; ++i) {
cout << setw(20) << Tpoints[i].toDouble() << setw(20) << tc[i] << setw(20) << tc2[i] << endl;
}
}
c.push_back(tc);
c.push_back(tc2);
}
return c;
}
bool test(const int nrank, const double tin) {
mpfr::mpreal::set_default_prec(GMPPREC);
const static int nsize = 1;
vector<mpreal> tt(nsize, tin);
vector<mpreal> rr(nsize*nrank);
vector<mpreal> ww(nsize*nrank);
rysroot_gmp(tt, rr, ww, nrank, nsize);
map<mpreal,mpreal> gmp;
for (int i = 0; i != nsize*nrank; ++i)
gmp.insert(make_pair(rr[i], ww[i]));
double dt[nsize] = {tt[0].toDouble()};
double dr[nsize*nrank];
double dw[nsize*nrank];
eriroot__.root(nrank, dt, dr, dw, nsize);
cout << setprecision(10) << scientific << endl;
auto iter = gmp.begin();
for (int i = 0; i != nrank*nsize; ++i, ++iter) {
cout << setw(20) << dr[i] << setw(20) << iter->first << setw(20) << fabs(dr[i] - (iter->first).toDouble()) << endl;
cout << setw(20) << dw[i] << setw(20) << iter->second << setw(20) << fabs(dw[i] - (iter->second).toDouble()) << endl;
}
iter = gmp.begin();
for (int i = 0; i != nrank; ++i, ++iter) {
if (!(fabs(dr[i] - (iter->first).toDouble()))) cout << dt[0] << endl;
//assert(fabs(dr[i] - (iter->first).toDouble()) < 1.0e-13);
//assert(fabs(dw[i] - (iter->second).toDouble()) < 1.0e-13);
}
cout << "test passed: rank" << setw(3) << nrank << endl;
cout << "
}
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
const mpreal T_ASYM = static_cast<mpreal>(MAXT + (NBOXL)*(NBOXL + 1.0)*(2.0*NBOXL + 1.0)/6.0);
mpfr::mpreal::set_default_prec(GMPPREC);
mpfr::mpreal pi = GMPPI;
if (argc > 1) {
cout << "
const string toggle = argv[1];
if (toggle == "t") {
#if 0
if (argc <= 3) assert(false);
const string low = argv[2];
const string high = argv[3];
for (int i = 0; i < 700; ++i) {
for (int n = lexical_cast<int>(low); n <= lexical_cast<int>(high); ++n) test(n, i*0.1+1.0e-10);
}
#else
test(6,1.10033333333333);
test(6,1.11133333333333);
test(6,1.12233333333333);
test(6,1.13233333333333);
test(6,1.14333333333333);
test(6,1.14333333333333e1);
test(6,0.645e2);
test(6,0.675e2);
test(6,0.805e2);
test(6,0.912e2);
test(6,1.14333333333333e2);
test(6,1.285e2);
test(6,128.000000000000);
test(6,1.31e2);
test(6,1.38e2);
test(6,2.43e2);
test(6,256.000000000000);
test(6,1.14333333333333e3);
test(6,8e3);
test(6,8192.000000000000);
test(6,1.14333333333333e4);
test(6,1.14333333333333e5);
test(6,1.14333333333333e6);
#endif
return 0;
}
}
vector<double> nbox_(52);
for (int nroot=1; nroot!=52; ++nroot) {
nbox_[nroot] = NBOX;
}
for (int nroot=1; nroot!=52; ++nroot) { // this is the outer most loop.
if (argc > 2) {
const string toggle = argv[1];
if (toggle == "-r") {
const string target = argv[2];
if (nroot != lexical_cast<int>(target)) continue;
}
}
vector<double> aroot;
vector<double> aweight;
#ifndef DAWSON
#ifndef SPIN2
#ifndef BREIT
// first obtain asymptotics
const int n=nroot*2;
double a[10000] = {0.0};
double b[100];
double c[500];
for (int i=0; i!= n; ++i) {
a[i+i*n] = 0.0;
if (i > 0) {
const double ia = static_cast<double>(i);
a[(i-1)+i*n] = std::sqrt(ia*0.5);
a[i+(i-1)*n] = std::sqrt(ia*0.5);
}
}
int nn = n*5;
int info = 0;
dsyev_("v", "U", &n, a, &n, b, c, &nn, &info);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(b[nroot+j]*b[nroot+j]);
aweight.push_back(a[(nroot+j)*(nroot*2)]*a[(nroot+j)*(nroot*2)]*(sqrt(pi)).toDouble());
}
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*sqrt(t) - dw[j+nroot]*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*sqrt(t)).toDouble());
}
#endif
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*t*sqrt(t) - dw[j+nroot]*s*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*t*sqrt(t)).toDouble());
}
#endif
#else
mpreal infty;
if (T_INFTY < MAXT) {
assert (NBOXL == 0);
const int nbox0 = static_cast<int>(log(MAXT)/log(2.0));
infty = pow(2, nbox0 + T_INFTY);
} else {
infty = static_cast<mpreal>(T_INFTY);
}
vector<mpreal> tt_infty(1); tt_infty[0] = infty;
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(((1.0 - dx_infty[j])*tt_infty[0]).toDouble());
aweight.push_back((dw_infty[j]*tt_infty[0]).toDouble());
}
#endif
const int ndeg = NGRID;
const int nbox = nbox_[nroot];
#ifndef DAWSON
const int jend = nbox;
#else
int jend;
if (MAXT < T_INFTY) {
jend = NBOX + NBOXL + 1;
} else {
jend = NBOX + T_INFTY;
}
#endif
const double stride = static_cast<double>(MAXT)/nbox;
const mpreal mstride = static_cast<mpreal>(MAXT)/nbox;
ofstream ofs;
#ifndef SPIN2
#ifndef BREIT
#ifndef DAWSON
const string func = "eriroot";
#else
const string func = "r2root";
#endif
#else
const string func = "breitroot";
#endif
#else
const string func = "spin2root";
#endif
string filename = "_" + func + "_" + lexical_cast<string>(nroot) + ".cc";
ofs.open(filename.c_str());
ofs << "\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: " + filename + "\n\
// Maintainer: Shiozaki group\n\
// This file is part of the BAGEL package.\n\
// This program is free software: you can redistribute it and/or modify\n\
// (at your option) any later version.\n\
// This program is distributed in the hope that it will be useful,\n\
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\
\n\
#include <algorithm> \n\
#include <cassert>" << endl;
#ifdef BREIT
ofs << "#include <src/integral/rys/breitrootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void BreitRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef DAWSON
ofs << "#include <src/integral/rys/r2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void R2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef SPIN2
ofs << "#include <src/integral/rys/spin2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void Spin2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
ofs << "#include <src/integral/rys/erirootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void ERIRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#endif
#endif
#endif
ofs << "\
constexpr double ax["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aroot[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
ofs << "\
constexpr double aw["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aweight[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
// now creates data
stringstream listx, listw;
string indent(" ");
int nblock = 0;
int index = 0;
double tiny = 1.0e-100;
int xcnt = 0;
int wcnt = 0;
#ifdef DAWSON
const int ibox0 = static_cast<int>(log(MAXT)/log(2.0));
#endif
for (int j=0; j != jend; ++j) {
#ifndef DAWSON
vector<vector<double>> c_all = get_C(j*mstride, mstride, nroot, false);
#else
vector<vector<double>> c_all;
if (j < NBOX) {
c_all = get_C(j*mstride, mstride, nroot, false);
} else {
if (MAXT < T_INFTY) {
if (j >= NBOX && j < jend-1) { // NBOXL between MAXT and T_ASYM
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal> (MAXT + ibox*(ibox + 1.0)*(2.0*ibox + 1.0)/6.0);
const mpreal mstrideL = static_cast<mpreal> (ibox + 1.0)*(ibox + 1.0);
c_all = get_C(mstart, mstrideL, nroot, false);
} else {
const mpreal mstart = static_cast<mpreal> (T_ASYM);
const mpreal mstrideL = static_cast<mpreal> (infty - T_ASYM);
c_all = get_C(mstart, mstrideL, nroot, true);
}
} else {
assert(NBOXL == 0);
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
const mpreal mstrideL = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
c_all = get_C(mstart, mstrideL, nroot, true);
}
}
#endif
for (int i = 0; i != nroot; ++i, ++index) {
const int ii = 2 * i;
const vector<double> x = c_all[ii];
const vector<double> w = c_all[ii + 1];
for (auto iter = x.begin(); iter != x.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != x.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = w.begin(); iter != w.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != w.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#ifdef DAWSON
if (MAXT >= T_INFTY) {
for (int ibox = 0; ibox != T_INFTY; ++ibox) {
vector<mpreal> tt_infty(1); tt_infty[0] = static_cast<mpreal>(pow(2.0, ibox + ibox0 + 1));
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (auto iter = dx_infty.begin(); iter != dx_infty.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dx_infty.end() || ibox + 1 != T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = dw_infty.begin(); iter != dw_infty.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dw_infty.end() || ibox + 1 != T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#endif
#ifndef SPIN2
#ifndef BREIT
string tafactor = "t";
#else
string tafactor = "t*t*t";
#endif
#else
string tafactor = "t*t*t*t*t";
#endif
int nbox2 = 0;
#ifndef DAWSON
const int nbox1 = nbox;
#else
int nbox1;
if (MAXT < T_INFTY) {
nbox1 = nbox + NBOXL + 1;
} else {
nbox1 = nbox + T_INFTY;
nbox2 = T_INFTY;
}
#endif
ofs << "\
constexpr double x[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listx.str() << "\
};" << endl;
ofs << "\
constexpr double w[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listw.str() << "\
};" << endl;
ofs << "\
int offset = -" << nroot << ";\n";
#ifdef DAWSON
ofs << "\
const int ibox0 = static_cast<int>(log(" << MAXT << ".0) / log(2.0)); \n";
#endif
ofs << "\
for (int i = 1; i <= n; ++i) {\n\
double t = ta[i-1];\n\
offset += " << nroot << ";\n\
if (std::isnan(t)) {\n\
fill_n(rr+offset, " << nroot << ", 0.5);\n\
fill_n(ww+offset, " << nroot << ", 0.0);\n";
#ifndef DAWSON
ofs << "\
} else if (t >= " << MAXT << ".0) {\n\
t = 1.0/sqrt(t);\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
rr[offset+r] = ax[r]*t*t;\n\
ww[offset+r] = aw[r]*" + tafactor + ";\n\
}\n\
} else {\n\
assert(t >= 0);\n\
int it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t-it*" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
\n";
#else
ofs << "\
} else if (t >= " << infty << ".0) {\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
ww[offset+r] = aw[" << nroot << "-r-1] / t;\n\
rr[offset+r] = 1.0 - ax[" << nroot << "-r-1] / t;\n\
}\n\
} else {\n\
assert(t >= 0);\n";
if (MAXT < T_INFTY) {
ofs << "\
vector<double> rr_infty(" << nroot << "); \n\
vector<double> ww_infty(" << nroot << "); \n";
for (int j = 0; j != nroot; ++j) {
ofs << "\
ww_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dw_infty[j] << "; \n\
rr_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dx_infty[j] << "; \n";
}
}
ofs << "\
int it; \n\
double bigT = 0.0; \n";
if (NBOXL != 0) {
ofs << "\
if (" << MAXT << ".0 <= t && t < " << T_ASYM << ".0) { \n\
int ka = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(0.25, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
int kb = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(6.0, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
assert(kb + 1 == ka || kb == ka); \n\
it = " << NBOX << " + ka; \n\
double a = " << MAXT << ".0 + ka * (ka + 1) * (2*ka + 1)/6.0; \n\
double b = " << MAXT << ".0 + (ka + 1) * (ka + 2) * (2*ka + 3)/6.0; \n\
t = (t - (a+b)/2) * 2/(a-b);\n\
} else if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
} else {
ofs << "\
if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
}
ofs << "\
bigT = t; \n";
if (MAXT < T_INFTY) {
ofs << "\
it = static_cast<int>(" << NBOX + NBOXL << ");\n\
t = (t - (" << T_ASYM << ".0 + " << infty << ".0)/2) * 2/(" << infty << ".0 - " << T_ASYM << ".0);\n";
} else {
ofs << "\
it = static_cast<int>(log(bigT) / log(2.0) + " << NBOX << " - ibox0);\n\
t = (t - 1.5 * pow(2.0, it + ibox0 - " << NBOX << "))* 2/pow(2.0, it + ibox0 - " << NBOX << ");\n\
cout << \" new t = \" << t << endl; \n";
}
ofs << "\
} else { \n\
it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t - it *" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
} \n";
#endif
ofs << "\
const double t2 = t * 2.0;\n\
for (int j=1; j <=" << nroot << "; ++j) {\n\
const int boxof = it*" << ndeg*nroot << "+" << ndeg << "*(j-1);\n";
assert((ndeg/2)*2 == ndeg);
for (int i=ndeg; i!=0; --i) {
if (i==ndeg) {
ofs << "\
double d = x[boxof+" << i-1 << "];\n\
double e = w[boxof+" << i-1 << "];\n";
} else if (i==ndeg-1) {
ofs << "\
double f = t2*d + x[boxof+" << i-1 << "];\n\
double g = t2*e + w[boxof+" << i-1 << "];\n";
} else if (i != 1 && ((i/2)*2 == i)) { // odd
ofs << "\
d = t2*f - d + x[boxof+" << i-1 << "];\n\
e = t2*g - e + w[boxof+" << i-1 << "];\n";
} else if (i != 1) { // even
ofs << "\
f = t2*d - f + x[boxof+" << i-1 << "];\n\
g = t2*e - g + w[boxof+" << i-1 << "];\n";
} else {
ofs << "\
rr[offset+j-1] = t*d - f + x[boxof+" << i-1 << "]*0.5;\n\
ww[offset+j-1] = t*e - g + w[boxof+" << i-1 << "]*0.5;\n";
#ifdef DAWSON
if (MAXT < T_INFTY) {
ofs << "\
if (" << T_ASYM << ".0 <= bigT && bigT < " << infty << ".0) { \n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty[" << nroot << "-j] * " << infty << ".0 / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty[" << nroot << "-j]) * " << infty << ".0 /bigT; \n\
}\n";
} else {
ofs << "\
if (" << MAXT << ".0 <= bigT && bigT < " << infty << ".0) {\n\
const int iref = " << (NBOX + T_INFTY) * nroot * NGRID << " + (it - " << NBOX << ") * " << nroot << " + " << nroot << " - j;\n\
double rr_infty = x[iref];\n\
double ww_infty = w[iref];\n\
double Tref = pow(2.0, it + ibox0 + 1 - " << NBOX << ");\n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty * Tref / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty) * Tref /bigT;\n\
}\n";
}
#endif
}
}
ofs << "\
}\n\
}\n\
}\n\
}";
ofs.close();
}
return 0;
}
|
\file container.h
\brief simple array in STL style, level-based array
\author LNM RWTH Aachen: Joerg Grande, Volker Reichelt; SC RWTH Aachen: Oliver Fortmeier
#ifndef DROPS_CONTAINER_H
#define DROPS_CONTAINER_H
#include <vector>
#include <list>
#include <cmath>
#include <iostream>
#include <valarray>
#include "misc/utils.h"
namespace DROPS
{
/*uninitialized memory; mainly for faster SVectorCL-math*/
/** Put the values of a_, d_ and beta_ in buffer. Note that buffer must be of size
(Rows_+2)*Cols_
*/
template <Uint Rows_, Uint Cols_>
void QRDecompCL<Rows_, Cols_>::Serialize(double* buffer) const
{
std::copy( a_.begin(), a_.end(), buffer);
std::copy( d_, d_+Cols_, buffer+a_.size());
std::copy( beta_, beta_+Cols_, buffer+a_.size()+Cols_);
}
template <Uint Rows_, Uint Cols_>
void QRDecompCL<Rows_, Cols_>::Deserialize( const double* buffer)
{
std::copy( buffer, buffer+a_.size(), a_.begin());
std::copy( buffer+a_.size(), buffer+a_.size()+Cols_, d_);
std::copy(buffer+a_.size()+Cols_, buffer+a_.size()+Cols_+Cols_, beta_);
}
|
<!DOCTYPE HTML PUBLIC "-
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>The transformDistance purpose</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="cairomatrix.scale.html">CairoMatrix::scale</a></div>
<div class="next" style="text-align: right; float: right;"><a href="cairomatrix.transformpoint.html">CairoMatrix::transformPoint</a></div>
<div class="up"><a href="class.cairomatrix.html">CairoMatrix</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="cairomatrix.transformdistance" class="refentry">
<div class="refnamediv">
<h1 class="refname">CairoMatrix::transformDistance</h1>
<p class="verinfo">(PECL cairo >= 0.1.0)</p><p class="refpurpose"><span class="refname">CairoMatrix::transformDistance</span> — <span class="dc-title">The transformDistance purpose</span></p>
</div>
<div class="refsect1 description" id="<API key>.<API key>">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="modifier">public</span> <span class="type">array</span> <span class="methodname"><strong>CairoMatrix::transformDistance</strong></span>
( <span class="methodparam"><span class="type">string</span> <code class="parameter">$dx</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$dy</code></span>
)</div>
<p class="para rdfs-comment">
The method description goes here.
</p>
<div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is
currently not documented; only its argument list is available.
</p></div>
</div>
<div class="refsect1 parameters" id="<API key>.<API key>">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<code class="parameter">dx</code></dt>
<dd>
<p class="para">
Description...
</p>
</dd>
<dt>
<code class="parameter">dy</code></dt>
<dd>
<p class="para">
Description...
</p>
</dd>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="<API key>.<API key>">
<h3 class="title">Return Values</h3>
<p class="para">
Description...
</p>
</div>
<div class="refsect1 examples" id="<API key>.<API key>">
<h3 class="title">Examples</h3>
<p class="para">
<div class="example" id="example-3249">
<p><strong>Example #1 <span class="methodname"><strong>CairoMatrix::transformDistance()</strong></span> example</strong></p>
<div class="example-contents">
<div class="phpcode"><code><span style="color: #000000">
<span style="color: #0000BB"><?php<br /></span><span style="color: #FF8000">/* ... */<br /></span><span style="color: #0000BB">?></span>
</span>
</code></div>
</div>
<div class="example-contents"><p>The above example will output
something similar to:</p></div>
<div class="example-contents screen">
<div class="cdata"><pre>
</pre></div>
</div>
</div>
</p>
</div>
<div class="refsect1 seealso" id="<API key>.<API key>">
<h3 class="title">See Also</h3>
<p class="para">
<ul class="simplelist">
<li class="member"><span class="methodname"><strong>Classname::Method()</strong></span></li>
</ul>
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="cairomatrix.scale.html">CairoMatrix::scale</a></div>
<div class="next" style="text-align: right; float: right;"><a href="cairomatrix.transformpoint.html">CairoMatrix::transformPoint</a></div>
<div class="up"><a href="class.cairomatrix.html">CairoMatrix</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Configuration;
using System.Security.Cryptography;
using System.Xml;
using Nesoft.Utility.DataAccess.Database.Config;
using Nesoft.Utility.DataAccess.Database;
using System.Data;
namespace Nesoft.Utility.DataAccess.RealTime
{
internal static class ConfigHelper
{
private static XmlNode[] GetChildrenNodes(XmlNode node, string nodeName)
{
return GetChildrenNodes(node, delegate(XmlNode child)
{
return child.Name == nodeName;
});
}
private static XmlNode[] GetChildrenNodes(XmlNode node, Predicate<XmlNode> match)
{
if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
{
return new XmlNode[0];
}
List<XmlNode> nodeList = new List<XmlNode>(node.ChildNodes.Count);
foreach (XmlNode child in node.ChildNodes)
{
if (match(child))
{
nodeList.Add(child);
}
}
return nodeList.ToArray();
}
private static string GetNodeAttribute(XmlNode node, string attributeName)
{
if (node.Attributes == null
|| node.Attributes[attributeName] == null
|| node.Attributes[attributeName].Value == null
|| node.Attributes[attributeName].Value.Trim() == string.Empty)
{
return string.Empty;
}
return node.Attributes[attributeName].Value.Trim();
}
private static string GetConfigPath()
{
string path = <API key>.AppSettings["<API key>"];
if (path == null || path.Trim().Length <= 0)
{
return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Configuration/RealTime.config");
}
string p = Path.GetPathRoot(path);
if (p == null || p.Trim().Length <= 0)
{
path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, path);
}
return path;
}
//internal static List<<API key>> GetExtensionConfig()
// List<<API key>> list = new List<<API key>>();
// string path = GetConfigPath();
// if (!File.Exists(path))
// return list;
// XmlDocument x = new XmlDocument();
// x.Load(path);
// XmlNode node = x.SelectSingleNode(@"//extensions");
// if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
// return list;
// XmlNode[] eventList = GetChildrenNodes(node, "data");
// foreach (XmlNode ev in eventList)
// string name = GetNodeAttribute(ev, "name");
// string dataType = GetNodeAttribute(ev, "type");
// string extensionType = GetNodeAttribute(ev, "extensionType");
// <API key> config = new <API key>();
// config.Name = name;
// config.DataType = dataType;
// config.ExtensionType = extensionType;
// list.Add(config);
// return list;
//internal static <API key> GetExtensionConfig(string dataName)
// var list = GetExtensionConfig();
// if (list != null)
// return list.FirstOrDefault(p => p.Name.Trim().ToUpper() == dataName.Trim().ToUpper());
// return null;
internal static List<RealTimeMethod> GetRealTimeConfig()
{
List<RealTimeMethod> list = new List<RealTimeMethod>();
string path = GetConfigPath();
if (!File.Exists(path))
{
return list;
}
XmlDocument x = new XmlDocument();
x.Load(path);
XmlNode node = x.SelectSingleNode(@"//realTime");
if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
{
return list;
}
XmlNode[] eventList = GetChildrenNodes(node, "query");
foreach (XmlNode ev in eventList)
{
string dataType = GetNodeAttribute(ev, "dataType");
string queryName = GetNodeAttribute(ev, "name");
//string tableName = GetNodeAttribute(ev, "tableName");
//string primaryField = GetNodeAttribute(ev, "primaryField");
RealTimeMethod query = new RealTimeMethod
{
Name = queryName,
DataType = dataType,
//TableName = tableName,
//PrimaryField = primaryField,
FilterFields = new List<FilterField>(),
ReturnFields = new List<ReturnField>()
};
list.Add(query);
XmlNode filterFieldsNode = ev.SelectSingleNode("filterFields");
XmlNode[] filterFields = GetChildrenNodes(filterFieldsNode,"field");
foreach (XmlNode no in filterFields)
{
string name = GetNodeAttribute(no, "name");
string valuePath = GetNodeAttribute(no, "valuePath");
string relationType = GetNodeAttribute(no, "relationType");
string operatorType = GetNodeAttribute(no, "operatorType");
string dbType = GetNodeAttribute(no, "dbType");
FilterField filed = new FilterField
{
Name = name,
ValuePath = valuePath,
OperatorType = operatorType,
RelationType = relationType,
DBType = dbType
};
query.FilterFields.Add(filed);
}
XmlNode returnFieldsNode = ev.SelectSingleNode("returnFields");
XmlNode[] returnFields = GetChildrenNodes(returnFieldsNode, "field");
foreach (XmlNode no in returnFields)
{
string name = GetNodeAttribute(no, "name");
string valuePath = GetNodeAttribute(no, "valuePath");
string dbType = GetNodeAttribute(no, "dbType");
ReturnField filed = new ReturnField
{
Name = name,
ValuePath = valuePath,
DBType = dbType
};
query.ReturnFields.Add(filed);
}
}
return list;
}
internal static RealTimeMethod GetRealTimeConfig(string name)
{
var list = GetRealTimeConfig();
if (list != null)
{
return list.FirstOrDefault(p => p.Name.Trim().ToUpper() == name.Trim().ToUpper());
}
return null;
}
internal static IRealTimePersister GetDefaultPersiter()
{
return PersisteFactory.GetInstance();
}
}
public static class RealTimeHelper
{
private static string loadDataSql = @"
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#";
private static string loadPagingDataSql = @"
SELECT @TotalCount = COUNT(1)
FROM (
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#
) result
SELECT
#Columns#
FROM(
SELECT TOP (@EndNumber)
ROW_NUMBER() OVER(ORDER BY #SortColumnName#) AS RowNumber,
#Columns#
FROM
(
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#
) unionResult ) result
WHERE RowNumber > @StartNumber
";
// private static string excludeDataSql = @"NOT EXISTS(
// SELECT TOP 1 1
// FROM #TableName# t WITH(NOLOCK)
// WHERE r.Key = t.#PrimaryKey#)";
<summary>
</summary>
<param name="pro"></param>
<param name="property"></param>
<param name="<API key>"></param>
<param name="<API key>"></param>
<returns></returns>
//private static Type GetPropertyType(object pro, string property, bool <API key>, bool <API key>)
// Type type = null;
// string[] pNames = property.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
// //object val = DataMapper.ConvertIfEnum(reader[i], typeof(T), pNames, <API key>, <API key>);
// int index = 0;
// foreach (string propertyName in pNames)
// if (!Invoker.ExistPropertySet(pro.GetType(), propertyName, <API key>))
// if (!<API key>)
// throw new <API key>("There is no public instance property that can be set '" + propertyName + "' in type '" + pro.GetType().FullName + "'");
// break;
// // propertypro
// string realName = Invoker.<API key>(pro.GetType(), propertyName);
// if (realName == null || (realName != propertyName && !<API key>))
// // realName == null proproperty
// // realName != propertyName
// if (!<API key>)
// throw new <API key>("There is no public instance property that can be set '" + propertyName + "' in type '" + pro.GetType().FullName + "'");
// break;
// if (index == pNames.Length - 1)
// type = Invoker.GetPropertyType(pro.GetType(), realName);
// else
// object tmp = null;
// if (Invoker.ExistPropertyGet(pro.GetType(), realName))
// tmp = Invoker.PropertyGet(pro, realName);
// if (tmp == null)
// type = Invoker.GetPropertyType(pro.GetType(), realName, false, false);
// pro = tmp;
// index++;
// return type;
//private static string GetDBTypeStr(Type type)
// if (type.IsGenericType && type.<API key>() == typeof(Nullable<>))
// type = type.GetGenericArguments()[0];
// TypeCode code = Type.GetTypeCode(type);
// switch (code)
// case TypeCode.Boolean:
// return "bit";
// case TypeCode.Int16:
// return "smallint";
// case TypeCode.Int32:
// return "int";
// case TypeCode.Int64:
// return "bigint";
// case TypeCode.String:
// case TypeCode.Char:
// return "nvarchar(max)";
// case TypeCode.Decimal:
// return "decimal(19,6)";
// case TypeCode.Double:
// return "double(19,6)";
// case TypeCode.DateTime:
// return "datetime";
// default:
// return "nvarchar(max)";
//private static System.Data.DbType GetDbType(Type type)
// if (type.IsGenericType && type.<API key>() == typeof(Nullable<>))
// type = type.GetGenericArguments()[0];
// TypeCode code = Type.GetTypeCode(type);
// switch (code)
// case TypeCode.Boolean:
// return DbType.Boolean;
// case TypeCode.Int16:
// return DbType.Int16;
// case TypeCode.Int32:
// return DbType.Int32;
// case TypeCode.Int64:
// return DbType.Int64;
// case TypeCode.String:
// return DbType.String;
// case TypeCode.Char:
// return DbType.<API key>;
// case TypeCode.Decimal:
// return DbType.Decimal;
// case TypeCode.Double:
// return DbType.Double;
// case TypeCode.DateTime:
// return DbType.DateTime;
// default:
// return DbType.String;
<summary>
SqlDbType
</summary>
<param name="sqlTypeString"></param>
<returns></returns>
private static DbType GetDbType(string sqlTypeString)
{
sqlTypeString = sqlTypeString.Trim();
if (sqlTypeString.Contains("("))
{
sqlTypeString = sqlTypeString.Substring(0, sqlTypeString.IndexOf("("));
}
switch (sqlTypeString)
{
case "bigint":
return DbType.Int64;
case "binary":
return DbType.Binary;
case "bit":
return DbType.Boolean;
case "char":
return DbType.<API key>;
case "date":
return DbType.Date;
case "datetime":
return DbType.DateTime;
case "datetime2":
return DbType.DateTime2;
case "datetimeoffset":
return DbType.DateTimeOffset;
case "decimal":
return DbType.Decimal;
case "filestream":
return DbType.Binary;
case "float":
return DbType.Double;
case "image":
return DbType.Binary;
case "int":
return DbType.Int32;
case "money":
return DbType.Decimal;
case "nchar":
return DbType.StringFixedLength;
case "ntext":
return DbType.String;
case "numeric":
return DbType.Decimal;
case "nvarchar":
return DbType.String;
case "real":
return DbType.Single;
case "rowversion":
return DbType.Binary;
case "smalldatetime":
return DbType.DateTime;
case "smallint":
return DbType.Int16;
case "smallmoney":
return DbType.Decimal;
case "sql_variant":
return DbType.Object;
case "text":
return DbType.String;
case "time":
return DbType.Time;
case "timestamp":
return DbType.Binary;
case "tinyint":
return DbType.Byte;
case "uniqueidentifier":
return DbType.Guid;
case "varbinary":
return DbType.Binary;
case "varchar":
return DbType.AnsiString;
case "xml":
return DbType.Xml;
default:
throw new ArgumentException("Invalid sql dbtype.");
}
}
private static T GetEnum<T>(string name) where T : struct
{
T result = default(T);
bool flag = Enum.TryParse<T>(name, out result);
if (flag)
{
return result;
}
throw new ArgumentException("Invalid value of enum {0}", typeof(T).Name);
}
private static void BuilCondition<Q>(Q filter, string dataType, List<FilterField> filterFields, <API key> sqlBuilder)
{
sqlBuilder.<API key>.AddCondition(<API key>.AND, "r.BusinessDataType", DbType.String, "@BusinessDataType", <API key>.Equal, dataType);
List<string> changeTypes = new List<string>() { "A", "U" };
sqlBuilder.<API key>.AddInCondition(<API key>.AND, "r.ChangeType", DbType.String, changeTypes);
int index = 0;
filterFields.ForEach(p =>
{
object parameterValue = Invoker.PropertyGet(filter, p.Name);
string[] pNames = p.ValuePath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string path = string.Format("(//{0}/text())[1]", pNames.Join("/"));
DbType dbType = GetDbType(p.DBType);
string field = string.Format("r.BusinessData.value('{0}','{1}')", path, p.DBType);
<API key> operatorType = GetEnum<<API key>>(p.OperatorType);
<API key> relationType = GetEnum<<API key>>(p.RelationType);
sqlBuilder.<API key>.AddCondition(relationType,
field, dbType, "@Parameter" + index.ToString(), operatorType, parameterValue);
index++;
});
}
private static void BuildColumns(List<ReturnField> returnFields, out string xmlFields, out List<string> columns)
{
StringBuilder fields = new StringBuilder();
var cols = new List<string>();
returnFields.ForEach(p =>
{
cols.Add(string.Format("[{0}]", p.Name));
string[] pNames = p.ValuePath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string path = string.Format("(//{0}/text())[1]", pNames.Join("/"));
fields.AppendFormat("r.BusinessData.value('{0}','{1}') AS [{2}],", path, p.DBType, p.Name);
});
fields.Remove(fields.Length - 1, 1);
xmlFields = fields.ToString();
columns = cols;
}
public static void Persiste<T>(RealTimeData<T> data) where T : class
{
ConfigHelper.GetDefaultPersiter().Persiste<T>(data);
}
public static object LoadData(int key)
{
return null;
}
public static T LoadData<T>(int key) where T : class, new()
{
//RealTime
return default(T);
}
<summary>
</summary>
<typeparam name="Q"></typeparam>
<typeparam name="T"></typeparam>
<param name="command"></param>
<param name="filter"></param>
<returns></returns>
public static List<T> QueryData<Q, T>(CustomDataCommand command, Q filter, string configName) where T : class, new()
{
var config = ConfigHelper.GetRealTimeConfig(configName);
string xmlFields;
List<string> columns;
BuildColumns(config.ReturnFields, out xmlFields, out columns);
var cmd = DataCommandManager.<API key>(loadDataSql, command.DatabaseAliasName);
using (<API key> sqlBuilder = new <API key>(cmd, "SysNo desc"))
{
BuilCondition<Q>(filter, config.DataType, config.FilterFields, sqlBuilder);
cmd.CommandText = sqlBuilder.BuildQuerySql();
cmd.CommandText = cmd.CommandText.Replace("#XmlFields#", xmlFields.ToString());
cmd.CommandText = cmd.CommandText.Replace("#InputSql#", command.CommandText);
var list = cmd.ExecuteEntityList<T>();
return list;
}
}
<summary>
</summary>
<typeparam name="Q"></typeparam>
<typeparam name="T"></typeparam>
<param name="command"></param>
<param name="filter"></param>
<param name="needRealTime"></param>
<param name="pageIndex"></param>
<param name="pageSize"></param>
<param name="sortField"></param>
<param name="totalCount"></param>
<returns></returns>
public static List<T> QueryData<Q, T>(CustomDataCommand command, Q filter, string configName,
PagingInfoEntity pagingInfo, out int totalCount) where T : class, new()
{
pagingInfo.SortField = "[SOMaster.SOSysNo]";
if (string.IsNullOrEmpty(pagingInfo.SortField))
{
throw new <API key>("You must specified one sort field at least.");
}
var config = ConfigHelper.GetRealTimeConfig(configName);
string xmlFields;
List<string> columns;
BuildColumns(config.ReturnFields, out xmlFields, out columns);
var cmd = DataCommandManager.<API key>(loadPagingDataSql, command.DatabaseAliasName);
using (<API key> sqlBuilder = new <API key>(cmd, pagingInfo, pagingInfo.SortField))
{
BuilCondition<Q>(filter, config.DataType, config.FilterFields, sqlBuilder);
cmd.CommandText = sqlBuilder.BuildQuerySql();
//DataCommand
//command.DbParameterList.ForEach(p =>
// var param = cmd.DbParameterList.FirstOrDefault(k => k.ParameterName.Trim().ToUpper() == p.ParameterName.Trim().ToUpper());
// if (param == null)
// cmd.AddInputParameter(p.ParameterName, p.DbType, p.Value);
cmd.CommandText = cmd.CommandText.Replace("#Columns#", columns.Join(","));
cmd.CommandText = cmd.CommandText.Replace("#XmlFields#", xmlFields.ToString());
cmd.CommandText = cmd.CommandText.Replace("#InputSql#", command.CommandText);
var list = cmd.ExecuteEntityList<T>();
totalCount = Convert.ToInt32(cmd.GetParameterValue("@TotalCount"));
return list;
}
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList | </title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css">
</head>
<body id="class">
<div class="header">
<ul>
<li><a href="../../../../../classes.html">Classes</a></li>
<li><a href="../../../../../namespaces.html">Namespaces</a></li>
<li><a href="../../../../../interfaces.html">Interfaces</a></li>
<li><a href="../../../../../traits.html">Traits</a></li>
<li><a href="../../../../../doc-index.html">Index</a></li>
</ul>
<div id="title"></div>
<div class="type">Class</div>
<h1><a href="../ChoiceList.html">Symfony\Bridge\Doctrine\Form\ChoiceList</a>\EntityChoiceList</h1>
</div>
<div class="content">
<p> class
<strong>EntityChoiceList</strong> extends <a href="../../../../Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.html"><abbr title="Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList">ObjectChoiceList</abbr></a></p>
<div class="description">
<p>A choice list presenting a list of Doctrine entities as choices</p>
<p>
</p>
</div>
<h2>Methods</h2>
<table>
<tr>
<td class="type">
</td>
<td class="last">
<a href="EntityChoiceList.html
<p>Creates a new entity choice list.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getChoices">getChoices</a>()
<p>Returns the list of entities</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getValues">getValues</a>()
<p>Returns the values for the entities</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#<API key>">getPreferredViews</a>()
<p>Returns the choice views of the preferred choices as nested array with the choice groups as top-level keys.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#<API key>">getRemainingViews</a>()
<p>Returns the choice views of the choices that are not preferred as nested array with the choice groups as top-level keys.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#<API key>">getChoicesForValues</a>(array $values)
<p>Returns the entities corresponding to the given values.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#<API key>">getValuesForChoices</a>(array $entities)
<p>Returns the values corresponding to the given entities.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#<API key>"><API key></a>(array $entities)
<p>Returns the indices corresponding to the given entities.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#<API key>">getIndicesForValues</a>(array $values)
<p>Returns the entities corresponding to the given values.</p>
</td>
<td></td>
</tr>
</table>
<h2>Details</h2>
<h3 id="method___construct">
<div class="location">at line 101</div>
<code> public
<strong>__construct</strong>(<abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr> $manager, string $class, string $labelPath = null, <a href="<API key>.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\<API key>"><API key></abbr></a> $entityLoader = null, array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null $entities = null, array $preferredEntities = array(), string $groupPath = null, <a href="../../../../Component/PropertyAccess/<API key>.html"><abbr title="Symfony\Component\PropertyAccess\<API key>"><API key></abbr></a> $propertyAccessor = null)</code>
</h3>
<div class="details">
<p>Creates a new entity choice list.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr></td>
<td>$manager</td>
<td>An EntityManager instance</td>
</tr>
<tr>
<td>string</td>
<td>$class</td>
<td>The class name</td>
</tr>
<tr>
<td>string</td>
<td>$labelPath</td>
<td>The property path used for the label</td>
</tr>
<tr>
<td><a href="<API key>.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\<API key>"><API key></abbr></a></td>
<td>$entityLoader</td>
<td>An optional query builder</td>
</tr>
<tr>
<td>array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null</td>
<td>$entities</td>
<td>An array of choices or null to lazy load</td>
</tr>
<tr>
<td>array</td>
<td>$preferredEntities</td>
<td>An array of preferred choices</td>
</tr>
<tr>
<td>string</td>
<td>$groupPath</td>
<td>A property path pointing to the property used to group the choices. Only allowed if the choices are given as flat array.</td>
</tr>
<tr>
<td><a href="../../../../Component/PropertyAccess/<API key>.html"><abbr title="Symfony\Component\PropertyAccess\<API key>"><API key></abbr></a></td>
<td>$propertyAccessor</td>
<td>The reflection graph for reading property paths.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getChoices">
<div class="location">at line 137</div>
<code> public array
<strong>getChoices</strong>()</code>
</h3>
<div class="details">
<p>Returns the list of entities</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>The choices with their indices as keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getValues">
<div class="location">at line 153</div>
<code> public array
<strong>getValues</strong>()</code>
</h3>
<div class="details">
<p>Returns the values for the entities</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>The values with the corresponding choice indices as keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="<API key>">
<div class="location">at line 170</div>
<code> public array
<strong>getPreferredViews</strong>()</code>
</h3>
<div class="details">
<p>Returns the choice views of the preferred choices as nested array with the choice groups as top-level keys.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A nested array containing the views with the corresponding choice indices as keys on the lowest levels and the choice group names in the keys of the higher levels</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="<API key>">
<div class="location">at line 187</div>
<code> public array
<strong>getRemainingViews</strong>()</code>
</h3>
<div class="details">
<p>Returns the choice views of the choices that are not preferred as nested array with the choice groups as top-level keys.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A nested array containing the views with the corresponding choice indices as keys on the lowest levels and the choice group names in the keys of the higher levels</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="<API key>">
<div class="location">at line 205</div>
<code> public array
<strong>getChoicesForValues</strong>(array $values)</code>
</h3>
<div class="details">
<p>Returns the entities corresponding to the given values.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$values</td>
<td>An array of choice values. Not existing values in this array are ignored</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of choices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="<API key>">
<div class="location">at line 258</div>
<code> public array
<strong>getValuesForChoices</strong>(array $entities)</code>
</h3>
<div class="details">
<p>Returns the values corresponding to the given entities.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$entities</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of choice values with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="<API key>">
<div class="location">at line 300</div>
<code> public array
<strong><API key></strong>(array $entities)</code>
</h3>
<div class="details">
<p>Returns the indices corresponding to the given entities.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$entities</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of indices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="<API key>">
<div class="location">at line 342</div>
<code> public array
<strong>getIndicesForValues</strong>(array $values)</code>
</h3>
<div class="details">
<p>Returns the entities corresponding to the given values.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$values</td>
<td>An array of choice values. Not existing values in this array are ignored</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of indices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>.
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-89393-6']);
_gaq.push(['_setDomainName', '.symfony.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https:
var s = document.<API key>('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--Converted with LaTeX2HTML 2008 (1.71)
original version by: Nikos Drakos, CBLU, University of Leeds
* revised and updated by: Marcus Hennecke, Ross Moore, Herb Swan
* with significant contributions from:
Jens Lippmann, Marek Rouchal, Martin Wilck and others
<HTML>
<HEAD>
<TITLE>Conclusion</TITLE>
<META NAME="description" CONTENT="Conclusion">
<META NAME="keywords" CONTENT="document">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<META NAME="Generator" CONTENT="LaTeX2HTML v2008">
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
<LINK REL="STYLESHEET" HREF="document.css">
<LINK REL="previous" HREF="node12.html">
<LINK REL="up" HREF="node2.html">
<LINK REL="next" HREF="node14.html">
</HEAD>
<BODY >
<DIV CLASS="navigation"><!--Navigation Panel
<A NAME="tex2html168"
HREF="node14.html">
<IMG WIDTH="37" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="next"
SRC="/usr/share/latex2html/icons/next.png"></A>
<A NAME="tex2html166"
HREF="node2.html">
<IMG WIDTH="26" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="up"
SRC="/usr/share/latex2html/icons/up.png"></A>
<A NAME="tex2html162"
HREF="node12.html">
<IMG WIDTH="63" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="previous"
SRC="/usr/share/latex2html/icons/prev.png"></A>
<BR>
<B> Next:</B> <A NAME="tex2html169"
HREF="node14.html">ReqHunter</A>
<B> Up:</B> <A NAME="tex2html167"
HREF="node2.html">Review of the available</A>
<B> Previous:</B> <A NAME="tex2html163"
HREF="node12.html">REMA</A>
<BR>
<BR></DIV>
<!--End of Navigation Panel
<H2><A NAME="<API key>">
Conclusion</A>
</H2>
<P>
<BR><HR>
<ADDRESS>
Nicolas James
2011-07-19
</ADDRESS>
</BODY>
</HTML>
|
package org.graylog2.plugin;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.graylog2.plugin.streams.Stream;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageTest {
private Message message;
private DateTime originalTimestamp;
@Before
public void setUp() {
originalTimestamp = Tools.iso8601();
message = new Message("foo", "bar", originalTimestamp);
}
@Test
public void <API key>() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("some-thing", "bar");
assertEquals("bar", m.getField("some-thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
@Test
public void <API key>() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", " bar ");
assertEquals("bar", m.getField("something"));
m.addField("something2", " bar");
assertEquals("bar", m.getField("something2"));
m.addField("something3", "bar ");
assertEquals("bar", m.getField("something3"));
}
@Test
public void <API key>() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", 3);
assertEquals(3, m.getField("something"));
}
@Test
public void testAddFields() throws Exception {
final Map<String, Object> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", 1);
message.addFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals(1, message.getField("field2"));
}
@Test
public void testAddStringFields() throws Exception {
final Map<String, String> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", "Bar");
message.addStringFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals("Bar", message.getField("field2"));
}
@Test
public void testAddLongFields() throws Exception {
final Map<String, Long> map = Maps.newHashMap();
map.put("field1", 10L);
map.put("field2", 230L);
message.addLongFields(map);
assertEquals(10L, message.getField("field1"));
assertEquals(230L, message.getField("field2"));
}
@Test
public void testAddDoubleFields() throws Exception {
final Map<String, Double> map = Maps.newHashMap();
map.put("field1", 10.0d);
map.put("field2", 230.2d);
message.addDoubleFields(map);
assertEquals(10.0d, message.getField("field1"));
assertEquals(230.2d, message.getField("field2"));
}
@Test
public void testRemoveField() throws Exception {
message.addField("foo", "bar");
message.removeField("foo");
assertNull(message.getField("foo"));
}
@Test
public void <API key>() throws Exception {
message.removeField("message");
message.removeField("source");
message.removeField("timestamp");
assertNotNull(message.getField("message"));
assertNotNull(message.getField("source"));
assertNotNull(message.getField("timestamp"));
}
@Test
public void testGetFieldAs() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields"));
}
@Test(expected = ClassCastException.class)
public void <API key>() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
message.getFieldAs(Map.class, "fields");
}
@Test
public void <API key>() throws Exception {
final Stream stream1 = mock(Stream.class);
final Stream stream2 = mock(Stream.class);
message.setStreams(Lists.newArrayList(stream1, stream2));
assertEquals(Lists.newArrayList(stream1, stream2), message.getStreams());
}
@Test
public void testGetStreamIds() throws Exception {
message.addField("streams", Lists.newArrayList("stream-id"));
assertEquals(Lists.newArrayList("stream-id"), message.getStreamIds());
}
@Test
public void <API key>() throws Exception {
assertFalse(message.getFilterOut());
message.setFilterOut(true);
assertTrue(message.getFilterOut());
message.setFilterOut(false);
assertFalse(message.getFilterOut());
}
@Test
public void testGetId() throws Exception {
final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
assertTrue(pattern.matcher(message.getId()).matches());
}
@Test
public void testGetTimestamp() {
try {
final DateTime timestamp = message.getTimestamp();
assertNotNull(timestamp);
assertEquals(originalTimestamp.getZone(), timestamp.getZone());
} catch (ClassCastException e) {
fail("timestamp wasn't a DateTime " + e.getMessage());
}
}
@Test
public void testTimestampAsDate() {
final DateTime dateTime = new DateTime(2015, 9, 8, 0, 0, DateTimeZone.UTC);
message.addField(Message.FIELD_TIMESTAMP,
dateTime.toDate());
final Map<String, Object> elasticSearchObject = message.<API key>();
final Object <API key> = elasticSearchObject.get(Message.FIELD_TIMESTAMP);
assertEquals("Setting message timestamp as java.util.Date results in correct format for elasticsearch",
Tools.<API key>(dateTime), <API key>);
}
@Test
public void testGetMessage() throws Exception {
assertEquals("foo", message.getMessage());
}
@Test
public void testGetSource() throws Exception {
assertEquals("bar", message.getSource());
}
@Test
public void testValidKeys() throws Exception {
assertTrue(Message.validKey("foo123"));
assertTrue(Message.validKey("foo-bar123"));
assertTrue(Message.validKey("foo_bar123"));
assertTrue(Message.validKey("foo.bar123"));
assertTrue(Message.validKey("123"));
assertTrue(Message.validKey(""));
assertFalse(Message.validKey("foo bar"));
assertFalse(Message.validKey("foo+bar"));
assertFalse(Message.validKey("foo$bar"));
assertFalse(Message.validKey(" "));
}
@Test
public void <API key>() throws Exception {
message.addField("field1", "wat");
message.addField("field2", "that");
final Map<String, Object> object = message.<API key>();
assertEquals("foo", object.get("message"));
assertEquals("bar", object.get("source"));
assertEquals("wat", object.get("field1"));
assertEquals("that", object.get("field2"));
assertEquals(Tools.<API key>((DateTime) message.getField("timestamp")), object.get("timestamp"));
assertEquals(Collections.EMPTY_LIST, object.get("streams"));
}
@Test
public void <API key>() throws Exception {
message.addField("timestamp", "time!");
final Map<String, Object> object = message.<API key>();
assertEquals("time!", object.get("timestamp"));
}
@Test
public void <API key>() throws Exception {
final Stream stream = mock(Stream.class);
when(stream.getId()).thenReturn("stream-id");
message.setStreams(Lists.newArrayList(stream));
final Map<String, Object> object = message.<API key>();
assertEquals(Lists.newArrayList("stream-id"), object.get("streams"));
}
@Test
public void testIsComplete() throws Exception {
Message message = new Message("message", "source", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", "", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", null, Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("", "source", Tools.iso8601());
assertFalse(message.isComplete());
message = new Message(null, "source", Tools.iso8601());
assertFalse(message.isComplete());
}
@Test
public void <API key>() throws Exception {
final Message message = new Message("", "source", Tools.iso8601());
assertEquals("message is empty, ", message.getValidationErrors());
}
@Test
public void <API key>() throws Exception {
final Message message = new Message(null, "source", Tools.iso8601());
assertEquals("message is missing, ", message.getValidationErrors());
}
@Test
public void testGetFields() throws Exception {
final Map<String, Object> fields = message.getFields();
assertEquals(message.getId(), fields.get("_id"));
assertEquals(message.getMessage(), fields.get("message"));
assertEquals(message.getSource(), fields.get("source"));
assertEquals(message.getField("timestamp"), fields.get("timestamp"));
}
@Test(expected = <API key>.class)
public void <API key>() throws Exception {
final Map<String, Object> fields = message.getFields();
fields.put("foo", "bar");
}
@Test
public void testGetFieldNames() throws Exception {
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty());
message.addField("testfield", "testvalue");
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message", "testfield")).isEmpty());
}
@Test(expected = <API key>.class)
public void <API key>() throws Exception {
final Set<String> fieldNames = message.getFieldNames();
fieldNames.remove("_id");
}
@Test
public void testHasField() throws Exception {
assertFalse(message.hasField("__foo__"));
message.addField("__foo__", "bar");
assertTrue(message.hasField("__foo__"));
}
}
|
var
assert = require('assert'),
path = require('path'),
exec = require('child_process').exec,
tmp = require('../lib/tmp');
// make sure that we do not test spam the global tmp
tmp.TMP_DIR = './tmp';
function _spawnTestWithError(testFile, params, cb) {
_spawnTest(true, testFile, params, cb);
}
function <API key>(testFile, params, cb) {
_spawnTest(false, testFile, params, cb);
}
function _spawnTest(passError, testFile, params, cb) {
var
node_path = process.argv[0],
command = [ node_path, path.join(__dirname, testFile) ].concat(params).join(' ');
exec(command, function _execDone(err, stdout, stderr) {
if (passError) {
if (err) {
return cb(err);
} else if (stderr.length > 0) {
return cb(stderr.toString());
}
}
return cb(null, stdout.toString());
});
}
function _testStat(stat, mode) {
assert.equal(stat.uid, process.getuid(), 'should have the same UID');
assert.equal(stat.gid, process.getgid(), 'should have the same GUID');
assert.equal(stat.mode, mode);
}
function _testPrefix(prefix) {
return function <API key>(err, name) {
assert.equal(path.basename(name).slice(0, prefix.length), prefix, 'should have the provided prefix');
};
}
function _testPrefixSync(prefix) {
return function <API key>(result) {
if (result instanceof Error) {
throw result;
}
_testPrefix(prefix)(null, result.name, result.fd);
};
}
function _testPostfix(postfix) {
return function <API key>(err, name) {
assert.equal(name.slice(name.length - postfix.length, name.length), postfix, 'should have the provided postfix');
};
}
function _testPostfixSync(postfix) {
return function <API key>(result) {
if (result instanceof Error) {
throw result;
}
_testPostfix(postfix)(null, result.name, result.fd);
};
}
function _testKeep(type, keep, cb) {
_spawnTestWithError('keep.js', [ type, keep ], cb);
}
function _testKeepSync(type, keep, cb) {
_spawnTestWithError('keep-sync.js', [ type, keep ], cb);
}
function _testGraceful(type, graceful, cb) {
<API key>('graceful.js', [ type, graceful ], cb);
}
function _testGracefulSync(type, graceful, cb) {
<API key>('graceful-sync.js', [ type, graceful ], cb);
}
function _assertName(err, name) {
assert.isString(name);
assert.isNotZero(name.length, 'an empty string is not a valid name');
}
function _assertNameSync(result) {
if (result instanceof Error) {
throw result;
}
var name = typeof(result) == 'string' ? result : result.name;
_assertName(null, name);
}
function _testName(expected){
return function _testNameGenerated(err, name) {
assert.equal(expected, name, 'should have the provided name');
};
}
function _testNameSync(expected){
return function <API key>(result) {
if (result instanceof Error) {
throw result;
}
_testName(expected)(null, result.name, result.fd);
};
}
function _testUnsafeCleanup(unsafe, cb) {
<API key>('unsafe.js', [ 'dir', unsafe ], cb);
}
function _testIssue62(cb) {
<API key>('issue62.js', [], cb);
}
function <API key>(unsafe, cb) {
<API key>('unsafe-sync.js', [ 'dir', unsafe ], cb);
}
function _testIssue62Sync(cb) {
<API key>('issue62-sync.js', [], cb);
}
module.exports.testStat = _testStat;
module.exports.testPrefix = _testPrefix;
module.exports.testPrefixSync = _testPrefixSync;
module.exports.testPostfix = _testPostfix;
module.exports.testPostfixSync = _testPostfixSync;
module.exports.testKeep = _testKeep;
module.exports.testKeepSync = _testKeepSync;
module.exports.testGraceful = _testGraceful;
module.exports.testGracefulSync = _testGracefulSync;
module.exports.assertName = _assertName;
module.exports.assertNameSync = _assertNameSync;
module.exports.testName = _testName;
module.exports.testNameSync = _testNameSync;
module.exports.testUnsafeCleanup = _testUnsafeCleanup;
module.exports.testIssue62 = _testIssue62;
module.exports.<API key> = <API key>;
module.exports.testIssue62Sync = _testIssue62Sync;
|
// This file is part of Gity.
// Gity is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Gity is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#import <Cocoa/Cocoa.h>
#import <GDKit/GDKit.h>
#import "GTBaseGitTask.h"
#import "GTGitCommitLoadInfo.h"
#import "GittyDocument.h"
#import "GTCallback.h"
#import "GTGitCommit.h"
@interface GTOpLoadHistory : GTBaseGitTask {
BOOL detatchedHead;
GTGitCommitLoadInfo * loadInfo;
//GTCallback * callback;
NSMutableArray * commits;
}
//- (id) initWithGD:(GittyDocument *) _gd andLoadInfo:(GTGitCommitLoadInfo *) _loadInfo andCallback:(GTCallback *) _callback;
- (id) initWithGD:(GittyDocument *) _gd andLoadInfo:(GTGitCommitLoadInfo *) _loadInfo;
//- (void) readSTDOUTC;
//- (void) readSTDOUTCPP;
@end
|
var searchData=
[
['gestionnaire_2ehpp',['Gestionnaire.hpp',['../Gestionnaire_8hpp.html',1,'']]],
['gestionnairemutex',['GestionnaireMutex',['../<API key>.html',1,'GestionnaireMutex'],['../<API key>.html#<API key>',1,'GestionnaireMutex::GestionnaireMutex()']]],
['<API key>',['GestionnaireMutex.cpp',['../<API key>.html',1,'']]],
['<API key>',['GestionnaireMutex.hpp',['../<API key>.html',1,'']]],
['gestionnairepartie',['GestionnairePartie',['../<API key>.html',1,'GestionnairePartie'],['../<API key>.html#<API key>',1,'GestionnairePartie::GestionnairePartie()']]],
['<API key>',['GestionnairePartie.cpp',['../<API key>.html',1,'']]],
['<API key>',['GestionnairePartie.hpp',['../<API key>.html',1,'']]],
['<API key>',['GestionnaireRequete.cpp',['../<API key>.html',1,'']]],
['<API key>',['GestionnaireRequete.hpp',['../<API key>.html',1,'']]],
['gestionnairesalon',['GestionnaireSalon',['../<API key>.html',1,'GestionnaireSalon'],['../<API key>.html#<API key>',1,'GestionnaireSalon::GestionnaireSalon()']]],
['<API key>',['GestionnaireSalon.cpp',['../<API key>.html',1,'']]],
['<API key>',['GestionnaireSalon.hpp',['../<API key>.html',1,'']]],
['gestionnairesocket',['GestionnaireSocket',['../<API key>.html',1,'GestionnaireSocket'],['../<API key>.html#<API key>',1,'GestionnaireSocket::GestionnaireSocket()']]],
['<API key>',['GestionnaireSocket.cpp',['../<API key>.html',1,'']]],
['<API key>',['GestionnaireSocket.hpp',['../<API key>.html',1,'']]],
['getdata',['getData',['../<API key>.html#<API key>',1,'DataPartieEnTete']]],
['gethote',['getHote',['../classSalon.html#<API key>',1,'Salon']]],
['<API key>',['<API key>',['../classMachineEtat.html#<API key>',1,'MachineEtat']]],
['getlisteetat',['getListeEtat',['../classMachineEtat.html#<API key>',1,'MachineEtat']]],
['getmutex',['getMutex',['../<API key>.html#<API key>',1,'GestionnaireMutex']]],
['<API key>',['<API key>',['../classMachineEtat.html#<API key>',1,'MachineEtat']]],
['getnomjoueur',['getNomJoueur',['../classJoueur.html#<API key>',1,'Joueur']]],
['getnumeroclient',['getNumeroClient',['../classSocketTcp.html#<API key>',1,'SocketTcp']]],
['getnumerojoueur',['getNumeroJoueur',['../classJoueur.html#<API key>',1,'Joueur']]],
['getnumerosalon',['getNumeroSalon',['../classSalon.html#<API key>',1,'Salon']]],
['getparam',['getParam',['../classConfiguration.html#<API key>',1,'Configuration']]],
['getsocket',['getSocket',['../<API key>.html#<API key>',1,'GestionnaireSocket']]],
['getsockettcp',['getSocketTcp',['../classJoueur.html#<API key>',1,'Joueur']]],
['<API key>',['<API key>',['../<API key>.html#<API key>',1,'GestionnaireSocket']]],
['getvaleurlisteetat',['getValeurListeEtat',['../classMachineEtat.html#<API key>',1,'MachineEtat']]]
];
|
#!/bin/sh
if [ $# -lt 4 ]; then
cat <<EOF
Usage: <API key>.sh SERVER SERVER_IP DOMAIN USERNAME PASSWORD
EOF
exit 1;
fi
SERVER="$1"
SERVER_IP="$2"
USERNAME="$3"
PASSWORD="$4"
TARGET_ENV="$5"
shift 5
ADDARGS="$@"
incdir=`dirname $0`/../../../testprogs/blackbox
. $incdir/subunit.sh
. $incdir/common_test_fns.inc
samba_bindir="$BINDIR"
samba_vlp="$samba_bindir/vlp"
samba_smbspool="$samba_bindir/smbspool"
samba_argv_wrapper="$samba_bindir/<API key>"
samba_smbtorture3="$samba_bindir/smbtorture3"
samba_smbspool_krb5="$samba_bindir/<API key>"
<API key>()
{
cmd='$1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "$out"
echo "failed to execute $1"
fi
echo "$out" | grep 'network smb "Unknown" "Windows Printer via SAMBA"'
ret=$?
if [ $ret != 0 ] ; then
echo "$out"
return 1
fi
}
test_smbspool_<API key>()
{
cmd='$samba_smbspool_krb5 smb://$SERVER_IP/print4 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps 2>&1'
AUTH_INFO_REQUIRED="none"
export AUTH_INFO_REQUIRED
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
unset AUTH_INFO_REQUIRED
if [ $ret != 0 ]; then
echo "$out"
echo "failed to execute $smbspool_krb5"
return 1
fi
return 0
}
test_smbspool_<API key>()
{
cmd='$samba_smbspool_krb5 smb://$SERVER_IP/print4 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps 2>&1'
# <API key> must ignore AUTH_INFO_REQUIRED unknown to him and pass the task to smbspool
# smbspool must fail with <API key> (22)
# "jjf4wgmsbc0" is just a random string
AUTH_INFO_REQUIRED="jjf4wgmsbc0"
export AUTH_INFO_REQUIRED
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
unset AUTH_INFO_REQUIRED
case "$ret" in
2 ) return 0 ;;
* )
echo "ret=$ret"
echo "$out"
echo "failed to test $smbspool_krb5 against unknown value of AUTH_INFO_REQUIRED"
return 1
;;
esac
}
# The test enviornment uses 'vlp' (virtual lp) as the printing backend.
# When using the vlp backend the print job is only written to the database.
# The job needs to removed manually using 'vlp lprm' command!
# This calls the 'vlp' command to check if the print job has been successfully
# added to the database and also makes sure the temorary print file has been
# created.
# The function removes the print job from the vlp database if successful.
test_vlp_verify()
{
tdbfile="$PREFIX_ABS/$TARGET_ENV/lockdir/vlp.tdb"
if [ ! -w $tdbfile ]; then
echo "vlp tdbfile $tdbfile doesn't exist or is not writeable!"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to get print queue with $samba_vlp"
echo "$out"
fi
jobid=$(echo "$out" | awk '/[0-9]+/ { print $1 };')
if [ -z "$jobid" ] || [ $jobid -lt 100 || [ $jobid -gt 2000 ]; then
echo "Invalid jobid: $jobid"
echo "$out"
return 1
fi
file=$(echo "$out" | awk '/[0-9]+/ { print $6 };')
if [ ! -r $PREFIX_ABS/$TARGET_ENV/share/$file ]; then
echo "$file doesn't exist"
echo "$out"
return 1
fi
$samba_vlp "tdbfile=$tdbfile" lprm print1 $jobid
ret=$?
if [ $ret != 0 ] ; then
echo "Failed to remove jobid $jobid from $tdbfile"
return 1
fi
}
<API key>()
{
tdbfile="$PREFIX_ABS/$TARGET_ENV/lockdir/vlp.tdb"
if [ ! -w $tdbfile ]; then
echo "vlp tdbfile $tdbfile doesn't exist or is not writeable!"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to lpq jobs on print1 with $samba_vlp"
echo "$out"
return 1
fi
num_jobs=$(echo "$out" | wc -l)
# Now run the test DELETE-PRINT from smbtorture3
cmd='$samba_smbtorture3 //$SERVER_IP/print1 -U$USERNAME%$PASSWORD DELETE-PRINT 2>&1'
eval echo "$cmd"
out_t=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to run DELETE-PRINT on print1"
echo "$out_t"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out1=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "(2) failed to lpq jobs on print1 with $samba_vlp"
echo "$out1"
return 1
fi
num_jobs1=$(echo "$out1" | wc -l)
# Number of jobs should not change. Job
# should not have made it to backend.
if [ "$num_jobs1" -ne "$num_jobs" ]; then
echo "delete-on-close fail $num_jobs1 -ne $num_jobs"
echo "$out"
echo "$out_t"
echo "$out1"
return 1
fi
return 0
}
testit "smbspool no args" \
<API key> $samba_smbspool || \
failed=$(expr $failed + 1)
testit "<API key> no args" \
<API key> $samba_smbspool_krb5 || \
failed=$(expr $failed + 1)
testit "<API key> AuthInfoRequired=none" \
test_smbspool_<API key> || \
failed=$(expr $failed + 1)
testit "<API key> AuthInfoRequired=(sth unknown)" \
test_smbspool_<API key> || \
failed=$(expr $failed + 1)
testit "smbspool print example.ps" \
$samba_smbspool smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
testit "smbspool print example.ps via stdin" \
$samba_smbspool smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print DEVICE_URI example.ps" \
$samba_smbspool 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print DEVICE_URI example.ps via stdin" \
$samba_smbspool 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print sanitized Device URI in argv0 example.ps" \
$<API key> $samba_smbspool smb://$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print sanitized Device URI in argv0 example.ps via stdin" \
$<API key> $samba_smbspool smb://$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
AUTH_INFO_REQUIRED="username,password"
export AUTH_INFO_REQUIRED
testit "smbspool_krb5(username,password) print example.ps" \
$samba_smbspool_krb5 smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify || \
failed=$(expr $failed + 1)
unset AUTH_INFO_REQUIRED
testit "delete on close" \
<API key> \
|| failed=$(expr $failed + 1)
exit $failed
|
#! /bin/sh
# A simple utility script which reads the SBD configuration file and loops
# through all SBD block devices, clearing message slots for all nodes. This
# effectively unfences any nodes.
SBD_CONFIG="/etc/sysconfig/sbd"
# Read the SBD config file and loop over all devices
while read -r device; do
while read -r sbd_list; do
node="$(echo ${sbd_list} | awk '{print $2}')"
echo "Clearing message slots for node '${node}'" \
"on device '${device}'..."
sbd -d ${device} message ${node} clear
done <<< "$(sbd -d ${device} list)"
done <<< "$(cat ${SBD_CONFIG} | grep SBD_DEVICE | cut -d= -f2 | \
tr -d '"' | tr ';' '\n')"
|
#include "Configuration.h"
#ifdef OPENSSL_IS_LINKED
#include <openssl/x509.h>
#include "<API key>.h"
<API key>::~<API key>() {
if (root) {
free(root);
}
root = NULL;
if (Cert) {
X509_free((X509*) Cert);
}
Cert = NULL;
}
void <API key>::setValidTimer(PASER_Timer_Message *_validTimer) {
validTimer = _validTimer;
}
#endif
|
#define HERCULES_CORE
#include "conf.h"
#include "common/showmsg.h" // ShowError
#include "common/strlib.h" // safestrncpy
#include "common/utils.h" // exists
#include <libconfig/libconfig.h>
/* interface source */
struct libconfig_interface libconfig_s;
struct libconfig_interface *libconfig;
/**
* Initializes 'config' and loads a configuration file.
*
* Shows error and destroys 'config' in case of failure.
* It is the caller's care to destroy 'config' in case of success.
*
* @param config The config file to initialize.
* @param config_filename The file to read.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_load_file(struct config_t *config, const char *config_filename)
{
libconfig->init(config);
if (!exists(config_filename)) {
ShowError("Unable to load '%s' - File not found\n", config_filename);
return CONFIG_FALSE;
}
if (libconfig->read_file_src(config, config_filename) != CONFIG_TRUE) {
ShowError("%s:%d - %s\n", config_error_file(config),
config_error_line(config), config_error_text(config));
libconfig->destroy(config);
return CONFIG_FALSE;
}
return CONFIG_TRUE;
}
// Functions to copy settings from libconfig/contrib
void <API key>(struct config_setting_t *parent, const struct config_setting_t *src)
{
if (<API key>(src)) {
libconfig-><API key>(parent, src);
} else {
struct config_setting_t *set;
if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL )
return;
if ((set = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src))) == NULL)
return;
if (CONFIG_TYPE_INT == config_setting_type(src)) {
libconfig->setting_set_int(set, libconfig->setting_get_int(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
libconfig->setting_set_int64(set, libconfig->setting_get_int64(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
libconfig->setting_set_float(set, libconfig->setting_get_float(src));
} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
libconfig->setting_set_string(set, libconfig->setting_get_string(src));
} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
libconfig->setting_set_bool(set, libconfig->setting_get_bool(src));
}
}
}
void <API key>(struct config_setting_t *parent, const struct config_setting_t *src)
{
struct config_setting_t *set = NULL;
if (<API key>(src))
libconfig-><API key>(parent, src);
else if (CONFIG_TYPE_INT == config_setting_type(src)) {
set = libconfig-><API key>(parent, -1, libconfig->setting_get_int(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
set = libconfig-><API key>(parent, -1, libconfig->setting_get_int64(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
libconfig-><API key>(parent, -1, libconfig->setting_get_float(src));
} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
libconfig-><API key>(parent, -1, libconfig->setting_get_string(src));
} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
libconfig-><API key>(parent, -1, libconfig->setting_get_bool(src));
}
}
void <API key>(struct config_setting_t *parent, const struct config_setting_t *src)
{
struct config_setting_t *newAgg;
int i, n;
if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL )
return;
newAgg = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src));
if (newAgg == NULL)
return;
n = <API key>(src);
for (i = 0; i < n; i++) {
if (<API key>(src)) {
libconfig->setting_copy_simple(newAgg, libconfig->setting_get_elem(src, i));
} else {
libconfig->setting_copy_elem(newAgg, libconfig->setting_get_elem(src, i));
}
}
}
int config_setting_copy(struct config_setting_t *parent, const struct config_setting_t *src)
{
if (!<API key>(parent) && !<API key>(parent))
return CONFIG_FALSE;
if (<API key>(src)) {
libconfig-><API key>(parent, src);
} else {
libconfig->setting_copy_simple(parent, src);
}
return CONFIG_TRUE;
}
/**
* Converts the value of a setting that is type CONFIG_TYPE_BOOL to bool.
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval false in case of failure.
*/
bool <API key>(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_BOOL)
return false;
return setting->value.ival ? true : false;
}
/**
* Same as <API key>, but uses bool instead of int.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int <API key>(const struct config_setting_t *setting, const char *name, bool *value)
{
struct config_setting_t *member = <API key>(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_BOOL)
return CONFIG_FALSE;
*value = <API key>(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to unsigned int (uint32).
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
uint32 <API key>(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival < 0)
return 0;
return (uint32)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint32.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int <API key>(const struct config_setting_t *setting, const char *name, uint32 *value)
{
struct config_setting_t *member = <API key>(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = <API key>(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to uint16
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
uint16 <API key>(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival > UINT16_MAX)
return UINT16_MAX;
if (setting->value.ival < UINT16_MIN)
return UINT16_MIN;
return (uint16)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint16.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int <API key>(const struct config_setting_t *setting, const char *name, uint16 *value)
{
struct config_setting_t *member = <API key>(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = <API key>(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to int16
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
int16 <API key>(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival > INT16_MAX)
return INT16_MAX;
if (setting->value.ival < INT16_MIN)
return INT16_MIN;
return (int16)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as int16.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int <API key>(const struct config_setting_t *setting, const char *name, int16 *value)
{
struct config_setting_t *member = <API key>(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = <API key>(member);
return CONFIG_TRUE;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_setting_t and copies it into a (non-const) char buffer.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] out The output buffer.
* @param[in] out_size The size of the output buffer.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int <API key>(const struct config_setting_t *setting, const char *name, char *out, size_t out_size)
{
const char *str = NULL;
if (libconfig-><API key>(setting, name, &str) == CONFIG_TRUE) {
safestrncpy(out, str, out_size);
return CONFIG_TRUE;
}
return CONFIG_FALSE;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_t and copies it into a (non-const) char buffer.
*
* @param[in] config The configuration to read.
* @param[in] name The setting name to lookup.
* @param[out] out The output buffer.
* @param[in] out_size The size of the output buffer.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int <API key>(const struct config_t *config, const char *name, char *out, size_t out_size)
{
const char *str = NULL;
if (libconfig->lookup_string(config, name, &str) == CONFIG_TRUE) {
safestrncpy(out, str, out_size);
return CONFIG_TRUE;
}
return CONFIG_FALSE;
}
void libconfig_defaults(void) {
libconfig = &libconfig_s;
libconfig->read = config_read;
libconfig->write = config_write;
libconfig->set_options = config_set_options;
libconfig->get_options = config_get_options;
libconfig->read_string = config_read_string;
libconfig->read_file_src = config_read_file;
libconfig->write_file = config_write_file;
libconfig->set_destructor = <API key>;
libconfig->set_include_dir = <API key>;
libconfig->init = config_init;
libconfig->destroy = config_destroy;
libconfig->setting_get_int = <API key>;
libconfig->setting_get_int64 = <API key>;
libconfig->setting_get_float = <API key>;
libconfig->setting_get_bool = <API key>;
libconfig->setting_get_string = <API key>;
libconfig->setting_lookup = <API key>;
libconfig->setting_lookup_int = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig->setting_lookup_bool = <API key>;
libconfig-><API key> = <API key>;
libconfig->setting_set_int = <API key>;
libconfig->setting_set_int64 = <API key>;
libconfig->setting_set_float = <API key>;
libconfig->setting_set_bool = <API key>;
libconfig->setting_set_string = <API key>;
libconfig->setting_set_format = <API key>;
libconfig->setting_get_format = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig->setting_index = <API key>;
libconfig->setting_length = <API key>;
libconfig->setting_get_elem = <API key>;
libconfig->setting_get_member = <API key>;
libconfig->setting_add = config_setting_add;
libconfig->setting_remove = <API key>;
libconfig->setting_remove_elem = <API key>;
libconfig->setting_set_hook = <API key>;
libconfig->lookup = config_lookup;
libconfig->lookup_int = config_lookup_int;
libconfig->lookup_int64 = config_lookup_int64;
libconfig->lookup_float = config_lookup_float;
libconfig->lookup_bool = config_lookup_bool;
libconfig->lookup_string = <API key>;
/* those are custom and are from src/common/conf.c */
libconfig->load_file = config_load_file;
libconfig->setting_copy_simple = <API key>;
libconfig->setting_copy_elem = <API key>;
libconfig-><API key> = <API key>;
libconfig->setting_copy = config_setting_copy;
/* Functions to get different types */
libconfig-><API key> = <API key>;
libconfig->setting_get_uint32 = <API key>;
libconfig->setting_get_uint16 = <API key>;
libconfig->setting_get_int16 = <API key>;
/* Functions to lookup different types */
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
libconfig-><API key> = <API key>;
}
|
<?php
namespace Magento\PageCache\Test\Unit\Model;
use Magento\PageCache\Model\Config;
class ConfigTest extends \<API key>
{
/**
* @var \Magento\PageCache\Model\Config
*/
protected $_model;
/**
* @var \<API key>|\Magento\Framework\App\Config\<API key>
*/
protected $_coreConfigMock;
/**
* @var \<API key>|\Magento\Framework\App\Cache\StateInterface
*/
protected $_cacheState;
/**
* @var \<API key>|\Magento\Framework\Module\Dir\Reader
*/
protected $moduleReader;
/**
* setUp all mocks and data function
*/
protected function setUp()
{
$readFactoryMock = $this->getMock('Magento\Framework\Filesystem\Directory\ReadFactory', [], [], '', false);
$this->_coreConfigMock = $this->getMock('Magento\Framework\App\Config\<API key>');
$this->_cacheState = $this-><API key>('Magento\Framework\App\Cache\StateInterface');
$<API key> = $this->getMock(
'Magento\Framework\Filesystem\Directory\Write',
[],
[],
'',
false
);
$readFactoryMock->expects(
$this->any()
)->method(
'create'
)->will(
$this->returnValue($<API key>)
);
$<API key>->expects(
$this->any()
)->method(
'readFile'
)->will(
$this->returnValue(file_get_contents(__DIR__ . '/_files/test.vcl'))
);
$this->_coreConfigMock->expects(
$this->any()
)->method(
'getValue'
)->will(
$this->returnValueMap(
[
[
\Magento\PageCache\Model\Config::<API key>,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'example.com',
],
[
\Magento\PageCache\Model\Config::<API key>,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'8080'
],
[
\Magento\PageCache\Model\Config::<API key>,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'127.0.0.1, 192.168.0.1,127.0.0.2'
],
[
\Magento\PageCache\Model\Config::<API key>,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
serialize([['regexp' => '(?i)pattern', 'value' => 'value_for_pattern']])
],
]
)
);
$this->moduleReader = $this->getMock('Magento\Framework\Module\Dir\Reader', [], [], '', false);
$this->_model = new \Magento\PageCache\Model\Config(
$readFactoryMock,
$this->_coreConfigMock,
$this->_cacheState,
$this->moduleReader
);
}
/**
* test for getVcl method
*/
public function testGetVcl()
{
$this->moduleReader->expects($this->once())
->method('getModuleDir')
->willReturn('/magento/app/code/Magento/PageCache');
$test = $this->_model->getVclFile(Config::<API key>);
$this->assertEquals(file_get_contents(__DIR__ . '/_files/result.vcl'), $test);
}
public function testGetTll()
{
$this->_coreConfigMock->expects($this->once())->method('getValue')->with(Config::XML_PAGECACHE_TTL);
$this->_model->getTtl();
}
/**
* Whether a cache type is enabled
*/
public function testIsEnabled()
{
$this->_cacheState->expects($this->at(0))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(true));
$this->_cacheState->expects($this->at(1))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(false));
$this->assertTrue($this->_model->isEnabled());
$this->assertFalse($this->_model->isEnabled());
}
}
|
#ifndef _INTERNAL_H
#define _INTERNAL_H
#include "pluginmain.h"
//menu identifiers
#define MENU_ANALYSIS 0
//functions
void internalInit(PLUG_INITSTRUCT* initStruct);
void internalStop();
void internalSetup();
#endif // _TEST_H
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Jan 16 16:58:40 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService (BCO DAL 1.5-SNAPSHOT API)</title>
<meta name="date" content="2018-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService (BCO DAL 1.5-SNAPSHOT API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../org/openbase/bco/dal/lib/layer/service/stream/StreamService.html" title="interface in org.openbase.bco.dal.lib.layer.service.stream">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html" target="_top">Frames</a></li>
<li><a href="StreamService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService" class="title">Uses of Interface<br>org.openbase.bco.dal.lib.layer.service.stream.StreamService</h2>
</div>
<div class="classUseContainer">No usage of org.openbase.bco.dal.lib.layer.service.stream.StreamService</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../org/openbase/bco/dal/lib/layer/service/stream/StreamService.html" title="interface in org.openbase.bco.dal.lib.layer.service.stream">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html" target="_top">Frames</a></li>
<li><a href="StreamService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
<a href="http://wikipedia.org">Wikipedia</a>
|
#include "bullet.h"
/**
* \fn Bullet* createBullet(Tower *tower)
* \brief create a new bullet
* a new bullet which doesn't have
* \param tower the tower the bullet belong to
*/
Bullet* createBullet(Tower *tower){
Bullet *bullet = malloc(sizeof (Bullet));
bullet->type = tower->type->typeBul;
bullet->position = searchEnemy(tower);
return bullet;
}
/**
* \fn void drawBullet(Bullet *bullet)
* \brief draw a bullet
*
* \param bullet a bullet to draw
*/
void drawBullet(Bullet *bullet){
SDL_Rect position;
position.x = 280;
position.y = 280;
blitToViewport(_viewport, bullet->type->image, NULL, &position);
}
/**
* \fn void animateBullet(Bullet *bullet)
* \brief move the bullet to an enemy and draw it
* Depreciated, recode your own function!
* \param bullet the bullet to animate
*/
void animateBullet(Bullet *bullet){
/* if(!(bullet->position->xx == bullet->position->x && bullet->position->yy == bullet->position->y)){*/
drawBullet(bullet);
}
|
<?php
namespace Nooku\Library;
class EventMixin extends ObjectMixinAbstract implements EventMixinInterface
{
/**
* Event publisher object
*
* @var <API key>
*/
private $__event_publisher;
/**
* List of event subscribers
*
* Associative array of event subscribers, where key holds the subscriber identifier string
* and the value is an identifier object.
*
* @var array
*/
private $__event_subscribers = array();
/**
* Object constructor
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @throws \<API key>
*/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
if (is_null($config->event_publisher)) {
throw new \<API key>('event_publisher [<API key>] config option is required');
}
//Set the event dispatcher
$this->__event_publisher = $config->event_publisher;
//Add the event listeners
foreach ($config->event_listeners as $event => $listener) {
$this->addEventListener($event, $listener);
}
//Add the event subscribers
$subscribers = (array) ObjectConfig::unbox($config->event_subscribers);
foreach ($subscribers as $key => $value)
{
if (is_numeric($key)) {
$this->addEventSubscriber($value);
} else {
$this->addEventSubscriber($key, $value);
}
}
}
/**
* Initializes the options for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @return void
*/
protected function _initialize(ObjectConfig $config)
{
$config->append(array(
'event_publisher' => 'event.publisher',
'event_subscribers' => array(),
'event_listeners' => array(),
));
parent::_initialize($config);
}
/**
* Publish an event by calling all listeners that have registered to receive it.
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param array|\Traversable|EventInterface $attributes An associative array, an object implementing the
* EventInterface or a Traversable object
* @param mixed $target The event target
* @throws \<API key> If the event is not a string or does not implement the KEventInterface
* @return null|EventInterface Returns the event object. If the chain is not enabled will return NULL.
*/
public function publishEvent($event, $attributes = array(), $target = null)
{
return $this->getEventPublisher()->publishEvent($event, $attributes, $target);
}
/**
* Get the event publisher
*
* @throws \<API key>
* @return <API key>
*/
public function getEventPublisher()
{
if(!$this->__event_publisher instanceof <API key>)
{
$this->__event_publisher = $this->getObject($this->__event_publisher);
if(!$this->__event_publisher instanceof <API key>)
{
throw new \<API key>(
'EventPublisher: '.get_class($this->__event_publisher).' does not implement <API key>'
);
}
}
return $this->__event_publisher;
}
/**
* Set the event publisher
*
* @param <API key> $publisher An event publisher object
* @return ObjectInterface The mixer
*/
public function setEventPublisher(<API key> $publisher)
{
$this->__event_publisher = $publisher;
return $this->getMixer();
}
/**
* Add an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @param integer $priority The event priority, usually between 1 (high priority) and 5 (lowest),
* default is 3 (normal)
* @throws \<API key> If the listener is not a callable
* @throws \<API key> If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function addEventListener($event, $listener, $priority = EventInterface::PRIORITY_NORMAL)
{
$this->getEventPublisher()->addListener($event, $listener, $priority);
return $this->getMixer();
}
/**
* Remove an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @throws \<API key> If the listener is not a callable
* @throws \<API key> If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function removeEventListener($event, $listener)
{
$this->getEventPublisher()->removeListener($event, $listener);
return $this->getMixer();
}
/**
* Add an event subscriber
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration options
* @return ObjectInterface The mixer
*/
public function addEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof <API key>)) {
$subscriber = $this->getEventSubscriber($subscriber, $config);
}
$subscriber->subscribe($this->getEventPublisher());
return $this;
}
/**
* Remove an event subscriber
*
* @param <API key> $subscriber An event subscriber
* @return ObjectInterface The mixer
*/
public function <API key>(<API key> $subscriber)
{
$subscriber->unsubscribe($this->getEventPublisher());
return $this->getMixer();
}
/**
* Get a event subscriber by identifier
*
* The subscriber will be created if does not exist yet, otherwise the existing subscriber will be returned.
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration settings
* @throws \<API key> If the subscriber is not implementing the <API key>
* @return <API key>
*/
public function getEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof ObjectIdentifier))
{
//Create the complete identifier if a partial identifier was passed
if (is_string($subscriber) && strpos($subscriber, '.') === false)
{
$identifier = $this->getIdentifier()->toArray();
$identifier['path'] = array('event', 'subscriber');
$identifier['name'] = $subscriber;
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($subscriber);
}
else $identifier = $subscriber;
if (!isset($this->__event_subscribers[(string)$identifier]))
{
$subscriber = $this->getObject($identifier, $config);
//Check the event subscriber interface
if (!($subscriber instanceof <API key>))
{
throw new \<API key>(
"Event Subscriber $identifier does not implement <API key>"
);
}
}
else $subscriber = $this->__event_subscribers[(string)$identifier];
return $subscriber;
}
/**
* Gets the event subscribers
*
* @return array An array of event subscribers
*/
public function getEventSubscribers()
{
return array_values($this->__event_subscribers);
}
}
|
require 'nokogiri'
require 'digest'
class XMLReader
# uses nokogiri to extract all system information from scenario.xml
# This includes module filters, which are module objects that contain filters for selecting
# from the actual modules that are available
# @return [Array] Array containing Systems objects
def self.parse_doc(file_path, schema, type)
doc = nil
begin
doc = Nokogiri::XML(File.read(file_path))
rescue
Print.err "Failed to read #{type} configuration file (#{file_path})"
exit
end
validate_xml(doc, file_path, schema, type)
# remove xml namespaces for ease of processing
doc.remove_namespaces!
end
def self.validate_xml(doc, file_path, schema, type)
# validate XML against schema
begin
xsd = Nokogiri::XML::Schema(File.open(schema))
xsd.validate(doc).each do |error|
Print.err "Error in scenario configuration file (#{scenario_file}):"
Print.err " #{error.line}: #{error.message}"
exit
end
rescue Exception => e
Print.err "Failed to validate #{type} xml file (#{file_path}): against schema (#{schema})"
Print.err e.message
exit
end
end
def self.read_attributes(node)
attributes = {}
node.xpath('@*').each do |attr|
attributes["#{attr.name}"] = [attr.text] unless attr.text.nil? || attr.text == ''
end
attributes
end
end
|
<?php
// Heading
$_['heading_title'] = 'Blog Viewed Report';
// Text
$_['text_success'] = 'Success: You have modified the blog viewed report!';
// Column
$_['column_article_name'] = 'Article Name';
$_['column_author_name'] = 'Author Name';
$_['column_viewed'] = 'Viewed';
$_['column_percent'] = 'Percent';
// Entry
$_['entry_date_start'] = 'Date Start:';
$_['entry_date_end'] = 'Date End:';
?>
|
#import "OWSViewController.h"
@class TSThread;
<API key>
@protocol <API key> <NSObject>
- (void)threadWasSelected:(TSThread *)thread;
- (BOOL)<API key>;
- (nullable UIView *)<API key>:(UISearchBar *)searchBar;
@end
#pragma mark -
// A base class for views used to pick a single signal user, either by
// entering a phone number or picking from your contacts.
@interface <API key> : OWSViewController
@property (nonatomic, weak) id<<API key>> delegate;
@end
<API key>
|
<?php
namespace App\itnovum\openITCOCKPIT\Core\AngularJS;
class PdfAssets {
/**
* @return array
*/
static public function getCssFiles() {
return [
'/node_modules/bootstrap/dist/css/bootstrap.css',
'/smartadmin4/dist/css/vendors.bundle.css',
'/smartadmin4/dist/css/app.bundle.css',
'/node_modules/@fortawesome/fontawesome-free/css/all.css',
'/css/<API key>.css',
'/css/openitcockpit-utils.css',
'/css/openitcockpit.css',
'/css/openitcockpit-pdf.css',
];
}
}
|
#!/usr/bin/perl
package Koha::Reporting::Report::Grouping::DateLastLoaned;
use Modern::Perl;
use Moose;
use Data::Dumper;
use C4::Context;
extends 'Koha::Reporting::Report::Grouping::Abstract';
sub BUILD {
my $self = shift;
$self->setName('datelastborrowed');
$self->setAlias('Date last borrowed');
$self->setDescription('Date last borrowed');
$self->setDimension('item');
$self->setField('datelastborrowed');
}
1;
|
using LeagueSharp.Common;
using SharpDX;
using EloBuddy;
using LeagueSharp.Common;
namespace e.Motion_Katarina
{
public class Dagger
{
private static readonly int DELAY = 0;
private static readonly int MAXACTIVETIME = 4000;
private bool Destructable;
private Vector3 Position;
private int Time;
public Dagger(Vector3 position)
{
Time = Utils.TickCount + DELAY;
this.Position = position;
}
//Object Pooling Pseudo-Constructor
public void Recreate(Vector3 position)
{
Destructable = false;
Time = Utils.TickCount + DELAY;
this.Position = position;
}
public Vector3 GetPosition()
{
return Position;
}
public bool IsDead()
{
return Destructable;
}
public void MarkDead()
{
Destructable = true;
}
public bool IsActive()
{
return Utils.TickCount >= Time;
}
public void CheckForUpdate()
{
if(Time + MAXACTIVETIME <= Utils.TickCount)
{
Destructable = true;
return;
}
}
}
}
|
package org.obiba.mica.search.aggregations;
import org.obiba.mica.micaConfig.service.helper.<API key>;
import org.obiba.mica.micaConfig.service.helper.<API key>;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Map;
@Component
public class <API key> implements <API key> {
private static final String AGGREGATION_NAME = "populationId";
private final <API key> helper;
@Inject
public <API key>(<API key> helper) {
this.helper = helper;
}
@Override
public MetaData getMetadata(String aggregation, String termKey, String locale) {
Map<String, LocalizedMetaData> dataMap = helper.getPopulations();
return AGGREGATION_NAME.equals(aggregation) && dataMap.containsKey(termKey) ?
MetaData.newBuilder()
.title(dataMap.get(termKey).getTitle().get(locale))
.description(dataMap.get(termKey).getDescription().get(locale))
.className(dataMap.get(termKey).getClassName())
.build() : null;
}
@Override
public boolean containsAggregation(String aggregation) {
return AGGREGATION_NAME.equals(aggregation);
}
@Override
public void refresh() {
}
}
|
<p style="text-align:justify">word0<strong> short term debt securities</strong> word1 word2 word3 <strong>december 21, 2010.</strong></p><p><br /></p>
|
package org.dswarm.graph.delta.match.model.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.dswarm.graph.delta.match.model.CSEntity;
import org.dswarm.graph.delta.match.model.ValueEntity;
/**
* @author tgaengler
*/
public final class CSEntityUtil {
public static Optional<? extends Collection<ValueEntity>> getValueEntities(final Optional<? extends Collection<CSEntity>> csEntities) {
if (!csEntities.isPresent() || csEntities.get().isEmpty()) {
return Optional.empty();
}
final Set<ValueEntity> valueEntities = new HashSet<>();
for (final CSEntity csEntity : csEntities.get()) {
valueEntities.addAll(csEntity.getValueEntities());
}
return Optional.of(valueEntities);
}
}
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
// This file is auto-generated by the Macro.Model.SqlServer.CodeGenerator project.
namespace Macro.ImageServer.Model.EntityBrokers
{
using Macro.ImageServer.Enterprise;
public interface <API key>: IEnumBroker<<API key>>
{ }
}
|
// This file is part of the ClearCanvas RIS/PACS open source project.
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// the ClearCanvas RIS/PACS open source project. If not, see
#endregion
using System;
namespace Macro.ImageServer.Common.Exceptions
{
<summary>
Represents an exception thrown when the study state is invalid for the operation.
</summary>
public class <API key> : System.Exception
{
public <API key>(string message):base(message)
{
}
}
}
|
function assign(taskID, assignedTo)
{
$('.assign').width(150);
$('.assign').height(40);
$('.assign').load(createLink('user', 'ajaxGetUser', 'taskID=' + taskID + '&assignedTo=' + assignedTo));
}
function setComment()
{
$('#comment').toggle();
}
|
(function() {
'use strict';
angular
.module('editor.database', [])
.config(function($indexedDBProvider) {
$indexedDBProvider
.connection('otus-studio')
.upgradeDatabase(1, function(event, db, tx) {
var store = db.createObjectStore('survey_template', { keyPath: 'template_oid'});
store.createIndex('contributor_idx', 'contributor', { unique: false });
});
});
}());
|
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: local('Montserrat-Regular'), url(https://fonts.gstatic.com/s/montserrat/v7/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
src: local('Montserrat-Bold'), url(https://fonts.gstatic.com/s/montserrat/v7/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/<API key>.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
|
<?php
echo("Discovery protocols:");
global $link_exists;
$community = $device['community'];
if ($device['os'] == "ironware")
{
echo(" Brocade FDP: ");
$fdp_array = <API key>($device, "snFdpCacheEntry", array(), "<API key>");
if ($fdp_array)
{
unset($fdp_links);
foreach (array_keys($fdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$key));
$fdp_if_array = $fdp_array[$key];
foreach (array_keys($fdp_if_array) as $entry_key)
{
$fdp = $fdp_if_array[$entry_key];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($fdp['snFdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through FDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $fdp['<API key>'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName = ?) AND `device_id` = ?",array($if,$if,$remote_device_id));
} else { $remote_port_id = "0"; }
discover_link($interface['port_id'], $fdp['snFdpCacheVendorId'], $remote_port_id, $fdp['snFdpCacheDeviceId'], $fdp['<API key>'], $fdp['snFdpCachePlatform'], $fdp['snFdpCacheVersion']);
}
}
}
}
echo(" CISCO-CDP-MIB: ");
unset($cdp_array);
$cdp_array = <API key>($device, "cdpCache", array(), "CISCO-CDP-MIB");
if ($cdp_array)
{
unset($cdp_links);
foreach (array_keys($cdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE device_id = ? AND `ifIndex` = ?", array($device['device_id'], $key));
$cdp_if_array = $cdp_array[$key];
foreach (array_keys($cdp_if_array) as $entry_key)
{
$cdp = $cdp_if_array[$entry_key];
if (is_valid_hostname($cdp['cdpCacheDeviceId']))
{
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?", array($cdp['cdpCacheDeviceId'], $cdp['cdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($cdp['cdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through CDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $cdp['cdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?", array($if, $if, $remote_device_id));
} else { $remote_port_id = "0"; }
if ($interface['port_id'] && $cdp['cdpCacheDeviceId'] && $cdp['cdpCacheDevicePort'])
{
discover_link($interface['port_id'], 'cdp', $remote_port_id, $cdp['cdpCacheDeviceId'], $cdp['cdpCacheDevicePort'], $cdp['cdpCachePlatform'], $cdp['cdpCacheVersion']);
}
}
else
{
echo("X");
}
}
}
}
echo(" LLDP-MIB: ");
unset($lldp_array);
$lldp_array = <API key>($device, "<API key>", array(), "LLDP-MIB");
$dot1d_array = snmpwalk_cache_oid($device, "<API key>", array(), "BRIDGE-MIB");
if ($lldp_array)
{
$lldp_links = "";
foreach (array_keys($lldp_array) as $key)
{
$lldp_if_array = $lldp_array[$key];
foreach (array_keys($lldp_if_array) as $entry_key)
{
if (is_numeric($dot1d_array[$entry_key]['<API key>']))
{
$ifIndex = $dot1d_array[$entry_key]['<API key>'];
} else {
$ifIndex = $entry_key;
}
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$ifIndex));
$lldp_instance = $lldp_if_array[$entry_key];
foreach (array_keys($lldp_instance) as $entry_instance)
{
$lldp = $lldp_instance[$entry_instance];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($lldp['lldpRemSysName'], $lldp['lldpRemSysName']));
if (!$remote_device_id && is_valid_hostname($lldp['lldpRemSysName']))
{
$remote_device_id = discover_new_device($lldp['lldpRemSysName']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through LLDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $lldp['lldpRemPortDesc']; $id = $lldp['lldpRemPortId'];
$remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ? OR `ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?",array($if,$if,$id,$id,$remote_device_id));
} else {
$remote_port_id = "0";
}
if (is_numeric($interface['port_id']) && isset($lldp['lldpRemSysName']) && isset($lldp['lldpRemPortId']))
{
discover_link($interface['port_id'], 'lldp', $remote_port_id, $lldp['lldpRemSysName'], $lldp['lldpRemPortId'], NULL, $lldp['lldpRemSysDesc']);
}
}
}
}
}
if ($debug) { print_r($link_exists); }
$sql = "SELECT * FROM `links` AS L, `ports` AS I WHERE L.local_port_id = I.port_id AND I.device_id = '".$device['device_id']."'";
foreach (dbFetchRows($sql) as $test)
{
$local_port_id = $test['local_port_id'];
$remote_hostname = $test['remote_hostname'];
$remote_port = $test['remote_port'];
if ($debug) { echo("$local_port_id -> $remote_hostname -> $remote_port \n"); }
if (!$link_exists[$local_port_id][$remote_hostname][$remote_port])
{
echo("-");
$rows = dbDelete('links', '`id` = ?', array($test['id']));
if ($debug) { echo("$rows deleted "); }
}
}
unset($link_exists);
echo("\n");
?>
|
#include <string.h> /* For strlen() */
#include <ctype.h> /* For tolower() */
#include <stdlib.h> /* For qsort() */
#include "hspset.h"
HSPset_ArgumentSet *<API key>(Argument *arg){
register ArgumentSet *as;
static HSPset_ArgumentSet has = {0};
if(arg){
as = ArgumentSet_create("HSP creation options");
<API key>(as, '\0', "hspfilter", NULL,
"Aggressive HSP filtering level", "0",
Argument_parse_int, &has.filter_threshold);
<API key>(as, '\0', "useworddropoff", NULL,
"Use word neighbourhood dropoff", "TRUE",
<API key>, &has.<API key>);
<API key>(as, '\0', "seedrepeat", NULL,
"Seeds per diagonal required for HSP seeding", "1",
Argument_parse_int, &has.seed_repeat);
<API key>(as, 0, "dnawordlen", "bp",
"Wordlength for DNA words", "12",
Argument_parse_int, &has.dna_wordlen);
<API key>(as, 0, "proteinwordlen", "aa",
"Wordlength for protein words", "6",
Argument_parse_int, &has.protein_wordlen);
<API key>(as, 0, "codonwordlen", "bp",
"Wordlength for codon words", "12",
Argument_parse_int, &has.codon_wordlen);
<API key>(as, 0, "dnahspdropoff", "score",
"DNA HSP dropoff score", "30",
Argument_parse_int, &has.dna_hsp_dropoff);
<API key>(as, 0, "proteinhspdropoff", "score",
"Protein HSP dropoff score", "20",
Argument_parse_int, &has.protein_hsp_dropoff);
<API key>(as, 0, "codonhspdropoff", "score",
"Codon HSP dropoff score", "40",
Argument_parse_int, &has.codon_hsp_dropoff);
<API key>(as, 0, "dnahspthreshold", "score",
"DNA HSP threshold score", "75",
Argument_parse_int, &has.dna_hsp_threshold);
<API key>(as, 0, "proteinhspthreshold", "score",
"Protein HSP threshold score", "30",
Argument_parse_int, &has.<API key>);
<API key>(as, 0, "codonhspthreshold", "score",
"Codon HSP threshold score", "50",
Argument_parse_int, &has.codon_hsp_threshold);
<API key>(as, 0, "dnawordlimit", "score",
"Score limit for dna word neighbourhood", "0",
Argument_parse_int, &has.dna_wordlimit);
<API key>(as, 0, "proteinwordlimit", "score",
"Score limit for protein word neighbourhood", "4",
Argument_parse_int, &has.protein_wordlimit);
<API key>(as, 0, "codonwordlimit", "score",
"Score limit for codon word neighbourhood", "4",
Argument_parse_int, &has.codon_wordlimit);
<API key>(as, '\0', "geneseed", "threshold",
"Geneseed Threshold", "0",
Argument_parse_int, &has.geneseed_threshold);
<API key>(as, '\0', "geneseedrepeat", "number",
"Seeds per diagonal required for geneseed HSP seeding", "3",
Argument_parse_int, &has.geneseed_repeat);
<API key>(arg, as);
}
return &has;
}
static gboolean HSP_check_positions(HSPset *hsp_set,
gint query_pos, gint target_pos){
g_assert(query_pos >= 0);
g_assert(target_pos >= 0);
g_assert(query_pos < hsp_set->query->len);
g_assert(target_pos < hsp_set->target->len);
return TRUE;
}
static gboolean HSP_check(HSP *hsp){
g_assert(hsp);
g_assert(hsp->hsp_set);
g_assert(hsp->length);
g_assert(HSP_query_end(hsp) <= hsp->hsp_set->query->len);
g_assert(HSP_target_end(hsp) <= hsp->hsp_set->target->len);
return TRUE;
}
void <API key>(HSP_Param *hsp_param, gint wordlen){
if(wordlen <= 0)
g_error("Wordlength must be greater than zero");
hsp_param->wordlen = wordlen;
hsp_param->seedlen = hsp_param->wordlen
/ hsp_param->match->query->advance;
return;
}
void <API key>(HSP_Param *hsp_param,
gint dna_hsp_threshold){
if(hsp_param->match->type == Match_Type_DNA2DNA)
hsp_param->threshold = dna_hsp_threshold;
return;
}
void <API key>(HSP_Param *hsp_param,
gint <API key>){
if((hsp_param->match->type == <API key>)
|| (hsp_param->match->type == <API key>)
|| (hsp_param->match->type == <API key>))
hsp_param->threshold = <API key>;
return;
}
void <API key>(HSP_Param *hsp_param,
gint codon_hsp_threshold){
if(hsp_param->match->type == <API key>)
hsp_param->threshold = codon_hsp_threshold;
return;
}
void <API key>(HSP_Param *hsp_param,
gint dna_hsp_dropoff){
if(hsp_param->match->type == Match_Type_DNA2DNA)
hsp_param->dropoff = dna_hsp_dropoff;
return;
}
void <API key>(HSP_Param *hsp_param,
gint protein_hsp_dropoff){
if((hsp_param->match->type == <API key>)
|| (hsp_param->match->type == <API key>)
|| (hsp_param->match->type == <API key>))
hsp_param->dropoff = protein_hsp_dropoff;
return;
}
void <API key>(HSP_Param *hsp_param,
gint codon_hsp_dropoff){
if(hsp_param->match->type == <API key>)
hsp_param->dropoff = codon_hsp_dropoff;
return;
}
void <API key>(HSP_Param *hsp_param,
gint hsp_threshold){
hsp_param->threshold = hsp_threshold;
return;
}
void <API key>(HSP_Param *hsp_param,
gint seed_repeat){
hsp_param->seed_repeat = seed_repeat;
return;
}
HSP_Param *HSP_Param_create(Match *match, gboolean use_horizon){
register HSP_Param *hsp_param = g_new(HSP_Param, 1);
register WordHood_Alphabet *wha = NULL;
register Submat *submat;
hsp_param->ref_count = 1;
hsp_param->has = <API key>(NULL);
hsp_param->match = match;
hsp_param->seed_repeat = hsp_param->has->seed_repeat;
switch(match->type){
case Match_Type_DNA2DNA:
hsp_param->dropoff = hsp_param->has->dna_hsp_dropoff;
hsp_param->threshold = hsp_param->has->dna_hsp_threshold;
<API key>(hsp_param, hsp_param->has->dna_wordlen);
hsp_param->wordlimit = hsp_param->has->dna_wordlimit;
break;
case <API key>: /*fallthrough*/
case <API key>: /*fallthrough*/
case <API key>:
hsp_param->dropoff = hsp_param->has->protein_hsp_dropoff;
hsp_param->threshold
= hsp_param->has-><API key>;
<API key>(hsp_param, hsp_param->has->protein_wordlen);
hsp_param->wordlimit = hsp_param->has->protein_wordlimit;
break;
case <API key>:
hsp_param->dropoff = hsp_param->has->codon_hsp_dropoff;
hsp_param->threshold = hsp_param->has->codon_hsp_threshold;
<API key>(hsp_param, hsp_param->has->codon_wordlen);
hsp_param->wordlimit = hsp_param->has->codon_wordlimit;
g_assert(!(hsp_param->wordlen % 3));
break;
default:
g_error("Bad Match_Type [%d]", match->type);
break;
}
hsp_param->use_horizon = use_horizon;
if(hsp_param->has-><API key> && (!hsp_param->wordlimit)){
hsp_param->wordhood = NULL;
} else {
submat = (match->type == Match_Type_DNA2DNA)
? match->mas->dna_submat
: match->mas->protein_submat;
wha = <API key>(
(gchar*)match->comparison_alphabet->member,
(gchar*)match->comparison_alphabet->member, submat, FALSE);
g_assert(wha);
hsp_param->wordhood = WordHood_create(wha, hsp_param->wordlimit,
hsp_param->has-><API key>);
<API key>(wha);
}
return hsp_param;
}
void HSP_Param_destroy(HSP_Param *hsp_param){
g_assert(hsp_param);
if(--hsp_param->ref_count)
return;
if(hsp_param->wordhood)
WordHood_destroy(hsp_param->wordhood);
g_free(hsp_param);
return;
}
HSP_Param *HSP_Param_share(HSP_Param *hsp_param){
g_assert(hsp_param);
hsp_param->ref_count++;
return hsp_param;
}
HSP_Param *HSP_Param_swap(HSP_Param *hsp_param){
g_assert(hsp_param);
return HSP_Param_create(Match_swap(hsp_param->match),
hsp_param->use_horizon);
}
static RecycleBin *<API key> = NULL;
HSPset *HSPset_create(Sequence *query, Sequence *target,
HSP_Param *hsp_param){
register HSPset *hsp_set = g_new(HSPset, 1);
g_assert(query);
g_assert(target);
hsp_set->ref_count = 1;
hsp_set->query = Sequence_share(query);
hsp_set->target = Sequence_share(target);
hsp_set->param = HSP_Param_share(hsp_param);
if(<API key>){
hsp_set->hsp_recycle = RecycleBin_share(<API key>);
} else {
<API key> = RecycleBin_create("HSP", sizeof(HSP), 64);
hsp_set->hsp_recycle = <API key>;
}
if(hsp_param->use_horizon){
hsp_set->horizon = (gint****)Matrix4d_create(
1 + ((hsp_param->seed_repeat > 1)?1:0),
query->len,
hsp_param->match->query->advance,
hsp_param->match->target->advance,
sizeof(gint));
} else {
hsp_set->horizon = NULL;
}
hsp_set->hsp_list = g_ptr_array_new();
hsp_set->is_finalised = FALSE;
hsp_set->param->has = <API key>(NULL);
if(hsp_set->param->has->filter_threshold){
hsp_set->filter = g_new0(PQueue*, query->len);
hsp_set->pqueue_set = PQueueSet_create();
} else {
hsp_set->filter = NULL;
hsp_set->pqueue_set = NULL;
}
hsp_set->is_empty = TRUE;
return hsp_set;
}
HSPset *HSPset_share(HSPset *hsp_set){
g_assert(hsp_set);
hsp_set->ref_count++;
return hsp_set;
}
void HSPset_destroy(HSPset *hsp_set){
register gint i;
register HSP *hsp;
g_assert(hsp_set);
if(--hsp_set->ref_count)
return;
HSP_Param_destroy(hsp_set->param);
if(hsp_set->filter)
g_free(hsp_set->filter);
if(hsp_set->pqueue_set)
PQueueSet_destroy(hsp_set->pqueue_set);
Sequence_destroy(hsp_set->query);
Sequence_destroy(hsp_set->target);
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
HSP_destroy(hsp);
}
g_ptr_array_free(hsp_set->hsp_list, TRUE);
if(hsp_set->hsp_recycle->ref_count == 1) /* last active hsp_set */
<API key> = NULL;
RecycleBin_destroy(hsp_set->hsp_recycle);
if(hsp_set->horizon)
g_free(hsp_set->horizon);
g_free(hsp_set);
return;
}
void HSPset_swap(HSPset *hsp_set, HSP_Param *hsp_param){
register Sequence *query;
register gint i, query_start;
register HSP *hsp;
g_assert(hsp_set->ref_count == 1);
/* Swap query and target */
query = hsp_set->query;
hsp_set->query = hsp_set->target;
hsp_set->target = query;
/* Switch parameters */
HSP_Param_destroy(hsp_set->param);
hsp_set->param = HSP_Param_share(hsp_param);
/* Swap HSPs coordinates */
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
query_start = hsp->query_start;
hsp->query_start = hsp->target_start;
hsp->target_start = query_start;
}
return;
}
void HSPset_revcomp(HSPset *hsp_set){
register Sequence *rc_query = Sequence_revcomp(hsp_set->query),
*rc_target = Sequence_revcomp(hsp_set->target);
register gint i;
register HSP *hsp;
g_assert(hsp_set);
g_assert(hsp_set->is_finalised);
g_assert(hsp_set->ref_count == 1);
Sequence_destroy(hsp_set->query);
Sequence_destroy(hsp_set->target);
hsp_set->query = rc_query;
hsp_set->target = rc_target;
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
hsp->query_start = hsp_set->query->len - HSP_query_end(hsp);
hsp->target_start = hsp_set->target->len - HSP_target_end(hsp);
}
return;
}
static gint HSP_find_cobs(HSP *hsp){
register gint i, query_pos = hsp->query_start,
target_pos = hsp->target_start;
register Match_Score score = 0;
/* Find the HSP centre offset by score */
for(i = 0; i < hsp->length; i++){
g_assert(HSP_check_positions(hsp->hsp_set,
query_pos, target_pos));
score += HSP_get_score(hsp, query_pos, target_pos);
if(score >= (hsp->score>>1))
break;
query_pos += HSP_query_advance(hsp);
target_pos += HSP_target_advance(hsp);
}
return i;
}
static void HSP_print_info(HSP *hsp){
g_print("HSP info (%p)\n"
" query_start = [%d]\n"
" target_start = [%d]\n"
" length = [%d]\n"
" score = [%d]\n"
" cobs = [%d]\n",
(gpointer)hsp,
hsp->query_start,
hsp->target_start,
hsp->length,
hsp->score,
hsp->cobs);
return;
}
typedef struct {
HSP *hsp; /* not freed */
gint padding;
gint max_advance;
gint query_display_pad;
gint target_display_pad;
GString *top;
GString *mid;
GString *low;
} HSP_Display;
static HSP_Display *HSP_Display_create(HSP *hsp, gint padding){
register HSP_Display *hd = g_new(HSP_Display, 1);
register gint approx_length;
hd->hsp = hsp;
hd->padding = padding;
hd->max_advance = MAX(HSP_query_advance(hsp),
HSP_target_advance(hsp));
hd->query_display_pad = (hd->max_advance
-HSP_query_advance(hsp))>>1;
hd->target_display_pad = (hd->max_advance
-HSP_target_advance(hsp))>>1;
approx_length = hd->max_advance * (hsp->length + 2);
hd->top = g_string_sized_new(approx_length);
hd->mid = g_string_sized_new(approx_length);
hd->low = g_string_sized_new(approx_length);
return hd;
}
static void HSP_Display_destroy(HSP_Display *hd){
g_assert(hd);
g_string_free(hd->top, TRUE);
g_string_free(hd->mid, TRUE);
g_string_free(hd->low, TRUE);
g_free(hd);
return;
}
static void HSP_Display_add(HSP_Display *hd,
gchar *top, gchar *mid, gchar *low){
g_assert(hd);
g_assert(top);
g_assert(mid);
g_assert(low);
g_string_append(hd->top, top);
g_string_append(hd->mid, mid);
g_string_append(hd->low, low);
g_assert(hd->top->len == hd->mid->len);
g_assert(hd->mid->len == hd->low->len);
return;
}
static gchar <API key>(HSP_Display *hd, gint pos,
gint advance){
register gint stop;
register gint pad_length = 3;
stop = hd->padding * hd->max_advance;
if(pos >= stop){
if(pos < (stop+pad_length)){
return '
}
stop = ((hd->padding+hd->hsp->length) * hd->max_advance)
+ pad_length;
if(pos >= stop){
if(pos < (stop+pad_length)){
return '
}
pos -= pad_length;
}
pos -= pad_length;
}
if((pos/advance) & 1)
return '=';
return '-';
}
static void <API key>(HSP_Display *hd, gint width,
gint pos, gboolean is_query){
register gint i, adv;
if(is_query){
if(HSP_target_advance(hd->hsp) == 1)
return; /* opposite padding */
adv = HSP_target_advance(hd->hsp);
} else { /* Is target */
if(HSP_query_advance(hd->hsp) == 1)
return; /* opposite padding */
adv = HSP_query_advance(hd->hsp);
}
g_print(" ruler:[");
for(i = 0; i < width; i++)
g_print("%c", <API key>(hd, pos+i, adv));
g_print("]\n");
return;
}
static void HSP_Display_print(HSP_Display *hd){
register gint pos, pause, width = 50;
g_assert(hd);
g_assert(hd->top->len == hd->mid->len);
g_assert(hd->mid->len == hd->low->len);
for(pos = 0, pause = hd->top->len-width; pos < pause; pos += width){
<API key>(hd, width, pos, TRUE);
g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n",
width, hd->top->str+pos,
width, hd->mid->str+pos,
width, hd->low->str+pos);
<API key>(hd, width, pos, FALSE);
g_print("\n");
}
<API key>(hd, hd->top->len-pos, pos, TRUE);
g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n",
hd->top->len-pos, hd->top->str+pos,
hd->mid->len-pos, hd->mid->str+pos,
hd->low->len-pos, hd->low->str+pos);
<API key>(hd, hd->top->len-pos, pos, FALSE);
g_print("\n");
return;
}
static void HSP_Display_insert(HSP_Display *hd, gint position){
register gint query_pos, target_pos;
register gboolean is_padding,
query_valid = TRUE, target_valid = TRUE;
register Match *match = hd->hsp->hsp_set->param->match;
gchar query_str[4] = {0},
target_str[4] = {0},
equiv_str[4] = {0};
g_assert(hd);
query_pos = hd->hsp->query_start
+ (HSP_query_advance(hd->hsp) * position);
target_pos = hd->hsp->target_start
+ (HSP_target_advance(hd->hsp) * position);
/* If outside HSP, then is_padding */
is_padding = ((position < 0) || (position >= hd->hsp->length));
/* If outside seqs, then invalid */
query_valid = ( (query_pos >= 0)
&&((query_pos+HSP_query_advance(hd->hsp))
<= hd->hsp->hsp_set->query->len));
target_valid = ((target_pos >= 0)
&&((target_pos+HSP_target_advance(hd->hsp))
<= hd->hsp->hsp_set->target->len));
/* Get equiv string */
if(query_valid && target_valid){
g_assert(HSP_check_positions(hd->hsp->hsp_set,
query_pos, target_pos));
HSP_get_display(hd->hsp, query_pos, target_pos, equiv_str);
} else {
strncpy(equiv_str, "###", hd->max_advance);
equiv_str[hd->max_advance] = '\0';
}
/* Get query string */
if(query_valid){
<API key>(match->query, hd->hsp->hsp_set->query,
query_pos, query_str);
if((match->query->advance == 1) && (hd->max_advance == 3)){
query_str[1] = query_str[0];
query_str[0] = query_str[2] = ' ';
query_str[3] = '\0';
}
} else {
strncpy(query_str, "###", hd->max_advance);
query_str[hd->max_advance] = '\0';
}
/* Get target string */
if(target_valid){
<API key>(match->target, hd->hsp->hsp_set->target,
target_pos, target_str);
if((match->target->advance == 1) && (hd->max_advance == 3)){
target_str[1] = target_str[0];
target_str[0] = target_str[2] = ' ';
target_str[3] = '\0';
}
} else {
strncpy(target_str, "###", hd->max_advance);
target_str[hd->max_advance] = '\0';
}
/* Make lower case for padding */
if(is_padding){
g_strdown(query_str);
g_strdown(target_str);
} else {
g_strup(query_str);
g_strup(target_str);
}
HSP_Display_add(hd, query_str, equiv_str, target_str);
return;
}
static void HSP_print_alignment(HSP *hsp){
register HSP_Display *hd = HSP_Display_create(hsp, 10);
register gint i;
for(i = 0; i < hd->padding; i++) /* Pre-padding */
HSP_Display_insert(hd, i-hd->padding);
/* Use pad_length == 3 */
HSP_Display_add(hd, " < ", " < ", " < "); /* Start divider */
for(i = 0; i < hsp->length; i++) /* The HSP itself */
HSP_Display_insert(hd, i);
HSP_Display_add(hd, " > ", " > ", " > "); /* End divider */
for(i = 0; i < hd->padding; i++) /* Post-padding */
HSP_Display_insert(hd, hsp->length+i);
HSP_Display_print(hd);
HSP_Display_destroy(hd);
return;
}
static void HSP_print_sugar(HSP *hsp){
g_print("sugar: %s %d %d %c %s %d %d %c %d\n",
hsp->hsp_set->query->id,
hsp->query_start,
hsp->length*HSP_query_advance(hsp),
<API key>(hsp->hsp_set->query),
hsp->hsp_set->target->id,
hsp->target_start,
hsp->length*HSP_target_advance(hsp),
<API key>(hsp->hsp_set->target),
hsp->score);
return;
}
/* Sugar output format:
* sugar: <query_id> <query_start> <query_length> <query_strand>
* <target_id> <target_start> <target_start> <target_strand>
* <score>
*/
void HSP_print(HSP *hsp, gchar *name){
g_print("draw_hsp(%d, %d, %d, %d, %d, %d, \"%s\")\n",
hsp->query_start,
hsp->target_start,
hsp->length,
hsp->cobs,
HSP_query_advance(hsp),
HSP_target_advance(hsp),
name);
HSP_print_info(hsp);
HSP_print_alignment(hsp);
HSP_print_sugar(hsp);
return;
}
void HSPset_print(HSPset *hsp_set){
register gint i;
register gchar *name;
g_print("HSPset [%p] contains [%d] hsps\n",
(gpointer)hsp_set, hsp_set->hsp_list->len);
g_print("Comparison of [%s] and [%s]\n",
hsp_set->query->id, hsp_set->target->id);
for(i = 0; i < hsp_set->hsp_list->len; i++){
name = g_strdup_printf("hsp [%d]", i+1);
HSP_print(hsp_set->hsp_list->pdata[i], name);
g_free(name);
}
return;
}
static void HSP_init(HSP *nh){
register gint i;
register gint query_pos, target_pos;
g_assert(HSP_check(nh));
/* Initial hsp score */
query_pos = nh->query_start;
target_pos = nh->target_start;
nh->score = 0;
for(i = 0; i < nh->length; i++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
nh->score += HSP_get_score(nh, query_pos, target_pos);
query_pos += HSP_query_advance(nh);
target_pos += HSP_target_advance(nh);
}
if(nh->score < 0){
HSP_print(nh, "Bad HSP seed");
g_error("Initial HSP score [%d] less than zero", nh->score);
}
g_assert(HSP_check(nh));
return;
}
static void HSP_extend(HSP *nh, gboolean forbid_masked){
register Match_Score score, maxscore;
register gint query_pos, target_pos;
register gint extend, maxext;
g_assert(HSP_check(nh));
/* extend left */
maxscore = score = nh->score;
query_pos = nh-><API key>(nh);
target_pos = nh-><API key>(nh);
for(extend = 1, maxext = 0;
((query_pos >= 0) && (target_pos >= 0));
extend++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
if((forbid_masked)
&& (HSP_query_masked(nh, query_pos)
|| HSP_target_masked(nh, target_pos)))
break;
score += HSP_get_score(nh, query_pos, target_pos);
if(maxscore <= score){
maxscore = score;
maxext = extend;
} else {
if(score < 0) /* See note below */
break;
if((maxscore-score) >= nh->hsp_set->param->dropoff)
break;
}
query_pos -= HSP_query_advance(nh);
target_pos -= HSP_target_advance(nh);
}
query_pos = HSP_query_end(nh);
target_pos = HSP_target_end(nh);
nh->query_start -= (maxext * HSP_query_advance(nh));
nh->target_start -= (maxext * HSP_target_advance(nh));
nh->length += maxext;
score = maxscore;
/* extend right */
for(extend = 1, maxext = 0;
( ((query_pos+HSP_query_advance(nh))
<= nh->hsp_set->query->len)
&& ((target_pos+HSP_target_advance(nh))
<= nh->hsp_set->target->len) );
extend++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
if((forbid_masked)
&& (HSP_query_masked(nh, query_pos)
|| HSP_target_masked(nh, target_pos)))
break;
score += HSP_get_score(nh, query_pos, target_pos);
if(maxscore <= score){
maxscore = score;
maxext = extend;
} else {
if(score < 0) /* See note below */
break;
if((maxscore-score) >= nh->hsp_set->param->dropoff)
break;
}
query_pos += HSP_query_advance(nh);
target_pos += HSP_target_advance(nh);
}
nh->score = maxscore;
nh->length += maxext;
g_assert(HSP_check(nh));
return;
}
/* The score cannot be allowed to drop below zero in the HSP,
* as this can result in overlapping HSPs in some circurmstances.
*/
static HSP *HSP_create(HSP *nh){
register HSP *hsp = RecycleBin_alloc(nh->hsp_set->hsp_recycle);
hsp->hsp_set = nh->hsp_set;
hsp->query_start = nh->query_start;
hsp->target_start = nh->target_start;
hsp->length = nh->length;
hsp->score = nh->score;
hsp->cobs = nh->cobs; /* Value can be set by HSPset_finalise(); */
return hsp;
}
void HSP_destroy(HSP *hsp){
register HSPset *hsp_set = hsp->hsp_set;
RecycleBin_recycle(hsp_set->hsp_recycle, hsp);
return;
}
static void HSP_trim_ends(HSP *hsp){
register gint i;
register gint query_pos, target_pos;
/* Trim left to first good match */
g_assert(HSP_check(hsp));
for(i = 0; i < hsp->length; i++){
if(HSP_get_score(hsp, hsp->query_start, hsp->target_start) > 0)
break;
hsp->query_start += HSP_query_advance(hsp);
hsp->target_start += HSP_target_advance(hsp);
}
hsp->length -= i;
g_assert(HSP_check(hsp));
query_pos = HSP_query_end(hsp) - HSP_query_advance(hsp);
target_pos = HSP_target_end(hsp) - HSP_target_advance(hsp);
/* Trim right to last good match */
while(hsp->length > 0){
g_assert(HSP_check_positions(hsp->hsp_set,
query_pos, target_pos));
if(HSP_get_score(hsp, query_pos, target_pos) > 0)
break;
hsp->length
query_pos -= HSP_query_advance(hsp);
target_pos -= HSP_target_advance(hsp);
}
g_assert(HSP_check(hsp));
return;
}
/* This is to remove any unmatching ends from the HSP seed.
*/
static gboolean <API key>(gpointer low, gpointer high,
gpointer user_data){
register HSP *hsp_low = (HSP*)low, *hsp_high = (HSP*)high;
return hsp_low->score - hsp_high->score;
}
static void HSP_store(HSP *nascent_hsp){
register HSPset *hsp_set = nascent_hsp->hsp_set;
register PQueue *pq;
register HSP *hsp = NULL;
g_assert(nascent_hsp);
if(nascent_hsp->score < hsp_set->param->threshold)
return;
if(hsp_set->param->has->filter_threshold){ /* If have filter */
/* Get cobs value */
nascent_hsp->cobs = HSP_find_cobs(nascent_hsp);
pq = hsp_set->filter[HSP_query_cobs(nascent_hsp)];
if(pq){ /* Put in PQueue if better than worst */
if(PQueue_total(pq)
< hsp_set->param->has->filter_threshold){
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
} else {
g_assert(PQueue_total(pq));
hsp = PQueue_top(pq);
if(hsp->score < nascent_hsp->score){
hsp = PQueue_pop(pq);
HSP_destroy(hsp);
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
}
}
} else {
pq = PQueue_create(hsp_set->pqueue_set,
<API key>, NULL);
hsp_set->filter[HSP_query_cobs(nascent_hsp)] = pq;
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
hsp_set->is_empty = FALSE;
}
} else {
hsp = HSP_create(nascent_hsp);
g_ptr_array_add(hsp_set->hsp_list, hsp);
hsp_set->is_empty = FALSE;
}
return;
}
/* FIXME: optimisation: could store HSPs as a list up until
* filter_threshold, then convert to a PQueue
*/
void HSPset_seed_hsp(HSPset *hsp_set,
guint query_start, guint target_start){
register gint diag_pos
= ((target_start * hsp_set->param->match->query->advance)
-(query_start * hsp_set->param->match->target->advance));
register gint query_frame = query_start
% hsp_set->param->match->query->advance,
target_frame = target_start
% hsp_set->param->match->target->advance;
register gint section_pos = (diag_pos + hsp_set->query->len)
% hsp_set->query->len;
HSP nascent_hsp;
g_assert(!hsp_set->is_finalised);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->query->len);
/* Check whether we have seen this HSP already */
if(target_start < hsp_set->horizon[0]
[section_pos]
[query_frame]
[target_frame])
return;
if(hsp_set->param->seed_repeat > 1){
if(++hsp_set->horizon[1][section_pos][query_frame][target_frame]
< hsp_set->param->seed_repeat)
return;
hsp_set->horizon[1][section_pos][query_frame][target_frame] = 0;
}
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
hsp_set->horizon[0][section_pos][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
hsp_set->horizon[0][section_pos][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
void <API key>(HSPset *hsp_set,
guint query_start, guint target_start,
guint length){
HSP nascent_hsp;
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = length;
nascent_hsp.cobs = 0;
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
HSP_store(&nascent_hsp);
return;
}
static void <API key>(HSPset *hsp_set,
guint query_start, guint target_start,
gint ***horizon){
HSP nascent_hsp;
register gint diag_pos
= ((target_start * hsp_set->param->match->query->advance)
-(query_start * hsp_set->param->match->target->advance));
register gint query_frame = query_start
% hsp_set->param->match->query->advance,
target_frame = target_start
% hsp_set->param->match->target->advance;
register gint section_pos = (diag_pos + hsp_set->query->len)
% hsp_set->query->len;
g_assert(!hsp_set->is_finalised);
g_assert(!hsp_set->horizon);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->query->len);
if(horizon[1][query_frame][target_frame] != section_pos){
horizon[1][query_frame][target_frame] = section_pos;
horizon[0][query_frame][target_frame] = 0;
horizon[2][query_frame][target_frame] = 0;
}
if(++horizon[2][query_frame][target_frame] < hsp_set->param->seed_repeat)
return;
horizon[2][query_frame][target_frame] = 0;
/* Check whether we have seen this HSP already */
if(target_start < horizon[0][query_frame][target_frame])
return;
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
horizon[0][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
horizon[0][query_frame][target_frame] = HSP_target_end(&nascent_hsp);
return;
}
/* horizon[0] = diag
* horizon[1] = target_end
* horizon[2] = repeat_count
*/
/* Need to use the global to pass q,t advance to qsort compare func */
static HSPset *<API key> = NULL;
static int HSPset_seed_compare(const void *a, const void *b){
register guint *seed_a = (guint*)a,
*seed_b = (guint*)b;
register gint diag_a, diag_b;
register HSPset *hsp_set = <API key>;
g_assert(hsp_set);
diag_a = ((seed_a[1] * hsp_set->param->match->query->advance)
- (seed_a[0] * hsp_set->param->match->target->advance)),
diag_b = ((seed_b[1] * hsp_set->param->match->query->advance)
- (seed_b[0] * hsp_set->param->match->target->advance));
if(diag_a == diag_b)
return seed_a[0] - seed_b[0];
return diag_a - diag_b;
}
void <API key>(HSPset *hsp_set,
guint *seed_list, guint seed_list_len){
register gint i;
register gint ***horizon;
register gint qpos, tpos;
if(seed_list_len > 1){
<API key> = hsp_set;
qsort(seed_list, seed_list_len, sizeof(guint) << 1,
HSPset_seed_compare);
<API key> = NULL;
}
if(seed_list_len){
horizon = (gint***)Matrix3d_create(3,
hsp_set->param->match->query->advance,
hsp_set->param->match->target->advance,
sizeof(gint));
for(i = 0; i < seed_list_len; i++){
<API key>(hsp_set,
seed_list[(i << 1)],
seed_list[(i << 1) + 1],
horizon);
qpos = seed_list[(i << 1)];
tpos = seed_list[(i << 1) + 1];
}
g_free(horizon);
}
HSPset_finalise(hsp_set);
return;
}
HSPset *HSPset_finalise(HSPset *hsp_set){
register gint i;
register HSP *hsp;
register PQueue *pq;
g_assert(!hsp_set->is_finalised);
hsp_set->is_finalised = TRUE;
if(hsp_set->param->has->filter_threshold && (!hsp_set->is_empty)){
/* Get HSPs from each PQueue */
for(i = 0; i < hsp_set->query->len; i++){
pq = hsp_set->filter[i];
if(pq){
while(PQueue_total(pq)){
hsp = PQueue_pop(pq);
g_ptr_array_add(hsp_set->hsp_list, hsp);
}
}
}
}
/* Set cobs for each HSP */
if(!hsp_set->param->has->filter_threshold){
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
hsp->cobs = HSP_find_cobs(hsp);
}
}
hsp_set->is_finalised = TRUE;
return hsp_set;
}
static int <API key>(const void *a,
const void *b){
register HSP **hsp_a = (HSP**)a, **hsp_b = (HSP**)b;
register gint diag_a = HSP_diagonal(*hsp_a),
diag_b = HSP_diagonal(*hsp_b);
if(diag_a == diag_b)
return (*hsp_a)->query_start - (*hsp_b)->query_start;
return diag_a - diag_b;
}
static Match_Score HSP_score_overlap(HSP *left, HSP *right){
register Match_Score score = 0;
register gint query_pos, target_pos;
g_assert(left->hsp_set == right->hsp_set);
g_assert(HSP_diagonal(left) == HSP_diagonal(right));
query_pos = HSP_query_end(left) - HSP_query_advance(left);
target_pos = HSP_target_end(left) - HSP_target_advance(left);
while(query_pos >= right->query_start){
score += HSP_get_score(left, query_pos, target_pos);
query_pos -= HSP_query_advance(left);
target_pos -= HSP_target_advance(left);
}
query_pos = right->query_start;
target_pos = right->target_start;
while(query_pos < (HSP_query_end(left)- HSP_query_advance(right))){
score += HSP_get_score(right, query_pos, target_pos);
query_pos += HSP_query_advance(right);
target_pos += HSP_target_advance(right);
}
return score;
}
/* Returns score for overlapping region of HSPs on same diagonal */
void <API key>(HSPset *hsp_set){
register GPtrArray *new_hsp_list;
register HSP *curr_hsp, *prev_hsp;
register gboolean del_prev, del_curr;
register gint i;
register Match_Score score;
/* Filter strongly overlapping HSPs on same diagonal
* but different frames (happens with 3:3 HSPs only)
*/
if((hsp_set->hsp_list->len > 1)
&& (hsp_set->param->match->query->advance == 3)
&& (hsp_set->param->match->target->advance == 3)){
/* FIXME: should not sort when using all-at-once HSPset */
qsort(hsp_set->hsp_list->pdata, hsp_set->hsp_list->len,
sizeof(gpointer), <API key>);
prev_hsp = hsp_set->hsp_list->pdata[0];
del_prev = FALSE;
del_curr = FALSE;
new_hsp_list = g_ptr_array_new();
for(i = 1; i < hsp_set->hsp_list->len; i++){
curr_hsp = hsp_set->hsp_list->pdata[i];
del_curr = FALSE;
if((HSP_diagonal(prev_hsp) == HSP_diagonal(curr_hsp))
&& (HSP_query_end(prev_hsp) > curr_hsp->query_start)){
score = HSP_score_overlap(prev_hsp, curr_hsp);
if((score << 1) > (curr_hsp->score + prev_hsp->score)){
/* FIXME: use codon_usage scores here instead */
if(prev_hsp->score < curr_hsp->score){
del_prev = TRUE;
} else {
del_curr = TRUE;
}
}
}
if(del_prev)
HSP_destroy(prev_hsp);
else
g_ptr_array_add(new_hsp_list, prev_hsp);
prev_hsp = curr_hsp;
del_prev = del_curr;
}
if(del_prev)
HSP_destroy(prev_hsp);
else
g_ptr_array_add(new_hsp_list, prev_hsp);
g_ptr_array_free(hsp_set->hsp_list, TRUE);
hsp_set->hsp_list = new_hsp_list;
}
return;
}
#define <API key> 10
#define <API key> (1 << <API key>)
RecycleBin *<API key>(void){
return RecycleBin_create("HSPset_Slist", sizeof(HSPset_SList_Node),
4096);
}
HSPset_SList_Node *HSPset_SList_append(RecycleBin *recycle_bin,
HSPset_SList_Node *next,
gint query_pos, gint target_pos){
register HSPset_SList_Node *node = RecycleBin_alloc(recycle_bin);
node->next = next;
node->query_pos = query_pos;
node->target_pos = target_pos;
return node;
}
#if 0
typedef struct {
gint page_alloc;
gint page_total;
HSPset_SList_Node **diag_page_list;
gint ****horizon;
gint *page_used;
gint page_used_total;
} HSPset_SeedData;
static HSPset_SeedData *<API key>(HSP_Param *hsp_param,
gint target_len){
register HSPset_SeedData *seed_data = g_new(HSPset_SeedData, 1);
seed_data->page_total = (target_len
>> <API key>) + 1;
seed_data->page_alloc = seed_data->page_total;
seed_data->diag_page_list = g_new0(HSPset_SList_Node*, seed_data->page_total);
seed_data->page_used = g_new(gint, seed_data->page_total);
seed_data->horizon = (gint****)Matrix4d_create(
2 + ((hsp_param->seed_repeat > 1)?1:0),
<API key>,
hsp_param->match->query->advance,
hsp_param->match->target->advance,
sizeof(gint));
seed_data->page_used_total = 0;
return seed_data;
}
static void <API key>(HSPset_SeedData *seed_data){
g_free(seed_data->diag_page_list);
g_free(seed_data->page_used);
g_free(seed_data->horizon);
g_free(seed_data);
return;
}
static void <API key>(HSPset_SeedData *seed_data,
HSPset *hsp_set){
register gint new_page_total = (hsp_set->target->len
>> <API key>) + 1;
register gint i, a, b, c, d;
seed_data->page_total = new_page_total;
if(seed_data->page_alloc < new_page_total){
seed_data->page_alloc = seed_data->page_total;
g_free(seed_data->diag_page_list);
seed_data->diag_page_list = g_new(HSPset_SList_Node*,
seed_data->page_total);
g_free(seed_data->page_used);
seed_data->page_used = g_new(gint, seed_data->page_total);
}
/* Clear diag_page_list */
for(i = 0; i < seed_data->page_total; i++)
seed_data->diag_page_list[i] = 0;
/* Clear horizon */
for(a = 2 + ((hsp_set->param->seed_repeat > 1)?1:0); a >= 0; a
for(b = <API key>; b >= 0; b
for(c = hsp_set->param->match->query->advance; c >= 0; c
for(d = hsp_set->param->match->target->advance; d >= 0; d
seed_data->horizon[a][b][c][d] = 0;
seed_data->page_used_total = 0;
return;
}
#endif
void <API key>(HSPset *hsp_set, HSPset_SList_Node *seed_list){
register gint page_total = (hsp_set->target->len
>> <API key>) + 1;
register HSPset_SList_Node **diag_page_list
= g_new0(HSPset_SList_Node*, page_total);
register gint *page_used = g_new(gint, page_total);
register gint ****horizon = (gint****)Matrix4d_create(
2 + ((hsp_set->param->seed_repeat > 1)?1:0),
<API key>,
hsp_set->param->match->query->advance,
hsp_set->param->match->target->advance,
sizeof(gint));
/*
register HSPset_SeedData *seed_data = <API key>(hsp_set->param,
hsp_set->target->len);
*/
register gint i, page, diag_pos, query_frame, target_frame,
section_pos, page_pos;
register HSPset_SList_Node *seed;
register gint page_used_total = 0;
HSP nascent_hsp;
/* g_message("[%s] with [%d]", __FUNCTION__, hsp_set->target->len); */
/* <API key>(seed_data, hsp_set); */
/* Bin on diagonal into pages */
while(seed_list){
seed = seed_list;
seed_list = seed_list->next;
diag_pos = (seed->target_pos
* hsp_set->param->match->query->advance)
- (seed->query_pos
* hsp_set->param->match->target->advance);
section_pos = ((diag_pos + hsp_set->target->len)
% hsp_set->target->len);
page = (section_pos >> <API key>);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->target->len);
g_assert(page >= 0);
g_assert(page < page_total);
if(!diag_page_list[page])
page_used[page_used_total++] = page;
seed->next = diag_page_list[page];
diag_page_list[page] = seed;
}
/* Seed each page using page horizon */
for(i = 0; i < page_used_total; i++){
page = page_used[i];
for(seed = diag_page_list[page]; seed; seed = seed->next){
g_assert((!seed->next)
|| (seed->query_pos <= seed->next->query_pos));
diag_pos = (seed->target_pos
* hsp_set->param->match->query->advance)
- (seed->query_pos
* hsp_set->param->match->target->advance);
query_frame = seed->query_pos
% hsp_set->param->match->query->advance;
target_frame = seed->target_pos
% hsp_set->param->match->target->advance;
section_pos = ((diag_pos + hsp_set->target->len)
% hsp_set->target->len);
page_pos = section_pos
- (page << <API key>);
g_assert(page_pos >= 0);
g_assert(page_pos < <API key>);
/* Clear if page has changed */
if(horizon[1][page_pos][query_frame][target_frame] != page){
horizon[0][page_pos][query_frame][target_frame] = 0;
horizon[1][page_pos][query_frame][target_frame] = page;
if(hsp_set->param->seed_repeat > 1)
horizon[2][page_pos][query_frame][target_frame] = 0;
}
if(seed->query_pos < horizon[0][page_pos][query_frame][target_frame])
continue;
if(hsp_set->param->seed_repeat > 1){
if(++horizon[2][page_pos][query_frame][target_frame]
< hsp_set->param->seed_repeat){
continue;
}
horizon[2][page_pos][query_frame][target_frame] = 0;
}
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = seed->query_pos;
nascent_hsp.target_start = seed->target_pos;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
horizon[0][page_pos][query_frame][target_frame]
= HSP_query_end(&nascent_hsp);
continue;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
horizon[0][page_pos][query_frame][target_frame]
= HSP_query_end(&nascent_hsp);
}
}
g_free(diag_page_list);
g_free(page_used);
g_free(horizon);
HSPset_finalise(hsp_set);
/* <API key>(seed_data); */
return;
}
/* horizon[horizon][mailbox][seed_repeat]
* [page_size][qadv][tadv]
*/
|
package com.redhat.lightblue.hystrix.ldap;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.<API key>;
import com.netflix.hystrix.HystrixCommandKey;
import com.unboundid.ldap.sdk.LDAPConnection;
public abstract class <API key><T> extends HystrixCommand<T>{
public static final String GROUPKEY = "ldap";
private final LDAPConnection connection;
public LDAPConnection getConnection(){
return connection;
}
public <API key>(LDAPConnection connection, String commandKey){
super(HystrixCommand.Setter.withGroupKey(<API key>.Factory.asKey(GROUPKEY)).
andCommandKey(HystrixCommandKey.Factory.asKey(GROUPKEY + ":" + commandKey)));
this.connection = connection;
}
}
|
#include "intfile.hh"
dcmplx Pf8(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
dcmplx y[149];
dcmplx FOUT;
dcmplx MYI(0.,1.);
y[1]=1./bi;
y[2]=em[0];
y[3]=x0*x0;
y[4]=em[3];
y[5]=em[1];
y[6]=em[2];
y[7]=esx[0];
y[8]=y[1]*y[5];
y[9]=-(y[1]*y[7]);
y[10]=-x1;
y[11]=1.+y[10];
y[12]=x0*y[1]*y[2];
y[13]=y[1]*y[2]*y[3];
y[14]=2.*x2*y[1]*y[2]*y[3];
y[15]=y[1]*y[3]*y[5];
y[16]=x0*y[1]*y[6];
y[17]=x0*y[1]*y[4];
y[18]=2.*x1*y[1]*y[3]*y[4];
y[19]=-(y[1]*y[3]*y[7]);
y[20]=y[12]+y[13]+y[14]+y[15]+y[16]+y[17]+y[18]+y[19];
y[21]=-x0;
y[22]=1.+y[21];
y[23]=x2*x2;
y[24]=x1*x1;
y[25]=lrs[0];
y[26]=x2*y[1]*y[2];
y[27]=2.*x0*x1*y[1]*y[5];
y[28]=x1*y[1]*y[6];
y[29]=x1*y[1]*y[4];
y[30]=2.*x0*y[1]*y[4]*y[24];
y[31]=x1*x2*y[1]*y[2];
y[32]=2.*x0*x1*x2*y[1]*y[2];
y[33]=y[1]*y[2]*y[23];
y[34]=2.*x0*x1*y[1]*y[2]*y[23];
y[35]=x1*y[1]*y[5];
y[36]=x2*y[1]*y[5];
y[37]=2.*x0*x1*x2*y[1]*y[5];
y[38]=x1*x2*y[1]*y[6];
y[39]=y[1]*y[4]*y[24];
y[40]=x1*x2*y[1]*y[4];
y[41]=2.*x0*x2*y[1]*y[4]*y[24];
y[42]=-(x1*y[1]*y[7]);
y[43]=-(x2*y[1]*y[7]);
y[44]=-2.*x0*x1*x2*y[1]*y[7];
y[45]=y[8]+y[26]+y[27]+y[28]+y[29]+y[30]+y[31]+y[32]+y[33]+y[34]+y[35]+y[36]\
+y[37]+y[38]+y[39]+y[40]+y[41]+y[42]+y[43]+y[44];
y[46]=lrs[1];
y[47]=-x2;
y[48]=1.+y[47];
y[49]=y[1]*y[2];
y[50]=x1*y[1]*y[2];
y[51]=2.*x0*x1*y[1]*y[2];
y[52]=2.*x2*y[1]*y[2];
y[53]=4.*x0*x1*x2*y[1]*y[2];
y[54]=-2.*x0*x1*y[1]*y[7];
y[55]=y[8]+y[9]+y[27]+y[28]+y[29]+y[30]+y[49]+y[50]+y[51]+y[52]+y[53]+y[54];
y[56]=lambda*lambda;
y[57]=2.*x0*x2*y[1]*y[2];
y[58]=2.*x0*y[1]*y[2]*y[23];
y[59]=2.*x0*y[1]*y[5];
y[60]=2.*x0*x2*y[1]*y[5];
y[61]=y[1]*y[6];
y[62]=x2*y[1]*y[6];
y[63]=y[1]*y[4];
y[64]=2.*x1*y[1]*y[4];
y[65]=4.*x0*x1*y[1]*y[4];
y[66]=x2*y[1]*y[4];
y[67]=4.*x0*x1*x2*y[1]*y[4];
y[68]=-2.*x0*x2*y[1]*y[7];
y[69]=y[8]+y[9]+y[26]+y[57]+y[58]+y[59]+y[60]+y[61]+y[62]+y[63]+y[64]+y[65]+\
y[66]+y[67]+y[68];
y[70]=x0*x2*y[1]*y[2];
y[71]=x2*y[1]*y[2]*y[3];
y[72]=y[1]*y[2]*y[3]*y[23];
y[73]=x0*y[1]*y[5];
y[74]=x2*y[1]*y[3]*y[5];
y[75]=x0*x2*y[1]*y[6];
y[76]=2.*x0*x1*y[1]*y[4];
y[77]=x0*x2*y[1]*y[4];
y[78]=2.*x1*x2*y[1]*y[3]*y[4];
y[79]=-(x0*y[1]*y[7]);
y[80]=-(x2*y[1]*y[3]*y[7]);
y[81]=y[15]+y[16]+y[17]+y[18]+y[61]+y[70]+y[71]+y[72]+y[73]+y[74]+y[75]+y[76\
]+y[77]+y[78]+y[79]+y[80];
y[82]=lrs[2];
y[83]=2.*x1*x2*y[1]*y[2];
y[84]=2.*x1*y[1]*y[2]*y[23];
y[85]=2.*x1*y[1]*y[5];
y[86]=2.*x1*x2*y[1]*y[5];
y[87]=2.*y[1]*y[4]*y[24];
y[88]=2.*x2*y[1]*y[4]*y[24];
y[89]=-2.*x1*x2*y[1]*y[7];
y[90]=y[83]+y[84]+y[85]+y[86]+y[87]+y[88]+y[89];
y[91]=-(lambda*MYI*x0*y[22]*y[25]*y[90]);
y[92]=-(lambda*MYI*y[22]*y[25]*y[45]);
y[93]=lambda*MYI*x0*y[25]*y[45];
y[94]=1.+y[91]+y[92]+y[93];
y[95]=2.*x0*y[1]*y[4];
y[96]=2.*y[1]*y[3]*y[4];
y[97]=2.*x2*y[1]*y[3]*y[4];
y[98]=y[95]+y[96]+y[97];
y[99]=-(lambda*MYI*x1*y[11]*y[46]*y[98]);
y[100]=-(lambda*MYI*y[11]*y[46]*y[81]);
y[101]=lambda*MYI*x1*y[46]*y[81];
y[102]=1.+y[99]+y[100]+y[101];
y[103]=x0*x1*y[1]*y[2];
y[104]=x1*y[1]*y[2]*y[3];
y[105]=2.*x1*x2*y[1]*y[2]*y[3];
y[106]=x1*y[1]*y[3]*y[5];
y[107]=x0*x1*y[1]*y[6];
y[108]=x0*x1*y[1]*y[4];
y[109]=y[1]*y[3]*y[4]*y[24];
y[110]=-(x1*y[1]*y[3]*y[7]);
y[111]=y[12]+y[57]+y[61]+y[73]+y[79]+y[103]+y[104]+y[105]+y[106]+y[107]+y[10\
8]+y[109]+y[110];
y[112]=-(lambda*MYI*x1*y[11]*y[46]*y[81]);
y[113]=x1+y[112];
y[114]=-(lambda*MYI*x0*y[22]*y[25]*y[45]);
y[115]=x0+y[114];
y[116]=-(lambda*MYI*x2*y[48]*y[82]*y[111]);
y[117]=x2+y[116];
y[118]=pow(bi,-2);
y[119]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[55]*y[56]*y[69];
y[120]=-(lambda*MYI*x1*y[11]*y[20]*y[46]*y[94]);
y[121]=y[119]+y[120];
y[122]=lambda*MYI*x2*y[20]*y[48]*y[82]*y[121];
y[123]=-(x0*x1*y[11]*y[20]*y[22]*y[25]*y[46]*y[56]*y[69]);
y[124]=lambda*MYI*x0*y[22]*y[25]*y[55]*y[102];
y[125]=y[123]+y[124];
y[126]=-(lambda*MYI*x2*y[48]*y[55]*y[82]*y[125]);
y[127]=pow(y[69],2);
y[128]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[56]*y[127];
y[129]=y[94]*y[102];
y[130]=y[128]+y[129];
y[131]=2.*x0*y[1]*y[2];
y[132]=2.*x1*y[1]*y[2]*y[3];
y[133]=y[131]+y[132];
y[134]=-(lambda*MYI*x2*y[48]*y[82]*y[133]);
y[135]=-(lambda*MYI*y[48]*y[82]*y[111]);
y[136]=lambda*MYI*x2*y[82]*y[111];
y[137]=1.+y[134]+y[135]+y[136];
y[138]=y[130]*y[137];
y[139]=y[122]+y[126]+y[138];
y[140]=y[1]*y[113];
y[141]=y[1]*y[113]*y[115];
y[142]=y[1]*y[117];
y[143]=y[1]*y[113]*y[115]*y[117];
y[144]=y[1]+y[140]+y[141]+y[142]+y[143];
y[145]=pow(y[144],-2);
y[146]=pow(y[115],2);
y[147]=pow(y[113],2);
y[148]=pow(y[117],2);
FOUT=myLog(bi)*y[118]*y[139]*y[145]+myLog(x0)*y[118]*y[139]*y[145]+myLog(1.+\
y[92])*y[118]*y[139]*y[145]+3.*myLog(y[144])*y[118]*y[139]*y[145]-2.*myLog(\
y[61]+y[1]*y[6]*y[113]+y[1]*y[5]*y[115]+y[1]*y[4]*y[113]*y[115]+y[1]*y[5]*y\
[113]*y[115]+y[1]*y[6]*y[113]*y[115]-y[1]*y[7]*y[113]*y[115]+y[1]*y[6]*y[11\
7]+y[1]*y[2]*y[115]*y[117]+y[1]*y[5]*y[115]*y[117]-y[1]*y[7]*y[115]*y[117]+\
y[1]*y[2]*y[113]*y[115]*y[117]+y[1]*y[4]*y[113]*y[115]*y[117]+y[1]*y[6]*y[1\
13]*y[115]*y[117]+y[1]*y[5]*y[113]*y[146]+y[1]*y[2]*y[113]*y[117]*y[146]+y[\
1]*y[5]*y[113]*y[117]*y[146]-y[1]*y[7]*y[113]*y[117]*y[146]+y[1]*y[4]*y[115\
]*y[147]+y[1]*y[4]*y[146]*y[147]+y[1]*y[4]*y[117]*y[146]*y[147]+y[1]*y[2]*y\
[115]*y[148]+y[1]*y[2]*y[113]*y[146]*y[148])*y[118]*y[139]*y[145];
return (FOUT);
}
|
package com.stacksync.desktop.watch.local;
import java.io.File;
import org.apache.log4j.Logger;
import com.stacksync.desktop.Environment;
import com.stacksync.desktop.Environment.OperatingSystem;
import com.stacksync.desktop.config.Config;
import com.stacksync.desktop.config.Folder;
import com.stacksync.desktop.config.profile.Profile;
import com.stacksync.desktop.index.Indexer;
import com.stacksync.desktop.util.FileUtil;
/**
*
* @author oubou68, pheckel
*/
public abstract class LocalWatcher {
protected final Logger logger = Logger.getLogger(LocalWatcher.class.getName());
protected static final Environment env = Environment.getInstance();
protected static LocalWatcher instance;
protected Config config;
protected Indexer indexer;
public LocalWatcher() {
initDependencies();
logger.info("Creating watcher ...");
}
private void initDependencies() {
config = Config.getInstance();
indexer = Indexer.getInstance();
}
public void queueCheckFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.debug("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// File vanished!
if (!file.exists()) {
logger.warn("Watcher: File "+file+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Checking new/modified file "+file);
indexer.queueChecked(root, file);
}
public void queueMoveFile(Folder fromRoot, File fromFile, Folder toRoot, File toFile) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(fromRoot, fromFile) || FileUtil.checkIgnoreFile(toRoot, toFile)) {
logger.info("Watcher: Ignoring file "+fromFile.getAbsolutePath());
return;
}
// File vanished!
if (!toFile.exists()) {
logger.warn("Watcher: File "+toFile+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Moving file "+fromFile+" TO "+toFile+"");
indexer.queueMoved(fromRoot, fromFile, toRoot, toFile);
}
public void queueDeleteFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.info("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// Add to queue
logger.info("Watcher: Deleted file "+file+"");
indexer.queueDeleted(root, file);
}
public static synchronized LocalWatcher getInstance() {
if (instance != null) {
return instance;
}
if (env.getOperatingSystem() == OperatingSystem.Linux
|| env.getOperatingSystem() == OperatingSystem.Windows
|| env.getOperatingSystem() == OperatingSystem.Mac) {
instance = new CommonLocalWatcher();
return instance;
}
throw new RuntimeException("Your operating system is currently not supported: " + System.getProperty("os.name"));
}
public abstract void start();
public abstract void stop();
public abstract void watch(Profile profile);
public abstract void unwatch(Profile profile);
}
|
<roundcube:include file="includes/layout.html" />
<div class="content frame-content">
<roundcube:object name="dialogcontent" />
</div>
<roundcube:include file="includes/footer.html" />
|
define([],function(){
'use strict'
/**
* Implements unique() using the browser's sort().
*
* @param a
* The array to sort and strip of duplicate values.
* Warning: this array will be modified in-place.
* @param compFn
* A custom comparison function that accepts two values a and
* b from the given array and returns -1, 0, 1 depending on
* whether a < b, a == b, a > b respectively.
*
* If no compFn is provided, the algorithm will use the
* browsers default sort behaviour and loose comparison to
* detect duplicates.
* @return
* The given array.
*/
function sortUnique(a, compFn){
var i;
if (compFn) {
a.sort(compFn);
for (i = 1; i < a.length; i++) {
if (0 === compFn(a[i], a[i - 1])) {
a.splice(i
}
}
} else {
a.sort();
for (i = 1; i < a.length; i++) {
// Use loosely typed comparsion if no compFn is given
// to avoid sortUnique( [6, "6", 6] ) => [6, "6", 6]
if (a[i] == a[i - 1]) {
a.splice(i
}
}
}
return a;
}
/**
* Shallow comparison of two arrays.
*
* @param a, b
* The arrays to compare.
* @param equalFn
* A custom comparison function that accepts two values a and
* b from the given arrays and returns true or false for
* equal and not equal respectively.
*
* If no equalFn is provided, the algorithm will use the strict
* equals operator.
* @return
* True if all items in a and b are equal, false if not.
*/
function equal(a, b, equalFn) {
var i = 0, len = a.length;
if (len !== b.length) {
return false;
}
if (equalFn) {
for (; i < len; i++) {
if (!equalFn(a[i], b[i])) {
return false;
}
}
} else {
for (; i < len; i++) {
if (a[i] !== b[i]) {
return false;
}
}
}
return true;
}
function map(a, fn) {
var i, len, result = [];
for (i = 0, len = a.length; i < len; i++) {
result.push(fn(a[i]));
}
return result;
}
function mapNative(a, fn) {
// Call map directly on the object instead of going through
// Array.prototype.map. This avoids the problem that we may get
// passed an array-like object (NodeList) which may cause an
// error if the implementation of Array.prototype.map can only
// deal with arrays (Array.prototype.map may be native or
// provided by a javscript framework).
return a.map(fn);
}
return {
sortUnique: sortUnique,
equal: equal,
map: Array.prototype.map ? mapNative : map
};
});
|
import logging
from borgmatic.borg.flags import make_flags, <API key>
from borgmatic.execute import execute_command
logger = logging.getLogger(__name__)
# A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a
# non-checkpoint archive name ends in a digit (e.g. from a timestamp).
<API key> = '*[0123456789]'
def <API key>(repository, archive, storage_config, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, an archive name, a storage config dict, a local Borg
path, and a remote Borg path, simply return the archive name. But if the archive name is
"latest", then instead introspect the repository for the latest successful (non-checkpoint)
archive, and return its name.
Raise ValueError if "latest" is given but there are no archives in the repository.
'''
if archive != "latest":
return archive
lock_wait = storage_config.get('lock_wait', None)
full_command = (
(local_path, 'list')
+ (('--info',) if logger.getEffectiveLevel() == logging.INFO else ())
+ (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ())
+ make_flags('remote-path', remote_path)
+ make_flags('lock-wait', lock_wait)
+ make_flags('glob-archives', <API key>)
+ make_flags('last', 1)
+ ('--short', repository)
)
output = execute_command(full_command, output_log_level=None, borg_local_path=local_path)
try:
latest_archive = output.strip().splitlines()[-1]
except IndexError:
raise ValueError('No archives found in the repository')
logger.debug('{}: Latest archive is {}'.format(repository, latest_archive))
return latest_archive
def list_archives(repository, storage_config, list_arguments, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, a storage config dict, and the arguments to the list
action, display the output of listing Borg archives in the repository or return JSON output. Or,
if an archive name is given, listing the files in that archive.
'''
lock_wait = storage_config.get('lock_wait', None)
if list_arguments.successful:
list_arguments.glob_archives = <API key>
full_command = (
(local_path, 'list')
+ (
('--info',)
if logger.getEffectiveLevel() == logging.INFO and not list_arguments.json
else ()
)
+ (
('--debug', '--show-rc')
if logger.isEnabledFor(logging.DEBUG) and not list_arguments.json
else ()
)
+ make_flags('remote-path', remote_path)
+ make_flags('lock-wait', lock_wait)
+ <API key>(
list_arguments, excludes=('repository', 'archive', 'paths', 'successful')
)
+ (
'::'.join((repository, list_arguments.archive))
if list_arguments.archive
else repository,
)
+ (tuple(list_arguments.paths) if list_arguments.paths else ())
)
return execute_command(
full_command,
output_log_level=None if list_arguments.json else logging.WARNING,
borg_local_path=local_path,
)
|
using System;
namespace NullConditional
{
class LoggingDemo
{
static void Main()
{
int x = 10;
Logger logger = new Logger();
logger.Debug?.Log($"Debug log entry");
logger.Info?.Log($"Info at {DateTime.UtcNow}; x={x}");
}
}
}
|
// a) the Lesser General Public Licence v3 (LGPL)
// Allors Platform is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
namespace Allors.Adapters.Object.SqlClient
{
using Allors.Meta;
using Adapters;
internal sealed class AssociationContains : Predicate
{
private readonly IObject allorsObject;
private readonly IAssociationType association;
internal AssociationContains(ExtentFiltered extent, IAssociationType association, IObject allorsObject)
{
extent.CheckAssociation(association);
PredicateAssertions.<API key>(association, allorsObject);
this.association = association;
this.allorsObject = allorsObject;
}
internal override bool BuildWhere(ExtentStatement statement, string alias)
{
var schema = statement.Mapping;
if ((this.association.IsMany && this.association.RoleType.IsMany) || !this.association.RelationType.<API key>)
{
statement.Append("\n");
statement.Append("EXISTS(\n");
statement.Append("SELECT " + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append("FROM " + schema.<API key>[this.association.RelationType] + "\n");
statement.Append("WHERE " + Mapping.<API key> + "=" + this.allorsObject.Strategy.ObjectId + "\n");
statement.Append("AND " + Mapping.ColumnNameForRole + "=" + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append(")");
}
else
{
statement.Append(" " + this.association.SingularFullName + "_A." + Mapping.ColumnNameForObject + " = " + this.allorsObject.Strategy.ObjectId);
}
return this.Include;
}
internal override void Setup(ExtentStatement statement)
{
statement.UseAssociation(this.association);
}
}
}
|
using System;
using System.Web;
using System.Web.Mvc;
using SmartStore.Core;
using SmartStore.Core.Domain.Catalog;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Media;
using SmartStore.Core.Html;
using SmartStore.Services.Catalog;
using SmartStore.Services.Media;
using SmartStore.Services.Orders;
using SmartStore.Web.Framework.Controllers;
namespace SmartStore.Web.Controllers
{
public partial class DownloadController : <API key>
{
private readonly IDownloadService _downloadService;
private readonly IProductService _productService;
private readonly IOrderService _orderService;
private readonly IWorkContext _workContext;
private readonly CustomerSettings _customerSettings;
public DownloadController(
IDownloadService downloadService,
IProductService productService,
IOrderService orderService,
IWorkContext workContext,
CustomerSettings customerSettings)
{
this._downloadService = downloadService;
this._productService = productService;
this._orderService = orderService;
this._workContext = workContext;
this._customerSettings = customerSettings;
}
private ActionResult <API key>(Download download, Product product, byte[] data)
{
if (data == null || data.LongLength == 0)
{
NotifyError(T("Common.Download.NoDataAvailable"));
return new RedirectResult(Url.Action("Info", "Customer"));
}
var fileName = (download.Filename.HasValue() ? download.Filename : download.Id.ToString());
var contentType = (download.ContentType.HasValue() ? download.ContentType : "application/octet-stream");
return new FileContentResult(data, contentType)
{
FileDownloadName = fileName + download.Extension
};
}
private ActionResult <API key>(Download download, Product product)
{
return <API key>(download, product, _downloadService.LoadDownloadBinary(download));
}
public ActionResult Sample(int productId)
{
var product = _productService.GetProductById(productId);
if (product == null)
return HttpNotFound();
if (!product.HasSampleDownload)
{
NotifyError(T("Common.Download.HasNoSample"));
return RedirectToAction("ProductDetails", "Product", new { productId = productId });
}
var download = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault());
if (download == null)
{
NotifyError(T("Common.Download.SampleNotAvailable"));
return RedirectToAction("ProductDetails", "Product", new { productId = productId });
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return <API key>(download, product);
}
public ActionResult GetDownload(Guid id, bool agree = false)
{
if (id == Guid.Empty)
return HttpNotFound();
var orderItem = _orderService.GetOrderItemByGuid(id);
if (orderItem == null)
return HttpNotFound();
var order = orderItem.Order;
var product = orderItem.Product;
var hasNotification = false;
if (!_downloadService.IsDownloadAllowed(orderItem))
{
hasNotification = true;
NotifyError(T("Common.Download.NotAllowed"));
}
if (_customerSettings.<API key>)
{
if (_workContext.CurrentCustomer == null)
return new <API key>();
if (order.CustomerId != _workContext.CurrentCustomer.Id)
{
hasNotification = true;
NotifyError(T("Account.CustomerOrders.NotYourOrder"));
}
}
var download = _downloadService.GetDownloadById(product.DownloadId);
if (download == null)
{
hasNotification = true;
NotifyError(T("Common.Download.NoDataAvailable"));
}
if (product.HasUserAgreement && !agree)
{
hasNotification = true;
}
if (!product.UnlimitedDownloads && orderItem.DownloadCount >= product.<API key>)
{
hasNotification = true;
NotifyError(T("Common.Download.MaxNumberReached", product.<API key>));
}
if (hasNotification)
{
return RedirectToAction("UserAgreement", "Customer", new { id = id });
}
if (download.UseDownloadUrl)
{
orderItem.DownloadCount++;
_orderService.UpdateOrder(order);
return new RedirectResult(download.DownloadUrl);
}
else
{
var data = _downloadService.LoadDownloadBinary(download);
if (data == null || data.LongLength == 0)
{
NotifyError(T("Common.Download.NoDataAvailable"));
return RedirectToAction("UserAgreement", "Customer", new { id = id });
}
orderItem.DownloadCount++;
_orderService.UpdateOrder(order);
return <API key>(download, product, data);
}
}
public ActionResult GetLicense(Guid id)
{
if (id == Guid.Empty)
return HttpNotFound();
var orderItem = _orderService.GetOrderItemByGuid(id);
if (orderItem == null)
return HttpNotFound();
var order = orderItem.Order;
var product = orderItem.Product;
if (!_downloadService.<API key>(orderItem))
{
NotifyError(T("Common.Download.NotAllowed"));
return RedirectToAction("<API key>", "Customer");
}
if (_customerSettings.<API key>)
{
if (_workContext.CurrentCustomer == null)
return new <API key>();
if (order.CustomerId != _workContext.CurrentCustomer.Id)
{
NotifyError(T("Account.CustomerOrders.NotYourOrder"));
return RedirectToAction("<API key>", "Customer");
}
}
var download = _downloadService.GetDownloadById(orderItem.LicenseDownloadId.HasValue ? orderItem.LicenseDownloadId.Value : 0);
if (download == null)
{
NotifyError(T("Common.Download.NotAvailable"));
return RedirectToAction("<API key>", "Customer");
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return <API key>(download, product);
}
public ActionResult GetFileUpload(Guid downloadId)
{
var download = _downloadService.GetDownloadByGuid(downloadId);
if (download == null)
{
NotifyError(T("Common.Download.NotAvailable"));
return RedirectToAction("<API key>", "Customer");
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return <API key>(download, null);
}
public ActionResult GetUserAgreement(int productId, bool? asPlainText)
{
var product = _productService.GetProductById(productId);
if (product == null)
return Content(T("Products.NotFound", productId));
if (!product.IsDownload || !product.HasUserAgreement || product.UserAgreementText.IsEmpty())
return Content(T("<API key>.HasNoUserAgreement"));
if (asPlainText ?? false)
{
var agreement = HtmlUtils.<API key>(product.UserAgreementText);
agreement = HtmlUtils.StripTags(HttpUtility.HtmlDecode(agreement));
return Content(agreement);
}
return Content(product.UserAgreementText);
}
}
}
|
<?
function auth_check_login()
{
ob_start();
session_start();
if ( $_SESSION["auth_id"] != "BVS@BIREME" ) {
ob_end_clean();
header("Location: /admin/index.php?error=TIMEOUT");
exit;
}
ob_end_clean();
}
?>
|
#ifndef <API key>
#define <API key>
#include <QWidget>
#include <QTime>
#include "src/chatlog/chatlinecontent.h"
#include "src/core/corestructs.h"
namespace Ui {
class FileTransferWidget;
}
class QVariantAnimation;
class QPushButton;
class FileTransferWidget : public QWidget
{
Q_OBJECT
public:
explicit FileTransferWidget(QWidget* parent, ToxFile file);
virtual ~FileTransferWidget();
void autoAcceptTransfer(const QString& path);
bool isActive() const;
protected slots:
void onFileTransferInfo(ToxFile file);
void <API key>(ToxFile file);
void <API key>(ToxFile file);
void <API key>(ToxFile file);
void <API key>(ToxFile file);
void <API key>(ToxFile file);
void <API key>(ToxFile file, bool paused);
void <API key>(ToxFile file, bool broken);
protected:
QString <API key>(qint64 size);
void hideWidgets();
void setupButtons();
void handleButton(QPushButton* btn);
void showPreview(const QString& filename);
void acceptTransfer(const QString& filepath);
void setBackgroundColor(const QColor& c, bool whiteFont);
void setButtonColor(const QColor& c);
bool <API key>() const;
virtual void paintEvent(QPaintEvent*) final override;
private slots:
void onTopButtonClicked();
void <API key>();
void <API key>();
private:
static QPixmap scaleCropIntoSquare(const QPixmap &source, int targetSize);
private:
Ui::FileTransferWidget *ui;
ToxFile fileInfo;
QTime lastTick;
quint64 lastBytesSent = 0;
QVariantAnimation* <API key> = nullptr;
QVariantAnimation* <API key> = nullptr;
QColor backgroundColor;
QColor buttonColor;
static const uint8_t <API key> = 4;
uint8_t meanIndex = 0;
qreal meanData[<API key>] = {0.0};
bool active;
};
#endif // <API key>
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example Mathematical Olympiad: XMO 2014 in Example Host Country Name</title>
<link rel="stylesheet" href="https:
</head>
<body>
<h1>XMO: XMO 2014 in <a href="/subdir/countries/country1/">Example Host Country Name</a></h1>
<table class="xmo-list">
<tr><th>XMO number</th><td>1</td></tr>
<tr><th>Year</th><td>2014 (<a href="http:
<tr><th>Country</th><td><a href="/subdir/countries/country1/">Example Host Country Name</a></td></tr>
<tr><th>City</th><td>Example Host City Name</td></tr>
<tr><th>Start date</th><td>2014-04-01</td></tr>
<tr><th>End date</th><td>2014-04-02</td></tr>
<tr><th>Contact name</th><td>Example Contact Name</td></tr>
<tr><th>Contact email</th><td>info@example.com</td></tr>
<tr><th>Participating teams</th><td>3 (<a href="/subdir/xmos/xmo1/countries/">list</a>)</td></tr>
<tr><th>Contestants</th><td>5 (<a href="/subdir/xmos/xmo1/scoreboard/">scoreboard</a>, <a href="/subdir/xmos/xmo1/people/">list of participants</a>, <a href="/subdir/xmos/xmo1/people/summary/">table of participants with photos</a>)</td></tr>
<tr><th>Number of exams</th><td>2</td></tr>
<tr><th>Number of problems</th><td>6 (marked out of: 7+7+7+7+7+7)</td></tr>
<tr><th>Gold medals</th><td>2 (scores ≥ 28)</td></tr>
<tr><th>Silver medals</th><td>1 (scores ≥ 21)</td></tr>
<tr><th>Bronze medals</th><td>1 (scores ≥ 14)</td></tr>
<tr><th>Honourable mentions</th><td>1</td></tr>
</table>
<!-- #include virtual="xmos/xmo1/extra.html" -->
<h2>Day 1 papers</h2>
<ul>
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="https:
</ul>
<h2>Day 2 papers</h2>
<ul>
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="https:
</ul>
</body>
</html>
|
#ifndef _AVISTRUCTURES_H_
#define _AVISTRUCTURES_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "DivXInt.h"
typedef struct <API key>
{
char cId[4];
uint32_t size;
char cType[4];
} AVIStructureHeader;
typedef AVIStructureHeader RiffHeader;
typedef AVIStructureHeader ListHeader;
typedef struct __AVIHeader__
{
int32_t dwMicroSecPerFrame; /* set to 0 ? */
int32_t dwMaxBytesPerSec; /* maximum transfer rate */
int32_t <API key>; /* pad to multiples of this size, normally 2K */
int32_t dwFlags;
int32_t dwTotalFrames; /* number of frames in first RIFF 'AVI ' chunk */
int32_t dwInitialFrames;
int32_t dwStreams;
int32_t <API key>;
int32_t dwWidth;
int32_t dwHeight;
int32_t dwReserved[4];
} AVIHeader;
typedef struct _AVIStreamHeader_
{
char cId[4];
int32_t size;
char ccType[4];
char ccHandler[4];
int32_t dwFlags; /* Contains AVITF_* flags */
int16_t wPriority;
int16_t wLanguage;
int32_t dwInitialFrames;
int32_t dwScale;
int32_t dwRate; /* dwRate / dwScale == samples/second */
int32_t dwStart;
int32_t dwLength; /* In units above... */
int32_t <API key>;
int32_t dwQuality;
int32_t dwSampleSize;
int16_t rcFrame_left;
int16_t rcFrame_top;
int16_t rcFrame_right;
int16_t rcFrame_bottom;
} AVIStreamHeader;
typedef struct _AviChunkHeader_
{
char cId[4];
uint32_t size;
} AVIChunkHeader;
typedef struct <API key>
{
uint32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t biPlanes;
int16_t biBitCount;
char cCompression[4];
uint32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
uint32_t biClrUsed;
uint32_t biClrImportant;
} <API key>, <API key>;
typedef struct <API key>
{
int16_t wFormatTag; /* format type */
int16_t nChannels; /* number of channels (i.e. mono, stereo...) */
int32_t nSamplesPerSec; /* sample rate */
int32_t nAvgBytesPerSec; /* for buffer estimation */
int16_t nBlockAlign; /* block size of data */
int16_t wBitsPerSample; /* number of bits per sample of mono data */
int16_t cbSize; /* the count in bytes of the size of extra information (after cbSize) */
#define AVI_STRF_MAX_EXTRA 22
uint8_t extra[AVI_STRF_MAX_EXTRA]; /* any extra information, e.g. mp3 needs this */
} <API key>;
typedef struct __AVI1IndexEntry__
{
char cId[4];
uint32_t dwFlags;
uint32_t dwOffset;
uint32_t dwSize;
} AVI1IndexEntry;
typedef struct _AVIStreamInfoDRM_
{
int32_t version;
uint32_t sizeDRMInfo;
uint8_t *drmInfo; /* encrpyted drm info. */
uint64_t drmOffset;
} AVIStreamInfoDRM;
#define <API key> ( sizeof( uint32_t ) + sizeof( int32_t ) )
typedef struct _DivXIdChunkHeader_
{
char cId[4];
uint32_t size;
uint32_t chunkId;
} DivXIdChunkHeader;
typedef struct MediaSourceType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t Reserved;
uint64_t RiffOffset;
} MediaSource;
typedef struct MediaTrackType
{
char FourCC[4];
uint32_t ChunkSize;
uint32_t ObjectID;
uint32_t MediaSourceID;
char TrackID[4];
int32_t StartTime;
int32_t EndTime;
int32_t LanguageCodeLen;
int16_t LanguageCode[2];
int32_t TranslationLookupID;
int32_t TypeLen;
int16_t Type[20];
} MediaTrack;
#define MTConstantSize ( sizeof( MediaTrack ) -\
( sizeof( int16_t ) *\
20 ) - ( 2 * sizeof( int32_t ) ) - ( sizeof( int16_t ) * 2 ) )
typedef struct <API key>
{
char FourCC[4];
uint32_t ChunkSize;
uint64_t Offset;
char VersionId[3];
uint32_t MenuVersion;
int32_t ObjectID;
int32_t StartingMenuID;
uint32_t <API key>;
uint16_t cDefLang[16 ];
} <API key>;
/* wchar default language string follows */
typedef struct DivxMediaMenuType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t BackgroundVideoID;
int32_t BackgroundAudioID;
int32_t StartingMenuItemID;
int32_t EnterAction;
int32_t ExitAction;
int32_t MenuTypeLen;
uint16_t MenuType[32];
int32_t MenuNameLen;
uint16_t MenuName[32];
} DivXMediaMenu;
#define DMMConstantSize ( sizeof( DivXMediaMenu ) -\
( 64 * sizeof( uint16_t ) ) - sizeof( int32_t ) )
typedef struct ButtonMenuType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t OverlayID;
int32_t UpAction;
int32_t DownAction;
int32_t LeftAction;
int32_t RightAction;
int32_t SelectAction;
int32_t ButtonNameLen;
int16_t ButtonName[64];
} ButtonMenu;
#define BMENConstantSize ( sizeof( ButtonMenu ) - ( 64 * sizeof( uint16_t ) ) )
typedef struct MenuRectangleType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t Left;
int32_t Top;
int32_t Width;
int32_t Height;
} MenuRectangle;
typedef struct LanguageMenusType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t LanguageCodeLen;
int16_t LanguageCode[2];
int32_t StartingMenuID;
int32_t RootMenuID;
} LanguageMenus;
typedef struct TranslationType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t LanguageCodeLen;
int16_t LanguageCode[2];
int32_t ValueLen;
} TranslationEntry;
typedef struct _StreamInfoStruct_
{
uint64_t riffOffset;
/* uint64_t indexOffset;
uint32_t moviOffset;
uint32_t headerOffset; */
uint8_t cFourCC[4];
uint8_t typeIndex;
uint8_t trackIndex;
uint8_t trackType;
uint64_t startFrame;
uint64_t endFrame;
uint64_t startTime;
uint64_t endTime;
uint32_t lookupId;
} StreamInfo;
#define VIDEO_TRACK 0
#define AUDIO_TRACK 1
#define SUBTITLE_TRACK 2
typedef struct <API key>
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
char TrackID[4];
} <API key>;
typedef struct <API key>
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
char TrackID[4];
} AudioSelectAction;
typedef struct <API key>
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
int32_t MediaObjectID;
} <API key>;
typedef struct <API key>
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t MenuID;
int32_t ButtonMenuID;
} <API key>;
typedef struct <API key>
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t ButtonMenuID;
} <API key>;
typedef struct PlayActionType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
int32_t MediaObjectID;
} PlayAction;
typedef struct _MenuInfo_
{
int32_t ObjectID;
int32_t BackgroundVideoID;
int32_t BackgroundAudioID;
int32_t StartingMenuItemID;
int32_t MenuTypeLen;
uint16_t MenuType[32];
int32_t MenuNameLen;
uint16_t MenuName[32];
} MenuInfo;
typedef struct TitleType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TranslationLookupID;
int32_t DefaultAudioLen;
int16_t DefaultAudioTrack[4];
int32_t DefaultSubtitleLen;
int16_t <API key>[4];
} TitleInfo;
typedef struct _ChapterInfo_
{
char FourCC[4];
uint32_t size;
int32_t ObjectId;
int32_t LookupId;
uint64_t startFrame;
uint64_t endFrame;
uint64_t startTime;
uint64_t endTime;
} ChapterInfo;
typedef struct _ChapterHeader_
{
char FourCC[4];
uint32_t size;
int32_t ObjectId;
int32_t LookupId;
} ChapterHeader;
typedef struct _ButtonInfo_
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t OverlayID;
int32_t UpAction;
int32_t DownAction;
int32_t LeftAction;
int32_t RightAction;
int32_t SelectAction;
int32_t ButtonNameLen;
int16_t ButtonName[64];
} ButtonInfo;
#ifdef __cplusplus
}
#endif
#endif /* _AVISTRUCTURES_H_ */
|
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Ghidra Java Coding Standards</title>
<style media="screen" type="text/css">
li { margin-left: 90px; font-family:times new roman; font-size:14pt; }
h1 { color:#000080; font-family:times new roman; font-size:36pt; font-style:italic; font-weight:bold; text-align:center; }
h2 { margin: 10px; margin-top: 40px; color:#984c4c; font-family:times new roman; font-size:18pt; font-weight:bold; }
h3 { margin-left: 37px; margin-top: 20px; color:#0000ff; font-family:times new roman; font-size:14pt; font-weight:bold; }
h4 { margin-left: 70px; margin-top: 10px; font-family:times new roman; font-size:14pt; font-weight:normal; }
h5 { margin-left: 70px; margin-top: 10px; font-family:times new roman; font-size:14pt; font-weight:normal; }
h6 { color:#000080; font-family:times new roman; font-size:18pt; font-style:italic; font-weight:bold; text-align:center; }
p { margin-left: 90px; font-family:times new roman; font-size:14pt; }
body {
counter-reset: section;
}
h2 {
counter-reset: topic;
}
h3 {
counter-reset: rule;
}
h2::before {
counter-increment: section;
content: counter(section) ": ";
}
h3::before {
counter-increment: topic;
content: counter(section) "." counter(topic) " ";
}
h4::before {
counter-increment: rule;
content: counter(section) "." counter(topic) "." counter(rule) " ";
}
div.info {
margin-left: 10px; margin-top: 80px; font-family:times new roman; font-size:18pt; font-weight:bold;
}
</style>
</head>
<body>
<H1> Ghidra's Java Style Guide </H1>
<H6> Ver 1.1 - 20190307 </H6>
<H2> Introduction </H2>
<P> The purpose of this document is to record the Ghidra team's accepted rules for code formatting, naming
conventions, code complexity, and other best practices. Many of the rules listed in this document
are not universal absolutes and many blur into areas of personal preferences. The purpose of these
types of rules is not to definitely state that one way is better than another, but that we
are consistent throughout the team.</P>
<P> Most of these rules came from one or more of the listed references at the end of this document. Many of
these rules were listed in just about every guide. Where they disagreed, We generally went with the majority.
Some rules seem arbitrary as to the actual value used, but that a value was needed seemed universal.
For example, just about every reference stated a maximum character line length. We think all were either
80 or 100. So everyone seems to think it is important to have some limit, but they don't agree to the actual number.</P>
<H3> Most Important Rules of All </H3>
<H4> Any of the rules or suggestions in this document can be broken, but you must document why breaking
the rule makes the code better. </H4>
<H4> Program for people, not machines. The primary goal of your development efforts should be that
your code is easy for other people to understand. </H4>
<H2> Naming Conventions </H2>
<H3> General Naming Rules </H3>
<H4> Names for classes, interfaces, methods, parameters, instance variables and long-lived local
variables should not contain abbreviations or acronyms except for well known ones (the abbreviation
is more commonly used than the full name) like URL and HTML. </H4>
<P> The following exceptions are allowed (The list can be expanded with majority approval) </P>
<UL>
<LI> Utils - can be used as a suffix for the name of a class of static utility methods (e.g., StringUtils) </LI>
</UL>
<H4> If an abbreviation or acronym is used, only the first letter should be capitalized. (Unless it
is the beginning of a method or variable name, in which case the first letter is also lower case.) </H4>
<P> For example, use fooUrl, not fooURL. </P>
<H3> Package Naming </H3>
<H4> Package names should start with ghidra.<module group>.<module name>. (e.g., ghidra.framework.docking.)</H4>
<H4> Package names should be all lower case, preferably one word and no abbreviations. </H4>
<H3> Class Naming </H3>
<H4> Class names should be nouns.</H4>
<H4> Class names should use upper CamelCase where the first letter of each word is capitalized.</H4>
<P> Examples: Table, FoldingTable, WoodTable </P>
<H4> Classes that extend other classes should use the base class name as a base and prepend it with what is more
specific about the extended class. </H4>
<P>For example, if the base class is "Truck", the subclasses would have names
like "DumpTruck", "DeliveryTruck", or "FlyingTruck". </P>
<H4> The design pattern of an interface with one or more implementations should use the following naming conventions:</H4>
<UL>
<LI> Foo - The interface should be named the fundamental thing. </LI>
<LI> AbstractFoo - An abstract implementation intended to be used as the base of a hierarchy of classes. </LI>
<LI> DefaultFoo - A "default" implementation that would be appropriate for the majority of use cases. </LI>
<LI> {descriptive}Foo - Other implementations should describe what makes them unique. </LI>
</UL>
<H4> Test class names should end with "Test" (e.g., FooTest).</H4>
<H4> Test doubles or stub objects should use the following naming rules: </H4>
<UL>
<LI> DummyFoo - a stub that returns empty or null values because they are irrelevant to the test. </LI>
<LI> SpyFoo - may provide values to the environment, but also records statistics. </LI>
<LI> MockFoo - provides values to the environment and usually has some form of expectations. </LI>
<LI> FakeFoo - replaces real functionality with a simplified version (like replacing Database access with in-memory data). </LI>
</UL>
<H3> Interface Naming </H3>
<H4> Interface names should be nouns, or adjectives ending with "able" such as Runnable or Serializable.</H4>
<H4> Interface names should use upper CamelCase where the first letter of each word is capitalized.</H4>
<H3> Method Naming </H3>
<H4> Method names should use lower CamelCase where the first letter of each word is capitalized except for the first word.</H4>
<H4> Method names should generally be verbs or other descriptions of actions. </H4>
<H4> Specific naming conventions: </H4>
<UL>
<LI> Methods that access a class's attributes should start with "get" or "set". </LI>
<LI> Methods that return a boolean should start with "is". Sometimes "has", "can", or "should" are more appropriate. </LI>
<LI> Methods that look something up should start with "find" </LI>
</UL>
<H4> Methods that return a value should be named based on what they return. Void methods should be named based on what they do. </H4>
<PRE>
public Foo buildFoo() { // returns a Foo so method name is based on Foo
}
public int getSize() { // returns a primitive, which is the size, so name is based on "size"
}
public void startServer() { // doesn't return anything so name it based on what it does
}
public boolean installHandler(Handler handler) { // even though it returns a boolean, its not about returning
// a boolean, so name it based on what it does
}
</PRE>
<H3> Instance Variable Naming </H3>
<H4> Instance Variable names should use lower CamelCase where the first letter of each word is capitalized except for the first word.</H4>
<H3> Local Variable and Parameter Naming </H3>
<H4> Local Variable names should use lower CamelCase where the first letter of each word is capitalized except for the first word.</H4>
<H4> Variable names should be proportional in length to their scope. </H4>
<UL>
<LI> Names that live throughout large blocks or methods should have very descriptive names and avoid abbreviations. </LI>
<LI> Names that exist in small blocks can use short or abbreviated names. </LI>
<LI> Names that exist in tiny blocks can use one letter names (e.g., lambdas). </LI>
</UL>
<H4> Variable names should generally have the same name as their class (e.g., Person person or Button button). </H4>
<UL>
<LI> If for some reason, this rule doesn't seem to fit, then that is a strong indication that the type is badly named. </LI>
<LI> Some variables have a role. These variables can often be named {role}Type. For example, Button openButton or
Point startPoint, endPoint. </LI>
</UL>
<H4> Collections should be named the plural form of the type without the collection type name. For example, use List<Dog> dogs, not List<Dog> dogList. </H4>
<H3> Enum Naming </H3>
<H4> Enum class names should be like any other class (UpperCamelCase). </H4>
<H4> Enum value names should be all upper case.</H4>
<PRE>
public enum AnalyzerStatus {
ENABLED, DELAYED, DISABLED
}
</PRE>
<H3> Loop Counters </H3>
<H4> Use of i, j, k, etc. is acceptable as generic loop counters, unless a more descriptive name would greatly enhance the readability. </H4>
<H3> Constants (static final fields) </H3>
<H4> Constants should be all upper case with words separated by "_" (underscore char). </H4>
<P> Examples: MAXIMUM_VELOCITY, or DEFAULT_COLOR </P>
<H3> Generic Types </H3>
<H4> Generic type names should be named in one of two styles: </H4>
<UL>
<LI> A single Capital Letter, optionally followed by a single number (e.g., T, X, V, T2) </LI>
<UL>
<LI> T is used most often for single parameter types. </LI>
<LI> R is commonly used for return type. </LI>
<LI> K,V is commonly used for key,value types. </LI>
</UL>
<LI> A name in the form used for classes followed by the capital letter T (e.g., ActionT, RowT, ColumnT). Try to
avoid using this full name form unless it greatly enhances readability. </LI>
</UL>
<H3> Utility Classes </H3>
<H4>Utility class names should end in "Utils".</H4>
<H2> Source File Structure </H2>
<H3> File Order </H3>
<H4> A Java File should be organized in the following order </H4>
<UL>
<LI> Header </LI>
<LI> Package statement </LI>
<LI> Import statements </LI>
<LI> Class Javadocs </LI>
<LI> Class declaration </LI>
<LI> Static Variables </LI>
<LI> Static factory methods </LI>
<LI> Instance Variables </LI>
<LI> Constructors </LI>
<LI> methods </LI>
<LI> Private classes </LI>
</UL>
<H4> Local variables should be declared when first needed and not at the top of the method and should be
initialized as close to the declaration as possible (preferably at the same time). </H4>
<H4> Overloaded methods should be next to each other. </H4>
<H4> Modifiers should appear in the following order: </H4>
<UL>
<LI> access modifier (public/private/protected) </LI>
<LI> abstract </LI>
<LI> static </LI>
<LI> final </LI>
<LI> transient </LI>
<LI> volatile </LI>
<LI> default </LI>
<LI> synchronized </LI>
<LI> native </LI>
<LI> strictfp </LI>
</UL>
<H2> Formatting </H2>
<P> Most of these are handled by the eclipse formatter and are here to document the Ghidra formatting style.
<H3> Line Length </H3>
<H4> Java code will have a character limit of 100 characters per line. </H4>
<H3> Indenting </H3>
<H4> New blocks are indented using a tab character (the tab should be 4 spaces wide).</H4>
<H4> Line continuation should be indented the same as a new block. </H4>
<H3> Braces </H3>
<H4> Braces should always be used where optional.
<H4> Braces should follow the Kernighan and Ritchie style for nonempty blocks and block-like structures. </H4>
<UL>
<LI> No line break before the opening brace. </LI>
<LI> Line break after the opening brace. </LI>
<LI> Line break before the closing brace. </LI>
<LI> Line break after the closing brace. </LI>
</UL>
<H4> Empty blocks should look as follows. </H4>
<PRE>
void doNothing() {
// comment as to why we are doing nothing
}
</PRE>
<H3> White Space </H3>
<H4> A single blank line should be used to separate the following sections: </H4>
<UL>
<LI> Copyright notice</LI>
<LI> Package statement </LI>
<LI> Import section </LI>
<LI> Class declarations </LI>
<LI> Methods </LI>
<LI> Constructors </LI>
</UL>
<H4> A single blank line should be used: </H4>
<UL>
<LI> Between statements as needed to break code into logical sections. </LI>
<LI> Between import statements as needed to break into logical groups. </LI>
<LI> Between fields as needed to break into logical groups. </LI>
<LI> Between the javadoc description and the javadoc tag section. </LI>
</UL>
<H4> A single space should be used: </H4>
<UL>
<LI> To separate keywords from neighboring opening or closing brackets and braces. </LI>
<LI> Before and after all binary operators </LI>
<LI> After a // that starts a comment </LI>
<LI> Before a // that starts an end of line comment </LI>
<LI> After semicolons separating parts of a "for" loop </LI>
</UL>
<H3> Variable Assignment </H3>
<H4> Each variable should be declared on its own line. </H4>
<PRE>
don't:
int i,j;
do:
int i;
int j;
</PRE>
<H2> Comments </H2>
<H3> Javadoc </H3>
<H4> Javadoc blocks are normally of the form </H4>
<PRE>
/**
* Some description with normal
* wrapping.
*/
</PRE>
<H4> Javadoc paragraphs should be separated by a single blank line (Starts with an aligned *) and
each paragraph other than the initial description should start with <p>. </H4>
<H4> When referencing other methods, use links (e.g., {@link #method(type1, type2, ...} or {@link Classname#method(type1, type2, ...}). </H4>
<H4> Block tags should never appear without a description. </H4>
<H4> Descriptions in block tags should not end in a period, unless followed by another sentence. </H4>
<H4> Block tags that are used should appear in the following order: </H4>
<UL>
<LI> @param </LI>
<LI> @return </LI>
<LI> @throws </LI>
<LI> @see </LI>
<LI> @deprecated </LI>
</UL>
<H4> The Javadoc block should begin with a brief summary fragment. This fragment should be
a noun phrase or a verb phrase and not a complete sentence. However, the fragment is
capitalized and punctuated as if it were a complete sentence. </H4>
<PRE>
For example, do
/**
* Sets the warning level for the messaging system.
*/
not
/**
* This method sets the warning level for the messaging system.
*/
</PRE>
<H4> Javadoc should be present for every public class and every public or protected method with
the following exceptions: </H4>
<UL>
<LI> Methods that override a super method. </LI>
</UL>
<H3> Code Comments </H3>
<H4>Block comments are indented at the same level as the surrounding code.</H4>
<H4>Block comments should be preceded by a blank line unless it is the first line of the block.</H4>
<H4>Block comments should be one of the following forms: </H4>
<PRE>
/*
* This is // I like this
* nice. // also.
*/
</PRE>
<H4> Any empty code block should have a comment so that the reader will know it was intentional. Also,
the comment should not be something like "// empty" or "don't care", but instead should state why it
is empty or why you don't care.</H4>
<H4> Comments should indicate the 'why' you are doing something, not just 'what' you are doing. The code
tells us what it is doing. Comments should not be pseudo code.</H4>
<H4> Prefer creating a descriptive method to using a block comment. So if you feel that a block
comment is needed to explain the next block of code, then it probably would be better off moved
to a method with a name that says what the code does.</H4>
<H4> Use of comments in code should be minimized by making the code self-documenting by appropriate name choices
and an explicit logical structure. </H4>
<H4> Tricky code should not be commented. Instead, it should be rewritten. </H4>
<H2> Complexity </H2>
<H3> Method Size </H3>
<H4> Avoid long methods. </H4>
<UL>
<LI> Methods should perform one clearly defined task. </LI>
<LI> Methods should generally fit on one page (approximately 30 lines). </LI>
</UL>
<H3> Method Complexity </H3>
<H4>A method should be completely understandable (what, how, why) in about 30 seconds. </H4>
<H4> Method Complexity should be kept low, according to the following scale:</H4>
<UL>
<LI><TT>0-5</TT>: The method is *probably* fine</LI>
<LI><TT>6-10</TT>: The method is questionable; seek to simplify</LI>
<LI><TT>11+</TT>: OMG! Unacceptable!</LI>
</UL>
<P>Calculating Complexity:</P>
<UL>
<LI> Start with one. </LI>
<LI> Add one for each of the following. </LI>
<UL>
<LI> Returns: Each return other than a simple early guard condition or the last statement in the method. </LI>
<LI> Selection: if, else if, case, default. </LI>
<LI> Loops: for, while, do-while, break, and continue. </LI>
<LI> Operators: &&, ||, ? </LI>
<LI> Exceptions: catch, finally, throw. </LI>
</UL>
</UL>
<H4>Methods should avoid deep nesting. </H4>
<UL>
<LI> 2 or less - good </LI>
<LI> 3 or 4 - questionable </LI>
<LI> 5 or more - unacceptable </LI>
</UL>
<H4>Methods and constructors should avoid large numbers of parameters.</H4>
<UL>
<LI> 3 or less - good </LI>
<LI> 4 or 5 - questionable </LI>
<LI> 6 or 7 - bad, should consider redesign </LI>
<LI> 8 or more - unacceptable </LI>
</UL>
<H4>All blocks of code in a method should be at the same level of abstraction </H4>
<PRE>
// example of mixed levels:
void doDailyChores() {
dust();
vacuum();
mopFloor();
<API key>();
<API key>();
<API key>();
startWashingMachine();
cleanToilet();
}
// fixed
void doDailyChores() {
dust();
vacuum();
mopFloor();
washClothes();
cleanToilet();
}
</PRE>
<H4>Methods and constructors should generally avoid multiple parameters of the same type, unless the method's purpose
is to process multiple instances of the same type (e.g., comparator, math functions). This is especially egregious
for boolean parameters.</H4>
<H4>Tips for lowering complexity </H4>
<UL>
<LI> Keep the number of nesting levels low </LI>
<LI> Keep the number of variables used low </LI>
<LI> Keep the lines of code low </LI>
<LI> Keep 'span' low (the number of lines between successive references to variables) </LI>
<LI> Keep 'live time' low (the number of lines that a variable is in use) </LI>
</UL>
<H2> Testing </H2>
<H3> Unit testing </H3>
<H4>A single test case should only test one result. If there are more than 2 or 3 asserts in
a single test, consider breaking into multiple tests. </H4>
<H4>Unit tests should run fast (a single test case (method) should be less than a second) </H4>
<H2> Miscellaneous </H2>
<H3> @Override </H3>
<H4> Methods that override a method in a parent class should use the @Override tag. </H4>
<H4> Methods that implement an interface method should use the @Override tag. </H4>
<H4> Methods that use the @Override tag do not need a Javadoc comment. </H4>
<H3> Use of Tuple Objects<A,B> </H3>
<H4> Use of Pair<A,B>, Triple<A,B,C>, etc. should be avoided. If the multiple values being returned
are related, then the method is conceptually returning a higher level object and so should return that.
Otherwise, the method should be redesigned. </H4>
<H3> Exception Handling </H3>
<H4> Exceptions should never have empty code blocks. There should at least be a comment explaining
why there is no code for the exception. </H4>
<H4> If the caught exception is believed to be impossible to happen, the correct action is to throw an AssertException
with a message explaining that it should never happen. </H4>
<H3> Final </H3>
<H4> Instance variables that are immutable should be declared final unless there is a compelling reason not to. </H4>
<H3> Shadowing </H3>
<H4> Avoid hiding/shadowing methods, variables, and type variables in outer scopes. </H4>
<H3> Access modifiers </H3>
<H4> Class instance fields should not be public. They should be private whenever possible, but protected and package are acceptable.</H4>
<H3> Java-specific constructs</H3>
<H4> Use the try-with-resources pattern whenever possible. </H4>
<H4> Always parameterize types when possible (e.g., JComboBox<String> vs. JComboBox). </H4>
<H4> If an object has an isEmpty() method, use it instead of checking its size == 0. </H4>
<H3> Miscellaneous </H3>
<H4> Mutating method parameters is discouraged. </H4>
<H4> Magic numbers should not appear in the code. Other than 0, or 1, the number should be declared as a constant. </H4>
<H4> Avoid creating a new Utilities class <B>*every time you need to share code*</B>. Try to add to
an existing utilities class OR take advantage of code re-use via inheritance. </H4>
<H3> Rules that shouldn't need to be stated, but do</H3>
<H4> Test your feature yourself before submitting for review and make sure the tests pass. </H4>
<div class="info">
Notes:
</div>
<H5>Complexity</H5>
<P>
'The McCabe measure of complexity isn't the only sound measure, but it's the measure most
discussed in computing literature and it's especially helpful when you're thinking about control flow.
Other measures include the amount of data used, the number of nesting levels in control
constructs, the number of lines of code, the number of lines between successive references
to variables ("span"), the number of lines that a variable is in use ("live time"), and the
amount of input and output. Some researchers have developed composite metrics based on
combinations of these simpler ones.' (McCabe)
</P>
<P>
'Moving part of a routine into another routine doesn't reduce the overall complexity of the
program; it just moves the decision points around. But it reduces the amount of complexity
you have to deal with at any one time. Since the important goal is to minimize the number of
items you have to juggle mentally, reducing the complexity of a given routine is worthwhile.' (McCabe)
</P>
<P>
'Excessive indentation, or "nesting," has been pilloried in computing literature for 25 years and is
still one of the chief culprits in confusing code. Studies by Noam Chomsky and Gerald
Weinberg suggest that few people can understand more than three levels of nested ifs
(Yourdon 1986a), and many researchers recommend avoiding nesting to more than three or four
levels (Myers 1976, Marca 1981, and Ledgard and Tauer 1987a). Deep nesting works against what
Chapter 5, describes as Software's Primary Technical Imperative: Managing Complexity. That is reason
enough to avoid deep nesting.' (McCabe)
</P>
<P>
'There is no code so big, twisted, or complex that maintenance can't make it worse.'<BR>
- Gerald Weinberg
</P>
<div class="info">
References:
</div>
<UL>
<LI> Google Java Style Guide </LI>
<LI> OpenJDK Style Guide </LI>
<LI> Java Programming Style Guidelines - Geotechnical Software Services </LI>
<LI> Code Complete, Steve McConnell </LI>
<LI> Java Code Conventions </LI>
<LI> Netscapes Software Coding Standards for Java </LI>
<LI> C / C++ / Java Coding Standards from NASA </LI>
<LI> Coding Standards for Java from AmbySoft </LI>
<LI> Clean Code, Robert Martin (Uncle Bob) </LI>
</UL>
</body>
</html>
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - <API key></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.7/angular.min.js"></script>
</head>
<body ng-app="">
<input ng-keyup="count = count + 1" ng-init="count=0">
key up count: {{count}}
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.