code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
package org.jboss.windup.config.phase;
import org.jboss.windup.config.AbstractRuleProvider;
import org.ocpsoft.rewrite.config.Rule;
/**
* Previous: {@link PostReportRenderingPhase}<br/>
* Next: {@link PostFinalizePhase}
*
* <p>
* This occurs at the end of execution. {@link Rule}s in this phase are responsible for any cleanup of resources that
* may have been opened during {@link Rule}s from earlier {@link AbstractRuleProvider}s.
* </p>
*
* @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a>
*
*/
public class FinalizePhase extends RulePhase
{
public FinalizePhase()
{
super(FinalizePhase.class);
}
@Override
public Class<? extends RulePhase> getExecuteAfter()
{
return PostReportRenderingPhase.class;
}
@Override
public Class<? extends RulePhase> getExecuteBefore()
{
return null;
}
}
| sgilda/windup | config/api/src/main/java/org/jboss/windup/config/phase/FinalizePhase.java | Java | epl-1.0 | 892 |
/* Copyright (C) 2010-2016 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#if !defined _X86INTRIN_H_INCLUDED && !defined _IMMINTRIN_H_INCLUDED
# error "Never use <bmiintrin.h> directly; include <x86intrin.h> instead."
#endif
#ifndef _BMIINTRIN_H_INCLUDED
#define _BMIINTRIN_H_INCLUDED
#ifndef __BMI__
#pragma GCC push_options
#pragma GCC target("bmi")
#define __DISABLE_BMI__
#endif /* __BMI__ */
extern __inline unsigned short __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__tzcnt_u16 (unsigned short __X)
{
return __builtin_ia32_tzcnt_u16 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__andn_u32 (unsigned int __X, unsigned int __Y)
{
return ~__X & __Y;
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__bextr_u32 (unsigned int __X, unsigned int __Y)
{
return __builtin_ia32_bextr_u32 (__X, __Y);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_bextr_u32 (unsigned int __X, unsigned int __Y, unsigned __Z)
{
return __builtin_ia32_bextr_u32 (__X, ((__Y & 0xff) | ((__Z & 0xff) << 8)));
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsi_u32 (unsigned int __X)
{
return __X & -__X;
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsi_u32 (unsigned int __X)
{
return __blsi_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsmsk_u32 (unsigned int __X)
{
return __X ^ (__X - 1);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsmsk_u32 (unsigned int __X)
{
return __blsmsk_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsr_u32 (unsigned int __X)
{
return __X & (__X - 1);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsr_u32 (unsigned int __X)
{
return __blsr_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__tzcnt_u32 (unsigned int __X)
{
return __builtin_ia32_tzcnt_u32 (__X);
}
extern __inline unsigned int __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_tzcnt_u32 (unsigned int __X)
{
return __builtin_ia32_tzcnt_u32 (__X);
}
#ifdef __x86_64__
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__andn_u64 (unsigned long long __X, unsigned long long __Y)
{
return ~__X & __Y;
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__bextr_u64 (unsigned long long __X, unsigned long long __Y)
{
return __builtin_ia32_bextr_u64 (__X, __Y);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_bextr_u64 (unsigned long long __X, unsigned int __Y, unsigned int __Z)
{
return __builtin_ia32_bextr_u64 (__X, ((__Y & 0xff) | ((__Z & 0xff) << 8)));
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsi_u64 (unsigned long long __X)
{
return __X & -__X;
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsi_u64 (unsigned long long __X)
{
return __blsi_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsmsk_u64 (unsigned long long __X)
{
return __X ^ (__X - 1);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsmsk_u64 (unsigned long long __X)
{
return __blsmsk_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__blsr_u64 (unsigned long long __X)
{
return __X & (__X - 1);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_blsr_u64 (unsigned long long __X)
{
return __blsr_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
__tzcnt_u64 (unsigned long long __X)
{
return __builtin_ia32_tzcnt_u64 (__X);
}
extern __inline unsigned long long __attribute__((__gnu_inline__, __always_inline__, __artificial__))
_tzcnt_u64 (unsigned long long __X)
{
return __builtin_ia32_tzcnt_u64 (__X);
}
#endif /* __x86_64__ */
#ifdef __DISABLE_BMI__
#undef __DISABLE_BMI__
#pragma GCC pop_options
#endif /* __DISABLE_BMI__ */
#endif /* _BMIINTRIN_H_INCLUDED */
| crtc-demos/gcc-ia16 | gcc/config/i386/bmiintrin.h | C | gpl-2.0 | 5,628 |
/* ========================================================================
* Bootstrap: iconset-typicon-2.0.6.js by @recktoner
* https://victor-valencia.github.com/bootstrap-iconpicker
*
* Iconset: Typicons 2.0.6
* https://github.com/stephenhutchings/typicons.font
* ========================================================================
* Copyright 2013-2014 Victor Valencia Rico.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
;(function($){
$.iconset_typicon = {
iconClass: 'typcn',
iconClassFix: 'typcn-',
icons: [
'adjust-brightness',
'adjust-contrast',
'anchor-outline',
'anchor',
'archive',
'arrow-back-outline',
'arrow-back',
'arrow-down-outline',
'arrow-down-thick',
'arrow-down',
'arrow-forward-outline',
'arrow-forward',
'arrow-left-outline',
'arrow-left-thick',
'arrow-left',
'arrow-loop-outline',
'arrow-loop',
'arrow-maximise-outline',
'arrow-maximise',
'arrow-minimise-outline',
'arrow-minimise',
'arrow-move-outline',
'arrow-move',
'arrow-repeat-outline',
'arrow-repeat',
'arrow-right-outline',
'arrow-right-thick',
'arrow-right',
'arrow-shuffle',
'arrow-sorted-down',
'arrow-sorted-up',
'arrow-sync-outline',
'arrow-sync',
'arrow-unsorted',
'arrow-up-outline',
'arrow-up-thick',
'arrow-up',
'at',
'attachment-outline',
'attachment',
'backspace-outline',
'backspace',
'battery-charge',
'battery-full',
'battery-high',
'battery-low',
'battery-mid',
'beaker',
'beer',
'bell',
'book',
'bookmark',
'briefcase',
'brush',
'business-card',
'calculator',
'calendar-outline',
'calendar',
'camera-outline',
'camera',
'cancel-outline',
'cancel',
'chart-area-outline',
'chart-area',
'chart-bar-outline',
'chart-bar',
'chart-line-outline',
'chart-line',
'chart-pie-outline',
'chart-pie',
'chevron-left-outline',
'chevron-left',
'chevron-right-outline',
'chevron-right',
'clipboard',
'cloud-storage',
'cloud-storage-outline',
'code-outline',
'code',
'coffee',
'cog-outline',
'cog',
'compass',
'contacts',
'credit-card',
'css3',
'database',
'delete-outline',
'delete',
'device-desktop',
'device-laptop',
'device-phone',
'device-tablet',
'directions',
'divide-outline',
'divide',
'document-add',
'document-delete',
'document-text',
'document',
'download-outline',
'download',
'dropbox',
'edit',
'eject-outline',
'eject',
'equals-outline',
'equals',
'export-outline',
'export',
'eye-outline',
'eye',
'feather',
'film',
'filter',
'flag-outline',
'flag',
'flash-outline',
'flash',
'flow-children',
'flow-merge',
'flow-parallel',
'flow-switch',
'folder-add',
'folder-delete',
'folder-open',
'folder',
'gift',
'globe-outline',
'globe',
'group-outline',
'group',
'headphones',
'heart-full-outline',
'heart-half-outline',
'heart-outline',
'heart',
'home-outline',
'home',
'html5',
'image-outline',
'image',
'infinity-outline',
'infinity',
'info-large-outline',
'info-large',
'info-outline',
'info',
'input-checked-outline',
'input-checked',
'key-outline',
'key',
'keyboard',
'leaf',
'lightbulb',
'link-outline',
'link',
'location-arrow-outline',
'location-arrow',
'location-outline',
'location',
'lock-closed-outline',
'lock-closed',
'lock-open-outline',
'lock-open',
'mail',
'map',
'media-eject-outline',
'media-eject',
'media-fast-forward-outline',
'media-fast-forward',
'media-pause-outline',
'media-pause',
'media-play-outline',
'media-play-reverse-outline',
'media-play-reverse',
'media-play',
'media-record-outline',
'media-record',
'media-rewind-outline',
'media-rewind',
'media-stop-outline',
'media-stop',
'message-typing',
'message',
'messages',
'microphone-outline',
'microphone',
'minus-outline',
'minus',
'mortar-board',
'news',
'notes-outline',
'notes',
'pen',
'pencil',
'phone-outline',
'phone',
'pi-outline',
'pi',
'pin-outline',
'pin',
'pipette',
'plane-outline',
'plane',
'plug',
'plus-outline',
'plus',
'point-of-interest-outline',
'point-of-interest',
'power-outline',
'power',
'printer',
'puzzle-outline',
'puzzle',
'radar-outline',
'radar',
'refresh-outline',
'refresh',
'rss-outline',
'rss',
'scissors-outline',
'scissors',
'shopping-bag',
'shopping-cart',
'social-at-circular',
'social-dribbble-circular',
'social-dribbble',
'social-facebook-circular',
'social-facebook',
'social-flickr-circular',
'social-flickr',
'social-github-circular',
'social-github',
'social-google-plus-circular',
'social-google-plus',
'social-instagram-circular',
'social-instagram',
'social-last-fm-circular',
'social-last-fm',
'social-linkedin-circular',
'social-linkedin',
'social-pinterest-circular',
'social-pinterest',
'social-skype-outline',
'social-skype',
'social-tumbler-circular',
'social-tumbler',
'social-twitter-circular',
'social-twitter',
'social-vimeo-circular',
'social-vimeo',
'social-youtube-circular',
'social-youtube',
'sort-alphabetically-outline',
'sort-alphabetically',
'sort-numerically-outline',
'sort-numerically',
'spanner-outline',
'spanner',
'spiral',
'star-full-outline',
'star-half-outline',
'star-half',
'star-outline',
'star',
'starburst-outline',
'starburst',
'stopwatch',
'support',
'tabs-outline',
'tag',
'tags',
'th-large-outline',
'th-large',
'th-list-outline',
'th-list',
'th-menu-outline',
'th-menu',
'th-small-outline',
'th-small',
'thermometer',
'thumbs-down',
'thumbs-ok',
'thumbs-up',
'tick-outline',
'tick',
'ticket',
'time',
'times-outline',
'times',
'trash',
'tree',
'upload-outline',
'upload',
'user-add-outline',
'user-add',
'user-delete-outline',
'user-delete',
'user-outline',
'user',
'vendor-android',
'vendor-apple',
'vendor-microsoft',
'video-outline',
'video',
'volume-down',
'volume-mute',
'volume-up',
'volume',
'warning-outline',
'warning',
'watch',
'waves-outline',
'waves',
'weather-cloudy',
'weather-downpour',
'weather-night',
'weather-partly-sunny',
'weather-shower',
'weather-snow',
'weather-stormy',
'weather-sunny',
'weather-windy-cloudy',
'weather-windy',
'wi-fi-outline',
'wi-fi',
'wine',
'world-outline',
'world',
'zoom-in-outline',
'zoom-in',
'zoom-out-outline',
'zoom-out',
'zoom-outline',
'zoom'
]};
})(jQuery); | ahsina/StudExpo | wp-content/plugins/tiny-bootstrap-elements-light/assets/js/iconset/iconset-typicon-2.0.6.js | JavaScript | gpl-2.0 | 10,551 |
/*
* linux/mm/vmscan.c
*
* Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
*
* Swap reorganised 29.12.95, Stephen Tweedie.
* kswapd added: 7.1.96 sct
* Removed kswapd_ctl limits, and swap out as many pages as needed
* to bring the system back to freepages.high: 2.4.97, Rik van Riel.
* Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
* Multiqueue VM started 5.8.00, Rik van Riel.
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/kernel_stat.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/vmpressure.h>
#include <linux/vmstat.h>
#include <linux/file.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/buffer_head.h> /* for try_to_release_page(),
buffer_heads_over_limit */
#include <linux/mm_inline.h>
#include <linux/backing-dev.h>
#include <linux/rmap.h>
#include <linux/topology.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/compaction.h>
#include <linux/notifier.h>
#include <linux/rwsem.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/memcontrol.h>
#include <linux/delayacct.h>
#include <linux/sysctl.h>
#include <linux/oom.h>
#include <linux/prefetch.h>
#include <linux/debugfs.h>
#include <asm/tlbflush.h>
#include <asm/div64.h>
#include <linux/swapops.h>
#include <linux/balloon_compaction.h>
#include "internal.h"
#define CREATE_TRACE_POINTS
#include <trace/events/vmscan.h>
struct scan_control {
/* Incremented by the number of inactive pages that were scanned */
unsigned long nr_scanned;
/* Number of pages freed so far during a call to shrink_zones() */
unsigned long nr_reclaimed;
/* How many pages shrink_list() should reclaim */
unsigned long nr_to_reclaim;
unsigned long hibernation_mode;
/* This context's GFP mask */
gfp_t gfp_mask;
int may_writepage;
/* Can mapped pages be reclaimed? */
int may_unmap;
/* Can pages be swapped as part of reclaim? */
int may_swap;
int order;
/* Scan (total_size >> priority) pages at once */
int priority;
/*
* The memory cgroup that hit its limit and as a result is the
* primary target of this reclaim invocation.
*/
struct mem_cgroup *target_mem_cgroup;
/*
* Nodemask of nodes allowed by the caller. If NULL, all nodes
* are scanned.
*/
nodemask_t *nodemask;
};
#define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
#ifdef ARCH_HAS_PREFETCH
#define prefetch_prev_lru_page(_page, _base, _field) \
do { \
if ((_page)->lru.prev != _base) { \
struct page *prev; \
\
prev = lru_to_page(&(_page->lru)); \
prefetch(&prev->_field); \
} \
} while (0)
#else
#define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
#endif
#ifdef ARCH_HAS_PREFETCHW
#define prefetchw_prev_lru_page(_page, _base, _field) \
do { \
if ((_page)->lru.prev != _base) { \
struct page *prev; \
\
prev = lru_to_page(&(_page->lru)); \
prefetchw(&prev->_field); \
} \
} while (0)
#else
#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
#endif
/*
* From 0 .. 100. Higher means more swappy.
*/
int vm_swappiness = 60;
unsigned long vm_total_pages; /* The total number of pages which the VM controls */
static LIST_HEAD(shrinker_list);
static DECLARE_RWSEM(shrinker_rwsem);
#ifdef CONFIG_MEMCG
static bool global_reclaim(struct scan_control *sc)
{
return !sc->target_mem_cgroup;
}
#else
static bool global_reclaim(struct scan_control *sc)
{
return true;
}
#endif
static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
{
if (!mem_cgroup_disabled())
return mem_cgroup_get_lru_size(lruvec, lru);
return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
}
struct dentry *debug_file;
static int debug_shrinker_show(struct seq_file *s, void *unused)
{
struct shrinker *shrinker;
struct shrink_control sc;
sc.gfp_mask = -1;
sc.nr_to_scan = 0;
down_read(&shrinker_rwsem);
list_for_each_entry(shrinker, &shrinker_list, list) {
int num_objs;
num_objs = shrinker->shrink(shrinker, &sc);
seq_printf(s, "%pf %d\n", shrinker->shrink, num_objs);
}
up_read(&shrinker_rwsem);
return 0;
}
static int debug_shrinker_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_shrinker_show, inode->i_private);
}
static const struct file_operations debug_shrinker_fops = {
.open = debug_shrinker_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/*
* Add a shrinker callback to be called from the vm
*/
void register_shrinker(struct shrinker *shrinker)
{
atomic_long_set(&shrinker->nr_in_batch, 0);
down_write(&shrinker_rwsem);
list_add_tail(&shrinker->list, &shrinker_list);
up_write(&shrinker_rwsem);
}
EXPORT_SYMBOL(register_shrinker);
static int __init add_shrinker_debug(void)
{
debugfs_create_file("shrinker", 0644, NULL, NULL,
&debug_shrinker_fops);
return 0;
}
late_initcall(add_shrinker_debug);
/*
* Remove one
*/
void unregister_shrinker(struct shrinker *shrinker)
{
down_write(&shrinker_rwsem);
list_del(&shrinker->list);
up_write(&shrinker_rwsem);
}
EXPORT_SYMBOL(unregister_shrinker);
static inline int do_shrinker_shrink(struct shrinker *shrinker,
struct shrink_control *sc,
unsigned long nr_to_scan)
{
sc->nr_to_scan = nr_to_scan;
return (*shrinker->shrink)(shrinker, sc);
}
#define SHRINK_BATCH 128
/*
* Call the shrink functions to age shrinkable caches
*
* Here we assume it costs one seek to replace a lru page and that it also
* takes a seek to recreate a cache object. With this in mind we age equal
* percentages of the lru and ageable caches. This should balance the seeks
* generated by these structures.
*
* If the vm encountered mapped pages on the LRU it increase the pressure on
* slab to avoid swapping.
*
* We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
*
* `lru_pages' represents the number of on-LRU pages in all the zones which
* are eligible for the caller's allocation attempt. It is used for balancing
* slab reclaim versus page reclaim.
*
* Returns the number of slab objects which we shrunk.
*/
unsigned long shrink_slab(struct shrink_control *shrink,
unsigned long nr_pages_scanned,
unsigned long lru_pages)
{
struct shrinker *shrinker;
unsigned long ret = 0;
if (nr_pages_scanned == 0)
nr_pages_scanned = SWAP_CLUSTER_MAX;
if (!down_read_trylock(&shrinker_rwsem)) {
/* Assume we'll be able to shrink next time */
ret = 1;
goto out;
}
list_for_each_entry(shrinker, &shrinker_list, list) {
unsigned long long delta;
long total_scan;
long max_pass;
int shrink_ret = 0;
long nr;
long new_nr;
long batch_size = shrinker->batch ? shrinker->batch
: SHRINK_BATCH;
max_pass = do_shrinker_shrink(shrinker, shrink, 0);
if (max_pass <= 0)
continue;
/*
* copy the current shrinker scan count into a local variable
* and zero it so that other concurrent shrinker invocations
* don't also do this scanning work.
*/
nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
total_scan = nr;
delta = (4 * nr_pages_scanned) / shrinker->seeks;
delta *= max_pass;
do_div(delta, lru_pages + 1);
total_scan += delta;
if (total_scan < 0) {
printk(KERN_ERR "shrink_slab: %pF negative objects to "
"delete nr=%ld\n",
shrinker->shrink, total_scan);
total_scan = max_pass;
}
/*
* We need to avoid excessive windup on filesystem shrinkers
* due to large numbers of GFP_NOFS allocations causing the
* shrinkers to return -1 all the time. This results in a large
* nr being built up so when a shrink that can do some work
* comes along it empties the entire cache due to nr >>>
* max_pass. This is bad for sustaining a working set in
* memory.
*
* Hence only allow the shrinker to scan the entire cache when
* a large delta change is calculated directly.
*/
if (delta < max_pass / 4)
total_scan = min(total_scan, max_pass / 2);
/*
* Avoid risking looping forever due to too large nr value:
* never try to free more than twice the estimate number of
* freeable entries.
*/
if (total_scan > max_pass * 2)
total_scan = max_pass * 2;
trace_mm_shrink_slab_start(shrinker, shrink, nr,
nr_pages_scanned, lru_pages,
max_pass, delta, total_scan);
while (total_scan >= batch_size) {
int nr_before;
nr_before = do_shrinker_shrink(shrinker, shrink, 0);
shrink_ret = do_shrinker_shrink(shrinker, shrink,
batch_size);
if (shrink_ret == -1)
break;
if (shrink_ret < nr_before)
ret += nr_before - shrink_ret;
count_vm_events(SLABS_SCANNED, batch_size);
total_scan -= batch_size;
cond_resched();
}
/*
* move the unused scan count back into the shrinker in a
* manner that handles concurrent updates. If we exhausted the
* scan, there is no need to do an update.
*/
if (total_scan > 0)
new_nr = atomic_long_add_return(total_scan,
&shrinker->nr_in_batch);
else
new_nr = atomic_long_read(&shrinker->nr_in_batch);
trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr);
}
up_read(&shrinker_rwsem);
out:
cond_resched();
return ret;
}
static inline int is_page_cache_freeable(struct page *page)
{
/*
* A freeable page cache page is referenced only by the caller
* that isolated the page, the page cache radix tree and
* optional buffer heads at page->private.
*/
return page_count(page) - page_has_private(page) == 2;
}
static int may_write_to_queue(struct backing_dev_info *bdi,
struct scan_control *sc)
{
if (current->flags & PF_SWAPWRITE)
return 1;
if (!bdi_write_congested(bdi))
return 1;
if (bdi == current->backing_dev_info)
return 1;
return 0;
}
/*
* We detected a synchronous write error writing a page out. Probably
* -ENOSPC. We need to propagate that into the address_space for a subsequent
* fsync(), msync() or close().
*
* The tricky part is that after writepage we cannot touch the mapping: nothing
* prevents it from being freed up. But we have a ref on the page and once
* that page is locked, the mapping is pinned.
*
* We're allowed to run sleeping lock_page() here because we know the caller has
* __GFP_FS.
*/
static void handle_write_error(struct address_space *mapping,
struct page *page, int error)
{
lock_page(page);
if (page_mapping(page) == mapping)
mapping_set_error(mapping, error);
unlock_page(page);
}
/* possible outcome of pageout() */
typedef enum {
/* failed to write page out, page is locked */
PAGE_KEEP,
/* move page to the active list, page is locked */
PAGE_ACTIVATE,
/* page has been sent to the disk successfully, page is unlocked */
PAGE_SUCCESS,
/* page is clean and locked */
PAGE_CLEAN,
} pageout_t;
/*
* pageout is called by shrink_page_list() for each dirty page.
* Calls ->writepage().
*/
static pageout_t pageout(struct page *page, struct address_space *mapping,
struct scan_control *sc)
{
/*
* If the page is dirty, only perform writeback if that write
* will be non-blocking. To prevent this allocation from being
* stalled by pagecache activity. But note that there may be
* stalls if we need to run get_block(). We could test
* PagePrivate for that.
*
* If this process is currently in __generic_file_aio_write() against
* this page's queue, we can perform writeback even if that
* will block.
*
* If the page is swapcache, write it back even if that would
* block, for some throttling. This happens by accident, because
* swap_backing_dev_info is bust: it doesn't reflect the
* congestion state of the swapdevs. Easy to fix, if needed.
*/
if (!is_page_cache_freeable(page))
return PAGE_KEEP;
if (!mapping) {
/*
* Some data journaling orphaned pages can have
* page->mapping == NULL while being dirty with clean buffers.
*/
if (page_has_private(page)) {
if (try_to_free_buffers(page)) {
ClearPageDirty(page);
printk("%s: orphaned page\n", __func__);
return PAGE_CLEAN;
}
}
return PAGE_KEEP;
}
if (mapping->a_ops->writepage == NULL)
return PAGE_ACTIVATE;
if (!may_write_to_queue(mapping->backing_dev_info, sc))
return PAGE_KEEP;
if (clear_page_dirty_for_io(page)) {
int res;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_NONE,
.nr_to_write = SWAP_CLUSTER_MAX,
.range_start = 0,
.range_end = LLONG_MAX,
.for_reclaim = 1,
};
SetPageReclaim(page);
res = mapping->a_ops->writepage(page, &wbc);
if (res < 0)
handle_write_error(mapping, page, res);
if (res == AOP_WRITEPAGE_ACTIVATE) {
ClearPageReclaim(page);
return PAGE_ACTIVATE;
}
if (!PageWriteback(page)) {
/* synchronous write or broken a_ops? */
ClearPageReclaim(page);
}
trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
inc_zone_page_state(page, NR_VMSCAN_WRITE);
return PAGE_SUCCESS;
}
return PAGE_CLEAN;
}
/*
* Same as remove_mapping, but if the page is removed from the mapping, it
* gets returned with a refcount of 0.
*/
static int __remove_mapping(struct address_space *mapping, struct page *page)
{
BUG_ON(!PageLocked(page));
BUG_ON(mapping != page_mapping(page));
spin_lock_irq(&mapping->tree_lock);
/*
* The non racy check for a busy page.
*
* Must be careful with the order of the tests. When someone has
* a ref to the page, it may be possible that they dirty it then
* drop the reference. So if PageDirty is tested before page_count
* here, then the following race may occur:
*
* get_user_pages(&page);
* [user mapping goes away]
* write_to(page);
* !PageDirty(page) [good]
* SetPageDirty(page);
* put_page(page);
* !page_count(page) [good, discard it]
*
* [oops, our write_to data is lost]
*
* Reversing the order of the tests ensures such a situation cannot
* escape unnoticed. The smp_rmb is needed to ensure the page->flags
* load is not satisfied before that of page->_count.
*
* Note that if SetPageDirty is always performed via set_page_dirty,
* and thus under tree_lock, then this ordering is not required.
*/
if (!page_freeze_refs(page, 2))
goto cannot_free;
/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
if (unlikely(PageDirty(page))) {
page_unfreeze_refs(page, 2);
goto cannot_free;
}
if (PageSwapCache(page)) {
swp_entry_t swap = { .val = page_private(page) };
__delete_from_swap_cache(page);
spin_unlock_irq(&mapping->tree_lock);
swapcache_free(swap, page);
} else {
void (*freepage)(struct page *);
freepage = mapping->a_ops->freepage;
__delete_from_page_cache(page);
spin_unlock_irq(&mapping->tree_lock);
mem_cgroup_uncharge_cache_page(page);
if (freepage != NULL)
freepage(page);
}
return 1;
cannot_free:
spin_unlock_irq(&mapping->tree_lock);
return 0;
}
/*
* Attempt to detach a locked page from its ->mapping. If it is dirty or if
* someone else has a ref on the page, abort and return 0. If it was
* successfully detached, return 1. Assumes the caller has a single ref on
* this page.
*/
int remove_mapping(struct address_space *mapping, struct page *page)
{
if (__remove_mapping(mapping, page)) {
/*
* Unfreezing the refcount with 1 rather than 2 effectively
* drops the pagecache ref for us without requiring another
* atomic operation.
*/
page_unfreeze_refs(page, 1);
return 1;
}
return 0;
}
/**
* putback_lru_page - put previously isolated page onto appropriate LRU list
* @page: page to be put back to appropriate lru list
*
* Add previously isolated @page to appropriate LRU list.
* Page may still be unevictable for other reasons.
*
* lru_lock must not be held, interrupts must be enabled.
*/
void putback_lru_page(struct page *page)
{
int lru;
int active = !!TestClearPageActive(page);
int was_unevictable = PageUnevictable(page);
VM_BUG_ON(PageLRU(page));
redo:
ClearPageUnevictable(page);
if (page_evictable(page)) {
/*
* For evictable pages, we can use the cache.
* In event of a race, worst case is we end up with an
* unevictable page on [in]active list.
* We know how to handle that.
*/
lru = active + page_lru_base_type(page);
lru_cache_add_lru(page, lru);
} else {
/*
* Put unevictable pages directly on zone's unevictable
* list.
*/
lru = LRU_UNEVICTABLE;
add_page_to_unevictable_list(page);
/*
* When racing with an mlock or AS_UNEVICTABLE clearing
* (page is unlocked) make sure that if the other thread
* does not observe our setting of PG_lru and fails
* isolation/check_move_unevictable_pages,
* we see PG_mlocked/AS_UNEVICTABLE cleared below and move
* the page back to the evictable list.
*
* The other side is TestClearPageMlocked() or shmem_lock().
*/
smp_mb();
}
/*
* page's status can change while we move it among lru. If an evictable
* page is on unevictable list, it never be freed. To avoid that,
* check after we added it to the list, again.
*/
if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
if (!isolate_lru_page(page)) {
put_page(page);
goto redo;
}
/* This means someone else dropped this page from LRU
* So, it will be freed or putback to LRU again. There is
* nothing to do here.
*/
}
if (was_unevictable && lru != LRU_UNEVICTABLE)
count_vm_event(UNEVICTABLE_PGRESCUED);
else if (!was_unevictable && lru == LRU_UNEVICTABLE)
count_vm_event(UNEVICTABLE_PGCULLED);
put_page(page); /* drop ref from isolate */
}
enum page_references {
PAGEREF_RECLAIM,
PAGEREF_RECLAIM_CLEAN,
PAGEREF_KEEP,
PAGEREF_ACTIVATE,
};
static enum page_references page_check_references(struct page *page,
struct scan_control *sc)
{
int referenced_ptes, referenced_page;
unsigned long vm_flags;
referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
&vm_flags);
referenced_page = TestClearPageReferenced(page);
/*
* Mlock lost the isolation race with us. Let try_to_unmap()
* move the page to the unevictable list.
*/
if (vm_flags & VM_LOCKED)
return PAGEREF_RECLAIM;
if (referenced_ptes) {
if (PageSwapBacked(page))
return PAGEREF_ACTIVATE;
/*
* All mapped pages start out with page table
* references from the instantiating fault, so we need
* to look twice if a mapped file page is used more
* than once.
*
* Mark it and spare it for another trip around the
* inactive list. Another page table reference will
* lead to its activation.
*
* Note: the mark is set for activated pages as well
* so that recently deactivated but used pages are
* quickly recovered.
*/
SetPageReferenced(page);
if (referenced_page || referenced_ptes > 1)
return PAGEREF_ACTIVATE;
/*
* Activate file-backed executable pages after first usage.
*/
if (vm_flags & VM_EXEC)
return PAGEREF_ACTIVATE;
return PAGEREF_KEEP;
}
/* Reclaim if clean, defer dirty pages to writeback */
if (referenced_page && !PageSwapBacked(page))
return PAGEREF_RECLAIM_CLEAN;
return PAGEREF_RECLAIM;
}
/*
* shrink_page_list() returns the number of reclaimed pages
*/
static unsigned long shrink_page_list(struct list_head *page_list,
struct zone *zone,
struct scan_control *sc,
enum ttu_flags ttu_flags,
unsigned long *ret_nr_dirty,
unsigned long *ret_nr_writeback,
bool force_reclaim)
{
LIST_HEAD(ret_pages);
LIST_HEAD(free_pages);
int pgactivate = 0;
unsigned long nr_dirty = 0;
unsigned long nr_congested = 0;
unsigned long nr_reclaimed = 0;
unsigned long nr_writeback = 0;
cond_resched();
mem_cgroup_uncharge_start();
while (!list_empty(page_list)) {
struct address_space *mapping;
struct page *page;
int may_enter_fs;
enum page_references references = PAGEREF_RECLAIM_CLEAN;
cond_resched();
page = lru_to_page(page_list);
list_del(&page->lru);
if (!trylock_page(page))
goto keep;
VM_BUG_ON(PageActive(page));
VM_BUG_ON(page_zone(page) != zone);
sc->nr_scanned++;
if (unlikely(!page_evictable(page)))
goto cull_mlocked;
if (!sc->may_unmap && page_mapped(page))
goto keep_locked;
/* Double the slab pressure for mapped and swapcache pages */
if (page_mapped(page) || PageSwapCache(page))
sc->nr_scanned++;
may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
if (PageWriteback(page)) {
/*
* memcg doesn't have any dirty pages throttling so we
* could easily OOM just because too many pages are in
* writeback and there is nothing else to reclaim.
*
* Require may_enter_fs to wait on writeback, because
* fs may not have submitted IO yet. And a loop driver
* thread might enter reclaim, and deadlock if it waits
* on a page for which it is needed to do the write
* (loop masks off __GFP_IO|__GFP_FS for this reason);
* but more thought would probably show more reasons.
*/
if (global_reclaim(sc) ||
!PageReclaim(page) || !may_enter_fs) {
/*
* This is slightly racy - end_page_writeback()
* might have just cleared PageReclaim, then
* setting PageReclaim here end up interpreted
* as PageReadahead - but that does not matter
* enough to care. What we do want is for this
* page to have PageReclaim set next time memcg
* reclaim reaches the tests above, so it will
* then wait_on_page_writeback() to avoid OOM;
* and it's also appropriate in global reclaim.
*/
SetPageReclaim(page);
nr_writeback++;
goto keep_locked;
}
wait_on_page_writeback(page);
}
if (!force_reclaim)
references = page_check_references(page, sc);
switch (references) {
case PAGEREF_ACTIVATE:
goto activate_locked;
case PAGEREF_KEEP:
goto keep_locked;
case PAGEREF_RECLAIM:
case PAGEREF_RECLAIM_CLEAN:
; /* try to reclaim the page below */
}
/*
* Anonymous process memory has backing store?
* Try to allocate it some swap space here.
*/
if (PageAnon(page) && !PageSwapCache(page)) {
if (!(sc->gfp_mask & __GFP_IO))
goto keep_locked;
if (!add_to_swap(page, page_list))
goto activate_locked;
may_enter_fs = 1;
}
mapping = page_mapping(page);
/*
* The page is mapped into the page tables of one or more
* processes. Try to unmap it here.
*/
if (page_mapped(page) && mapping) {
switch (try_to_unmap(page, ttu_flags)) {
case SWAP_FAIL:
goto activate_locked;
case SWAP_AGAIN:
goto keep_locked;
case SWAP_MLOCK:
goto cull_mlocked;
case SWAP_SUCCESS:
; /* try to free the page below */
}
}
if (PageDirty(page)) {
nr_dirty++;
/*
* Only kswapd can writeback filesystem pages to
* avoid risk of stack overflow but do not writeback
* unless under significant pressure.
*/
if (page_is_file_cache(page) &&
(!current_is_kswapd() ||
sc->priority >= DEF_PRIORITY - 2)) {
/*
* Immediately reclaim when written back.
* Similar in principal to deactivate_page()
* except we already have the page isolated
* and know it's dirty
*/
inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
SetPageReclaim(page);
goto keep_locked;
}
if (references == PAGEREF_RECLAIM_CLEAN)
goto keep_locked;
if (!may_enter_fs)
goto keep_locked;
if (!sc->may_writepage)
goto keep_locked;
/* Page is dirty, try to write it out here */
switch (pageout(page, mapping, sc)) {
case PAGE_KEEP:
nr_congested++;
goto keep_locked;
case PAGE_ACTIVATE:
goto activate_locked;
case PAGE_SUCCESS:
if (PageWriteback(page))
goto keep;
if (PageDirty(page))
goto keep;
/*
* A synchronous write - probably a ramdisk. Go
* ahead and try to reclaim the page.
*/
if (!trylock_page(page))
goto keep;
if (PageDirty(page) || PageWriteback(page))
goto keep_locked;
mapping = page_mapping(page);
case PAGE_CLEAN:
; /* try to free the page below */
}
}
/*
* If the page has buffers, try to free the buffer mappings
* associated with this page. If we succeed we try to free
* the page as well.
*
* We do this even if the page is PageDirty().
* try_to_release_page() does not perform I/O, but it is
* possible for a page to have PageDirty set, but it is actually
* clean (all its buffers are clean). This happens if the
* buffers were written out directly, with submit_bh(). ext3
* will do this, as well as the blockdev mapping.
* try_to_release_page() will discover that cleanness and will
* drop the buffers and mark the page clean - it can be freed.
*
* Rarely, pages can have buffers and no ->mapping. These are
* the pages which were not successfully invalidated in
* truncate_complete_page(). We try to drop those buffers here
* and if that worked, and the page is no longer mapped into
* process address space (page_count == 1) it can be freed.
* Otherwise, leave the page on the LRU so it is swappable.
*/
if (page_has_private(page)) {
if (!try_to_release_page(page, sc->gfp_mask))
goto activate_locked;
if (!mapping && page_count(page) == 1) {
unlock_page(page);
if (put_page_testzero(page))
goto free_it;
else {
/*
* rare race with speculative reference.
* the speculative reference will free
* this page shortly, so we may
* increment nr_reclaimed here (and
* leave it off the LRU).
*/
nr_reclaimed++;
continue;
}
}
}
if (!mapping || !__remove_mapping(mapping, page))
goto keep_locked;
/*
* At this point, we have no other references and there is
* no way to pick any more up (removed from LRU, removed
* from pagecache). Can use non-atomic bitops now (and
* we obviously don't have to worry about waking up a process
* waiting on the page lock, because there are no references.
*/
__clear_page_locked(page);
free_it:
nr_reclaimed++;
/*
* Is there need to periodically free_page_list? It would
* appear not as the counts should be low
*/
list_add(&page->lru, &free_pages);
continue;
cull_mlocked:
if (PageSwapCache(page))
try_to_free_swap(page);
unlock_page(page);
list_add(&page->lru, &ret_pages);
continue;
activate_locked:
/* Not a candidate for swapping, so reclaim swap space. */
if (PageSwapCache(page) && vm_swap_full())
try_to_free_swap(page);
VM_BUG_ON(PageActive(page));
SetPageActive(page);
pgactivate++;
keep_locked:
unlock_page(page);
keep:
list_add(&page->lru, &ret_pages);
VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
}
/*
* Tag a zone as congested if all the dirty pages encountered were
* backed by a congested BDI. In this case, reclaimers should just
* back off and wait for congestion to clear because further reclaim
* will encounter the same problem
*/
if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
zone_set_flag(zone, ZONE_CONGESTED);
free_hot_cold_page_list(&free_pages, 1);
list_splice(&ret_pages, page_list);
count_vm_events(PGACTIVATE, pgactivate);
mem_cgroup_uncharge_end();
*ret_nr_dirty += nr_dirty;
*ret_nr_writeback += nr_writeback;
return nr_reclaimed;
}
unsigned long reclaim_clean_pages_from_list(struct zone *zone,
struct list_head *page_list)
{
struct scan_control sc = {
.gfp_mask = GFP_KERNEL,
.priority = DEF_PRIORITY,
.may_unmap = 1,
};
unsigned long ret, dummy1, dummy2;
struct page *page, *next;
LIST_HEAD(clean_pages);
list_for_each_entry_safe(page, next, page_list, lru) {
if (page_is_file_cache(page) && !PageDirty(page) &&
!isolated_balloon_page(page)) {
ClearPageActive(page);
list_move(&page->lru, &clean_pages);
}
}
ret = shrink_page_list(&clean_pages, zone, &sc,
TTU_UNMAP|TTU_IGNORE_ACCESS,
&dummy1, &dummy2, true);
list_splice(&clean_pages, page_list);
__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
return ret;
}
/*
* Attempt to remove the specified page from its LRU. Only take this page
* if it is of the appropriate PageActive status. Pages which are being
* freed elsewhere are also ignored.
*
* page: page to consider
* mode: one of the LRU isolation modes defined above
*
* returns 0 on success, -ve errno on failure.
*/
int __isolate_lru_page(struct page *page, isolate_mode_t mode)
{
int ret = -EINVAL;
/* Only take pages on the LRU. */
if (!PageLRU(page))
return ret;
/* Compaction should not handle unevictable pages but CMA can do so */
if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
return ret;
ret = -EBUSY;
/*
* To minimise LRU disruption, the caller can indicate that it only
* wants to isolate pages it will be able to operate on without
* blocking - clean pages for the most part.
*
* ISOLATE_CLEAN means that only clean pages should be isolated. This
* is used by reclaim when it is cannot write to backing storage
*
* ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
* that it is possible to migrate without blocking
*/
if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
/* All the caller can do on PageWriteback is block */
if (PageWriteback(page))
return ret;
if (PageDirty(page)) {
struct address_space *mapping;
/* ISOLATE_CLEAN means only clean pages */
if (mode & ISOLATE_CLEAN)
return ret;
/*
* Only pages without mappings or that have a
* ->migratepage callback are possible to migrate
* without blocking
*/
mapping = page_mapping(page);
if (mapping && !mapping->a_ops->migratepage)
return ret;
}
}
if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
return ret;
if (likely(get_page_unless_zero(page))) {
/*
* Be careful not to clear PageLRU until after we're
* sure the page is not being freed elsewhere -- the
* page release code relies on it.
*/
ClearPageLRU(page);
ret = 0;
}
return ret;
}
/*
* zone->lru_lock is heavily contended. Some of the functions that
* shrink the lists perform better by taking out a batch of pages
* and working on them outside the LRU lock.
*
* For pagecache intensive workloads, this function is the hottest
* spot in the kernel (apart from copy_*_user functions).
*
* Appropriate locks must be held before calling this function.
*
* @nr_to_scan: The number of pages to look through on the list.
* @lruvec: The LRU vector to pull pages from.
* @dst: The temp list to put pages on to.
* @nr_scanned: The number of pages that were scanned.
* @sc: The scan_control struct for this reclaim session
* @mode: One of the LRU isolation modes
* @lru: LRU list id for isolating
*
* returns how many pages were moved onto *@dst.
*/
static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
struct lruvec *lruvec, struct list_head *dst,
unsigned long *nr_scanned, struct scan_control *sc,
isolate_mode_t mode, enum lru_list lru)
{
struct list_head *src = &lruvec->lists[lru];
unsigned long nr_taken = 0;
unsigned long scan;
for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
struct page *page;
int nr_pages;
page = lru_to_page(src);
prefetchw_prev_lru_page(page, src, flags);
VM_BUG_ON(!PageLRU(page));
switch (__isolate_lru_page(page, mode)) {
case 0:
nr_pages = hpage_nr_pages(page);
mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
list_move(&page->lru, dst);
nr_taken += nr_pages;
break;
case -EBUSY:
/* else it is being freed elsewhere */
list_move(&page->lru, src);
continue;
default:
BUG();
}
}
*nr_scanned = scan;
trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
nr_taken, mode, is_file_lru(lru));
return nr_taken;
}
/**
* isolate_lru_page - tries to isolate a page from its LRU list
* @page: page to isolate from its LRU list
*
* Isolates a @page from an LRU list, clears PageLRU and adjusts the
* vmstat statistic corresponding to whatever LRU list the page was on.
*
* Returns 0 if the page was removed from an LRU list.
* Returns -EBUSY if the page was not on an LRU list.
*
* The returned page will have PageLRU() cleared. If it was found on
* the active list, it will have PageActive set. If it was found on
* the unevictable list, it will have the PageUnevictable bit set. That flag
* may need to be cleared by the caller before letting the page go.
*
* The vmstat statistic corresponding to the list on which the page was
* found will be decremented.
*
* Restrictions:
* (1) Must be called with an elevated refcount on the page. This is a
* fundamentnal difference from isolate_lru_pages (which is called
* without a stable reference).
* (2) the lru_lock must not be held.
* (3) interrupts must be enabled.
*/
int isolate_lru_page(struct page *page)
{
int ret = -EBUSY;
VM_BUG_ON(!page_count(page));
if (PageLRU(page)) {
struct zone *zone = page_zone(page);
struct lruvec *lruvec;
spin_lock_irq(&zone->lru_lock);
lruvec = mem_cgroup_page_lruvec(page, zone);
if (PageLRU(page)) {
int lru = page_lru(page);
get_page(page);
ClearPageLRU(page);
del_page_from_lru_list(page, lruvec, lru);
ret = 0;
}
spin_unlock_irq(&zone->lru_lock);
}
return ret;
}
/*
* A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
* then get resheduled. When there are massive number of tasks doing page
* allocation, such sleeping direct reclaimers may keep piling up on each CPU,
* the LRU list will go small and be scanned faster than necessary, leading to
* unnecessary swapping, thrashing and OOM.
*/
static int too_many_isolated(struct zone *zone, int file,
struct scan_control *sc)
{
unsigned long inactive, isolated;
if (current_is_kswapd())
return 0;
if (!global_reclaim(sc))
return 0;
if (file) {
inactive = zone_page_state(zone, NR_INACTIVE_FILE);
isolated = zone_page_state(zone, NR_ISOLATED_FILE);
} else {
inactive = zone_page_state(zone, NR_INACTIVE_ANON);
isolated = zone_page_state(zone, NR_ISOLATED_ANON);
}
/*
* GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
* won't get blocked by normal direct-reclaimers, forming a circular
* deadlock.
*/
if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
inactive >>= 3;
return isolated > inactive;
}
static noinline_for_stack void
putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
{
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
struct zone *zone = lruvec_zone(lruvec);
LIST_HEAD(pages_to_free);
/*
* Put back any unfreeable pages.
*/
while (!list_empty(page_list)) {
struct page *page = lru_to_page(page_list);
int lru;
VM_BUG_ON(PageLRU(page));
list_del(&page->lru);
if (unlikely(!page_evictable(page))) {
spin_unlock_irq(&zone->lru_lock);
putback_lru_page(page);
spin_lock_irq(&zone->lru_lock);
continue;
}
lruvec = mem_cgroup_page_lruvec(page, zone);
SetPageLRU(page);
lru = page_lru(page);
add_page_to_lru_list(page, lruvec, lru);
if (is_active_lru(lru)) {
int file = is_file_lru(lru);
int numpages = hpage_nr_pages(page);
reclaim_stat->recent_rotated[file] += numpages;
}
if (put_page_testzero(page)) {
__ClearPageLRU(page);
__ClearPageActive(page);
del_page_from_lru_list(page, lruvec, lru);
if (unlikely(PageCompound(page))) {
spin_unlock_irq(&zone->lru_lock);
(*get_compound_page_dtor(page))(page);
spin_lock_irq(&zone->lru_lock);
} else
list_add(&page->lru, &pages_to_free);
}
}
/*
* To save our caller's stack, now use input list for pages to free.
*/
list_splice(&pages_to_free, page_list);
}
/*
* shrink_inactive_list() is a helper for shrink_zone(). It returns the number
* of reclaimed pages
*/
static noinline_for_stack unsigned long
shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
struct scan_control *sc, enum lru_list lru)
{
LIST_HEAD(page_list);
unsigned long nr_scanned;
unsigned long nr_reclaimed = 0;
unsigned long nr_taken;
unsigned long nr_dirty = 0;
unsigned long nr_writeback = 0;
isolate_mode_t isolate_mode = 0;
int file = is_file_lru(lru);
struct zone *zone = lruvec_zone(lruvec);
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
while (unlikely(too_many_isolated(zone, file, sc))) {
congestion_wait(BLK_RW_ASYNC, HZ/10);
/* We are about to die and free our memory. Return now. */
if (fatal_signal_pending(current))
return SWAP_CLUSTER_MAX;
}
lru_add_drain();
if (!sc->may_unmap)
isolate_mode |= ISOLATE_UNMAPPED;
if (!sc->may_writepage)
isolate_mode |= ISOLATE_CLEAN;
spin_lock_irq(&zone->lru_lock);
nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
&nr_scanned, sc, isolate_mode, lru);
__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
if (global_reclaim(sc)) {
zone->pages_scanned += nr_scanned;
if (current_is_kswapd())
__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
else
__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
}
spin_unlock_irq(&zone->lru_lock);
if (nr_taken == 0)
return 0;
nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
&nr_dirty, &nr_writeback, false);
spin_lock_irq(&zone->lru_lock);
reclaim_stat->recent_scanned[file] += nr_taken;
if (global_reclaim(sc)) {
if (current_is_kswapd())
__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
nr_reclaimed);
else
__count_zone_vm_events(PGSTEAL_DIRECT, zone,
nr_reclaimed);
}
putback_inactive_pages(lruvec, &page_list);
__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
spin_unlock_irq(&zone->lru_lock);
free_hot_cold_page_list(&page_list, 1);
/*
* If reclaim is isolating dirty pages under writeback, it implies
* that the long-lived page allocation rate is exceeding the page
* laundering rate. Either the global limits are not being effective
* at throttling processes due to the page distribution throughout
* zones or there is heavy usage of a slow backing device. The
* only option is to throttle from reclaim context which is not ideal
* as there is no guarantee the dirtying process is throttled in the
* same way balance_dirty_pages() manages.
*
* This scales the number of dirty pages that must be under writeback
* before throttling depending on priority. It is a simple backoff
* function that has the most effect in the range DEF_PRIORITY to
* DEF_PRIORITY-2 which is the priority reclaim is considered to be
* in trouble and reclaim is considered to be in trouble.
*
* DEF_PRIORITY 100% isolated pages must be PageWriteback to throttle
* DEF_PRIORITY-1 50% must be PageWriteback
* DEF_PRIORITY-2 25% must be PageWriteback, kswapd in trouble
* ...
* DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
* isolated page is PageWriteback
*/
if (nr_writeback && nr_writeback >=
(nr_taken >> (DEF_PRIORITY - sc->priority)))
wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
zone_idx(zone),
nr_scanned, nr_reclaimed,
sc->priority,
trace_shrink_flags(file));
return nr_reclaimed;
}
/*
* This moves pages from the active list to the inactive list.
*
* We move them the other way if the page is referenced by one or more
* processes, from rmap.
*
* If the pages are mostly unmapped, the processing is fast and it is
* appropriate to hold zone->lru_lock across the whole operation. But if
* the pages are mapped, the processing is slow (page_referenced()) so we
* should drop zone->lru_lock around each page. It's impossible to balance
* this, so instead we remove the pages from the LRU while processing them.
* It is safe to rely on PG_active against the non-LRU pages in here because
* nobody will play with that bit on a non-LRU page.
*
* The downside is that we have to touch page->_count against each page.
* But we had to alter page->flags anyway.
*/
static void move_active_pages_to_lru(struct lruvec *lruvec,
struct list_head *list,
struct list_head *pages_to_free,
enum lru_list lru)
{
struct zone *zone = lruvec_zone(lruvec);
unsigned long pgmoved = 0;
struct page *page;
int nr_pages;
while (!list_empty(list)) {
page = lru_to_page(list);
lruvec = mem_cgroup_page_lruvec(page, zone);
VM_BUG_ON(PageLRU(page));
SetPageLRU(page);
nr_pages = hpage_nr_pages(page);
mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
list_move(&page->lru, &lruvec->lists[lru]);
pgmoved += nr_pages;
if (put_page_testzero(page)) {
__ClearPageLRU(page);
__ClearPageActive(page);
del_page_from_lru_list(page, lruvec, lru);
if (unlikely(PageCompound(page))) {
spin_unlock_irq(&zone->lru_lock);
(*get_compound_page_dtor(page))(page);
spin_lock_irq(&zone->lru_lock);
} else
list_add(&page->lru, pages_to_free);
}
}
__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
if (!is_active_lru(lru))
__count_vm_events(PGDEACTIVATE, pgmoved);
}
static void shrink_active_list(unsigned long nr_to_scan,
struct lruvec *lruvec,
struct scan_control *sc,
enum lru_list lru)
{
unsigned long nr_taken;
unsigned long nr_scanned;
unsigned long vm_flags;
LIST_HEAD(l_hold); /* The pages which were snipped off */
LIST_HEAD(l_active);
LIST_HEAD(l_inactive);
struct page *page;
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
unsigned long nr_rotated = 0;
isolate_mode_t isolate_mode = 0;
int file = is_file_lru(lru);
struct zone *zone = lruvec_zone(lruvec);
lru_add_drain();
if (!sc->may_unmap)
isolate_mode |= ISOLATE_UNMAPPED;
if (!sc->may_writepage)
isolate_mode |= ISOLATE_CLEAN;
spin_lock_irq(&zone->lru_lock);
nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
&nr_scanned, sc, isolate_mode, lru);
if (global_reclaim(sc))
zone->pages_scanned += nr_scanned;
reclaim_stat->recent_scanned[file] += nr_taken;
__count_zone_vm_events(PGREFILL, zone, nr_scanned);
__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
spin_unlock_irq(&zone->lru_lock);
while (!list_empty(&l_hold)) {
cond_resched();
page = lru_to_page(&l_hold);
list_del(&page->lru);
if (unlikely(!page_evictable(page))) {
putback_lru_page(page);
continue;
}
if (unlikely(buffer_heads_over_limit)) {
if (page_has_private(page) && trylock_page(page)) {
if (page_has_private(page))
try_to_release_page(page, 0);
unlock_page(page);
}
}
if (page_referenced(page, 0, sc->target_mem_cgroup,
&vm_flags)) {
nr_rotated += hpage_nr_pages(page);
/*
* Identify referenced, file-backed active pages and
* give them one more trip around the active list. So
* that executable code get better chances to stay in
* memory under moderate memory pressure. Anon pages
* are not likely to be evicted by use-once streaming
* IO, plus JVM can create lots of anon VM_EXEC pages,
* so we ignore them here.
*/
if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
list_add(&page->lru, &l_active);
continue;
}
}
ClearPageActive(page); /* we are de-activating */
list_add(&page->lru, &l_inactive);
}
/*
* Move pages back to the lru list.
*/
spin_lock_irq(&zone->lru_lock);
/*
* Count referenced pages from currently used mappings as rotated,
* even though only some of them are actually re-activated. This
* helps balance scan pressure between file and anonymous pages in
* get_scan_ratio.
*/
reclaim_stat->recent_rotated[file] += nr_rotated;
move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
spin_unlock_irq(&zone->lru_lock);
free_hot_cold_page_list(&l_hold, 1);
}
#ifdef CONFIG_SWAP
static int inactive_anon_is_low_global(struct zone *zone)
{
unsigned long active, inactive;
active = zone_page_state(zone, NR_ACTIVE_ANON);
inactive = zone_page_state(zone, NR_INACTIVE_ANON);
if (inactive * zone->inactive_ratio < active)
return 1;
return 0;
}
/**
* inactive_anon_is_low - check if anonymous pages need to be deactivated
* @lruvec: LRU vector to check
*
* Returns true if the zone does not have enough inactive anon pages,
* meaning some active anon pages need to be deactivated.
*/
static int inactive_anon_is_low(struct lruvec *lruvec)
{
/*
* If we don't have swap space, anonymous page deactivation
* is pointless.
*/
if (!total_swap_pages)
return 0;
if (!mem_cgroup_disabled())
return mem_cgroup_inactive_anon_is_low(lruvec);
return inactive_anon_is_low_global(lruvec_zone(lruvec));
}
#else
static inline int inactive_anon_is_low(struct lruvec *lruvec)
{
return 0;
}
#endif
/**
* inactive_file_is_low - check if file pages need to be deactivated
* @lruvec: LRU vector to check
*
* When the system is doing streaming IO, memory pressure here
* ensures that active file pages get deactivated, until more
* than half of the file pages are on the inactive list.
*
* Once we get to that situation, protect the system's working
* set from being evicted by disabling active file page aging.
*
* This uses a different ratio than the anonymous pages, because
* the page cache uses a use-once replacement algorithm.
*/
static int inactive_file_is_low(struct lruvec *lruvec)
{
unsigned long inactive;
unsigned long active;
inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
return active > inactive;
}
static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
{
if (is_file_lru(lru))
return inactive_file_is_low(lruvec);
else
return inactive_anon_is_low(lruvec);
}
static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
struct lruvec *lruvec, struct scan_control *sc)
{
if (is_active_lru(lru)) {
if (inactive_list_is_low(lruvec, lru))
shrink_active_list(nr_to_scan, lruvec, sc, lru);
return 0;
}
return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
}
static int vmscan_swappiness(struct scan_control *sc)
{
if (global_reclaim(sc))
return vm_swappiness;
return mem_cgroup_swappiness(sc->target_mem_cgroup);
}
enum scan_balance {
SCAN_EQUAL,
SCAN_FRACT,
SCAN_ANON,
SCAN_FILE,
};
/*
* Determine how aggressively the anon and file LRU lists should be
* scanned. The relative value of each set of LRU lists is determined
* by looking at the fraction of the pages scanned we did rotate back
* onto the active list instead of evict.
*
* nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
* nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
*/
static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
unsigned long *nr)
{
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
u64 fraction[2];
u64 denominator = 0; /* gcc */
struct zone *zone = lruvec_zone(lruvec);
unsigned long anon_prio, file_prio;
enum scan_balance scan_balance;
unsigned long anon, file, free;
bool force_scan = false;
unsigned long ap, fp;
enum lru_list lru;
/*
* If the zone or memcg is small, nr[l] can be 0. This
* results in no scanning on this priority and a potential
* priority drop. Global direct reclaim can go to the next
* zone and tends to have no problems. Global kswapd is for
* zone balancing and it needs to scan a minimum amount. When
* reclaiming for a memcg, a priority drop can cause high
* latencies, so it's better to scan a minimum amount there as
* well.
*/
if (current_is_kswapd() && zone->all_unreclaimable)
force_scan = true;
if (!global_reclaim(sc))
force_scan = true;
/* If we have no swap space, do not bother scanning anon pages. */
if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
scan_balance = SCAN_FILE;
goto out;
}
/*
* Global reclaim will swap to prevent OOM even with no
* swappiness, but memcg users want to use this knob to
* disable swapping for individual groups completely when
* using the memory controller's swap limit feature would be
* too expensive.
*/
if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
scan_balance = SCAN_FILE;
goto out;
}
/*
* Do not apply any pressure balancing cleverness when the
* system is close to OOM, scan both anon and file equally
* (unless the swappiness setting disagrees with swapping).
*/
if (!sc->priority && vmscan_swappiness(sc)) {
scan_balance = SCAN_EQUAL;
goto out;
}
anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
get_lru_size(lruvec, LRU_INACTIVE_ANON);
file = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
get_lru_size(lruvec, LRU_INACTIVE_FILE);
/*
* If it's foreseeable that reclaiming the file cache won't be
* enough to get the zone back into a desirable shape, we have
* to swap. Better start now and leave the - probably heavily
* thrashing - remaining file pages alone.
*/
if (global_reclaim(sc)) {
free = zone_page_state(zone, NR_FREE_PAGES);
if (unlikely(file + free <= high_wmark_pages(zone))) {
scan_balance = SCAN_ANON;
goto out;
}
}
/*
* There is enough inactive page cache, do not reclaim
* anything from the anonymous working set right now.
*/
if (!inactive_file_is_low(lruvec)) {
scan_balance = SCAN_FILE;
goto out;
}
scan_balance = SCAN_FRACT;
/*
* With swappiness at 100, anonymous and file have the same priority.
* This scanning priority is essentially the inverse of IO cost.
*/
anon_prio = vmscan_swappiness(sc);
file_prio = 200 - anon_prio;
/*
* OK, so we have swap space and a fair amount of page cache
* pages. We use the recently rotated / recently scanned
* ratios to determine how valuable each cache is.
*
* Because workloads change over time (and to avoid overflow)
* we keep these statistics as a floating average, which ends
* up weighing recent references more than old ones.
*
* anon in [0], file in [1]
*/
spin_lock_irq(&zone->lru_lock);
if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
reclaim_stat->recent_scanned[0] /= 2;
reclaim_stat->recent_rotated[0] /= 2;
}
if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
reclaim_stat->recent_scanned[1] /= 2;
reclaim_stat->recent_rotated[1] /= 2;
}
/*
* The amount of pressure on anon vs file pages is inversely
* proportional to the fraction of recently scanned pages on
* each list that were recently referenced and in active use.
*/
ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
ap /= reclaim_stat->recent_rotated[0] + 1;
fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
fp /= reclaim_stat->recent_rotated[1] + 1;
spin_unlock_irq(&zone->lru_lock);
fraction[0] = ap;
fraction[1] = fp;
denominator = ap + fp + 1;
out:
for_each_evictable_lru(lru) {
int file = is_file_lru(lru);
unsigned long size;
unsigned long scan;
size = get_lru_size(lruvec, lru);
scan = size >> sc->priority;
if (!scan && force_scan)
scan = min(size, SWAP_CLUSTER_MAX);
switch (scan_balance) {
case SCAN_EQUAL:
/* Scan lists relative to size */
break;
case SCAN_FRACT:
/*
* Scan types proportional to swappiness and
* their relative recent reclaim efficiency.
*/
scan = div64_u64(scan * fraction[file], denominator);
break;
case SCAN_FILE:
case SCAN_ANON:
/* Scan one type exclusively */
if ((scan_balance == SCAN_FILE) != file)
scan = 0;
break;
default:
/* Look ma, no brain */
BUG();
}
nr[lru] = scan;
}
}
/*
* This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
*/
static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
{
unsigned long nr[NR_LRU_LISTS];
unsigned long nr_to_scan;
enum lru_list lru;
unsigned long nr_reclaimed = 0;
unsigned long nr_to_reclaim = sc->nr_to_reclaim;
struct blk_plug plug;
get_scan_count(lruvec, sc, nr);
blk_start_plug(&plug);
while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
nr[LRU_INACTIVE_FILE]) {
for_each_evictable_lru(lru) {
if (nr[lru]) {
nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
nr[lru] -= nr_to_scan;
nr_reclaimed += shrink_list(lru, nr_to_scan,
lruvec, sc);
}
}
/*
* On large memory systems, scan >> priority can become
* really large. This is fine for the starting priority;
* we want to put equal scanning pressure on each zone.
* However, if the VM has a harder time of freeing pages,
* with multiple processes reclaiming pages, the total
* freeing target can get unreasonably large.
*/
if (nr_reclaimed >= nr_to_reclaim &&
sc->priority < DEF_PRIORITY)
break;
}
blk_finish_plug(&plug);
sc->nr_reclaimed += nr_reclaimed;
/*
* Even if we did not try to evict anon pages at all, we want to
* rebalance the anon lru active/inactive ratio.
*/
if (inactive_anon_is_low(lruvec))
shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
sc, LRU_ACTIVE_ANON);
throttle_vm_writeout(sc->gfp_mask);
}
/* Use reclaim/compaction for costly allocs or under memory pressure */
static bool in_reclaim_compaction(struct scan_control *sc)
{
if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
sc->priority < DEF_PRIORITY - 2))
return true;
return false;
}
/*
* Reclaim/compaction is used for high-order allocation requests. It reclaims
* order-0 pages before compacting the zone. should_continue_reclaim() returns
* true if more pages should be reclaimed such that when the page allocator
* calls try_to_compact_zone() that it will have enough free pages to succeed.
* It will give up earlier than that if there is difficulty reclaiming pages.
*/
static inline bool should_continue_reclaim(struct zone *zone,
unsigned long nr_reclaimed,
unsigned long nr_scanned,
struct scan_control *sc)
{
unsigned long pages_for_compaction;
unsigned long inactive_lru_pages;
/* If not in reclaim/compaction mode, stop */
if (!in_reclaim_compaction(sc))
return false;
/* Consider stopping depending on scan and reclaim activity */
if (sc->gfp_mask & __GFP_REPEAT) {
/*
* For __GFP_REPEAT allocations, stop reclaiming if the
* full LRU list has been scanned and we are still failing
* to reclaim pages. This full LRU scan is potentially
* expensive but a __GFP_REPEAT caller really wants to succeed
*/
if (!nr_reclaimed && !nr_scanned)
return false;
} else {
/*
* For non-__GFP_REPEAT allocations which can presumably
* fail without consequence, stop if we failed to reclaim
* any pages from the last SWAP_CLUSTER_MAX number of
* pages that were scanned. This will return to the
* caller faster at the risk reclaim/compaction and
* the resulting allocation attempt fails
*/
if (!nr_reclaimed)
return false;
}
/*
* If we have not reclaimed enough pages for compaction and the
* inactive lists are large enough, continue reclaiming
*/
pages_for_compaction = (2UL << sc->order);
inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
if (get_nr_swap_pages() > 0)
inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
if (sc->nr_reclaimed < pages_for_compaction &&
inactive_lru_pages > pages_for_compaction)
return true;
/* If compaction would go ahead or the allocation would succeed, stop */
switch (compaction_suitable(zone, sc->order)) {
case COMPACT_PARTIAL:
case COMPACT_CONTINUE:
return false;
default:
return true;
}
}
static void shrink_zone(struct zone *zone, struct scan_control *sc)
{
unsigned long nr_reclaimed, nr_scanned;
do {
struct mem_cgroup *root = sc->target_mem_cgroup;
struct mem_cgroup_reclaim_cookie reclaim = {
.zone = zone,
.priority = sc->priority,
};
struct mem_cgroup *memcg;
nr_reclaimed = sc->nr_reclaimed;
nr_scanned = sc->nr_scanned;
memcg = mem_cgroup_iter(root, NULL, &reclaim);
do {
struct lruvec *lruvec;
lruvec = mem_cgroup_zone_lruvec(zone, memcg);
shrink_lruvec(lruvec, sc);
/*
* Direct reclaim and kswapd have to scan all memory
* cgroups to fulfill the overall scan target for the
* zone.
*
* Limit reclaim, on the other hand, only cares about
* nr_to_reclaim pages to be reclaimed and it will
* retry with decreasing priority if one round over the
* whole hierarchy is not sufficient.
*/
if (!global_reclaim(sc) &&
sc->nr_reclaimed >= sc->nr_to_reclaim) {
mem_cgroup_iter_break(root, memcg);
break;
}
memcg = mem_cgroup_iter(root, memcg, &reclaim);
} while (memcg);
vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
sc->nr_scanned - nr_scanned,
sc->nr_reclaimed - nr_reclaimed);
} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
sc->nr_scanned - nr_scanned, sc));
}
/* Returns true if compaction should go ahead for a high-order request */
static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
{
unsigned long balance_gap, watermark;
bool watermark_ok;
/* Do not consider compaction for orders reclaim is meant to satisfy */
if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
return false;
/*
* Compaction takes time to run and there are potentially other
* callers using the pages just freed. Continue reclaiming until
* there is a buffer of free pages available to give compaction
* a reasonable chance of completing and allocating the page
*/
balance_gap = min(low_wmark_pages(zone),
(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
KSWAPD_ZONE_BALANCE_GAP_RATIO);
watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
/*
* If compaction is deferred, reclaim up to a point where
* compaction will have a chance of success when re-enabled
*/
if (compaction_deferred(zone, sc->order))
return watermark_ok;
/* If compaction is not ready to start, keep reclaiming */
if (!compaction_suitable(zone, sc->order))
return false;
return watermark_ok;
}
/*
* This is the direct reclaim path, for page-allocating processes. We only
* try to reclaim pages from zones which will satisfy the caller's allocation
* request.
*
* We reclaim from a zone even if that zone is over high_wmark_pages(zone).
* Because:
* a) The caller may be trying to free *extra* pages to satisfy a higher-order
* allocation or
* b) The target zone may be at high_wmark_pages(zone) but the lower zones
* must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
* zone defense algorithm.
*
* If a zone is deemed to be full of pinned pages then just give it a light
* scan then give up on it.
*
* This function returns true if a zone is being reclaimed for a costly
* high-order allocation and compaction is ready to begin. This indicates to
* the caller that it should consider retrying the allocation instead of
* further reclaim.
*/
static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
{
struct zoneref *z;
struct zone *zone;
unsigned long nr_soft_reclaimed;
unsigned long nr_soft_scanned;
bool aborted_reclaim = false;
/*
* If the number of buffer_heads in the machine exceeds the maximum
* allowed level, force direct reclaim to scan the highmem zone as
* highmem pages could be pinning lowmem pages storing buffer_heads
*/
if (buffer_heads_over_limit)
sc->gfp_mask |= __GFP_HIGHMEM;
for_each_zone_zonelist_nodemask(zone, z, zonelist,
gfp_zone(sc->gfp_mask), sc->nodemask) {
if (!populated_zone(zone))
continue;
/*
* Take care memory controller reclaiming has small influence
* to global LRU.
*/
if (global_reclaim(sc)) {
if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
continue;
if (zone->all_unreclaimable &&
sc->priority != DEF_PRIORITY)
continue; /* Let kswapd poll it */
if (IS_ENABLED(CONFIG_COMPACTION)) {
/*
* If we already have plenty of memory free for
* compaction in this zone, don't free any more.
* Even though compaction is invoked for any
* non-zero order, only frequent costly order
* reclamation is disruptive enough to become a
* noticeable problem, like transparent huge
* page allocations.
*/
if (compaction_ready(zone, sc)) {
aborted_reclaim = true;
continue;
}
}
/*
* This steals pages from memory cgroups over softlimit
* and returns the number of reclaimed pages and
* scanned pages. This works for global memory pressure
* and balancing, not for a memcg's limit.
*/
nr_soft_scanned = 0;
nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
sc->order, sc->gfp_mask,
&nr_soft_scanned);
sc->nr_reclaimed += nr_soft_reclaimed;
sc->nr_scanned += nr_soft_scanned;
/* need some check for avoid more shrink_zone() */
}
shrink_zone(zone, sc);
}
return aborted_reclaim;
}
static unsigned long zone_reclaimable_pages(struct zone *zone)
{
int nr;
nr = zone_page_state(zone, NR_ACTIVE_FILE) +
zone_page_state(zone, NR_INACTIVE_FILE);
if (get_nr_swap_pages() > 0)
nr += zone_page_state(zone, NR_ACTIVE_ANON) +
zone_page_state(zone, NR_INACTIVE_ANON);
return nr;
}
static bool zone_reclaimable(struct zone *zone)
{
return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
}
/* All zones in zonelist are unreclaimable? */
static bool all_unreclaimable(struct zonelist *zonelist,
struct scan_control *sc)
{
struct zoneref *z;
struct zone *zone;
for_each_zone_zonelist_nodemask(zone, z, zonelist,
gfp_zone(sc->gfp_mask), sc->nodemask) {
if (!populated_zone(zone))
continue;
if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
continue;
if (!zone->all_unreclaimable)
return false;
}
return true;
}
/*
* This is the main entry point to direct page reclaim.
*
* If a full scan of the inactive list fails to free enough memory then we
* are "out of memory" and something needs to be killed.
*
* If the caller is !__GFP_FS then the probability of a failure is reasonably
* high - the zone may be full of dirty or under-writeback pages, which this
* caller can't do much about. We kick the writeback threads and take explicit
* naps in the hope that some of these pages can be written. But if the
* allocating task holds filesystem locks which prevent writeout this might not
* work, and the allocation attempt will fail.
*
* returns: 0, if no pages reclaimed
* else, the number of pages reclaimed
*/
static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
struct scan_control *sc,
struct shrink_control *shrink)
{
unsigned long total_scanned = 0;
struct reclaim_state *reclaim_state = current->reclaim_state;
struct zoneref *z;
struct zone *zone;
unsigned long writeback_threshold;
bool aborted_reclaim;
delayacct_freepages_start();
if (global_reclaim(sc))
count_vm_event(ALLOCSTALL);
do {
vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
sc->priority);
sc->nr_scanned = 0;
aborted_reclaim = shrink_zones(zonelist, sc);
/*
* Don't shrink slabs when reclaiming memory from
* over limit cgroups
*/
if (global_reclaim(sc)) {
unsigned long lru_pages = 0;
for_each_zone_zonelist(zone, z, zonelist,
gfp_zone(sc->gfp_mask)) {
if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
continue;
lru_pages += zone_reclaimable_pages(zone);
}
shrink_slab(shrink, sc->nr_scanned, lru_pages);
if (reclaim_state) {
sc->nr_reclaimed += reclaim_state->reclaimed_slab;
reclaim_state->reclaimed_slab = 0;
}
}
total_scanned += sc->nr_scanned;
if (sc->nr_reclaimed >= sc->nr_to_reclaim)
goto out;
/*
* If we're getting trouble reclaiming, start doing
* writepage even in laptop mode.
*/
if (sc->priority < DEF_PRIORITY - 2)
sc->may_writepage = 1;
/*
* Try to write back as many pages as we just scanned. This
* tends to cause slow streaming writers to write data to the
* disk smoothly, at the dirtying rate, which is nice. But
* that's undesirable in laptop mode, where we *want* lumpy
* writeout. So in laptop mode, write out the whole world.
*/
writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
if (total_scanned > writeback_threshold) {
wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
WB_REASON_TRY_TO_FREE_PAGES);
sc->may_writepage = 1;
}
/* Take a nap, wait for some writeback to complete */
if (!sc->hibernation_mode && sc->nr_scanned &&
sc->priority < DEF_PRIORITY - 2) {
struct zone *preferred_zone;
first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
&cpuset_current_mems_allowed,
&preferred_zone);
wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
}
} while (--sc->priority >= 0);
out:
delayacct_freepages_end();
if (sc->nr_reclaimed)
return sc->nr_reclaimed;
/*
* As hibernation is going on, kswapd is freezed so that it can't mark
* the zone into all_unreclaimable. Thus bypassing all_unreclaimable
* check.
*/
if (oom_killer_disabled)
return 0;
/* Aborted reclaim to try compaction? don't OOM, then */
if (aborted_reclaim)
return 1;
/* top priority shrink_zones still had more to do? don't OOM, then */
if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
return 1;
return 0;
}
static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
{
struct zone *zone;
unsigned long pfmemalloc_reserve = 0;
unsigned long free_pages = 0;
int i;
bool wmark_ok;
for (i = 0; i <= ZONE_NORMAL; i++) {
zone = &pgdat->node_zones[i];
if (!populated_zone(zone))
continue;
pfmemalloc_reserve += min_wmark_pages(zone);
free_pages += zone_page_state(zone, NR_FREE_PAGES);
}
/* If there are no reserves (unexpected config) then do not throttle */
if (!pfmemalloc_reserve)
return true;
wmark_ok = free_pages > pfmemalloc_reserve / 2;
/* kswapd must be awake if processes are being throttled */
if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
pgdat->classzone_idx = min(pgdat->classzone_idx,
(enum zone_type)ZONE_NORMAL);
wake_up_interruptible(&pgdat->kswapd_wait);
}
return wmark_ok;
}
/*
* Throttle direct reclaimers if backing storage is backed by the network
* and the PFMEMALLOC reserve for the preferred node is getting dangerously
* depleted. kswapd will continue to make progress and wake the processes
* when the low watermark is reached.
*
* Returns true if a fatal signal was delivered during throttling. If this
* happens, the page allocator should not consider triggering the OOM killer.
*/
static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
nodemask_t *nodemask)
{
struct zoneref *z;
struct zone *zone;
pg_data_t *pgdat = NULL;
/*
* Kernel threads should not be throttled as they may be indirectly
* responsible for cleaning pages necessary for reclaim to make forward
* progress. kjournald for example may enter direct reclaim while
* committing a transaction where throttling it could forcing other
* processes to block on log_wait_commit().
*/
if (current->flags & PF_KTHREAD)
goto out;
/*
* If a fatal signal is pending, this process should not throttle.
* It should return quickly so it can exit and free its memory
*/
if (fatal_signal_pending(current))
goto out;
/*
* Check if the pfmemalloc reserves are ok by finding the first node
* with a usable ZONE_NORMAL or lower zone. The expectation is that
* GFP_KERNEL will be required for allocating network buffers when
* swapping over the network so ZONE_HIGHMEM is unusable.
*
* Throttling is based on the first usable node and throttled processes
* wait on a queue until kswapd makes progress and wakes them. There
* is an affinity then between processes waking up and where reclaim
* progress has been made assuming the process wakes on the same node.
* More importantly, processes running on remote nodes will not compete
* for remote pfmemalloc reserves and processes on different nodes
* should make reasonable progress.
*/
for_each_zone_zonelist_nodemask(zone, z, zonelist,
gfp_mask, nodemask) {
if (zone_idx(zone) > ZONE_NORMAL)
continue;
/* Throttle based on the first usable node */
pgdat = zone->zone_pgdat;
if (pfmemalloc_watermark_ok(pgdat))
goto out;
break;
}
/* If no zone was usable by the allocation flags then do not throttle */
if (!pgdat)
goto out;
/* Account for the throttling */
count_vm_event(PGSCAN_DIRECT_THROTTLE);
/*
* If the caller cannot enter the filesystem, it's possible that it
* is due to the caller holding an FS lock or performing a journal
* transaction in the case of a filesystem like ext[3|4]. In this case,
* it is not safe to block on pfmemalloc_wait as kswapd could be
* blocked waiting on the same lock. Instead, throttle for up to a
* second before continuing.
*/
if (!(gfp_mask & __GFP_FS)) {
wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
pfmemalloc_watermark_ok(pgdat), HZ);
goto check_pending;
}
/* Throttle until kswapd wakes the process */
wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
pfmemalloc_watermark_ok(pgdat));
check_pending:
if (fatal_signal_pending(current))
return true;
out:
return false;
}
unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
gfp_t gfp_mask, nodemask_t *nodemask)
{
unsigned long nr_reclaimed;
struct scan_control sc = {
.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
.may_writepage = !laptop_mode,
.nr_to_reclaim = SWAP_CLUSTER_MAX,
.may_unmap = 1,
.may_swap = 1,
.order = order,
.priority = DEF_PRIORITY,
.target_mem_cgroup = NULL,
.nodemask = nodemask,
};
struct shrink_control shrink = {
.gfp_mask = sc.gfp_mask,
};
/*
* Do not enter reclaim if fatal signal was delivered while throttled.
* 1 is returned so that the page allocator does not OOM kill at this
* point.
*/
if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
return 1;
trace_mm_vmscan_direct_reclaim_begin(order,
sc.may_writepage,
gfp_mask);
nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
return nr_reclaimed;
}
#ifdef CONFIG_MEMCG
unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
gfp_t gfp_mask, bool noswap,
struct zone *zone,
unsigned long *nr_scanned)
{
struct scan_control sc = {
.nr_scanned = 0,
.nr_to_reclaim = SWAP_CLUSTER_MAX,
.may_writepage = !laptop_mode,
.may_unmap = 1,
.may_swap = !noswap,
.order = 0,
.priority = 0,
.target_mem_cgroup = memcg,
};
struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
sc.may_writepage,
sc.gfp_mask);
/*
* NOTE: Although we can get the priority field, using it
* here is not a good idea, since it limits the pages we can scan.
* if we don't reclaim here, the shrink_zone from balance_pgdat
* will pick up pages from other mem cgroup's as well. We hack
* the priority and make it zero.
*/
shrink_lruvec(lruvec, &sc);
trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
*nr_scanned = sc.nr_scanned;
return sc.nr_reclaimed;
}
unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
gfp_t gfp_mask,
bool noswap)
{
struct zonelist *zonelist;
unsigned long nr_reclaimed;
int nid;
struct scan_control sc = {
.may_writepage = !laptop_mode,
.may_unmap = 1,
.may_swap = !noswap,
.nr_to_reclaim = SWAP_CLUSTER_MAX,
.order = 0,
.priority = DEF_PRIORITY,
.target_mem_cgroup = memcg,
.nodemask = NULL, /* we don't care the placement */
.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
};
struct shrink_control shrink = {
.gfp_mask = sc.gfp_mask,
};
/*
* Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
* take care of from where we get pages. So the node where we start the
* scan does not need to be the current node.
*/
nid = mem_cgroup_select_victim_node(memcg);
zonelist = NODE_DATA(nid)->node_zonelists;
trace_mm_vmscan_memcg_reclaim_begin(0,
sc.may_writepage,
sc.gfp_mask);
nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
return nr_reclaimed;
}
#endif
static void age_active_anon(struct zone *zone, struct scan_control *sc)
{
struct mem_cgroup *memcg;
if (!total_swap_pages)
return;
memcg = mem_cgroup_iter(NULL, NULL, NULL);
do {
struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
if (inactive_anon_is_low(lruvec))
shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
sc, LRU_ACTIVE_ANON);
memcg = mem_cgroup_iter(NULL, memcg, NULL);
} while (memcg);
}
static bool zone_balanced(struct zone *zone, int order,
unsigned long balance_gap, int classzone_idx)
{
if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
balance_gap, classzone_idx, 0))
return false;
if (IS_ENABLED(CONFIG_COMPACTION) && order &&
!compaction_suitable(zone, order))
return false;
return true;
}
/*
* pgdat_balanced() is used when checking if a node is balanced.
*
* For order-0, all zones must be balanced!
*
* For high-order allocations only zones that meet watermarks and are in a
* zone allowed by the callers classzone_idx are added to balanced_pages. The
* total of balanced pages must be at least 25% of the zones allowed by
* classzone_idx for the node to be considered balanced. Forcing all zones to
* be balanced for high orders can cause excessive reclaim when there are
* imbalanced zones.
* The choice of 25% is due to
* o a 16M DMA zone that is balanced will not balance a zone on any
* reasonable sized machine
* o On all other machines, the top zone must be at least a reasonable
* percentage of the middle zones. For example, on 32-bit x86, highmem
* would need to be at least 256M for it to be balance a whole node.
* Similarly, on x86-64 the Normal zone would need to be at least 1G
* to balance a node on its own. These seemed like reasonable ratios.
*/
static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
{
unsigned long managed_pages = 0;
unsigned long balanced_pages = 0;
int i;
/* Check the watermark levels */
for (i = 0; i <= classzone_idx; i++) {
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
managed_pages += zone->managed_pages;
/*
* A special case here:
*
* balance_pgdat() skips over all_unreclaimable after
* DEF_PRIORITY. Effectively, it considers them balanced so
* they must be considered balanced here as well!
*/
if (zone->all_unreclaimable) {
balanced_pages += zone->managed_pages;
continue;
}
if (zone_balanced(zone, order, 0, i))
balanced_pages += zone->managed_pages;
else if (!order)
return false;
}
if (order)
return balanced_pages >= (managed_pages >> 2);
else
return true;
}
/*
* Prepare kswapd for sleeping. This verifies that there are no processes
* waiting in throttle_direct_reclaim() and that watermarks have been met.
*
* Returns true if kswapd is ready to sleep
*/
static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
int classzone_idx)
{
/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
if (remaining)
return false;
/*
* The throttled processes are normally woken up in balance_pgdat() as
* soon as pfmemalloc_watermark_ok() is true. But there is a potential
* race between when kswapd checks the watermarks and a process gets
* throttled. There is also a potential race if processes get
* throttled, kswapd wakes, a large process exits thereby balancing the
* zones, which causes kswapd to exit balance_pgdat() before reaching
* the wake up checks. If kswapd is going to sleep, no process should
* be sleeping on pfmemalloc_wait, so wake them now if necessary. If
* the wake up is premature, processes will wake kswapd and get
* throttled again. The difference from wake ups in balance_pgdat() is
* that here we are under prepare_to_wait().
*/
if (waitqueue_active(&pgdat->pfmemalloc_wait))
wake_up_all(&pgdat->pfmemalloc_wait);
return pgdat_balanced(pgdat, order, classzone_idx);
}
/*
* For kswapd, balance_pgdat() will work across all this node's zones until
* they are all at high_wmark_pages(zone).
*
* Returns the final order kswapd was reclaiming at
*
* There is special handling here for zones which are full of pinned pages.
* This can happen if the pages are all mlocked, or if they are all used by
* device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
* What we do is to detect the case where all pages in the zone have been
* scanned twice and there has been zero successful reclaim. Mark the zone as
* dead and from now on, only perform a short scan. Basically we're polling
* the zone for when the problem goes away.
*
* kswapd scans the zones in the highmem->normal->dma direction. It skips
* zones which have free_pages > high_wmark_pages(zone), but once a zone is
* found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
* lower zones regardless of the number of free pages in the lower zones. This
* interoperates with the page allocator fallback scheme to ensure that aging
* of pages is balanced across the zones.
*/
static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
int *classzone_idx)
{
bool pgdat_is_balanced = false;
int i;
int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
struct reclaim_state *reclaim_state = current->reclaim_state;
unsigned long nr_soft_reclaimed;
unsigned long nr_soft_scanned;
struct scan_control sc = {
.gfp_mask = GFP_KERNEL,
.may_unmap = 1,
.may_swap = 1,
/*
* kswapd doesn't want to be bailed out while reclaim. because
* we want to put equal scanning pressure on each zone.
*/
.nr_to_reclaim = ULONG_MAX,
.order = order,
.target_mem_cgroup = NULL,
};
struct shrink_control shrink = {
.gfp_mask = sc.gfp_mask,
};
loop_again:
sc.priority = DEF_PRIORITY;
sc.nr_reclaimed = 0;
sc.may_writepage = !laptop_mode;
count_vm_event(PAGEOUTRUN);
do {
unsigned long lru_pages = 0;
/*
* Scan in the highmem->dma direction for the highest
* zone which needs scanning
*/
for (i = pgdat->nr_zones - 1; i >= 0; i--) {
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
if (zone->all_unreclaimable &&
sc.priority != DEF_PRIORITY)
continue;
/*
* Do some background aging of the anon list, to give
* pages a chance to be referenced before reclaiming.
*/
age_active_anon(zone, &sc);
/*
* If the number of buffer_heads in the machine
* exceeds the maximum allowed level and this node
* has a highmem zone, force kswapd to reclaim from
* it to relieve lowmem pressure.
*/
if (buffer_heads_over_limit && is_highmem_idx(i)) {
end_zone = i;
break;
}
if (!zone_balanced(zone, order, 0, 0)) {
end_zone = i;
break;
} else {
/* If balanced, clear the congested flag */
zone_clear_flag(zone, ZONE_CONGESTED);
}
}
if (i < 0) {
pgdat_is_balanced = true;
goto out;
}
for (i = 0; i <= end_zone; i++) {
struct zone *zone = pgdat->node_zones + i;
lru_pages += zone_reclaimable_pages(zone);
}
/*
* Now scan the zone in the dma->highmem direction, stopping
* at the last zone which needs scanning.
*
* We do this because the page allocator works in the opposite
* direction. This prevents the page allocator from allocating
* pages behind kswapd's direction of progress, which would
* cause too much scanning of the lower zones.
*/
for (i = 0; i <= end_zone; i++) {
struct zone *zone = pgdat->node_zones + i;
int nr_slab, testorder;
unsigned long balance_gap;
if (!populated_zone(zone))
continue;
if (zone->all_unreclaimable &&
sc.priority != DEF_PRIORITY)
continue;
sc.nr_scanned = 0;
nr_soft_scanned = 0;
/*
* Call soft limit reclaim before calling shrink_zone.
*/
nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
order, sc.gfp_mask,
&nr_soft_scanned);
sc.nr_reclaimed += nr_soft_reclaimed;
/*
* We put equal pressure on every zone, unless
* one zone has way too many pages free
* already. The "too many pages" is defined
* as the high wmark plus a "gap" where the
* gap is either the low watermark or 1%
* of the zone, whichever is smaller.
*/
balance_gap = min(low_wmark_pages(zone),
(zone->managed_pages +
KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
KSWAPD_ZONE_BALANCE_GAP_RATIO);
/*
* Kswapd reclaims only single pages with compaction
* enabled. Trying too hard to reclaim until contiguous
* free pages have become available can hurt performance
* by evicting too much useful data from memory.
* Do not reclaim more than needed for compaction.
*/
testorder = order;
if (IS_ENABLED(CONFIG_COMPACTION) && order &&
compaction_suitable(zone, order) !=
COMPACT_SKIPPED)
testorder = 0;
if ((buffer_heads_over_limit && is_highmem_idx(i)) ||
!zone_balanced(zone, testorder,
balance_gap, end_zone)) {
shrink_zone(zone, &sc);
reclaim_state->reclaimed_slab = 0;
nr_slab = shrink_slab(&shrink, sc.nr_scanned, lru_pages);
sc.nr_reclaimed += reclaim_state->reclaimed_slab;
if (nr_slab == 0 && !zone_reclaimable(zone))
zone->all_unreclaimable = 1;
}
/*
* If we're getting trouble reclaiming, start doing
* writepage even in laptop mode.
*/
if (sc.priority < DEF_PRIORITY - 2)
sc.may_writepage = 1;
if (zone->all_unreclaimable) {
if (end_zone && end_zone == i)
end_zone--;
continue;
}
if (zone_balanced(zone, testorder, 0, end_zone))
/*
* If a zone reaches its high watermark,
* consider it to be no longer congested. It's
* possible there are dirty pages backed by
* congested BDIs but as pressure is relieved,
* speculatively avoid congestion waits
*/
zone_clear_flag(zone, ZONE_CONGESTED);
}
/*
* If the low watermark is met there is no need for processes
* to be throttled on pfmemalloc_wait as they should not be
* able to safely make forward progress. Wake them
*/
if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
pfmemalloc_watermark_ok(pgdat))
wake_up(&pgdat->pfmemalloc_wait);
if (pgdat_balanced(pgdat, order, *classzone_idx)) {
pgdat_is_balanced = true;
break; /* kswapd: all done */
}
/*
* We do this so kswapd doesn't build up large priorities for
* example when it is freeing in parallel with allocators. It
* matches the direct reclaim path behaviour in terms of impact
* on zone->*_priority.
*/
if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
break;
} while (--sc.priority >= 0);
out:
if (!pgdat_is_balanced) {
cond_resched();
try_to_freeze();
/*
* Fragmentation may mean that the system cannot be
* rebalanced for high-order allocations in all zones.
* At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
* it means the zones have been fully scanned and are still
* not balanced. For high-order allocations, there is
* little point trying all over again as kswapd may
* infinite loop.
*
* Instead, recheck all watermarks at order-0 as they
* are the most important. If watermarks are ok, kswapd will go
* back to sleep. High-order users can still perform direct
* reclaim if they wish.
*/
if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
order = sc.order = 0;
goto loop_again;
}
/*
* If kswapd was reclaiming at a higher order, it has the option of
* sleeping without all zones being balanced. Before it does, it must
* ensure that the watermarks for order-0 on *all* zones are met and
* that the congestion flags are cleared. The congestion flag must
* be cleared as kswapd is the only mechanism that clears the flag
* and it is potentially going to sleep here.
*/
if (order) {
int zones_need_compaction = 1;
for (i = 0; i <= end_zone; i++) {
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
/* Check if the memory needs to be defragmented. */
if (zone_watermark_ok(zone, order,
low_wmark_pages(zone), *classzone_idx, 0))
zones_need_compaction = 0;
}
if (zones_need_compaction)
compact_pgdat(pgdat, order);
}
/*
* Return the order we were reclaiming at so prepare_kswapd_sleep()
* makes a decision on the order we were last reclaiming at. However,
* if another caller entered the allocator slow path while kswapd
* was awake, order will remain at the higher level
*/
*classzone_idx = end_zone;
return order;
}
static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
{
long remaining = 0;
DEFINE_WAIT(wait);
if (freezing(current) || kthread_should_stop())
return;
prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
/* Try to sleep for a short interval */
if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
remaining = schedule_timeout(HZ/10);
finish_wait(&pgdat->kswapd_wait, &wait);
prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
}
/*
* After a short sleep, check if it was a premature sleep. If not, then
* go fully to sleep until explicitly woken up.
*/
if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
/*
* vmstat counters are not perfectly accurate and the estimated
* value for counters such as NR_FREE_PAGES can deviate from the
* true value by nr_online_cpus * threshold. To avoid the zone
* watermarks being breached while under pressure, we reduce the
* per-cpu vmstat threshold while kswapd is awake and restore
* them before going back to sleep.
*/
set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
/*
* Compaction records what page blocks it recently failed to
* isolate pages from and skips them in the future scanning.
* When kswapd is going to sleep, it is reasonable to assume
* that pages and compaction may succeed so reset the cache.
*/
reset_isolation_suitable(pgdat);
if (!kthread_should_stop())
schedule();
set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
} else {
if (remaining)
count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
else
count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
}
finish_wait(&pgdat->kswapd_wait, &wait);
}
/*
* The background pageout daemon, started as a kernel thread
* from the init process.
*
* This basically trickles out pages so that we have _some_
* free memory available even if there is no other activity
* that frees anything up. This is needed for things like routing
* etc, where we otherwise might have all activity going on in
* asynchronous contexts that cannot page things out.
*
* If there are applications that are active memory-allocators
* (most normal use), this basically shouldn't matter.
*/
static int kswapd(void *p)
{
unsigned long order, new_order;
unsigned balanced_order;
int classzone_idx, new_classzone_idx;
int balanced_classzone_idx;
pg_data_t *pgdat = (pg_data_t*)p;
struct task_struct *tsk = current;
struct reclaim_state reclaim_state = {
.reclaimed_slab = 0,
};
const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
lockdep_set_current_reclaim_state(GFP_KERNEL);
if (!cpumask_empty(cpumask))
set_cpus_allowed_ptr(tsk, cpumask);
current->reclaim_state = &reclaim_state;
/*
* Tell the memory management that we're a "memory allocator",
* and that if we need more memory we should get access to it
* regardless (see "__alloc_pages()"). "kswapd" should
* never get caught in the normal page freeing logic.
*
* (Kswapd normally doesn't need memory anyway, but sometimes
* you need a small amount of memory in order to be able to
* page out something else, and this flag essentially protects
* us from recursively trying to free more memory as we're
* trying to free the first piece of memory in the first place).
*/
tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
set_freezable();
order = new_order = 0;
balanced_order = 0;
classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
balanced_classzone_idx = classzone_idx;
for ( ; ; ) {
bool ret;
/*
* If the last balance_pgdat was unsuccessful it's unlikely a
* new request of a similar or harder type will succeed soon
* so consider going to sleep on the basis we reclaimed at
*/
if (balanced_classzone_idx >= new_classzone_idx &&
balanced_order == new_order) {
new_order = pgdat->kswapd_max_order;
new_classzone_idx = pgdat->classzone_idx;
pgdat->kswapd_max_order = 0;
pgdat->classzone_idx = pgdat->nr_zones - 1;
}
if (order < new_order || classzone_idx > new_classzone_idx) {
/*
* Don't sleep if someone wants a larger 'order'
* allocation or has tigher zone constraints
*/
order = new_order;
classzone_idx = new_classzone_idx;
} else {
kswapd_try_to_sleep(pgdat, balanced_order,
balanced_classzone_idx);
order = pgdat->kswapd_max_order;
classzone_idx = pgdat->classzone_idx;
new_order = order;
new_classzone_idx = classzone_idx;
pgdat->kswapd_max_order = 0;
pgdat->classzone_idx = pgdat->nr_zones - 1;
}
ret = try_to_freeze();
if (kthread_should_stop())
break;
/*
* We can speed up thawing tasks if we don't call balance_pgdat
* after returning from the refrigerator
*/
if (!ret) {
trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
balanced_classzone_idx = classzone_idx;
balanced_order = balance_pgdat(pgdat, order,
&balanced_classzone_idx);
}
}
tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
current->reclaim_state = NULL;
lockdep_clear_current_reclaim_state();
return 0;
}
/*
* A zone is low on free memory, so wake its kswapd task to service it.
*/
void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
{
pg_data_t *pgdat;
if (!populated_zone(zone))
return;
if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
return;
pgdat = zone->zone_pgdat;
if (pgdat->kswapd_max_order < order) {
pgdat->kswapd_max_order = order;
pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
}
if (!waitqueue_active(&pgdat->kswapd_wait))
return;
if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
return;
trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
wake_up_interruptible(&pgdat->kswapd_wait);
}
#ifdef CONFIG_HIBERNATION
/*
* Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
* freed pages.
*
* Rather than trying to age LRUs the aim is to preserve the overall
* LRU order by reclaiming preferentially
* inactive > active > active referenced > active mapped
*/
unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
{
struct reclaim_state reclaim_state;
struct scan_control sc = {
.gfp_mask = GFP_HIGHUSER_MOVABLE,
.may_swap = 1,
.may_unmap = 1,
.may_writepage = 1,
.nr_to_reclaim = nr_to_reclaim,
.hibernation_mode = 1,
.order = 0,
.priority = DEF_PRIORITY,
};
struct shrink_control shrink = {
.gfp_mask = sc.gfp_mask,
};
struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
struct task_struct *p = current;
unsigned long nr_reclaimed;
p->flags |= PF_MEMALLOC;
lockdep_set_current_reclaim_state(sc.gfp_mask);
reclaim_state.reclaimed_slab = 0;
p->reclaim_state = &reclaim_state;
nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
p->reclaim_state = NULL;
lockdep_clear_current_reclaim_state();
p->flags &= ~PF_MEMALLOC;
return nr_reclaimed;
}
#endif /* CONFIG_HIBERNATION */
/* It's optimal to keep kswapds on the same CPUs as their memory, but
not required for correctness. So if the last cpu in a node goes
away, we get changed to run anywhere: as the first one comes back,
restore their cpu bindings. */
static int cpu_callback(struct notifier_block *nfb, unsigned long action,
void *hcpu)
{
int nid;
if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
for_each_node_state(nid, N_MEMORY) {
pg_data_t *pgdat = NODE_DATA(nid);
const struct cpumask *mask;
mask = cpumask_of_node(pgdat->node_id);
if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
/* One of our CPUs online: restore mask */
set_cpus_allowed_ptr(pgdat->kswapd, mask);
}
}
return NOTIFY_OK;
}
/*
* This kswapd start function will be called by init and node-hot-add.
* On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
*/
int kswapd_run(int nid)
{
pg_data_t *pgdat = NODE_DATA(nid);
int ret = 0;
if (pgdat->kswapd)
return 0;
pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
if (IS_ERR(pgdat->kswapd)) {
/* failure at boot is fatal */
BUG_ON(system_state == SYSTEM_BOOTING);
pr_err("Failed to start kswapd on node %d\n", nid);
ret = PTR_ERR(pgdat->kswapd);
pgdat->kswapd = NULL;
}
return ret;
}
/*
* Called by memory hotplug when all memory in a node is offlined. Caller must
* hold lock_memory_hotplug().
*/
void kswapd_stop(int nid)
{
struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
if (kswapd) {
kthread_stop(kswapd);
NODE_DATA(nid)->kswapd = NULL;
}
}
static int __init kswapd_init(void)
{
int nid;
swap_setup();
for_each_node_state(nid, N_MEMORY)
kswapd_run(nid);
hotcpu_notifier(cpu_callback, 0);
return 0;
}
module_init(kswapd_init)
#ifdef CONFIG_NUMA
/*
* Zone reclaim mode
*
* If non-zero call zone_reclaim when the number of free pages falls below
* the watermarks.
*/
int zone_reclaim_mode __read_mostly;
#define RECLAIM_OFF 0
#define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
#define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
#define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
/*
* Priority for ZONE_RECLAIM. This determines the fraction of pages
* of a node considered for each zone_reclaim. 4 scans 1/16th of
* a zone.
*/
#define ZONE_RECLAIM_PRIORITY 4
/*
* Percentage of pages in a zone that must be unmapped for zone_reclaim to
* occur.
*/
int sysctl_min_unmapped_ratio = 1;
/*
* If the number of slab pages in a zone grows beyond this percentage then
* slab reclaim needs to occur.
*/
int sysctl_min_slab_ratio = 5;
static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
{
unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
zone_page_state(zone, NR_ACTIVE_FILE);
/*
* It's possible for there to be more file mapped pages than
* accounted for by the pages on the file LRU lists because
* tmpfs pages accounted for as ANON can also be FILE_MAPPED
*/
return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
}
/* Work out how many page cache pages we can reclaim in this reclaim_mode */
static long zone_pagecache_reclaimable(struct zone *zone)
{
long nr_pagecache_reclaimable;
long delta = 0;
/*
* If RECLAIM_SWAP is set, then all file pages are considered
* potentially reclaimable. Otherwise, we have to worry about
* pages like swapcache and zone_unmapped_file_pages() provides
* a better estimate
*/
if (zone_reclaim_mode & RECLAIM_SWAP)
nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
else
nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
/* If we can't clean pages, remove dirty pages from consideration */
if (!(zone_reclaim_mode & RECLAIM_WRITE))
delta += zone_page_state(zone, NR_FILE_DIRTY);
/* Watch for any possible underflows due to delta */
if (unlikely(delta > nr_pagecache_reclaimable))
delta = nr_pagecache_reclaimable;
return nr_pagecache_reclaimable - delta;
}
/*
* Try to free up some pages from this zone through reclaim.
*/
static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
{
/* Minimum pages needed in order to stay on node */
const unsigned long nr_pages = 1 << order;
struct task_struct *p = current;
struct reclaim_state reclaim_state;
struct scan_control sc = {
.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
.may_swap = 1,
.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
.order = order,
.priority = ZONE_RECLAIM_PRIORITY,
};
struct shrink_control shrink = {
.gfp_mask = sc.gfp_mask,
};
unsigned long nr_slab_pages0, nr_slab_pages1;
cond_resched();
/*
* We need to be able to allocate from the reserves for RECLAIM_SWAP
* and we also need to be able to write out pages for RECLAIM_WRITE
* and RECLAIM_SWAP.
*/
p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
lockdep_set_current_reclaim_state(gfp_mask);
reclaim_state.reclaimed_slab = 0;
p->reclaim_state = &reclaim_state;
if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
/*
* Free memory by calling shrink zone with increasing
* priorities until we have enough memory freed.
*/
do {
shrink_zone(zone, &sc);
} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
}
nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
if (nr_slab_pages0 > zone->min_slab_pages) {
/*
* shrink_slab() does not currently allow us to determine how
* many pages were freed in this zone. So we take the current
* number of slab pages and shake the slab until it is reduced
* by the same nr_pages that we used for reclaiming unmapped
* pages.
*
* Note that shrink_slab will free memory on all zones and may
* take a long time.
*/
for (;;) {
unsigned long lru_pages = zone_reclaimable_pages(zone);
/* No reclaimable slab or very low memory pressure */
if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
break;
/* Freed enough memory */
nr_slab_pages1 = zone_page_state(zone,
NR_SLAB_RECLAIMABLE);
if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
break;
}
/*
* Update nr_reclaimed by the number of slab pages we
* reclaimed from this zone.
*/
nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
if (nr_slab_pages1 < nr_slab_pages0)
sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
}
p->reclaim_state = NULL;
current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
lockdep_clear_current_reclaim_state();
return sc.nr_reclaimed >= nr_pages;
}
int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
{
int node_id;
int ret;
/*
* Zone reclaim reclaims unmapped file backed pages and
* slab pages if we are over the defined limits.
*
* A small portion of unmapped file backed pages is needed for
* file I/O otherwise pages read by file I/O will be immediately
* thrown out if the zone is overallocated. So we do not reclaim
* if less than a specified percentage of the zone is used by
* unmapped file backed pages.
*/
if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
return ZONE_RECLAIM_FULL;
if (zone->all_unreclaimable)
return ZONE_RECLAIM_FULL;
/*
* Do not scan if the allocation should not be delayed.
*/
if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
return ZONE_RECLAIM_NOSCAN;
/*
* Only run zone reclaim on the local zone or on zones that do not
* have associated processors. This will favor the local processor
* over remote processors and spread off node memory allocations
* as wide as possible.
*/
node_id = zone_to_nid(zone);
if (node_state(node_id, N_CPU) && node_id != numa_node_id())
return ZONE_RECLAIM_NOSCAN;
if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
return ZONE_RECLAIM_NOSCAN;
ret = __zone_reclaim(zone, gfp_mask, order);
zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
if (!ret)
count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
return ret;
}
#endif
/*
* page_evictable - test whether a page is evictable
* @page: the page to test
*
* Test whether page is evictable--i.e., should be placed on active/inactive
* lists vs unevictable list.
*
* Reasons page might not be evictable:
* (1) page's mapping marked unevictable
* (2) page is part of an mlocked VMA
*
*/
int page_evictable(struct page *page)
{
return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
}
#ifdef CONFIG_SHMEM
/**
* check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
* @pages: array of pages to check
* @nr_pages: number of pages to check
*
* Checks pages for evictability and moves them to the appropriate lru list.
*
* This function is only used for SysV IPC SHM_UNLOCK.
*/
void check_move_unevictable_pages(struct page **pages, int nr_pages)
{
struct lruvec *lruvec;
struct zone *zone = NULL;
int pgscanned = 0;
int pgrescued = 0;
int i;
for (i = 0; i < nr_pages; i++) {
struct page *page = pages[i];
struct zone *pagezone;
pgscanned++;
pagezone = page_zone(page);
if (pagezone != zone) {
if (zone)
spin_unlock_irq(&zone->lru_lock);
zone = pagezone;
spin_lock_irq(&zone->lru_lock);
}
lruvec = mem_cgroup_page_lruvec(page, zone);
if (!PageLRU(page) || !PageUnevictable(page))
continue;
if (page_evictable(page)) {
enum lru_list lru = page_lru_base_type(page);
VM_BUG_ON(PageActive(page));
ClearPageUnevictable(page);
del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
add_page_to_lru_list(page, lruvec, lru);
pgrescued++;
}
}
if (zone) {
__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
spin_unlock_irq(&zone->lru_lock);
}
}
#endif /* CONFIG_SHMEM */
static void warn_scan_unevictable_pages(void)
{
printk_once(KERN_WARNING
"%s: The scan_unevictable_pages sysctl/node-interface has been "
"disabled for lack of a legitimate use case. If you have "
"one, please send an email to linux-mm@kvack.org.\n",
current->comm);
}
/*
* scan_unevictable_pages [vm] sysctl handler. On demand re-scan of
* all nodes' unevictable lists for evictable pages
*/
unsigned long scan_unevictable_pages;
int scan_unevictable_handler(struct ctl_table *table, int write,
void __user *buffer,
size_t *length, loff_t *ppos)
{
warn_scan_unevictable_pages();
proc_doulongvec_minmax(table, write, buffer, length, ppos);
scan_unevictable_pages = 0;
return 0;
}
#ifdef CONFIG_NUMA
/*
* per node 'scan_unevictable_pages' attribute. On demand re-scan of
* a specified node's per zone unevictable lists for evictable pages.
*/
static ssize_t read_scan_unevictable_node(struct device *dev,
struct device_attribute *attr,
char *buf)
{
warn_scan_unevictable_pages();
return sprintf(buf, "0\n"); /* always zero; should fit... */
}
static ssize_t write_scan_unevictable_node(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
warn_scan_unevictable_pages();
return 1;
}
static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
read_scan_unevictable_node,
write_scan_unevictable_node);
int scan_unevictable_register_node(struct node *node)
{
return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
}
void scan_unevictable_unregister_node(struct node *node)
{
device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
}
#endif
| artefvck/X_Artefvck | mm/vmscan.c | C | gpl-2.0 | 104,394 |
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _MAPTREE_H
#define _MAPTREE_H
#include "Platform/Define.h"
#include "Utilities/UnorderedMapSet.h"
#include "BIH.h"
namespace VMAP
{
class ModelInstance;
class GroupModel;
class VMapManager2;
struct LocationInfo
{
LocationInfo(): hitInstance(0), hitModel(0), ground_Z(-G3D::inf()) {};
const ModelInstance* hitInstance;
const GroupModel* hitModel;
float ground_Z;
};
class StaticMapTree
{
typedef UNORDERED_MAP<uint32, bool> loadedTileMap;
typedef UNORDERED_MAP<uint32, uint32> loadedSpawnMap;
private:
uint32 iMapID;
bool iIsTiled;
BIH iTree;
ModelInstance* iTreeValues; // the tree entries
uint32 iNTreeValues;
// Store all the map tile idents that are loaded for that map
// some maps are not splitted into tiles and we have to make sure, not removing the map before all tiles are removed
// empty tiles have no tile file, hence map with bool instead of just a set (consistency check)
loadedTileMap iLoadedTiles;
// stores <tree_index, reference_count> to invalidate tree values, unload map, and to be able to report errors
loadedSpawnMap iLoadedSpawns;
std::string iBasePath;
private:
bool getIntersectionTime(const G3D::Ray& pRay, float& pMaxDist, bool pStopAtFirstHit, bool isLosCheck) const;
// bool containsLoadedMapTile(unsigned int pTileIdent) const { return(iLoadedMapTiles.containsKey(pTileIdent)); }
public:
static std::string getTileFileName(uint32 mapID, uint32 tileX, uint32 tileY);
static uint32 packTileID(uint32 tileX, uint32 tileY) { return tileX << 16 | tileY; }
static void unpackTileID(uint32 ID, uint32& tileX, uint32& tileY) { tileX = ID >> 16; tileY = ID & 0xFF; }
static bool CanLoadMap(const std::string& basePath, uint32 mapID, uint32 tileX, uint32 tileY);
StaticMapTree(uint32 mapID, const std::string& basePath);
~StaticMapTree();
bool isInLineOfSight(const G3D::Vector3& pos1, const G3D::Vector3& pos2) const;
ModelInstance* FindCollisionModel(const G3D::Vector3& pos1, const G3D::Vector3& pos2);
bool getObjectHitPos(const G3D::Vector3& pos1, const G3D::Vector3& pos2, G3D::Vector3& pResultHitPos, float pModifyDist) const;
float getHeight(const G3D::Vector3& pPos, float maxSearchDist) const;
bool getAreaInfo(G3D::Vector3& pos, uint32& flags, int32& adtId, int32& rootId, int32& groupId) const;
bool isUnderModel(G3D::Vector3& pos, float* outDist = NULL, float* inDist = NULL) const;
bool GetLocationInfo(const Vector3& pos, LocationInfo& info) const;
bool InitMap(const std::string& fname, VMapManager2* vm);
void UnloadMap(VMapManager2* vm);
bool LoadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm);
void UnloadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm);
bool isTiled() const { return iIsTiled; }
uint32 numLoadedTiles() const { return iLoadedTiles.size(); }
#ifdef MMAP_GENERATOR
public:
void getModelInstances(ModelInstance*& models, uint32& count);
#endif
};
struct AreaInfo
{
AreaInfo(): result(false), ground_Z(-G3D::inf()) {};
bool result;
float ground_Z;
uint32 flags;
int32 adtId;
int32 rootId;
int32 groupId;
};
} // VMAP
#endif // _MAPTREE_H
| Dahkelor/theorycraft | src/game/vmap/MapTree.h | C | gpl-2.0 | 4,494 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* DNS Library for handling lookups and updates.
*
* PHP Version 5
*
* Copyright (c) 2010, Mike Pultz <mike@mikepultz.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Mike Pultz nor the names of his contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
* 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.
*
* @category Networking
* @package Net_DNS2
* @author Mike Pultz <mike@mikepultz.com>
* @copyright 2010 Mike Pultz <mike@mikepultz.com>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id: LOC.php 127 2011-12-03 03:29:39Z mike.pultz $
* @link http://pear.php.net/package/Net_DNS2
* @since File available since Release 0.6.0
*
*/
/**
* LOC Resource Record - RFC1876 section 2
*
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | VERSION | SIZE |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | HORIZ PRE | VERT PRE |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | LATITUDE |
* | |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | LONGITUDE |
* | |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
* | ALTITUDE |
* | |
* +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*
* @category Networking
* @package Net_DNS2
* @author Mike Pultz <mike@mikepultz.com>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link http://pear.php.net/package/Net_DNS2
* @see Net_DNS2_RR
*
*/
class Net_DNS2_RR_LOC extends Net_DNS2_RR
{
/*
* the LOC version- should only ever be 0
*/
public $version;
/*
* The diameter of a sphere enclosing the described entity
*/
public $size;
/*
* The horizontal precision of the data
*/
public $horiz_pre;
/*
* The vertical precision of the data
*/
public $vert_pre;
/*
* The latitude - stored in decimal degrees
*/
public $latitude;
/*
* The longitude - stored in decimal degrees
*/
public $longitude;
/*
* The altitude - stored in decimal
*/
public $altitude;
/*
* used for quick power-of-ten lookups
*/
private $_powerOfTen = array(1, 10, 100, 1000, 10000, 100000,
1000000,10000000,100000000,1000000000);
/*
* some conversion values
*/
const CONV_SEC = 1000;
const CONV_MIN = 60000;
const CONV_DEG = 3600000;
const REFERENCE_ALT = 10000000;
const REFERENCE_LATLON = 2147483648;
/**
* method to return the rdata portion of the packet as a string
*
* @return string
* @access protected
*
*/
protected function rrToString()
{
if ($this->version == 0) {
return $this->_d2Dms($this->latitude, 'LAT') . ' ' .
$this->_d2Dms($this->longitude, 'LNG') . ' ' .
sprintf('%.2fm', $this->altitude) . ' ' .
sprintf('%.2fm', $this->size) . ' ' .
sprintf('%.2fm', $this->horiz_pre) . ' ' .
sprintf('%.2fm', $this->vert_pre);
}
return '';
}
/**
* parses the rdata portion from a standard DNS config line
*
* @param array $rdata a string split line of values for the rdata
*
* @return boolean
* @access protected
*
*/
protected function rrFromString(array $rdata)
{
//
// format as defined by RFC1876 section 3
//
// d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"]
// [siz["m"] [hp["m"] [vp["m"]]]]
//
$res = preg_match(
'/^(\d+) \s+((\d+) \s+)?(([\d.]+) \s+)?(N|S) \s+(\d+) ' .
'\s+((\d+) \s+)?(([\d.]+) \s+)?(E|W) \s+(-?[\d.]+) m?(\s+ ' .
'([\d.]+) m?)?(\s+ ([\d.]+) m?)?(\s+ ([\d.]+) m?)?/ix',
implode(' ', $rdata), $x
);
if ($res) {
//
// latitude
//
$latdeg = $x[1];
$latmin = (isset($x[3])) ? $x[3] : 0;
$latsec = (isset($x[5])) ? $x[5] : 0;
$lathem = strtoupper($x[6]);
$this->latitude = $this->_dms2d($latdeg, $latmin, $latsec, $lathem);
//
// longitude
//
$londeg = $x[7];
$lonmin = (isset($x[9])) ? $x[9] : 0;
$lonsec = (isset($x[11])) ? $x[11] : 0;
$lonhem = strtoupper($x[12]);
$this->longitude = $this->_dms2d($londeg, $lonmin, $lonsec, $lonhem);
//
// the rest of teh values
//
$version = 0;
$this->size = (isset($x[15])) ? $x[15] : 1;
$this->horiz_pre = ((isset($x[17])) ? $x[17] : 10000);
$this->vert_pre = ((isset($x[19])) ? $x[19] : 10);
$this->altitude = $x[13];
return true;
}
return false;
}
/**
* parses the rdata of the Net_DNS2_Packet object
*
* @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet to parse the RR from
*
* @return boolean
* @access protected
*
*/
protected function rrSet(Net_DNS2_Packet &$packet)
{
if ($this->rdlength > 0) {
//
// unpack all the values
//
$x = unpack(
'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude',
$this->rdata
);
//
// version must be 0 per RFC 1876 section 2
//
$this->version = $x['ver'];
if ($this->version == 0) {
$this->size = $this->_precsizeNtoA($x['size']);
$this->horiz_pre = $this->_precsizeNtoA($x['horiz_pre']);
$this->vert_pre = $this->_precsizeNtoA($x['vert_pre']);
//
// convert the latitude and longitude to degress in decimal
//
if ($x['latitude'] < 0) {
$this->latitude = ($x['latitude'] +
self::REFERENCE_LATLON) / self::CONV_DEG;
} else {
$this->latitude = ($x['latitude'] -
self::REFERENCE_LATLON) / self::CONV_DEG;
}
if ($x['longitude'] < 0) {
$this->longitude = ($x['longitude'] +
self::REFERENCE_LATLON) / self::CONV_DEG;
} else {
$this->longitude = ($x['longitude'] -
self::REFERENCE_LATLON) / self::CONV_DEG;
}
//
// convert down the altitude
//
$this->altitude = ($x['altitude'] - self::REFERENCE_ALT) / 100;
return true;
} else {
return false;
}
return true;
}
return false;
}
/**
* returns the rdata portion of the DNS packet
*
* @param Net_DNS2_Packet &$packet a Net_DNS2_Packet packet use for
* compressed names
*
* @return mixed either returns a binary packed
* string or null on failure
* @access protected
*
*/
protected function rrGet(Net_DNS2_Packet &$packet)
{
if ($this->version == 0) {
$lat = 0;
$lng = 0;
if ($this->latitude < 0) {
$lat = ($this->latitude * self::CONV_DEG) - self::REFERENCE_LATLON;
} else {
$lat = ($this->latitude * self::CONV_DEG) + self::REFERENCE_LATLON;
}
if ($this->longitude < 0) {
$lng = ($this->longitude * self::CONV_DEG) - self::REFERENCE_LATLON;
} else {
$lng = ($this->longitude * self::CONV_DEG) + self::REFERENCE_LATLON;
}
return pack(
'CCCCNNN',
$this->version,
$this->_precsizeAtoN($this->size),
$this->_precsizeAtoN($this->horiz_pre),
$this->_precsizeAtoN($this->vert_pre),
$lat, $lng,
($this->altitude * 100) + self::REFERENCE_ALT
);
}
return null;
}
/**
* takes an XeY precision/size value, returns a string representation.
* shamlessly stolen from RFC1876 Appendix A
*
* @param integer $prec the value to convert
*
* @return string
* @access private
*
*/
private function _precsizeNtoA($prec)
{
$mantissa = (($prec >> 4) & 0x0f) % 10;
$exponent = (($prec >> 0) & 0x0f) % 10;
return $mantissa * $this->_powerOfTen[$exponent];
}
/**
* converts ascii size/precision X * 10**Y(cm) to 0xXY.
* shamlessly stolen from RFC1876 Appendix A
*
* @param string $prec the value to convert
*
* @return integer
* @access private
*
*/
private function _precsizeAtoN($prec)
{
$exponent = 0;
while ($prec >= 10) {
$prec /= 10;
++$exponent;
}
return ($prec << 4) | ($exponent & 0x0f);
}
/**
* convert lat/lng in deg/min/sec/hem to decimal value
*
* @param integer $deg the degree value
* @param integer $min the minutes value
* @param integer $sec the seconds value
* @param string $hem the hemisphere (N/E/S/W)
*
* @return float the decinmal value
* @access private
*
*/
private function _dms2d($deg, $min, $sec, $hem)
{
$deg = $deg - 0;
$min = $min - 0;
$sign = ($hem == 'W' || $hem == 'S') ? -1 : 1;
return ((($sec/60+$min)/60)+$deg) * $sign;
}
/**
* convert lat/lng in decimal to deg/min/sec/hem
*
* @param float $data the decimal value
* @param string $latlng either LAT or LNG so we can determine the HEM value
*
* @return string
* @access private
*
*/
private function _d2Dms($data, $latlng)
{
$deg = 0;
$min = 0;
$sec = 0;
$msec = 0;
$hem = '';
if ($latlng == 'LAT') {
$hem = ($data > 0) ? 'N' : 'S';
} else {
$hem = ($data > 0) ? 'E' : 'W';
}
$data = abs($data);
$deg = (int)$data;
$min = (int)(($data - $deg) * 60);
$sec = (int)(((($data - $deg) * 60) - $min) * 60);
$msec = round((((((($data - $deg) * 60) - $min) * 60) - $sec) * 1000));
return sprintf('%d %02d %02d.%03d %s', $deg, $min, $sec, round($msec), $hem);
}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>
| prdatur/soopfw | plugins/Net_DNS2-1.2.1/DNS2/RR/LOC.php | PHP | gpl-2.0 | 12,763 |
;; @file
; IPRT - ASMBitFirstClear().
;
;
; Copyright (C) 2006-2010 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
;*******************************************************************************
;* Header Files *
;*******************************************************************************
%include "iprt/asmdefs.mac"
BEGINCODE
;;
; Finds the first clear bit in a bitmap.
;
; @returns eax Index of the first zero bit.
; @returns eax -1 if no clear bit was found.
; @param rcx pvBitmap Pointer to the bitmap.
; @param edx cBits The number of bits in the bitmap. Multiple of 32.
;
BEGINPROC_EXPORTED ASMBitFirstClear
;if (cBits)
or edx, edx
jz short .failed
;{
push rdi
; asm {...}
mov rdi, rcx ; rdi = start of scasd
mov ecx, edx
add ecx, 31 ; 32 bit aligned
shr ecx, 5 ; number of dwords to scan.
mov rdx, rdi ; rdx = saved pvBitmap
mov eax, 0ffffffffh
repe scasd ; Scan for the first dword with any clear bit.
je .failed_restore
; find the bit in question
lea rdi, [rdi - 4] ; one step back.
xor eax, [rdi] ; eax = NOT [rdi]
sub rdi, rdx
shl edi, 3 ; calc bit offset.
mov ecx, 0ffffffffh
bsf ecx, eax
add ecx, edi
mov eax, ecx
; return success
pop rdi
ret
; failure
;}
;return -1;
.failed_restore:
pop rdi
ret
.failed:
mov eax, 0ffffffffh
ret
ENDPROC ASMBitFirstClear
| eaas-framework/virtualbox | src/VBox/Runtime/win/amd64/ASMBitFirstClear.asm | Assembly | gpl-2.0 | 2,742 |
/*
* Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/vmalloc.h>
#include <linux/hardirq.h>
#include <linux/mlx5/driver.h>
#include <linux/mlx5/cmd.h>
#include "mlx5_core.h"
enum {
MLX5_HEALTH_POLL_INTERVAL = 2 * HZ,
MAX_MISSES = 3,
};
enum {
MLX5_HEALTH_SYNDR_FW_ERR = 0x1,
MLX5_HEALTH_SYNDR_IRISC_ERR = 0x7,
MLX5_HEALTH_SYNDR_HW_UNRECOVERABLE_ERR = 0x8,
MLX5_HEALTH_SYNDR_CRC_ERR = 0x9,
MLX5_HEALTH_SYNDR_FETCH_PCI_ERR = 0xa,
MLX5_HEALTH_SYNDR_HW_FTL_ERR = 0xb,
MLX5_HEALTH_SYNDR_ASYNC_EQ_OVERRUN_ERR = 0xc,
MLX5_HEALTH_SYNDR_EQ_ERR = 0xd,
MLX5_HEALTH_SYNDR_EQ_INV = 0xe,
MLX5_HEALTH_SYNDR_FFSER_ERR = 0xf,
MLX5_HEALTH_SYNDR_HIGH_TEMP = 0x10
};
enum {
MLX5_NIC_IFC_FULL = 0,
MLX5_NIC_IFC_DISABLED = 1,
MLX5_NIC_IFC_NO_DRAM_NIC = 2,
MLX5_NIC_IFC_INVALID = 3
};
enum {
MLX5_DROP_NEW_HEALTH_WORK,
MLX5_DROP_NEW_RECOVERY_WORK,
};
static u8 get_nic_state(struct mlx5_core_dev *dev)
{
return (ioread32be(&dev->iseg->cmdq_addr_l_sz) >> 8) & 3;
}
static void trigger_cmd_completions(struct mlx5_core_dev *dev)
{
unsigned long flags;
u64 vector;
/* wait for pending handlers to complete */
synchronize_irq(pci_irq_vector(dev->pdev, MLX5_EQ_VEC_CMD));
spin_lock_irqsave(&dev->cmd.alloc_lock, flags);
vector = ~dev->cmd.bitmask & ((1ul << (1 << dev->cmd.log_sz)) - 1);
if (!vector)
goto no_trig;
vector |= MLX5_TRIGGERED_CMD_COMP;
spin_unlock_irqrestore(&dev->cmd.alloc_lock, flags);
mlx5_core_dbg(dev, "vector 0x%llx\n", vector);
mlx5_cmd_comp_handler(dev, vector, true);
return;
no_trig:
spin_unlock_irqrestore(&dev->cmd.alloc_lock, flags);
}
static int in_fatal(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
struct health_buffer __iomem *h = health->health;
if (get_nic_state(dev) == MLX5_NIC_IFC_DISABLED)
return 1;
if (ioread32be(&h->fw_ver) == 0xffffffff)
return 1;
return 0;
}
void mlx5_enter_error_state(struct mlx5_core_dev *dev, bool force)
{
mutex_lock(&dev->intf_state_mutex);
if (dev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR)
goto unlock;
mlx5_core_err(dev, "start\n");
if (pci_channel_offline(dev->pdev) || in_fatal(dev) || force) {
dev->state = MLX5_DEVICE_STATE_INTERNAL_ERROR;
trigger_cmd_completions(dev);
}
mlx5_core_event(dev, MLX5_DEV_EVENT_SYS_ERROR, 0);
mlx5_core_err(dev, "end\n");
unlock:
mutex_unlock(&dev->intf_state_mutex);
}
static void mlx5_handle_bad_state(struct mlx5_core_dev *dev)
{
u8 nic_interface = get_nic_state(dev);
switch (nic_interface) {
case MLX5_NIC_IFC_FULL:
mlx5_core_warn(dev, "Expected to see disabled NIC but it is full driver\n");
break;
case MLX5_NIC_IFC_DISABLED:
mlx5_core_warn(dev, "starting teardown\n");
break;
case MLX5_NIC_IFC_NO_DRAM_NIC:
mlx5_core_warn(dev, "Expected to see disabled NIC but it is no dram nic\n");
break;
default:
mlx5_core_warn(dev, "Expected to see disabled NIC but it is has invalid value %d\n",
nic_interface);
}
mlx5_disable_device(dev);
}
static void health_recover(struct work_struct *work)
{
struct mlx5_core_health *health;
struct delayed_work *dwork;
struct mlx5_core_dev *dev;
struct mlx5_priv *priv;
u8 nic_state;
dwork = container_of(work, struct delayed_work, work);
health = container_of(dwork, struct mlx5_core_health, recover_work);
priv = container_of(health, struct mlx5_priv, health);
dev = container_of(priv, struct mlx5_core_dev, priv);
nic_state = get_nic_state(dev);
if (nic_state == MLX5_NIC_IFC_INVALID) {
dev_err(&dev->pdev->dev, "health recovery flow aborted since the nic state is invalid\n");
return;
}
dev_err(&dev->pdev->dev, "starting health recovery flow\n");
mlx5_recover_device(dev);
}
/* How much time to wait until health resetting the driver (in msecs) */
#define MLX5_RECOVERY_DELAY_MSECS 60000
static void health_care(struct work_struct *work)
{
unsigned long recover_delay = msecs_to_jiffies(MLX5_RECOVERY_DELAY_MSECS);
struct mlx5_core_health *health;
struct mlx5_core_dev *dev;
struct mlx5_priv *priv;
unsigned long flags;
health = container_of(work, struct mlx5_core_health, work);
priv = container_of(health, struct mlx5_priv, health);
dev = container_of(priv, struct mlx5_core_dev, priv);
mlx5_core_warn(dev, "handling bad device here\n");
mlx5_handle_bad_state(dev);
spin_lock_irqsave(&health->wq_lock, flags);
if (!test_bit(MLX5_DROP_NEW_RECOVERY_WORK, &health->flags))
schedule_delayed_work(&health->recover_work, recover_delay);
else
dev_err(&dev->pdev->dev,
"new health works are not permitted at this stage\n");
spin_unlock_irqrestore(&health->wq_lock, flags);
}
static const char *hsynd_str(u8 synd)
{
switch (synd) {
case MLX5_HEALTH_SYNDR_FW_ERR:
return "firmware internal error";
case MLX5_HEALTH_SYNDR_IRISC_ERR:
return "irisc not responding";
case MLX5_HEALTH_SYNDR_HW_UNRECOVERABLE_ERR:
return "unrecoverable hardware error";
case MLX5_HEALTH_SYNDR_CRC_ERR:
return "firmware CRC error";
case MLX5_HEALTH_SYNDR_FETCH_PCI_ERR:
return "ICM fetch PCI error";
case MLX5_HEALTH_SYNDR_HW_FTL_ERR:
return "HW fatal error\n";
case MLX5_HEALTH_SYNDR_ASYNC_EQ_OVERRUN_ERR:
return "async EQ buffer overrun";
case MLX5_HEALTH_SYNDR_EQ_ERR:
return "EQ error";
case MLX5_HEALTH_SYNDR_EQ_INV:
return "Invalid EQ referenced";
case MLX5_HEALTH_SYNDR_FFSER_ERR:
return "FFSER error";
case MLX5_HEALTH_SYNDR_HIGH_TEMP:
return "High temperature";
default:
return "unrecognized error";
}
}
static void print_health_info(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
struct health_buffer __iomem *h = health->health;
char fw_str[18];
u32 fw;
int i;
/* If the syndrom is 0, the device is OK and no need to print buffer */
if (!ioread8(&h->synd))
return;
for (i = 0; i < ARRAY_SIZE(h->assert_var); i++)
dev_err(&dev->pdev->dev, "assert_var[%d] 0x%08x\n", i, ioread32be(h->assert_var + i));
dev_err(&dev->pdev->dev, "assert_exit_ptr 0x%08x\n", ioread32be(&h->assert_exit_ptr));
dev_err(&dev->pdev->dev, "assert_callra 0x%08x\n", ioread32be(&h->assert_callra));
sprintf(fw_str, "%d.%d.%d", fw_rev_maj(dev), fw_rev_min(dev), fw_rev_sub(dev));
dev_err(&dev->pdev->dev, "fw_ver %s\n", fw_str);
dev_err(&dev->pdev->dev, "hw_id 0x%08x\n", ioread32be(&h->hw_id));
dev_err(&dev->pdev->dev, "irisc_index %d\n", ioread8(&h->irisc_index));
dev_err(&dev->pdev->dev, "synd 0x%x: %s\n", ioread8(&h->synd), hsynd_str(ioread8(&h->synd)));
dev_err(&dev->pdev->dev, "ext_synd 0x%04x\n", ioread16be(&h->ext_synd));
fw = ioread32be(&h->fw_ver);
dev_err(&dev->pdev->dev, "raw fw_ver 0x%08x\n", fw);
}
static unsigned long get_next_poll_jiffies(void)
{
unsigned long next;
get_random_bytes(&next, sizeof(next));
next %= HZ;
next += jiffies + MLX5_HEALTH_POLL_INTERVAL;
return next;
}
void mlx5_trigger_health_work(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
unsigned long flags;
spin_lock_irqsave(&health->wq_lock, flags);
if (!test_bit(MLX5_DROP_NEW_HEALTH_WORK, &health->flags))
queue_work(health->wq, &health->work);
else
dev_err(&dev->pdev->dev,
"new health works are not permitted at this stage\n");
spin_unlock_irqrestore(&health->wq_lock, flags);
}
static void poll_health(struct timer_list *t)
{
struct mlx5_core_dev *dev = from_timer(dev, t, priv.health.timer);
struct mlx5_core_health *health = &dev->priv.health;
u32 count;
if (dev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR)
goto out;
count = ioread32be(health->health_counter);
if (count == health->prev)
++health->miss_counter;
else
health->miss_counter = 0;
health->prev = count;
if (health->miss_counter == MAX_MISSES) {
dev_err(&dev->pdev->dev, "device's health compromised - reached miss count\n");
print_health_info(dev);
}
if (in_fatal(dev) && !health->sick) {
health->sick = true;
print_health_info(dev);
mlx5_trigger_health_work(dev);
}
out:
mod_timer(&health->timer, get_next_poll_jiffies());
}
void mlx5_start_health_poll(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
timer_setup(&health->timer, poll_health, 0);
health->sick = 0;
clear_bit(MLX5_DROP_NEW_HEALTH_WORK, &health->flags);
clear_bit(MLX5_DROP_NEW_RECOVERY_WORK, &health->flags);
health->health = &dev->iseg->health;
health->health_counter = &dev->iseg->health_counter;
health->timer.expires = round_jiffies(jiffies + MLX5_HEALTH_POLL_INTERVAL);
add_timer(&health->timer);
}
void mlx5_stop_health_poll(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
del_timer_sync(&health->timer);
}
void mlx5_drain_health_wq(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
unsigned long flags;
spin_lock_irqsave(&health->wq_lock, flags);
set_bit(MLX5_DROP_NEW_HEALTH_WORK, &health->flags);
set_bit(MLX5_DROP_NEW_RECOVERY_WORK, &health->flags);
spin_unlock_irqrestore(&health->wq_lock, flags);
cancel_delayed_work_sync(&health->recover_work);
cancel_work_sync(&health->work);
}
void mlx5_drain_health_recovery(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
unsigned long flags;
spin_lock_irqsave(&health->wq_lock, flags);
set_bit(MLX5_DROP_NEW_RECOVERY_WORK, &health->flags);
spin_unlock_irqrestore(&health->wq_lock, flags);
cancel_delayed_work_sync(&dev->priv.health.recover_work);
}
void mlx5_health_cleanup(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health = &dev->priv.health;
destroy_workqueue(health->wq);
}
int mlx5_health_init(struct mlx5_core_dev *dev)
{
struct mlx5_core_health *health;
char *name;
health = &dev->priv.health;
name = kmalloc(64, GFP_KERNEL);
if (!name)
return -ENOMEM;
strcpy(name, "mlx5_health");
strcat(name, dev_name(&dev->pdev->dev));
health->wq = create_singlethread_workqueue(name);
kfree(name);
if (!health->wq)
return -ENOMEM;
spin_lock_init(&health->wq_lock);
INIT_WORK(&health->work, health_care);
INIT_DELAYED_WORK(&health->recover_work, health_recover);
return 0;
}
| michael2012z/myKernel | drivers/net/ethernet/mellanox/mlx5/core/health.c | C | gpl-2.0 | 11,503 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Methods for working with cecog
Copyright 2010 University of Dundee, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import os
import re
import sys
from omero.cli import BaseControl, CLI
import omero
import omero.constants
from omero.rtypes import rstring
class CecogControl(BaseControl):
"""CeCog integration plugin.
Provides actions for prepairing data and otherwise integrating with Cecog. See
the Run_Cecog_4.1.py script.
"""
# [MetaMorph_PlateScanPackage]
# regex_subdirectories = re.compile('(?=[^_]).*?(?P<D>\d+).*?')
# regex_position = re.compile('P(?P<P>.+?)_')
# continuous_frames = 1
regex_token = re.compile(r'(?P<Token>.+)\.')
regex_time = re.compile(r'T(?P<T>\d+)')
regex_channel = re.compile(r'_C(?P<C>.+?)(_|$)')
regex_zslice = re.compile(r'_Z(?P<Z>\d+)')
def _configure(self, parser):
sub = parser.sub()
merge = parser.add(sub, self.merge, self.merge.__doc__)
merge.add_argument("path", help="Path to image files")
rois = parser.add(sub, self.rois, self.rois.__doc__)
rois.add_argument(
"-f", "--file", required=True, help="Details file to be parsed")
rois.add_argument(
"-i", "--image", required=True,
help="Image id which should have ids attached")
for x in (merge, rois):
x.add_login_arguments()
#
# Public methods
#
def merge(self, args):
"""Uses PIL to read multiple planes from a local folder.
Planes are combined and uploaded to OMERO as new images with additional T, C,
Z dimensions.
It should be run as a local script (not via scripting service) in order that
it has access to the local users file system. Therefore need EMAN2 or PIL
installed locally.
Example usage:
$ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/0037/
Since this dir does not contain folders, this will upload images in '0037'
into a Dataset called Demo_data in a Project called 'Data'.
$ bin/omero cecog merge /Applications/CecogPackage/Data/Demo_data/
Since this dir does contain folders, this will look for images in all
subdirectories of 'Demo_data' and upload images into a Dataset called
Demo_data in a Project called 'Data'.
Images will be combined in Z, C and T according to the \
MetaMorph_PlateScanPackage naming convention.
E.g. tubulin_P0037_T00005_Cgfp_Z1_S1.tiff is Point 37, Timepoint 5, Channel \
gfp, Z 1. S?
see \
/Applications/CecogPackage/CecogAnalyzer.app/Contents/Resources/resources/\
naming_schemes.conf
"""
"""
Processes the command args, makes project and dataset then calls
uploadDirAsImages() to process and
upload the images to OMERO.
"""
from omero.rtypes import unwrap
from omero.util.script_utils import uploadDirAsImages
path = args.path
client = self.ctx.conn(args)
queryService = client.sf.getQueryService()
updateService = client.sf.getUpdateService()
pixelsService = client.sf.getPixelsService()
# if we don't have any folders in the 'dir' E.g.
# CecogPackage/Data/Demo_data/0037/
# then 'Demo_data' becomes a dataset
subDirs = []
for f in os.listdir(path):
fullpath = path + f
# process folders in root dir:
if os.path.isdir(fullpath):
subDirs.append(fullpath)
# get the dataset name and project name from path
if len(subDirs) == 0:
p = path[:-1] # will remove the last folder
p = os.path.dirname(p)
else:
if os.path.basename(path) == "":
p = path[:-1] # remove slash
datasetName = os.path.basename(p) # e.g. Demo_data
p = p[:-1]
p = os.path.dirname(p)
projectName = os.path.basename(p) # e.g. Data
self.ctx.err("Putting images in Project: %s Dataset: %s"
% (projectName, datasetName))
# create dataset
dataset = omero.model.DatasetI()
dataset.name = rstring(datasetName)
dataset = updateService.saveAndReturnObject(dataset)
# create project
project = omero.model.ProjectI()
project.name = rstring(projectName)
project = updateService.saveAndReturnObject(project)
# put dataset in project
link = omero.model.ProjectDatasetLinkI()
link.parent = omero.model.ProjectI(project.id.val, False)
link.child = omero.model.DatasetI(dataset.id.val, False)
updateService.saveAndReturnObject(link)
if len(subDirs) > 0:
for subDir in subDirs:
self.ctx.err("Processing images in %s" % subDir)
rv = uploadDirAsImages(client.sf, queryService, updateService,
pixelsService, subDir, dataset)
self.ctx.out("%s" % unwrap(rv))
# if there are no sub-directories, just put all the images in the dir
else:
self.ctx.err("Processing images in %s" % path)
rv = uploadDirAsImages(client.sf, queryService, updateService,
pixelsService, path, dataset)
self.ctx.out("%s" % unwrap(rv))
def rois(self, args):
"""Parses an object_details text file, as generated by CeCog Analyzer
and saves the data as ROIs on an Image in OMERO.
Text file is of the form:
frame objID classLabel className centerX centerY mean sd
1 10 6 lateana 1119 41 76.8253796095 \
54.9305640673
Example usage:
bin/omero cecog rois -f \
Data/Demo_output/analyzed/0037/statistics/P0037__object_details.txt -i 502
"""
"""
Processes the command args, parses the object_details.txt file and
creates ROIs on the image specified in OMERO
"""
from omero.util.script_utils import uploadCecogObjectDetails
filePath = args.file
imageId = args.image
if not os.path.exists(filePath):
self.ctx.die(654, "Could find the object_details file at %s"
% filePath)
client = self.ctx.conn(args)
updateService = client.sf.getUpdateService()
ids = uploadCecogObjectDetails(updateService, imageId, filePath)
self.ctx.out("Rois created: %s" % len(ids))
try:
register("cecog", CecogControl, CecogControl.__doc__)
except NameError:
if __name__ == "__main__":
cli = CLI()
cli.register("cecog", CecogControl, CecogControl.__doc__)
cli.invoke(sys.argv[1:])
| dominikl/openmicroscopy | components/tools/OmeroPy/src/omero/plugins/cecog.py | Python | gpl-2.0 | 6,684 |
/* { dg-do compile } */
/* { dg-require-effective-target arm_dsp } */
/* Ensure the smlatb doesn't get generated when reading the Q flag
from ACLE. */
#include <arm_acle.h>
int
foo (int x, int in, int32_t c)
{
short a = in & 0xffff;
short b = (in & 0xffff0000) >> 16;
int res = x + b * a + __ssat (c, 24);
return res + __saturation_occurred ();
}
/* { dg-final { scan-assembler-not "smlatb\\t" } } */
| Gurgel100/gcc | gcc/testsuite/gcc.target/arm/acle/sat_no_smlatb.c | C | gpl-2.0 | 421 |
<?php
/**
* @package JCE
* @copyright Copyright © 2009-2011 Ryan Demmer. All rights reserved.
* @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
defined('_JEXEC') or die('RESTRICTED');
?>
<dl class="adminformlist">
<dt><?php echo WFText::_('WF_INSTALLER_INSTALL_DESC');?></dt>
<dd>
<label for="install" class="tooltip" title="<?php echo WFText::_('WF_INSTALLER_PACKAGE'); ?>::<?php echo WFText::_('WF_INSTALLER_PACKAGE_DESC'); ?>"><?php echo WFText::_('WF_INSTALLER_PACKAGE'); ?></label>
<span>
<input type="file" name="install" id="upload" placeholder="<?php echo $this->state->get('install.directory'); ?>" />
<button id="install_button"><?php echo WFText::_('WF_INSTALLER_UPLOAD'); ?></button>
</span>
</dd>
</dl> | ArtificialEX/jwexport | administrator/components/com_jce/views/installer/tmpl/install_install.php | PHP | gpl-2.0 | 1,071 |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import re
from waflib import Utils,Task,TaskGen,Logs
from waflib.TaskGen import feature,before_method,after_method,extension
from waflib.Configure import conf
INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])"""
USE_REGEX="""(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)"""
MOD_REGEX="""(?:^|;)\s*MODULE(?!\s*PROCEDURE)(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)"""
re_inc=re.compile(INC_REGEX,re.I)
re_use=re.compile(USE_REGEX,re.I)
re_mod=re.compile(MOD_REGEX,re.I)
class fortran_parser(object):
def __init__(self,incpaths):
self.seen=[]
self.nodes=[]
self.names=[]
self.incpaths=incpaths
def find_deps(self,node):
txt=node.read()
incs=[]
uses=[]
mods=[]
for line in txt.splitlines():
m=re_inc.search(line)
if m:
incs.append(m.group(1))
m=re_use.search(line)
if m:
uses.append(m.group(1))
m=re_mod.search(line)
if m:
mods.append(m.group(1))
return(incs,uses,mods)
def start(self,node):
self.waiting=[node]
while self.waiting:
nd=self.waiting.pop(0)
self.iter(nd)
def iter(self,node):
path=node.abspath()
incs,uses,mods=self.find_deps(node)
for x in incs:
if x in self.seen:
continue
self.seen.append(x)
self.tryfind_header(x)
for x in uses:
name="USE@%s"%x
if not name in self.names:
self.names.append(name)
for x in mods:
name="MOD@%s"%x
if not name in self.names:
self.names.append(name)
def tryfind_header(self,filename):
found=None
for n in self.incpaths:
found=n.find_resource(filename)
if found:
self.nodes.append(found)
self.waiting.append(found)
break
if not found:
if not filename in self.names:
self.names.append(filename)
| asljivo1/802.11ah-ns3 | ns-3/.waf-1.8.12-f00e5b53f6bbeab1384a38c9cc5d51f7/waflib/Tools/fc_scan.py | Python | gpl-2.0 | 1,859 |
/*
* File : touch.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2010 - 2012, RT-Thread Develop Team
*
* The license and distribution terms for this file may be
* found in the file LICENSE in this distribution or at
* http://www.rt-thread.org/license/LICENSE
*
* Change Logs:
* Date Author Notes
* 2010-01-01 Yi.Qiu first version
*/
#include <rthw.h>
#include <rtthread.h>
#include <s3c24x0.h>
#ifdef RT_USING_RTGUI
#include <rtgui/rtgui_system.h>
#include <rtgui/rtgui_server.h>
#include <rtgui/event.h>
#endif
#include "lcd.h"
#include "touch.h"
/* ADCCON Register Bits */
#define S3C2410_ADCCON_ECFLG (1<<15)
#define S3C2410_ADCCON_PRSCEN (1<<14)
#define S3C2410_ADCCON_PRSCVL(x) (((x)&0xFF)<<6)
#define S3C2410_ADCCON_PRSCVLMASK (0xFF<<6)
#define S3C2410_ADCCON_SELMUX(x) (((x)&0x7)<<3)
#define S3C2410_ADCCON_MUXMASK (0x7<<3)
#define S3C2410_ADCCON_STDBM (1<<2)
#define S3C2410_ADCCON_READ_START (1<<1)
#define S3C2410_ADCCON_ENABLE_START (1<<0)
#define S3C2410_ADCCON_STARTMASK (0x3<<0)
/* ADCTSC Register Bits */
#define S3C2410_ADCTSC_UD_SEN (1<<8) /* ghcstop add for s3c2440a */
#define S3C2410_ADCTSC_YM_SEN (1<<7)
#define S3C2410_ADCTSC_YP_SEN (1<<6)
#define S3C2410_ADCTSC_XM_SEN (1<<5)
#define S3C2410_ADCTSC_XP_SEN (1<<4)
#define S3C2410_ADCTSC_PULL_UP_DISABLE (1<<3)
#define S3C2410_ADCTSC_AUTO_PST (1<<2)
#define S3C2410_ADCTSC_XY_PST(x) (((x)&0x3)<<0)
/* ADCDAT0 Bits */
#define S3C2410_ADCDAT0_UPDOWN (1<<15)
#define S3C2410_ADCDAT0_AUTO_PST (1<<14)
#define S3C2410_ADCDAT0_XY_PST (0x3<<12)
#define S3C2410_ADCDAT0_XPDATA_MASK (0x03FF)
/* ADCDAT1 Bits */
#define S3C2410_ADCDAT1_UPDOWN (1<<15)
#define S3C2410_ADCDAT1_AUTO_PST (1<<14)
#define S3C2410_ADCDAT1_XY_PST (0x3<<12)
#define S3C2410_ADCDAT1_YPDATA_MASK (0x03FF)
#define WAIT4INT(x) (((x)<<8) | \
S3C2410_ADCTSC_YM_SEN | S3C2410_ADCTSC_YP_SEN | S3C2410_ADCTSC_XP_SEN | \
S3C2410_ADCTSC_XY_PST(3))
#define AUTOPST (S3C2410_ADCTSC_YM_SEN | S3C2410_ADCTSC_YP_SEN | S3C2410_ADCTSC_XP_SEN | \
S3C2410_ADCTSC_AUTO_PST | S3C2410_ADCTSC_XY_PST(0))
#define X_MIN 74
#define X_MAX 934
#define Y_MIN 920
#define Y_MAX 89
struct s3c2410ts
{
long xp;
long yp;
int count;
int shift;
int delay;
int presc;
char phys[32];
};
static struct s3c2410ts ts;
struct rtgui_touch_device
{
struct rt_device parent;
rt_timer_t poll_timer;
rt_uint16_t x, y;
rt_bool_t calibrating;
rt_touch_calibration_func_t calibration_func;
rt_touch_eventpost_func_t eventpost_func;
void *eventpost_param;
rt_uint16_t min_x, max_x;
rt_uint16_t min_y, max_y;
rt_uint16_t width;
rt_uint16_t height;
rt_bool_t first_down_report;
};
static struct rtgui_touch_device *touch = RT_NULL;
#ifdef RT_USING_RTGUI
static void report_touch_input(int updown)
{
struct rtgui_event_mouse emouse;
RTGUI_EVENT_MOUSE_BUTTON_INIT(&emouse);
emouse.wid = RT_NULL;
/* set emouse button */
emouse.button = RTGUI_MOUSE_BUTTON_LEFT;
emouse.parent.sender = RT_NULL;
if (updown)
{
ts.xp = ts.xp / ts.count;
ts.yp = ts.yp / ts.count;;
if ((touch->calibrating == RT_TRUE) && (touch->calibration_func != RT_NULL))
{
touch->x = ts.xp;
touch->y = ts.yp;
}
else
{
if (touch->max_x > touch->min_x)
{
touch->x = touch->width * (ts.xp-touch->min_x)/(touch->max_x-touch->min_x);
}
else
{
touch->x = touch->width * ( touch->min_x - ts.xp ) / (touch->min_x-touch->max_x);
}
if (touch->max_y > touch->min_y)
{
touch->y = touch->height * ( ts.yp - touch->min_y ) / (touch->max_y-touch->min_y);
}
else
{
touch->y = touch->height * ( touch->min_y - ts.yp ) / (touch->min_y-touch->max_y);
}
}
emouse.x = touch->x;
emouse.y = touch->y;
if (touch->first_down_report == RT_TRUE)
{
emouse.parent.type = RTGUI_EVENT_MOUSE_BUTTON;
emouse.button |= RTGUI_MOUSE_BUTTON_DOWN;
}
else
{
emouse.parent.type = RTGUI_EVENT_MOUSE_MOTION;
emouse.button = 0;
}
}
else
{
emouse.x = touch->x;
emouse.y = touch->y;
emouse.parent.type = RTGUI_EVENT_MOUSE_BUTTON;
emouse.button |= RTGUI_MOUSE_BUTTON_UP;
if ((touch->calibrating == RT_TRUE) && (touch->calibration_func != RT_NULL))
{
/* callback function */
touch->calibration_func(emouse.x, emouse.y);
}
}
/* rt_kprintf("touch %s: ts.x: %d, ts.y: %d\n", updown? "down" : "up",
touch->x, touch->y); */
/* send event to server */
if (touch->calibrating != RT_TRUE)
{
rtgui_server_post_event((&emouse.parent), sizeof(emouse));
}
}
#else
static void report_touch_input(int updown)
{
struct rt_touch_event touch_event;
if (updown)
{
ts.xp = ts.xp / ts.count;
ts.yp = ts.yp / ts.count;
if ((touch->calibrating == RT_TRUE) && (touch->calibration_func != RT_NULL))
{
touch->x = ts.xp;
touch->y = ts.yp;
}
else
{
if (touch->max_x > touch->min_x)
{
touch->x = touch->width * ( ts.xp - touch->min_x ) / (touch->max_x-touch->min_x);
}
else
{
touch->x = touch->width * ( touch->min_x - ts.xp ) / (touch->min_x-touch->max_x);
}
if (touch->max_y > touch->min_y)
{
touch->y = touch->height * ( ts.yp - touch->min_y ) / (touch->max_y-touch->min_y);
}
else
{
touch->y = touch->height * ( touch->min_y - ts.yp ) / (touch->min_y-touch->max_y);
}
}
touch_event.x = touch->x;
touch_event.y = touch->y;
touch_event.pressed = 1;
if (touch->first_down_report == RT_TRUE)
{
if (touch->calibrating != RT_TRUE && touch->eventpost_func)
{
touch->eventpost_func(touch->eventpost_param, &touch_event);
}
}
}
else
{
touch_event.x = touch->x;
touch_event.y = touch->y;
touch_event.pressed = 0;
if ((touch->calibrating == RT_TRUE) && (touch->calibration_func != RT_NULL))
{
/* callback function */
touch->calibration_func(touch_event.x, touch_event.y);
}
if (touch->calibrating != RT_TRUE && touch->eventpost_func)
{
touch->eventpost_func(touch->eventpost_param, &touch_event);
}
}
}
#endif
static void touch_timer_fire(void *parameter)
{
rt_uint32_t data0;
rt_uint32_t data1;
int updown;
data0 = ADCDAT0;
data1 = ADCDAT1;
updown = (!(data0 & S3C2410_ADCDAT0_UPDOWN)) && (!(data1 & S3C2410_ADCDAT0_UPDOWN));
if (updown)
{
if (ts.count != 0)
{
report_touch_input(updown);
}
ts.xp = 0;
ts.yp = 0;
ts.count = 0;
ADCTSC = S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST;
ADCCON |= S3C2410_ADCCON_ENABLE_START;
}
}
static void s3c2410_adc_stylus_action(void)
{
rt_uint32_t data0;
rt_uint32_t data1;
data0 = ADCDAT0;
data1 = ADCDAT1;
ts.xp += data0 & S3C2410_ADCDAT0_XPDATA_MASK;
ts.yp += data1 & S3C2410_ADCDAT1_YPDATA_MASK;
ts.count ++;
if (ts.count < (1<<ts.shift))
{
ADCTSC = S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST;
ADCCON |= S3C2410_ADCCON_ENABLE_START;
}
else
{
if (touch->first_down_report)
{
report_touch_input(1);
ts.xp = 0;
ts.yp = 0;
ts.count = 0;
touch->first_down_report = 0;
}
/* start timer */
rt_timer_start(touch->poll_timer);
ADCTSC = WAIT4INT(1);
}
SUBSRCPND |= BIT_SUB_ADC;
}
static void s3c2410_intc_stylus_updown(void)
{
rt_uint32_t data0;
rt_uint32_t data1;
int updown;
data0 = ADCDAT0;
data1 = ADCDAT1;
updown = (!(data0 & S3C2410_ADCDAT0_UPDOWN)) && (!(data1 & S3C2410_ADCDAT0_UPDOWN));
/* rt_kprintf("stylus: %s\n", updown? "down" : "up"); */
if (updown)
{
touch_timer_fire(0);
}
else
{
/* stop timer */
rt_timer_stop(touch->poll_timer);
touch->first_down_report = RT_TRUE;
if (ts.xp >= 0 && ts.yp >= 0)
{
report_touch_input(updown);
}
ts.count = 0;
ADCTSC = WAIT4INT(0);
}
SUBSRCPND |= BIT_SUB_TC;
}
static void rt_touch_handler(int irqno)
{
if (SUBSRCPND & BIT_SUB_ADC)
{
/* INT_SUB_ADC */
s3c2410_adc_stylus_action();
}
if (SUBSRCPND & BIT_SUB_TC)
{
/* INT_SUB_TC */
s3c2410_intc_stylus_updown();
}
/* clear interrupt */
INTPND |= (1ul << INTADC);
}
/* RT-Thread Device Interface */
static rt_err_t rtgui_touch_init(rt_device_t dev)
{
/* init touch screen structure */
rt_memset(&ts, 0, sizeof(struct s3c2410ts));
ts.delay = 50000;
ts.presc = 9;
ts.shift = 2;
ts.count = 0;
ts.xp = ts.yp = 0;
ADCCON = S3C2410_ADCCON_PRSCEN | S3C2410_ADCCON_PRSCVL(ts.presc);
ADCDLY = ts.delay;
ADCTSC = WAIT4INT(0);
rt_hw_interrupt_install(INTADC, rt_touch_handler, RT_NULL , "INTADC");
rt_hw_interrupt_umask(INTADC);
/* clear interrupt */
INTPND |= (1ul << INTADC);
SUBSRCPND |= BIT_SUB_TC;
SUBSRCPND |= BIT_SUB_ADC;
/* install interrupt handler */
INTSUBMSK &= ~BIT_SUB_ADC;
INTSUBMSK &= ~BIT_SUB_TC;
touch->first_down_report = RT_TRUE;
return RT_EOK;
}
static rt_err_t rtgui_touch_control(rt_device_t dev, rt_uint8_t cmd, void *args)
{
switch (cmd)
{
case RT_TOUCH_CALIBRATION:
touch->calibrating = RT_TRUE;
touch->calibration_func = (rt_touch_calibration_func_t)args;
break;
case RT_TOUCH_NORMAL:
touch->calibrating = RT_FALSE;
break;
case RT_TOUCH_CALIBRATION_DATA:
{
struct calibration_data *data;
data = (struct calibration_data *)args;
/* update */
touch->min_x = data->min_x;
touch->max_x = data->max_x;
touch->min_y = data->min_y;
touch->max_y = data->max_y;
/*
rt_kprintf("min_x = %d, max_x = %d, min_y = %d, max_y = %d\n",
touch->min_x, touch->max_x, touch->min_y, touch->max_y);
*/
}
break;
case RT_TOUCH_EVENTPOST:
touch->eventpost_func = (rt_touch_eventpost_func_t)args;
break;
case RT_TOUCH_EVENTPOST_PARAM:
touch->eventpost_param = args;
break;
}
return RT_EOK;
}
void rtgui_touch_hw_init(void)
{
rt_err_t result = RT_FALSE;
rt_device_t device = RT_NULL;
struct rt_device_graphic_info info;
touch = (struct rtgui_touch_device *)rt_malloc(sizeof(struct rtgui_touch_device));
if (touch == RT_NULL)
return; /* no memory yet */
/* clear device structure */
rt_memset(&(touch->parent), 0, sizeof(struct rt_device));
touch->calibrating = RT_FALSE;
touch->min_x = X_MIN;
touch->max_x = X_MAX;
touch->min_y = Y_MIN;
touch->max_y = Y_MAX;
touch->eventpost_func = RT_NULL;
touch->eventpost_param = RT_NULL;
/* init device structure */
touch->parent.type = RT_Device_Class_Unknown;
touch->parent.init = rtgui_touch_init;
touch->parent.control = rtgui_touch_control;
touch->parent.user_data = RT_NULL;
device = rt_device_find("lcd");
if (device == RT_NULL)
return; /* no this device */
/* get graphic device info */
result = rt_device_control(device, RTGRAPHIC_CTRL_GET_INFO, &info);
if (result != RT_EOK)
{
/* get device information failed */
return;
}
touch->width = info.width;
touch->height = info.height;
/* create 1/8 second timer */
touch->poll_timer = rt_timer_create("touch", touch_timer_fire, RT_NULL,
RT_TICK_PER_SECOND/8, RT_TIMER_FLAG_PERIODIC);
/* register touch device to RT-Thread */
rt_device_register(&(touch->parent), "touch", RT_DEVICE_FLAG_RDWR);
}
| zhangzq71/rt-thread | bsp/mini2440/drivers/touch.c | C | gpl-2.0 | 10,961 |
/*************************************************************************
* °æÈ¨ËùÓÐ(C) 1987-2004, ÉîÛÚ»ªÎª¼¼ÊõÓÐÏÞ¹«Ë¾.
*
* ÎÄ ¼þ Ãû : BSP_DRV_IPC.h
*
* ×÷ Õß : wangjing
*
* Ãè Êö : IPCÄ£¿éÓû§½Ó¿ÚÎļþ
*
* Ð޸ļǼ : 2011Äê4ÔÂ11ÈÕ v1.00 wangjing ´´½¨
*************************************************************************/
#ifndef _BSP_DRV_IPC_H_
#define _BSP_DRV_IPC_H_
#include <asm/io.h>
#include "soc_baseaddr_interface.h"
#include "soc_irqs.h"
#include "soc_ipc_interface.h"
#ifdef __cplusplus
extern "C" {
#endif
/*********************************************************
* Ìí¼ÓÐÂIPC×ÊÔ´£¬Ã¶¾ÙÃüÃû¸ñʽ:
* IPC_<Ä¿±ê´¦ÀíÆ÷>_INT_SRC_<Ô´´¦ÀíÆ÷>_<¹¦ÄÜ/×÷ÓÃ>
* Ä¿±ê´¦ÀíÆ÷:ACPU¡¢CCPU¡¢MCU¡¢HIFI¡¢BBE16
* Ô´´¦ÀíÆ÷ :ACPU¡¢CCPU¡¢MCU¡¢HIFI¡¢BBE16
* ¹¦ÄÜ/×÷Óà :
*********************************************************/
typedef enum tagNOSEC_IPC2_INT_LEV_E
{
NOSEC_IPC2_INT_BUTTOM = 32,
}NOSEC_IPC2_INT_LEV_E;
#define SIZE_4K (4096)
#define IPC_REG_SIZE (SIZE_4K)
#define BSP_RegRd(uwAddr) (*((volatile int *)(uwAddr)))
#define BSP_RegWr(uwAddr, uwValue) (*((volatile int *)(uwAddr)) = uwValue)
#define IPC_CHECK_PARA(ulLvl) \
do{\
if(ulLvl >= 32)\
{\
printk("Wrong para , line:%d\n", __LINE__);\
return -1;\
}\
}while(0)
int BSP_DRV_PRIVATE_IPCIntInit(void);
void clear_private_ipc_int(unsigned int enTarget, unsigned int enIntSrc);
int BSP_PRIVATE_IPC_IntEnable (unsigned int ulLvl);
int BSP_PRIVATE_IPC_IntDisable (NOSEC_IPC2_INT_LEV_E ulLvl);
#ifdef __cplusplus
}
#endif
#endif /* end #define _BSP_IPC_H_*/
| yuenar/huawei_P6S-U06_KK_kernel | drivers/multicore/ipcm/bsp_private_ipc.h | C | gpl-2.0 | 1,673 |
/*
* Gadget Function Driver for MTP
*
* Copyright (C) 2010 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/* #define DEBUG */
/* #define VERBOSE_DEBUG */
#include <linux/module.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/delay.h>
#include <linux/wait.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/file.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/usb.h>
#include <linux/usb_usual.h>
#include <linux/usb/ch9.h>
#include <linux/usb/f_mtp.h>
#define MTP_BULK_BUFFER_SIZE 16384
#define INTR_BUFFER_SIZE 28
/* String IDs */
#define INTERFACE_STRING_INDEX 0
/* values for mtp_dev.state */
#define STATE_OFFLINE 0 /* initial state, disconnected */
#define STATE_READY 1 /* ready for userspace calls */
#define STATE_BUSY 2 /* processing userspace calls */
#define STATE_CANCELED 3 /* transaction canceled by host */
#define STATE_ERROR 4 /* error from completion routine */
/* number of tx and rx requests to allocate */
#define TX_REQ_MAX 4
#define RX_REQ_MAX 2
#define INTR_REQ_MAX 5
/* ID for Microsoft MTP OS String */
#define MTP_OS_STRING_ID 0xEE
/* MTP class reqeusts */
#define MTP_REQ_CANCEL 0x64
#define MTP_REQ_GET_EXT_EVENT_DATA 0x65
#define MTP_REQ_RESET 0x66
#define MTP_REQ_GET_DEVICE_STATUS 0x67
/* constants for device status */
#define MTP_RESPONSE_OK 0x2001
#define MTP_RESPONSE_DEVICE_BUSY 0x2019
static const char mtp_shortname[] = "mtp_usb";
struct mtp_dev {
struct usb_function function;
struct usb_composite_dev *cdev;
spinlock_t lock;
struct usb_ep *ep_in;
struct usb_ep *ep_out;
struct usb_ep *ep_intr;
int state;
/* synchronize access to our device file */
atomic_t open_excl;
/* to enforce only one ioctl at a time */
atomic_t ioctl_excl;
struct list_head tx_idle;
struct list_head intr_idle;
wait_queue_head_t read_wq;
wait_queue_head_t write_wq;
wait_queue_head_t intr_wq;
struct usb_request *rx_req[RX_REQ_MAX];
int rx_done;
/* for processing MTP_SEND_FILE, MTP_RECEIVE_FILE and
* MTP_SEND_FILE_WITH_HEADER ioctls on a work queue
*/
struct workqueue_struct *wq;
struct work_struct send_file_work;
struct work_struct receive_file_work;
struct file *xfer_file;
loff_t xfer_file_offset;
int64_t xfer_file_length;
unsigned xfer_send_header;
uint16_t xfer_command;
uint32_t xfer_transaction_id;
int xfer_result;
int zlp_maxpacket;
};
static struct usb_interface_descriptor mtp_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 0,
.bNumEndpoints = 3,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.bInterfaceSubClass = USB_SUBCLASS_VENDOR_SPEC,
.bInterfaceProtocol = 0,
};
static struct usb_interface_descriptor ptp_interface_desc = {
.bLength = USB_DT_INTERFACE_SIZE,
.bDescriptorType = USB_DT_INTERFACE,
.bInterfaceNumber = 0,
.bNumEndpoints = 3,
.bInterfaceClass = USB_CLASS_STILL_IMAGE,
.bInterfaceSubClass = 1,
.bInterfaceProtocol = 1,
};
static struct usb_endpoint_descriptor mtp_highspeed_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor mtp_highspeed_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = __constant_cpu_to_le16(512),
};
static struct usb_endpoint_descriptor mtp_fullspeed_in_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor mtp_fullspeed_out_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor mtp_intr_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = __constant_cpu_to_le16(INTR_BUFFER_SIZE),
.bInterval = 6,
};
static struct usb_descriptor_header *fs_mtp_descs[] = {
(struct usb_descriptor_header *) &mtp_interface_desc,
(struct usb_descriptor_header *) &mtp_fullspeed_in_desc,
(struct usb_descriptor_header *) &mtp_fullspeed_out_desc,
(struct usb_descriptor_header *) &mtp_intr_desc,
NULL,
};
static struct usb_descriptor_header *hs_mtp_descs[] = {
(struct usb_descriptor_header *) &mtp_interface_desc,
(struct usb_descriptor_header *) &mtp_highspeed_in_desc,
(struct usb_descriptor_header *) &mtp_highspeed_out_desc,
(struct usb_descriptor_header *) &mtp_intr_desc,
NULL,
};
static struct usb_descriptor_header *fs_ptp_descs[] = {
(struct usb_descriptor_header *) &ptp_interface_desc,
(struct usb_descriptor_header *) &mtp_fullspeed_in_desc,
(struct usb_descriptor_header *) &mtp_fullspeed_out_desc,
(struct usb_descriptor_header *) &mtp_intr_desc,
NULL,
};
static struct usb_descriptor_header *hs_ptp_descs[] = {
(struct usb_descriptor_header *) &ptp_interface_desc,
(struct usb_descriptor_header *) &mtp_highspeed_in_desc,
(struct usb_descriptor_header *) &mtp_highspeed_out_desc,
(struct usb_descriptor_header *) &mtp_intr_desc,
NULL,
};
static struct usb_string mtp_string_defs[] = {
/* Naming interface "MTP" so libmtp will recognize us */
[INTERFACE_STRING_INDEX].s = "MTP",
{ }, /* end of list */
};
static struct usb_gadget_strings mtp_string_table = {
.language = 0x0409, /* en-US */
.strings = mtp_string_defs,
};
static struct usb_gadget_strings *mtp_strings[] = {
&mtp_string_table,
NULL,
};
/* Microsoft MTP OS String */
static u8 mtp_os_string[] = {
18, /* sizeof(mtp_os_string) */
USB_DT_STRING,
/* Signature field: "MSFT100" */
'M', 0, 'S', 0, 'F', 0, 'T', 0, '1', 0, '0', 0, '0', 0,
/* vendor code */
1,
/* padding */
0
};
/* Microsoft Extended Configuration Descriptor Header Section */
struct mtp_ext_config_desc_header {
__le32 dwLength;
__u16 bcdVersion;
__le16 wIndex;
__u8 bCount;
__u8 reserved[7];
};
/* Microsoft Extended Configuration Descriptor Function Section */
struct mtp_ext_config_desc_function {
__u8 bFirstInterfaceNumber;
__u8 bInterfaceCount;
__u8 compatibleID[8];
__u8 subCompatibleID[8];
__u8 reserved[6];
};
/* MTP Extended Configuration Descriptor */
struct {
struct mtp_ext_config_desc_header header;
struct mtp_ext_config_desc_function function;
} mtp_ext_config_desc = {
.header = {
.dwLength = __constant_cpu_to_le32(sizeof(mtp_ext_config_desc)),
.bcdVersion = __constant_cpu_to_le16(0x0100),
.wIndex = __constant_cpu_to_le16(4),
.bCount = __constant_cpu_to_le16(1),
},
.function = {
.bFirstInterfaceNumber = 0,
.bInterfaceCount = 1,
.compatibleID = { 'M', 'T', 'P' },
},
};
struct mtp_device_status {
__le16 wLength;
__le16 wCode;
};
/* temporary variable used between mtp_open() and mtp_gadget_bind() */
static struct mtp_dev *_mtp_dev;
static inline struct mtp_dev *func_to_mtp(struct usb_function *f)
{
return container_of(f, struct mtp_dev, function);
}
static struct usb_request *mtp_request_new(struct usb_ep *ep, int buffer_size)
{
struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!req)
return NULL;
/* now allocate buffers for the requests */
req->buf = kmalloc(buffer_size, GFP_KERNEL);
if (!req->buf) {
usb_ep_free_request(ep, req);
return NULL;
}
return req;
}
static void mtp_request_free(struct usb_request *req, struct usb_ep *ep)
{
if (req) {
kfree(req->buf);
usb_ep_free_request(ep, req);
}
}
static inline int mtp_lock(atomic_t *excl)
{
if (atomic_inc_return(excl) == 1) {
return 0;
} else {
atomic_dec(excl);
return -1;
}
}
static inline void mtp_unlock(atomic_t *excl)
{
atomic_dec(excl);
}
/* add a request to the tail of a list */
static void mtp_req_put(struct mtp_dev *dev, struct list_head *head,
struct usb_request *req)
{
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
list_add_tail(&req->list, head);
spin_unlock_irqrestore(&dev->lock, flags);
}
/* remove a request from the head of a list */
static struct usb_request
*mtp_req_get(struct mtp_dev *dev, struct list_head *head)
{
unsigned long flags;
struct usb_request *req;
spin_lock_irqsave(&dev->lock, flags);
if (list_empty(head)) {
req = 0;
} else {
req = list_first_entry(head, struct usb_request, list);
list_del(&req->list);
}
spin_unlock_irqrestore(&dev->lock, flags);
return req;
}
static void mtp_complete_in(struct usb_ep *ep, struct usb_request *req)
{
struct mtp_dev *dev = _mtp_dev;
if (req->status != 0)
dev->state = STATE_ERROR;
mtp_req_put(dev, &dev->tx_idle, req);
wake_up(&dev->write_wq);
}
static void mtp_complete_out(struct usb_ep *ep, struct usb_request *req)
{
struct mtp_dev *dev = _mtp_dev;
dev->rx_done = 1;
if (req->status != 0)
dev->state = STATE_ERROR;
wake_up(&dev->read_wq);
}
static void mtp_complete_intr(struct usb_ep *ep, struct usb_request *req)
{
struct mtp_dev *dev = _mtp_dev;
if (req->status != 0)
dev->state = STATE_ERROR;
mtp_req_put(dev, &dev->intr_idle, req);
wake_up(&dev->intr_wq);
}
static int mtp_create_bulk_endpoints(struct mtp_dev *dev,
struct usb_endpoint_descriptor *in_desc,
struct usb_endpoint_descriptor *out_desc,
struct usb_endpoint_descriptor *intr_desc)
{
struct usb_composite_dev *cdev = dev->cdev;
struct usb_request *req;
struct usb_ep *ep;
int i;
DBG(cdev, "create_bulk_endpoints dev: %p\n", dev);
ep = usb_ep_autoconfig(cdev->gadget, in_desc);
if (!ep) {
DBG(cdev, "usb_ep_autoconfig for ep_in failed\n");
return -ENODEV;
}
DBG(cdev, "usb_ep_autoconfig for ep_in got %s\n", ep->name);
ep->driver_data = dev; /* claim the endpoint */
dev->ep_in = ep;
ep = usb_ep_autoconfig(cdev->gadget, out_desc);
if (!ep) {
DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
return -ENODEV;
}
DBG(cdev, "usb_ep_autoconfig for mtp ep_out got %s\n", ep->name);
ep->driver_data = dev; /* claim the endpoint */
dev->ep_out = ep;
ep = usb_ep_autoconfig(cdev->gadget, intr_desc);
if (!ep) {
DBG(cdev, "usb_ep_autoconfig for ep_intr failed\n");
return -ENODEV;
}
DBG(cdev, "usb_ep_autoconfig for mtp ep_intr got %s\n", ep->name);
ep->driver_data = dev; /* claim the endpoint */
dev->ep_intr = ep;
/* now allocate requests for our endpoints */
for (i = 0; i < TX_REQ_MAX; i++) {
req = mtp_request_new(dev->ep_in, MTP_BULK_BUFFER_SIZE);
if (!req)
goto fail;
req->complete = mtp_complete_in;
mtp_req_put(dev, &dev->tx_idle, req);
}
for (i = 0; i < RX_REQ_MAX; i++) {
req = mtp_request_new(dev->ep_out, MTP_BULK_BUFFER_SIZE);
if (!req)
goto fail;
req->complete = mtp_complete_out;
dev->rx_req[i] = req;
}
for (i = 0; i < INTR_REQ_MAX; i++) {
req = mtp_request_new(dev->ep_intr, INTR_BUFFER_SIZE);
if (!req)
goto fail;
req->complete = mtp_complete_intr;
mtp_req_put(dev, &dev->intr_idle, req);
}
return 0;
fail:
printk(KERN_ERR "mtp_bind() could not allocate requests\n");
return -1;
}
static ssize_t mtp_read(struct file *fp, char __user *buf,
size_t count, loff_t *pos)
{
struct mtp_dev *dev = fp->private_data;
struct usb_composite_dev *cdev = dev->cdev;
struct usb_request *req;
int r = count, xfer;
int ret = 0;
DBG(cdev, "mtp_read(%d)\n", count);
if (count > MTP_BULK_BUFFER_SIZE)
return -EINVAL;
/* we will block until we're online */
DBG(cdev, "mtp_read: waiting for online state\n");
ret = wait_event_interruptible(dev->read_wq,
dev->state != STATE_OFFLINE);
if (ret < 0) {
r = ret;
goto done;
}
spin_lock_irq(&dev->lock);
if (dev->state == STATE_CANCELED) {
/* report cancelation to userspace */
dev->state = STATE_READY;
spin_unlock_irq(&dev->lock);
return -ECANCELED;
}
dev->state = STATE_BUSY;
spin_unlock_irq(&dev->lock);
requeue_req:
/* queue a request */
req = dev->rx_req[0];
req->length = count;
dev->rx_done = 0;
ret = usb_ep_queue(dev->ep_out, req, GFP_KERNEL);
if (ret < 0) {
r = -EIO;
goto done;
} else {
DBG(cdev, "rx %p queue\n", req);
}
/* wait for a request to complete */
ret = wait_event_interruptible(dev->read_wq, dev->rx_done);
if (ret < 0) {
r = ret;
usb_ep_dequeue(dev->ep_out, req);
goto done;
}
if (dev->state == STATE_BUSY) {
/* If we got a 0-len packet, throw it back and try again. */
if (req->actual == 0)
goto requeue_req;
DBG(cdev, "rx %p %d\n", req, req->actual);
xfer = (req->actual < count) ? req->actual : count;
r = xfer;
if (copy_to_user(buf, req->buf, xfer))
r = -EFAULT;
} else
r = -EIO;
done:
spin_lock_irq(&dev->lock);
if (dev->state == STATE_CANCELED)
r = -ECANCELED;
else if (dev->state != STATE_OFFLINE)
dev->state = STATE_READY;
spin_unlock_irq(&dev->lock);
DBG(cdev, "mtp_read returning %d\n", r);
return r;
}
static ssize_t mtp_write(struct file *fp, const char __user *buf,
size_t count, loff_t *pos)
{
struct mtp_dev *dev = fp->private_data;
struct usb_composite_dev *cdev = dev->cdev;
struct usb_request *req = 0;
int r = count, xfer;
int sendZLP = 0;
int ret;
DBG(cdev, "mtp_write(%d)\n", count);
spin_lock_irq(&dev->lock);
if (dev->state == STATE_CANCELED) {
/* report cancelation to userspace */
dev->state = STATE_READY;
spin_unlock_irq(&dev->lock);
return -ECANCELED;
}
if (dev->state == STATE_OFFLINE) {
spin_unlock_irq(&dev->lock);
return -ENODEV;
}
dev->state = STATE_BUSY;
spin_unlock_irq(&dev->lock);
/* we need to send a zero length packet to signal the end of transfer
* if the transfer size is aligned to a packet boundary.
*/
if ((count & (dev->zlp_maxpacket - 1)) == 0)
sendZLP = 1;
while (count > 0 || sendZLP) {
/* so we exit after sending ZLP */
if (count == 0)
sendZLP = 0;
if (dev->state != STATE_BUSY) {
DBG(cdev, "mtp_write dev->error\n");
r = -EIO;
break;
}
/* get an idle tx request to use */
req = 0;
ret = wait_event_interruptible(dev->write_wq,
((req = mtp_req_get(dev, &dev->tx_idle))
|| dev->state != STATE_BUSY));
if (!req) {
r = ret;
break;
}
if (count > MTP_BULK_BUFFER_SIZE)
xfer = MTP_BULK_BUFFER_SIZE;
else
xfer = count;
if (xfer && copy_from_user(req->buf, buf, xfer)) {
r = -EFAULT;
break;
}
req->length = xfer;
ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
if (ret < 0) {
DBG(cdev, "mtp_write: xfer error %d\n", ret);
r = -EIO;
break;
}
buf += xfer;
count -= xfer;
/* zero this so we don't try to free it on error exit */
req = 0;
}
if (req)
mtp_req_put(dev, &dev->tx_idle, req);
spin_lock_irq(&dev->lock);
if (dev->state == STATE_CANCELED)
r = -ECANCELED;
else if (dev->state != STATE_OFFLINE)
dev->state = STATE_READY;
spin_unlock_irq(&dev->lock);
DBG(cdev, "mtp_write returning %d\n", r);
return r;
}
/* read from a local file and write to USB */
static void send_file_work(struct work_struct *data) {
struct mtp_dev *dev = container_of(data, struct mtp_dev, send_file_work);
struct usb_composite_dev *cdev = dev->cdev;
struct usb_request *req = 0;
struct mtp_data_header *header;
struct file *filp;
loff_t offset;
int64_t count;
int xfer, ret, hdr_size;
int r = 0;
int sendZLP = 0;
/* read our parameters */
smp_rmb();
filp = dev->xfer_file;
offset = dev->xfer_file_offset;
count = dev->xfer_file_length;
DBG(cdev, "send_file_work(%lld %lld)\n", offset, count);
if (dev->xfer_send_header) {
hdr_size = sizeof(struct mtp_data_header);
count += hdr_size;
} else {
hdr_size = 0;
}
/* we need to send a zero length packet to signal the end of transfer
* if the transfer size is aligned to a packet boundary.
*/
if ((count & (dev->zlp_maxpacket - 1)) == 0)
sendZLP = 1;
while (count > 0 || sendZLP) {
/* so we exit after sending ZLP */
if (count == 0)
sendZLP = 0;
/* get an idle tx request to use */
req = 0;
ret = wait_event_interruptible(dev->write_wq,
(req = mtp_req_get(dev, &dev->tx_idle))
|| dev->state != STATE_BUSY);
if (dev->state == STATE_CANCELED) {
r = -ECANCELED;
break;
}
if (!req) {
r = ret;
break;
}
if (count > MTP_BULK_BUFFER_SIZE)
xfer = MTP_BULK_BUFFER_SIZE;
else
xfer = count;
if (hdr_size) {
/* prepend MTP data header */
header = (struct mtp_data_header *)req->buf;
header->length = __cpu_to_le32(count);
header->type = __cpu_to_le16(2); /* data packet */
header->command = __cpu_to_le16(dev->xfer_command);
header->transaction_id = __cpu_to_le32(dev->xfer_transaction_id);
}
ret = vfs_read(filp, req->buf + hdr_size, xfer - hdr_size, &offset);
if (ret < 0) {
r = ret;
break;
}
xfer = ret + hdr_size;
hdr_size = 0;
req->length = xfer;
ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
if (ret < 0) {
DBG(cdev, "send_file_work: xfer error %d\n", ret);
dev->state = STATE_ERROR;
r = -EIO;
break;
}
count -= xfer;
/* zero this so we don't try to free it on error exit */
req = 0;
}
if (req)
mtp_req_put(dev, &dev->tx_idle, req);
DBG(cdev, "send_file_work returning %d\n", r);
/* write the result */
dev->xfer_result = r;
smp_wmb();
}
/* read from USB and write to a local file */
static void receive_file_work(struct work_struct *data)
{
struct mtp_dev *dev = container_of(data, struct mtp_dev, receive_file_work);
struct usb_composite_dev *cdev = dev->cdev;
struct usb_request *read_req = NULL, *write_req = NULL;
struct file *filp;
loff_t offset;
int64_t count;
int ret, cur_buf = 0;
int r = 0;
/* read our parameters */
smp_rmb();
filp = dev->xfer_file;
offset = dev->xfer_file_offset;
count = dev->xfer_file_length;
DBG(cdev, "receive_file_work(%lld)\n", count);
while (count > 0 || write_req) {
if (count > 0) {
/* queue a request */
read_req = dev->rx_req[cur_buf];
cur_buf = (cur_buf + 1) % RX_REQ_MAX;
read_req->length = (count > MTP_BULK_BUFFER_SIZE
? MTP_BULK_BUFFER_SIZE : count);
dev->rx_done = 0;
ret = usb_ep_queue(dev->ep_out, read_req, GFP_KERNEL);
if (ret < 0) {
r = -EIO;
dev->state = STATE_ERROR;
break;
}
}
if (write_req) {
DBG(cdev, "rx %p %d\n", write_req, write_req->actual);
ret = vfs_write(filp, write_req->buf, write_req->actual,
&offset);
DBG(cdev, "vfs_write %d\n", ret);
if (ret != write_req->actual) {
r = -EIO;
dev->state = STATE_ERROR;
break;
}
write_req = NULL;
}
if (read_req) {
/* wait for our last read to complete */
ret = wait_event_interruptible(dev->read_wq,
dev->rx_done || dev->state != STATE_BUSY);
if (dev->state == STATE_CANCELED) {
r = -ECANCELED;
if (!dev->rx_done)
usb_ep_dequeue(dev->ep_out, read_req);
break;
}
/* if xfer_file_length is 0xFFFFFFFF, then we read until
* we get a zero length packet
*/
if (count != 0xFFFFFFFF)
count -= read_req->actual;
if (read_req->actual < read_req->length) {
/* short packet is used to signal EOF for sizes > 4 gig */
DBG(cdev, "got short packet\n");
count = 0;
}
write_req = read_req;
read_req = NULL;
}
}
DBG(cdev, "receive_file_work returning %d\n", r);
/* write the result */
dev->xfer_result = r;
smp_wmb();
}
static int mtp_send_event(struct mtp_dev *dev, struct mtp_event *event)
{
struct usb_request *req= NULL;
int ret;
int length = event->length;
DBG(dev->cdev, "mtp_send_event(%d)\n", event->length);
if (length < 0 || length > INTR_BUFFER_SIZE)
return -EINVAL;
if (dev->state == STATE_OFFLINE)
return -ENODEV;
ret = wait_event_interruptible_timeout(dev->intr_wq,
(req = mtp_req_get(dev, &dev->intr_idle)), msecs_to_jiffies(1000));
if (!req)
return -ETIME;
if (copy_from_user(req->buf, (void __user *)event->data, length)) {
mtp_req_put(dev, &dev->intr_idle, req);
return -EFAULT;
}
req->length = length;
ret = usb_ep_queue(dev->ep_intr, req, GFP_KERNEL);
if (ret)
mtp_req_put(dev, &dev->intr_idle, req);
return ret;
}
static long mtp_ioctl(struct file *fp, unsigned code, unsigned long value)
{
struct mtp_dev *dev = fp->private_data;
struct file *filp = NULL;
int ret = -EINVAL;
if (mtp_lock(&dev->ioctl_excl))
return -EBUSY;
switch (code) {
case MTP_SEND_FILE:
case MTP_RECEIVE_FILE:
case MTP_SEND_FILE_WITH_HEADER:
{
struct mtp_file_range mfr;
struct work_struct *work;
spin_lock_irq(&dev->lock);
if (dev->state == STATE_CANCELED) {
/* report cancelation to userspace */
dev->state = STATE_READY;
spin_unlock_irq(&dev->lock);
ret = -ECANCELED;
goto out;
}
if (dev->state == STATE_OFFLINE) {
spin_unlock_irq(&dev->lock);
ret = -ENODEV;
goto out;
}
dev->state = STATE_BUSY;
spin_unlock_irq(&dev->lock);
if (copy_from_user(&mfr, (void __user *)value, sizeof(mfr))) {
ret = -EFAULT;
goto fail;
}
/* hold a reference to the file while we are working with it */
filp = fget(mfr.fd);
if (!filp) {
ret = -EBADF;
goto fail;
}
/* write the parameters */
dev->xfer_file = filp;
dev->xfer_file_offset = mfr.offset;
dev->xfer_file_length = mfr.length;
smp_wmb();
if (code == MTP_SEND_FILE_WITH_HEADER) {
work = &dev->send_file_work;
dev->xfer_send_header = 1;
dev->xfer_command = mfr.command;
dev->xfer_transaction_id = mfr.transaction_id;
} else if (code == MTP_SEND_FILE) {
work = &dev->send_file_work;
dev->xfer_send_header = 0;
} else {
work = &dev->receive_file_work;
}
/* We do the file transfer on a work queue so it will run
* in kernel context, which is necessary for vfs_read and
* vfs_write to use our buffers in the kernel address space.
*/
queue_work(dev->wq, work);
/* wait for operation to complete */
flush_workqueue(dev->wq);
fput(filp);
/* read the result */
smp_rmb();
ret = dev->xfer_result;
break;
}
case MTP_SEND_EVENT:
{
struct mtp_event event;
/* return here so we don't change dev->state below,
* which would interfere with bulk transfer state.
*/
if (copy_from_user(&event, (void __user *)value, sizeof(event)))
ret = -EFAULT;
else
ret = mtp_send_event(dev, &event);
goto out;
}
}
fail:
spin_lock_irq(&dev->lock);
if (dev->state == STATE_CANCELED)
ret = -ECANCELED;
else if (dev->state != STATE_OFFLINE)
dev->state = STATE_READY;
spin_unlock_irq(&dev->lock);
out:
mtp_unlock(&dev->ioctl_excl);
DBG(dev->cdev, "ioctl returning %d\n", ret);
return ret;
}
static int mtp_open(struct inode *ip, struct file *fp)
{
struct usb_descriptor_header **descriptors;
printk(KERN_INFO "mtp_open\n");
if (!_mtp_dev->cdev) {
WARN(1, "_mtp_dev->cdev is NULL in mtp_open\n");
return -ENODEV;
}
if (mtp_lock(&_mtp_dev->open_excl))
return -EBUSY;
/* clear any error condition */
if (_mtp_dev->state != STATE_OFFLINE)
_mtp_dev->state = STATE_READY;
if (_mtp_dev->cdev->gadget->speed == USB_SPEED_HIGH)
descriptors = _mtp_dev->function.hs_descriptors;
else
descriptors = _mtp_dev->function.descriptors;
/* find mtp ep_in descriptor */
for (; *descriptors; ++descriptors) {
struct usb_endpoint_descriptor *ep;
ep = (struct usb_endpoint_descriptor *)*descriptors;
if (ep->bDescriptorType == USB_DT_ENDPOINT
&& (ep->bEndpointAddress & USB_DIR_IN)
&& ep->bmAttributes == USB_ENDPOINT_XFER_BULK) {
_mtp_dev->zlp_maxpacket =
__le16_to_cpu(ep->wMaxPacketSize);
fp->private_data = _mtp_dev;
return 0;
}
}
return -ENODEV;
}
static int mtp_release(struct inode *ip, struct file *fp)
{
printk(KERN_INFO "mtp_release\n");
mtp_unlock(&_mtp_dev->open_excl);
return 0;
}
/* file operations for /dev/mtp_usb */
static const struct file_operations mtp_fops = {
.owner = THIS_MODULE,
.read = mtp_read,
.write = mtp_write,
.unlocked_ioctl = mtp_ioctl,
.open = mtp_open,
.release = mtp_release,
};
static struct miscdevice mtp_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = mtp_shortname,
.fops = &mtp_fops,
};
static int mtp_ctrlrequest(struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *ctrl)
{
struct mtp_dev *dev = _mtp_dev;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
unsigned long flags;
VDBG(cdev, "mtp_ctrlrequest "
"%02x.%02x v%04x i%04x l%u\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
/* Handle MTP OS string */
if (ctrl->bRequestType ==
(USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE)
&& ctrl->bRequest == USB_REQ_GET_DESCRIPTOR
&& (w_value >> 8) == USB_DT_STRING
&& (w_value & 0xFF) == MTP_OS_STRING_ID) {
value = (w_length < sizeof(mtp_os_string)
? w_length : sizeof(mtp_os_string));
memcpy(cdev->req->buf, mtp_os_string, value);
} else if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_VENDOR) {
/* Handle MTP OS descriptor */
DBG(cdev, "vendor request: %d index: %d value: %d length: %d\n",
ctrl->bRequest, w_index, w_value, w_length);
if (ctrl->bRequest == 1
&& (ctrl->bRequestType & USB_DIR_IN)
&& (w_index == 4 || w_index == 5)) {
value = (w_length < sizeof(mtp_ext_config_desc) ?
w_length : sizeof(mtp_ext_config_desc));
memcpy(cdev->req->buf, &mtp_ext_config_desc, value);
}
} else if ((ctrl->bRequestType & USB_TYPE_MASK) == USB_TYPE_CLASS) {
DBG(cdev, "class request: %d index: %d value: %d length: %d\n",
ctrl->bRequest, w_index, w_value, w_length);
if (ctrl->bRequest == MTP_REQ_CANCEL && w_index == 0
&& w_value == 0) {
DBG(cdev, "MTP_REQ_CANCEL\n");
spin_lock_irqsave(&dev->lock, flags);
if (dev->state == STATE_BUSY) {
dev->state = STATE_CANCELED;
wake_up(&dev->read_wq);
wake_up(&dev->write_wq);
}
spin_unlock_irqrestore(&dev->lock, flags);
/* We need to queue a request to read the remaining
* bytes, but we don't actually need to look at
* the contents.
*/
value = w_length;
} else if (ctrl->bRequest == MTP_REQ_GET_DEVICE_STATUS
&& w_index == 0 && w_value == 0) {
struct mtp_device_status *status = cdev->req->buf;
status->wLength =
__constant_cpu_to_le16(sizeof(*status));
DBG(cdev, "MTP_REQ_GET_DEVICE_STATUS\n");
spin_lock_irqsave(&dev->lock, flags);
/* device status is "busy" until we report
* the cancelation to userspace
*/
if (dev->state == STATE_CANCELED)
status->wCode =
__cpu_to_le16(MTP_RESPONSE_DEVICE_BUSY);
else
status->wCode =
__cpu_to_le16(MTP_RESPONSE_OK);
spin_unlock_irqrestore(&dev->lock, flags);
value = sizeof(*status);
}
}
/* respond with data transfer or status phase? */
if (value >= 0) {
int rc;
cdev->req->zero = value < w_length;
cdev->req->length = value;
rc = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
if (rc < 0)
ERROR(cdev, "%s setup response queue error\n", __func__);
}
return value;
}
static int
mtp_function_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct mtp_dev *dev = func_to_mtp(f);
int id;
int ret;
dev->cdev = cdev;
DBG(cdev, "mtp_function_bind dev: %p\n", dev);
/* allocate interface ID(s) */
id = usb_interface_id(c, f);
if (id < 0)
return id;
mtp_interface_desc.bInterfaceNumber = id;
/* allocate endpoints */
ret = mtp_create_bulk_endpoints(dev, &mtp_fullspeed_in_desc,
&mtp_fullspeed_out_desc, &mtp_intr_desc);
if (ret)
return ret;
/* support high speed hardware */
if (gadget_is_dualspeed(c->cdev->gadget)) {
mtp_highspeed_in_desc.bEndpointAddress =
mtp_fullspeed_in_desc.bEndpointAddress;
mtp_highspeed_out_desc.bEndpointAddress =
mtp_fullspeed_out_desc.bEndpointAddress;
}
DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
f->name, dev->ep_in->name, dev->ep_out->name);
return 0;
}
static void
mtp_function_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct mtp_dev *dev = func_to_mtp(f);
struct usb_request *req;
int i;
while ((req = mtp_req_get(dev, &dev->tx_idle)))
mtp_request_free(req, dev->ep_in);
for (i = 0; i < RX_REQ_MAX; i++)
mtp_request_free(dev->rx_req[i], dev->ep_out);
while ((req = mtp_req_get(dev, &dev->intr_idle)))
mtp_request_free(req, dev->ep_intr);
dev->state = STATE_OFFLINE;
}
static int mtp_function_set_alt(struct usb_function *f,
unsigned intf, unsigned alt)
{
struct mtp_dev *dev = func_to_mtp(f);
struct usb_composite_dev *cdev = f->config->cdev;
int ret;
DBG(cdev, "mtp_function_set_alt intf: %d alt: %d\n", intf, alt);
ret = usb_ep_enable(dev->ep_in,
ep_choose(cdev->gadget,
&mtp_highspeed_in_desc,
&mtp_fullspeed_in_desc));
if (ret)
return ret;
ret = usb_ep_enable(dev->ep_out,
ep_choose(cdev->gadget,
&mtp_highspeed_out_desc,
&mtp_fullspeed_out_desc));
if (ret) {
usb_ep_disable(dev->ep_in);
return ret;
}
ret = usb_ep_enable(dev->ep_intr, &mtp_intr_desc);
if (ret) {
usb_ep_disable(dev->ep_out);
usb_ep_disable(dev->ep_in);
return ret;
}
dev->state = STATE_READY;
/* readers may be blocked waiting for us to go online */
wake_up(&dev->read_wq);
return 0;
}
static void mtp_function_disable(struct usb_function *f)
{
struct mtp_dev *dev = func_to_mtp(f);
struct usb_composite_dev *cdev = dev->cdev;
DBG(cdev, "mtp_function_disable\n");
dev->state = STATE_OFFLINE;
usb_ep_disable(dev->ep_in);
usb_ep_disable(dev->ep_out);
usb_ep_disable(dev->ep_intr);
/* readers may be blocked waiting for us to go online */
wake_up(&dev->read_wq);
VDBG(cdev, "%s disabled\n", dev->function.name);
}
static int mtp_bind_config(struct usb_configuration *c, bool ptp_config)
{
struct mtp_dev *dev = _mtp_dev;
int ret = 0;
printk(KERN_INFO "mtp_bind_config\n");
/* allocate a string ID for our interface */
if (mtp_string_defs[INTERFACE_STRING_INDEX].id == 0) {
ret = usb_string_id(c->cdev);
if (ret < 0)
return ret;
mtp_string_defs[INTERFACE_STRING_INDEX].id = ret;
mtp_interface_desc.iInterface = ret;
}
dev->cdev = c->cdev;
dev->function.name = "mtp";
dev->function.strings = mtp_strings;
if (ptp_config) {
dev->function.descriptors = fs_ptp_descs;
dev->function.hs_descriptors = hs_ptp_descs;
} else {
dev->function.descriptors = fs_mtp_descs;
dev->function.hs_descriptors = hs_mtp_descs;
}
dev->function.bind = mtp_function_bind;
dev->function.unbind = mtp_function_unbind;
dev->function.set_alt = mtp_function_set_alt;
dev->function.disable = mtp_function_disable;
return usb_add_function(c, &dev->function);
}
static int mtp_setup(void)
{
struct mtp_dev *dev;
int ret;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
spin_lock_init(&dev->lock);
init_waitqueue_head(&dev->read_wq);
init_waitqueue_head(&dev->write_wq);
init_waitqueue_head(&dev->intr_wq);
atomic_set(&dev->open_excl, 0);
atomic_set(&dev->ioctl_excl, 0);
INIT_LIST_HEAD(&dev->tx_idle);
INIT_LIST_HEAD(&dev->intr_idle);
dev->wq = create_singlethread_workqueue("f_mtp");
if (!dev->wq) {
ret = -ENOMEM;
goto err1;
}
INIT_WORK(&dev->send_file_work, send_file_work);
INIT_WORK(&dev->receive_file_work, receive_file_work);
_mtp_dev = dev;
ret = misc_register(&mtp_device);
if (ret)
goto err2;
return 0;
err2:
destroy_workqueue(dev->wq);
err1:
_mtp_dev = NULL;
kfree(dev);
printk(KERN_ERR "mtp gadget driver failed to initialize\n");
return ret;
}
static void mtp_cleanup(void)
{
struct mtp_dev *dev = _mtp_dev;
if (!dev)
return;
misc_deregister(&mtp_device);
destroy_workqueue(dev->wq);
_mtp_dev = NULL;
kfree(dev);
}
| transi/kernel_amazon_bowser-common | drivers/usb/gadget/f_mtp.c | C | gpl-2.0 | 32,603 |
/*
* drivers/amlogic/cpufreq/cpufreq_table.h
*
* Copyright (C) 2015 Amlogic, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
*/
#include <linux/cpufreq.h>
static struct cpufreq_frequency_table meson_freq_table[] = {
{0, 96000 },
{1, 192000 },
{2, 312000 },
{3, 408000 },
{4, 504000 },
{5, 600000 },
{6, 696000 },
{7, 816000 },
{8, 912000 },
{9, 1008000 },
{10, 1104000 },
{11, 1200000 },
{12, 1296000 },
{13, 1416000 },
{14, 1512000 },
{15, 1608000 },
{16, 1800000 },
{17, 1992000 },
{18, CPUFREQ_TABLE_END},
};
| wetek-enigma/linux-wetek-3.14.y | drivers/amlogic/cpufreq/cpufreq_table.h | C | gpl-2.0 | 1,050 |
<?php
class AWPCP_FeeType extends AWPCP_PaymentTermType {
const TYPE = 'fee';
public function __construct() {
parent::__construct(_x('Fee', 'payment term type', 'AWPCP'), self::TYPE, '');
add_action('awpcp-transaction-status-updated', array($this, 'update_buys_count'), 10, 2);
}
public function update_buys_count($transaction, $status) {
if ($transaction->is_completed() && $transaction->was_payment_successful()) {
if ($transaction->get('payment-term-type', false) !== self::TYPE)
return;
$term = self::find_by_id($transaction->get('payment-term-id'));
if (is_null($term)) return;
$term->buys = $term->buys + 1;
$term->save();
}
}
public function find_by_id($id) {
if (absint($id) === 0)
return $this->get_free_payment_term();
return AWPCP_Fee::find_by_id($id);
}
private function get_free_payment_term() {
return new AWPCP_Fee(array(
'id' => 0,
'name' => __('Free Listing', 'AWPCP'),
'description' => '',
'duration_amount' => get_awpcp_option('addurationfreemode'),
'duration_interval' => AWPCP_Fee::INTERVAL_DAY,
'price' => 0,
'credits' => 0,
'categories' => array(),
'images' => get_awpcp_option('imagesallowedfree'),
'ads' => 1,
'characters' => get_awpcp_option( 'maxcharactersallowed' ),
'title_characters' => get_awpcp_option( 'characters-allowed-in-title' ),
'buys' => 0,
'featured' => 0,
'private' => 0,
));
}
public function get_payment_terms() {
global $wpdb;
if (!awpcp_payments_api()->payments_enabled()) {
return array($this->get_free_payment_term());
}
$order = get_awpcp_option( 'fee-order' );
$direction = get_awpcp_option( 'fee-order-direction' );
switch ($order) {
case 1:
$orderby = array( 'adterm_name', $direction );
break;
case 2:
$orderby = array( "amount $direction, adterm_name", $direction );
break;
case 3:
$orderby = array( "imagesallowed $direction, adterm_name", $direction );
break;
case 5:
$orderby = array( "_duration_interval $direction, rec_period $direction, adterm_name", $direction );
break;
}
if ( awpcp_current_user_is_admin() ) {
$args = array(
'orderby' => $orderby[0],
'order' => $orderby[1],
);
} else {
$args = array(
'where' => 'private = 0',
'orderby' => $orderby[0],
'order' => $orderby[1],
);
}
return AWPCP_Fee::query($args);
}
public function get_user_payment_terms($user_id) {
static $terms = null;
if ( is_null( $terms ) ) {
$terms = $this->get_payment_terms();
}
return $terms;
}
}
| Owchzzz/Militiatoday | wp-content/plugins/another-wordpress-classifieds-plugin/includes/payment-term-fee-type.php | PHP | gpl-2.0 | 3,188 |
/*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LOAD_LIB_H
#define LOAD_LIB_H
#include "Define.h"
#include "CascHandles.h"
#include <map>
#include <string>
#define FILE_FORMAT_VERSION 18
#pragma pack(push, 1)
union u_map_fcc
{
char fcc_txt[4];
uint32 fcc;
};
//
// File version chunk
//
struct file_MVER
{
union{
uint32 fcc;
char fcc_txt[4];
};
uint32 size;
uint32 ver;
};
struct file_MWMO
{
u_map_fcc fcc;
uint32 size;
char FileList[1];
};
class FileChunk
{
public:
FileChunk(uint8* data_, uint32 size_) : data(data_), size(size_) { }
~FileChunk();
uint8* data;
uint32 size;
template<class T>
T* As() { return (T*)data; }
void parseSubChunks();
std::multimap<std::string, FileChunk*> subchunks;
FileChunk* GetSubChunk(std::string const& name);
};
class ChunkedFile
{
public:
uint8 *data;
uint32 data_size;
uint8 *GetData() { return data; }
uint32 GetDataSize() { return data_size; }
ChunkedFile();
virtual ~ChunkedFile();
bool prepareLoadedData();
bool loadFile(CASC::StorageHandle const& mpq, std::string const& fileName, bool log = true);
void free();
void parseChunks();
std::multimap<std::string, FileChunk*> chunks;
FileChunk* GetChunk(std::string const& name);
};
#pragma pack(pop)
#endif
| Poveda09/TrinityCore | src/tools/map_extractor/loadlib/loadlib.h | C | gpl-2.0 | 2,102 |
#!/bin/bash
#
# Copyright 2013 Tim O'Shea
#
# This file is part of PyBOMBS
#
# PyBOMBS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# PyBOMBS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
meld $2 $5
| scalable-networks/ext | pybombs/git-meld.sh | Shell | gpl-2.0 | 778 |
/*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
* Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero>
* Copyright (C) 2011-2016 Nostalrius <https://nostalrius.org>
* Copyright (C) 2016-2017 Elysium Project <https://github.com/elysium-project>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "MovementGenerator.h"
#include "Unit.h"
MovementGenerator::~MovementGenerator()
{
}
bool MovementGenerator::IsActive(Unit& u)
{
// When movement generator list modified from Update movegen object erase delayed,
// so pointer still valid and be used for check
return !u.GetMotionMaster()->empty() && u.GetMotionMaster()->top() == this;
}
| jzcxw/core | src/game/Movement/MovementGenerator.cpp | C++ | gpl-2.0 | 1,356 |
UPDATE `realmlist` SET `gamebuild`=30993 WHERE `gamebuild`=30706;
ALTER TABLE `realmlist` CHANGE `gamebuild` `gamebuild` int(10) unsigned NOT NULL DEFAULT '30993';
| Regigicas/TrinityCore | sql/old/7/auth/19061_2019_07_15/2019_07_14_00_auth.sql | SQL | gpl-2.0 | 165 |
/*
* Real-Time Scheduling Class (mapped to the SCHED_FIFO and SCHED_RR
* policies)
*/
#include "sched.h"
#include <linux/slab.h>
#include <trace/events/sched.h>
int sched_rr_timeslice = RR_TIMESLICE;
static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
struct rt_bandwidth def_rt_bandwidth;
static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
{
struct rt_bandwidth *rt_b =
container_of(timer, struct rt_bandwidth, rt_period_timer);
ktime_t now;
int overrun;
int idle = 0;
for (;;) {
now = hrtimer_cb_get_time(timer);
overrun = hrtimer_forward(timer, now, rt_b->rt_period);
if (!overrun)
break;
idle = do_sched_rt_period_timer(rt_b, overrun);
}
return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
}
void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
{
rt_b->rt_period = ns_to_ktime(period);
rt_b->rt_runtime = runtime;
raw_spin_lock_init(&rt_b->rt_runtime_lock);
hrtimer_init(&rt_b->rt_period_timer,
CLOCK_MONOTONIC, HRTIMER_MODE_REL);
rt_b->rt_period_timer.function = sched_rt_period_timer;
}
static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
{
if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
return;
if (hrtimer_active(&rt_b->rt_period_timer))
return;
raw_spin_lock(&rt_b->rt_runtime_lock);
start_bandwidth_timer(&rt_b->rt_period_timer, rt_b->rt_period);
raw_spin_unlock(&rt_b->rt_runtime_lock);
}
void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
{
struct rt_prio_array *array;
int i;
array = &rt_rq->active;
for (i = 0; i < MAX_RT_PRIO; i++) {
INIT_LIST_HEAD(array->queue + i);
__clear_bit(i, array->bitmap);
}
/* delimiter for bitsearch: */
__set_bit(MAX_RT_PRIO, array->bitmap);
#if defined CONFIG_SMP
rt_rq->highest_prio.curr = MAX_RT_PRIO;
rt_rq->highest_prio.next = MAX_RT_PRIO;
rt_rq->rt_nr_migratory = 0;
rt_rq->overloaded = 0;
plist_head_init(&rt_rq->pushable_tasks);
#endif
rt_rq->rt_time = 0;
rt_rq->rt_throttled = 0;
rt_rq->rt_runtime = 0;
raw_spin_lock_init(&rt_rq->rt_runtime_lock);
}
#ifdef CONFIG_RT_GROUP_SCHED
static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
{
hrtimer_cancel(&rt_b->rt_period_timer);
}
#define rt_entity_is_task(rt_se) (!(rt_se)->my_q)
static inline struct task_struct *rt_task_of(struct sched_rt_entity *rt_se)
{
#ifdef CONFIG_SCHED_DEBUG
WARN_ON_ONCE(!rt_entity_is_task(rt_se));
#endif
return container_of(rt_se, struct task_struct, rt);
}
static inline struct rq *rq_of_rt_rq(struct rt_rq *rt_rq)
{
return rt_rq->rq;
}
static inline struct rt_rq *rt_rq_of_se(struct sched_rt_entity *rt_se)
{
return rt_se->rt_rq;
}
void free_rt_sched_group(struct task_group *tg)
{
int i;
if (tg->rt_se)
destroy_rt_bandwidth(&tg->rt_bandwidth);
for_each_possible_cpu(i) {
if (tg->rt_rq)
kfree(tg->rt_rq[i]);
if (tg->rt_se)
kfree(tg->rt_se[i]);
}
kfree(tg->rt_rq);
kfree(tg->rt_se);
}
void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
struct sched_rt_entity *rt_se, int cpu,
struct sched_rt_entity *parent)
{
struct rq *rq = cpu_rq(cpu);
rt_rq->highest_prio.curr = MAX_RT_PRIO;
rt_rq->rt_nr_boosted = 0;
rt_rq->rq = rq;
rt_rq->tg = tg;
tg->rt_rq[cpu] = rt_rq;
tg->rt_se[cpu] = rt_se;
if (!rt_se)
return;
if (!parent)
rt_se->rt_rq = &rq->rt;
else
rt_se->rt_rq = parent->my_q;
rt_se->my_q = rt_rq;
rt_se->parent = parent;
INIT_LIST_HEAD(&rt_se->run_list);
}
int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
{
struct rt_rq *rt_rq;
struct sched_rt_entity *rt_se;
int i;
tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
if (!tg->rt_rq)
goto err;
tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
if (!tg->rt_se)
goto err;
init_rt_bandwidth(&tg->rt_bandwidth,
ktime_to_ns(def_rt_bandwidth.rt_period), 0);
for_each_possible_cpu(i) {
rt_rq = kzalloc_node(sizeof(struct rt_rq),
GFP_KERNEL, cpu_to_node(i));
if (!rt_rq)
goto err;
rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
GFP_KERNEL, cpu_to_node(i));
if (!rt_se)
goto err_free_rq;
init_rt_rq(rt_rq, cpu_rq(i));
rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
}
return 1;
err_free_rq:
kfree(rt_rq);
err:
return 0;
}
#else /* CONFIG_RT_GROUP_SCHED */
#define rt_entity_is_task(rt_se) (1)
static inline struct task_struct *rt_task_of(struct sched_rt_entity *rt_se)
{
return container_of(rt_se, struct task_struct, rt);
}
static inline struct rq *rq_of_rt_rq(struct rt_rq *rt_rq)
{
return container_of(rt_rq, struct rq, rt);
}
static inline struct rt_rq *rt_rq_of_se(struct sched_rt_entity *rt_se)
{
struct task_struct *p = rt_task_of(rt_se);
struct rq *rq = task_rq(p);
return &rq->rt;
}
void free_rt_sched_group(struct task_group *tg) { }
int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
{
return 1;
}
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_SMP
static inline int rt_overloaded(struct rq *rq)
{
return atomic_read(&rq->rd->rto_count);
}
static inline void rt_set_overload(struct rq *rq)
{
if (!rq->online)
return;
cpumask_set_cpu(rq->cpu, rq->rd->rto_mask);
/*
* Make sure the mask is visible before we set
* the overload count. That is checked to determine
* if we should look at the mask. It would be a shame
* if we looked at the mask, but the mask was not
* updated yet.
*/
wmb();
atomic_inc(&rq->rd->rto_count);
}
static inline void rt_clear_overload(struct rq *rq)
{
if (!rq->online)
return;
/* the order here really doesn't matter */
atomic_dec(&rq->rd->rto_count);
cpumask_clear_cpu(rq->cpu, rq->rd->rto_mask);
}
static void update_rt_migration(struct rt_rq *rt_rq)
{
if (rt_rq->rt_nr_migratory && rt_rq->rt_nr_total > 1) {
if (!rt_rq->overloaded) {
rt_set_overload(rq_of_rt_rq(rt_rq));
rt_rq->overloaded = 1;
}
} else if (rt_rq->overloaded) {
rt_clear_overload(rq_of_rt_rq(rt_rq));
rt_rq->overloaded = 0;
}
}
static void inc_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
struct task_struct *p;
if (!rt_entity_is_task(rt_se))
return;
p = rt_task_of(rt_se);
rt_rq = &rq_of_rt_rq(rt_rq)->rt;
rt_rq->rt_nr_total++;
if (p->nr_cpus_allowed > 1)
rt_rq->rt_nr_migratory++;
update_rt_migration(rt_rq);
}
static void dec_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
struct task_struct *p;
if (!rt_entity_is_task(rt_se))
return;
p = rt_task_of(rt_se);
rt_rq = &rq_of_rt_rq(rt_rq)->rt;
rt_rq->rt_nr_total--;
if (p->nr_cpus_allowed > 1)
rt_rq->rt_nr_migratory--;
update_rt_migration(rt_rq);
}
static inline int has_pushable_tasks(struct rq *rq)
{
return !plist_head_empty(&rq->rt.pushable_tasks);
}
static void enqueue_pushable_task(struct rq *rq, struct task_struct *p)
{
plist_del(&p->pushable_tasks, &rq->rt.pushable_tasks);
plist_node_init(&p->pushable_tasks, p->prio);
plist_add(&p->pushable_tasks, &rq->rt.pushable_tasks);
/* Update the highest prio pushable task */
if (p->prio < rq->rt.highest_prio.next)
rq->rt.highest_prio.next = p->prio;
}
static void dequeue_pushable_task(struct rq *rq, struct task_struct *p)
{
plist_del(&p->pushable_tasks, &rq->rt.pushable_tasks);
/* Update the new highest prio pushable task */
if (has_pushable_tasks(rq)) {
p = plist_first_entry(&rq->rt.pushable_tasks,
struct task_struct, pushable_tasks);
rq->rt.highest_prio.next = p->prio;
} else
rq->rt.highest_prio.next = MAX_RT_PRIO;
}
#else
static inline void enqueue_pushable_task(struct rq *rq, struct task_struct *p)
{
}
static inline void dequeue_pushable_task(struct rq *rq, struct task_struct *p)
{
}
static inline
void inc_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
}
static inline
void dec_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
}
#endif /* CONFIG_SMP */
static inline int on_rt_rq(struct sched_rt_entity *rt_se)
{
return !list_empty(&rt_se->run_list);
}
#ifdef CONFIG_RT_GROUP_SCHED
static inline u64 sched_rt_runtime(struct rt_rq *rt_rq)
{
if (!rt_rq->tg)
return RUNTIME_INF;
return rt_rq->rt_runtime;
}
static inline u64 sched_rt_period(struct rt_rq *rt_rq)
{
return ktime_to_ns(rt_rq->tg->rt_bandwidth.rt_period);
}
typedef struct task_group *rt_rq_iter_t;
static inline struct task_group *next_task_group(struct task_group *tg)
{
do {
tg = list_entry_rcu(tg->list.next,
typeof(struct task_group), list);
} while (&tg->list != &task_groups && task_group_is_autogroup(tg));
if (&tg->list == &task_groups)
tg = NULL;
return tg;
}
#define for_each_rt_rq(rt_rq, iter, rq) \
for (iter = container_of(&task_groups, typeof(*iter), list); \
(iter = next_task_group(iter)) && \
(rt_rq = iter->rt_rq[cpu_of(rq)]);)
static inline void list_add_leaf_rt_rq(struct rt_rq *rt_rq)
{
list_add_rcu(&rt_rq->leaf_rt_rq_list,
&rq_of_rt_rq(rt_rq)->leaf_rt_rq_list);
}
static inline void list_del_leaf_rt_rq(struct rt_rq *rt_rq)
{
list_del_rcu(&rt_rq->leaf_rt_rq_list);
}
#define for_each_leaf_rt_rq(rt_rq, rq) \
list_for_each_entry_rcu(rt_rq, &rq->leaf_rt_rq_list, leaf_rt_rq_list)
#define for_each_sched_rt_entity(rt_se) \
for (; rt_se; rt_se = rt_se->parent)
static inline struct rt_rq *group_rt_rq(struct sched_rt_entity *rt_se)
{
return rt_se->my_q;
}
static void enqueue_rt_entity(struct sched_rt_entity *rt_se, bool head);
static void dequeue_rt_entity(struct sched_rt_entity *rt_se);
static void sched_rt_rq_enqueue(struct rt_rq *rt_rq)
{
struct task_struct *curr = rq_of_rt_rq(rt_rq)->curr;
struct sched_rt_entity *rt_se;
int cpu = cpu_of(rq_of_rt_rq(rt_rq));
rt_se = rt_rq->tg->rt_se[cpu];
if (rt_rq->rt_nr_running) {
if (rt_se && !on_rt_rq(rt_se))
enqueue_rt_entity(rt_se, false);
if (rt_rq->highest_prio.curr < curr->prio)
resched_task(curr);
}
}
static void sched_rt_rq_dequeue(struct rt_rq *rt_rq)
{
struct sched_rt_entity *rt_se;
int cpu = cpu_of(rq_of_rt_rq(rt_rq));
rt_se = rt_rq->tg->rt_se[cpu];
if (rt_se && on_rt_rq(rt_se))
dequeue_rt_entity(rt_se);
}
static inline int rt_rq_throttled(struct rt_rq *rt_rq)
{
return rt_rq->rt_throttled && !rt_rq->rt_nr_boosted;
}
static int rt_se_boosted(struct sched_rt_entity *rt_se)
{
struct rt_rq *rt_rq = group_rt_rq(rt_se);
struct task_struct *p;
if (rt_rq)
return !!rt_rq->rt_nr_boosted;
p = rt_task_of(rt_se);
return p->prio != p->normal_prio;
}
#ifdef CONFIG_SMP
static inline const struct cpumask *sched_rt_period_mask(void)
{
return cpu_rq(smp_processor_id())->rd->span;
}
#else
static inline const struct cpumask *sched_rt_period_mask(void)
{
return cpu_online_mask;
}
#endif
static inline
struct rt_rq *sched_rt_period_rt_rq(struct rt_bandwidth *rt_b, int cpu)
{
return container_of(rt_b, struct task_group, rt_bandwidth)->rt_rq[cpu];
}
static inline struct rt_bandwidth *sched_rt_bandwidth(struct rt_rq *rt_rq)
{
return &rt_rq->tg->rt_bandwidth;
}
#else /* !CONFIG_RT_GROUP_SCHED */
static inline u64 sched_rt_runtime(struct rt_rq *rt_rq)
{
return rt_rq->rt_runtime;
}
static inline u64 sched_rt_period(struct rt_rq *rt_rq)
{
return ktime_to_ns(def_rt_bandwidth.rt_period);
}
typedef struct rt_rq *rt_rq_iter_t;
#define for_each_rt_rq(rt_rq, iter, rq) \
for ((void) iter, rt_rq = &rq->rt; rt_rq; rt_rq = NULL)
static inline void list_add_leaf_rt_rq(struct rt_rq *rt_rq)
{
}
static inline void list_del_leaf_rt_rq(struct rt_rq *rt_rq)
{
}
#define for_each_leaf_rt_rq(rt_rq, rq) \
for (rt_rq = &rq->rt; rt_rq; rt_rq = NULL)
#define for_each_sched_rt_entity(rt_se) \
for (; rt_se; rt_se = NULL)
static inline struct rt_rq *group_rt_rq(struct sched_rt_entity *rt_se)
{
return NULL;
}
static inline void sched_rt_rq_enqueue(struct rt_rq *rt_rq)
{
if (rt_rq->rt_nr_running)
resched_task(rq_of_rt_rq(rt_rq)->curr);
}
static inline void sched_rt_rq_dequeue(struct rt_rq *rt_rq)
{
}
static inline int rt_rq_throttled(struct rt_rq *rt_rq)
{
return rt_rq->rt_throttled;
}
static inline const struct cpumask *sched_rt_period_mask(void)
{
return cpu_online_mask;
}
static inline
struct rt_rq *sched_rt_period_rt_rq(struct rt_bandwidth *rt_b, int cpu)
{
return &cpu_rq(cpu)->rt;
}
static inline struct rt_bandwidth *sched_rt_bandwidth(struct rt_rq *rt_rq)
{
return &def_rt_bandwidth;
}
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_SMP
/*
* We ran out of runtime, see if we can borrow some from our neighbours.
*/
static int do_balance_runtime(struct rt_rq *rt_rq)
{
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
struct root_domain *rd = rq_of_rt_rq(rt_rq)->rd;
int i, weight, more = 0;
u64 rt_period;
weight = cpumask_weight(rd->span);
raw_spin_lock(&rt_b->rt_runtime_lock);
rt_period = ktime_to_ns(rt_b->rt_period);
for_each_cpu(i, rd->span) {
struct rt_rq *iter = sched_rt_period_rt_rq(rt_b, i);
s64 diff;
if (iter == rt_rq)
continue;
raw_spin_lock(&iter->rt_runtime_lock);
/*
* Either all rqs have inf runtime and there's nothing to steal
* or __disable_runtime() below sets a specific rq to inf to
* indicate its been disabled and disalow stealing.
*/
if (iter->rt_runtime == RUNTIME_INF)
goto next;
/*
* From runqueues with spare time, take 1/n part of their
* spare time, but no more than our period.
*/
diff = iter->rt_runtime - iter->rt_time;
if (diff > 0) {
diff = div_u64((u64)diff, weight);
if (rt_rq->rt_runtime + diff > rt_period)
diff = rt_period - rt_rq->rt_runtime;
iter->rt_runtime -= diff;
rt_rq->rt_runtime += diff;
more = 1;
if (rt_rq->rt_runtime == rt_period) {
raw_spin_unlock(&iter->rt_runtime_lock);
break;
}
}
next:
raw_spin_unlock(&iter->rt_runtime_lock);
}
raw_spin_unlock(&rt_b->rt_runtime_lock);
return more;
}
/*
* Ensure this RQ takes back all the runtime it lend to its neighbours.
*/
static void __disable_runtime(struct rq *rq)
{
struct root_domain *rd = rq->rd;
rt_rq_iter_t iter;
struct rt_rq *rt_rq;
if (unlikely(!scheduler_running))
return;
for_each_rt_rq(rt_rq, iter, rq) {
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
s64 want;
int i;
raw_spin_lock(&rt_b->rt_runtime_lock);
raw_spin_lock(&rt_rq->rt_runtime_lock);
/*
* Either we're all inf and nobody needs to borrow, or we're
* already disabled and thus have nothing to do, or we have
* exactly the right amount of runtime to take out.
*/
if (rt_rq->rt_runtime == RUNTIME_INF ||
rt_rq->rt_runtime == rt_b->rt_runtime)
goto balanced;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
/*
* Calculate the difference between what we started out with
* and what we current have, that's the amount of runtime
* we lend and now have to reclaim.
*/
want = rt_b->rt_runtime - rt_rq->rt_runtime;
/*
* Greedy reclaim, take back as much as we can.
*/
for_each_cpu(i, rd->span) {
struct rt_rq *iter = sched_rt_period_rt_rq(rt_b, i);
s64 diff;
/*
* Can't reclaim from ourselves or disabled runqueues.
*/
if (iter == rt_rq || iter->rt_runtime == RUNTIME_INF)
continue;
raw_spin_lock(&iter->rt_runtime_lock);
if (want > 0) {
diff = min_t(s64, iter->rt_runtime, want);
iter->rt_runtime -= diff;
want -= diff;
} else {
iter->rt_runtime -= want;
want -= want;
}
raw_spin_unlock(&iter->rt_runtime_lock);
if (!want)
break;
}
raw_spin_lock(&rt_rq->rt_runtime_lock);
/*
* We cannot be left wanting - that would mean some runtime
* leaked out of the system.
*/
BUG_ON(want);
balanced:
/*
* Disable all the borrow logic by pretending we have inf
* runtime - in which case borrowing doesn't make sense.
*/
rt_rq->rt_runtime = RUNTIME_INF;
rt_rq->rt_throttled = 0;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
raw_spin_unlock(&rt_b->rt_runtime_lock);
}
}
static void __enable_runtime(struct rq *rq)
{
rt_rq_iter_t iter;
struct rt_rq *rt_rq;
if (unlikely(!scheduler_running))
return;
/*
* Reset each runqueue's bandwidth settings
*/
for_each_rt_rq(rt_rq, iter, rq) {
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
raw_spin_lock(&rt_b->rt_runtime_lock);
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_b->rt_runtime;
rt_rq->rt_time = 0;
rt_rq->rt_throttled = 0;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
raw_spin_unlock(&rt_b->rt_runtime_lock);
}
}
static int balance_runtime(struct rt_rq *rt_rq)
{
int more = 0;
if (!sched_feat(RT_RUNTIME_SHARE))
return more;
if (rt_rq->rt_time > rt_rq->rt_runtime) {
raw_spin_unlock(&rt_rq->rt_runtime_lock);
more = do_balance_runtime(rt_rq);
raw_spin_lock(&rt_rq->rt_runtime_lock);
}
return more;
}
#else /* !CONFIG_SMP */
static inline int balance_runtime(struct rt_rq *rt_rq)
{
return 0;
}
#endif /* CONFIG_SMP */
static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun)
{
int i, idle = 1, throttled = 0;
const struct cpumask *span;
span = sched_rt_period_mask();
#ifdef CONFIG_RT_GROUP_SCHED
/*
* FIXME: isolated CPUs should really leave the root task group,
* whether they are isolcpus or were isolated via cpusets, lest
* the timer run on a CPU which does not service all runqueues,
* potentially leaving other CPUs indefinitely throttled. If
* isolation is really required, the user will turn the throttle
* off to kill the perturbations it causes anyway. Meanwhile,
* this maintains functionality for boot and/or troubleshooting.
*/
if (rt_b == &root_task_group.rt_bandwidth)
span = cpu_online_mask;
#endif
for_each_cpu(i, span) {
int enqueue = 0;
struct rt_rq *rt_rq = sched_rt_period_rt_rq(rt_b, i);
struct rq *rq = rq_of_rt_rq(rt_rq);
raw_spin_lock(&rq->lock);
if (rt_rq->rt_time) {
u64 runtime;
raw_spin_lock(&rt_rq->rt_runtime_lock);
if (rt_rq->rt_throttled)
balance_runtime(rt_rq);
runtime = rt_rq->rt_runtime;
rt_rq->rt_time -= min(rt_rq->rt_time, overrun*runtime);
if (rt_rq->rt_throttled && rt_rq->rt_time < runtime) {
rt_rq->rt_throttled = 0;
enqueue = 1;
/*
* Force a clock update if the CPU was idle,
* lest wakeup -> unthrottle time accumulate.
*/
if (rt_rq->rt_nr_running && rq->curr == rq->idle)
rq->skip_clock_update = -1;
}
if (rt_rq->rt_time || rt_rq->rt_nr_running)
idle = 0;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
} else if (rt_rq->rt_nr_running) {
idle = 0;
if (!rt_rq_throttled(rt_rq))
enqueue = 1;
}
if (rt_rq->rt_throttled)
throttled = 1;
if (enqueue)
sched_rt_rq_enqueue(rt_rq);
raw_spin_unlock(&rq->lock);
}
if (!throttled && (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF))
return 1;
return idle;
}
static inline int rt_se_prio(struct sched_rt_entity *rt_se)
{
#ifdef CONFIG_RT_GROUP_SCHED
struct rt_rq *rt_rq = group_rt_rq(rt_se);
if (rt_rq)
return rt_rq->highest_prio.curr;
#endif
return rt_task_of(rt_se)->prio;
}
static void dump_throttled_rt_tasks(struct rt_rq *rt_rq)
{
struct rt_prio_array *array = &rt_rq->active;
struct sched_rt_entity *rt_se;
char buf[500];
char *pos = buf;
char *end = buf + sizeof(buf);
int idx;
pos += snprintf(pos, sizeof(buf),
"sched: RT throttling activated for rt_rq %p (cpu %d)\n",
rt_rq, cpu_of(rq_of_rt_rq(rt_rq)));
if (bitmap_empty(array->bitmap, MAX_RT_PRIO))
goto out;
pos += snprintf(pos, end - pos, "potential CPU hogs:\n");
idx = sched_find_first_bit(array->bitmap);
while (idx < MAX_RT_PRIO) {
list_for_each_entry(rt_se, array->queue + idx, run_list) {
struct task_struct *p;
if (!rt_entity_is_task(rt_se))
continue;
p = rt_task_of(rt_se);
if (pos < end)
pos += snprintf(pos, end - pos, "\t%s (%d)\n",
p->comm, p->pid);
}
idx = find_next_bit(array->bitmap, MAX_RT_PRIO, idx + 1);
}
out:
#ifdef CONFIG_PANIC_ON_RT_THROTTLING
/*
* Use pr_err() in the BUG() case since printk_sched() will
* not get flushed and deadlock is not a concern.
*/
pr_err("%s", buf);
BUG();
#else
printk_deferred("%s", buf);
#endif
}
static int sched_rt_runtime_exceeded(struct rt_rq *rt_rq)
{
u64 runtime = sched_rt_runtime(rt_rq);
if (rt_rq->rt_throttled)
return rt_rq_throttled(rt_rq);
if (runtime >= sched_rt_period(rt_rq))
return 0;
balance_runtime(rt_rq);
runtime = sched_rt_runtime(rt_rq);
if (runtime == RUNTIME_INF)
return 0;
if (rt_rq->rt_time > runtime) {
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
/*
* Don't actually throttle groups that have no runtime assigned
* but accrue some time due to boosting.
*/
if (likely(rt_b->rt_runtime)) {
static bool once = false;
rt_rq->rt_throttled = 1;
if (!once) {
once = true;
dump_throttled_rt_tasks(rt_rq);
}
} else {
/*
* In case we did anyway, make it go away,
* replenishment is a joke, since it will replenish us
* with exactly 0 ns.
*/
rt_rq->rt_time = 0;
}
if (rt_rq_throttled(rt_rq)) {
sched_rt_rq_dequeue(rt_rq);
return 1;
}
}
return 0;
}
/*
* Update the current task's runtime statistics. Skip current tasks that
* are not in our scheduling class.
*/
static void update_curr_rt(struct rq *rq)
{
struct task_struct *curr = rq->curr;
struct sched_rt_entity *rt_se = &curr->rt;
struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
u64 delta_exec;
if (curr->sched_class != &rt_sched_class)
return;
delta_exec = rq->clock_task - curr->se.exec_start;
if (unlikely((s64)delta_exec <= 0))
return;
schedstat_set(curr->se.statistics.exec_max,
max(curr->se.statistics.exec_max, delta_exec));
curr->se.sum_exec_runtime += delta_exec;
account_group_exec_runtime(curr, delta_exec);
curr->se.exec_start = rq->clock_task;
cpuacct_charge(curr, delta_exec);
sched_rt_avg_update(rq, delta_exec);
if (!rt_bandwidth_enabled())
return;
for_each_sched_rt_entity(rt_se) {
rt_rq = rt_rq_of_se(rt_se);
if (sched_rt_runtime(rt_rq) != RUNTIME_INF) {
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_time += delta_exec;
if (sched_rt_runtime_exceeded(rt_rq))
resched_task(curr);
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
}
}
#if defined CONFIG_SMP
static void
inc_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Change rq's cpupri only if rt_rq is the top queue.
*/
if (&rq->rt != rt_rq)
return;
#endif
if (rq->online && prio < prev_prio)
cpupri_set(&rq->rd->cpupri, rq->cpu, prio);
}
static void
dec_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Change rq's cpupri only if rt_rq is the top queue.
*/
if (&rq->rt != rt_rq)
return;
#endif
if (rq->online && rt_rq->highest_prio.curr != prev_prio)
cpupri_set(&rq->rd->cpupri, rq->cpu, rt_rq->highest_prio.curr);
}
#else /* CONFIG_SMP */
static inline
void inc_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio) {}
static inline
void dec_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio) {}
#endif /* CONFIG_SMP */
#if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
static void
inc_rt_prio(struct rt_rq *rt_rq, int prio)
{
int prev_prio = rt_rq->highest_prio.curr;
if (prio < prev_prio)
rt_rq->highest_prio.curr = prio;
inc_rt_prio_smp(rt_rq, prio, prev_prio);
}
static void
dec_rt_prio(struct rt_rq *rt_rq, int prio)
{
int prev_prio = rt_rq->highest_prio.curr;
if (rt_rq->rt_nr_running) {
WARN_ON(prio < prev_prio);
/*
* This may have been our highest task, and therefore
* we may have some recomputation to do
*/
if (prio == prev_prio) {
struct rt_prio_array *array = &rt_rq->active;
rt_rq->highest_prio.curr =
sched_find_first_bit(array->bitmap);
}
} else
rt_rq->highest_prio.curr = MAX_RT_PRIO;
dec_rt_prio_smp(rt_rq, prio, prev_prio);
}
#else
static inline void inc_rt_prio(struct rt_rq *rt_rq, int prio) {}
static inline void dec_rt_prio(struct rt_rq *rt_rq, int prio) {}
#endif /* CONFIG_SMP || CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_RT_GROUP_SCHED
static void
inc_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
if (rt_se_boosted(rt_se))
rt_rq->rt_nr_boosted++;
if (rt_rq->tg)
start_rt_bandwidth(&rt_rq->tg->rt_bandwidth);
}
static void
dec_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
if (rt_se_boosted(rt_se))
rt_rq->rt_nr_boosted--;
WARN_ON(!rt_rq->rt_nr_running && rt_rq->rt_nr_boosted);
}
#else /* CONFIG_RT_GROUP_SCHED */
static void
inc_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
start_rt_bandwidth(&def_rt_bandwidth);
}
static inline
void dec_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq) {}
#endif /* CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_SCHED_HMP
static void
inc_hmp_sched_stats_rt(struct rq *rq, struct task_struct *p)
{
inc_cumulative_runnable_avg(&rq->hmp_stats, p);
}
static void
dec_hmp_sched_stats_rt(struct rq *rq, struct task_struct *p)
{
dec_cumulative_runnable_avg(&rq->hmp_stats, p);
}
#else /* CONFIG_SCHED_HMP */
static inline void
inc_hmp_sched_stats_rt(struct rq *rq, struct task_struct *p) { }
static inline void
dec_hmp_sched_stats_rt(struct rq *rq, struct task_struct *p) { }
#endif /* CONFIG_SCHED_HMP */
static inline
void inc_rt_tasks(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
int prio = rt_se_prio(rt_se);
WARN_ON(!rt_prio(prio));
rt_rq->rt_nr_running++;
inc_rt_prio(rt_rq, prio);
inc_rt_migration(rt_se, rt_rq);
inc_rt_group(rt_se, rt_rq);
}
static inline
void dec_rt_tasks(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
WARN_ON(!rt_prio(rt_se_prio(rt_se)));
WARN_ON(!rt_rq->rt_nr_running);
rt_rq->rt_nr_running--;
dec_rt_prio(rt_rq, rt_se_prio(rt_se));
dec_rt_migration(rt_se, rt_rq);
dec_rt_group(rt_se, rt_rq);
}
static void __enqueue_rt_entity(struct sched_rt_entity *rt_se, bool head)
{
struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
struct rt_prio_array *array = &rt_rq->active;
struct rt_rq *group_rq = group_rt_rq(rt_se);
struct list_head *queue = array->queue + rt_se_prio(rt_se);
/*
* Don't enqueue the group if its throttled, or when empty.
* The latter is a consequence of the former when a child group
* get throttled and the current group doesn't have any other
* active members.
*/
if (group_rq && (rt_rq_throttled(group_rq) || !group_rq->rt_nr_running))
return;
if (!rt_rq->rt_nr_running)
list_add_leaf_rt_rq(rt_rq);
if (head)
list_add(&rt_se->run_list, queue);
else
list_add_tail(&rt_se->run_list, queue);
__set_bit(rt_se_prio(rt_se), array->bitmap);
inc_rt_tasks(rt_se, rt_rq);
}
static void __dequeue_rt_entity(struct sched_rt_entity *rt_se)
{
struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
struct rt_prio_array *array = &rt_rq->active;
list_del_init(&rt_se->run_list);
if (list_empty(array->queue + rt_se_prio(rt_se)))
__clear_bit(rt_se_prio(rt_se), array->bitmap);
dec_rt_tasks(rt_se, rt_rq);
if (!rt_rq->rt_nr_running)
list_del_leaf_rt_rq(rt_rq);
}
/*
* Because the prio of an upper entry depends on the lower
* entries, we must remove entries top - down.
*/
static void dequeue_rt_stack(struct sched_rt_entity *rt_se)
{
struct sched_rt_entity *back = NULL;
for_each_sched_rt_entity(rt_se) {
rt_se->back = back;
back = rt_se;
}
for (rt_se = back; rt_se; rt_se = rt_se->back) {
if (on_rt_rq(rt_se))
__dequeue_rt_entity(rt_se);
}
}
static void enqueue_rt_entity(struct sched_rt_entity *rt_se, bool head)
{
dequeue_rt_stack(rt_se);
for_each_sched_rt_entity(rt_se)
__enqueue_rt_entity(rt_se, head);
}
static void dequeue_rt_entity(struct sched_rt_entity *rt_se)
{
dequeue_rt_stack(rt_se);
for_each_sched_rt_entity(rt_se) {
struct rt_rq *rt_rq = group_rt_rq(rt_se);
if (rt_rq && rt_rq->rt_nr_running)
__enqueue_rt_entity(rt_se, false);
}
}
/*
* Adding/removing a task to/from a priority array:
*/
static void
enqueue_task_rt(struct rq *rq, struct task_struct *p, int flags)
{
struct sched_rt_entity *rt_se = &p->rt;
if (flags & ENQUEUE_WAKEUP)
rt_se->timeout = 0;
enqueue_rt_entity(rt_se, flags & ENQUEUE_HEAD);
if (!task_current(rq, p) && p->nr_cpus_allowed > 1)
enqueue_pushable_task(rq, p);
inc_nr_running(rq);
inc_hmp_sched_stats_rt(rq, p);
}
static void dequeue_task_rt(struct rq *rq, struct task_struct *p, int flags)
{
struct sched_rt_entity *rt_se = &p->rt;
update_curr_rt(rq);
dequeue_rt_entity(rt_se);
dequeue_pushable_task(rq, p);
dec_nr_running(rq);
dec_hmp_sched_stats_rt(rq, p);
}
/*
* Put task to the head or the end of the run list without the overhead of
* dequeue followed by enqueue.
*/
static void
requeue_rt_entity(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se, int head)
{
if (on_rt_rq(rt_se)) {
struct rt_prio_array *array = &rt_rq->active;
struct list_head *queue = array->queue + rt_se_prio(rt_se);
if (head)
list_move(&rt_se->run_list, queue);
else
list_move_tail(&rt_se->run_list, queue);
}
}
static void requeue_task_rt(struct rq *rq, struct task_struct *p, int head)
{
struct sched_rt_entity *rt_se = &p->rt;
struct rt_rq *rt_rq;
for_each_sched_rt_entity(rt_se) {
rt_rq = rt_rq_of_se(rt_se);
requeue_rt_entity(rt_rq, rt_se, head);
}
}
static void yield_task_rt(struct rq *rq)
{
requeue_task_rt(rq, rq->curr, 0);
}
#ifdef CONFIG_SMP
static int find_lowest_rq(struct task_struct *task);
static int
select_task_rq_rt_hmp(struct task_struct *p, int sd_flag, int flags)
{
int cpu, target;
cpu = task_cpu(p);
rcu_read_lock();
target = find_lowest_rq(p);
if (target != -1)
cpu = target;
rcu_read_unlock();
return cpu;
}
static int
select_task_rq_rt(struct task_struct *p, int sd_flag, int flags)
{
struct task_struct *curr;
struct rq *rq;
int cpu;
cpu = task_cpu(p);
if (p->nr_cpus_allowed == 1)
goto out;
if (sched_enable_hmp)
return select_task_rq_rt_hmp(p, sd_flag, flags);
/* For anything but wake ups, just return the task_cpu */
if (sd_flag != SD_BALANCE_WAKE && sd_flag != SD_BALANCE_FORK)
goto out;
rq = cpu_rq(cpu);
rcu_read_lock();
curr = ACCESS_ONCE(rq->curr); /* unlocked access */
/*
* If the current task on @p's runqueue is an RT task, then
* try to see if we can wake this RT task up on another
* runqueue. Otherwise simply start this RT task
* on its current runqueue.
*
* We want to avoid overloading runqueues. If the woken
* task is a higher priority, then it will stay on this CPU
* and the lower prio task should be moved to another CPU.
* Even though this will probably make the lower prio task
* lose its cache, we do not want to bounce a higher task
* around just because it gave up its CPU, perhaps for a
* lock?
*
* For equal prio tasks, we just let the scheduler sort it out.
*
* Otherwise, just let it ride on the affined RQ and the
* post-schedule router will push the preempted task away
*
* This test is optimistic, if we get it wrong the load-balancer
* will have to sort it out.
*/
if (curr && unlikely(rt_task(curr)) &&
(curr->nr_cpus_allowed < 2 ||
curr->prio <= p->prio) &&
(p->nr_cpus_allowed > 1)) {
int target = find_lowest_rq(p);
if (target != -1)
cpu = target;
}
rcu_read_unlock();
out:
return cpu;
}
static void check_preempt_equal_prio(struct rq *rq, struct task_struct *p)
{
if (rq->curr->nr_cpus_allowed == 1)
return;
if (p->nr_cpus_allowed != 1
&& cpupri_find(&rq->rd->cpupri, p, NULL))
return;
if (!cpupri_find(&rq->rd->cpupri, rq->curr, NULL))
return;
/*
* There appears to be other cpus that can accept
* current and none to run 'p', so lets reschedule
* to try and push current away:
*/
requeue_task_rt(rq, p, 1);
resched_task(rq->curr);
}
#endif /* CONFIG_SMP */
/*
* Preempt the current task with a newly woken task if needed:
*/
static void check_preempt_curr_rt(struct rq *rq, struct task_struct *p, int flags)
{
if (p->prio < rq->curr->prio) {
resched_task(rq->curr);
return;
}
#ifdef CONFIG_SMP
/*
* If:
*
* - the newly woken task is of equal priority to the current task
* - the newly woken task is non-migratable while current is migratable
* - current will be preempted on the next reschedule
*
* we should check to see if current can readily move to a different
* cpu. If so, we will reschedule to allow the push logic to try
* to move current somewhere else, making room for our non-migratable
* task.
*/
if (p->prio == rq->curr->prio && !test_tsk_need_resched(rq->curr))
check_preempt_equal_prio(rq, p);
#endif
}
static struct sched_rt_entity *pick_next_rt_entity(struct rq *rq,
struct rt_rq *rt_rq)
{
struct rt_prio_array *array = &rt_rq->active;
struct sched_rt_entity *next = NULL;
struct list_head *queue;
int idx;
idx = sched_find_first_bit(array->bitmap);
BUG_ON(idx >= MAX_RT_PRIO);
queue = array->queue + idx;
next = list_entry(queue->next, struct sched_rt_entity, run_list);
return next;
}
static struct task_struct *_pick_next_task_rt(struct rq *rq)
{
struct sched_rt_entity *rt_se;
struct task_struct *p;
struct rt_rq *rt_rq;
rt_rq = &rq->rt;
if (!rt_rq->rt_nr_running)
return NULL;
if (rt_rq_throttled(rt_rq))
return NULL;
do {
rt_se = pick_next_rt_entity(rq, rt_rq);
BUG_ON(!rt_se);
rt_rq = group_rt_rq(rt_se);
} while (rt_rq);
/*
* Force update of rq->clock_task in case we failed to do so in
* put_prev_task. A stale value can cause us to over-charge execution
* time to real-time task, that could trigger throttling unnecessarily
*/
if (rq->skip_clock_update > 0)
rq->skip_clock_update = 0;
update_rq_clock(rq);
p = rt_task_of(rt_se);
p->se.exec_start = rq->clock_task;
return p;
}
static struct task_struct *pick_next_task_rt(struct rq *rq)
{
struct task_struct *p = _pick_next_task_rt(rq);
/* The running task is never eligible for pushing */
if (p)
dequeue_pushable_task(rq, p);
#ifdef CONFIG_SMP
/*
* We detect this state here so that we can avoid taking the RQ
* lock again later if there is no need to push
*/
rq->post_schedule = has_pushable_tasks(rq);
#endif
return p;
}
static void put_prev_task_rt(struct rq *rq, struct task_struct *p)
{
update_curr_rt(rq);
/*
* The previous task needs to be made eligible for pushing
* if it is still active
*/
if (on_rt_rq(&p->rt) && p->nr_cpus_allowed > 1)
enqueue_pushable_task(rq, p);
}
#ifdef CONFIG_SMP
/* Only try algorithms three times */
#define RT_MAX_TRIES 3
static int pick_rt_task(struct rq *rq, struct task_struct *p, int cpu)
{
if (!task_running(rq, p) &&
cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
return 1;
return 0;
}
/* Return the second highest RT task, NULL otherwise */
static struct task_struct *pick_next_highest_task_rt(struct rq *rq, int cpu)
{
struct task_struct *next = NULL;
struct sched_rt_entity *rt_se;
struct rt_prio_array *array;
struct rt_rq *rt_rq;
int idx;
for_each_leaf_rt_rq(rt_rq, rq) {
array = &rt_rq->active;
idx = sched_find_first_bit(array->bitmap);
next_idx:
if (idx >= MAX_RT_PRIO)
continue;
if (next && next->prio <= idx)
continue;
list_for_each_entry(rt_se, array->queue + idx, run_list) {
struct task_struct *p;
if (!rt_entity_is_task(rt_se))
continue;
p = rt_task_of(rt_se);
if (pick_rt_task(rq, p, cpu)) {
next = p;
break;
}
}
if (!next) {
idx = find_next_bit(array->bitmap, MAX_RT_PRIO, idx+1);
goto next_idx;
}
}
return next;
}
static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask);
#ifdef CONFIG_SCHED_HMP
static int find_lowest_rq_hmp(struct task_struct *task)
{
struct cpumask *lowest_mask = __get_cpu_var(local_cpu_mask);
int cpu_cost, min_cost = INT_MAX;
int best_cpu = -1;
int i;
/* Make sure the mask is initialized first */
if (unlikely(!lowest_mask))
return best_cpu;
if (task->nr_cpus_allowed == 1)
return best_cpu; /* No other targets possible */
if (!cpupri_find(&task_rq(task)->rd->cpupri, task, lowest_mask))
return best_cpu; /* No targets found */
/*
* At this point we have built a mask of cpus representing the
* lowest priority tasks in the system. Now we want to elect
* the best one based on our affinity and topology.
*/
/* Skip performance considerations and optimize for power.
* Worst case we'll be iterating over all CPUs here. CPU
* online mask should be taken care of when constructing
* the lowest_mask.
*/
for_each_cpu(i, lowest_mask) {
struct rq *rq = cpu_rq(i);
cpu_cost = power_cost_at_freq(i, ACCESS_ONCE(rq->min_freq));
trace_sched_cpu_load(rq, idle_cpu(i), mostly_idle_cpu(i),
sched_irqload(i), cpu_cost, cpu_temp(i));
if (sched_boost() && capacity(rq) != max_capacity)
continue;
if (cpu_cost < min_cost && !sched_cpu_high_irqload(i)) {
min_cost = cpu_cost;
best_cpu = i;
}
}
return best_cpu;
}
#else /* CONFIG_SCHED_HMP */
static int find_lowest_rq_hmp(struct task_struct *task)
{
return -1;
}
#endif /* CONFIG_SCHED_HMP */
static int find_lowest_rq(struct task_struct *task)
{
struct sched_domain *sd;
struct cpumask *lowest_mask = __get_cpu_var(local_cpu_mask);
int this_cpu = smp_processor_id();
int cpu = task_cpu(task);
if (sched_enable_hmp)
return find_lowest_rq_hmp(task);
/* Make sure the mask is initialized first */
if (unlikely(!lowest_mask))
return -1;
if (task->nr_cpus_allowed == 1)
return -1; /* No other targets possible */
if (!cpupri_find(&task_rq(task)->rd->cpupri, task, lowest_mask))
return -1; /* No targets found */
/*
* At this point we have built a mask of cpus representing the
* lowest priority tasks in the system. Now we want to elect
* the best one based on our affinity and topology.
*
* We prioritize the last cpu that the task executed on since
* it is most likely cache-hot in that location.
*/
if (cpumask_test_cpu(cpu, lowest_mask))
return cpu;
/*
* Otherwise, we consult the sched_domains span maps to figure
* out which cpu is logically closest to our hot cache data.
*/
if (!cpumask_test_cpu(this_cpu, lowest_mask))
this_cpu = -1; /* Skip this_cpu opt if not among lowest */
rcu_read_lock();
for_each_domain(cpu, sd) {
if (sd->flags & SD_WAKE_AFFINE) {
int best_cpu;
/*
* "this_cpu" is cheaper to preempt than a
* remote processor.
*/
if (this_cpu != -1 &&
cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
rcu_read_unlock();
return this_cpu;
}
best_cpu = cpumask_first_and(lowest_mask,
sched_domain_span(sd));
if (best_cpu < nr_cpu_ids) {
rcu_read_unlock();
return best_cpu;
}
}
}
rcu_read_unlock();
/*
* And finally, if there were no matches within the domains
* just give the caller *something* to work with from the compatible
* locations.
*/
if (this_cpu != -1)
return this_cpu;
cpu = cpumask_any(lowest_mask);
if (cpu < nr_cpu_ids)
return cpu;
return -1;
}
/* Will lock the rq it finds */
static struct rq *find_lock_lowest_rq(struct task_struct *task, struct rq *rq)
{
struct rq *lowest_rq = NULL;
int tries;
int cpu;
for (tries = 0; tries < RT_MAX_TRIES; tries++) {
cpu = find_lowest_rq(task);
if ((cpu == -1) || (cpu == rq->cpu))
break;
lowest_rq = cpu_rq(cpu);
/* if the prio of this runqueue changed, try again */
if (double_lock_balance(rq, lowest_rq)) {
/*
* We had to unlock the run queue. In
* the mean time, task could have
* migrated already or had its affinity changed.
* Also make sure that it wasn't scheduled on its rq.
*/
if (unlikely(task_rq(task) != rq ||
!cpumask_test_cpu(lowest_rq->cpu,
tsk_cpus_allowed(task)) ||
task_running(rq, task) ||
!task->on_rq)) {
double_unlock_balance(rq, lowest_rq);
lowest_rq = NULL;
break;
}
}
/* If this rq is still suitable use it. */
if (lowest_rq->rt.highest_prio.curr > task->prio)
break;
/* try again */
double_unlock_balance(rq, lowest_rq);
lowest_rq = NULL;
}
return lowest_rq;
}
static struct task_struct *pick_next_pushable_task(struct rq *rq)
{
struct task_struct *p;
if (!has_pushable_tasks(rq))
return NULL;
p = plist_first_entry(&rq->rt.pushable_tasks,
struct task_struct, pushable_tasks);
BUG_ON(rq->cpu != task_cpu(p));
BUG_ON(task_current(rq, p));
BUG_ON(p->nr_cpus_allowed <= 1);
BUG_ON(!p->on_rq);
BUG_ON(!rt_task(p));
return p;
}
/*
* If the current CPU has more than one RT task, see if the non
* running task can migrate over to a CPU that is running a task
* of lesser priority.
*/
static int push_rt_task(struct rq *rq)
{
struct task_struct *next_task;
struct rq *lowest_rq;
int ret = 0;
if (!rq->rt.overloaded)
return 0;
next_task = pick_next_pushable_task(rq);
if (!next_task)
return 0;
retry:
if (unlikely(next_task == rq->curr)) {
WARN_ON(1);
return 0;
}
/*
* It's possible that the next_task slipped in of
* higher priority than current. If that's the case
* just reschedule current.
*/
if (unlikely(next_task->prio < rq->curr->prio)) {
resched_task(rq->curr);
return 0;
}
/* We might release rq lock */
get_task_struct(next_task);
/* find_lock_lowest_rq locks the rq if found */
lowest_rq = find_lock_lowest_rq(next_task, rq);
if (!lowest_rq) {
struct task_struct *task;
/*
* find_lock_lowest_rq releases rq->lock
* so it is possible that next_task has migrated.
*
* We need to make sure that the task is still on the same
* run-queue and is also still the next task eligible for
* pushing.
*/
task = pick_next_pushable_task(rq);
if (task_cpu(next_task) == rq->cpu && task == next_task) {
/*
* The task hasn't migrated, and is still the next
* eligible task, but we failed to find a run-queue
* to push it to. Do not retry in this case, since
* other cpus will pull from us when ready.
*/
goto out;
}
if (!task)
/* No more tasks, just exit */
goto out;
/*
* Something has shifted, try again.
*/
put_task_struct(next_task);
next_task = task;
goto retry;
}
deactivate_task(rq, next_task, 0);
set_task_cpu(next_task, lowest_rq->cpu);
activate_task(lowest_rq, next_task, 0);
ret = 1;
resched_task(lowest_rq->curr);
double_unlock_balance(rq, lowest_rq);
out:
put_task_struct(next_task);
return ret;
}
static void push_rt_tasks(struct rq *rq)
{
/* push_rt_task will return true if it moved an RT */
while (push_rt_task(rq))
;
}
static int pull_rt_task(struct rq *this_rq)
{
int this_cpu = this_rq->cpu, ret = 0, cpu;
struct task_struct *p;
struct rq *src_rq;
if (likely(!rt_overloaded(this_rq)))
return 0;
for_each_cpu(cpu, this_rq->rd->rto_mask) {
if (this_cpu == cpu)
continue;
src_rq = cpu_rq(cpu);
/*
* Don't bother taking the src_rq->lock if the next highest
* task is known to be lower-priority than our current task.
* This may look racy, but if this value is about to go
* logically higher, the src_rq will push this task away.
* And if its going logically lower, we do not care
*/
if (src_rq->rt.highest_prio.next >=
this_rq->rt.highest_prio.curr)
continue;
/*
* We can potentially drop this_rq's lock in
* double_lock_balance, and another CPU could
* alter this_rq
*/
double_lock_balance(this_rq, src_rq);
/*
* Are there still pullable RT tasks?
*/
if (src_rq->rt.rt_nr_running <= 1)
goto skip;
p = pick_next_highest_task_rt(src_rq, this_cpu);
/*
* Do we have an RT task that preempts
* the to-be-scheduled task?
*/
if (p && (p->prio < this_rq->rt.highest_prio.curr)) {
WARN_ON(p == src_rq->curr);
WARN_ON(!p->on_rq);
/*
* There's a chance that p is higher in priority
* than what's currently running on its cpu.
* This is just that p is wakeing up and hasn't
* had a chance to schedule. We only pull
* p if it is lower in priority than the
* current task on the run queue
*/
if (p->prio < src_rq->curr->prio)
goto skip;
ret = 1;
deactivate_task(src_rq, p, 0);
set_task_cpu(p, this_cpu);
activate_task(this_rq, p, 0);
/*
* We continue with the search, just in
* case there's an even higher prio task
* in another runqueue. (low likelihood
* but possible)
*/
}
skip:
double_unlock_balance(this_rq, src_rq);
}
return ret;
}
static void pre_schedule_rt(struct rq *rq, struct task_struct *prev)
{
/* Try to pull RT tasks here if we lower this rq's prio */
if (rq->rt.highest_prio.curr > prev->prio)
pull_rt_task(rq);
}
static void post_schedule_rt(struct rq *rq)
{
push_rt_tasks(rq);
}
/*
* If we are not running and we are not going to reschedule soon, we should
* try to push tasks away now
*/
static void task_woken_rt(struct rq *rq, struct task_struct *p)
{
if (!task_running(rq, p) &&
!test_tsk_need_resched(rq->curr) &&
has_pushable_tasks(rq) &&
p->nr_cpus_allowed > 1 &&
rt_task(rq->curr) &&
(rq->curr->nr_cpus_allowed < 2 ||
rq->curr->prio <= p->prio))
push_rt_tasks(rq);
}
static void set_cpus_allowed_rt(struct task_struct *p,
const struct cpumask *new_mask)
{
struct rq *rq;
int weight;
BUG_ON(!rt_task(p));
if (!p->on_rq)
return;
weight = cpumask_weight(new_mask);
/*
* Only update if the process changes its state from whether it
* can migrate or not.
*/
if ((p->nr_cpus_allowed > 1) == (weight > 1))
return;
rq = task_rq(p);
/*
* The process used to be able to migrate OR it can now migrate
*/
if (weight <= 1) {
if (!task_current(rq, p))
dequeue_pushable_task(rq, p);
BUG_ON(!rq->rt.rt_nr_migratory);
rq->rt.rt_nr_migratory--;
} else {
if (!task_current(rq, p))
enqueue_pushable_task(rq, p);
rq->rt.rt_nr_migratory++;
}
update_rt_migration(&rq->rt);
}
/* Assumes rq->lock is held */
static void rq_online_rt(struct rq *rq)
{
if (rq->rt.overloaded)
rt_set_overload(rq);
__enable_runtime(rq);
cpupri_set(&rq->rd->cpupri, rq->cpu, rq->rt.highest_prio.curr);
}
/* Assumes rq->lock is held */
static void rq_offline_rt(struct rq *rq)
{
if (rq->rt.overloaded)
rt_clear_overload(rq);
__disable_runtime(rq);
cpupri_set(&rq->rd->cpupri, rq->cpu, CPUPRI_INVALID);
}
/*
* When switch from the rt queue, we bring ourselves to a position
* that we might want to pull RT tasks from other runqueues.
*/
static void switched_from_rt(struct rq *rq, struct task_struct *p)
{
/*
* If there are other RT tasks then we will reschedule
* and the scheduling of the other RT tasks will handle
* the balancing. But if we are the last RT task
* we may need to handle the pulling of RT tasks
* now.
*/
if (!p->on_rq || rq->rt.rt_nr_running)
return;
if (pull_rt_task(rq))
resched_task(rq->curr);
}
void init_sched_rt_class(void)
{
unsigned int i;
for_each_possible_cpu(i) {
zalloc_cpumask_var_node(&per_cpu(local_cpu_mask, i),
GFP_KERNEL, cpu_to_node(i));
}
}
#endif /* CONFIG_SMP */
/*
* When switching a task to RT, we may overload the runqueue
* with RT tasks. In this case we try to push them off to
* other runqueues.
*/
static void switched_to_rt(struct rq *rq, struct task_struct *p)
{
int check_resched = 1;
/*
* If we are already running, then there's nothing
* that needs to be done. But if we are not running
* we may need to preempt the current running task.
* If that current running task is also an RT task
* then see if we can move to another run queue.
*/
if (p->on_rq && rq->curr != p) {
#ifdef CONFIG_SMP
if (rq->rt.overloaded && push_rt_task(rq) &&
/* Don't resched if we changed runqueues */
rq != task_rq(p))
check_resched = 0;
#endif /* CONFIG_SMP */
if (check_resched && p->prio < rq->curr->prio)
resched_task(rq->curr);
}
}
/*
* Priority of the task has changed. This may cause
* us to initiate a push or pull.
*/
static void
prio_changed_rt(struct rq *rq, struct task_struct *p, int oldprio)
{
if (!p->on_rq)
return;
if (rq->curr == p) {
#ifdef CONFIG_SMP
/*
* If our priority decreases while running, we
* may need to pull tasks to this runqueue.
*/
if (oldprio < p->prio)
pull_rt_task(rq);
/*
* If there's a higher priority task waiting to run
* then reschedule. Note, the above pull_rt_task
* can release the rq lock and p could migrate.
* Only reschedule if p is still on the same runqueue.
*/
if (p->prio > rq->rt.highest_prio.curr && rq->curr == p)
resched_task(p);
#else
/* For UP simply resched on drop of prio */
if (oldprio < p->prio)
resched_task(p);
#endif /* CONFIG_SMP */
} else {
/*
* This task is not running, but if it is
* greater than the current running task
* then reschedule.
*/
if (p->prio < rq->curr->prio)
resched_task(rq->curr);
}
}
static void watchdog(struct rq *rq, struct task_struct *p)
{
unsigned long soft, hard;
/* max may change after cur was read, this will be fixed next tick */
soft = task_rlimit(p, RLIMIT_RTTIME);
hard = task_rlimit_max(p, RLIMIT_RTTIME);
if (soft != RLIM_INFINITY) {
unsigned long next;
if (p->rt.watchdog_stamp != jiffies) {
p->rt.timeout++;
p->rt.watchdog_stamp = jiffies;
}
next = DIV_ROUND_UP(min(soft, hard), USEC_PER_SEC/HZ);
if (p->rt.timeout > next)
p->cputime_expires.sched_exp = p->se.sum_exec_runtime;
}
}
static void task_tick_rt(struct rq *rq, struct task_struct *p, int queued)
{
struct sched_rt_entity *rt_se = &p->rt;
update_curr_rt(rq);
watchdog(rq, p);
/*
* RR tasks need a special form of timeslice management.
* FIFO tasks have no timeslices.
*/
if (p->policy != SCHED_RR)
return;
if (--p->rt.time_slice)
return;
p->rt.time_slice = sched_rr_timeslice;
/*
* Requeue to the end of queue if we (and all of our ancestors) are the
* only element on the queue
*/
for_each_sched_rt_entity(rt_se) {
if (rt_se->run_list.prev != rt_se->run_list.next) {
requeue_task_rt(rq, p, 0);
set_tsk_need_resched(p);
return;
}
}
}
static void set_curr_task_rt(struct rq *rq)
{
struct task_struct *p = rq->curr;
p->se.exec_start = rq->clock_task;
/* The running task is never eligible for pushing */
dequeue_pushable_task(rq, p);
}
static unsigned int get_rr_interval_rt(struct rq *rq, struct task_struct *task)
{
/*
* Time slice is 0 for SCHED_FIFO tasks
*/
if (task->policy == SCHED_RR)
return sched_rr_timeslice;
else
return 0;
}
const struct sched_class rt_sched_class = {
.next = &fair_sched_class,
.enqueue_task = enqueue_task_rt,
.dequeue_task = dequeue_task_rt,
.yield_task = yield_task_rt,
.check_preempt_curr = check_preempt_curr_rt,
.pick_next_task = pick_next_task_rt,
.put_prev_task = put_prev_task_rt,
#ifdef CONFIG_SMP
.select_task_rq = select_task_rq_rt,
.set_cpus_allowed = set_cpus_allowed_rt,
.rq_online = rq_online_rt,
.rq_offline = rq_offline_rt,
.pre_schedule = pre_schedule_rt,
.post_schedule = post_schedule_rt,
.task_woken = task_woken_rt,
.switched_from = switched_from_rt,
#endif
.set_curr_task = set_curr_task_rt,
.task_tick = task_tick_rt,
.get_rr_interval = get_rr_interval_rt,
.prio_changed = prio_changed_rt,
.switched_to = switched_to_rt,
#ifdef CONFIG_SCHED_HMP
.inc_hmp_sched_stats = inc_hmp_sched_stats_rt,
.dec_hmp_sched_stats = dec_hmp_sched_stats_rt,
#endif
};
#ifdef CONFIG_SCHED_DEBUG
extern void print_rt_rq(struct seq_file *m, int cpu, struct rt_rq *rt_rq);
void print_rt_stats(struct seq_file *m, int cpu)
{
rt_rq_iter_t iter;
struct rt_rq *rt_rq;
rcu_read_lock();
for_each_rt_rq(rt_rq, iter, cpu_rq(cpu))
print_rt_rq(m, cpu, rt_rq);
rcu_read_unlock();
}
#endif /* CONFIG_SCHED_DEBUG */
| BlissRoms-Kernels/kernel_motorola_BlissPure | kernel/sched/rt.c | C | gpl-2.0 | 51,646 |
<?php
/**
* @file
* @ingroup SMWSpecialPage
* @ingroup SpecialPage
*
* A factbox like view on an article, implemented by a special page.
*
* @author Denny Vrandecic
*/
/**
* A factbox view on one specific article, showing all the Semantic data about it
*
* @ingroup SMWSpecialPage
* @ingroup SpecialPage
*/
class SMWSpecialBrowse extends SpecialPage {
/// int How many incoming values should be asked for
static public $incomingvaluescount = 8;
/// int How many incoming properties should be asked for
static public $incomingpropertiescount = 21;
/// SMWDataValue Topic of this page
private $subject = null;
/// Text to be set in the query form
private $articletext = "";
/// bool To display outgoing values?
private $showoutgoing = true;
/// bool To display incoming values?
private $showincoming = false;
/// int At which incoming property are we currently?
private $offset = 0;
/**
* Constructor
*/
public function __construct() {
global $smwgBrowseShowAll;
parent::__construct( 'Browse', '', true, false, 'default', true );
if ( $smwgBrowseShowAll ) {
SMWSpecialBrowse::$incomingvaluescount = 21;
SMWSpecialBrowse::$incomingpropertiescount = - 1;
}
}
/**
* Main entry point for Special Pages
*
* @param[in] $query string Given by MediaWiki
*/
public function execute( $query ) {
global $wgRequest, $wgOut, $smwgBrowseShowAll;
$this->setHeaders();
// get the GET parameters
$this->articletext = $wgRequest->getVal( 'article' );
// no GET parameters? Then try the URL
if ( is_null( $this->articletext ) ) {
$params = SMWInfolink::decodeParameters( $query, false );
reset( $params );
$this->articletext = current( $params );
}
$this->subject = SMWDataValueFactory::newTypeIDValue( '_wpg', $this->articletext );
$offsettext = $wgRequest->getVal( 'offset' );
$this->offset = ( is_null( $offsettext ) ) ? 0 : intval( $offsettext );
$dir = $wgRequest->getVal( 'dir' );
if ( $smwgBrowseShowAll ) {
$this->showoutgoing = true;
$this->showincoming = true;
}
if ( $dir === 'both' || $dir === 'in' ) {
$this->showincoming = true;
}
if ( $dir === 'in' ) {
$this->showoutgoing = false;
}
if ( $dir === 'out' ) {
$this->showincoming = false;
}
$wgOut->addHTML( $this->displayBrowse() );
SMWOutputs::commitToOutputPage( $wgOut ); // make sure locally collected output data is pushed to the output!
}
/**
* Create and output HTML including the complete factbox, based on the extracted
* parameters in the execute comment.
*
* @return string A HTML string with the factbox
*/
private function displayBrowse() {
global $wgContLang, $wgOut;
$html = "\n";
$leftside = !( $wgContLang->isRTL() ); // For right to left languages, all is mirrored
if ( $this->subject->isValid() ) {
$html .= $this->displayHead();
if ( $this->showoutgoing ) {
$data = smwfGetStore()->getSemanticData( $this->subject->getDataItem() );
$html .= $this->displayData( $data, $leftside );
$html .= $this->displayCenter();
}
if ( $this->showincoming ) {
list( $indata, $more ) = $this->getInData();
global $smwgBrowseShowInverse;
if ( !$smwgBrowseShowInverse ) {
$leftside = !$leftside;
}
$html .= $this->displayData( $indata, $leftside, true );
$html .= $this->displayBottom( $more );
}
$this->articletext = $this->subject->getWikiValue();
// Add a bit space between the factbox and the query form
if ( !$this->including() ) {
$html .= "<p>   </p>\n";
}
}
if ( !$this->including() ) {
$html .= $this->queryForm();
}
$wgOut->addHTML( $html );
}
/**
* Creates the HTML table displaying the data of one subject.
*
* @param[in] $data SMWSemanticData The data to be displayed
* @param[in] $left bool Should properties be displayed on the left side?
* @param[in] $incoming bool Is this an incoming? Or an outgoing?
*
* @return A string containing the HTML with the factbox
*/
private function displayData( SMWSemanticData $data, $left = true, $incoming = false ) {
// Some of the CSS classes are different for the left or the right side.
// In this case, there is an "i" after the "smwb-". This is set here.
$ccsPrefix = $left ? 'smwb-' : 'smwb-i';
$html = "<table class=\"{$ccsPrefix}factbox\" cellpadding=\"0\" cellspacing=\"0\">\n";
$diProperties = $data->getProperties();
$noresult = true;
foreach ( $diProperties as $key => $diProperty ) {
$dvProperty = SMWDataValueFactory::newDataItemValue( $diProperty, null );
if ( $dvProperty->isVisible() ) {
$dvProperty->setCaption( $this->getPropertyLabel( $dvProperty, $incoming ) );
$proptext = $dvProperty->getShortHTMLText( smwfGetLinker() ) . "\n";
} elseif ( $diProperty->getKey() == '_INST' ) {
$proptext = smwfGetLinker()->specialLink( 'Categories' );
} elseif ( $diProperty->getKey() == '_REDI' ) {
$proptext = smwfGetLinker()->specialLink( 'Listredirects', 'isredirect' );
} else {
continue; // skip this line
}
$head = '<th>' . $proptext . "</th>\n";
$body = "<td>\n";
$values = $data->getPropertyValues( $diProperty );
if ( $incoming && ( count( $values ) >= SMWSpecialBrowse::$incomingvaluescount ) ) {
$moreIncoming = true;
array_pop( $values );
} else {
$moreIncoming = false;
}
$first = true;
foreach ( $values as /* SMWDataItem */ $di ) {
if ( $first ) {
$first = false;
} else {
$body .= ', ';
}
if ( $incoming ) {
$dv = SMWDataValueFactory::newDataItemValue( $di, null );
} else {
$dv = SMWDataValueFactory::newDataItemValue( $di, $diProperty );
}
$body .= "<span class=\"{$ccsPrefix}value\">" .
$this->displayValue( $dvProperty, $dv, $incoming ) . "</span>\n";
}
if ( $moreIncoming ) { // link to the remaining incoming pages:
$body .= Html::element(
'a',
array(
'href' => SpecialPage::getSafeTitleFor( 'SearchByProperty' )->getLocalURL( array(
'property' => $dvProperty->getWikiValue(),
'value' => $this->subject->getWikiValue()
) )
),
wfMessage( 'smw_browse_more' )->text()
);
}
$body .= "</td>\n";
// display row
$html .= "<tr class=\"{$ccsPrefix}propvalue\">\n" .
( $left ? ( $head . $body ):( $body . $head ) ) . "</tr>\n";
$noresult = false;
} // end foreach properties
if ( $noresult ) {
$html .= "<tr class=\"smwb-propvalue\"><th>   </th><td><em>" .
wfMessage( $incoming ? 'smw_browse_no_incoming':'smw_browse_no_outgoing' )->text() . "</em></td></tr>\n";
}
$html .= "</table>\n";
return $html;
}
/**
* Displays a value, including all relevant links (browse and search by property)
*
* @param[in] $property SMWPropertyValue The property this value is linked to the subject with
* @param[in] $value SMWDataValue The actual value
* @param[in] $incoming bool If this is an incoming or outgoing link
*
* @return string HTML with the link to the article, browse, and search pages
*/
private function displayValue( SMWPropertyValue $property, SMWDataValue $dataValue, $incoming ) {
$linker = smwfGetLinker();
$html = $dataValue->getLongHTMLText( $linker );
if ( $dataValue->getTypeID() == '_wpg' ) {
$html .= " " . SMWInfolink::newBrowsingLink( '+', $dataValue->getLongWikiText() )->getHTML( $linker );
} elseif ( $incoming && $property->isVisible() ) {
$html .= " " . SMWInfolink::newInversePropertySearchLink( '+', $dataValue->getTitle(), $property->getDataItem()->getLabel(), 'smwsearch' )->getHTML( $linker );
} else {
$html .= $dataValue->getInfolinkText( SMW_OUTPUT_HTML, $linker );
}
return $html;
}
/**
* Displays the subject that is currently being browsed to.
*
* @return A string containing the HTML with the subject line
*/
private function displayHead() {
global $wgOut;
$wgOut->setHTMLTitle( $this->subject->getTitle() );
$html = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
"<tr class=\"smwb-title\"><td colspan=\"2\">\n" .
$this->subject->getLongHTMLText( smwfGetLinker() ) . "\n" .
"</td></tr>\n</table>\n";
return $html;
}
/**
* Creates the HTML for the center bar including the links with further navigation options.
*
* @return string HTMl with the center bar
*/
private function displayCenter() {
return "<a name=\"smw_browse_incoming\"></a>\n" .
"<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
"<tr class=\"smwb-center\"><td colspan=\"2\">\n" .
( $this->showincoming ?
$this->linkHere( wfMessage( 'smw_browse_hide_incoming' )->text(), true, false, 0 ):
$this->linkHere( wfMessage( 'smw_browse_show_incoming' )->text(), true, true, $this->offset ) ) .
" \n" . "</td></tr>\n" . "</table>\n";
}
/**
* Creates the HTML for the bottom bar including the links with further navigation options.
*
* @param[in] $more bool Are there more inproperties to be displayed?
* @return string HTMl with the bottom bar
*/
private function displayBottom( $more ) {
$html = "<table class=\"smwb-factbox\" cellpadding=\"0\" cellspacing=\"0\">\n" .
"<tr class=\"smwb-center\"><td colspan=\"2\">\n";
global $smwgBrowseShowAll;
if ( !$smwgBrowseShowAll ) {
if ( ( $this->offset > 0 ) || $more ) {
$offset = max( $this->offset - SMWSpecialBrowse::$incomingpropertiescount + 1, 0 );
$html .= ( $this->offset == 0 ) ? wfMessage( 'smw_result_prev' )->text():
$this->linkHere( wfMessage( 'smw_result_prev' )->text(), $this->showoutgoing, true, $offset );
$offset = $this->offset + SMWSpecialBrowse::$incomingpropertiescount - 1;
// @todo FIXME: i18n patchwork.
$html .= "     <strong>" . wfMessage( 'smw_result_results' )->text() . " " . ( $this->offset + 1 ) .
" – " . ( $offset ) . "</strong>     ";
$html .= $more ? $this->linkHere( wfMessage( 'smw_result_next' )->text(), $this->showoutgoing, true, $offset ):wfMessage( 'smw_result_next' )->text();
}
}
$html .= " \n" . "</td></tr>\n" . "</table>\n";
return $html;
}
/**
* Creates the HTML for a link to this page, with some parameters set.
*
* @param[in] $text string The anchor text for the link
* @param[in] $out bool Should the linked to page include outgoing properties?
* @param[in] $in bool Should the linked to page include incoming properties?
* @param[in] $offset int What is the offset for the incoming properties?
*
* @return string HTML with the link to this page
*/
private function linkHere( $text, $out, $in, $offset ) {
$frag = ( $text == wfMessage( 'smw_browse_show_incoming' )->text() ) ? '#smw_browse_incoming' : '';
return Html::element(
'a',
array(
'href' => SpecialPage::getSafeTitleFor( 'Browse' )->getLocalURL( array(
'offset' => $offset,
'dir' => $out ? ( $in ? 'both' : 'out' ) : 'in',
'article' => $this->subject->getLongWikiText()
) ) . $frag
),
$text
);
}
/**
* Creates a Semantic Data object with the incoming properties instead of the
* usual outproperties.
*
* @return array(SMWSemanticData, bool) The semantic data including all inproperties, and if there are more inproperties left
*/
private function getInData() {
$indata = new SMWSemanticData( $this->subject->getDataItem() );
$options = new SMWRequestOptions();
$options->sort = true;
$options->limit = SMWSpecialBrowse::$incomingpropertiescount;
if ( $this->offset > 0 ) $options->offset = $this->offset;
$inproperties = smwfGetStore()->getInProperties( $this->subject->getDataItem(), $options );
if ( count( $inproperties ) == SMWSpecialBrowse::$incomingpropertiescount ) {
$more = true;
array_pop( $inproperties ); // drop the last one
} else {
$more = false;
}
$valoptions = new SMWRequestOptions();
$valoptions->sort = true;
$valoptions->limit = SMWSpecialBrowse::$incomingvaluescount;
foreach ( $inproperties as $property ) {
$values = smwfGetStore()->getPropertySubjects( $property, $this->subject->getDataItem(), $valoptions );
foreach ( $values as $value ) {
$indata->addPropertyObjectValue( $property, $value );
}
}
return array( $indata, $more );
}
/**
* Figures out the label of the property to be used. For outgoing ones it is just
* the text, for incoming ones we try to figure out the inverse one if needed,
* either by looking for an explicitly stated one or by creating a default one.
*
* @param[in] $property SMWPropertyValue The property of interest
* @param[in] $incoming bool If it is an incoming property
*
* @return string The label of the property
*/
private function getPropertyLabel( SMWPropertyValue $property, $incoming = false ) {
global $smwgBrowseShowInverse;
if ( $incoming && $smwgBrowseShowInverse ) {
$oppositeprop = SMWPropertyValue::makeUserProperty( wfMessage( 'smw_inverse_label_property' )->text() );
$labelarray = &smwfGetStore()->getPropertyValues( $property->getDataItem()->getDiWikiPage(), $oppositeprop->getDataItem() );
$rv = ( count( $labelarray ) > 0 ) ? $labelarray[0]->getLongWikiText():
wfMessage( 'smw_inverse_label_default', $property->getWikiValue() )->text();
} else {
$rv = $property->getWikiValue();
}
return $this->unbreak( $rv );
}
/**
* Creates the query form in order to quickly switch to a specific article.
*
* @return A string containing the HTML for the form
*/
private function queryForm() {
SMWOutputs::requireResource( 'ext.smw.browse' );
$title = SpecialPage::getTitleFor( 'Browse' );
return ' <form name="smwbrowse" action="' . htmlspecialchars( $title->getLocalURL() ) . '" method="get">' . "\n" .
' <input type="hidden" name="title" value="' . $title->getPrefixedText() . '"/>' .
wfMessage( 'smw_browse_article' )->text() . "<br />\n" .
' <input type="text" name="article" id="page_input_box" value="' . htmlspecialchars( $this->articletext ) . '" />' . "\n" .
' <input type="submit" value="' . wfMessage( 'smw_browse_go' )->text() . "\"/>\n" .
" </form>\n";
}
/**
* Replace the last two space characters with unbreakable spaces for beautification.
*
* @param[in] $text string Text to be transformed. Does not need to have spaces
* @return string Transformed text
*/
private function unbreak( $text ) {
$nonBreakingSpace = html_entity_decode( ' ', ENT_NOQUOTES, 'UTF-8' );
$text = preg_replace( '/[\s]/u', $nonBreakingSpace, $text, - 1, $count );
return $count > 2 ? preg_replace( '/($nonBreakingSpace)/u', ' ', $text, max( 0, $count - 2 ) ):$text;
}
}
| JeroenDeDauw/SemanticMediaWiki | includes/specials/SMW_SpecialBrowse.php | PHP | gpl-2.0 | 14,800 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* Validates that a card number belongs to a specified scheme.
*
* @author Tim Nagel <t.nagel@infinite.net.au>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @see http://en.wikipedia.org/wiki/Bank_card_number
* @see http://www.regular-expressions.info/creditcard.html
* @see http://www.barclaycard.co.uk/business/files/Ranges_and_Rules_September_2014.pdf
*/
class CardSchemeValidator extends ConstraintValidator
{
protected $schemes = [
// American Express card numbers start with 34 or 37 and have 15 digits.
'AMEX' => [
'/^3[47][0-9]{13}$/',
],
// China UnionPay cards start with 62 and have between 16 and 19 digits.
// Please note that these cards do not follow Luhn Algorithm as a checksum.
'CHINA_UNIONPAY' => [
'/^62[0-9]{14,17}$/',
],
// Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits.
// There are Diners Club cards that begin with 5 and have 16 digits.
// These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
'DINERS' => [
'/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',
],
// Discover card numbers begin with 6011, 622126 through 622925, 644 through 649 or 65.
// All have 16 digits.
'DISCOVER' => [
'/^6011[0-9]{12}$/',
'/^64[4-9][0-9]{13}$/',
'/^65[0-9]{14}$/',
'/^622(12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|91[0-9]|92[0-5])[0-9]{10}$/',
],
// InstaPayment cards begin with 637 through 639 and have 16 digits.
'INSTAPAYMENT' => [
'/^63[7-9][0-9]{13}$/',
],
// JCB cards beginning with 2131 or 1800 have 15 digits.
// JCB cards beginning with 35 have 16 digits.
'JCB' => [
'/^(?:2131|1800|35[0-9]{3})[0-9]{11}$/',
],
// Laser cards begin with either 6304, 6706, 6709 or 6771 and have between 16 and 19 digits.
'LASER' => [
'/^(6304|670[69]|6771)[0-9]{12,15}$/',
],
// Maestro international cards begin with 675900..675999 and have between 12 and 19 digits.
// Maestro UK cards begin with either 500000..509999 or 560000..699999 and have between 12 and 19 digits.
'MAESTRO' => [
'/^(6759[0-9]{2})[0-9]{6,13}$/',
'/^(50[0-9]{4})[0-9]{6,13}$/',
'/^5[6-9][0-9]{10,17}$/',
'/^6[0-9]{11,18}$/',
],
// All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.
// October 2016 MasterCard numbers can also start with 222100 through 272099.
'MASTERCARD' => [
'/^5[1-5][0-9]{14}$/',
'/^2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12})$/',
],
// All Visa card numbers start with a 4 and have a length of 13, 16, or 19 digits.
'VISA' => [
'/^4([0-9]{12}|[0-9]{15}|[0-9]{18})$/',
],
];
/**
* Validates a creditcard belongs to a specified scheme.
*
* @param mixed $value
* @param Constraint $constraint
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof CardScheme) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\CardScheme');
}
if (null === $value || '' === $value) {
return;
}
if (!is_numeric($value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(CardScheme::NOT_NUMERIC_ERROR)
->addViolation();
return;
}
$schemes = array_flip((array) $constraint->schemes);
$schemeRegexes = array_intersect_key($this->schemes, $schemes);
foreach ($schemeRegexes as $regexes) {
foreach ($regexes as $regex) {
if (preg_match($regex, $value)) {
return;
}
}
}
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(CardScheme::INVALID_FORMAT_ERROR)
->addViolation();
}
}
| enslyon/ensl | vendor/symfony/validator/Constraints/CardSchemeValidator.php | PHP | gpl-2.0 | 4,811 |
<?php
Class AddThis_addjs_extender extends AddThis_addjs{
var $jsAfterAdd;
function getAtPluginPromoText(){
if (! did_action('admin_init') && ! current_filter('admin_init'))
{
_doing_it_wrong('getAtPluginPromoText', 'This function should only be called on an admin page load and no earlier the admin_init', 1);
return null;
}
if (apply_filters('addthis_crosspromote', '__return_true'))
{
$plugins = get_plugins();
if (empty($this->_atInstalled))
{
foreach($plugins as $plugin)
{
if (substr($plugin['Name'], 0, 7) === 'AddThis')
array_push($this->_atInstalled, $plugin['Name']);
}
}
$keys = array_keys($this->_atPlugins);
$uninstalled = array_diff( $keys, $this->_atInstalled);
if (empty($uninstalled))
return false;
// Get rid of our keys, we just want the names which are the keys elsewhere
$uninstalled = array_values($uninstalled);
$string = __('Want to increase your site traffic? AddThis also has ');
$count = count($uninstalled);
if ($count == 1){
$string .= __('a plugin for ', 'addthis');
$string .= __( sprintf('<a href="%s" target="_blank">' .$this->_atPlugins[$uninstalled[0]][1] .'</a>', $this->_atPlugins[$uninstalled[0]][0]), 'addthis');
} else {
$string . __('plugins for ');
for ($i = 0; $i < $count; $i++) {
$string .= __( sprintf('<strong><a href="%s" target="_blank" >' .$this->_atPlugins[$uninstalled[$i]][1] .'</a></strong>', $this->_atPlugins[$uninstalled[$i]][0]), 'addthis');
if ($i < ($count - 2))
$string .= ', ';
else if ($i == ($count -2))
$string .= ' and ';
else if ($i == ($count -1))
$string .= ' plugins available.';
}
}
return '<p class="addthis_more_promo">' .$string . '</p>';
}
}
function addAfterScript($newData){
$this->jsAfterAdd .= $newData;
}
function addAfterToJs(){
if (! empty($this->jsAfterAdd));
$this->jsToAdd .= '<script type="text/javascript">' . $this->jsAfterAdd . '</script>';
}
function output_script(){
if ($this->_js_added != true)
{
$this->wrapJs();
$this->addWidgetToJs();
$this->addAfterToJs();
echo $this->jsToAdd;
$this->_js_added = true;
}
}
function output_script_filter($content){
if ($this->_js_added != true && ! is_admin() && ! is_feed() )
{
$this->wrapJs();
$this->addWidgetToJs();
$this->addAfterToJs();
$content = $content . $this->jsToAdd;
$this->_js_added = true;
}
return $content;
}
}
| cw196/tiwal | zh/wp-content/plugins/addthis-smart-layers/views/includes/addthis_addjs_extender.php | PHP | gpl-2.0 | 3,170 |
<?php
/**
* File containing the LocaleConverterInterface interface.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Publish\Core\MVC\Symfony\Locale;
/**
* Interface for locale converters.
* eZ Publish uses <ISO639-2/B>-<ISO3166-Alpha2> locale format (mostly, some supported locales being out of this format, e.g. cro-HR).
* Symfony uses the standard POSIX locale format (<ISO639-1>_<ISO3166-Alpha2>), which is supported by Intl PHP extension.
*
* Locale converters are meant to convert in those 2 formats back and forth.
*/
interface LocaleConverterInterface
{
/**
* Converts a locale in eZ Publish internal format to POSIX format.
* Returns null if conversion cannot be made.
*
* @param string $ezpLocale
*
* @return string|null
*/
public function convertToPOSIX($ezpLocale);
/**
* Converts a locale in POSIX format to eZ Publish internal format.
* Returns null if conversion cannot be made.
*
* @param string $posixLocale
*
* @return string|null
*/
public function convertToEz($posixLocale);
}
| alongosz/ezpublish-kernel | eZ/Publish/Core/MVC/Symfony/Locale/LocaleConverterInterface.php | PHP | gpl-2.0 | 1,236 |
/*
* (C) Copyright 2003-2006
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* (C) Copyright 2004
* Mark Jonas, Freescale Semiconductor, mark.jonas@motorola.com.
*
* (C) Copyright 2004-2006
* Martin Krause, TQ-Systems GmbH, martin.krause@tqs.de
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <mpc5xxx.h>
#include <pci.h>
#include <asm/processor.h>
#ifdef CONFIG_VIDEO_SM501
#include <sm501.h>
#endif
#if defined(CONFIG_MPC5200_DDR)
#include "mt46v16m16-75.h"
#else
#include "mt48lc16m16a2-75.h"
#endif
#ifdef CONFIG_PS2MULT
void ps2mult_early_init(void);
#endif
#ifndef CFG_RAMBOOT
static void sdram_start (int hi_addr)
{
long hi_addr_bit = hi_addr ? 0x01000000 : 0;
/* unlock mode register */
*(vu_long *)MPC5XXX_SDRAM_CTRL = SDRAM_CONTROL | 0x80000000 |
hi_addr_bit;
__asm__ volatile ("sync");
/* precharge all banks */
*(vu_long *)MPC5XXX_SDRAM_CTRL = SDRAM_CONTROL | 0x80000002 |
hi_addr_bit;
__asm__ volatile ("sync");
#if SDRAM_DDR
/* set mode register: extended mode */
*(vu_long *)MPC5XXX_SDRAM_MODE = SDRAM_EMODE;
__asm__ volatile ("sync");
/* set mode register: reset DLL */
*(vu_long *)MPC5XXX_SDRAM_MODE = SDRAM_MODE | 0x04000000;
__asm__ volatile ("sync");
#endif
/* precharge all banks */
*(vu_long *)MPC5XXX_SDRAM_CTRL = SDRAM_CONTROL | 0x80000002 |
hi_addr_bit;
__asm__ volatile ("sync");
/* auto refresh */
*(vu_long *)MPC5XXX_SDRAM_CTRL = SDRAM_CONTROL | 0x80000004 |
hi_addr_bit;
__asm__ volatile ("sync");
/* set mode register */
*(vu_long *)MPC5XXX_SDRAM_MODE = SDRAM_MODE;
__asm__ volatile ("sync");
/* normal operation */
*(vu_long *)MPC5XXX_SDRAM_CTRL = SDRAM_CONTROL | hi_addr_bit;
__asm__ volatile ("sync");
}
#endif
/*
* ATTENTION: Although partially referenced initdram does NOT make real use
* use of CFG_SDRAM_BASE. The code does not work if CFG_SDRAM_BASE
* is something else than 0x00000000.
*/
#if defined(CONFIG_MPC5200)
long int initdram (int board_type)
{
ulong dramsize = 0;
ulong dramsize2 = 0;
uint svr, pvr;
#ifndef CFG_RAMBOOT
ulong test1, test2;
/* setup SDRAM chip selects */
*(vu_long *)MPC5XXX_SDRAM_CS0CFG = 0x0000001c; /* 512MB at 0x0 */
*(vu_long *)MPC5XXX_SDRAM_CS1CFG = 0x40000000; /* disabled */
__asm__ volatile ("sync");
/* setup config registers */
*(vu_long *)MPC5XXX_SDRAM_CONFIG1 = SDRAM_CONFIG1;
*(vu_long *)MPC5XXX_SDRAM_CONFIG2 = SDRAM_CONFIG2;
__asm__ volatile ("sync");
#if SDRAM_DDR
/* set tap delay */
*(vu_long *)MPC5XXX_CDM_PORCFG = SDRAM_TAPDELAY;
__asm__ volatile ("sync");
#endif
/* find RAM size using SDRAM CS0 only */
sdram_start(0);
test1 = get_ram_size((long *)CFG_SDRAM_BASE, 0x20000000);
sdram_start(1);
test2 = get_ram_size((long *)CFG_SDRAM_BASE, 0x20000000);
if (test1 > test2) {
sdram_start(0);
dramsize = test1;
} else {
dramsize = test2;
}
/* memory smaller than 1MB is impossible */
if (dramsize < (1 << 20)) {
dramsize = 0;
}
/* set SDRAM CS0 size according to the amount of RAM found */
if (dramsize > 0) {
*(vu_long *)MPC5XXX_SDRAM_CS0CFG = 0x13 +
__builtin_ffs(dramsize >> 20) - 1;
} else {
*(vu_long *)MPC5XXX_SDRAM_CS0CFG = 0; /* disabled */
}
/* let SDRAM CS1 start right after CS0 */
*(vu_long *)MPC5XXX_SDRAM_CS1CFG = dramsize + 0x0000001c; /* 512MB */
/* find RAM size using SDRAM CS1 only */
sdram_start(0);
test1 = get_ram_size((long *)(CFG_SDRAM_BASE + dramsize), 0x20000000);
sdram_start(1);
test2 = get_ram_size((long *)(CFG_SDRAM_BASE + dramsize), 0x20000000);
if (test1 > test2) {
sdram_start(0);
dramsize2 = test1;
} else {
dramsize2 = test2;
}
/* memory smaller than 1MB is impossible */
if (dramsize2 < (1 << 20)) {
dramsize2 = 0;
}
/* set SDRAM CS1 size according to the amount of RAM found */
if (dramsize2 > 0) {
*(vu_long *)MPC5XXX_SDRAM_CS1CFG = dramsize
| (0x13 + __builtin_ffs(dramsize2 >> 20) - 1);
} else {
*(vu_long *)MPC5XXX_SDRAM_CS1CFG = dramsize; /* disabled */
}
#else /* CFG_RAMBOOT */
/* retrieve size of memory connected to SDRAM CS0 */
dramsize = *(vu_long *)MPC5XXX_SDRAM_CS0CFG & 0xFF;
if (dramsize >= 0x13) {
dramsize = (1 << (dramsize - 0x13)) << 20;
} else {
dramsize = 0;
}
/* retrieve size of memory connected to SDRAM CS1 */
dramsize2 = *(vu_long *)MPC5XXX_SDRAM_CS1CFG & 0xFF;
if (dramsize2 >= 0x13) {
dramsize2 = (1 << (dramsize2 - 0x13)) << 20;
} else {
dramsize2 = 0;
}
#endif /* CFG_RAMBOOT */
/*
* On MPC5200B we need to set the special configuration delay in the
* DDR controller. Please refer to Freescale's AN3221 "MPC5200B SDRAM
* Initialization and Configuration", 3.3.1 SDelay--MBAR + 0x0190:
*
* "The SDelay should be written to a value of 0x00000004. It is
* required to account for changes caused by normal wafer processing
* parameters."
*/
svr = get_svr();
pvr = get_pvr();
if ((SVR_MJREV(svr) >= 2) &&
(PVR_MAJ(pvr) == 1) && (PVR_MIN(pvr) == 4)) {
*(vu_long *)MPC5XXX_SDRAM_SDELAY = 0x04;
__asm__ volatile ("sync");
}
#if defined(CONFIG_TQM5200_B)
return dramsize + dramsize2;
#else
return dramsize;
#endif /* CONFIG_TQM5200_B */
}
#elif defined(CONFIG_MGT5100)
long int initdram (int board_type)
{
ulong dramsize = 0;
#ifndef CFG_RAMBOOT
ulong test1, test2;
/* setup and enable SDRAM chip selects */
*(vu_long *)MPC5XXX_SDRAM_START = 0x00000000;
*(vu_long *)MPC5XXX_SDRAM_STOP = 0x0000ffff;/* 2G */
*(vu_long *)MPC5XXX_ADDECR |= (1 << 22); /* Enable SDRAM */
__asm__ volatile ("sync");
/* setup config registers */
*(vu_long *)MPC5XXX_SDRAM_CONFIG1 = SDRAM_CONFIG1;
*(vu_long *)MPC5XXX_SDRAM_CONFIG2 = SDRAM_CONFIG2;
/* address select register */
*(vu_long *)MPC5XXX_SDRAM_XLBSEL = SDRAM_ADDRSEL;
__asm__ volatile ("sync");
/* find RAM size */
sdram_start(0);
test1 = get_ram_size((ulong *)CFG_SDRAM_BASE, 0x80000000);
sdram_start(1);
test2 = get_ram_size((ulong *)CFG_SDRAM_BASE, 0x80000000);
if (test1 > test2) {
sdram_start(0);
dramsize = test1;
} else {
dramsize = test2;
}
/* set SDRAM end address according to size */
*(vu_long *)MPC5XXX_SDRAM_STOP = ((dramsize - 1) >> 15);
#else /* CFG_RAMBOOT */
/* Retrieve amount of SDRAM available */
dramsize = ((*(vu_long *)MPC5XXX_SDRAM_STOP + 1) << 15);
#endif /* CFG_RAMBOOT */
return dramsize;
}
#else
#error Neither CONFIG_MPC5200 or CONFIG_MGT5100 defined
#endif
int checkboard (void)
{
#if defined(CONFIG_AEVFIFO)
puts ("Board: AEVFIFO\n");
return 0;
#endif
#if defined(CONFIG_TQM5200S)
# define MODULE_NAME "TQM5200S"
#else
# define MODULE_NAME "TQM5200"
#endif
#if defined(CONFIG_STK52XX)
# define CARRIER_NAME "STK52xx"
#elif defined(CONFIG_TB5200)
# define CARRIER_NAME "TB5200"
#elif defined(CONFIG_CAM5200)
# define CARRIER_NAME "Cam5200"
#else
# error "Unknown carrier board"
#endif
puts ( "Board: " MODULE_NAME " (TQ-Components GmbH)\n"
" on a " CARRIER_NAME " carrier board\n");
return 0;
}
#undef MODULE_NAME
#undef CARRIER_NAME
void flash_preinit(void)
{
/*
* Now, when we are in RAM, enable flash write
* access for detection process.
* Note that CS_BOOT cannot be cleared when
* executing in flash.
*/
#if defined(CONFIG_MGT5100)
*(vu_long *)MPC5XXX_ADDECR &= ~(1 << 25); /* disable CS_BOOT */
*(vu_long *)MPC5XXX_ADDECR |= (1 << 16); /* enable CS0 */
#endif
*(vu_long *)MPC5XXX_BOOTCS_CFG &= ~0x1; /* clear RO */
}
#ifdef CONFIG_PCI
static struct pci_controller hose;
extern void pci_mpc5xxx_init(struct pci_controller *);
void pci_init_board(void)
{
pci_mpc5xxx_init(&hose);
}
#endif
#if defined (CFG_CMD_IDE) && defined (CONFIG_IDE_RESET)
#if defined (CONFIG_MINIFAP)
#define SM501_POWER_MODE0_GATE 0x00000040UL
#define SM501_POWER_MODE1_GATE 0x00000048UL
#define POWER_MODE_GATE_GPIO_PWM_I2C 0x00000040UL
#define SM501_GPIO_DATA_DIR_HIGH 0x0001000CUL
#define SM501_GPIO_DATA_HIGH 0x00010004UL
#define SM501_GPIO_51 0x00080000UL
#else
#define GPIO_PSC1_4 0x01000000UL
#endif
void init_ide_reset (void)
{
debug ("init_ide_reset\n");
#if defined (CONFIG_MINIFAP)
/* Configure GPIO_51 of the SM501 grafic controller as ATA reset */
/* enable GPIO control (in both power modes) */
*(vu_long *) (SM501_MMIO_BASE+SM501_POWER_MODE0_GATE) |=
POWER_MODE_GATE_GPIO_PWM_I2C;
*(vu_long *) (SM501_MMIO_BASE+SM501_POWER_MODE1_GATE) |=
POWER_MODE_GATE_GPIO_PWM_I2C;
/* configure GPIO51 as output */
*(vu_long *) (SM501_MMIO_BASE+SM501_GPIO_DATA_DIR_HIGH) |=
SM501_GPIO_51;
#else
/* Configure PSC1_4 as GPIO output for ATA reset */
*(vu_long *) MPC5XXX_WU_GPIO_ENABLE |= GPIO_PSC1_4;
*(vu_long *) MPC5XXX_WU_GPIO_DIR |= GPIO_PSC1_4;
#endif
}
void ide_set_reset (int idereset)
{
debug ("ide_reset(%d)\n", idereset);
#if defined (CONFIG_MINIFAP)
if (idereset) {
*(vu_long *) (SM501_MMIO_BASE+SM501_GPIO_DATA_HIGH) &=
~SM501_GPIO_51;
} else {
*(vu_long *) (SM501_MMIO_BASE+SM501_GPIO_DATA_HIGH) |=
SM501_GPIO_51;
}
#else
if (idereset) {
*(vu_long *) MPC5XXX_WU_GPIO_DATA &= ~GPIO_PSC1_4;
} else {
*(vu_long *) MPC5XXX_WU_GPIO_DATA |= GPIO_PSC1_4;
}
#endif
}
#endif /* defined (CFG_CMD_IDE) && defined (CONFIG_IDE_RESET) */
#ifdef CONFIG_POST
/*
* Reads GPIO pin PSC6_3. A keypress is reported, if PSC6_3 is low. If PSC6_3
* is left open, no keypress is detected.
*/
int post_hotkeys_pressed(void)
{
struct mpc5xxx_gpio *gpio;
gpio = (struct mpc5xxx_gpio*) MPC5XXX_GPIO;
/*
* Configure PSC6_1 and PSC6_3 as GPIO. PSC6 then couldn't be used in
* CODEC or UART mode. Consumer IrDA should still be possible.
*/
gpio->port_config &= ~(0x07000000);
gpio->port_config |= 0x03000000;
/* Enable GPIO for GPIO_IRDA_1 (IR_USB_CLK pin) = PSC6_3 */
gpio->simple_gpioe |= 0x20000000;
/* Configure GPIO_IRDA_1 as input */
gpio->simple_ddr &= ~(0x20000000);
return ((gpio->simple_ival & 0x20000000) ? 0 : 1);
}
#endif
#if defined(CONFIG_POST) || defined(CONFIG_LOGBUFFER)
void post_word_store (ulong a)
{
volatile ulong *save_addr =
(volatile ulong *)(MPC5XXX_SRAM + MPC5XXX_SRAM_POST_SIZE);
*save_addr = a;
}
ulong post_word_load (void)
{
volatile ulong *save_addr =
(volatile ulong *)(MPC5XXX_SRAM + MPC5XXX_SRAM_POST_SIZE);
return *save_addr;
}
#endif /* CONFIG_POST || CONFIG_LOGBUFFER*/
#ifdef CONFIG_PS2MULT
#ifdef CONFIG_BOARD_EARLY_INIT_R
int board_early_init_r (void)
{
ps2mult_early_init();
return (0);
}
#endif
#endif /* CONFIG_PS2MULT */
int last_stage_init (void)
{
/*
* auto scan for really existing devices and re-set chip select
* configuration.
*/
u16 save, tmp;
int restore;
/*
* Check for SRAM and SRAM size
*/
/* save original SRAM content */
save = *(volatile u16 *)CFG_CS2_START;
restore = 1;
/* write test pattern to SRAM */
*(volatile u16 *)CFG_CS2_START = 0xA5A5;
__asm__ volatile ("sync");
/*
* Put a different pattern on the data lines: otherwise they may float
* long enough to read back what we wrote.
*/
tmp = *(volatile u16 *)CFG_FLASH_BASE;
if (tmp == 0xA5A5)
puts ("!! possible error in SRAM detection\n");
if (*(volatile u16 *)CFG_CS2_START != 0xA5A5) {
/* no SRAM at all, disable cs */
*(vu_long *)MPC5XXX_ADDECR &= ~(1 << 18);
*(vu_long *)MPC5XXX_CS2_START = 0x0000FFFF;
*(vu_long *)MPC5XXX_CS2_STOP = 0x0000FFFF;
restore = 0;
__asm__ volatile ("sync");
} else if (*(volatile u16 *)(CFG_CS2_START + (1<<19)) == 0xA5A5) {
/* make sure that we access a mirrored address */
*(volatile u16 *)CFG_CS2_START = 0x1111;
__asm__ volatile ("sync");
if (*(volatile u16 *)(CFG_CS2_START + (1<<19)) == 0x1111) {
/* SRAM size = 512 kByte */
*(vu_long *)MPC5XXX_CS2_STOP = STOP_REG(CFG_CS2_START,
0x80000);
__asm__ volatile ("sync");
puts ("SRAM: 512 kB\n");
}
else
puts ("!! possible error in SRAM detection\n");
} else {
puts ("SRAM: 1 MB\n");
}
/* restore origianl SRAM content */
if (restore) {
*(volatile u16 *)CFG_CS2_START = save;
__asm__ volatile ("sync");
}
/*
* Check for Grafic Controller
*/
/* save origianl FB content */
save = *(volatile u16 *)CFG_CS1_START;
restore = 1;
/* write test pattern to FB memory */
*(volatile u16 *)CFG_CS1_START = 0xA5A5;
__asm__ volatile ("sync");
/*
* Put a different pattern on the data lines: otherwise they may float
* long enough to read back what we wrote.
*/
tmp = *(volatile u16 *)CFG_FLASH_BASE;
if (tmp == 0xA5A5)
puts ("!! possible error in grafic controller detection\n");
if (*(volatile u16 *)CFG_CS1_START != 0xA5A5) {
/* no grafic controller at all, disable cs */
*(vu_long *)MPC5XXX_ADDECR &= ~(1 << 17);
*(vu_long *)MPC5XXX_CS1_START = 0x0000FFFF;
*(vu_long *)MPC5XXX_CS1_STOP = 0x0000FFFF;
restore = 0;
__asm__ volatile ("sync");
} else {
puts ("VGA: SMI501 (Voyager) with 8 MB\n");
}
/* restore origianl FB content */
if (restore) {
*(volatile u16 *)CFG_CS1_START = save;
__asm__ volatile ("sync");
}
return 0;
}
#ifdef CONFIG_VIDEO_SM501
#define DISPLAY_WIDTH 640
#define DISPLAY_HEIGHT 480
#ifdef CONFIG_VIDEO_SM501_8BPP
#error CONFIG_VIDEO_SM501_8BPP not supported.
#endif /* CONFIG_VIDEO_SM501_8BPP */
#ifdef CONFIG_VIDEO_SM501_16BPP
#error CONFIG_VIDEO_SM501_16BPP not supported.
#endif /* CONFIG_VIDEO_SM501_16BPP */
#ifdef CONFIG_VIDEO_SM501_32BPP
static const SMI_REGS init_regs [] =
{
#if 0 /* CRT only */
{0x00004, 0x0},
{0x00048, 0x00021807},
{0x0004C, 0x10090a01},
{0x00054, 0x1},
{0x00040, 0x00021807},
{0x00044, 0x10090a01},
{0x00054, 0x0},
{0x80200, 0x00010000},
{0x80204, 0x0},
{0x80208, 0x0A000A00},
{0x8020C, 0x02fa027f},
{0x80210, 0x004a028b},
{0x80214, 0x020c01df},
{0x80218, 0x000201e9},
{0x80200, 0x00013306},
#else /* panel + CRT */
{0x00004, 0x0},
{0x00048, 0x00021807},
{0x0004C, 0x091a0a01},
{0x00054, 0x1},
{0x00040, 0x00021807},
{0x00044, 0x091a0a01},
{0x00054, 0x0},
{0x80000, 0x0f013106},
{0x80004, 0xc428bb17},
{0x8000C, 0x00000000},
{0x80010, 0x0a000a00},
{0x80014, 0x02800000},
{0x80018, 0x01e00000},
{0x8001C, 0x00000000},
{0x80020, 0x01e00280},
{0x80024, 0x02fa027f},
{0x80028, 0x004a028b},
{0x8002C, 0x020c01df},
{0x80030, 0x000201e9},
{0x80200, 0x00010000},
#endif
{0, 0}
};
#endif /* CONFIG_VIDEO_SM501_32BPP */
#ifdef CONFIG_CONSOLE_EXTRA_INFO
/*
* Return text to be printed besides the logo.
*/
void video_get_info_str (int line_number, char *info)
{
if (line_number == 1) {
strcpy (info, " Board: TQM5200 (TQ-Components GmbH)");
#if defined (CONFIG_STK52XX) || defined (CONFIG_TB5200)
} else if (line_number == 2) {
#if defined (CONFIG_STK52XX)
strcpy (info, " on a STK52xx carrier board");
#endif
#if defined (CONFIG_TB5200)
strcpy (info, " on a TB5200 carrier board");
#endif
#endif
}
else {
info [0] = '\0';
}
}
#endif
/*
* Returns SM501 register base address. First thing called in the
* driver. Checks if SM501 is physically present.
*/
unsigned int board_video_init (void)
{
u16 save, tmp;
int restore, ret;
/*
* Check for Grafic Controller
*/
/* save origianl FB content */
save = *(volatile u16 *)CFG_CS1_START;
restore = 1;
/* write test pattern to FB memory */
*(volatile u16 *)CFG_CS1_START = 0xA5A5;
__asm__ volatile ("sync");
/*
* Put a different pattern on the data lines: otherwise they may float
* long enough to read back what we wrote.
*/
tmp = *(volatile u16 *)CFG_FLASH_BASE;
if (tmp == 0xA5A5)
puts ("!! possible error in grafic controller detection\n");
if (*(volatile u16 *)CFG_CS1_START != 0xA5A5) {
/* no grafic controller found */
restore = 0;
ret = 0;
} else {
ret = SM501_MMIO_BASE;
}
if (restore) {
*(volatile u16 *)CFG_CS1_START = save;
__asm__ volatile ("sync");
}
return ret;
}
/*
* Returns SM501 framebuffer address
*/
unsigned int board_video_get_fb (void)
{
return SM501_FB_BASE;
}
/*
* Called after initializing the SM501 and before clearing the screen.
*/
void board_validate_screen (unsigned int base)
{
}
/*
* Return a pointer to the initialization sequence.
*/
const SMI_REGS *board_get_regs (void)
{
return init_regs;
}
int board_get_width (void)
{
return DISPLAY_WIDTH;
}
int board_get_height (void)
{
return DISPLAY_HEIGHT;
}
#endif /* CONFIG_VIDEO_SM501 */
| eldarerathis/FIREFIREFIRE-Multiboot-PoC | board/tqm5200/tqm5200.c | C | gpl-2.0 | 16,892 |
<?php defined('_JEXEC') or die; ?>
<?php if ( $this->params->def( 'show_page_title', 1 ) ) : ?>
<div class="componentheading<?php echo $this->params->get( 'pageclass_sfx' ); ?>">
<?php echo $this->escape($this->params->get('page_title')); ?>
</div>
<?php endif; ?>
<form action="index.php?option=com_user&task=remindusername" method="post" class="josForm form-validate">
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="contentpane">
<tr>
<td colspan="2" height="40">
<p><?php echo JText::_('REMIND_USERNAME_DESCRIPTION'); ?></p>
</td>
</tr>
<tr>
<td height="40">
<label for="email" class="hasTip" title="<?php echo JText::_('REMIND_USERNAME_EMAIL_TIP_TITLE'); ?>::<?php echo JText::_('REMIND_USERNAME_EMAIL_TIP_TEXT'); ?>"><?php echo JText::_('Email Address'); ?>:</label>
</td>
<td>
<input id="email" name="email" type="text" class="required validate-email" />
</td>
</tr>
</table>
<button type="submit" class="validate"><?php echo JText::_('Submit'); ?></button>
<?php echo JHTML::_( 'form.token' ); ?>
</form>
| intelogen/organica | components/com_user_0/views/remind/tmpl/default.php | PHP | gpl-2.0 | 1,088 |
#
# Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com)
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
| ShaolongHu/lpts | site-packages/pychart/line_plot.py | Python | gpl-2.0 | 6,684 |
<html lang="en">
<head>
<title>ARM-Instruction-Set - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="ARM-Syntax.html#ARM-Syntax" title="ARM Syntax">
<link rel="next" href="ARM_002dChars.html#ARM_002dChars" title="ARM-Chars">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2000, 2001, 2002, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
<link rel="stylesheet" type="text/css" href="../cs.css">
</head>
<body>
<div class="node">
<a name="ARM-Instruction-Set"></a>
<a name="ARM_002dInstruction_002dSet"></a>
<p>
Next: <a rel="next" accesskey="n" href="ARM_002dChars.html#ARM_002dChars">ARM-Chars</a>,
Up: <a rel="up" accesskey="u" href="ARM-Syntax.html#ARM-Syntax">ARM Syntax</a>
<hr>
</div>
<h5 class="subsubsection">9.3.2.1 Instruction Set Syntax</h5>
<p>Two slightly different syntaxes are support for ARM and THUMB
instructions. The default, <code>divided</code>, uses the old style where
ARM and THUMB instructions had their own, separate syntaxes. The new,
<code>unified</code> syntax, which can be selected via the <code>.syntax</code>
directive, and has the following main features:
<dl>
<dt>•<dd>Immediate operands do not require a <code>#</code> prefix.
<br><dt>•<dd>The <code>IT</code> instruction may appear, and if it does it is validated
against subsequent conditional affixes. In ARM mode it does not
generate machine code, in THUMB mode it does.
<br><dt>•<dd>For ARM instructions the conditional affixes always appear at the end
of the instruction. For THUMB instructions conditional affixes can be
used, but only inside the scope of an <code>IT</code> instruction.
<br><dt>•<dd>All of the instructions new to the V6T2 architecture (and later) are
available. (Only a few such instructions can be written in the
<code>divided</code> syntax).
<br><dt>•<dd>The <code>.N</code> and <code>.W</code> suffixes are recognized and honored.
<br><dt>•<dd>All instructions set the flags if and only if they have an <code>s</code>
affix.
</dl>
</body></html>
| byeonggonlee/lynx-ns-gb | toolchain/share/doc/arm-arm-none-eabi/html/as.html/ARM_002dInstruction_002dSet.html | HTML | gpl-2.0 | 3,356 |
#ifndef AMDISPLAY_UTILS_H
#define AMDISPLAY_UTILS_H
#ifdef __cplusplus
extern "C" {
#endif
int amdisplay_utils_get_size(int *width, int *height);
int amdisplay_utils_get_size_fb2(int *width, int *height);
/*scale osd mode ,only support x1 x2*/
int amdisplay_utils_set_scale_mode(int scale_wx, int scale_hx);
#ifdef __cplusplus
}
#endif
#endif
| giannoug/android_device_jxd_s7300b | packages/LibPlayer/amavutils/include/Amdisplayutils.h | C | gpl-2.0 | 368 |
<?php
/**
* FTP Exception Class
*
* @author Andreas Skodzek <webmaster@phpbuddy.eu>
* @link http://www.phpbuddy.eu/
* @copyright 2008 Andreas Skodzek
* @license GNU Public License <http://www.gnu.org/licenses/gpl.html>
* @package phpBuddy.FTP.Exception.Class
* @version 1.0 released 01.09.2008
*/
class FTPException extends Exception
{
/**
* Error Message if no native FTP support is available
*/
const FTP_SUPPORT_ERROR = 'Die FTP-Funktionen sind auf diesem System nicht verfuegbar!';
/**
* Error Message if the given Host does not respond
*/
const CONNECT_FAILED_BADHOST = 'Der angegebene Host konnte nicht kontaktiert werden!';
/**
* Error Message if no SSL-FTP is available and no fallback is used
*/
const CONNECT_FAILED_NOSSL = 'Die Verbindung via SSL konnte nicht hergestellt werden!';
/**
* Error Message if the given login information is not valid
*/
const CONNECT_FAILED_BADLOGIN = 'Die Zugangsdaten für die FTP Verbindung sind inkorrekt!';
/**
* Error Message if the FTP server OS could not be determined.
*/
const CONNECT_UNKNOWN_OS = 'Das Betriebssystem des FTP Server konnte nicht identifiziert werden!';
/**
* Constructor
*/
public function __construct( $meldung, $code = 0 )
{
parent::__construct( $meldung, $code );
}
}
?> | meetai/2Moons | src/includes/libs/ftp/ftpexception.class.php | PHP | gpl-3.0 | 1,339 |
using SmartStore.Web.Framework.Modelling;
namespace SmartStore.PayPal.Models
{
public class PayPalExpressPaymentInfoModel : ModelBase
{
public PayPalExpressPaymentInfoModel()
{
}
public bool CurrentPageIsBasket { get; set; }
public string SubmitButtonImageUrl { get; set; }
}
} | chunlizh/SmartStoreNET | src/Plugins/SmartStore.PayPal/Models/PayPalExpressPaymentInfoModel.cs | C# | gpl-3.0 | 349 |
<?php
namespace app\models;
use app\properties\HasProperties;
use devgroup\TagDependencyHelper\ActiveRecordHelper;
use Yii;
use yii\behaviors\AttributeBehavior;
use yii\caching\TagDependency;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
/**
* This is the model class for table "property_group".
*
* @property integer $id
* @property integer $object_id
* @property string $name
* @property integer $sort_order
* @property integer $is_internal
* @property integer $hidden_group_title
*/
class PropertyGroup extends ActiveRecord
{
private static $identity_map = [];
private static $groups_by_object_id = [];
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'sort_order',
],
'value' => 0,
],
[
'class' => ActiveRecordHelper::className(),
],
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%property_group}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['object_id', 'name'], 'required'],
[['object_id', 'sort_order', 'is_internal', 'hidden_group_title'], 'integer'],
[['name'], 'string']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'object_id' => Yii::t('app', 'Object ID'),
'name' => Yii::t('app', 'Name'),
'sort_order' => Yii::t('app', 'Sort Order'),
'is_internal' => Yii::t('app', 'Is Internal'),
'hidden_group_title' => Yii::t('app', 'Hidden Group Title'),
];
}
/**
* Relation to \app\models\Object
* @return \yii\db\ActiveQuery
*/
public function getObject()
{
return $this->hasOne(Object::className(), ['id' => 'object_id']);
}
/**
* Search tasks
* @param $params
* @return ActiveDataProvider
*/
public function search($params)
{
/* @var $query \yii\db\ActiveQuery */
$query = self::find();
$dataProvider = new ActiveDataProvider(
[
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]
);
if (!($this->load($params))) {
return $dataProvider;
}
$query->andFilterWhere(['id' => $this->id]);
$query->andFilterWhere(['like', 'name', $this->name]);
$query->andFilterWhere(['object_id' => $this->object_id]);
$query->andFilterWhere(['is_internal' => $this->is_internal]);
$query->andFilterWhere(['hidden_group_title' => $this->hidden_group_title]);
return $dataProvider;
}
/**
* Возвращает модель по ID с использованием IdentityMap
*
* @param int $id
* @return null|PropertyGroup
*/
public static function findById($id)
{
if (!isset(static::$identity_map[$id])) {
$cacheKey = "PropertyGroup:$id";
if (false === $group = Yii::$app->cache->get($cacheKey)) {
if (null !== $group = static::findOne($id)) {
Yii::$app->cache->set(
$cacheKey,
$group,
0,
new TagDependency(
[
'tags' => [
ActiveRecordHelper::getObjectTag(static::className(), $id),
],
]
)
);
}
}
static::$identity_map[$id] = $group;
}
return static::$identity_map[$id];
}
/**
* Relation to properties
* @return \yii\db\ActiveQuery
*/
public function getProperties()
{
return $this->hasMany(Property::className(), ['property_group_id' => 'id'])->orderBy('sort_order');
}
/**
* @param $object_id
* @param bool $withProperties
* @return PropertyGroup[]
*/
public static function getForObjectId($object_id, $withProperties = false)
{
if (null === $object_id) {
return [];
}
if (!isset(static::$groups_by_object_id[$object_id])) {
$cacheKey = 'PropertyGroup:objectId:'.$object_id;
static::$groups_by_object_id[$object_id] = Yii::$app->cache->get($cacheKey);
if (!is_array(static::$groups_by_object_id[$object_id])) {
$query = static::find()
->where(['object_id'=>$object_id])
->orderBy('sort_order');
if ($withProperties === true) {
$query = $query->with('properties');
}
static::$groups_by_object_id[$object_id] = $query->all();
if (null !== $object = Object::findById($object_id)) {
$tags = [
ActiveRecordHelper::getObjectTag($object, $object_id)
];
foreach (static::$groups_by_object_id[$object_id] as $propertyGroup){
$tags[] = ActiveRecordHelper::getObjectTag($propertyGroup, $propertyGroup->id);
if ($withProperties === true) {
foreach ($propertyGroup->properties as $prop) {
if (isset(Property::$group_id_to_property_ids[$propertyGroup->id]) === false) {
Property::$group_id_to_property_ids[$propertyGroup->id]=[];
}
Property::$group_id_to_property_ids[$propertyGroup->id][] = $prop->id;
Property::$identity_map[$prop->id] = $prop;
}
}
}
Yii::$app->cache->set(
$cacheKey,
static::$groups_by_object_id[$object_id],
0,
new TagDependency(
[
'tags' => $tags,
]
)
);
}
}
}
return static::$groups_by_object_id[$object_id];
}
/**
* @param int $object_id
* @param int $object_model_id
* @return null|\yii\db\ActiveRecord[]
*/
public static function getForModel($object_id, $object_model_id)
{
$cacheKey = "PropertyGroupBy:$object_id:$object_model_id";
if (false === $groups = Yii::$app->cache->get($cacheKey)) {
$group_ids = ObjectPropertyGroup::find()
->select('property_group_id')
->where([
'object_id' => $object_id,
'object_model_id' => $object_model_id,
])->column();
if (null === $group_ids) {
return null;
}
if (null === $groups = static::find()->where(['in', 'id', $group_ids])->all()) {
return null;
}
if (null !== $object = Object::findById($object_id)) {
Yii::$app->cache->set(
$cacheKey,
$groups,
0,
new TagDependency(
[
'tags' => [
ActiveRecordHelper::getObjectTag($object, $object_id),
ActiveRecordHelper::getObjectTag($object->object_class, $object_model_id),
],
]
)
);
}
}
return $groups;
}
public function beforeDelete()
{
if (!parent::beforeDelete()) {
return false;
}
$properties = Property::findAll(['property_group_id' => $this->id]);
foreach ($properties as $prop) {
$prop->delete();
}
return true;
}
public function afterDelete()
{
ObjectPropertyGroup::deleteAll(['property_group_id' => $this->id]);
parent::afterDelete();
}
/**
* @param ActiveRecord|HasProperties $model
* @param string $idAttribute
* @return bool
*/
public function appendToObjectModel(ActiveRecord $model, $idAttribute = 'id')
{
$object = Object::getForClass($model::className());
if (null === $object || !$model->hasAttribute($idAttribute)) {
return false;
}
$link = new ObjectPropertyGroup();
$link->object_id = $object->id;
$link->object_model_id = $model->$idAttribute;
$link->property_group_id = $this->id;
$result = $link->save();
$model->updatePropertyGroupsInformation();
return $result;
}
}
?> | rinodung/yii2-shop-cms | models/PropertyGroup.php | PHP | gpl-3.0 | 9,292 |
/*
* Created by Phil on 07/01/2011.
* Copyright 2011 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
#include <string>
#include "catch_result_type.h"
#include "catch_common.h"
namespace Catch {
class TestCase;
class AssertionResult;
struct AssertionInfo;
struct SectionInfo;
struct MessageInfo;
class ScopedMessageBuilder;
struct Counts;
struct IResultCapture {
virtual ~IResultCapture();
virtual void assertionEnded( AssertionResult const& result ) = 0;
virtual bool sectionStarted( SectionInfo const& sectionInfo,
Counts& assertions ) = 0;
virtual void sectionEnded( SectionInfo const& name, Counts const& assertions, double _durationInSeconds ) = 0;
virtual void pushScopedMessage( MessageInfo const& message ) = 0;
virtual void popScopedMessage( MessageInfo const& message ) = 0;
virtual std::string getCurrentTestName() const = 0;
virtual const AssertionResult* getLastResult() const = 0;
virtual void handleFatalErrorCondition( std::string const& message ) = 0;
};
IResultCapture& getResultCapture();
}
#endif // TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
| edlund/fabl-ng | vendor/builds/catch-1/internal/catch_interfaces_capture.h | C | gpl-3.0 | 1,506 |
package org.jnbt;
/*
* JNBT License
*
* Copyright (c) 2010 Graham Edgecombe
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the JNBT team nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
/**
* The <code>TAG_Float</code> tag.
* @author Graham Edgecombe
*
*/
public final class FloatTag extends Tag {
/**
* The value.
*/
private final float value;
/**
* Creates the tag.
* @param name The name.
* @param value The value.
*/
public FloatTag(String name, float value) {
super(name);
this.value = value;
}
@Override
public Float getValue() {
return value;
}
@Override
public String toString() {
String name = getName();
String append = "";
if(name != null && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
}
return "TAG_Float" + append + ": " + value;
}
}
| ferrybig/Enderstone | src/org/jnbt/FloatTag.java | Java | gpl-3.0 | 2,294 |
/* -*- c++ -*- */
/*
* Copyright 2005,2012 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_COMEDI_SINK_IMPL_H
#define INCLUDED_COMEDI_SINK_IMPL_H
#include <gnuradio/comedi/sink_s.h>
#include <string>
#include <comedilib.h>
#include <stdexcept>
namespace gr {
namespace comedi {
class sink_s_impl : public sink_s
{
private:
// typedef for pointer to class work method
typedef int (sink_s::*work_t)(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
unsigned int d_sampling_freq;
std::string d_device_name;
comedi_t *d_dev;
int d_subdevice;
int d_n_chan;
void *d_map;
int d_buffer_size;
unsigned d_buf_front;
unsigned d_buf_back;
// random stats
int d_nunderuns; // count of underruns
void output_error_msg(const char *msg, int err);
void bail(const char *msg, int err) throw (std::runtime_error);
public:
sink_s_impl(int sampling_freq, const std::string device_name);
~sink_s_impl();
bool check_topology(int ninputs, int noutputs);
int work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
};
} /* namespace comedi */
} /* namespace gr */
#endif /* INCLUDED_COMEDI_SINK_IMPL_H */
| riveridea/gnuradio | gr-comedi/lib/sink_s_impl.h | C | gpl-3.0 | 2,133 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Date: 2001-07-12
*
* SUMMARY: Regression test for bug 89443
* See http://bugzilla.mozilla.org/show_bug.cgi?id=89443
*
* Just seeing if this script will compile without stack overflow.
*/
//-----------------------------------------------------------------------------
var gTestfile = 'regress-89443.js';
var BUGNUMBER = 89443;
var summary = 'Testing this script will compile without stack overflow';
printBugNumber(BUGNUMBER);
printStatus (summary);
// I don't know what these functions are supposed to be; use dummies -
function isPlainHostName()
{
}
function dnsDomainIs()
{
}
// Here's the big function -
function FindProxyForURL(url, host)
{
if (isPlainHostName(host)
|| dnsDomainIs(host, ".hennepin.lib.mn.us")
|| dnsDomainIs(host, ".hclib.org")
)
return "DIRECT";
else if (isPlainHostName(host)
// subscription database access
|| dnsDomainIs(host, ".asahi.com")
|| dnsDomainIs(host, ".2facts.com")
|| dnsDomainIs(host, ".oclc.org")
|| dnsDomainIs(host, ".collegesource.com")
|| dnsDomainIs(host, ".cq.com")
|| dnsDomainIs(host, ".grolier.com")
|| dnsDomainIs(host, ".groveart.com")
|| dnsDomainIs(host, ".groveopera.com")
|| dnsDomainIs(host, ".fsonline.com")
|| dnsDomainIs(host, ".carl.org")
|| dnsDomainIs(host, ".newslibrary.com")
|| dnsDomainIs(host, ".pioneerplanet.com")
|| dnsDomainIs(host, ".startribune.com")
|| dnsDomainIs(host, ".poemfinder.com")
|| dnsDomainIs(host, ".umi.com")
|| dnsDomainIs(host, ".referenceusa.com")
|| dnsDomainIs(host, ".sirs.com")
|| dnsDomainIs(host, ".krmediastream.com")
|| dnsDomainIs(host, ".gale.com")
|| dnsDomainIs(host, ".galenet.com")
|| dnsDomainIs(host, ".galegroup.com")
|| dnsDomainIs(host, ".facts.com")
|| dnsDomainIs(host, ".eb.com")
|| dnsDomainIs(host, ".worldbookonline.com")
|| dnsDomainIs(host, ".galegroup.com")
|| dnsDomainIs(host, ".accessscience.com")
|| dnsDomainIs(host, ".booksinprint.com")
|| dnsDomainIs(host, ".infolearning.com")
|| dnsDomainIs(host, ".standardpoor.com")
// image servers
|| dnsDomainIs(host, ".akamaitech.net")
|| dnsDomainIs(host, ".akamai.net")
|| dnsDomainIs(host, ".yimg.com")
|| dnsDomainIs(host, ".imgis.com")
|| dnsDomainIs(host, ".ibsys.com")
// KidsClick-linked kids search engines
|| dnsDomainIs(host, ".edview.com")
|| dnsDomainIs(host, ".searchopolis.com")
|| dnsDomainIs(host, ".onekey.com")
|| dnsDomainIs(host, ".askjeeves.com")
// Non-subscription Reference Tools URLs from the RecWebSites DBData table
|| dnsDomainIs(host, "www.cnn.com")
|| dnsDomainIs(host, "www.emulateme.com")
|| dnsDomainIs(host, "terraserver.microsoft.com")
|| dnsDomainIs(host, "www.theodora.com")
|| dnsDomainIs(host, "www.3datlas.com")
|| dnsDomainIs(host, "www.infoplease.com")
|| dnsDomainIs(host, "www.switchboard.com")
|| dnsDomainIs(host, "www.bartleby.com")
|| dnsDomainIs(host, "www.mn-politics.com")
|| dnsDomainIs(host, "www.thesaurus.com")
|| dnsDomainIs(host, "www.usnews.com")
|| dnsDomainIs(host, "www.petersons.com")
|| dnsDomainIs(host, "www.collegenet.com")
|| dnsDomainIs(host, "www.m-w.com")
|| dnsDomainIs(host, "clever.net")
|| dnsDomainIs(host, "maps.expedia.com")
|| dnsDomainIs(host, "www.CollegeEdge.com")
|| dnsDomainIs(host, "www.homeworkcentral.com")
|| dnsDomainIs(host, "www.studyweb.com")
|| dnsDomainIs(host, "www.mnpro.com")
// custom URLs for local and other access
|| dnsDomainIs(host, ".dsdukes.com")
|| dnsDomainIs(host, ".spsaints.com")
|| dnsDomainIs(host, ".mnzoo.com")
|| dnsDomainIs(host, ".realaudio.com")
|| dnsDomainIs(host, ".co.hennepin.mn.us")
|| dnsDomainIs(host, ".gov")
|| dnsDomainIs(host, ".org")
|| dnsDomainIs(host, ".edu")
|| dnsDomainIs(host, ".fox29.com")
|| dnsDomainIs(host, ".wcco.com")
|| dnsDomainIs(host, ".kstp.com")
|| dnsDomainIs(host, ".kmsp.com")
|| dnsDomainIs(host, ".kare11.com")
|| dnsDomainIs(host, ".macromedia.com")
|| dnsDomainIs(host, ".shockwave.com")
|| dnsDomainIs(host, ".wwf.com")
|| dnsDomainIs(host, ".wwfsuperstars.com")
|| dnsDomainIs(host, ".summerslam.com")
|| dnsDomainIs(host, ".yahooligans.com")
|| dnsDomainIs(host, ".mhoob.com")
|| dnsDomainIs(host, "www.hmonginternet.com")
|| dnsDomainIs(host, "www.hmongonline.com")
|| dnsDomainIs(host, ".yahoo.com")
|| dnsDomainIs(host, ".pokemon.com")
|| dnsDomainIs(host, ".bet.com")
|| dnsDomainIs(host, ".smallworld.com")
|| dnsDomainIs(host, ".cartoonnetwork.com")
|| dnsDomainIs(host, ".carmensandiego.com")
|| dnsDomainIs(host, ".disney.com")
|| dnsDomainIs(host, ".powerpuffgirls.com")
|| dnsDomainIs(host, ".aol.com")
// Smithsonian
|| dnsDomainIs(host, "160.111.100.190")
// Hotmail
|| dnsDomainIs(host, ".passport.com")
|| dnsDomainIs(host, ".hotmail.com")
|| dnsDomainIs(host, "216.33.236.24")
|| dnsDomainIs(host, "216.32.182.251")
|| dnsDomainIs(host, ".hotmail.msn.com")
// K12 schools
|| dnsDomainIs(host, ".k12.al.us")
|| dnsDomainIs(host, ".k12.ak.us")
|| dnsDomainIs(host, ".k12.ar.us")
|| dnsDomainIs(host, ".k12.az.us")
|| dnsDomainIs(host, ".k12.ca.us")
|| dnsDomainIs(host, ".k12.co.us")
|| dnsDomainIs(host, ".k12.ct.us")
|| dnsDomainIs(host, ".k12.dc.us")
|| dnsDomainIs(host, ".k12.de.us")
|| dnsDomainIs(host, ".k12.fl.us")
|| dnsDomainIs(host, ".k12.ga.us")
|| dnsDomainIs(host, ".k12.hi.us")
|| dnsDomainIs(host, ".k12.id.us")
|| dnsDomainIs(host, ".k12.il.us")
|| dnsDomainIs(host, ".k12.in.us")
|| dnsDomainIs(host, ".k12.ia.us")
|| dnsDomainIs(host, ".k12.ks.us")
|| dnsDomainIs(host, ".k12.ky.us")
|| dnsDomainIs(host, ".k12.la.us")
|| dnsDomainIs(host, ".k12.me.us")
|| dnsDomainIs(host, ".k12.md.us")
|| dnsDomainIs(host, ".k12.ma.us")
|| dnsDomainIs(host, ".k12.mi.us")
|| dnsDomainIs(host, ".k12.mn.us")
|| dnsDomainIs(host, ".k12.ms.us")
|| dnsDomainIs(host, ".k12.mo.us")
|| dnsDomainIs(host, ".k12.mt.us")
|| dnsDomainIs(host, ".k12.ne.us")
|| dnsDomainIs(host, ".k12.nv.us")
|| dnsDomainIs(host, ".k12.nh.us")
|| dnsDomainIs(host, ".k12.nj.us")
|| dnsDomainIs(host, ".k12.nm.us")
|| dnsDomainIs(host, ".k12.ny.us")
|| dnsDomainIs(host, ".k12.nc.us")
|| dnsDomainIs(host, ".k12.nd.us")
|| dnsDomainIs(host, ".k12.oh.us")
|| dnsDomainIs(host, ".k12.ok.us")
|| dnsDomainIs(host, ".k12.or.us")
|| dnsDomainIs(host, ".k12.pa.us")
|| dnsDomainIs(host, ".k12.ri.us")
|| dnsDomainIs(host, ".k12.sc.us")
|| dnsDomainIs(host, ".k12.sd.us")
|| dnsDomainIs(host, ".k12.tn.us")
|| dnsDomainIs(host, ".k12.tx.us")
|| dnsDomainIs(host, ".k12.ut.us")
|| dnsDomainIs(host, ".k12.vt.us")
|| dnsDomainIs(host, ".k12.va.us")
|| dnsDomainIs(host, ".k12.wa.us")
|| dnsDomainIs(host, ".k12.wv.us")
|| dnsDomainIs(host, ".k12.wi.us")
|| dnsDomainIs(host, ".k12.wy.us")
// U.S. Libraries
|| dnsDomainIs(host, ".lib.al.us")
|| dnsDomainIs(host, ".lib.ak.us")
|| dnsDomainIs(host, ".lib.ar.us")
|| dnsDomainIs(host, ".lib.az.us")
|| dnsDomainIs(host, ".lib.ca.us")
|| dnsDomainIs(host, ".lib.co.us")
|| dnsDomainIs(host, ".lib.ct.us")
|| dnsDomainIs(host, ".lib.dc.us")
|| dnsDomainIs(host, ".lib.de.us")
|| dnsDomainIs(host, ".lib.fl.us")
|| dnsDomainIs(host, ".lib.ga.us")
|| dnsDomainIs(host, ".lib.hi.us")
|| dnsDomainIs(host, ".lib.id.us")
|| dnsDomainIs(host, ".lib.il.us")
|| dnsDomainIs(host, ".lib.in.us")
|| dnsDomainIs(host, ".lib.ia.us")
|| dnsDomainIs(host, ".lib.ks.us")
|| dnsDomainIs(host, ".lib.ky.us")
|| dnsDomainIs(host, ".lib.la.us")
|| dnsDomainIs(host, ".lib.me.us")
|| dnsDomainIs(host, ".lib.md.us")
|| dnsDomainIs(host, ".lib.ma.us")
|| dnsDomainIs(host, ".lib.mi.us")
|| dnsDomainIs(host, ".lib.mn.us")
|| dnsDomainIs(host, ".lib.ms.us")
|| dnsDomainIs(host, ".lib.mo.us")
|| dnsDomainIs(host, ".lib.mt.us")
|| dnsDomainIs(host, ".lib.ne.us")
|| dnsDomainIs(host, ".lib.nv.us")
|| dnsDomainIs(host, ".lib.nh.us")
|| dnsDomainIs(host, ".lib.nj.us")
|| dnsDomainIs(host, ".lib.nm.us")
|| dnsDomainIs(host, ".lib.ny.us")
|| dnsDomainIs(host, ".lib.nc.us")
|| dnsDomainIs(host, ".lib.nd.us")
|| dnsDomainIs(host, ".lib.oh.us")
|| dnsDomainIs(host, ".lib.ok.us")
|| dnsDomainIs(host, ".lib.or.us")
|| dnsDomainIs(host, ".lib.pa.us")
|| dnsDomainIs(host, ".lib.ri.us")
|| dnsDomainIs(host, ".lib.sc.us")
|| dnsDomainIs(host, ".lib.sd.us")
|| dnsDomainIs(host, ".lib.tn.us")
|| dnsDomainIs(host, ".lib.tx.us")
|| dnsDomainIs(host, ".lib.ut.us")
|| dnsDomainIs(host, ".lib.vt.us")
|| dnsDomainIs(host, ".lib.va.us")
|| dnsDomainIs(host, ".lib.wa.us")
|| dnsDomainIs(host, ".lib.wv.us")
|| dnsDomainIs(host, ".lib.wi.us")
|| dnsDomainIs(host, ".lib.wy.us")
// U.S. Cities
|| dnsDomainIs(host, ".ci.al.us")
|| dnsDomainIs(host, ".ci.ak.us")
|| dnsDomainIs(host, ".ci.ar.us")
|| dnsDomainIs(host, ".ci.az.us")
|| dnsDomainIs(host, ".ci.ca.us")
|| dnsDomainIs(host, ".ci.co.us")
|| dnsDomainIs(host, ".ci.ct.us")
|| dnsDomainIs(host, ".ci.dc.us")
|| dnsDomainIs(host, ".ci.de.us")
|| dnsDomainIs(host, ".ci.fl.us")
|| dnsDomainIs(host, ".ci.ga.us")
|| dnsDomainIs(host, ".ci.hi.us")
|| dnsDomainIs(host, ".ci.id.us")
|| dnsDomainIs(host, ".ci.il.us")
|| dnsDomainIs(host, ".ci.in.us")
|| dnsDomainIs(host, ".ci.ia.us")
|| dnsDomainIs(host, ".ci.ks.us")
|| dnsDomainIs(host, ".ci.ky.us")
|| dnsDomainIs(host, ".ci.la.us")
|| dnsDomainIs(host, ".ci.me.us")
|| dnsDomainIs(host, ".ci.md.us")
|| dnsDomainIs(host, ".ci.ma.us")
|| dnsDomainIs(host, ".ci.mi.us")
|| dnsDomainIs(host, ".ci.mn.us")
|| dnsDomainIs(host, ".ci.ms.us")
|| dnsDomainIs(host, ".ci.mo.us")
|| dnsDomainIs(host, ".ci.mt.us")
|| dnsDomainIs(host, ".ci.ne.us")
|| dnsDomainIs(host, ".ci.nv.us")
|| dnsDomainIs(host, ".ci.nh.us")
|| dnsDomainIs(host, ".ci.nj.us")
|| dnsDomainIs(host, ".ci.nm.us")
|| dnsDomainIs(host, ".ci.ny.us")
|| dnsDomainIs(host, ".ci.nc.us")
|| dnsDomainIs(host, ".ci.nd.us")
|| dnsDomainIs(host, ".ci.oh.us")
|| dnsDomainIs(host, ".ci.ok.us")
|| dnsDomainIs(host, ".ci.or.us")
|| dnsDomainIs(host, ".ci.pa.us")
|| dnsDomainIs(host, ".ci.ri.us")
|| dnsDomainIs(host, ".ci.sc.us")
|| dnsDomainIs(host, ".ci.sd.us")
|| dnsDomainIs(host, ".ci.tn.us")
|| dnsDomainIs(host, ".ci.tx.us")
|| dnsDomainIs(host, ".ci.ut.us")
|| dnsDomainIs(host, ".ci.vt.us")
|| dnsDomainIs(host, ".ci.va.us")
|| dnsDomainIs(host, ".ci.wa.us")
|| dnsDomainIs(host, ".ci.wv.us")
|| dnsDomainIs(host, ".ci.wi.us")
|| dnsDomainIs(host, ".ci.wy.us")
// U.S. Counties
|| dnsDomainIs(host, ".co.al.us")
|| dnsDomainIs(host, ".co.ak.us")
|| dnsDomainIs(host, ".co.ar.us")
|| dnsDomainIs(host, ".co.az.us")
|| dnsDomainIs(host, ".co.ca.us")
|| dnsDomainIs(host, ".co.co.us")
|| dnsDomainIs(host, ".co.ct.us")
|| dnsDomainIs(host, ".co.dc.us")
|| dnsDomainIs(host, ".co.de.us")
|| dnsDomainIs(host, ".co.fl.us")
|| dnsDomainIs(host, ".co.ga.us")
|| dnsDomainIs(host, ".co.hi.us")
|| dnsDomainIs(host, ".co.id.us")
|| dnsDomainIs(host, ".co.il.us")
|| dnsDomainIs(host, ".co.in.us")
|| dnsDomainIs(host, ".co.ia.us")
|| dnsDomainIs(host, ".co.ks.us")
|| dnsDomainIs(host, ".co.ky.us")
|| dnsDomainIs(host, ".co.la.us")
|| dnsDomainIs(host, ".co.me.us")
|| dnsDomainIs(host, ".co.md.us")
|| dnsDomainIs(host, ".co.ma.us")
|| dnsDomainIs(host, ".co.mi.us")
|| dnsDomainIs(host, ".co.mn.us")
|| dnsDomainIs(host, ".co.ms.us")
|| dnsDomainIs(host, ".co.mo.us")
|| dnsDomainIs(host, ".co.mt.us")
|| dnsDomainIs(host, ".co.ne.us")
|| dnsDomainIs(host, ".co.nv.us")
|| dnsDomainIs(host, ".co.nh.us")
|| dnsDomainIs(host, ".co.nj.us")
|| dnsDomainIs(host, ".co.nm.us")
|| dnsDomainIs(host, ".co.ny.us")
|| dnsDomainIs(host, ".co.nc.us")
|| dnsDomainIs(host, ".co.nd.us")
|| dnsDomainIs(host, ".co.oh.us")
|| dnsDomainIs(host, ".co.ok.us")
|| dnsDomainIs(host, ".co.or.us")
|| dnsDomainIs(host, ".co.pa.us")
|| dnsDomainIs(host, ".co.ri.us")
|| dnsDomainIs(host, ".co.sc.us")
|| dnsDomainIs(host, ".co.sd.us")
|| dnsDomainIs(host, ".co.tn.us")
|| dnsDomainIs(host, ".co.tx.us")
|| dnsDomainIs(host, ".co.ut.us")
|| dnsDomainIs(host, ".co.vt.us")
|| dnsDomainIs(host, ".co.va.us")
|| dnsDomainIs(host, ".co.wa.us")
|| dnsDomainIs(host, ".co.wv.us")
|| dnsDomainIs(host, ".co.wi.us")
|| dnsDomainIs(host, ".co.wy.us")
// U.S. States
|| dnsDomainIs(host, ".state.al.us")
|| dnsDomainIs(host, ".state.ak.us")
|| dnsDomainIs(host, ".state.ar.us")
|| dnsDomainIs(host, ".state.az.us")
|| dnsDomainIs(host, ".state.ca.us")
|| dnsDomainIs(host, ".state.co.us")
|| dnsDomainIs(host, ".state.ct.us")
|| dnsDomainIs(host, ".state.dc.us")
|| dnsDomainIs(host, ".state.de.us")
|| dnsDomainIs(host, ".state.fl.us")
|| dnsDomainIs(host, ".state.ga.us")
|| dnsDomainIs(host, ".state.hi.us")
|| dnsDomainIs(host, ".state.id.us")
|| dnsDomainIs(host, ".state.il.us")
|| dnsDomainIs(host, ".state.in.us")
|| dnsDomainIs(host, ".state.ia.us")
|| dnsDomainIs(host, ".state.ks.us")
|| dnsDomainIs(host, ".state.ky.us")
|| dnsDomainIs(host, ".state.la.us")
|| dnsDomainIs(host, ".state.me.us")
|| dnsDomainIs(host, ".state.md.us")
|| dnsDomainIs(host, ".state.ma.us")
|| dnsDomainIs(host, ".state.mi.us")
|| dnsDomainIs(host, ".state.mn.us")
|| dnsDomainIs(host, ".state.ms.us")
|| dnsDomainIs(host, ".state.mo.us")
|| dnsDomainIs(host, ".state.mt.us")
|| dnsDomainIs(host, ".state.ne.us")
|| dnsDomainIs(host, ".state.nv.us")
|| dnsDomainIs(host, ".state.nh.us")
|| dnsDomainIs(host, ".state.nj.us")
|| dnsDomainIs(host, ".state.nm.us")
|| dnsDomainIs(host, ".state.ny.us")
|| dnsDomainIs(host, ".state.nc.us")
|| dnsDomainIs(host, ".state.nd.us")
|| dnsDomainIs(host, ".state.oh.us")
|| dnsDomainIs(host, ".state.ok.us")
|| dnsDomainIs(host, ".state.or.us")
|| dnsDomainIs(host, ".state.pa.us")
|| dnsDomainIs(host, ".state.ri.us")
|| dnsDomainIs(host, ".state.sc.us")
|| dnsDomainIs(host, ".state.sd.us")
|| dnsDomainIs(host, ".state.tn.us")
|| dnsDomainIs(host, ".state.tx.us")
|| dnsDomainIs(host, ".state.ut.us")
|| dnsDomainIs(host, ".state.vt.us")
|| dnsDomainIs(host, ".state.va.us")
|| dnsDomainIs(host, ".state.wa.us")
|| dnsDomainIs(host, ".state.wv.us")
|| dnsDomainIs(host, ".state.wi.us")
|| dnsDomainIs(host, ".state.wy.us")
// KidsClick URLs
|| dnsDomainIs(host, "12.16.163.163")
|| dnsDomainIs(host, "128.59.173.136")
|| dnsDomainIs(host, "165.112.78.61")
|| dnsDomainIs(host, "216.55.23.140")
|| dnsDomainIs(host, "63.111.53.150")
|| dnsDomainIs(host, "64.94.206.8")
|| dnsDomainIs(host, "abc.go.com")
|| dnsDomainIs(host, "acmepet.petsmart.com")
|| dnsDomainIs(host, "adver-net.com")
|| dnsDomainIs(host, "aint-it-cool-news.com")
|| dnsDomainIs(host, "akidsheart.com")
|| dnsDomainIs(host, "alabanza.com")
|| dnsDomainIs(host, "allerdays.com")
|| dnsDomainIs(host, "allgame.com")
|| dnsDomainIs(host, "allowancenet.com")
|| dnsDomainIs(host, "amish-heartland.com")
|| dnsDomainIs(host, "ancienthistory.about.com")
|| dnsDomainIs(host, "animals.about.com")
|| dnsDomainIs(host, "antenna.nl")
|| dnsDomainIs(host, "arcweb.sos.state.or.us")
|| dnsDomainIs(host, "artistmummer.homestead.com")
|| dnsDomainIs(host, "artists.vh1.com")
|| dnsDomainIs(host, "arts.lausd.k12.ca.us")
|| dnsDomainIs(host, "asiatravel.com")
|| dnsDomainIs(host, "asterius.com")
|| dnsDomainIs(host, "atlas.gc.ca")
|| dnsDomainIs(host, "atschool.eduweb.co.uk")
|| dnsDomainIs(host, "ayya.pd.net")
|| dnsDomainIs(host, "babelfish.altavista.com")
|| dnsDomainIs(host, "babylon5.warnerbros.com")
|| dnsDomainIs(host, "banzai.neosoft.com")
|| dnsDomainIs(host, "barneyonline.com")
|| dnsDomainIs(host, "baroque-music.com")
|| dnsDomainIs(host, "barsoom.msss.com")
|| dnsDomainIs(host, "baseball-almanac.com")
|| dnsDomainIs(host, "bcadventure.com")
|| dnsDomainIs(host, "beadiecritters.hosting4less.com")
|| dnsDomainIs(host, "beverlyscrafts.com")
|| dnsDomainIs(host, "biology.about.com")
|| dnsDomainIs(host, "birding.about.com")
|| dnsDomainIs(host, "boatsafe.com")
|| dnsDomainIs(host, "bombpop.com")
|| dnsDomainIs(host, "boulter.com")
|| dnsDomainIs(host, "bright-ideas-software.com")
|| dnsDomainIs(host, "buckman.pps.k12.or.us")
|| dnsDomainIs(host, "buffalobills.com")
|| dnsDomainIs(host, "bvsd.k12.co.us")
|| dnsDomainIs(host, "cagle.slate.msn.com")
|| dnsDomainIs(host, "calc.entisoft.com")
|| dnsDomainIs(host, "canada.gc.ca")
|| dnsDomainIs(host, "candleandsoap.about.com")
|| dnsDomainIs(host, "caselaw.lp.findlaw.com")
|| dnsDomainIs(host, "catalog.com")
|| dnsDomainIs(host, "catalog.socialstudies.com")
|| dnsDomainIs(host, "cavern.com")
|| dnsDomainIs(host, "cbs.sportsline.com")
|| dnsDomainIs(host, "cc.matsuyama-u.ac.jp")
|| dnsDomainIs(host, "celt.net")
|| dnsDomainIs(host, "cgfa.kelloggcreek.com")
|| dnsDomainIs(host, "channel4000.com")
|| dnsDomainIs(host, "chess.delorie.com")
|| dnsDomainIs(host, "chess.liveonthenet.com")
|| dnsDomainIs(host, "childfun.com")
|| dnsDomainIs(host, "christmas.com")
|| dnsDomainIs(host, "citystar.com")
|| dnsDomainIs(host, "claim.goldrush.com")
|| dnsDomainIs(host, "clairerosemaryjane.com")
|| dnsDomainIs(host, "clevermedia.com")
|| dnsDomainIs(host, "cobblestonepub.com")
|| dnsDomainIs(host, "codebrkr.infopages.net")
|| dnsDomainIs(host, "colitz.com")
|| dnsDomainIs(host, "collections.ic.gc.ca")
|| dnsDomainIs(host, "coloquio.com")
|| dnsDomainIs(host, "come.to")
|| dnsDomainIs(host, "coombs.anu.edu.au")
|| dnsDomainIs(host, "crafterscommunity.com")
|| dnsDomainIs(host, "craftsforkids.about.com")
|| dnsDomainIs(host, "creativity.net")
|| dnsDomainIs(host, "cslewis.drzeus.net")
|| dnsDomainIs(host, "cust.idl.com.au")
|| dnsDomainIs(host, "cvs.anu.edu.au")
|| dnsDomainIs(host, "cybersleuth-kids.com")
|| dnsDomainIs(host, "cybertown.com")
|| dnsDomainIs(host, "darkfish.com")
|| dnsDomainIs(host, "datadragon.com")
|| dnsDomainIs(host, "davesite.com")
|| dnsDomainIs(host, "dbertens.www.cistron.nl")
|| dnsDomainIs(host, "detnews.com")
|| dnsDomainIs(host, "dhr.dos.state.fl.us")
|| dnsDomainIs(host, "dialspace.dial.pipex.com")
|| dnsDomainIs(host, "dictionaries.travlang.com")
|| dnsDomainIs(host, "disney.go.com")
|| dnsDomainIs(host, "disneyland.disney.go.com")
|| dnsDomainIs(host, "district.gresham.k12.or.us")
|| dnsDomainIs(host, "dmarie.com")
|| dnsDomainIs(host, "dreamwater.com")
|| dnsDomainIs(host, "duke.fuse.net")
|| dnsDomainIs(host, "earlyamerica.com")
|| dnsDomainIs(host, "earthsky.com")
|| dnsDomainIs(host, "easyweb.easynet.co.uk")
|| dnsDomainIs(host, "ecards1.bansheeweb.com")
|| dnsDomainIs(host, "edugreen.teri.res.in")
|| dnsDomainIs(host, "edwardlear.tripod.com")
|| dnsDomainIs(host, "eelink.net")
|| dnsDomainIs(host, "elizabethsings.com")
|| dnsDomainIs(host, "enature.com")
|| dnsDomainIs(host, "encarta.msn.com")
|| dnsDomainIs(host, "endangeredspecie.com")
|| dnsDomainIs(host, "enterprise.america.com")
|| dnsDomainIs(host, "ericae.net")
|| dnsDomainIs(host, "esl.about.com")
|| dnsDomainIs(host, "eveander.com")
|| dnsDomainIs(host, "exn.ca")
|| dnsDomainIs(host, "fallscam.niagara.com")
|| dnsDomainIs(host, "family.go.com")
|| dnsDomainIs(host, "family2.go.com")
|| dnsDomainIs(host, "familyeducation.com")
|| dnsDomainIs(host, "finditquick.com")
|| dnsDomainIs(host, "fln-bma.yazigi.com.br")
|| dnsDomainIs(host, "fln-con.yazigi.com.br")
|| dnsDomainIs(host, "food.epicurious.com")
|| dnsDomainIs(host, "forums.sympatico.ca")
|| dnsDomainIs(host, "fotw.vexillum.com")
|| dnsDomainIs(host, "fox.nstn.ca")
|| dnsDomainIs(host, "framingham.com")
|| dnsDomainIs(host, "freevote.com")
|| dnsDomainIs(host, "freeweb.pdq.net")
|| dnsDomainIs(host, "games.yahoo.com")
|| dnsDomainIs(host, "gardening.sierrahome.com")
|| dnsDomainIs(host, "gardenofpraise.com")
|| dnsDomainIs(host, "gcclearn.gcc.cc.va.us")
|| dnsDomainIs(host, "genealogytoday.com")
|| dnsDomainIs(host, "genesis.ne.mediaone.net")
|| dnsDomainIs(host, "geniefind.com")
|| dnsDomainIs(host, "geography.about.com")
|| dnsDomainIs(host, "gf.state.wy.us")
|| dnsDomainIs(host, "gi.grolier.com")
|| dnsDomainIs(host, "golf.com")
|| dnsDomainIs(host, "greatseal.com")
|| dnsDomainIs(host, "guardians.net")
|| dnsDomainIs(host, "hamlet.hypermart.net")
|| dnsDomainIs(host, "happypuppy.com")
|| dnsDomainIs(host, "harcourt.fsc.follett.com")
|| dnsDomainIs(host, "haringkids.com")
|| dnsDomainIs(host, "harrietmaysavitz.com")
|| dnsDomainIs(host, "harrypotter.warnerbros.com")
|| dnsDomainIs(host, "hca.gilead.org.il")
|| dnsDomainIs(host, "header.future.easyspace.com")
|| dnsDomainIs(host, "historymedren.about.com")
|| dnsDomainIs(host, "home.att.net")
|| dnsDomainIs(host, "home.austin.rr.com")
|| dnsDomainIs(host, "home.capu.net")
|| dnsDomainIs(host, "home.cfl.rr.com")
|| dnsDomainIs(host, "home.clara.net")
|| dnsDomainIs(host, "home.clear.net.nz")
|| dnsDomainIs(host, "home.earthlink.net")
|| dnsDomainIs(host, "home.eznet.net")
|| dnsDomainIs(host, "home.flash.net")
|| dnsDomainIs(host, "home.hiwaay.net")
|| dnsDomainIs(host, "home.hkstar.com")
|| dnsDomainIs(host, "home.ici.net")
|| dnsDomainIs(host, "home.inreach.com")
|| dnsDomainIs(host, "home.interlynx.net")
|| dnsDomainIs(host, "home.istar.ca")
|| dnsDomainIs(host, "home.mira.net")
|| dnsDomainIs(host, "home.nycap.rr.com")
|| dnsDomainIs(host, "home.online.no")
|| dnsDomainIs(host, "home.pb.net")
|| dnsDomainIs(host, "home2.pacific.net.sg")
|| dnsDomainIs(host, "homearts.com")
|| dnsDomainIs(host, "homepage.mac.com")
|| dnsDomainIs(host, "hometown.aol.com")
|| dnsDomainIs(host, "homiliesbyemail.com")
|| dnsDomainIs(host, "hotei.fix.co.jp")
|| dnsDomainIs(host, "hotwired.lycos.com")
|| dnsDomainIs(host, "hp.vector.co.jp")
|| dnsDomainIs(host, "hum.amu.edu.pl")
|| dnsDomainIs(host, "i-cias.com")
|| dnsDomainIs(host, "icatapults.freeservers.com")
|| dnsDomainIs(host, "ind.cioe.com")
|| dnsDomainIs(host, "info.ex.ac.uk")
|| dnsDomainIs(host, "infocan.gc.ca")
|| dnsDomainIs(host, "infoservice.gc.ca")
|| dnsDomainIs(host, "interoz.com")
|| dnsDomainIs(host, "ireland.iol.ie")
|| dnsDomainIs(host, "is.dal.ca")
|| dnsDomainIs(host, "itss.raytheon.com")
|| dnsDomainIs(host, "iul.com")
|| dnsDomainIs(host, "jameswhitcombriley.com")
|| dnsDomainIs(host, "jellieszone.com")
|| dnsDomainIs(host, "jordan.sportsline.com")
|| dnsDomainIs(host, "judyanddavid.com")
|| dnsDomainIs(host, "jurai.murdoch.edu.au")
|| dnsDomainIs(host, "just.about.com")
|| dnsDomainIs(host, "kayleigh.tierranet.com")
|| dnsDomainIs(host, "kcwingwalker.tripod.com")
|| dnsDomainIs(host, "kidexchange.about.com")
|| dnsDomainIs(host, "kids-world.colgatepalmolive.com")
|| dnsDomainIs(host, "kids.mysterynet.com")
|| dnsDomainIs(host, "kids.ot.com")
|| dnsDomainIs(host, "kidsartscrafts.about.com")
|| dnsDomainIs(host, "kidsastronomy.about.com")
|| dnsDomainIs(host, "kidscience.about.com")
|| dnsDomainIs(host, "kidscience.miningco.com")
|| dnsDomainIs(host, "kidscollecting.about.com")
|| dnsDomainIs(host, "kidsfun.co.uk")
|| dnsDomainIs(host, "kidsinternet.about.com")
|| dnsDomainIs(host, "kidslangarts.about.com")
|| dnsDomainIs(host, "kidspenpals.about.com")
|| dnsDomainIs(host, "kitecast.com")
|| dnsDomainIs(host, "knight.city.ba.k12.md.us")
|| dnsDomainIs(host, "kodak.com")
|| dnsDomainIs(host, "kwanzaa4kids.homestead.com")
|| dnsDomainIs(host, "lagos.africaonline.com")
|| dnsDomainIs(host, "lancearmstrong.com")
|| dnsDomainIs(host, "landru.i-link-2.net")
|| dnsDomainIs(host, "lang.nagoya-u.ac.jp")
|| dnsDomainIs(host, "lascala.milano.it")
|| dnsDomainIs(host, "latinoculture.about.com")
|| dnsDomainIs(host, "litcal.yasuda-u.ac.jp")
|| dnsDomainIs(host, "littlebit.com")
|| dnsDomainIs(host, "live.edventures.com")
|| dnsDomainIs(host, "look.net")
|| dnsDomainIs(host, "lycoskids.infoplease.com")
|| dnsDomainIs(host, "lynx.uio.no")
|| dnsDomainIs(host, "macdict.dict.mq.edu.au")
|| dnsDomainIs(host, "maori.culture.co.nz")
|| dnsDomainIs(host, "marktwain.about.com")
|| dnsDomainIs(host, "marktwain.miningco.com")
|| dnsDomainIs(host, "mars2030.net")
|| dnsDomainIs(host, "martin.parasitology.mcgill.ca")
|| dnsDomainIs(host, "martinlutherking.8m.com")
|| dnsDomainIs(host, "mastercollector.com")
|| dnsDomainIs(host, "mathcentral.uregina.ca")
|| dnsDomainIs(host, "members.aol.com")
|| dnsDomainIs(host, "members.carol.net")
|| dnsDomainIs(host, "members.cland.net")
|| dnsDomainIs(host, "members.cruzio.com")
|| dnsDomainIs(host, "members.easyspace.com")
|| dnsDomainIs(host, "members.eisa.net.au")
|| dnsDomainIs(host, "members.home.net")
|| dnsDomainIs(host, "members.iinet.net.au")
|| dnsDomainIs(host, "members.nbci.com")
|| dnsDomainIs(host, "members.ozemail.com.au")
|| dnsDomainIs(host, "members.surfsouth.com")
|| dnsDomainIs(host, "members.theglobe.com")
|| dnsDomainIs(host, "members.tripod.com")
|| dnsDomainIs(host, "mexplaza.udg.mx")
|| dnsDomainIs(host, "mgfx.com")
|| dnsDomainIs(host, "microimg.com")
|| dnsDomainIs(host, "midusa.net")
|| dnsDomainIs(host, "mildan.com")
|| dnsDomainIs(host, "millennianet.com")
|| dnsDomainIs(host, "mindbreakers.e-fun.nu")
|| dnsDomainIs(host, "missjanet.xs4all.nl")
|| dnsDomainIs(host, "mistral.culture.fr")
|| dnsDomainIs(host, "mobileation.com")
|| dnsDomainIs(host, "mrshowbiz.go.com")
|| dnsDomainIs(host, "ms.simplenet.com")
|| dnsDomainIs(host, "museum.gov.ns.ca")
|| dnsDomainIs(host, "music.excite.com")
|| dnsDomainIs(host, "musicfinder.yahoo.com")
|| dnsDomainIs(host, "my.freeway.net")
|| dnsDomainIs(host, "mytrains.com")
|| dnsDomainIs(host, "nativeauthors.com")
|| dnsDomainIs(host, "nba.com")
|| dnsDomainIs(host, "nch.ari.net")
|| dnsDomainIs(host, "neonpeach.tripod.com")
|| dnsDomainIs(host, "net.indra.com")
|| dnsDomainIs(host, "ngeorgia.com")
|| dnsDomainIs(host, "ngp.ngpc.state.ne.us")
|| dnsDomainIs(host, "nhd.heinle.com")
|| dnsDomainIs(host, "nick.com")
|| dnsDomainIs(host, "normandy.eb.com")
|| dnsDomainIs(host, "northshore.shore.net")
|| dnsDomainIs(host, "now2000.com")
|| dnsDomainIs(host, "npc.nunavut.ca")
|| dnsDomainIs(host, "ns2.carib-link.net")
|| dnsDomainIs(host, "ntl.sympatico.ca")
|| dnsDomainIs(host, "oceanographer.navy.mil")
|| dnsDomainIs(host, "oddens.geog.uu.nl")
|| dnsDomainIs(host, "officialcitysites.com")
|| dnsDomainIs(host, "oneida-nation.net")
|| dnsDomainIs(host, "onlinegeorgia.com")
|| dnsDomainIs(host, "originator_2.tripod.com")
|| dnsDomainIs(host, "ortech-engr.com")
|| dnsDomainIs(host, "osage.voorhees.k12.nj.us")
|| dnsDomainIs(host, "osiris.sund.ac.uk")
|| dnsDomainIs(host, "ourworld.compuserve.com")
|| dnsDomainIs(host, "outdoorphoto.com")
|| dnsDomainIs(host, "pages.map.com")
|| dnsDomainIs(host, "pages.prodigy.com")
|| dnsDomainIs(host, "pages.prodigy.net")
|| dnsDomainIs(host, "pages.tca.net")
|| dnsDomainIs(host, "parcsafari.qc.ca")
|| dnsDomainIs(host, "parenthoodweb.com")
|| dnsDomainIs(host, "pathfinder.com")
|| dnsDomainIs(host, "people.clarityconnect.com")
|| dnsDomainIs(host, "people.enternet.com.au")
|| dnsDomainIs(host, "people.ne.mediaone.net")
|| dnsDomainIs(host, "phonics.jazzles.com")
|| dnsDomainIs(host, "pibburns.com")
|| dnsDomainIs(host, "pilgrims.net")
|| dnsDomainIs(host, "pinenet.com")
|| dnsDomainIs(host, "place.scholastic.com")
|| dnsDomainIs(host, "playground.kodak.com")
|| dnsDomainIs(host, "politicalgraveyard.com")
|| dnsDomainIs(host, "polk.ga.net")
|| dnsDomainIs(host, "pompstory.home.mindspring.com")
|| dnsDomainIs(host, "popularmechanics.com")
|| dnsDomainIs(host, "projects.edtech.sandi.net")
|| dnsDomainIs(host, "psyche.usno.navy.mil")
|| dnsDomainIs(host, "pubweb.parc.xerox.com")
|| dnsDomainIs(host, "puzzlemaker.school.discovery.com")
|| dnsDomainIs(host, "quest.classroom.com")
|| dnsDomainIs(host, "quilting.about.com")
|| dnsDomainIs(host, "rabbitmoon.home.mindspring.com")
|| dnsDomainIs(host, "radio.cbc.ca")
|| dnsDomainIs(host, "rats2u.com")
|| dnsDomainIs(host, "rbcm1.rbcm.gov.bc.ca")
|| dnsDomainIs(host, "readplay.com")
|| dnsDomainIs(host, "recipes4children.homestead.com")
|| dnsDomainIs(host, "redsox.com")
|| dnsDomainIs(host, "renaissance.district96.k12.il.us")
|| dnsDomainIs(host, "rhyme.lycos.com")
|| dnsDomainIs(host, "rhythmweb.com")
|| dnsDomainIs(host, "riverresource.com")
|| dnsDomainIs(host, "rockhoundingar.com")
|| dnsDomainIs(host, "rockies.mlb.com")
|| dnsDomainIs(host, "rosecity.net")
|| dnsDomainIs(host, "rr-vs.informatik.uni-ulm.de")
|| dnsDomainIs(host, "rubens.anu.edu.au")
|| dnsDomainIs(host, "rummelplatz.uni-mannheim.de")
|| dnsDomainIs(host, "sandbox.xerox.com")
|| dnsDomainIs(host, "sarah.fredart.com")
|| dnsDomainIs(host, "schmidel.com")
|| dnsDomainIs(host, "scholastic.com")
|| dnsDomainIs(host, "school.discovery.com")
|| dnsDomainIs(host, "schoolcentral.com")
|| dnsDomainIs(host, "seattletimes.nwsource.com")
|| dnsDomainIs(host, "sericulum.com")
|| dnsDomainIs(host, "sf.airforce.com")
|| dnsDomainIs(host, "shop.usps.com")
|| dnsDomainIs(host, "showcase.netins.net")
|| dnsDomainIs(host, "sikids.com")
|| dnsDomainIs(host, "sites.huji.ac.il")
|| dnsDomainIs(host, "sjliving.com")
|| dnsDomainIs(host, "skullduggery.com")
|| dnsDomainIs(host, "skyways.lib.ks.us")
|| dnsDomainIs(host, "snowdaymovie.nick.com")
|| dnsDomainIs(host, "sosa21.hypermart.net")
|| dnsDomainIs(host, "soundamerica.com")
|| dnsDomainIs(host, "spaceboy.nasda.go.jp")
|| dnsDomainIs(host, "sports.nfl.com")
|| dnsDomainIs(host, "sportsillustrated.cnn.com")
|| dnsDomainIs(host, "starwars.hasbro.com")
|| dnsDomainIs(host, "statelibrary.dcr.state.nc.us")
|| dnsDomainIs(host, "streetplay.com")
|| dnsDomainIs(host, "sts.gsc.nrcan.gc.ca")
|| dnsDomainIs(host, "sunniebunniezz.com")
|| dnsDomainIs(host, "sunsite.nus.edu.sg")
|| dnsDomainIs(host, "sunsite.sut.ac.jp")
|| dnsDomainIs(host, "superm.bart.nl")
|| dnsDomainIs(host, "surf.to")
|| dnsDomainIs(host, "svinet2.fs.fed.us")
|| dnsDomainIs(host, "swiminfo.com")
|| dnsDomainIs(host, "tabletennis.about.com")
|| dnsDomainIs(host, "teacher.scholastic.com")
|| dnsDomainIs(host, "theforce.net")
|| dnsDomainIs(host, "thejessicas.homestead.com")
|| dnsDomainIs(host, "themes.editthispage.com")
|| dnsDomainIs(host, "theory.uwinnipeg.ca")
|| dnsDomainIs(host, "theshadowlands.net")
|| dnsDomainIs(host, "thinks.com")
|| dnsDomainIs(host, "thryomanes.tripod.com")
|| dnsDomainIs(host, "time_zone.tripod.com")
|| dnsDomainIs(host, "titania.cobuild.collins.co.uk")
|| dnsDomainIs(host, "torre.duomo.pisa.it")
|| dnsDomainIs(host, "touregypt.net")
|| dnsDomainIs(host, "toycollecting.about.com")
|| dnsDomainIs(host, "trace.ntu.ac.uk")
|| dnsDomainIs(host, "travelwithkids.about.com")
|| dnsDomainIs(host, "tukids.tucows.com")
|| dnsDomainIs(host, "tv.yahoo.com")
|| dnsDomainIs(host, "tycho.usno.navy.mil")
|| dnsDomainIs(host, "ubl.artistdirect.com")
|| dnsDomainIs(host, "uk-pages.net")
|| dnsDomainIs(host, "ukraine.uazone.net")
|| dnsDomainIs(host, "unmuseum.mus.pa.us")
|| dnsDomainIs(host, "us.imdb.com")
|| dnsDomainIs(host, "userpage.chemie.fu-berlin.de")
|| dnsDomainIs(host, "userpage.fu-berlin.de")
|| dnsDomainIs(host, "userpages.aug.com")
|| dnsDomainIs(host, "users.aol.com")
|| dnsDomainIs(host, "users.bigpond.net.au")
|| dnsDomainIs(host, "users.breathemail.net")
|| dnsDomainIs(host, "users.erols.com")
|| dnsDomainIs(host, "users.imag.net")
|| dnsDomainIs(host, "users.inetw.net")
|| dnsDomainIs(host, "users.massed.net")
|| dnsDomainIs(host, "users.skynet.be")
|| dnsDomainIs(host, "users.uniserve.com")
|| dnsDomainIs(host, "venus.spaceports.com")
|| dnsDomainIs(host, "vgstrategies.about.com")
|| dnsDomainIs(host, "victorian.fortunecity.com")
|| dnsDomainIs(host, "vilenski.com")
|| dnsDomainIs(host, "village.infoweb.ne.jp")
|| dnsDomainIs(host, "virtual.finland.fi")
|| dnsDomainIs(host, "vrml.fornax.hu")
|| dnsDomainIs(host, "vvv.com")
|| dnsDomainIs(host, "w1.xrefer.com")
|| dnsDomainIs(host, "w3.one.net")
|| dnsDomainIs(host, "w3.rz-berlin.mpg.de")
|| dnsDomainIs(host, "w3.trib.com")
|| dnsDomainIs(host, "wallofsound.go.com")
|| dnsDomainIs(host, "web.aimnet.com")
|| dnsDomainIs(host, "web.ccsd.k12.wy.us")
|| dnsDomainIs(host, "web.cs.ualberta.ca")
|| dnsDomainIs(host, "web.idirect.com")
|| dnsDomainIs(host, "web.kyoto-inet.or.jp")
|| dnsDomainIs(host, "web.macam98.ac.il")
|| dnsDomainIs(host, "web.massvacation.com")
|| dnsDomainIs(host, "web.one.net.au")
|| dnsDomainIs(host, "web.qx.net")
|| dnsDomainIs(host, "web.uvic.ca")
|| dnsDomainIs(host, "web2.airmail.net")
|| dnsDomainIs(host, "webcoast.com")
|| dnsDomainIs(host, "webgames.kalisto.com")
|| dnsDomainIs(host, "webhome.idirect.com")
|| dnsDomainIs(host, "webpages.homestead.com")
|| dnsDomainIs(host, "webrum.uni-mannheim.de")
|| dnsDomainIs(host, "webusers.anet-stl.com")
|| dnsDomainIs(host, "welcome.to")
|| dnsDomainIs(host, "wgntv.com")
|| dnsDomainIs(host, "whales.magna.com.au")
|| dnsDomainIs(host, "wildheart.com")
|| dnsDomainIs(host, "wilstar.net")
|| dnsDomainIs(host, "winter-wonderland.com")
|| dnsDomainIs(host, "women.com")
|| dnsDomainIs(host, "woodrow.mpls.frb.fed.us")
|| dnsDomainIs(host, "wordzap.com")
|| dnsDomainIs(host, "worldkids.net")
|| dnsDomainIs(host, "worldwideguide.net")
|| dnsDomainIs(host, "ww3.bay.k12.fl.us")
|| dnsDomainIs(host, "ww3.sportsline.com")
|| dnsDomainIs(host, "www-groups.dcs.st-and.ac.uk")
|| dnsDomainIs(host, "www-public.rz.uni-duesseldorf.de")
|| dnsDomainIs(host, "www.1stkids.com")
|| dnsDomainIs(host, "www.2020tech.com")
|| dnsDomainIs(host, "www.21stcenturytoys.com")
|| dnsDomainIs(host, "www.4adventure.com")
|| dnsDomainIs(host, "www.50states.com")
|| dnsDomainIs(host, "www.800padutch.com")
|| dnsDomainIs(host, "www.88.com")
|| dnsDomainIs(host, "www.a-better.com")
|| dnsDomainIs(host, "www.aaa.com.au")
|| dnsDomainIs(host, "www.aacca.com")
|| dnsDomainIs(host, "www.aalbc.com")
|| dnsDomainIs(host, "www.aardman.com")
|| dnsDomainIs(host, "www.aardvarkelectric.com")
|| dnsDomainIs(host, "www.aawc.com")
|| dnsDomainIs(host, "www.ababmx.com")
|| dnsDomainIs(host, "www.abbeville.com")
|| dnsDomainIs(host, "www.abc.net.au")
|| dnsDomainIs(host, "www.abcb.com")
|| dnsDomainIs(host, "www.abctooncenter.com")
|| dnsDomainIs(host, "www.about.ch")
|| dnsDomainIs(host, "www.accessart.org.uk")
|| dnsDomainIs(host, "www.accu.or.jp")
|| dnsDomainIs(host, "www.accuweather.com")
|| dnsDomainIs(host, "www.achuka.co.uk")
|| dnsDomainIs(host, "www.acmecity.com")
|| dnsDomainIs(host, "www.acorn-group.com")
|| dnsDomainIs(host, "www.acs.ucalgary.ca")
|| dnsDomainIs(host, "www.actden.com")
|| dnsDomainIs(host, "www.actionplanet.com")
|| dnsDomainIs(host, "www.activityvillage.co.uk")
|| dnsDomainIs(host, "www.actwin.com")
|| dnsDomainIs(host, "www.adequate.com")
|| dnsDomainIs(host, "www.adidas.com")
|| dnsDomainIs(host, "www.advent-calendars.com")
|| dnsDomainIs(host, "www.aegis.com")
|| dnsDomainIs(host, "www.af.mil")
|| dnsDomainIs(host, "www.africaindex.africainfo.no")
|| dnsDomainIs(host, "www.africam.com")
|| dnsDomainIs(host, "www.africancrafts.com")
|| dnsDomainIs(host, "www.aggressive.com")
|| dnsDomainIs(host, "www.aghines.com")
|| dnsDomainIs(host, "www.agirlsworld.com")
|| dnsDomainIs(host, "www.agora.stm.it")
|| dnsDomainIs(host, "www.agriculture.com")
|| dnsDomainIs(host, "www.aikidofaq.com")
|| dnsDomainIs(host, "www.ajkids.com")
|| dnsDomainIs(host, "www.akfkoala.gil.com.au")
|| dnsDomainIs(host, "www.akhlah.com")
|| dnsDomainIs(host, "www.alabamainfo.com")
|| dnsDomainIs(host, "www.aland.fi")
|| dnsDomainIs(host, "www.albion.com")
|| dnsDomainIs(host, "www.alcoholismhelp.com")
|| dnsDomainIs(host, "www.alcottweb.com")
|| dnsDomainIs(host, "www.alfanet.it")
|| dnsDomainIs(host, "www.alfy.com")
|| dnsDomainIs(host, "www.algebra-online.com")
|| dnsDomainIs(host, "www.alienexplorer.com")
|| dnsDomainIs(host, "www.aliensatschool.com")
|| dnsDomainIs(host, "www.all-links.com")
|| dnsDomainIs(host, "www.alldetroit.com")
|| dnsDomainIs(host, "www.allexperts.com")
|| dnsDomainIs(host, "www.allmixedup.com")
|| dnsDomainIs(host, "www.allmusic.com")
|| dnsDomainIs(host, "www.almanac.com")
|| dnsDomainIs(host, "www.almaz.com")
|| dnsDomainIs(host, "www.almondseed.com")
|| dnsDomainIs(host, "www.aloha.com")
|| dnsDomainIs(host, "www.aloha.net")
|| dnsDomainIs(host, "www.altonweb.com")
|| dnsDomainIs(host, "www.alyeska-pipe.com")
|| dnsDomainIs(host, "www.am-wood.com")
|| dnsDomainIs(host, "www.amazingadventure.com")
|| dnsDomainIs(host, "www.amazon.com")
|| dnsDomainIs(host, "www.americancheerleader.com")
|| dnsDomainIs(host, "www.americancowboy.com")
|| dnsDomainIs(host, "www.americangirl.com")
|| dnsDomainIs(host, "www.americanparknetwork.com")
|| dnsDomainIs(host, "www.americansouthwest.net")
|| dnsDomainIs(host, "www.americanwest.com")
|| dnsDomainIs(host, "www.ameritech.net")
|| dnsDomainIs(host, "www.amtexpo.com")
|| dnsDomainIs(host, "www.anbg.gov.au")
|| dnsDomainIs(host, "www.anc.org.za")
|| dnsDomainIs(host, "www.ancientegypt.co.uk")
|| dnsDomainIs(host, "www.angelfire.com")
|| dnsDomainIs(host, "www.angelsbaseball.com")
|| dnsDomainIs(host, "www.anholt.co.uk")
|| dnsDomainIs(host, "www.animabets.com")
|| dnsDomainIs(host, "www.animalnetwork.com")
|| dnsDomainIs(host, "www.animalpicturesarchive.com")
|| dnsDomainIs(host, "www.anime-genesis.com")
|| dnsDomainIs(host, "www.annefrank.com")
|| dnsDomainIs(host, "www.annefrank.nl")
|| dnsDomainIs(host, "www.annie75.com")
|| dnsDomainIs(host, "www.antbee.com")
|| dnsDomainIs(host, "www.antiquetools.com")
|| dnsDomainIs(host, "www.antiquetoy.com")
|| dnsDomainIs(host, "www.anzsbeg.org.au")
|| dnsDomainIs(host, "www.aol.com")
|| dnsDomainIs(host, "www.aone.com")
|| dnsDomainIs(host, "www.aphids.com")
|| dnsDomainIs(host, "www.apl.com")
|| dnsDomainIs(host, "www.aplusmath.com")
|| dnsDomainIs(host, "www.applebookshop.co.uk")
|| dnsDomainIs(host, "www.appropriatesoftware.com")
|| dnsDomainIs(host, "www.appukids.com")
|| dnsDomainIs(host, "www.april-joy.com")
|| dnsDomainIs(host, "www.arab.net")
|| dnsDomainIs(host, "www.aracnet.com")
|| dnsDomainIs(host, "www.arborday.com")
|| dnsDomainIs(host, "www.arcadevillage.com")
|| dnsDomainIs(host, "www.archiecomics.com")
|| dnsDomainIs(host, "www.archives.state.al.us")
|| dnsDomainIs(host, "www.arctic.ca")
|| dnsDomainIs(host, "www.ardenjohnson.com")
|| dnsDomainIs(host, "www.aristotle.net")
|| dnsDomainIs(host, "www.arizhwys.com")
|| dnsDomainIs(host, "www.arizonaguide.com")
|| dnsDomainIs(host, "www.arlingtoncemetery.com")
|| dnsDomainIs(host, "www.armory.com")
|| dnsDomainIs(host, "www.armwrestling.com")
|| dnsDomainIs(host, "www.arnprior.com")
|| dnsDomainIs(host, "www.artabunga.com")
|| dnsDomainIs(host, "www.artcarte.com")
|| dnsDomainIs(host, "www.artchive.com")
|| dnsDomainIs(host, "www.artcontest.com")
|| dnsDomainIs(host, "www.artcyclopedia.com")
|| dnsDomainIs(host, "www.artisandevelopers.com")
|| dnsDomainIs(host, "www.artlex.com")
|| dnsDomainIs(host, "www.artsandkids.com")
|| dnsDomainIs(host, "www.artyastro.com")
|| dnsDomainIs(host, "www.arwhead.com")
|| dnsDomainIs(host, "www.asahi-net.or.jp")
|| dnsDomainIs(host, "www.asap.unimelb.edu.au")
|| dnsDomainIs(host, "www.ascpl.lib.oh.us")
|| dnsDomainIs(host, "www.asia-art.net")
|| dnsDomainIs(host, "www.asiabigtime.com")
|| dnsDomainIs(host, "www.asianart.com")
|| dnsDomainIs(host, "www.asiatour.com")
|| dnsDomainIs(host, "www.asiaweek.com")
|| dnsDomainIs(host, "www.askanexpert.com")
|| dnsDomainIs(host, "www.askbasil.com")
|| dnsDomainIs(host, "www.assa.org.au")
|| dnsDomainIs(host, "www.ast.cam.ac.uk")
|| dnsDomainIs(host, "www.astronomy.com")
|| dnsDomainIs(host, "www.astros.com")
|| dnsDomainIs(host, "www.atek.com")
|| dnsDomainIs(host, "www.athlete.com")
|| dnsDomainIs(host, "www.athropolis.com")
|| dnsDomainIs(host, "www.atkielski.com")
|| dnsDomainIs(host, "www.atlantabraves.com")
|| dnsDomainIs(host, "www.atlantafalcons.com")
|| dnsDomainIs(host, "www.atlantathrashers.com")
|| dnsDomainIs(host, "www.atlanticus.com")
|| dnsDomainIs(host, "www.atm.ch.cam.ac.uk")
|| dnsDomainIs(host, "www.atom.co.jp")
|| dnsDomainIs(host, "www.atomicarchive.com")
|| dnsDomainIs(host, "www.att.com")
|| dnsDomainIs(host, "www.audreywood.com")
|| dnsDomainIs(host, "www.auntannie.com")
|| dnsDomainIs(host, "www.auntie.com")
|| dnsDomainIs(host, "www.avi-writer.com")
|| dnsDomainIs(host, "www.awesomeclipartforkids.com")
|| dnsDomainIs(host, "www.awhitehorse.com")
|| dnsDomainIs(host, "www.axess.com")
|| dnsDomainIs(host, "www.ayles.com")
|| dnsDomainIs(host, "www.ayn.ca")
|| dnsDomainIs(host, "www.azcardinals.com")
|| dnsDomainIs(host, "www.azdiamondbacks.com")
|| dnsDomainIs(host, "www.azsolarcenter.com")
|| dnsDomainIs(host, "www.azstarnet.com")
|| dnsDomainIs(host, "www.aztecafoods.com")
|| dnsDomainIs(host, "www.b-witched.com")
|| dnsDomainIs(host, "www.baberuthmuseum.com")
|| dnsDomainIs(host, "www.backstreetboys.com")
|| dnsDomainIs(host, "www.bagheera.com")
|| dnsDomainIs(host, "www.bahamas.com")
|| dnsDomainIs(host, "www.baileykids.com")
|| dnsDomainIs(host, "www.baldeagleinfo.com")
|| dnsDomainIs(host, "www.balloonhq.com")
|| dnsDomainIs(host, "www.balloonzone.com")
|| dnsDomainIs(host, "www.ballparks.com")
|| dnsDomainIs(host, "www.balmoralsoftware.com")
|| dnsDomainIs(host, "www.banja.com")
|| dnsDomainIs(host, "www.banph.com")
|| dnsDomainIs(host, "www.barbie.com")
|| dnsDomainIs(host, "www.barkingbuddies.com")
|| dnsDomainIs(host, "www.barnsdle.demon.co.uk")
|| dnsDomainIs(host, "www.barrysclipart.com")
|| dnsDomainIs(host, "www.bartleby.com")
|| dnsDomainIs(host, "www.baseplate.com")
|| dnsDomainIs(host, "www.batman-superman.com")
|| dnsDomainIs(host, "www.batmanbeyond.com")
|| dnsDomainIs(host, "www.bbc.co.uk")
|| dnsDomainIs(host, "www.bbhighway.com")
|| dnsDomainIs(host, "www.bboy.com")
|| dnsDomainIs(host, "www.bcit.tec.nj.us")
|| dnsDomainIs(host, "www.bconnex.net")
|| dnsDomainIs(host, "www.bcpl.net")
|| dnsDomainIs(host, "www.beach-net.com")
|| dnsDomainIs(host, "www.beachboys.com")
|| dnsDomainIs(host, "www.beakman.com")
|| dnsDomainIs(host, "www.beano.co.uk")
|| dnsDomainIs(host, "www.beans.demon.co.uk")
|| dnsDomainIs(host, "www.beartime.com")
|| dnsDomainIs(host, "www.bearyspecial.co.uk")
|| dnsDomainIs(host, "www.bedtime.com")
|| dnsDomainIs(host, "www.beingme.com")
|| dnsDomainIs(host, "www.belizeexplorer.com")
|| dnsDomainIs(host, "www.bell-labs.com")
|| dnsDomainIs(host, "www.bemorecreative.com")
|| dnsDomainIs(host, "www.bengals.com")
|| dnsDomainIs(host, "www.benjerry.com")
|| dnsDomainIs(host, "www.bennygoodsport.com")
|| dnsDomainIs(host, "www.berenstainbears.com")
|| dnsDomainIs(host, "www.beringia.com")
|| dnsDomainIs(host, "www.beritsbest.com")
|| dnsDomainIs(host, "www.berksweb.com")
|| dnsDomainIs(host, "www.best.com")
|| dnsDomainIs(host, "www.betsybyars.com")
|| dnsDomainIs(host, "www.bfro.net")
|| dnsDomainIs(host, "www.bgmm.com")
|| dnsDomainIs(host, "www.bibliography.com")
|| dnsDomainIs(host, "www.bigblue.com.au")
|| dnsDomainIs(host, "www.bigchalk.com")
|| dnsDomainIs(host, "www.bigidea.com")
|| dnsDomainIs(host, "www.bigtop.com")
|| dnsDomainIs(host, "www.bikecrawler.com")
|| dnsDomainIs(host, "www.billboard.com")
|| dnsDomainIs(host, "www.billybear4kids.com")
|| dnsDomainIs(host, "www.biography.com")
|| dnsDomainIs(host, "www.birdnature.com")
|| dnsDomainIs(host, "www.birdsnways.com")
|| dnsDomainIs(host, "www.birdtimes.com")
|| dnsDomainIs(host, "www.birminghamzoo.com")
|| dnsDomainIs(host, "www.birthdaypartyideas.com")
|| dnsDomainIs(host, "www.bis.arachsys.com")
|| dnsDomainIs(host, "www.bkgm.com")
|| dnsDomainIs(host, "www.blackbaseball.com")
|| dnsDomainIs(host, "www.blackbeardthepirate.com")
|| dnsDomainIs(host, "www.blackbeltmag.com")
|| dnsDomainIs(host, "www.blackfacts.com")
|| dnsDomainIs(host, "www.blackfeetnation.com")
|| dnsDomainIs(host, "www.blackhills-info.com")
|| dnsDomainIs(host, "www.blackholegang.com")
|| dnsDomainIs(host, "www.blaque.net")
|| dnsDomainIs(host, "www.blarg.net")
|| dnsDomainIs(host, "www.blasternaut.com")
|| dnsDomainIs(host, "www.blizzard.com")
|| dnsDomainIs(host, "www.blocksite.com")
|| dnsDomainIs(host, "www.bluejackets.com")
|| dnsDomainIs(host, "www.bluejays.ca")
|| dnsDomainIs(host, "www.bluemountain.com")
|| dnsDomainIs(host, "www.blupete.com")
|| dnsDomainIs(host, "www.blyton.co.uk")
|| dnsDomainIs(host, "www.boatnerd.com")
|| dnsDomainIs(host, "www.boatsafe.com")
|| dnsDomainIs(host, "www.bonus.com")
|| dnsDomainIs(host, "www.boowakwala.com")
|| dnsDomainIs(host, "www.bostonbruins.com")
|| dnsDomainIs(host, "www.braceface.com")
|| dnsDomainIs(host, "www.bracesinfo.com")
|| dnsDomainIs(host, "www.bradkent.com")
|| dnsDomainIs(host, "www.brainium.com")
|| dnsDomainIs(host, "www.brainmania.com")
|| dnsDomainIs(host, "www.brainpop.com")
|| dnsDomainIs(host, "www.bridalcave.com")
|| dnsDomainIs(host, "www.brightmoments.com")
|| dnsDomainIs(host, "www.britannia.com")
|| dnsDomainIs(host, "www.britannica.com")
|| dnsDomainIs(host, "www.british-museum.ac.uk")
|| dnsDomainIs(host, "www.brookes.ac.uk")
|| dnsDomainIs(host, "www.brookfieldreader.com")
|| dnsDomainIs(host, "www.btinternet.com")
|| dnsDomainIs(host, "www.bubbledome.co.nz")
|| dnsDomainIs(host, "www.buccaneers.com")
|| dnsDomainIs(host, "www.buffy.com")
|| dnsDomainIs(host, "www.bullying.co.uk")
|| dnsDomainIs(host, "www.bumply.com")
|| dnsDomainIs(host, "www.bungi.com")
|| dnsDomainIs(host, "www.burlco.lib.nj.us")
|| dnsDomainIs(host, "www.burlingamepezmuseum.com")
|| dnsDomainIs(host, "www.bus.ualberta.ca")
|| dnsDomainIs(host, "www.busprod.com")
|| dnsDomainIs(host, "www.butlerart.com")
|| dnsDomainIs(host, "www.butterflies.com")
|| dnsDomainIs(host, "www.butterflyfarm.co.cr")
|| dnsDomainIs(host, "www.bway.net")
|| dnsDomainIs(host, "www.bydonovan.com")
|| dnsDomainIs(host, "www.ca-mall.com")
|| dnsDomainIs(host, "www.cabinessence.com")
|| dnsDomainIs(host, "www.cablecarmuseum.com")
|| dnsDomainIs(host, "www.cadbury.co.uk")
|| dnsDomainIs(host, "www.calendarzone.com")
|| dnsDomainIs(host, "www.calgaryflames.com")
|| dnsDomainIs(host, "www.californiamissions.com")
|| dnsDomainIs(host, "www.camalott.com")
|| dnsDomainIs(host, "www.camelotintl.com")
|| dnsDomainIs(host, "www.campbellsoup.com")
|| dnsDomainIs(host, "www.camvista.com")
|| dnsDomainIs(host, "www.canadiens.com")
|| dnsDomainIs(host, "www.canals.state.ny.us")
|| dnsDomainIs(host, "www.candlelightstories.com")
|| dnsDomainIs(host, "www.candles-museum.com")
|| dnsDomainIs(host, "www.candystand.com")
|| dnsDomainIs(host, "www.caneshockey.com")
|| dnsDomainIs(host, "www.canismajor.com")
|| dnsDomainIs(host, "www.canucks.com")
|| dnsDomainIs(host, "www.capecod.net")
|| dnsDomainIs(host, "www.capital.net")
|| dnsDomainIs(host, "www.capstonestudio.com")
|| dnsDomainIs(host, "www.cardblvd.com")
|| dnsDomainIs(host, "www.caro.net")
|| dnsDomainIs(host, "www.carolhurst.com")
|| dnsDomainIs(host, "www.carr.lib.md.us")
|| dnsDomainIs(host, "www.cartooncorner.com")
|| dnsDomainIs(host, "www.cartooncritters.com")
|| dnsDomainIs(host, "www.cartoonnetwork.com")
|| dnsDomainIs(host, "www.carvingpatterns.com")
|| dnsDomainIs(host, "www.cashuniversity.com")
|| dnsDomainIs(host, "www.castles-of-britain.com")
|| dnsDomainIs(host, "www.castlewales.com")
|| dnsDomainIs(host, "www.catholic-forum.com")
|| dnsDomainIs(host, "www.catholic.net")
|| dnsDomainIs(host, "www.cattle.guelph.on.ca")
|| dnsDomainIs(host, "www.cavedive.com")
|| dnsDomainIs(host, "www.caveofthewinds.com")
|| dnsDomainIs(host, "www.cbc4kids.ca")
|| dnsDomainIs(host, "www.ccer.ggl.ruu.nl")
|| dnsDomainIs(host, "www.ccnet.com")
|| dnsDomainIs(host, "www.celineonline.com")
|| dnsDomainIs(host, "www.cellsalive.com")
|| dnsDomainIs(host, "www.centuryinshoes.com")
|| dnsDomainIs(host, "www.cfl.ca")
|| dnsDomainIs(host, "www.channel4.com")
|| dnsDomainIs(host, "www.channel8.net")
|| dnsDomainIs(host, "www.chanukah99.com")
|| dnsDomainIs(host, "www.charged.com")
|| dnsDomainIs(host, "www.chargers.com")
|| dnsDomainIs(host, "www.charlotte.com")
|| dnsDomainIs(host, "www.chaseday.com")
|| dnsDomainIs(host, "www.chateauversailles.fr")
|| dnsDomainIs(host, "www.cheatcc.com")
|| dnsDomainIs(host, "www.cheerleading.net")
|| dnsDomainIs(host, "www.cheese.com")
|| dnsDomainIs(host, "www.chem4kids.com")
|| dnsDomainIs(host, "www.chemicool.com")
|| dnsDomainIs(host, "www.cherbearsden.com")
|| dnsDomainIs(host, "www.chesskids.com")
|| dnsDomainIs(host, "www.chessvariants.com")
|| dnsDomainIs(host, "www.cheungswingchun.com")
|| dnsDomainIs(host, "www.chevroncars.com")
|| dnsDomainIs(host, "www.chibi.simplenet.com")
|| dnsDomainIs(host, "www.chicagobears.com")
|| dnsDomainIs(host, "www.chicagoblackhawks.com")
|| dnsDomainIs(host, "www.chickasaw.net")
|| dnsDomainIs(host, "www.childrensmusic.co.uk")
|| dnsDomainIs(host, "www.childrenssoftware.com")
|| dnsDomainIs(host, "www.childrenstory.com")
|| dnsDomainIs(host, "www.childrenwithdiabetes.com")
|| dnsDomainIs(host, "www.chinapage.com")
|| dnsDomainIs(host, "www.chinatoday.com")
|| dnsDomainIs(host, "www.chinavista.com")
|| dnsDomainIs(host, "www.chinnet.net")
|| dnsDomainIs(host, "www.chiquita.com")
|| dnsDomainIs(host, "www.chisox.com")
|| dnsDomainIs(host, "www.chivalry.com")
|| dnsDomainIs(host, "www.christiananswers.net")
|| dnsDomainIs(host, "www.christianity.com")
|| dnsDomainIs(host, "www.christmas.com")
|| dnsDomainIs(host, "www.christmas98.com")
|| dnsDomainIs(host, "www.chron.com")
|| dnsDomainIs(host, "www.chronique.com")
|| dnsDomainIs(host, "www.chuckecheese.com")
|| dnsDomainIs(host, "www.chucklebait.com")
|| dnsDomainIs(host, "www.chunkymonkey.com")
|| dnsDomainIs(host, "www.ci.chi.il.us")
|| dnsDomainIs(host, "www.ci.nyc.ny.us")
|| dnsDomainIs(host, "www.ci.phoenix.az.us")
|| dnsDomainIs(host, "www.ci.san-diego.ca.us")
|| dnsDomainIs(host, "www.cibc.com")
|| dnsDomainIs(host, "www.ciderpresspottery.com")
|| dnsDomainIs(host, "www.cincinnatireds.com")
|| dnsDomainIs(host, "www.circusparade.com")
|| dnsDomainIs(host, "www.circusweb.com")
|| dnsDomainIs(host, "www.cirquedusoleil.com")
|| dnsDomainIs(host, "www.cit.state.vt.us")
|| dnsDomainIs(host, "www.citycastles.com")
|| dnsDomainIs(host, "www.cityu.edu.hk")
|| dnsDomainIs(host, "www.civicmind.com")
|| dnsDomainIs(host, "www.civil-war.net")
|| dnsDomainIs(host, "www.civilization.ca")
|| dnsDomainIs(host, "www.cl.cam.ac.uk")
|| dnsDomainIs(host, "www.clantongang.com")
|| dnsDomainIs(host, "www.clark.net")
|| dnsDomainIs(host, "www.classicgaming.com")
|| dnsDomainIs(host, "www.claus.com")
|| dnsDomainIs(host, "www.clayz.com")
|| dnsDomainIs(host, "www.clearcf.uvic.ca")
|| dnsDomainIs(host, "www.clearlight.com")
|| dnsDomainIs(host, "www.clemusart.com")
|| dnsDomainIs(host, "www.clevelandbrowns.com")
|| dnsDomainIs(host, "www.clipartcastle.com")
|| dnsDomainIs(host, "www.clubi.ie")
|| dnsDomainIs(host, "www.cnn.com")
|| dnsDomainIs(host, "www.co.henrico.va.us")
|| dnsDomainIs(host, "www.coax.net")
|| dnsDomainIs(host, "www.cocacola.com")
|| dnsDomainIs(host, "www.cocori.com")
|| dnsDomainIs(host, "www.codesmiths.com")
|| dnsDomainIs(host, "www.codetalk.fed.us")
|| dnsDomainIs(host, "www.coin-gallery.com")
|| dnsDomainIs(host, "www.colinthompson.com")
|| dnsDomainIs(host, "www.collectoronline.com")
|| dnsDomainIs(host, "www.colonialhall.com")
|| dnsDomainIs(host, "www.coloradoavalanche.com")
|| dnsDomainIs(host, "www.coloradorockies.com")
|| dnsDomainIs(host, "www.colormathpink.com")
|| dnsDomainIs(host, "www.colts.com")
|| dnsDomainIs(host, "www.comet.net")
|| dnsDomainIs(host, "www.cometsystems.com")
|| dnsDomainIs(host, "www.comicbookresources.com")
|| dnsDomainIs(host, "www.comicspage.com")
|| dnsDomainIs(host, "www.compassnet.com")
|| dnsDomainIs(host, "www.compleatbellairs.com")
|| dnsDomainIs(host, "www.comptons.com")
|| dnsDomainIs(host, "www.concentric.net")
|| dnsDomainIs(host, "www.congogorillaforest.com")
|| dnsDomainIs(host, "www.conjuror.com")
|| dnsDomainIs(host, "www.conk.com")
|| dnsDomainIs(host, "www.conservation.state.mo.us")
|| dnsDomainIs(host, "www.contracostatimes.com")
|| dnsDomainIs(host, "www.control.chalmers.se")
|| dnsDomainIs(host, "www.cookierecipe.com")
|| dnsDomainIs(host, "www.cooljapanesetoys.com")
|| dnsDomainIs(host, "www.cooper.com")
|| dnsDomainIs(host, "www.corpcomm.net")
|| dnsDomainIs(host, "www.corrietenboom.com")
|| dnsDomainIs(host, "www.corynet.com")
|| dnsDomainIs(host, "www.corypaints.com")
|| dnsDomainIs(host, "www.cosmosmith.com")
|| dnsDomainIs(host, "www.countdown2000.com")
|| dnsDomainIs(host, "www.cowboy.net")
|| dnsDomainIs(host, "www.cowboypal.com")
|| dnsDomainIs(host, "www.cowcreek.com")
|| dnsDomainIs(host, "www.cowgirl.net")
|| dnsDomainIs(host, "www.cowgirls.com")
|| dnsDomainIs(host, "www.cp.duluth.mn.us")
|| dnsDomainIs(host, "www.cpsweb.com")
|| dnsDomainIs(host, "www.craftideas.com")
|| dnsDomainIs(host, "www.craniamania.com")
|| dnsDomainIs(host, "www.crater.lake.national-park.com")
|| dnsDomainIs(host, "www.crayoncrawler.com")
|| dnsDomainIs(host, "www.crazybone.com")
|| dnsDomainIs(host, "www.crazybones.com")
|| dnsDomainIs(host, "www.crd.ge.com")
|| dnsDomainIs(host, "www.create4kids.com")
|| dnsDomainIs(host, "www.creativemusic.com")
|| dnsDomainIs(host, "www.crocodilian.com")
|| dnsDomainIs(host, "www.crop.cri.nz")
|| dnsDomainIs(host, "www.cruzio.com")
|| dnsDomainIs(host, "www.crwflags.com")
|| dnsDomainIs(host, "www.cryptograph.com")
|| dnsDomainIs(host, "www.cryst.bbk.ac.uk")
|| dnsDomainIs(host, "www.cs.bilkent.edu.tr")
|| dnsDomainIs(host, "www.cs.man.ac.uk")
|| dnsDomainIs(host, "www.cs.sfu.ca")
|| dnsDomainIs(host, "www.cs.ubc.ca")
|| dnsDomainIs(host, "www.csd.uu.se")
|| dnsDomainIs(host, "www.csmonitor.com")
|| dnsDomainIs(host, "www.csse.monash.edu.au")
|| dnsDomainIs(host, "www.cstone.net")
|| dnsDomainIs(host, "www.csu.edu.au")
|| dnsDomainIs(host, "www.cubs.com")
|| dnsDomainIs(host, "www.culture.fr")
|| dnsDomainIs(host, "www.cultures.com")
|| dnsDomainIs(host, "www.curtis-collection.com")
|| dnsDomainIs(host, "www.cut-the-knot.com")
|| dnsDomainIs(host, "www.cws-scf.ec.gc.ca")
|| dnsDomainIs(host, "www.cyber-dyne.com")
|| dnsDomainIs(host, "www.cyberbee.com")
|| dnsDomainIs(host, "www.cyberbee.net")
|| dnsDomainIs(host, "www.cybercom.net")
|| dnsDomainIs(host, "www.cybercomm.net")
|| dnsDomainIs(host, "www.cybercomm.nl")
|| dnsDomainIs(host, "www.cybercorp.co.nz")
|| dnsDomainIs(host, "www.cybercs.com")
|| dnsDomainIs(host, "www.cybergoal.com")
|| dnsDomainIs(host, "www.cyberkids.com")
|| dnsDomainIs(host, "www.cyberspaceag.com")
|| dnsDomainIs(host, "www.cyberteens.com")
|| dnsDomainIs(host, "www.cybertours.com")
|| dnsDomainIs(host, "www.cybiko.com")
|| dnsDomainIs(host, "www.czweb.com")
|| dnsDomainIs(host, "www.d91.k12.id.us")
|| dnsDomainIs(host, "www.dailygrammar.com")
|| dnsDomainIs(host, "www.dakidz.com")
|| dnsDomainIs(host, "www.dalejarrettonline.com")
|| dnsDomainIs(host, "www.dallascowboys.com")
|| dnsDomainIs(host, "www.dallasdogndisc.com")
|| dnsDomainIs(host, "www.dallasstars.com")
|| dnsDomainIs(host, "www.damnyankees.com")
|| dnsDomainIs(host, "www.danceart.com")
|| dnsDomainIs(host, "www.daniellesplace.com")
|| dnsDomainIs(host, "www.dare-america.com")
|| dnsDomainIs(host, "www.darkfish.com")
|| dnsDomainIs(host, "www.darsbydesign.com")
|| dnsDomainIs(host, "www.datadragon.com")
|| dnsDomainIs(host, "www.davidreilly.com")
|| dnsDomainIs(host, "www.dccomics.com")
|| dnsDomainIs(host, "www.dcn.davis.ca.us")
|| dnsDomainIs(host, "www.deepseaworld.com")
|| dnsDomainIs(host, "www.delawaretribeofindians.nsn.us")
|| dnsDomainIs(host, "www.demon.co.uk")
|| dnsDomainIs(host, "www.denverbroncos.com")
|| dnsDomainIs(host, "www.denverpost.com")
|| dnsDomainIs(host, "www.dep.state.pa.us")
|| dnsDomainIs(host, "www.desert-fairy.com")
|| dnsDomainIs(host, "www.desert-storm.com")
|| dnsDomainIs(host, "www.desertusa.com")
|| dnsDomainIs(host, "www.designltd.com")
|| dnsDomainIs(host, "www.designsbykat.com")
|| dnsDomainIs(host, "www.detnews.com")
|| dnsDomainIs(host, "www.detroitlions.com")
|| dnsDomainIs(host, "www.detroitredwings.com")
|| dnsDomainIs(host, "www.detroittigers.com")
|| dnsDomainIs(host, "www.deutsches-museum.de")
|| dnsDomainIs(host, "www.devilray.com")
|| dnsDomainIs(host, "www.dhorse.com")
|| dnsDomainIs(host, "www.diana-ross.co.uk")
|| dnsDomainIs(host, "www.dianarossandthesupremes.net")
|| dnsDomainIs(host, "www.diaryproject.com")
|| dnsDomainIs(host, "www.dickbutkus.com")
|| dnsDomainIs(host, "www.dickshovel.com")
|| dnsDomainIs(host, "www.dictionary.com")
|| dnsDomainIs(host, "www.didyouknow.com")
|| dnsDomainIs(host, "www.diegorivera.com")
|| dnsDomainIs(host, "www.digitalcentury.com")
|| dnsDomainIs(host, "www.digitaldog.com")
|| dnsDomainIs(host, "www.digiweb.com")
|| dnsDomainIs(host, "www.dimdima.com")
|| dnsDomainIs(host, "www.dinodon.com")
|| dnsDomainIs(host, "www.dinosauria.com")
|| dnsDomainIs(host, "www.discovereso.com")
|| dnsDomainIs(host, "www.discovergalapagos.com")
|| dnsDomainIs(host, "www.discovergames.com")
|| dnsDomainIs(host, "www.discoveringarchaeology.com")
|| dnsDomainIs(host, "www.discoveringmontana.com")
|| dnsDomainIs(host, "www.discoverlearning.com")
|| dnsDomainIs(host, "www.discovery.com")
|| dnsDomainIs(host, "www.disknet.com")
|| dnsDomainIs(host, "www.disney.go.com")
|| dnsDomainIs(host, "www.distinguishedwomen.com")
|| dnsDomainIs(host, "www.dkonline.com")
|| dnsDomainIs(host, "www.dltk-kids.com")
|| dnsDomainIs(host, "www.dmgi.com")
|| dnsDomainIs(host, "www.dnr.state.md.us")
|| dnsDomainIs(host, "www.dnr.state.mi.us")
|| dnsDomainIs(host, "www.dnr.state.wi.us")
|| dnsDomainIs(host, "www.dodgers.com")
|| dnsDomainIs(host, "www.dodoland.com")
|| dnsDomainIs(host, "www.dog-play.com")
|| dnsDomainIs(host, "www.dogbreedinfo.com")
|| dnsDomainIs(host, "www.doginfomat.com")
|| dnsDomainIs(host, "www.dole5aday.com")
|| dnsDomainIs(host, "www.dollart.com")
|| dnsDomainIs(host, "www.dolliedish.com")
|| dnsDomainIs(host, "www.dome2000.co.uk")
|| dnsDomainIs(host, "www.domtar.com")
|| dnsDomainIs(host, "www.donegal.k12.pa.us")
|| dnsDomainIs(host, "www.dorneypark.com")
|| dnsDomainIs(host, "www.dorothyhinshawpatent.com")
|| dnsDomainIs(host, "www.dougweb.com")
|| dnsDomainIs(host, "www.dps.state.ak.us")
|| dnsDomainIs(host, "www.draw3d.com")
|| dnsDomainIs(host, "www.dreamgate.com")
|| dnsDomainIs(host, "www.dreamkitty.com")
|| dnsDomainIs(host, "www.dreamscape.com")
|| dnsDomainIs(host, "www.dreamtime.net.au")
|| dnsDomainIs(host, "www.drpeppermuseum.com")
|| dnsDomainIs(host, "www.drscience.com")
|| dnsDomainIs(host, "www.drseward.com")
|| dnsDomainIs(host, "www.drtoy.com")
|| dnsDomainIs(host, "www.dse.nl")
|| dnsDomainIs(host, "www.dtic.mil")
|| dnsDomainIs(host, "www.duracell.com")
|| dnsDomainIs(host, "www.dustbunny.com")
|| dnsDomainIs(host, "www.dynanet.com")
|| dnsDomainIs(host, "www.eagerreaders.com")
|| dnsDomainIs(host, "www.eaglekids.com")
|| dnsDomainIs(host, "www.earthcalendar.net")
|| dnsDomainIs(host, "www.earthday.net")
|| dnsDomainIs(host, "www.earthdog.com")
|| dnsDomainIs(host, "www.earthwatch.com")
|| dnsDomainIs(host, "www.ease.com")
|| dnsDomainIs(host, "www.eastasia.ws")
|| dnsDomainIs(host, "www.easytype.com")
|| dnsDomainIs(host, "www.eblewis.com")
|| dnsDomainIs(host, "www.ebs.hw.ac.uk")
|| dnsDomainIs(host, "www.eclipse.net")
|| dnsDomainIs(host, "www.eco-pros.com")
|| dnsDomainIs(host, "www.edbydesign.com")
|| dnsDomainIs(host, "www.eddytheeco-dog.com")
|| dnsDomainIs(host, "www.edgate.com")
|| dnsDomainIs(host, "www.edmontonoilers.com")
|| dnsDomainIs(host, "www.edu-source.com")
|| dnsDomainIs(host, "www.edu.gov.on.ca")
|| dnsDomainIs(host, "www.edu4kids.com")
|| dnsDomainIs(host, "www.educ.uvic.ca")
|| dnsDomainIs(host, "www.educate.org.uk")
|| dnsDomainIs(host, "www.education-world.com")
|| dnsDomainIs(host, "www.edunet.com")
|| dnsDomainIs(host, "www.eduplace.com")
|| dnsDomainIs(host, "www.edupuppy.com")
|| dnsDomainIs(host, "www.eduweb.com")
|| dnsDomainIs(host, "www.ee.ryerson.ca")
|| dnsDomainIs(host, "www.ee.surrey.ac.uk")
|| dnsDomainIs(host, "www.eeggs.com")
|| dnsDomainIs(host, "www.efes.com")
|| dnsDomainIs(host, "www.egalvao.com")
|| dnsDomainIs(host, "www.egypt.com")
|| dnsDomainIs(host, "www.egyptology.com")
|| dnsDomainIs(host, "www.ehobbies.com")
|| dnsDomainIs(host, "www.ehow.com")
|| dnsDomainIs(host, "www.eia.brad.ac.uk")
|| dnsDomainIs(host, "www.elbalero.gob.mx")
|| dnsDomainIs(host, "www.eliki.com")
|| dnsDomainIs(host, "www.elnino.com")
|| dnsDomainIs(host, "www.elok.com")
|| dnsDomainIs(host, "www.emf.net")
|| dnsDomainIs(host, "www.emsphone.com")
|| dnsDomainIs(host, "www.emulateme.com")
|| dnsDomainIs(host, "www.en.com")
|| dnsDomainIs(host, "www.enature.com")
|| dnsDomainIs(host, "www.enchantedlearning.com")
|| dnsDomainIs(host, "www.encyclopedia.com")
|| dnsDomainIs(host, "www.endex.com")
|| dnsDomainIs(host, "www.enjoyillinois.com")
|| dnsDomainIs(host, "www.enn.com")
|| dnsDomainIs(host, "www.enriqueig.com")
|| dnsDomainIs(host, "www.enteract.com")
|| dnsDomainIs(host, "www.epals.com")
|| dnsDomainIs(host, "www.equine-world.co.uk")
|| dnsDomainIs(host, "www.eric-carle.com")
|| dnsDomainIs(host, "www.ericlindros.net")
|| dnsDomainIs(host, "www.escape.com")
|| dnsDomainIs(host, "www.eskimo.com")
|| dnsDomainIs(host, "www.essentialsofmusic.com")
|| dnsDomainIs(host, "www.etch-a-sketch.com")
|| dnsDomainIs(host, "www.ethanallen.together.com")
|| dnsDomainIs(host, "www.etoys.com")
|| dnsDomainIs(host, "www.eurekascience.com")
|| dnsDomainIs(host, "www.euronet.nl")
|| dnsDomainIs(host, "www.everyrule.com")
|| dnsDomainIs(host, "www.ex.ac.uk")
|| dnsDomainIs(host, "www.excite.com")
|| dnsDomainIs(host, "www.execpc.com")
|| dnsDomainIs(host, "www.execulink.com")
|| dnsDomainIs(host, "www.exn.net")
|| dnsDomainIs(host, "www.expa.hvu.nl")
|| dnsDomainIs(host, "www.expage.com")
|| dnsDomainIs(host, "www.explode.to")
|| dnsDomainIs(host, "www.explorescience.com")
|| dnsDomainIs(host, "www.explorezone.com")
|| dnsDomainIs(host, "www.extremescience.com")
|| dnsDomainIs(host, "www.eyelid.co.uk")
|| dnsDomainIs(host, "www.eyeneer.com")
|| dnsDomainIs(host, "www.eyesofachild.com")
|| dnsDomainIs(host, "www.eyesofglory.com")
|| dnsDomainIs(host, "www.ezschool.com")
|| dnsDomainIs(host, "www.f1-live.com")
|| dnsDomainIs(host, "www.fables.co.uk")
|| dnsDomainIs(host, "www.factmonster.com")
|| dnsDomainIs(host, "www.fairygodmother.com")
|| dnsDomainIs(host, "www.familybuzz.com")
|| dnsDomainIs(host, "www.familygames.com")
|| dnsDomainIs(host, "www.familygardening.com")
|| dnsDomainIs(host, "www.familyinternet.com")
|| dnsDomainIs(host, "www.familymoney.com")
|| dnsDomainIs(host, "www.familyplay.com")
|| dnsDomainIs(host, "www.famousbirthdays.com")
|| dnsDomainIs(host, "www.fandom.com")
|| dnsDomainIs(host, "www.fansites.com")
|| dnsDomainIs(host, "www.faoschwarz.com")
|| dnsDomainIs(host, "www.fbe.unsw.edu.au")
|| dnsDomainIs(host, "www.fcps.k12.va.us")
|| dnsDomainIs(host, "www.fellersartsfactory.com")
|| dnsDomainIs(host, "www.ferrari.it")
|| dnsDomainIs(host, "www.fertnel.com")
|| dnsDomainIs(host, "www.fh-konstanz.de")
|| dnsDomainIs(host, "www.fhw.gr")
|| dnsDomainIs(host, "www.fibblesnork.com")
|| dnsDomainIs(host, "www.fidnet.com")
|| dnsDomainIs(host, "www.fieldhockey.com")
|| dnsDomainIs(host, "www.fieldhockeytraining.com")
|| dnsDomainIs(host, "www.fieler.com")
|| dnsDomainIs(host, "www.finalfour.net")
|| dnsDomainIs(host, "www.finifter.com")
|| dnsDomainIs(host, "www.fireworks-safety.com")
|| dnsDomainIs(host, "www.firstcut.com")
|| dnsDomainIs(host, "www.firstnations.com")
|| dnsDomainIs(host, "www.fishbc.com")
|| dnsDomainIs(host, "www.fisher-price.com")
|| dnsDomainIs(host, "www.fisheyeview.com")
|| dnsDomainIs(host, "www.fishgeeks.com")
|| dnsDomainIs(host, "www.fishindex.com")
|| dnsDomainIs(host, "www.fitzgeraldstudio.com")
|| dnsDomainIs(host, "www.flags.net")
|| dnsDomainIs(host, "www.flail.com")
|| dnsDomainIs(host, "www.flamarlins.com")
|| dnsDomainIs(host, "www.flausa.com")
|| dnsDomainIs(host, "www.floodlight-findings.com")
|| dnsDomainIs(host, "www.floridahistory.com")
|| dnsDomainIs(host, "www.floridapanthers.com")
|| dnsDomainIs(host, "www.fng.fi")
|| dnsDomainIs(host, "www.foodsci.uoguelph.ca")
|| dnsDomainIs(host, "www.foremost.com")
|| dnsDomainIs(host, "www.fortress.am")
|| dnsDomainIs(host, "www.fortunecity.com")
|| dnsDomainIs(host, "www.fosterclub.com")
|| dnsDomainIs(host, "www.foundus.com")
|| dnsDomainIs(host, "www.fourmilab.ch")
|| dnsDomainIs(host, "www.fox.com")
|| dnsDomainIs(host, "www.foxfamilychannel.com")
|| dnsDomainIs(host, "www.foxhome.com")
|| dnsDomainIs(host, "www.foxkids.com")
|| dnsDomainIs(host, "www.franceway.com")
|| dnsDomainIs(host, "www.fred.net")
|| dnsDomainIs(host, "www.fredpenner.com")
|| dnsDomainIs(host, "www.freedomknot.com")
|| dnsDomainIs(host, "www.freejigsawpuzzles.com")
|| dnsDomainIs(host, "www.freenet.edmonton.ab.ca")
|| dnsDomainIs(host, "www.frii.com")
|| dnsDomainIs(host, "www.frisbee.com")
|| dnsDomainIs(host, "www.fritolay.com")
|| dnsDomainIs(host, "www.frogsonice.com")
|| dnsDomainIs(host, "www.frontiernet.net")
|| dnsDomainIs(host, "www.fs.fed.us")
|| dnsDomainIs(host, "www.funattic.com")
|| dnsDomainIs(host, ".funbrain.com")
|| dnsDomainIs(host, "www.fundango.com")
|| dnsDomainIs(host, "www.funisland.com")
|| dnsDomainIs(host, "www.funkandwagnalls.com")
|| dnsDomainIs(host, "www.funorama.com")
|| dnsDomainIs(host, "www.funschool.com")
|| dnsDomainIs(host, "www.funster.com")
|| dnsDomainIs(host, "www.furby.com")
|| dnsDomainIs(host, "www.fusion.org.uk")
|| dnsDomainIs(host, "www.futcher.com")
|| dnsDomainIs(host, "www.futurescan.com")
|| dnsDomainIs(host, "www.fyi.net")
|| dnsDomainIs(host, "www.gailgibbons.com")
|| dnsDomainIs(host, "www.galegroup.com")
|| dnsDomainIs(host, "www.gambia.com")
|| dnsDomainIs(host, "www.gamecabinet.com")
|| dnsDomainIs(host, "www.gamecenter.com")
|| dnsDomainIs(host, "www.gamefaqs.com")
|| dnsDomainIs(host, "www.garfield.com")
|| dnsDomainIs(host, "www.garyharbo.com")
|| dnsDomainIs(host, "www.gatefish.com")
|| dnsDomainIs(host, "www.gateway-va.com")
|| dnsDomainIs(host, "www.gazillionaire.com")
|| dnsDomainIs(host, "www.gearhead.com")
|| dnsDomainIs(host, "www.genesplicing.com")
|| dnsDomainIs(host, "www.genhomepage.com")
|| dnsDomainIs(host, "www.geobop.com")
|| dnsDomainIs(host, "www.geocities.com")
|| dnsDomainIs(host, "www.geographia.com")
|| dnsDomainIs(host, "www.georgeworld.com")
|| dnsDomainIs(host, "www.georgian.net")
|| dnsDomainIs(host, "www.german-way.com")
|| dnsDomainIs(host, "www.germanfortravellers.com")
|| dnsDomainIs(host, "www.germantown.k12.il.us")
|| dnsDomainIs(host, "www.germany-tourism.de")
|| dnsDomainIs(host, "www.getmusic.com")
|| dnsDomainIs(host, "www.gettysburg.com")
|| dnsDomainIs(host, "www.ghirardellisq.com")
|| dnsDomainIs(host, "www.ghosttowngallery.com")
|| dnsDomainIs(host, "www.ghosttownsusa.com")
|| dnsDomainIs(host, "www.giants.com")
|| dnsDomainIs(host, "www.gibraltar.gi")
|| dnsDomainIs(host, "www.gigglepoetry.com")
|| dnsDomainIs(host, "www.gilchriststudios.com")
|| dnsDomainIs(host, "www.gillslap.freeserve.co.uk")
|| dnsDomainIs(host, "www.gilmer.net")
|| dnsDomainIs(host, "www.gio.gov.tw")
|| dnsDomainIs(host, "www.girltech.com")
|| dnsDomainIs(host, "www.girlzone.com")
|| dnsDomainIs(host, "www.globalgang.org.uk")
|| dnsDomainIs(host, "www.globalindex.com")
|| dnsDomainIs(host, "www.globalinfo.com")
|| dnsDomainIs(host, "www.gloriafan.com")
|| dnsDomainIs(host, "www.gms.ocps.k12.fl.us")
|| dnsDomainIs(host, "www.go-go-diggity.com")
|| dnsDomainIs(host, "www.goals.com")
|| dnsDomainIs(host, "www.godiva.com")
|| dnsDomainIs(host, "www.golden-retriever.com")
|| dnsDomainIs(host, "www.goldenbooks.com")
|| dnsDomainIs(host, "www.goldeneggs.com.au")
|| dnsDomainIs(host, "www.golfonline.com")
|| dnsDomainIs(host, "www.goobo.com")
|| dnsDomainIs(host, "www.goodearthgraphics.com")
|| dnsDomainIs(host, "www.goodyear.com")
|| dnsDomainIs(host, "www.gopbi.com")
|| dnsDomainIs(host, "www.gorge.net")
|| dnsDomainIs(host, "www.gorp.com")
|| dnsDomainIs(host, "www.got-milk.com")
|| dnsDomainIs(host, "www.gov.ab.ca")
|| dnsDomainIs(host, "www.gov.nb.ca")
|| dnsDomainIs(host, "www.grammarbook.com")
|| dnsDomainIs(host, "www.grammarlady.com")
|| dnsDomainIs(host, "www.grandparents-day.com")
|| dnsDomainIs(host, "www.granthill.com")
|| dnsDomainIs(host, "www.grayweb.com")
|| dnsDomainIs(host, "www.greatbuildings.com")
|| dnsDomainIs(host, "www.greatkids.com")
|| dnsDomainIs(host, "www.greatscience.com")
|| dnsDomainIs(host, "www.greeceny.com")
|| dnsDomainIs(host, "www.greenkeepers.com")
|| dnsDomainIs(host, "www.greylabyrinth.com")
|| dnsDomainIs(host, "www.grimmy.com")
|| dnsDomainIs(host, "www.gsrg.nmh.ac.uk")
|| dnsDomainIs(host, "www.gti.net")
|| dnsDomainIs(host, "www.guinnessworldrecords.com")
|| dnsDomainIs(host, "www.guitar.net")
|| dnsDomainIs(host, "www.guitarplaying.com")
|| dnsDomainIs(host, "www.gumbyworld.com")
|| dnsDomainIs(host, "www.gurlwurld.com")
|| dnsDomainIs(host, "www.gwi.net")
|| dnsDomainIs(host, "www.gymn-forum.com")
|| dnsDomainIs(host, "www.gzkidzone.com")
|| dnsDomainIs(host, "www.haemibalgassi.com")
|| dnsDomainIs(host, "www.hairstylist.com")
|| dnsDomainIs(host, "www.halcyon.com")
|| dnsDomainIs(host, "www.halifax.cbc.ca")
|| dnsDomainIs(host, "www.halloween-online.com")
|| dnsDomainIs(host, "www.halloweenkids.com")
|| dnsDomainIs(host, "www.halloweenmagazine.com")
|| dnsDomainIs(host, "www.hamill.co.uk")
|| dnsDomainIs(host, "www.hamsterdance2.com")
|| dnsDomainIs(host, "www.hamsters.co.uk")
|| dnsDomainIs(host, "www.hamstertours.com")
|| dnsDomainIs(host, "www.handsonmath.com")
|| dnsDomainIs(host, "www.handspeak.com")
|| dnsDomainIs(host, "www.hansonline.com")
|| dnsDomainIs(host, "www.happychild.org.uk")
|| dnsDomainIs(host, "www.happyfamilies.com")
|| dnsDomainIs(host, "www.happytoy.com")
|| dnsDomainIs(host, "www.harley-davidson.com")
|| dnsDomainIs(host, "www.harmonicalessons.com")
|| dnsDomainIs(host, "www.harperchildrens.com")
|| dnsDomainIs(host, "www.harvey.com")
|| dnsDomainIs(host, "www.hasbro-interactive.com")
|| dnsDomainIs(host, "www.haynet.net")
|| dnsDomainIs(host, "www.hbc.com")
|| dnsDomainIs(host, "www.hblewis.com")
|| dnsDomainIs(host, "www.hbook.com")
|| dnsDomainIs(host, "www.he.net")
|| dnsDomainIs(host, "www.headbone.com")
|| dnsDomainIs(host, "www.healthatoz.com")
|| dnsDomainIs(host, "www.healthypet.com")
|| dnsDomainIs(host, "www.heartfoundation.com.au")
|| dnsDomainIs(host, "www.heatersworld.com")
|| dnsDomainIs(host, "www.her-online.com")
|| dnsDomainIs(host, "www.heroesofhistory.com")
|| dnsDomainIs(host, "www.hersheypa.com")
|| dnsDomainIs(host, "www.hersheys.com")
|| dnsDomainIs(host, "www.hevanet.com")
|| dnsDomainIs(host, "www.heynetwork.com")
|| dnsDomainIs(host, "www.hgo.com")
|| dnsDomainIs(host, "www.hhof.com")
|| dnsDomainIs(host, "www.hideandseekpuppies.com")
|| dnsDomainIs(host, "www.hifusion.com")
|| dnsDomainIs(host, "www.highbridgepress.com")
|| dnsDomainIs(host, "www.his.com")
|| dnsDomainIs(host, "www.history.navy.mil")
|| dnsDomainIs(host, "www.historychannel.com")
|| dnsDomainIs(host, "www.historyhouse.com")
|| dnsDomainIs(host, "www.historyplace.com")
|| dnsDomainIs(host, "www.hisurf.com")
|| dnsDomainIs(host, "www.hiyah.com")
|| dnsDomainIs(host, "www.hmnet.com")
|| dnsDomainIs(host, "www.hoboes.com")
|| dnsDomainIs(host, "www.hockeydb.com")
|| dnsDomainIs(host, "www.hohnerusa.com")
|| dnsDomainIs(host, "www.holidaychannel.com")
|| dnsDomainIs(host, "www.holidayfestival.com")
|| dnsDomainIs(host, "www.holidays.net")
|| dnsDomainIs(host, "www.hollywood.com")
|| dnsDomainIs(host, "www.holoworld.com")
|| dnsDomainIs(host, "www.homepagers.com")
|| dnsDomainIs(host, "www.homeschoolzone.com")
|| dnsDomainIs(host, "www.homestead.com")
|| dnsDomainIs(host, "www.homeworkspot.com")
|| dnsDomainIs(host, "www.hompro.com")
|| dnsDomainIs(host, "www.honey.com")
|| dnsDomainIs(host, "www.hooked.net")
|| dnsDomainIs(host, "www.hoophall.com")
|| dnsDomainIs(host, "www.hooverdam.com")
|| dnsDomainIs(host, "www.hopepaul.com")
|| dnsDomainIs(host, "www.horse-country.com")
|| dnsDomainIs(host, "www.horsechat.com")
|| dnsDomainIs(host, "www.horsefun.com")
|| dnsDomainIs(host, "www.horus.ics.org.eg")
|| dnsDomainIs(host, "www.hotbraille.com")
|| dnsDomainIs(host, "www.hotwheels.com")
|| dnsDomainIs(host, "www.howstuffworks.com")
|| dnsDomainIs(host, "www.hpdigitalbookclub.com")
|| dnsDomainIs(host, "www.hpj.com")
|| dnsDomainIs(host, "www.hpl.hp.com")
|| dnsDomainIs(host, "www.hpl.lib.tx.us")
|| dnsDomainIs(host, "www.hpnetwork.f2s.com")
|| dnsDomainIs(host, "www.hsswp.com")
|| dnsDomainIs(host, "www.hsx.com")
|| dnsDomainIs(host, "www.humboldt1.com")
|| dnsDomainIs(host, "www.humongous.com")
|| dnsDomainIs(host, "www.humph3.freeserve.co.uk")
|| dnsDomainIs(host, "www.humphreybear.com ")
|| dnsDomainIs(host, "www.hurricanehunters.com")
|| dnsDomainIs(host, "www.hyperhistory.com")
|| dnsDomainIs(host, "www.i2k.com")
|| dnsDomainIs(host, "www.ibhof.com")
|| dnsDomainIs(host, "www.ibiscom.com")
|| dnsDomainIs(host, "www.ibm.com")
|| dnsDomainIs(host, "www.icangarden.com")
|| dnsDomainIs(host, "www.icecreamusa.com")
|| dnsDomainIs(host, "www.icn.co.uk")
|| dnsDomainIs(host, "www.icomm.ca")
|| dnsDomainIs(host, "www.idfishnhunt.com")
|| dnsDomainIs(host, "www.iditarod.com")
|| dnsDomainIs(host, "www.iei.net")
|| dnsDomainIs(host, "www.iemily.com")
|| dnsDomainIs(host, "www.iir.com")
|| dnsDomainIs(host, "www.ika.com")
|| dnsDomainIs(host, "www.ikoala.com")
|| dnsDomainIs(host, "www.iln.net")
|| dnsDomainIs(host, "www.imagine5.com")
|| dnsDomainIs(host, "www.imes.boj.or.jp")
|| dnsDomainIs(host, "www.inch.com")
|| dnsDomainIs(host, "www.incwell.com")
|| dnsDomainIs(host, "www.indian-river.fl.us")
|| dnsDomainIs(host, "www.indians.com")
|| dnsDomainIs(host, "www.indo.com")
|| dnsDomainIs(host, "www.indyracingleague.com")
|| dnsDomainIs(host, "www.indyzoo.com")
|| dnsDomainIs(host, "www.info-canada.com")
|| dnsDomainIs(host, "www.infomagic.net")
|| dnsDomainIs(host, "www.infoplease.com")
|| dnsDomainIs(host, "www.infoporium.com")
|| dnsDomainIs(host, "www.infostuff.com")
|| dnsDomainIs(host, "www.inhandmuseum.com")
|| dnsDomainIs(host, "www.inil.com")
|| dnsDomainIs(host, "www.inkspot.com")
|| dnsDomainIs(host, "www.inkyfingers.com")
|| dnsDomainIs(host, "www.innerauto.com")
|| dnsDomainIs(host, "www.innerbody.com")
|| dnsDomainIs(host, "www.inqpub.com")
|| dnsDomainIs(host, "www.insecta-inspecta.com")
|| dnsDomainIs(host, "www.insectclopedia.com")
|| dnsDomainIs(host, "www.inside-mexico.com")
|| dnsDomainIs(host, "www.insiders.com")
|| dnsDomainIs(host, "www.insteam.com")
|| dnsDomainIs(host, "www.intel.com")
|| dnsDomainIs(host, "www.intellicast.com")
|| dnsDomainIs(host, "www.interads.co.uk")
|| dnsDomainIs(host, "www.intercot.com")
|| dnsDomainIs(host, "www.intergraffix.com")
|| dnsDomainIs(host, "www.interknowledge.com")
|| dnsDomainIs(host, "www.interlog.com")
|| dnsDomainIs(host, "www.internet4kids.com")
|| dnsDomainIs(host, "www.intersurf.com")
|| dnsDomainIs(host, "www.inthe80s.com")
|| dnsDomainIs(host, "www.inventorsmuseum.com")
|| dnsDomainIs(host, "www.inwap.com")
|| dnsDomainIs(host, "www.ioa.com")
|| dnsDomainIs(host, "www.ionet.net")
|| dnsDomainIs(host, "www.iowacity.com")
|| dnsDomainIs(host, "www.ireland-now.com")
|| dnsDomainIs(host, "www.ireland.com")
|| dnsDomainIs(host, "www.irelandseye.com")
|| dnsDomainIs(host, "www.irlgov.ie")
|| dnsDomainIs(host, "www.isd.net")
|| dnsDomainIs(host, "www.islandnet.com")
|| dnsDomainIs(host, "www.isomedia.com")
|| dnsDomainIs(host, "www.itftennis.com")
|| dnsDomainIs(host, "www.itpi.dpi.state.nc.us")
|| dnsDomainIs(host, "www.itskwanzaatime.com")
|| dnsDomainIs(host, "www.itss.raytheon.com")
|| dnsDomainIs(host, "www.iuma.com")
|| dnsDomainIs(host, "www.iwaynet.net")
|| dnsDomainIs(host, "www.iwc.com")
|| dnsDomainIs(host, "www.iwight.gov.uk")
|| dnsDomainIs(host, "www.ixpres.com")
|| dnsDomainIs(host, "www.j.b.allen.btinternet.co.uk")
|| dnsDomainIs(host, "www.jabuti.com")
|| dnsDomainIs(host, "www.jackinthebox.com")
|| dnsDomainIs(host, "www.jaffebros.com")
|| dnsDomainIs(host, "www.jaguars.com")
|| dnsDomainIs(host, "www.jamaica-gleaner.com")
|| dnsDomainIs(host, "www.jamm.com")
|| dnsDomainIs(host, "www.janbrett.com")
|| dnsDomainIs(host, "www.janetstevens.com")
|| dnsDomainIs(host, "www.japan-guide.com")
|| dnsDomainIs(host, "www.jargon.net")
|| dnsDomainIs(host, "www.javelinamx.com")
|| dnsDomainIs(host, "www.jayjay.com")
|| dnsDomainIs(host, "www.jazclass.aust.com")
|| dnsDomainIs(host, "www.jedinet.com")
|| dnsDomainIs(host, "www.jenniferlopez.com")
|| dnsDomainIs(host, "www.jlpanagopoulos.com")
|| dnsDomainIs(host, "www.jmarshall.com")
|| dnsDomainIs(host, "www.jmccall.demon.co.uk")
|| dnsDomainIs(host, "www.jmts.com")
|| dnsDomainIs(host, "www.joesherlock.com")
|| dnsDomainIs(host, "www.jorvik-viking-centre.co.uk")
|| dnsDomainIs(host, "www.joycecarolthomas.com")
|| dnsDomainIs(host, "www.joycone.com")
|| dnsDomainIs(host, "www.joyrides.com")
|| dnsDomainIs(host, "www.jps.net")
|| dnsDomainIs(host, "www.jspub.com")
|| dnsDomainIs(host, "www.judaica.com")
|| dnsDomainIs(host, "www.judyblume.com")
|| dnsDomainIs(host, "www.julen.net")
|| dnsDomainIs(host, "www.june29.com")
|| dnsDomainIs(host, "www.juneteenth.com")
|| dnsDomainIs(host, "www.justuskidz.com")
|| dnsDomainIs(host, "www.justwomen.com")
|| dnsDomainIs(host, "www.jwindow.net")
|| dnsDomainIs(host, "www.k9web.com")
|| dnsDomainIs(host, "www.kaercher.de")
|| dnsDomainIs(host, "www.kaleidoscapes.com")
|| dnsDomainIs(host, "www.kapili.com")
|| dnsDomainIs(host, "www.kcchiefs.com")
|| dnsDomainIs(host, "www.kcpl.lib.mo.us")
|| dnsDomainIs(host, "www.kcroyals.com")
|| dnsDomainIs(host, "www.kcsd.k12.pa.us")
|| dnsDomainIs(host, "www.kdu.com")
|| dnsDomainIs(host, "www.kelloggs.com")
|| dnsDomainIs(host, "www.kentuckyfriedchicken.com")
|| dnsDomainIs(host, "www.kenyaweb.com")
|| dnsDomainIs(host, "www.keypals.com")
|| dnsDomainIs(host, "www.kfn.com")
|| dnsDomainIs(host, "www.kid-at-art.com")
|| dnsDomainIs(host, "www.kid-channel.com")
|| dnsDomainIs(host, "www.kidallergy.com")
|| dnsDomainIs(host, "www.kidbibs.com")
|| dnsDomainIs(host, "www.kidcomics.com")
|| dnsDomainIs(host, "www.kiddesafety.com")
|| dnsDomainIs(host, "www.kiddiecampus.com")
|| dnsDomainIs(host, "www.kididdles.com")
|| dnsDomainIs(host, "www.kidnews.com")
|| dnsDomainIs(host, "www.kidocracy.com")
|| dnsDomainIs(host, "www.kidport.com")
|| dnsDomainIs(host, "www.kids-channel.co.uk")
|| dnsDomainIs(host, "www.kids-drawings.com")
|| dnsDomainIs(host, "www.kids-in-mind.com")
|| dnsDomainIs(host, "www.kids4peace.com")
|| dnsDomainIs(host, "www.kidsandcomputers.com")
|| dnsDomainIs(host, "www.kidsart.co.uk")
|| dnsDomainIs(host, "www.kidsastronomy.com")
|| dnsDomainIs(host, "www.kidsbank.com")
|| dnsDomainIs(host, "www.kidsbookshelf.com")
|| dnsDomainIs(host, "www.kidsclick.com")
|| dnsDomainIs(host, "www.kidscom.com")
|| dnsDomainIs(host, "www.kidscook.com")
|| dnsDomainIs(host, "www.kidsdoctor.com")
|| dnsDomainIs(host, "www.kidsdomain.com")
|| dnsDomainIs(host, "www.kidsfarm.com")
|| dnsDomainIs(host, "www.kidsfreeware.com")
|| dnsDomainIs(host, "www.kidsfun.tv")
|| dnsDomainIs(host, "www.kidsgolf.com")
|| dnsDomainIs(host, "www.kidsgowild.com")
|| dnsDomainIs(host, "www.kidsjokes.com")
|| dnsDomainIs(host, "www.kidsloveamystery.com")
|| dnsDomainIs(host, "www.kidsmoneycents.com")
|| dnsDomainIs(host, "www.kidsnewsroom.com")
|| dnsDomainIs(host, "www.kidsource.com")
|| dnsDomainIs(host, "www.kidsparties.com")
|| dnsDomainIs(host, "www.kidsplaytown.com")
|| dnsDomainIs(host, "www.kidsreads.com")
|| dnsDomainIs(host, "www.kidsreport.com")
|| dnsDomainIs(host, "www.kidsrunning.com")
|| dnsDomainIs(host, "www.kidstamps.com")
|| dnsDomainIs(host, "www.kidsvideogames.com")
|| dnsDomainIs(host, "www.kidsway.com")
|| dnsDomainIs(host, "www.kidswithcancer.com")
|| dnsDomainIs(host, "www.kidszone.ourfamily.com")
|| dnsDomainIs(host, "www.kidzup.com")
|| dnsDomainIs(host, "www.kinderart.com")
|| dnsDomainIs(host, "www.kineticcity.com")
|| dnsDomainIs(host, "www.kings.k12.ca.us")
|| dnsDomainIs(host, "www.kiplinger.com")
|| dnsDomainIs(host, "www.kiwirecovery.org.nz")
|| dnsDomainIs(host, "www.klipsan.com")
|| dnsDomainIs(host, "www.klutz.com")
|| dnsDomainIs(host, "www.kn.pacbell.com")
|| dnsDomainIs(host, "www.knex.com")
|| dnsDomainIs(host, "www.knowledgeadventure.com")
|| dnsDomainIs(host, "www.knto.or.kr")
|| dnsDomainIs(host, "www.kodak.com")
|| dnsDomainIs(host, "www.konica.co.jp")
|| dnsDomainIs(host, "www.kraftfoods.com")
|| dnsDomainIs(host, "www.kudzukids.com")
|| dnsDomainIs(host, "www.kulichki.com")
|| dnsDomainIs(host, "www.kuttu.com")
|| dnsDomainIs(host, "www.kv5.com")
|| dnsDomainIs(host, "www.kyes-world.com")
|| dnsDomainIs(host, "www.kyohaku.go.jp")
|| dnsDomainIs(host, "www.kyrene.k12.az.us")
|| dnsDomainIs(host, "www.kz")
|| dnsDomainIs(host, "www.la-hq.org.uk")
|| dnsDomainIs(host, "www.labs.net")
|| dnsDomainIs(host, "www.labyrinth.net.au")
|| dnsDomainIs(host, "www.laffinthedark.com")
|| dnsDomainIs(host, "www.lakhota.com")
|| dnsDomainIs(host, "www.lakings.com")
|| dnsDomainIs(host, "www.lam.mus.ca.us")
|| dnsDomainIs(host, "www.lampstras.k12.pa.us")
|| dnsDomainIs(host, "www.lams.losalamos.k12.nm.us")
|| dnsDomainIs(host, "www.landofcadbury.ca")
|| dnsDomainIs(host, "www.larry-boy.com")
|| dnsDomainIs(host, "www.lasersite.com")
|| dnsDomainIs(host, "www.last-word.com")
|| dnsDomainIs(host, "www.latimes.com")
|| dnsDomainIs(host, "www.laughon.com")
|| dnsDomainIs(host, "www.laurasmidiheaven.com")
|| dnsDomainIs(host, "www.lausd.k12.ca.us")
|| dnsDomainIs(host, "www.learn2.com")
|| dnsDomainIs(host, "www.learn2type.com")
|| dnsDomainIs(host, "www.learnfree-hobbies.com")
|| dnsDomainIs(host, "www.learningkingdom.com")
|| dnsDomainIs(host, "www.learningplanet.com")
|| dnsDomainIs(host, "www.leftjustified.com")
|| dnsDomainIs(host, "www.legalpadjr.com")
|| dnsDomainIs(host, "www.legendarysurfers.com")
|| dnsDomainIs(host, "www.legends.dm.net")
|| dnsDomainIs(host, "www.legis.state.wi.us")
|| dnsDomainIs(host, "www.legis.state.wv.us")
|| dnsDomainIs(host, "www.lego.com")
|| dnsDomainIs(host, "www.leje.com")
|| dnsDomainIs(host, "www.leonardodicaprio.com")
|| dnsDomainIs(host, "www.lessonplanspage.com")
|| dnsDomainIs(host, "www.letour.fr")
|| dnsDomainIs(host, "www.levins.com")
|| dnsDomainIs(host, "www.levistrauss.com")
|| dnsDomainIs(host, "www.libertystatepark.com")
|| dnsDomainIs(host, "www.libraryspot.com")
|| dnsDomainIs(host, "www.lifelong.com")
|| dnsDomainIs(host, "www.lighthouse.cc")
|| dnsDomainIs(host, "www.lightlink.com")
|| dnsDomainIs(host, "www.lightspan.com")
|| dnsDomainIs(host, "www.lil-fingers.com")
|| dnsDomainIs(host, "www.linc.or.jp")
|| dnsDomainIs(host, "www.lindsaysbackyard.com")
|| dnsDomainIs(host, "www.lindtchocolate.com")
|| dnsDomainIs(host, "www.lineone.net")
|| dnsDomainIs(host, "www.lionel.com")
|| dnsDomainIs(host, "www.lisafrank.com")
|| dnsDomainIs(host, "www.lissaexplains.com")
|| dnsDomainIs(host, "www.literacycenter.net")
|| dnsDomainIs(host, "www.littleartist.com")
|| dnsDomainIs(host, "www.littlechiles.com")
|| dnsDomainIs(host, "www.littlecritter.com")
|| dnsDomainIs(host, "www.littlecrowtoys.com")
|| dnsDomainIs(host, "www.littlehousebooks.com")
|| dnsDomainIs(host, "www.littlejason.com")
|| dnsDomainIs(host, "www.littleplanettimes.com")
|| dnsDomainIs(host, "www.liveandlearn.com")
|| dnsDomainIs(host, "www.loadstar.prometeus.net")
|| dnsDomainIs(host, "www.localaccess.com")
|| dnsDomainIs(host, "www.lochness.co.uk")
|| dnsDomainIs(host, "www.lochness.scotland.net")
|| dnsDomainIs(host, "www.logos.it")
|| dnsDomainIs(host, "www.lonelyplanet.com")
|| dnsDomainIs(host, "www.looklearnanddo.com")
|| dnsDomainIs(host, "www.loosejocks.com")
|| dnsDomainIs(host, "www.lost-worlds.com")
|| dnsDomainIs(host, "www.love-story.com")
|| dnsDomainIs(host, "www.lpga.com")
|| dnsDomainIs(host, "www.lsjunction.com")
|| dnsDomainIs(host, "www.lucasarts.com")
|| dnsDomainIs(host, "www.lucent.com")
|| dnsDomainIs(host, "www.lucie.com")
|| dnsDomainIs(host, "www.lunaland.co.za")
|| dnsDomainIs(host, "www.luth.se")
|| dnsDomainIs(host, "www.lyricalworks.com")
|| dnsDomainIs(host, "www.infoporium.com")
|| dnsDomainIs(host, "www.infostuff.com")
|| dnsDomainIs(host, "www.inhandmuseum.com")
|| dnsDomainIs(host, "www.inil.com")
|| dnsDomainIs(host, "www.inkspot.com")
|| dnsDomainIs(host, "www.inkyfingers.com")
|| dnsDomainIs(host, "www.innerauto.com")
|| dnsDomainIs(host, "www.innerbody.com")
|| dnsDomainIs(host, "www.inqpub.com")
|| dnsDomainIs(host, "www.insecta-inspecta.com")
|| dnsDomainIs(host, "www.insectclopedia.com")
|| dnsDomainIs(host, "www.inside-mexico.com")
|| dnsDomainIs(host, "www.insiders.com")
|| dnsDomainIs(host, "www.insteam.com")
|| dnsDomainIs(host, "www.intel.com")
|| dnsDomainIs(host, "www.intellicast.com")
|| dnsDomainIs(host, "www.interads.co.uk")
|| dnsDomainIs(host, "www.intercot.com")
|| dnsDomainIs(host, "www.intergraffix.com")
|| dnsDomainIs(host, "www.interknowledge.com")
|| dnsDomainIs(host, "www.interlog.com")
|| dnsDomainIs(host, "www.internet4kids.com")
|| dnsDomainIs(host, "www.intersurf.com")
|| dnsDomainIs(host, "www.inthe80s.com")
|| dnsDomainIs(host, "www.inventorsmuseum.com")
|| dnsDomainIs(host, "www.inwap.com")
|| dnsDomainIs(host, "www.ioa.com")
|| dnsDomainIs(host, "www.ionet.net")
|| dnsDomainIs(host, "www.iowacity.com")
|| dnsDomainIs(host, "www.ireland-now.com")
|| dnsDomainIs(host, "www.ireland.com")
|| dnsDomainIs(host, "www.irelandseye.com")
|| dnsDomainIs(host, "www.irlgov.ie")
|| dnsDomainIs(host, "www.isd.net")
|| dnsDomainIs(host, "www.islandnet.com")
|| dnsDomainIs(host, "www.isomedia.com")
|| dnsDomainIs(host, "www.itftennis.com")
|| dnsDomainIs(host, "www.itpi.dpi.state.nc.us")
|| dnsDomainIs(host, "www.itskwanzaatime.com")
|| dnsDomainIs(host, "www.itss.raytheon.com")
|| dnsDomainIs(host, "www.iuma.com")
|| dnsDomainIs(host, "www.iwaynet.net")
|| dnsDomainIs(host, "www.iwc.com")
|| dnsDomainIs(host, "www.iwight.gov.uk")
|| dnsDomainIs(host, "www.ixpres.com")
|| dnsDomainIs(host, "www.j.b.allen.btinternet.co.uk")
|| dnsDomainIs(host, "www.jabuti.com")
|| dnsDomainIs(host, "www.jackinthebox.com")
|| dnsDomainIs(host, "www.jaffebros.com")
|| dnsDomainIs(host, "www.jaguars.com")
|| dnsDomainIs(host, "www.jamaica-gleaner.com")
|| dnsDomainIs(host, "www.jamm.com")
|| dnsDomainIs(host, "www.janbrett.com")
|| dnsDomainIs(host, "www.janetstevens.com")
|| dnsDomainIs(host, "www.japan-guide.com")
|| dnsDomainIs(host, "www.jargon.net")
|| dnsDomainIs(host, "www.javelinamx.com")
|| dnsDomainIs(host, "www.jayjay.com")
|| dnsDomainIs(host, "www.jazclass.aust.com")
)
return "PROXY proxy.hclib.org:80";
else
return "PROXY 172.16.100.20:8080";
}
reportCompare('No Crash', 'No Crash', '');
| sam/htmlunit-rhino-fork | testsrc/tests/js1_5/Regress/regress-89443.js | JavaScript | mpl-2.0 | 94,445 |
package aws
import (
"errors"
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceAwsNetworkAcls() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsNetworkAclsRead,
Schema: map[string]*schema.Schema{
"filter": ec2CustomFiltersSchema(),
"tags": tagsSchemaComputed(),
"vpc_id": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
},
}
}
func dataSourceAwsNetworkAclsRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
req := &ec2.DescribeNetworkAclsInput{}
if v, ok := d.GetOk("vpc_id"); ok {
req.Filters = buildEC2AttributeFilterList(
map[string]string{
"vpc-id": v.(string),
},
)
}
filters, filtersOk := d.GetOk("filter")
tags, tagsOk := d.GetOk("tags")
if tagsOk {
req.Filters = append(req.Filters, buildEC2TagFilterList(
tagsFromMap(tags.(map[string]interface{})),
)...)
}
if filtersOk {
req.Filters = append(req.Filters, buildEC2CustomFilterList(
filters.(*schema.Set),
)...)
}
if len(req.Filters) == 0 {
// Don't send an empty filters list; the EC2 API won't accept it.
req.Filters = nil
}
log.Printf("[DEBUG] DescribeNetworkAcls %s\n", req)
resp, err := conn.DescribeNetworkAcls(req)
if err != nil {
return err
}
if resp == nil || len(resp.NetworkAcls) == 0 {
return errors.New("no matching network ACLs found")
}
networkAcls := make([]string, 0)
for _, networkAcl := range resp.NetworkAcls {
networkAcls = append(networkAcls, aws.StringValue(networkAcl.NetworkAclId))
}
d.SetId(resource.UniqueId())
if err := d.Set("ids", networkAcls); err != nil {
return fmt.Errorf("Error setting network ACL ids: %s", err)
}
return nil
}
| tpounds/terraform | vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_network_acls.go | GO | mpl-2.0 | 1,999 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* test_ocspchecker.c
*
* Test OcspChecker function
*
*/
#include "testutil.h"
#include "testutil_nss.h"
static void *plContext = NULL;
static void
printUsage(void)
{
(void)printf("\nUSAGE:\nOcspChecker -d <certStoreDirectory> TestName "
"[ENE|EE] <certLocationDirectory> <trustedCert> "
"<targetCert>\n\n");
(void)printf("Validates a chain of certificates between "
"<trustedCert> and <targetCert>\n"
"using the certs and CRLs in <certLocationDirectory> and "
"pkcs11 db from <certStoreDirectory>. "
"If ENE is specified,\n"
"then an Error is Not Expected. "
"If EE is specified, an Error is Expected.\n");
}
static char *
createFullPathName(
char *dirName,
char *certFile,
void *plContext)
{
PKIX_UInt32 certFileLen;
PKIX_UInt32 dirNameLen;
char *certPathName = NULL;
PKIX_TEST_STD_VARS();
certFileLen = PL_strlen(certFile);
dirNameLen = PL_strlen(dirName);
PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Malloc(dirNameLen +
certFileLen +
2,
(void **)&certPathName,
plContext));
PL_strcpy(certPathName, dirName);
PL_strcat(certPathName, "/");
PL_strcat(certPathName, certFile);
printf("certPathName = %s\n", certPathName);
cleanup:
PKIX_TEST_RETURN();
return (certPathName);
}
static PKIX_Error *
testDefaultCertStore(PKIX_ValidateParams *valParams, char *crlDir)
{
PKIX_PL_String *dirString = NULL;
PKIX_CertStore *certStore = NULL;
PKIX_ProcessingParams *procParams = NULL;
PKIX_PL_Date *validity = NULL;
PKIX_List *revCheckers = NULL;
PKIX_RevocationChecker *revChecker = NULL;
PKIX_PL_Object *revCheckerContext = NULL;
PKIX_OcspChecker *ocspChecker = NULL;
PKIX_TEST_STD_VARS();
subTest("PKIX_PL_CollectionCertStoreContext_Create");
/* Create CollectionCertStore */
PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_String_Create(PKIX_ESCASCII, crlDir, 0, &dirString, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CollectionCertStore_Create(dirString, &certStore, plContext));
/* Create CertStore */
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ValidateParams_GetProcessingParams(valParams, &procParams, plContext));
subTest("PKIX_ProcessingParams_AddCertStore");
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_AddCertStore(procParams, certStore, plContext));
subTest("PKIX_ProcessingParams_SetRevocationEnabled");
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_SetRevocationEnabled(procParams, PKIX_FALSE, plContext));
/* create current Date */
PKIX_TEST_EXPECT_NO_ERROR(pkix_pl_Date_CreateFromPRTime(PR_Now(), &validity, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_Create(&revCheckers, plContext));
/* create revChecker */
PKIX_TEST_EXPECT_NO_ERROR(PKIX_OcspChecker_Initialize(validity,
NULL, /* pwArg */
NULL, /* Use default responder */
&revChecker,
plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_RevocationChecker_GetRevCheckerContext(revChecker, &revCheckerContext, plContext));
/* Check that this object is a ocsp checker */
PKIX_TEST_EXPECT_NO_ERROR(pkix_CheckType(revCheckerContext, PKIX_OCSPCHECKER_TYPE, plContext));
ocspChecker = (PKIX_OcspChecker *)revCheckerContext;
PKIX_TEST_EXPECT_NO_ERROR(PKIX_OcspChecker_SetVerifyFcn(ocspChecker,
PKIX_PL_OcspResponse_UseBuildChain,
plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_AppendItem(revCheckers, (PKIX_PL_Object *)revChecker, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_SetRevocationCheckers(procParams, revCheckers, plContext));
cleanup:
PKIX_TEST_DECREF_AC(dirString);
PKIX_TEST_DECREF_AC(procParams);
PKIX_TEST_DECREF_AC(certStore);
PKIX_TEST_DECREF_AC(revCheckers);
PKIX_TEST_DECREF_AC(revChecker);
PKIX_TEST_DECREF_AC(ocspChecker);
PKIX_TEST_DECREF_AC(validity);
PKIX_TEST_RETURN();
return (0);
}
int
test_ocsp(int argc, char *argv[])
{
PKIX_ValidateParams *valParams = NULL;
PKIX_ProcessingParams *procParams = NULL;
PKIX_ComCertSelParams *certSelParams = NULL;
PKIX_CertSelector *certSelector = NULL;
PKIX_ValidateResult *valResult = NULL;
PKIX_UInt32 actualMinorVersion;
PKIX_UInt32 j = 0;
PKIX_UInt32 k = 0;
PKIX_UInt32 chainLength = 0;
PKIX_Boolean testValid = PKIX_TRUE;
PKIX_List *chainCerts = NULL;
PKIX_VerifyNode *verifyTree = NULL;
PKIX_PL_String *verifyString = NULL;
PKIX_PL_Cert *dirCert = NULL;
PKIX_PL_Cert *trustedCert = NULL;
PKIX_PL_Cert *targetCert = NULL;
PKIX_TrustAnchor *anchor = NULL;
PKIX_List *anchors = NULL;
char *dirCertName = NULL;
char *anchorCertName = NULL;
char *dirName = NULL;
char *databaseDir = NULL;
PKIX_TEST_STD_VARS();
if (argc < 5) {
printUsage();
return (0);
}
startTests("OcspChecker");
PKIX_TEST_EXPECT_NO_ERROR(
PKIX_PL_NssContext_Create(0, PKIX_FALSE, NULL, &plContext));
/* ENE = expect no error; EE = expect error */
if (PORT_Strcmp(argv[2 + j], "ENE") == 0) {
testValid = PKIX_TRUE;
} else if (PORT_Strcmp(argv[2 + j], "EE") == 0) {
testValid = PKIX_FALSE;
} else {
printUsage();
return (0);
}
subTest(argv[1 + j]);
dirName = argv[3 + j];
chainLength = argc - j - 5;
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_Create(&chainCerts, plContext));
for (k = 0; k < chainLength; k++) {
dirCert = createCert(dirName, argv[5 + k + j], plContext);
if (k == 0) {
PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Object_IncRef((PKIX_PL_Object *)dirCert, plContext));
targetCert = dirCert;
}
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_AppendItem(chainCerts, (PKIX_PL_Object *)dirCert, plContext));
PKIX_TEST_DECREF_BC(dirCert);
}
/* create processing params with list of trust anchors */
anchorCertName = argv[4 + j];
trustedCert = createCert(dirName, anchorCertName, plContext);
PKIX_TEST_EXPECT_NO_ERROR(PKIX_TrustAnchor_CreateWithCert(trustedCert, &anchor, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_Create(&anchors, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_AppendItem(anchors, (PKIX_PL_Object *)anchor, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_Create(anchors, &procParams, plContext));
/* create CertSelector with target certificate in params */
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ComCertSelParams_Create(&certSelParams, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ComCertSelParams_SetCertificate(certSelParams, targetCert, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_CertSelector_Create(NULL, NULL, &certSelector, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_CertSelector_SetCommonCertSelectorParams(certSelector, certSelParams, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ProcessingParams_SetTargetCertConstraints(procParams, certSelector, plContext));
PKIX_TEST_EXPECT_NO_ERROR(PKIX_ValidateParams_Create(procParams, chainCerts, &valParams, plContext));
testDefaultCertStore(valParams, dirName);
pkixTestErrorResult = PKIX_ValidateChain(valParams, &valResult, &verifyTree, plContext);
if (pkixTestErrorResult) {
if (testValid == PKIX_FALSE) { /* EE */
(void)printf("EXPECTED ERROR RECEIVED!\n");
} else { /* ENE */
testError("UNEXPECTED ERROR RECEIVED");
}
PKIX_TEST_DECREF_BC(pkixTestErrorResult);
} else {
if (testValid == PKIX_TRUE) { /* ENE */
(void)printf("EXPECTED SUCCESSFUL VALIDATION!\n");
} else { /* EE */
(void)printf("UNEXPECTED SUCCESSFUL VALIDATION!\n");
}
}
subTest("Displaying VerifyTree");
if (verifyTree == NULL) {
(void)printf("VerifyTree is NULL\n");
} else {
PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Object_ToString((PKIX_PL_Object *)verifyTree, &verifyString, plContext));
(void)printf("verifyTree is\n%s\n",
verifyString->escAsciiString);
PKIX_TEST_DECREF_BC(verifyString);
PKIX_TEST_DECREF_BC(verifyTree);
}
cleanup:
PKIX_TEST_DECREF_AC(valParams);
PKIX_TEST_DECREF_AC(procParams);
PKIX_TEST_DECREF_AC(certSelParams);
PKIX_TEST_DECREF_AC(certSelector);
PKIX_TEST_DECREF_AC(chainCerts);
PKIX_TEST_DECREF_AC(anchors);
PKIX_TEST_DECREF_AC(anchor);
PKIX_TEST_DECREF_AC(trustedCert);
PKIX_TEST_DECREF_AC(targetCert);
PKIX_TEST_DECREF_AC(valResult);
PKIX_Shutdown(plContext);
PKIX_TEST_RETURN();
endTests("OcspChecker");
return (0);
}
| Yukarumya/Yukarum-Redfoxes | security/nss/cmd/libpkix/pkix/top/test_ocsp.c | C | mpl-2.0 | 9,426 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Second article</title>
<link rel="stylesheet" href="../../../../../theme/css/main.css" />
<link href="http://blog.notmyidea.org/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Alexis' log Atom Feed" />
<link href="http://blog.notmyidea.org/feeds/all.rss.xml" type="application/rss+xml" rel="alternate" title="Alexis' log RSS Feed" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body id="index" class="home">
<a href="http://github.com/ametaireau/">
<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub" />
</a>
<header id="banner" class="body">
<h1><a href="../../../../../">Alexis' log </a></h1>
<nav><ul>
<li><a href="../../../../../tag/oh.html">Oh Oh Oh</a></li>
<li><a href="../../../../../override/">Override url/save_as</a></li>
<li><a href="../../../../../pages/this-is-a-test-page.html">This is a test page</a></li>
<li><a href="../../../../../category/yeah.html">yeah</a></li>
<li class="active"><a href="../../../../../category/misc.html">misc</a></li>
<li><a href="../../../../../category/cat1.html">cat1</a></li>
<li><a href="../../../../../category/bar.html">bar</a></li>
</ul></nav>
</header><!-- /#banner -->
<section id="content" class="body">
<article>
<header>
<h1 class="entry-title">
<a href="../../../../../posts/2012/février/29/second-article/" rel="bookmark"
title="Permalink to Second article">Second article</a></h1>
</header>
<div class="entry-content">
<footer class="post-info">
<abbr class="published" title="2012-02-29T00:00:00+01:00">
Published: 29 février 2012
</abbr>
<address class="vcard author">
By <a class="url fn" href="../../../../../author/alexis-metaireau.html">Alexis Métaireau</a>
</address>
<p>In <a href="../../../../../category/misc.html">misc</a>. </p>
<p>tags: <a href="../../../../../tag/foo.html">foo</a> <a href="../../../../../tag/bar.html">bar</a> <a href="../../../../../tag/baz.html">baz</a> </p>Translations:
<a href="../../../../../second-article-fr.html">fr</a>
</footer><!-- /.post-info --> <p>This is some article, in english</p>
</div><!-- /.entry-content -->
<div class="comments">
<h2>Comments !</h2>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'blog-notmyidea';
var disqus_identifier = 'posts/2012/février/29/second-article/';
var disqus_url = '../../../../../posts/2012/février/29/second-article/';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//blog-notmyidea.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the comments.</noscript>
</div>
</article>
</section>
<section id="extras" class="body">
<div class="blogroll">
<h2>blogroll</h2>
<ul>
<li><a href="http://biologeek.org">Biologeek</a></li>
<li><a href="http://filyb.info/">Filyb</a></li>
<li><a href="http://www.libert-fr.com">Libert-fr</a></li>
<li><a href="http://prendreuncafe.com/blog/">N1k0</a></li>
<li><a href="http://ziade.org/blog">Tarek Ziadé</a></li>
<li><a href="http://zubin71.wordpress.com/">Zubin Mithra</a></li>
</ul>
</div><!-- /.blogroll -->
<div class="social">
<h2>social</h2>
<ul>
<li><a href="http://blog.notmyidea.org/feeds/all.atom.xml" type="application/atom+xml" rel="alternate">atom feed</a></li>
<li><a href="http://blog.notmyidea.org/feeds/all.rss.xml" type="application/rss+xml" rel="alternate">rss feed</a></li>
<li><a href="http://twitter.com/ametaireau">twitter</a></li>
<li><a href="http://lastfm.com/user/akounet">lastfm</a></li>
<li><a href="http://github.com/ametaireau">github</a></li>
</ul>
</div><!-- /.social -->
</section><!-- /#extras -->
<footer id="contentinfo" class="body">
<address id="about" class="vcard body">
Proudly powered by <a href="http://getpelican.com/">Pelican</a>, which takes great advantage of <a href="http://python.org">Python</a>.
</address><!-- /#about -->
<p>The theme is by <a href="http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!</p>
</footer><!-- /#contentinfo -->
<script type="text/javascript">
var disqus_shortname = 'blog-notmyidea';
(function () {
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
</body>
</html> | goerz/pelican | pelican/tests/output/custom_locale/posts/2012/février/29/second-article/index.html | HTML | agpl-3.0 | 5,907 |
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ExampleApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "MooseSyntax.h"
// Example 13 Includes
#include "ExampleFunction.h"
template<>
InputParameters validParams<ExampleApp>()
{
InputParameters params = validParams<MooseApp>();
params.set<bool>("use_legacy_uo_initialization") = false;
params.set<bool>("use_legacy_uo_aux_computation") = false;
return params;
}
ExampleApp::ExampleApp(InputParameters parameters) :
MooseApp(parameters)
{
srand(processor_id());
Moose::registerObjects(_factory);
ExampleApp::registerObjects(_factory);
Moose::associateSyntax(_syntax, _action_factory);
ExampleApp::associateSyntax(_syntax, _action_factory);
}
ExampleApp::~ExampleApp()
{
}
void
ExampleApp::registerApps()
{
registerApp(ExampleApp);
}
void
ExampleApp::registerObjects(Factory & factory)
{
registerFunction(ExampleFunction);
}
void
ExampleApp::associateSyntax(Syntax & /*syntax*/, ActionFactory & /*action_factory*/)
{
}
| katyhuff/moose | examples/ex13_functions/src/base/ExampleApp.C | C++ | lgpl-2.1 | 1,845 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.doclava;
import java.util.ArrayList;
public class ParsedTagInfo extends TagInfo {
private ContainerInfo mContainer;
private String mCommentText;
private Comment mComment;
ParsedTagInfo(String name, String kind, String text, ContainerInfo base, SourcePositionInfo sp) {
super(name, kind, text, SourcePositionInfo.findBeginning(sp, text));
mContainer = base;
mCommentText = text;
}
public TagInfo[] commentTags() {
if (mComment == null) {
mComment = new Comment(mCommentText, mContainer, position());
}
return mComment.tags();
}
protected void setCommentText(String comment) {
mCommentText = comment;
}
public static <T extends ParsedTagInfo> TagInfo[] joinTags(T[] tags) {
ArrayList<TagInfo> list = new ArrayList<TagInfo>();
final int N = tags.length;
for (int i = 0; i < N; i++) {
TagInfo[] t = tags[i].commentTags();
final int M = t.length;
for (int j = 0; j < M; j++) {
list.add(t[j]);
}
}
return list.toArray(new TagInfo[list.size()]);
}
}
| kwf2030/doclava | src/main/java/com/google/doclava/ParsedTagInfo.java | Java | apache-2.0 | 1,692 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WingtipToys
{
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | sorenhl/Glimpse | source/Glimpse.WebForms.WingTip.Sample/About.aspx.cs | C# | apache-2.0 | 300 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utility functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long,wildcard-import
from tensorflow.contrib.kfac.python.ops.utils import *
from tensorflow.python.util.all_util import remove_undocumented
# pylint: enable=unused-import,line-too-long,wildcard-import
_allowed_symbols = [
"SequenceDict",
"setdefault",
"tensors_to_column",
"column_to_tensors",
"kronecker_product",
"layer_params_to_mat2d",
"mat2d_to_layer_params",
"compute_pi",
"posdef_inv",
"posdef_inv_matrix_inverse",
"posdef_inv_cholesky",
"posdef_inv_funcs",
"SubGraph",
"generate_random_signs",
"fwd_gradients",
]
remove_undocumented(__name__, allowed_exception_list=_allowed_symbols)
| benoitsteiner/tensorflow-opencl | tensorflow/contrib/kfac/python/ops/utils_lib.py | Python | apache-2.0 | 1,520 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gobblin.data.management.retention.action;
import java.io.IOException;
import java.util.List;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import org.apache.gobblin.data.management.policy.VersionSelectionPolicy;
import org.apache.gobblin.data.management.version.DatasetVersion;
import org.apache.gobblin.data.management.version.FileStatusAware;
import org.apache.gobblin.data.management.version.FileSystemDatasetVersion;
import org.apache.gobblin.util.ConfigUtils;
/**
* A {@link RetentionAction} that is used to change the permissions/owner/group of a {@link FileSystemDatasetVersion}
*/
@Slf4j
public class AccessControlAction extends RetentionAction {
/**
* Optional - The permission mode to set on selected versions either in octal or symbolic format. E.g 750
*/
private static final String MODE_KEY = "mode";
/**
* Optional - The owner to set on selected versions
*/
private static final String OWNER_KEY = "owner";
/**
* Optional - The group to set on selected versions
*/
private static final String GROUP_KEY = "group";
private final Optional<FsPermission> permission;
private final Optional<String> owner;
private final Optional<String> group;
@VisibleForTesting
@Getter
private final VersionSelectionPolicy<DatasetVersion> selectionPolicy;
@VisibleForTesting
AccessControlAction(Config actionConfig, FileSystem fs, Config jobConfig) {
super(actionConfig, fs, jobConfig);
this.permission = actionConfig.hasPath(MODE_KEY) ? Optional.of(new FsPermission(actionConfig.getString(MODE_KEY))) : Optional
.<FsPermission> absent();
this.owner = Optional.fromNullable(ConfigUtils.getString(actionConfig, OWNER_KEY, null));
this.group = Optional.fromNullable(ConfigUtils.getString(actionConfig, GROUP_KEY, null));
this.selectionPolicy = createSelectionPolicy(actionConfig, jobConfig);
}
/**
* Applies {@link #selectionPolicy} on <code>allVersions</code> and modifies permission/owner to the selected {@link DatasetVersion}s
* where necessary.
* <p>
* This action only available for {@link FileSystemDatasetVersion}. It simply skips the operation if a different type
* of {@link DatasetVersion} is passed.
* </p>
* {@inheritDoc}
* @see org.apache.gobblin.data.management.retention.action.RetentionAction#execute(java.util.List)
*/
@Override
public void execute(List<DatasetVersion> allVersions) throws IOException {
// Select version on which access control actions need to performed
for (DatasetVersion datasetVersion : this.selectionPolicy.listSelectedVersions(allVersions)) {
executeOnVersion(datasetVersion);
}
}
private void executeOnVersion(DatasetVersion datasetVersion) throws IOException {
// Perform action if it is a FileSystemDatasetVersion
if (datasetVersion instanceof FileSystemDatasetVersion) {
FileSystemDatasetVersion fsDatasetVersion = (FileSystemDatasetVersion) datasetVersion;
// If the version is filestatus aware, use the filestatus to ignore permissions update when the path already has
// the desired permissions
if (datasetVersion instanceof FileStatusAware) {
for (FileStatus fileStatus : ((FileStatusAware)datasetVersion).getFileStatuses()) {
if (needsPermissionsUpdate(fileStatus) || needsOwnerUpdate(fileStatus) || needsGroupUpdate(fileStatus)) {
updatePermissionsAndOwner(fileStatus.getPath());
}
}
} else {
for (Path path : fsDatasetVersion.getPaths()) {
updatePermissionsAndOwner(path);
}
}
}
}
private boolean needsPermissionsUpdate(FileStatus fileStatus) {
return this.permission.isPresent() && !this.permission.get().equals(fileStatus.getPermission());
}
private boolean needsOwnerUpdate(FileStatus fileStatus) {
return this.owner.isPresent() && !StringUtils.equals(owner.get(), fileStatus.getOwner());
}
private boolean needsGroupUpdate(FileStatus fileStatus) {
return this.group.isPresent() && !StringUtils.equals(group.get(), fileStatus.getGroup());
}
private void updatePermissionsAndOwner(Path path) throws IOException {
boolean atLeastOneOperationFailed = false;
if (this.fs.exists(path)) {
try {
// Update permissions if set in config
if (this.permission.isPresent()) {
if (!this.isSimulateMode) {
this.fs.setPermission(path, this.permission.get());
log.debug("Set permissions for {} to {}", path, this.permission.get());
} else {
log.info("Simulating set permissions for {} to {}", path, this.permission.get());
}
}
} catch (IOException e) {
log.error(String.format("Setting permissions failed on %s", path), e);
atLeastOneOperationFailed = true;
}
// Update owner and group if set in config
if (this.owner.isPresent() || this.group.isPresent()) {
if (!this.isSimulateMode) {
this.fs.setOwner(path, this.owner.orNull(), this.group.orNull());
log.debug("Set owner and group for {} to {}:{}", path, this.owner.orNull(),
this.group.orNull());
} else {
log.info("Simulating set owner and group for {} to {}:{}", path, this.owner.orNull(),
this.group.orNull());
}
}
if (atLeastOneOperationFailed) {
throw new RuntimeException(String.format(
"At least one failure happened while processing %s. Look for previous logs for failures", path));
}
}
}
}
| aditya1105/gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/action/AccessControlAction.java | Java | apache-2.0 | 6,736 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() {
'use strict';
var ALERT_FETCH_LIMIT = 1000 * 60 * 60 * 12;
var ALERT_REFRESH_INTERVAL = 1000 * 10;
var ALERT_TEMPLATE = '#/site/${siteId}/alert/detail/${alertId}?timestamp=${timestamp}';
var serviceModule = angular.module('eagle.service');
serviceModule.service('Alert', function ($notification, Time, CompatibleEntity) {
var Alert = {
list: null,
};
$notification.getPromise().then(function () {
function queryAlerts() {
var endTime = new Time();
var list = CompatibleEntity.query("LIST", {
query: "AlertService",
startTime: endTime.clone().subtract(ALERT_FETCH_LIMIT, 'ms'),
endTime: endTime
});
list._then(function () {
if (!Alert.list) {
Alert.list = list;
return;
}
var subList = common.array.minus(list, Alert.list, ['encodedRowkey'], ['encodedRowkey']);
Alert.list = list;
$.each(subList, function (i, alert) {
$notification(alert.alertSubject, common.template(ALERT_TEMPLATE, {
siteId: alert.tags.siteId,
alertId: alert.tags.alertId,
timestamp: alert.timestamp,
}));
});
});
}
queryAlerts();
setInterval(queryAlerts, ALERT_REFRESH_INTERVAL);
});
return Alert;
});
})();
| qingwen220/eagle | eagle-server/src/main/webapp/app/dev/public/js/services/alertSrv.js | JavaScript | apache-2.0 | 2,048 |
HandlebarsIntl.__addLocaleData({"locale":"guz","pluralRuleFunction":function (n,ord){if(ord)return"other";return"other"},"fields":{"year":{"displayName":"Omwaka","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"Omotienyi","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"Rituko","relative":{"0":"Rero","1":"Mambia","-1":"Igoro"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"Ensa","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"Edakika","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"Esekendi","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}});
HandlebarsIntl.__addLocaleData({"locale":"guz-KE","parentLocale":"guz"});
| yoanngern/iahm_2016 | wp-content/themes/iahm_2016/js/vendor/handlebars-intl/locale-data/guz.js | JavaScript | apache-2.0 | 1,039 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.spi.checkpoint.jdbc;
import org.apache.ignite.spi.checkpoint.*;
import org.apache.ignite.testframework.junits.spi.*;
import org.hsqldb.jdbc.*;
/**
* Grid jdbc checkpoint SPI custom config self test.
*/
@GridSpiTest(spi = JdbcCheckpointSpi.class, group = "Checkpoint SPI")
public class JdbcCheckpointSpiCustomConfigSelfTest extends
GridCheckpointSpiAbstractTest<JdbcCheckpointSpi> {
/** {@inheritDoc} */
@Override protected void spiConfigure(JdbcCheckpointSpi spi) throws Exception {
jdbcDataSource ds = new jdbcDataSource();
ds.setDatabase("jdbc:hsqldb:mem:gg_test_" + getClass().getSimpleName());
ds.setUser("sa");
ds.setPassword("");
spi.setDataSource(ds);
spi.setCheckpointTableName("custom_config_checkpoints");
spi.setKeyFieldName("key");
spi.setValueFieldName("value");
spi.setValueFieldType("longvarbinary");
spi.setExpireDateFieldName("expire_date");
super.spiConfigure(spi);
}
}
| akuznetsov-gridgain/ignite | modules/core/src/test/java/org/apache/ignite/spi/checkpoint/jdbc/JdbcCheckpointSpiCustomConfigSelfTest.java | Java | apache-2.0 | 1,829 |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that the lambda kind is inferred correctly as a return
// expression
fn unique() -> proc():'static { proc() () }
pub fn main() {
}
| emk/rust | src/test/run-pass/newlambdas-ret-infer2.rs | Rust | apache-2.0 | 608 |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.config;
import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfigurationCollectionFactory;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.Fragment;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadCompatible;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.util.Preconditions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A factory class for {@link BuildConfiguration} instances. This is unfortunately more complex,
* and should be simplified in the future, if
* possible. Right now, creating a {@link BuildConfiguration} instance involves
* creating the instance itself and the related configurations; the main method
* is {@link #createConfigurations}.
*
* <p>Avoid calling into this class, and instead use the skyframe infrastructure to obtain
* configuration instances.
*
* <p>Blaze currently relies on the fact that all {@link BuildConfiguration}
* instances used in a build can be constructed ahead of time by this class.
*/
@ThreadCompatible // safe as long as separate instances are used
public final class ConfigurationFactory {
private final List<ConfigurationFragmentFactory> configurationFragmentFactories;
private final ConfigurationCollectionFactory configurationCollectionFactory;
public ConfigurationFactory(
ConfigurationCollectionFactory configurationCollectionFactory,
ConfigurationFragmentFactory... fragmentFactories) {
this(configurationCollectionFactory, ImmutableList.copyOf(fragmentFactories));
}
public ConfigurationFactory(
ConfigurationCollectionFactory configurationCollectionFactory,
List<ConfigurationFragmentFactory> fragmentFactories) {
this.configurationCollectionFactory =
Preconditions.checkNotNull(configurationCollectionFactory);
this.configurationFragmentFactories = ImmutableList.copyOf(fragmentFactories);
}
/**
* Creates a set of build configurations with top-level configuration having the given options.
*
* <p>The rest of the configurations are created based on the set of transitions available.
*/
@Nullable
public BuildConfiguration createConfigurations(
Cache<String, BuildConfiguration> cache,
PackageProviderForConfigurations loadedPackageProvider,
BuildOptions buildOptions,
EventHandler errorEventListener)
throws InvalidConfigurationException, InterruptedException {
return configurationCollectionFactory.createConfigurations(this, cache,
loadedPackageProvider, buildOptions, errorEventListener);
}
/**
* Returns a {@link com.google.devtools.build.lib.analysis.config.BuildConfiguration} based on the
* given set of build options.
*
* <p>If the configuration has already been created, re-uses it, otherwise, creates a new one.
*/
@Nullable
public BuildConfiguration getConfiguration(
PackageProviderForConfigurations loadedPackageProvider,
BuildOptions buildOptions,
boolean actionsDisabled,
Cache<String, BuildConfiguration> cache)
throws InvalidConfigurationException, InterruptedException {
String cacheKey = buildOptions.computeCacheKey();
BuildConfiguration result = cache.getIfPresent(cacheKey);
if (result != null) {
return result;
}
Map<Class<? extends Fragment>, Fragment> fragments = new HashMap<>();
// Create configuration fragments
for (ConfigurationFragmentFactory factory : configurationFragmentFactories) {
Class<? extends Fragment> fragmentType = factory.creates();
Fragment fragment = loadedPackageProvider.getFragment(buildOptions, fragmentType);
if (fragment != null && fragments.get(fragment.getClass()) == null) {
fragments.put(fragment.getClass(), fragment);
}
}
BlazeDirectories directories = loadedPackageProvider.getDirectories();
if (loadedPackageProvider.valuesMissing()) {
return null;
}
result = new BuildConfiguration(directories, fragments, buildOptions, actionsDisabled);
cache.put(cacheKey, result);
return result;
}
public List<ConfigurationFragmentFactory> getFactories() {
return configurationFragmentFactories;
}
}
| iamthearm/bazel | src/main/java/com/google/devtools/build/lib/analysis/config/ConfigurationFactory.java | Java | apache-2.0 | 5,071 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.document.blob.ds;
import java.util.Date;
import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore;
import org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreUtils;
import org.apache.jackrabbit.oak.plugins.document.DocumentMK;
import org.apache.jackrabbit.oak.plugins.document.MongoBlobGCTest;
import org.apache.jackrabbit.oak.plugins.document.MongoUtils;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
/**
* Test for MongoMK GC with {@link DataStoreBlobStore}
*
*/
public class MongoDataStoreBlobGCTest extends MongoBlobGCTest {
protected Date startDate;
protected DataStoreBlobStore blobStore;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
Assume.assumeNotNull(DataStoreUtils.getBlobStore());
} catch (Exception e) {
Assume.assumeNoException(e);
}
}
@Override
protected DocumentMK.Builder addToBuilder(DocumentMK.Builder mk) {
return super.addToBuilder(mk).setBlobStore(blobStore);
}
@Before
@Override
public void setUpConnection() throws Exception {
startDate = new Date();
blobStore = DataStoreUtils.getBlobStore(folder.newFolder());
super.setUpConnection();
}
}
| trekawek/jackrabbit-oak | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/blob/ds/MongoDataStoreBlobGCTest.java | Java | apache-2.0 | 2,161 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.physical.impl.validate;
import java.util.List;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.ops.ExecutorFragmentContext;
import org.apache.drill.exec.physical.config.IteratorValidator;
import org.apache.drill.exec.physical.impl.BatchCreator;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
public class IteratorValidatorCreator implements BatchCreator<IteratorValidator>{
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(IteratorValidatorCreator.class);
@Override
public IteratorValidatorBatchIterator getBatch(ExecutorFragmentContext context, IteratorValidator config,
List<RecordBatch> children)
throws ExecutionSetupException {
Preconditions.checkArgument(children.size() == 1);
RecordBatch child = children.iterator().next();
IteratorValidatorBatchIterator iter = new IteratorValidatorBatchIterator(child, config.isRepeatable);
boolean validateBatches = context.getOptions().getOption(ExecConstants.ENABLE_VECTOR_VALIDATOR) ||
context.getConfig().getBoolean(ExecConstants.ENABLE_VECTOR_VALIDATION);
iter.enableBatchValidation(validateBatches);
logger.trace("Iterator validation enabled for " + child.getClass().getSimpleName() +
(validateBatches ? " with vector validation" : ""));
return iter;
}
}
| apache/drill | exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorCreator.java | Java | apache-2.0 | 2,373 |
<?php
require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
/**
* OAuth Store
*
* Updated version, works with consumer-callbacks, certificates and 1.0-RevA protocol
* behaviour (requestToken-callbacks and verifiers)
*
* @author Andreas Åkre Solberg, <andreas.solberg@uninett.no>, UNINETT AS.
* @author Mark Dobrinic, <mdobrinic@cozmanova.com>, Cozmanova bv
* @package SimpleSAMLphp
*/
class sspmod_oauth_OAuthStore extends OAuthDataStore {
private $store;
private $config;
private $defaultversion = '1.0';
protected $_store_tables = array(
'consumers' => 'consumer = array with consumer attributes',
'nonce' => 'nonce+consumer_key = -boolean-',
'requesttorequest' => 'requestToken.key = array(version,callback,consumerKey,)',
'authorized' => 'requestToken.key, verifier = array(authenticated-user-attributes)',
'access' => 'accessToken.key+consumerKey = accestoken',
'request' => 'requestToken.key+consumerKey = requesttoken',
);
function __construct() {
$this->store = new sspmod_core_Storage_SQLPermanentStorage('oauth');
$this->config = SimpleSAML_Configuration::getOptionalConfig('module_oauth.php');
}
/**
* Attach the data to the token, and establish the Callback URL and verifier
* @param $requestTokenKey RequestToken that was authorized
* @param $data Data that is authorized and to be attached to the requestToken
* @return array(string:url, string:verifier) ; empty verifier for 1.0-response
*/
public function authorize($requestTokenKey, $data) {
$url = null;
$verifier = '';
$version = $this->defaultversion;
// See whether to remember values from the original requestToken request:
$request_attributes = $this->store->get('requesttorequest', $requestTokenKey, ''); // must be there ..
if ($request_attributes['value']) {
// establish version to work with
$v = $request_attributes['value']['version'];
if ($v) $version = $v;
// establish callback to use
if ($request_attributes['value']['callback']) {
$url = $request_attributes['value']['callback'];
}
}
// Is there a callback registered? This is leading, even over a supplied oauth_callback-parameter
$oConsumer = $this->lookup_consumer($request_attributes['value']['consumerKey']);
if ($oConsumer && ($oConsumer->callback_url)) $url = $oConsumer->callback_url;
$verifier = SimpleSAML\Utils\Random::generateID();
$url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array("oauth_verifier"=>$verifier));
$this->store->set('authorized', $requestTokenKey, $verifier, $data, $this->config->getValue('requestTokenDuration', 60*30) );
return array($url, $verifier);
}
/**
* Perform lookup whether a given token exists in the list of authorized tokens; if a verifier is
* passed as well, the verifier *must* match the verifier that was registered with the token<br/>
* Note that an accessToken should never be stored with a verifier
* @param $requestToken
* @param $verifier
* @return unknown_type
*/
public function isAuthorized($requestToken, $verifier='') {
SimpleSAML_Logger::info('OAuth isAuthorized(' . $requestToken . ')');
return $this->store->exists('authorized', $requestToken, $verifier);
}
public function getAuthorizedData($token, $verifier = '') {
SimpleSAML_Logger::info('OAuth getAuthorizedData(' . $token . ')');
$data = $this->store->get('authorized', $token, $verifier);
return $data['value'];
}
public function moveAuthorizedData($requestToken, $verifier, $accessTokenKey) {
SimpleSAML_Logger::info('OAuth moveAuthorizedData(' . $requestToken . ', ' . $accessTokenKey . ')');
// Retrieve authorizedData from authorized.requestToken (with provider verifier)
$authorizedData = $this->getAuthorizedData($requestToken, $verifier);
// Remove the requesttoken+verifier from authorized store
$this->store->remove('authorized', $requestToken, $verifier);
// Add accesstoken with authorizedData to authorized store (with empty verifier)
// accessTokenKey+consumer => accessToken is already registered in 'access'-table
$this->store->set('authorized', $accessTokenKey, '', $authorizedData, $this->config->getValue('accessTokenDuration', 60*60*24));
}
public function lookup_consumer($consumer_key) {
SimpleSAML_Logger::info('OAuth lookup_consumer(' . $consumer_key . ')');
if (! $this->store->exists('consumers', $consumer_key, '')) return NULL;
$consumer = $this->store->get('consumers', $consumer_key, '');
$callback = NULL;
if ($consumer['value']['callback_url']) $callback = $consumer['value']['callback_url'];
if ($consumer['value']['RSAcertificate']) {
return new OAuthConsumer($consumer['value']['key'], $consumer['value']['RSAcertificate'], $callback);
} else {
return new OAuthConsumer($consumer['value']['key'], $consumer['value']['secret'], $callback);
}
}
function lookup_token($consumer, $tokenType = 'default', $token) {
SimpleSAML_Logger::info('OAuth lookup_token(' . $consumer->key . ', ' . $tokenType. ',' . $token . ')');
$data = $this->store->get($tokenType, $token, $consumer->key);
if ($data == NULL) throw new Exception('Could not find token');
return $data['value'];
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
SimpleSAML_Logger::info('OAuth lookup_nonce(' . $consumer . ', ' . $token. ',' . $nonce . ')');
if ($this->store->exists('nonce', $nonce, $consumer->key)) return TRUE;
$this->store->set('nonce', $nonce, $consumer->key, TRUE, $this->config->getValue('nonceCache', 60*60*24*14));
return FALSE;
}
function new_request_token($consumer, $callback = null, $version = null) {
SimpleSAML_Logger::info('OAuth new_request_token(' . $consumer . ')');
$lifetime = $this->config->getValue('requestTokenDuration', 60*30);
$token = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID());
$token->callback = $callback; // OAuth1.0-RevA
$this->store->set('request', $token->key, $consumer->key, $token, $lifetime);
// also store in requestToken->key => array('callback'=>CallbackURL, 'version'=>oauth_version
$request_attributes = array(
'callback' => $callback,
'version' => ($version?$version:$this->defaultversion),
'consumerKey' => $consumer->key,
);
$this->store->set('requesttorequest', $token->key, '', $request_attributes, $lifetime);
// also store in requestToken->key => Consumer->key (enables consumer-lookup during reqToken-authorization stage)
$this->store->set('requesttoconsumer', $token->key, '', $consumer->key, $lifetime);
return $token;
}
function new_access_token($requestToken, $consumer, $verifier = null) {
SimpleSAML_Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')');
$accestoken = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID());
$this->store->set('access', $accestoken->key, $consumer->key, $accestoken, $this->config->getValue('accessTokenDuration', 60*60*24) );
return $accestoken;
}
/**
* Return OAuthConsumer-instance that a given requestToken was issued to
* @param $requestTokenKey
* @return unknown_type
*/
public function lookup_consumer_by_requestToken($requestTokenKey) {
SimpleSAML_Logger::info('OAuth lookup_consumer_by_requestToken(' . $requestTokenKey . ')');
if (! $this->store->exists('requesttorequest', $requestTokenKey, '')) return NULL;
$request = $this->store->get('requesttorequest', $requestTokenKey, '');
$consumerKey = $request['value']['consumerKey'];
if (! $consumerKey) {
return NULL;
}
$consumer = $this->store->get('consumers', $consumerKey['value'], '');
return $consumer['value'];
}
}
| RKathees/is-connectors | tiqr/tiqr-client/modules/oauth/lib/OAuthStore.php | PHP | apache-2.0 | 7,852 |
/*jshint globalstrict:false, strict:false, unused : false */
/*global assertEqual, assertFalse, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief tests for dump/reload
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var db = require("org/arangodb").db;
var internal = require("internal");
var jsunity = require("jsunity");
function runSetup () {
'use strict';
internal.debugClearFailAt();
db._drop("UnitTestsRecovery1");
var c = db._create("UnitTestsRecovery1"), i;
c.ensureSkiplist("value");
for (i = 0; i < 1000; ++i) {
c.save({ value: i });
}
db._drop("UnitTestsRecovery2");
c = db._create("UnitTestsRecovery2");
c.ensureUniqueSkiplist("a.value");
for (i = 0; i < 1000; ++i) {
c.save({ a: { value: i } });
}
db._drop("UnitTestsRecovery3");
c = db._create("UnitTestsRecovery3");
c.ensureSkiplist("a", "b");
for (i = 0; i < 500; ++i) {
c.save({ a: (i % 2) + 1, b: 1 });
c.save({ a: (i % 2) + 1, b: 2 });
}
db._drop("test");
c = db._create("test");
c.save({ _key: "crashme" }, true);
internal.debugSegfault("crashing server");
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////
function recoverySuite () {
'use strict';
jsunity.jsUnity.attachAssertions();
return {
setUp: function () {
},
tearDown: function () {
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test whether we can restore the trx data
////////////////////////////////////////////////////////////////////////////////
testIndexesSkiplist : function () {
var c = db._collection("UnitTestsRecovery1"), idx, i;
idx = c.getIndexes()[1];
assertFalse(idx.unique);
assertFalse(idx.sparse);
assertEqual([ "value" ], idx.fields);
for (i = 0; i < 1000; ++i) {
assertEqual(1, c.byExampleSkiplist(idx.id, { value: i }).toArray().length);
}
c = db._collection("UnitTestsRecovery2");
idx = c.getIndexes()[1];
assertTrue(idx.unique);
assertFalse(idx.sparse);
assertEqual([ "a.value" ], idx.fields);
for (i = 0; i < 1000; ++i) {
assertEqual(1, c.byExampleSkiplist(idx.id, { "a.value" : i }).toArray().length);
}
c = db._collection("UnitTestsRecovery3");
idx = c.getIndexes()[1];
assertFalse(idx.unique);
assertFalse(idx.sparse);
assertEqual([ "a", "b" ], idx.fields);
assertEqual(250, c.byExampleSkiplist(idx.id, { a: 1, b: 1 }).toArray().length);
assertEqual(250, c.byExampleSkiplist(idx.id, { a: 1, b: 2 }).toArray().length);
assertEqual(250, c.byExampleSkiplist(idx.id, { a: 2, b: 1 }).toArray().length);
assertEqual(250, c.byExampleSkiplist(idx.id, { a: 2, b: 2 }).toArray().length);
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////
function main (argv) {
'use strict';
if (argv[1] === "setup") {
runSetup();
return 0;
}
else {
jsunity.run(recoverySuite);
return jsunity.done().status ? 0 : 1;
}
}
| CoDEmanX/ArangoDB | js/server/tests/recovery/indexes-skiplist.js | JavaScript | apache-2.0 | 4,197 |
/// <reference path='fourslash.ts' />
// Exercises completions for hidden files (ie: those beginning with '.')
// @Filename: f.ts
//// /*f1*/
// @Filename: d1/g.ts
//// /*g1*/
// @Filename: d1/d2/h.ts
//// /*h1*/
// @Filename: d1/d2/d3/i.ts
//// /// <reference path=".\..\..\/*28*/
// @Filename: test.ts
//// /// <reference path="/*0*/
//// /// <reference path=".//*1*/
//// /// <reference path=".\/*2*/
//// /// <reference path="[|./*3*/|]
//// /// <reference path="d1//*4*/
//// /// <reference path="d1/.//*5*/
//// /// <reference path="d1/.\/*6*/
//// /// <reference path="d1/[|./*7*/|]
//// /// <reference path="d1\/*8*/
//// /// <reference path="d1\.//*9*/
//// /// <reference path="d1\.\/*10*/
//// /// <reference path="d1\[|./*11*/|]
//// /// <reference path="d1/d2//*12*/
//// /// <reference path="d1/d2/.//*13*/
//// /// <reference path="d1/d2/.\/*14*/
//// /// <reference path="d1/d2/[|./*15*/|]
//// /// <reference path="d1/d2\/*16*/
//// /// <reference path="d1/d2\.//*17*/
//// /// <reference path="d1/d2\.\/*18*/
//// /// <reference path="d1/d2\[|./*19*/|]
//// /// <reference path="d1\d2//*20*/
//// /// <reference path="d1\d2/.//*21*/
//// /// <reference path="d1\d2/.\/*22*/
//// /// <reference path="d1\d2/[|./*23*/|]
//// /// <reference path="d1\d2\/*24*/
//// /// <reference path="d1\d2\.//*25*/
//// /// <reference path="d1\d2\.\/*26*/
//// /// <reference path="d1\d2\[|./*27*/|]
testBlock(0, 'f.ts', "d1");
testBlock(4, 'g.ts', "d2");
testBlock(8, 'g.ts', "d2");
testBlock(12, 'h.ts', "d3");
testBlock(16, 'h.ts', "d3");
testBlock(20, 'h.ts', "d3");
testBlock(24, 'h.ts', "d3");
verify.completions({ marker: "28", exact: ["g.ts", "d2"], isNewIdentifierLocation: true });
function testBlock(offset: number, fileName: string, dir: string) {
const names = [fileName, dir];
verify.completions(
{
marker: [offset, offset + 1, offset + 2].map(String),
exact: names,
isNewIdentifierLocation: true,
},
{
marker: String(offset + 3),
exact: names.map(name => ({ name, replacementSpan: test.ranges()[offset / 4] })),
isNewIdentifierLocation: true,
});
}
| weswigham/TypeScript | tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts | TypeScript | apache-2.0 | 2,191 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.predicate;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
/**
* A predicate that returns true if the request is idempotent
* according to the HTTP RFC.
*
* @author Stuart Douglas
*/
public class IdempotentPredicate implements Predicate {
public static final IdempotentPredicate INSTANCE = new IdempotentPredicate();
private static final Set<HttpString> METHODS;
static {
Set<HttpString> methods = new HashSet<>();
methods.add(Methods.GET);
methods.add(Methods.DELETE);
methods.add(Methods.PUT);
methods.add(Methods.HEAD);
methods.add(Methods.OPTIONS);
METHODS = Collections.unmodifiableSet(methods);
}
@Override
public boolean resolve(HttpServerExchange value) {
return METHODS.contains(value.getRequestMethod());
}
public static class Builder implements PredicateBuilder {
@Override
public String name() {
return "idempotent";
}
@Override
public Map<String, Class<?>> parameters() {
return Collections.emptyMap();
}
@Override
public Set<String> requiredParameters() {
return Collections.emptySet();
}
@Override
public String defaultParameter() {
return null;
}
@Override
public Predicate build(Map<String, Object> config) {
return INSTANCE;
}
}
}
| stuartwdouglas/undertow | core/src/main/java/io/undertow/predicate/IdempotentPredicate.java | Java | apache-2.0 | 2,348 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package github
import (
"sync"
"k8s.io/kubernetes/pkg/util/sets"
)
// StatusChange keeps track of issue/commit for status changes
type StatusChange struct {
heads map[int]string // Pull-Request ID -> head-sha
pullRequests map[string]sets.Int // head-sha -> Pull-Request IDs
changed sets.String // SHA of commits whose status changed
mutex sync.Mutex
}
// NewStatusChange creates a new status change tracker
func NewStatusChange() *StatusChange {
return &StatusChange{
heads: map[int]string{},
pullRequests: map[string]sets.Int{},
changed: sets.NewString(),
}
}
// UpdatePullRequestHead updates the head commit for a pull-request
func (s *StatusChange) UpdatePullRequestHead(pullRequestID int, newHead string) {
s.mutex.Lock()
defer s.mutex.Unlock()
if oldHead, has := s.heads[pullRequestID]; has {
delete(s.pullRequests, oldHead)
}
s.heads[pullRequestID] = newHead
if _, has := s.pullRequests[newHead]; !has {
s.pullRequests[newHead] = sets.NewInt()
}
s.pullRequests[newHead].Insert(pullRequestID)
}
// CommitStatusChanged must be called when the status for this commit has changed
func (s *StatusChange) CommitStatusChanged(commit string) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.changed.Insert(commit)
}
// PopChangedPullRequests returns the list of issues changed since last call
func (s *StatusChange) PopChangedPullRequests() []int {
s.mutex.Lock()
defer s.mutex.Unlock()
changedPullRequests := sets.NewInt()
for _, commit := range s.changed.List() {
if pullRequests, has := s.pullRequests[commit]; has {
changedPullRequests = changedPullRequests.Union(pullRequests)
}
}
s.changed = sets.NewString()
return changedPullRequests.List()
}
| piosz/test-infra | mungegithub/github/status_change.go | GO | apache-2.0 | 2,311 |
package terraform
import (
"github.com/hashicorp/terraform/addrs"
"github.com/hashicorp/terraform/configs/configschema"
"github.com/hashicorp/terraform/dag"
)
// ResourceCountTransformer is a GraphTransformer that expands the count
// out for a specific resource.
//
// This assumes that the count is already interpolated.
type ResourceCountTransformer struct {
Concrete ConcreteResourceInstanceNodeFunc
Schema *configschema.Block
// Count is either the number of indexed instances to create, or -1 to
// indicate that count is not set at all and thus a no-key instance should
// be created.
Count int
Addr addrs.AbsResource
}
func (t *ResourceCountTransformer) Transform(g *Graph) error {
if t.Count < 0 {
// Negative count indicates that count is not set at all.
addr := t.Addr.Instance(addrs.NoKey)
abstract := NewNodeAbstractResourceInstance(addr)
abstract.Schema = t.Schema
var node dag.Vertex = abstract
if f := t.Concrete; f != nil {
node = f(abstract)
}
g.Add(node)
return nil
}
// For each count, build and add the node
for i := 0; i < t.Count; i++ {
key := addrs.IntKey(i)
addr := t.Addr.Instance(key)
abstract := NewNodeAbstractResourceInstance(addr)
abstract.Schema = t.Schema
var node dag.Vertex = abstract
if f := t.Concrete; f != nil {
node = f(abstract)
}
g.Add(node)
}
return nil
}
| xanzy/terraform-provider-cosmic | vendor/github.com/hashicorp/terraform/terraform/transform_resource_count.go | GO | apache-2.0 | 1,368 |
// Copyright 2021 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_UTIL_IOS_IOS_INTERMEDIATE_DUMP_DATA_H_
#define CRASHPAD_UTIL_IOS_IOS_INTERMEDIATE_DUMP_DATA_H_
#include <string>
#include <vector>
#include "util/ios/ios_intermediate_dump_object.h"
namespace crashpad {
namespace internal {
//! \brief A data object, consisting of a std::vector<uint8_t>.
class IOSIntermediateDumpData : public IOSIntermediateDumpObject {
public:
IOSIntermediateDumpData();
IOSIntermediateDumpData(const IOSIntermediateDumpData&) = delete;
IOSIntermediateDumpData& operator=(const IOSIntermediateDumpData&) = delete;
~IOSIntermediateDumpData() override;
//! \brief Constructs a new data object which owns a std::vector<uint8_t>.
//!
//! \param[in] data An array of uint8_t.
//! \param[in] length The length of \a data.
IOSIntermediateDumpData(std::vector<uint8_t> data) : data_(std::move(data)) {}
// IOSIntermediateDumpObject:
Type GetType() const override;
//! \brief Returns data as a string.
std::string GetString() const;
//! \brief Copies the data into \a value if sizeof(T) matches data_.size().
//!
//! \param[out] value The data to populate.
//!
//! \return On success, returns `true`, otherwise returns `false`.
template <typename T>
bool GetValue(T* value) const {
return GetValueInternal(reinterpret_cast<void*>(value), sizeof(*value));
}
const std::vector<uint8_t>& bytes() const { return data_; }
private:
bool GetValueInternal(void* value, size_t value_size) const;
std::vector<uint8_t> data_;
};
} // namespace internal
} // namespace crashpad
#endif // CRASHPAD_UTIL_IOS_IOS_INTERMEDIATE_DUMP_DATA_H_
| chromium/crashpad | util/ios/ios_intermediate_dump_data.h | C | apache-2.0 | 2,243 |
/*
* Copyright (c) 2017 Matthias Boesl
*
* SPDX-License-Identifier: Apache-2.0
*/
/** @file
* @brief IPv4 Autoconfiguration
*/
#ifndef ZEPHYR_INCLUDE_NET_IPV4_AUTOCONF_H_
#define ZEPHYR_INCLUDE_NET_IPV4_AUTOCONF_H_
/** Current state of IPv4 Autoconfiguration */
enum net_ipv4_autoconf_state {
NET_IPV4_AUTOCONF_INIT,
NET_IPV4_AUTOCONF_PROBE,
NET_IPV4_AUTOCONF_ANNOUNCE,
NET_IPV4_AUTOCONF_ASSIGNED,
NET_IPV4_AUTOCONF_RENEW,
};
/**
* @brief Initialize IPv4 auto configuration engine.
*/
#if defined(CONFIG_NET_IPV4_AUTO)
void net_ipv4_autoconf_init(void);
#else
#define net_ipv4_autoconf_init(...)
#endif
#endif /* ZEPHYR_INCLUDE_NET_IPV4_AUTOCONF_H_ */
| ldts/zephyr | include/net/ipv4_autoconf.h | C | apache-2.0 | 670 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.cxf.converter;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Element;
import org.apache.camel.Converter;
import org.apache.camel.component.cxf.CxfPayload;
import org.apache.camel.converter.jaxp.DomConverter;
// This converter is used to show how to override the CxfPayload default toString converter
@Converter
public final class MyCxfCustomerConverter {
private MyCxfCustomerConverter() {
//Helper class
}
@Converter
public static String cxfPayloadToString(final CxfPayload<?> payload) {
DomConverter converter = new DomConverter();
StringBuilder buf = new StringBuilder();
for (Object element : payload.getBody()) {
String elementString = "";
try {
elementString = converter.toString((Element) element, null);
} catch (TransformerException e) {
elementString = element.toString();
}
buf.append(elementString);
}
return buf.toString();
}
}
| nikhilvibhav/camel | components/camel-cxf/src/test/java/org/apache/camel/component/cxf/converter/MyCxfCustomerConverter.java | Java | apache-2.0 | 1,868 |
package builds
import (
"fmt"
"path/filepath"
"strings"
"time"
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
"k8s.io/kubernetes/test/e2e"
exutil "github.com/openshift/origin/test/extended/util"
)
var _ = g.Describe("default: S2I incremental build with push and pull to authenticated registry", func() {
defer g.GinkgoRecover()
var (
templateFixture = exutil.FixturePath("fixtures", "incremental-auth-build.json")
oc = exutil.NewCLI("build-sti-env", exutil.KubeConfigPath())
)
g.JustBeforeEach(func() {
g.By("waiting for builder service account")
err := exutil.WaitForBuilderAccount(oc.KubeREST().ServiceAccounts(oc.Namespace()))
o.Expect(err).NotTo(o.HaveOccurred())
})
g.Describe("Building from a template", func() {
g.It(fmt.Sprintf("should create a build from %q template and run it", templateFixture), func() {
oc.SetOutputDir(exutil.TestContext.OutputDir)
g.By(fmt.Sprintf("calling oc new-app -f %q", templateFixture))
err := oc.Run("new-app").Args("-f", templateFixture).Execute()
o.Expect(err).NotTo(o.HaveOccurred())
g.By("starting a test build")
buildName, err := oc.Run("start-build").Args("initial-build").Output()
o.Expect(err).NotTo(o.HaveOccurred())
g.By("expecting the build is in Complete phase")
err = exutil.WaitForABuild(oc.REST().Builds(oc.Namespace()), buildName, exutil.CheckBuildSuccessFunc, exutil.CheckBuildFailedFunc)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("starting a test build using the image produced by the last build")
buildName, err = oc.Run("start-build").Args("internal-build").Output()
o.Expect(err).NotTo(o.HaveOccurred())
g.By("expecting the build is in Complete phase")
err = exutil.WaitForABuild(oc.REST().Builds(oc.Namespace()), buildName, exutil.CheckBuildSuccessFunc, exutil.CheckBuildFailedFunc)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("getting the Docker image reference from ImageStream")
imageName, err := exutil.GetDockerImageReference(oc.REST().ImageStreams(oc.Namespace()), "internal-image", "latest")
o.Expect(err).NotTo(o.HaveOccurred())
g.By("writing the pod definition to a file")
outputPath := filepath.Join(exutil.TestContext.OutputDir, oc.Namespace()+"-sample-pod.json")
pod := exutil.CreatePodForImage(imageName)
err = exutil.WriteObjectToFile(pod, outputPath)
o.Expect(err).NotTo(o.HaveOccurred())
g.By(fmt.Sprintf("calling oc create -f %q", outputPath))
err = oc.Run("create").Args("-f", outputPath).Execute()
o.Expect(err).NotTo(o.HaveOccurred())
g.By("expecting the pod to be running")
err = oc.KubeFramework().WaitForPodRunning(pod.Name)
o.Expect(err).NotTo(o.HaveOccurred())
// even though the pod is running, the app isn't always started
// so wait until webrick output is complete before curling.
logs := ""
count := 0
for strings.Contains(logs, "8080") && count < 10 {
logs, _ = oc.Run("logs").Args(pod.Name).Output()
time.Sleep(time.Second)
count++
}
g.By("expecting the pod container has saved artifacts")
out, err := oc.Run("exec").Args("-p", pod.Name, "--", "curl", "http://0.0.0.0:8080").Output()
o.Expect(err).NotTo(o.HaveOccurred())
if !strings.Contains(out, "artifacts exist") {
logs, _ = oc.Run("logs").Args(pod.Name).Output()
e2e.Failf("Pod %q does not contain expected artifacts: %q\n%q", pod.Name, out, logs)
}
})
})
})
| pkdevbox/origin | test/extended/builds/sti_incremental.go | GO | apache-2.0 | 3,417 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.plan.rules.physical.stream
import org.apache.flink.table.planner.plan.logical.WindowAttachedWindowingStrategy
import org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery
import org.apache.flink.table.planner.plan.nodes.FlinkConventions
import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalRank
import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalWindowDeduplicate
import org.apache.flink.table.planner.plan.`trait`.FlinkRelDistribution
import org.apache.flink.table.planner.plan.utils.{RankUtil, WindowUtil}
import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
import org.apache.calcite.rel.convert.ConverterRule
import org.apache.calcite.rel.RelNode
/**
* Rule to convert a [[FlinkLogicalRank]] into a [[StreamPhysicalWindowDeduplicate]].
*/
class StreamPhysicalWindowDeduplicateRule
extends ConverterRule(
classOf[FlinkLogicalRank],
FlinkConventions.LOGICAL,
FlinkConventions.STREAM_PHYSICAL,
"StreamPhysicalWindowDeduplicateRule") {
override def matches(call: RelOptRuleCall): Boolean = {
val rank: FlinkLogicalRank = call.rel(0)
val fmq = FlinkRelMetadataQuery.reuseOrCreate(call.getMetadataQuery)
val windowProperties = fmq.getRelWindowProperties(rank.getInput)
val partitionKey = rank.partitionKey
WindowUtil.groupingContainsWindowStartEnd(partitionKey, windowProperties) &&
RankUtil.canConvertToDeduplicate(rank)
}
override def convert(rel: RelNode): RelNode = {
val rank: FlinkLogicalRank = rel.asInstanceOf[FlinkLogicalRank]
val fmq = FlinkRelMetadataQuery.reuseOrCreate(rel.getCluster.getMetadataQuery)
val relWindowProperties = fmq.getRelWindowProperties(rank.getInput)
val partitionKey = rank.partitionKey
val (startColumns, endColumns, _, newPartitionKey) =
WindowUtil.groupingExcludeWindowStartEndTimeColumns(partitionKey, relWindowProperties)
val requiredDistribution = if (!newPartitionKey.isEmpty) {
FlinkRelDistribution.hash(newPartitionKey.toArray, requireStrict = true)
} else {
FlinkRelDistribution.SINGLETON
}
val requiredTraitSet = rank.getCluster.getPlanner.emptyTraitSet()
.replace(requiredDistribution)
.replace(FlinkConventions.STREAM_PHYSICAL)
val providedTraitSet = rank.getTraitSet.replace(FlinkConventions.STREAM_PHYSICAL)
val newInput: RelNode = RelOptRule.convert(rank.getInput, requiredTraitSet)
val windowingStrategy = new WindowAttachedWindowingStrategy(
relWindowProperties.getWindowSpec,
relWindowProperties.getTimeAttributeType,
startColumns.toArray.head,
endColumns.toArray.head)
// order by timeIndicator desc ==> lastRow, otherwise is firstRow
val fieldCollation = rank.orderKey.getFieldCollations.get(0)
val isLastRow = fieldCollation.direction.isDescending
new StreamPhysicalWindowDeduplicate(
rank.getCluster,
providedTraitSet,
newInput,
newPartitionKey.toArray,
fieldCollation.getFieldIndex,
isLastRow,
windowingStrategy)
}
}
object StreamPhysicalWindowDeduplicateRule {
val INSTANCE = new StreamPhysicalWindowDeduplicateRule
}
| apache/flink | flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalWindowDeduplicateRule.scala | Scala | apache-2.0 | 4,011 |
//===--- SILDebugInfoGenerator.cpp - Writes a SIL file for debugging ------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "gsil-gen"
#include "swift/AST/SILOptions.h"
#include "swift/SIL/SILPrintContext.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
using namespace swift;
namespace {
/// A pass for generating debug info on SIL level.
///
/// This pass is only enabled if SILOptions::SILOutputFileNameForDebugging is
/// set (i.e. if the -gsil command line option is specified).
/// The pass writes all SIL functions into one or multiple output files,
/// depending on the size of the SIL. The names of the output files are derived
/// from the main output file.
///
/// output file name = <main-output-filename>.gsil_<n>.sil
///
/// Where <n> is a consecutive number. The files are stored in the same
/// same directory as the main output file.
/// The debug locations and scopes of all functions and instructions are changed
/// to point to the generated SIL output files.
/// This enables debugging and profiling on SIL level.
class SILDebugInfoGenerator : public SILModuleTransform {
enum {
/// To prevent extra large output files, e.g. when compiling the stdlib.
LineLimitPerFile = 10000
};
/// A stream for counting line numbers.
struct LineCountStream : public llvm::raw_ostream {
llvm::raw_ostream &Underlying;
int LineNum = 1;
uint64_t Pos = 0;
void write_impl(const char *Ptr, size_t Size) override {
for (size_t Idx = 0; Idx < Size; Idx++) {
char c = Ptr[Idx];
if (c == '\n')
++LineNum;
}
Underlying.write(Ptr, Size);
Pos += Size;
}
uint64_t current_pos() const override { return Pos; }
LineCountStream(llvm::raw_ostream &Underlying) :
llvm::raw_ostream(/* unbuffered = */ true),
Underlying(Underlying) { }
~LineCountStream() {
flush();
}
};
/// A print context which records the line numbers where instructions are
/// printed.
struct PrintContext : public SILPrintContext {
LineCountStream LCS;
llvm::DenseMap<const SILInstruction *, int> LineNums;
void printInstructionCallBack(const SILInstruction *I) override {
// Record the current line number of the instruction.
LineNums[I] = LCS.LineNum;
}
PrintContext(llvm::raw_ostream &OS) : SILPrintContext(LCS), LCS(OS) { }
virtual ~PrintContext() { }
};
void run() override {
SILModule *M = getModule();
StringRef FileBaseName = M->getOptions().SILOutputFileNameForDebugging;
if (FileBaseName.empty())
return;
DEBUG(llvm::dbgs() << "** SILDebugInfoGenerator **\n");
std::vector<SILFunction *> PrintedFuncs;
int FileIdx = 0;
auto FIter = M->begin();
while (FIter != M->end()) {
std::string FileName;
llvm::raw_string_ostream NameOS(FileName);
NameOS << FileBaseName << ".gsil_" << FileIdx++ << ".sil";
NameOS.flush();
char *FileNameBuf = (char *)M->allocate(FileName.size() + 1, 1);
strcpy(FileNameBuf, FileName.c_str());
DEBUG(llvm::dbgs() << "Write debug SIL file " << FileName << '\n');
std::error_code EC;
llvm::raw_fd_ostream OutFile(FileName, EC,
llvm::sys::fs::OpenFlags::F_None);
assert(!OutFile.has_error() && !EC && "Can't write SIL debug file");
PrintContext Ctx(OutFile);
// Write functions until we reach the LineLimitPerFile.
do {
SILFunction *F = &*FIter++;
PrintedFuncs.push_back(F);
// Set the debug scope for the function.
SILLocation::DebugLoc DL(Ctx.LCS.LineNum, 1, FileNameBuf);
RegularLocation Loc(DL);
SILDebugScope *Scope = new (*M) SILDebugScope(Loc, F);
F->setDebugScope(Scope);
// Ensure that the function is visible for debugging.
F->setBare(IsNotBare);
// Print it to the output file.
F->print(Ctx);
} while (FIter != M->end() && Ctx.LCS.LineNum < LineLimitPerFile);
// Set the debug locations of all instructions.
for (SILFunction *F : PrintedFuncs) {
const SILDebugScope *Scope = F->getDebugScope();
for (SILBasicBlock &BB : *F) {
for (SILInstruction &I : BB) {
SILLocation Loc = I.getLoc();
SILLocation::DebugLoc DL(Ctx.LineNums[&I], 1, FileNameBuf);
assert(DL.Line && "no line set for instruction");
if (Loc.is<ReturnLocation>() || Loc.is<ImplicitReturnLocation>()) {
Loc.setDebugInfoLoc(DL);
I.setDebugLocation(SILDebugLocation(Loc, Scope));
} else {
RegularLocation RLoc(DL);
I.setDebugLocation(SILDebugLocation(RLoc, Scope));
}
}
}
}
PrintedFuncs.clear();
}
}
StringRef getName() override { return "SILDebugInfoGenerator"; }
};
} // end anonymous namespace
SILTransform *swift::createSILDebugInfoGenerator() {
return new SILDebugInfoGenerator();
}
| russbishop/swift | lib/SILOptimizer/UtilityPasses/SILDebugInfoGenerator.cpp | C++ | apache-2.0 | 5,535 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
{
using Common.ArgumentCompleters;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
/// <summary>
/// Filters resource groups.
/// </summary>
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ResourceGroup", SupportsShouldProcess = true), OutputType(typeof(PSResourceGroup))]
public class NewAzureResourceGroupCmdlet : ResourceManagerCmdletBase
{
[Alias("ResourceGroupName")]
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group location.")]
[LocationCompleter("Microsoft.Resources/resourceGroups")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
[Alias("Tags")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")]
public Hashtable Tag { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
public SwitchParameter Force { get; set; }
public override void ExecuteCmdlet()
{
PSCreateResourceGroupParameters parameters = new PSCreateResourceGroupParameters
{
ResourceGroupName = Name,
Location = Location,
Force = Force.IsPresent,
Tag = Tag,
ConfirmAction = ConfirmAction
};
WriteObject(ResourceManagerSdkClient.CreatePSResourceGroup(parameters));
}
}
}
| AzureAutomationTeam/azure-powershell | src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/ResourceGroups/NewAzureResourceGroupCmdlet.cs | C# | apache-2.0 | 2,741 |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.util;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.kuali.rice.core.api.exception.KualiException;
import org.kuali.rice.core.api.util.type.TypeUtils;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* BeanPropertyComparator compares the two beans using multiple property names
*
*
*/
public class BeanPropertyComparator implements Comparator, Serializable {
private static final long serialVersionUID = -2675700473766186018L;
boolean ignoreCase;
private List propertyNames;
private Comparator stringComparator;
private Comparator booleanComparator;
private Comparator genericComparator;
/**
* Constructs a PropertyComparator for comparing beans using the properties named in the given List
*
* <p>if the List is null, the beans will be compared directly
* by Properties will be compared in the order in which they are listed. Case will be ignored
* in String comparisons.</p>
*
* @param propertyNames List of property names (as Strings) used to compare beans
*/
public BeanPropertyComparator(List propertyNames) {
this(propertyNames, true);
}
/**
* Constructs a PropertyComparator for comparing beans using the properties named in the given List.
*
* <p>Properties will be compared
* in the order in which they are listed. Case will be ignored if ignoreCase is true.</p>
*
* @param propertyNames List of property names (as Strings) used to compare beans
* @param ignoreCase if true, case will be ignored during String comparisons
*/
public BeanPropertyComparator(List propertyNames, boolean ignoreCase) {
if (propertyNames == null) {
throw new IllegalArgumentException("invalid (null) propertyNames list");
}
if (propertyNames.size() == 0) {
throw new IllegalArgumentException("invalid (empty) propertyNames list");
}
this.propertyNames = Collections.unmodifiableList(propertyNames);
this.ignoreCase = ignoreCase;
if (ignoreCase) {
this.stringComparator = String.CASE_INSENSITIVE_ORDER;
}
else {
this.stringComparator = ComparableComparator.getInstance();
}
this.booleanComparator = new Comparator() {
public int compare(Object o1, Object o2) {
int compared = 0;
Boolean b1 = (Boolean) o1;
Boolean b2 = (Boolean) o2;
if (!b1.equals(b2)) {
if (b1.equals(Boolean.FALSE)) {
compared = -1;
}
else {
compared = 1;
}
}
return compared;
}
};
this.genericComparator = ComparableComparator.getInstance();
}
/**
* Compare two JavaBeans by the properties given to the constructor.
*
* @param o1 Object The first bean to get data from to compare against
* @param o2 Object The second bean to get data from to compare
* @return int negative or positive based on order
*/
public int compare(Object o1, Object o2) {
int compared = 0;
try {
for (Iterator i = propertyNames.iterator(); (compared == 0) && i.hasNext();) {
String currentProperty = i.next().toString();
// choose appropriate comparator
Comparator currentComparator = null;
try {
PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o1, currentProperty);
Class propertyClass = propertyDescriptor.getPropertyType();
if (propertyClass.equals(String.class)) {
currentComparator = this.stringComparator;
}
else if (TypeUtils.isBooleanClass(propertyClass)) {
currentComparator = this.booleanComparator;
}
else {
currentComparator = this.genericComparator;
}
}
catch (NullPointerException e) {
throw new BeanComparisonException("unable to find property '" + o1.getClass().getName() + "." + currentProperty + "'", e);
}
// compare the values
Object value1 = PropertyUtils.getProperty(o1, currentProperty);
Object value2 = PropertyUtils.getProperty(o2, currentProperty);
/* Fix for KULRICE-5170 : BeanPropertyComparator throws exception when a null value is found in sortable non-string data type column */
if ( value1 == null && value2 == null)
return 0;
else if ( value1 == null)
return -1;
else if ( value2 == null )
return 1;
/* End KULRICE-5170 Fix*/
compared = currentComparator.compare(value1, value2);
}
}
catch (IllegalAccessException e) {
throw new BeanComparisonException("unable to compare property values", e);
}
catch (NoSuchMethodException e) {
throw new BeanComparisonException("unable to compare property values", e);
}
catch (InvocationTargetException e) {
throw new BeanComparisonException("unable to compare property values", e);
}
return compared;
}
public static class BeanComparisonException extends KualiException {
private static final long serialVersionUID = 2622379680100640029L;
/**
* @param message
* @param t
*/
public BeanComparisonException(String message, Throwable t) {
super(message, t);
}
}
}
| jruchcolo/rice-cd | rice-framework/krad-app-framework/src/main/java/org/kuali/rice/krad/util/BeanPropertyComparator.java | Java | apache-2.0 | 6,807 |
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openejb.core.mdb;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;
public class MdbInvoker implements MessageListener {
private final Map<String, Method> signatures = new TreeMap<String, Method>();
private final Object target;
private Connection connection;
private Session session;
private ConnectionFactory connectionFactory;
public MdbInvoker(ConnectionFactory connectionFactory, Object target) throws JMSException {
this.target = target;
this.connectionFactory = connectionFactory;
for (Method method : target.getClass().getMethods()) {
String signature = MdbUtil.getSignature(method);
signatures.put(signature, method);
}
}
public synchronized void destroy() {
MdbUtil.close(session);
session = null;
MdbUtil.close(connection);
connection = null;
}
private synchronized Session getSession() throws JMSException {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
return session;
}
public void onMessage(Message message) {
if (!(message instanceof ObjectMessage)) return;
try {
Session session = getSession();
if (session == null) throw new IllegalStateException("Invoker has been destroyed");
if (message == null) throw new NullPointerException("request message is null");
if (!(message instanceof ObjectMessage)) throw new IllegalArgumentException("Expected a ObjectMessage request but got a " + message.getClass().getName());
ObjectMessage objectMessage = (ObjectMessage) message;
Serializable object = objectMessage.getObject();
if (object == null) throw new NullPointerException("object in ObjectMessage is null");
if (!(object instanceof Map)) {
if (message instanceof ObjectMessage) throw new IllegalArgumentException("Expected a Map contained in the ObjectMessage request but got a " + object.getClass().getName());
}
Map request = (Map) object;
String signature = (String) request.get("method");
Method method = signatures.get(signature);
Object[] args = (Object[]) request.get("args");
boolean exception = false;
Object result = null;
try {
result = method.invoke(target, args);
} catch (IllegalAccessException e) {
result = e;
exception = true;
} catch (InvocationTargetException e) {
result = e.getCause();
if (result == null) result = e;
exception = true;
}
MessageProducer producer = null;
try {
// create response
Map<String, Object> response = new TreeMap<String, Object>();
if (exception) {
response.put("exception", "true");
}
response.put("return", result);
// create response message
ObjectMessage resMessage = session.createObjectMessage();
resMessage.setJMSCorrelationID(objectMessage.getJMSCorrelationID());
resMessage.setObject((Serializable) response);
// send response message
producer = session.createProducer(objectMessage.getJMSReplyTo());
producer.send(resMessage);
} catch (Exception e) {
e.printStackTrace();
} finally {
MdbUtil.close(producer);
destroy();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
| apache/openejb | container/openejb-core/src/test/java/org/apache/openejb/core/mdb/MdbInvoker.java | Java | apache-2.0 | 5,024 |
/*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.collector.cluster.route;
import com.navercorp.pinpoint.collector.cluster.ClusterPointLocator;
import com.navercorp.pinpoint.collector.cluster.TargetClusterPoint;
import com.navercorp.pinpoint.collector.cluster.route.filter.RouteFilter;
import com.navercorp.pinpoint.rpc.Future;
import com.navercorp.pinpoint.rpc.ResponseMessage;
import com.navercorp.pinpoint.thrift.dto.command.TCommandTransferResponse;
import com.navercorp.pinpoint.thrift.dto.command.TRouteResult;
import com.navercorp.pinpoint.thrift.io.TCommandTypeVersion;
import org.apache.thrift.TBase;
/**
* @author koo.taejin
* @author HyunGil Jeong
*/
public class DefaultRouteHandler extends AbstractRouteHandler<RequestEvent> {
private final RouteFilterChain<RequestEvent> requestFilterChain;
private final RouteFilterChain<ResponseEvent> responseFilterChain;
public DefaultRouteHandler(ClusterPointLocator<TargetClusterPoint> targetClusterPointLocator,
RouteFilterChain<RequestEvent> requestFilterChain,
RouteFilterChain<ResponseEvent> responseFilterChain) {
super(targetClusterPointLocator);
this.requestFilterChain = requestFilterChain;
this.responseFilterChain = responseFilterChain;
}
@Override
public void addRequestFilter(RouteFilter<RequestEvent> filter) {
this.requestFilterChain.addLast(filter);
}
@Override
public void addResponseFilter(RouteFilter<ResponseEvent> filter) {
this.responseFilterChain.addLast(filter);
}
@Override
public TCommandTransferResponse onRoute(RequestEvent event) {
requestFilterChain.doEvent(event);
TCommandTransferResponse routeResult = onRoute0(event);
responseFilterChain.doEvent(new ResponseEvent(event, event.getRequestId(), routeResult));
return routeResult;
}
private TCommandTransferResponse onRoute0(RequestEvent event) {
TBase<?,?> requestObject = event.getRequestObject();
if (requestObject == null) {
return createResponse(TRouteResult.EMPTY_REQUEST);
}
TargetClusterPoint clusterPoint = findClusterPoint(event.getDeliveryCommand());
if (clusterPoint == null) {
return createResponse(TRouteResult.NOT_FOUND);
}
TCommandTypeVersion commandVersion = TCommandTypeVersion.getVersion(clusterPoint.gerVersion());
if (!commandVersion.isSupportCommand(requestObject)) {
return createResponse(TRouteResult.NOT_SUPPORTED_REQUEST);
}
Future<ResponseMessage> future = clusterPoint.request(event.getDeliveryCommand().getPayload());
boolean isCompleted = future.await();
if (!isCompleted) {
return createResponse(TRouteResult.TIMEOUT);
}
ResponseMessage responseMessage = future.getResult();
if (responseMessage == null) {
return createResponse(TRouteResult.EMPTY_RESPONSE);
}
byte[] responsePayload = responseMessage.getMessage();
if (responsePayload == null || responsePayload.length == 0) {
return createResponse(TRouteResult.EMPTY_RESPONSE, new byte[0]);
}
return createResponse(TRouteResult.OK, responsePayload);
}
private TCommandTransferResponse createResponse(TRouteResult result) {
return createResponse(result, new byte[0]);
}
private TCommandTransferResponse createResponse(TRouteResult result, byte[] payload) {
TCommandTransferResponse response = new TCommandTransferResponse();
response.setRouteResult(result);
response.setPayload(payload);
return response;
}
}
| dawidmalina/pinpoint | collector/src/main/java/com/navercorp/pinpoint/collector/cluster/route/DefaultRouteHandler.java | Java | apache-2.0 | 4,382 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.twitter.search;
import java.util.Collections;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.component.twitter.TwitterEndpoint;
import org.apache.camel.component.twitter.consumer.AbstractTwitterConsumerHandler;
import org.apache.camel.component.twitter.consumer.TwitterEventType;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.Query.Unit;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
/**
* Consumes search requests
*/
public class SearchConsumerHandler extends AbstractTwitterConsumerHandler {
private static final Logger LOG = LoggerFactory.getLogger(SearchConsumerHandler.class);
private String keywords;
public SearchConsumerHandler(TwitterEndpoint te, String keywords) {
super(te);
this.keywords = keywords;
}
@Override
public List<Exchange> pollConsume() throws TwitterException {
String keywords = this.keywords;
Query query;
if (keywords != null && keywords.trim().length() > 0) {
query = new Query(keywords);
LOG.debug("Searching twitter with keywords: {}", keywords);
} else {
query = new Query();
LOG.debug("Searching twitter without keywords.");
}
if (endpoint.getProperties().isFilterOld()) {
query.setSinceId(getLastId());
}
return search(query);
}
@Override
public List<Exchange> directConsume() throws TwitterException {
String keywords = this.keywords;
if (keywords == null || keywords.trim().length() == 0) {
return Collections.emptyList();
}
Query query = new Query(keywords);
LOG.debug("Searching twitter with keywords: {}", keywords);
return search(query);
}
private List<Exchange> search(Query query) throws TwitterException {
Integer numberOfPages = 1;
if (ObjectHelper.isNotEmpty(endpoint.getProperties().getLang())) {
query.setLang(endpoint.getProperties().getLang());
}
if (ObjectHelper.isNotEmpty(endpoint.getProperties().getCount())) {
query.setCount(endpoint.getProperties().getCount());
}
if (ObjectHelper.isNotEmpty(endpoint.getProperties().getNumberOfPages())) {
numberOfPages = endpoint.getProperties().getNumberOfPages();
}
if (ObjectHelper.isNotEmpty(endpoint.getProperties().getLatitude())
&& ObjectHelper.isNotEmpty(endpoint.getProperties().getLongitude())
&& ObjectHelper.isNotEmpty(endpoint.getProperties().getRadius())) {
GeoLocation location
= new GeoLocation(endpoint.getProperties().getLatitude(), endpoint.getProperties().getLongitude());
query.setGeoCode(location, endpoint.getProperties().getRadius(),
Unit.valueOf(endpoint.getProperties().getDistanceMetric()));
LOG.debug("Searching with additional geolocation parameters.");
}
LOG.debug("Searching with {} pages.", numberOfPages);
Twitter twitter = getTwitter();
QueryResult qr = twitter.search(query);
List<Status> tweets = qr.getTweets();
for (int i = 1; i < numberOfPages; i++) {
if (!qr.hasNext()) {
break;
}
qr = twitter.search(qr.nextQuery());
tweets.addAll(qr.getTweets());
}
if (endpoint.getProperties().isFilterOld()) {
for (Status status : tweets) {
setLastIdIfGreater(status.getId());
}
}
return TwitterEventType.STATUS.createExchangeList(endpoint, tweets);
}
}
| nikhilvibhav/camel | components/camel-twitter/src/main/java/org/apache/camel/component/twitter/search/SearchConsumerHandler.java | Java | apache-2.0 | 4,705 |
/*
*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package springfox.documentation.spring.web.dummy;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.AuthorizationScope;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.spring.web.dummy.DummyModels.Ignorable;
import springfox.documentation.spring.web.dummy.models.EnumType;
import springfox.documentation.spring.web.dummy.models.Example;
import springfox.documentation.spring.web.dummy.models.FoobarDto;
import springfox.documentation.spring.web.dummy.models.Treeish;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RequestMapping(produces = {"application/json"}, consumes = {"application/json", "application/xml"})
public class DummyClass {
@ApiParam
public void annotatedWithApiParam() {
}
public void dummyMethod() {
}
public void methodWithOneArgs(int a) {
}
public void methodWithTwoArgs(int a, String b) {
}
public void methodWithNoArgs() {
}
@ApiOperation(value = "description", httpMethod = "GET")
public void methodWithHttpGETMethod() {
}
@ApiOperation(value = "description", nickname = "unique")
public void methodWithNickName() {
}
@ApiOperation(value = "description", httpMethod = "GET", hidden = true)
public void methodThatIsHidden() {
}
@ApiOperation(value = "description", httpMethod = "RUBBISH")
public void methodWithInvalidHttpMethod() {
}
@ApiOperation(value = "summary", httpMethod = "RUBBISH")
public void methodWithSummary() {
}
@ApiOperation(value = "", notes = "some notes")
public void methodWithNotes() {
}
@ApiOperation(value = "", nickname = "a nickname")
public void methodWithNickname() {
}
@ApiOperation(value = "", position = 5)
public void methodWithPosition() {
}
@ApiOperation(value = "", consumes = "application/xml")
public void methodWithXmlConsumes() {
}
@ApiOperation(value = "", produces = "application/xml")
public void methodWithXmlProduces() {
}
@ApiOperation(value = "", produces = "application/xml, application/json", consumes = "application/xml, " +
"application/json")
public void methodWithMultipleMediaTypes() {
}
@ApiOperation(value = "", produces = "application/xml", consumes = "application/xml")
public void methodWithBothXmlMediaTypes() {
}
@ApiOperation(value = "", produces = "application/json", consumes = "application/xml")
public void methodWithMediaTypeAndFile(MultipartFile multipartFile) {
}
@ApiOperation(value = "", response = DummyModels.FunkyBusiness.class)
public void methodApiResponseClass() {
}
@ApiResponses({
@ApiResponse(code = 201, response = Void.class, message = "Rule Scheduled successfuly"),
@ApiResponse(code = 500, response = RestError.class, message = "Internal Server Error"),
@ApiResponse(code = 406, response = RestError.class, message = "Not acceptable")})
public void methodAnnotatedWithApiResponse() {
}
@ApiOperation(value = "methodWithExtensions",
extensions = {
@Extension(properties = @ExtensionProperty(name="x-test1", value="value1")),
@Extension(name="test2", properties = @ExtensionProperty(name="name2", value="value2"))
}
)
public void methodWithExtensions() {
}
@ApiOperation(value = "SomeVal",
authorizations = @Authorization(value = "oauth2",
scopes = {@AuthorizationScope(scope = "scope", description = "scope description")
}))
public void methodWithAuth() {
}
@ApiOperation(value = "")
public DummyModels.FunkyBusiness methodWithAPiAnnotationButWithoutResponseClass() {
return null;
}
@ApiOperation(value = "")
public DummyModels.Paginated<BusinessType> methodWithGenericType() {
return null;
}
public ResponseEntity<byte[]> methodWithGenericPrimitiveArray() {
return null;
}
public ResponseEntity<DummyClass[]> methodWithGenericComplexArray() {
return null;
}
public ResponseEntity<EnumType> methodWithEnumResponse() {
return null;
}
@Deprecated
public void methodWithDeprecated() {
}
public void methodWithServletRequest(ServletRequest req) {
}
public void methodWithBindingResult(BindingResult res) {
}
public void methodWithInteger(Integer integer) {
}
public void methodWithAnnotatedInteger(@Ignorable Integer integer) {
}
public void methodWithModelAttribute(@ModelAttribute Example example) {
}
public void methodWithoutModelAttribute(Example example) {
}
public void methodWithTreeishModelAttribute(@ModelAttribute Treeish example) {
}
@RequestMapping("/businesses/{businessId}")
public void methodWithSinglePathVariable(@PathVariable String businessId) {
}
@RequestMapping("/businesses/{businessId}")
public void methodWithSingleEnum(BusinessType businessType) {
}
@RequestMapping("/businesses/{businessId}")
public void methodWithSingleEnumArray(BusinessType[] businessTypes) {
}
@RequestMapping("/businesses/{businessId}/employees/{employeeId}/salary")
public void methodWithRatherLongRequestPath() {
}
@RequestMapping(value = "/parameter-conditions", params = "test=testValue")
public void methodWithParameterRequestCondition() {
}
@ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header",
value = "Authentication token")
public void methodWithApiImplicitParam() {
}
@ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header",
value = "Authentication token")
public void methodWithApiImplicitParamAndInteger(Integer integer) {
}
@ApiImplicitParams({
@ApiImplicitParam(name = "lang", dataType = "string", required = true, paramType = "query",
value = "Language", defaultValue = "EN", allowableValues = "EN,FR"),
@ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header",
value = "Authentication token")
})
public void methodWithApiImplicitParams(Integer integer) {
}
public interface ApiImplicitParamsInterface {
@ApiImplicitParams({
@ApiImplicitParam(name = "lang", dataType = "string", required = true, paramType = "query",
value = "Language", defaultValue = "EN", allowableValues = "EN,FR")
})
@ApiImplicitParam(name = "Authentication", dataType = "string", required = true, paramType = "header",
value = "Authentication token")
void methodWithApiImplicitParam();
}
public static class ApiImplicitParamsClass implements ApiImplicitParamsInterface {
@Override
public void methodWithApiImplicitParam() {
}
}
@ResponseBody
public DummyModels.BusinessModel methodWithConcreteResponseBody() {
return null;
}
@ResponseBody
public Map<String, DummyModels.BusinessModel> methodWithMapReturn() {
return null;
}
@ResponseBody
@ResponseStatus(value = HttpStatus.ACCEPTED, reason = "Accepted request")
public DummyModels.BusinessModel methodWithResponseStatusAnnotation() {
return null;
}
@ResponseBody
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void methodWithResponseStatusAnnotationAndEmptyReason() {
}
@ResponseBody
public DummyModels.AnnotatedBusinessModel methodWithModelPropertyAnnotations() {
return null;
}
@ResponseBody
public DummyModels.NamedBusinessModel methodWithModelAnnotations() {
return null;
}
@ResponseBody
public List<DummyModels.BusinessModel> methodWithListOfBusinesses() {
return null;
}
@ResponseBody
public DummyModels.CorporationModel methodWithConcreteCorporationModel() {
return null;
}
@ResponseBody
public Date methodWithDateResponseBody() {
return null;
}
public void methodParameterWithRequestBodyAnnotation(
@RequestBody DummyModels.BusinessModel model,
HttpServletResponse response,
DummyModels.AnnotatedBusinessModel annotatedBusinessModel) {
}
public void methodParameterWithRequestPartAnnotation(
@RequestPart DummyModels.BusinessModel model,
HttpServletResponse response,
DummyModels.AnnotatedBusinessModel annotatedBusinessModel) {
}
public void methodParameterWithRequestPartAnnotationOnSimpleType(
@RequestPart String model,
HttpServletResponse response,
DummyModels.AnnotatedBusinessModel annotatedBusinessModel) {
}
@ResponseBody
public DummyModels.AnnotatedBusinessModel methodWithSameAnnotatedModelInReturnAndRequestBodyParam(
@RequestBody DummyModels.AnnotatedBusinessModel model) {
return null;
}
@ApiResponses({@ApiResponse(code = 413, message = "a message")})
public void methodWithApiResponses() {
}
@ApiIgnore
public static class ApiIgnorableClass {
@ApiIgnore
public void dummyMethod() {
}
}
@ResponseBody
public DummyModels.ModelWithSerializeOnlyProperty methodWithSerializeOnlyPropInReturnAndRequestBodyParam(
@RequestBody DummyModels.ModelWithSerializeOnlyProperty model) {
return null;
}
@ResponseBody
public FoobarDto methodToTestFoobarDto(@RequestBody FoobarDto model) {
return null;
}
public enum BusinessType {
PRODUCT(1),
SERVICE(2);
private int value;
private BusinessType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class CustomClass {
}
public class MethodsWithSameName {
public ResponseEntity methodToTest(Integer integer, Parent child) {
return null;
}
public void methodToTest(Integer integer, Child child) {
}
}
class Parent {
}
class Child extends Parent {
}
}
| zhiqinghuang/springfox | springfox-spring-web/src/test/java/springfox/documentation/spring/web/dummy/DummyClass.java | Java | apache-2.0 | 11,454 |
from Child import Child
from Node import Node # noqa: I201
AVAILABILITY_NODES = [
# availability-spec-list -> availability-entry availability-spec-list?
Node('AvailabilitySpecList', kind='SyntaxCollection',
element='AvailabilityArgument'),
# Wrapper for all the different entries that may occur inside @available
# availability-entry -> '*' ','?
# | identifier ','?
# | availability-version-restriction ','?
# | availability-versioned-argument ','?
Node('AvailabilityArgument', kind='Syntax',
description='''
A single argument to an `@available` argument like `*`, `iOS 10.1`, \
or `message: "This has been deprecated"`.
''',
children=[
Child('Entry', kind='Syntax',
description='The actual argument',
node_choices=[
Child('Star', kind='SpacedBinaryOperatorToken',
text_choices=['*']),
Child('IdentifierRestriction',
kind='IdentifierToken'),
Child('AvailabilityVersionRestriction',
kind='AvailabilityVersionRestriction'),
Child('AvailabilityLabeledArgument',
kind='AvailabilityLabeledArgument'),
]),
Child('TrailingComma', kind='CommaToken', is_optional=True,
description='''
A trailing comma if the argument is followed by another \
argument
'''),
]),
# Representation of 'deprecated: 2.3', 'message: "Hello world"' etc.
# availability-versioned-argument -> identifier ':' version-tuple
Node('AvailabilityLabeledArgument', kind='Syntax',
description='''
A argument to an `@available` attribute that consists of a label and \
a value, e.g. `message: "This has been deprecated"`.
''',
children=[
Child('Label', kind='IdentifierToken',
description='The label of the argument'),
Child('Colon', kind='ColonToken',
description='The colon separating label and value'),
Child('Value', kind='Syntax',
node_choices=[
Child('String', 'StringLiteralToken'),
Child('Version', 'VersionTuple'),
], description='The value of this labeled argument',),
]),
# Representation for 'iOS 10', 'swift 3.4' etc.
# availability-version-restriction -> identifier version-tuple
Node('AvailabilityVersionRestriction', kind='Syntax',
description='''
An argument to `@available` that restricts the availability on a \
certain platform to a version, e.g. `iOS 10` or `swift 3.4`.
''',
children=[
Child('Platform', kind='IdentifierToken',
classification='Keyword',
description='''
The name of the OS on which the availability should be \
restricted or 'swift' if the availability should be \
restricted based on a Swift version.
'''),
Child('Version', kind='VersionTuple'),
]),
# version-tuple -> integer-literal
# | float-literal
# | float-literal '.' integer-literal
Node('VersionTuple', kind='Syntax',
description='''
A version number of the form major.minor.patch in which the minor \
and patch part may be ommited.
''',
children=[
Child('MajorMinor', kind='Syntax',
node_choices=[
Child('Major', kind='IntegerLiteralToken'),
Child('MajorMinor', kind='FloatingLiteralToken')
], description='''
In case the version consists only of the major version, an \
integer literal that specifies the major version. In case \
the version consists of major and minor version number, a \
floating literal in which the decimal part is interpreted \
as the minor version.
'''),
Child('PatchPeriod', kind='PeriodToken', is_optional=True,
description='''
If the version contains a patch number, the period \
separating the minor from the patch number.
'''),
Child('PatchVersion', kind='IntegerLiteralToken',
is_optional=True, description='''
The patch version if specified.
'''),
]),
]
| austinzheng/swift | utils/gyb_syntax_support/AvailabilityNodes.py | Python | apache-2.0 | 4,872 |
// +build integration
package storage
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"testing"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/googleapi"
storage "google.golang.org/api/storage/v1"
)
type object struct {
name, contents string
}
var (
projectID string
bucket string
objects = []object{
{"obj1", testContents},
{"obj2", testContents},
{"obj/with/slashes", testContents},
{"resumable", testContents},
{"large", strings.Repeat("a", 514)}, // larger than the first section of content that is sniffed by ContentSniffer.
}
aclObjects = []string{"acl1", "acl2"}
copyObj = "copy-object"
)
const (
envProject = "GCLOUD_TESTS_GOLANG_PROJECT_ID"
envPrivateKey = "GCLOUD_TESTS_GOLANG_KEY"
// NOTE that running this test on a bucket deletes ALL contents of the bucket!
envBucket = "GCLOUD_TESTS_GOLANG_DESTRUCTIVE_TEST_BUCKET_NAME"
testContents = "some text that will be saved to a bucket object"
)
func verifyAcls(obj *storage.Object, wantDomainRole, wantAllUsersRole string) (err error) {
var gotDomainRole, gotAllUsersRole string
for _, acl := range obj.Acl {
if acl.Entity == "domain-google.com" {
gotDomainRole = acl.Role
}
if acl.Entity == "allUsers" {
gotAllUsersRole = acl.Role
}
}
if gotDomainRole != wantDomainRole {
err = fmt.Errorf("domain-google.com role = %q; want %q", gotDomainRole, wantDomainRole)
}
if gotAllUsersRole != wantAllUsersRole {
err = fmt.Errorf("allUsers role = %q; want %q; %v", gotAllUsersRole, wantAllUsersRole, err)
}
return err
}
// TODO(gmlewis): Move this to a common location.
func tokenSource(ctx context.Context, scopes ...string) (oauth2.TokenSource, error) {
keyFile := os.Getenv(envPrivateKey)
if keyFile == "" {
return nil, errors.New(envPrivateKey + " not set")
}
jsonKey, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, fmt.Errorf("unable to read %q: %v", keyFile, err)
}
conf, err := google.JWTConfigFromJSON(jsonKey, scopes...)
if err != nil {
return nil, fmt.Errorf("google.JWTConfigFromJSON: %v", err)
}
return conf.TokenSource(ctx), nil
}
const defaultType = "text/plain; charset=utf-8"
// writeObject writes some data and default metadata to the specified object.
// Resumable upload is used if resumable is true.
// The written data is returned.
func writeObject(s *storage.Service, bucket, obj string, resumable bool, contents string) error {
o := &storage.Object{
Bucket: bucket,
Name: obj,
ContentType: defaultType,
ContentEncoding: "utf-8",
ContentLanguage: "en",
Metadata: map[string]string{"foo": "bar"},
}
f := strings.NewReader(contents)
insert := s.Objects.Insert(bucket, o)
if resumable {
insert.ResumableMedia(context.Background(), f, int64(len(contents)), defaultType)
} else {
insert.Media(f)
}
_, err := insert.Do()
return err
}
func checkMetadata(t *testing.T, s *storage.Service, bucket, obj string) {
o, err := s.Objects.Get(bucket, obj).Do()
if err != nil {
t.Error(err)
}
if got, want := o.Name, obj; got != want {
t.Errorf("name of %q = %q; want %q", obj, got, want)
}
if got, want := o.ContentType, defaultType; got != want {
t.Errorf("contentType of %q = %q; want %q", obj, got, want)
}
if got, want := o.Metadata["foo"], "bar"; got != want {
t.Errorf("metadata entry foo of %q = %q; want %q", obj, got, want)
}
}
func createService() *storage.Service {
if projectID = os.Getenv(envProject); projectID == "" {
log.Print("no project ID specified")
return nil
}
if bucket = os.Getenv(envBucket); bucket == "" {
log.Print("no project ID specified")
return nil
}
ctx := context.Background()
ts, err := tokenSource(ctx, storage.DevstorageFullControlScope)
if err != nil {
log.Print("createService: %v", err)
return nil
}
client := oauth2.NewClient(ctx, ts)
s, err := storage.New(client)
if err != nil {
log.Print("unable to create service: %v", err)
return nil
}
return s
}
func TestMain(m *testing.M) {
if err := cleanup(); err != nil {
log.Fatalf("Pre-test cleanup failed: %v", err)
}
exit := m.Run()
if err := cleanup(); err != nil {
log.Fatalf("Post-test cleanup failed: %v", err)
}
os.Exit(exit)
}
func TestContentType(t *testing.T) {
s := createService()
if s == nil {
t.Fatal("Could not create service")
}
type testCase struct {
objectContentType string
useOptionContentType bool
optionContentType string
wantContentType string
}
// The Media method will use resumable upload if the supplied data is
// larger than googleapi.DefaultUploadChunkSize We run the following
// tests with two different file contents: one that will trigger
// resumable upload, and one that won't.
forceResumableData := bytes.Repeat([]byte("a"), googleapi.DefaultUploadChunkSize+1)
smallData := bytes.Repeat([]byte("a"), 2)
// In the following test, the content type, if any, in the Object struct is always "text/plain".
// The content type configured via googleapi.ContentType, if any, is always "text/html".
for _, tc := range []testCase{
// With content type specified in the object struct
{
objectContentType: "text/plain",
useOptionContentType: true,
optionContentType: "text/html",
wantContentType: "text/html",
},
{
objectContentType: "text/plain",
useOptionContentType: true,
optionContentType: "",
wantContentType: "text/plain",
},
{
objectContentType: "text/plain",
useOptionContentType: false,
wantContentType: "text/plain; charset=utf-8", // sniffed.
},
// Without content type specified in the object struct
{
useOptionContentType: true,
optionContentType: "text/html",
wantContentType: "text/html",
},
{
useOptionContentType: true,
optionContentType: "",
wantContentType: "", // Result is an object without a content type.
},
{
useOptionContentType: false,
wantContentType: "text/plain; charset=utf-8", // sniffed.
},
} {
// The behavior should be the same, regardless of whether resumable upload is used or not.
for _, data := range [][]byte{smallData, forceResumableData} {
o := &storage.Object{
Bucket: bucket,
Name: "test-content-type",
ContentType: tc.objectContentType,
}
call := s.Objects.Insert(bucket, o)
var opts []googleapi.MediaOption
if tc.useOptionContentType {
opts = append(opts, googleapi.ContentType(tc.optionContentType))
}
call.Media(bytes.NewReader(data), opts...)
_, err := call.Do()
if err != nil {
t.Fatalf("unable to insert object %q: %v", o.Name, err)
}
readObj, err := s.Objects.Get(bucket, o.Name).Do()
if err != nil {
t.Error(err)
}
if got, want := readObj.ContentType, tc.wantContentType; got != want {
t.Errorf("contentType of %q; got %q; want %q", o.Name, got, want)
}
}
}
}
func TestFunctions(t *testing.T) {
s := createService()
if s == nil {
t.Fatal("Could not create service")
}
t.Logf("Listing buckets for project %q", projectID)
var numBuckets int
pageToken := ""
for {
call := s.Buckets.List(projectID)
if pageToken != "" {
call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
t.Fatalf("unable to list buckets for project %q: %v", projectID, err)
}
numBuckets += len(resp.Items)
if pageToken = resp.NextPageToken; pageToken == "" {
break
}
}
if numBuckets == 0 {
t.Fatalf("no buckets found for project %q", projectID)
}
for _, obj := range objects {
t.Logf("Writing %q", obj.name)
// TODO(mcgreevy): stop relying on "resumable" name to determine whether to
// do a resumable upload.
err := writeObject(s, bucket, obj.name, obj.name == "resumable", obj.contents)
if err != nil {
t.Fatalf("unable to insert object %q: %v", obj.name, err)
}
}
for _, obj := range objects {
t.Logf("Reading %q", obj.name)
resp, err := s.Objects.Get(bucket, obj.name).Download()
if err != nil {
t.Fatalf("unable to get object %q: %v", obj.name, err)
}
slurp, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("unable to read response body %q: %v", obj.name, err)
}
resp.Body.Close()
if got, want := string(slurp), obj.contents; got != want {
t.Errorf("contents of %q = %q; want %q", obj.name, got, want)
}
}
name := "obj-not-exists"
if _, err := s.Objects.Get(bucket, name).Download(); !isError(err, http.StatusNotFound) {
t.Errorf("object %q should not exist, err = %v", name, err)
} else {
t.Log("Successfully tested StatusNotFound.")
}
for _, obj := range objects {
t.Logf("Checking %q metadata", obj.name)
checkMetadata(t, s, bucket, obj.name)
}
name = objects[0].name
t.Logf("Rewriting %q to %q", name, copyObj)
copy, err := s.Objects.Rewrite(bucket, name, bucket, copyObj, nil).Do()
if err != nil {
t.Errorf("unable to rewrite object %q to %q: %v", name, copyObj, err)
}
if copy.Resource.Name != copyObj {
t.Errorf("copy object's name = %q; want %q", copy.Resource.Name, copyObj)
}
if copy.Resource.Bucket != bucket {
t.Errorf("copy object's bucket = %q; want %q", copy.Resource.Bucket, bucket)
}
// Note that arrays such as ACLs below are completely overwritten using Patch
// semantics, so these must be updated in a read-modify-write sequence of operations.
// See https://cloud.google.com/storage/docs/json_api/v1/how-tos/performance#patch-semantics
// for more details.
t.Logf("Updating attributes of %q", name)
obj, err := s.Objects.Get(bucket, name).Projection("full").Fields("acl").Do()
if err != nil {
t.Errorf("Objects.Get(%q, %q): %v", bucket, name, err)
}
if err := verifyAcls(obj, "", ""); err != nil {
t.Errorf("before update ACLs: %v", err)
}
obj.ContentType = "text/html"
for _, entity := range []string{"domain-google.com", "allUsers"} {
obj.Acl = append(obj.Acl, &storage.ObjectAccessControl{Entity: entity, Role: "READER"})
}
updated, err := s.Objects.Patch(bucket, name, obj).Projection("full").Fields("contentType", "acl").Do()
if err != nil {
t.Errorf("Objects.Patch(%q, %q, %#v) failed with %v", bucket, name, obj, err)
}
if want := "text/html"; updated.ContentType != want {
t.Errorf("updated.ContentType == %q; want %q", updated.ContentType, want)
}
if err := verifyAcls(updated, "READER", "READER"); err != nil {
t.Errorf("after update ACLs: %v", err)
}
t.Log("Testing checksums")
checksumCases := []struct {
name string
contents string
size uint64
md5 string
crc32c uint32
}{
{
name: "checksum-object",
contents: "helloworld",
size: 10,
md5: "fc5e038d38a57032085441e7fe7010b0",
crc32c: 1456190592,
},
{
name: "zero-object",
contents: "",
size: 0,
md5: "d41d8cd98f00b204e9800998ecf8427e",
crc32c: 0,
},
}
for _, c := range checksumCases {
f := strings.NewReader(c.contents)
o := &storage.Object{
Bucket: bucket,
Name: c.name,
ContentType: defaultType,
ContentEncoding: "utf-8",
ContentLanguage: "en",
}
obj, err := s.Objects.Insert(bucket, o).Media(f).Do()
if err != nil {
t.Fatalf("unable to insert object %q: %v", obj, err)
}
if got, want := obj.Size, c.size; got != want {
t.Errorf("object %q size = %v; want %v", c.name, got, want)
}
md5, err := base64.StdEncoding.DecodeString(obj.Md5Hash)
if err != nil {
t.Errorf("object %q base64 decode of MD5 %q: %v", c.name, obj.Md5Hash, err)
}
if got, want := fmt.Sprintf("%x", md5), c.md5; got != want {
t.Errorf("object %q MD5 = %q; want %q", c.name, got, want)
}
var crc32c uint32
d, err := base64.StdEncoding.DecodeString(obj.Crc32c)
if err != nil {
t.Errorf("object %q base64 decode of CRC32 %q: %v", c.name, obj.Crc32c, err)
}
if err == nil && len(d) == 4 {
crc32c = uint32(d[0])<<24 + uint32(d[1])<<16 + uint32(d[2])<<8 + uint32(d[3])
}
if got, want := crc32c, c.crc32c; got != want {
t.Errorf("object %q CRC32C = %v; want %v", c.name, got, want)
}
}
}
// cleanup destroys ALL objects in the bucket!
func cleanup() error {
s := createService()
if s == nil {
return errors.New("Could not create service")
}
var pageToken string
var failed bool
for {
call := s.Objects.List(bucket)
if pageToken != "" {
call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
return fmt.Errorf("cleanup list failed: %v", err)
}
for _, obj := range resp.Items {
log.Printf("Cleanup deletion of %q", obj.Name)
if err := s.Objects.Delete(bucket, obj.Name).Do(); err != nil {
// Print the error out, but keep going.
log.Printf("Cleanup deletion of %q failed: %v", obj.Name, err)
failed = true
}
if _, err := s.Objects.Get(bucket, obj.Name).Download(); !isError(err, http.StatusNotFound) {
log.Printf("object %q should not exist, err = %v", obj.Name, err)
failed = true
} else {
log.Printf("Successfully deleted %q.", obj.Name)
}
}
if pageToken = resp.NextPageToken; pageToken == "" {
break
}
}
if failed {
return errors.New("Failed to delete at least one object")
}
return nil
}
func isError(err error, code int) bool {
if err == nil {
return false
}
ae, ok := err.(*googleapi.Error)
return ok && ae.Code == code
}
| jnewland/kops | vendor/google.golang.org/api/integration-tests/storage/integration_test.go | GO | apache-2.0 | 13,349 |
/* Copyright (c) 2019 Arm Limited
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*************************************************************************************************/
/*!
* \file
* \brief Link Layer math utilities.
*/
/*************************************************************************************************/
#ifndef LL_MATH_H
#define LL_MATH_H
#ifdef __cplusplus
extern "C" {
#endif
#include "wsf_types.h"
/**************************************************************************************************
Macros
**************************************************************************************************/
/*! \brief Binary divide with 1,000 divisor (n[max]=7,999). */
#define LL_MATH_DIV_10E3(n) (((n) * UINT32_C(536871)) >> 29)
/*! \brief Binary divide with 1,000,000 divisor (n[max]=0xFFFFFFFF). */
#define LL_MATH_DIV_10E6(n) ((uint32_t)(((uint64_t)(n) * UINT64_C(4295)) >> 32))
/*! \brief Binary divide with 10 divisor (n[max]=0xFFFFFFFF). */
#define LL_MATH_DIV_10(n) ((uint32_t)(((uint64_t)(n) * UINT64_C(419431)) >> 22))
/*! \brief Binary divide with 27 divisor (n[max]=55,295). */
#define LL_MATH_DIV_27(n) (((n) * UINT32_C(77673)) >> 21)
/*! \brief Binary divide with 37 divisor (n[max]=75,776). */
#define LL_MATH_DIV_37(n) (((n) * UINT32_C(56680)) >> 21)
/*! \brief Binary modulo 37. */
#define LL_MATH_MOD_37(n) ((n) - (LL_MATH_DIV_37(n) * 37))
/*! \brief Binary divide with 1250 divisor (n[max]=0xFFFFFFFF). */
#define LL_MATH_DIV_1250(n) ((uint32_t)(((uint64_t)(n) * UINT64_C(1717987)) >> 31))
/*! \brief Binary divide with 625 divisor (n[max]=0xFFFFFFFF). */
#define LL_MATH_DIV_625(n) ((uint32_t)(((uint64_t)(n) * UINT64_C(1717987)) >> 30))
/*! \brief Binary divide with 30 divisor (n[max]=0xFFFFFFFF). */
#define LL_MATH_DIV_30(n) ((uint32_t)(((uint64_t)(n) * UINT64_C(286331154)) >> 33))
/*! \brief Binary divide with 300 divisor (n[max]=0x3FFFFFFF). */
#define LL_MATH_DIV_300(n) ((uint32_t)(((uint64_t)(n) * UINT64_C(14660155038)) >> 42))
/**************************************************************************************************
Data Types
**************************************************************************************************/
/*! \brief ECC service callback. */
typedef void (*LlMathEccServiceCback_t)(uint8_t op);
/*! \brief ECC operations. */
enum
{
LL_MATH_ECC_OP_GENERATE_P256_KEY_PAIR, /*!< Generate P-256 key pair. */
LL_MATH_ECC_OP_GENERATE_DH_KEY /*!< Generate Diffie-Hellman key. */
};
/**************************************************************************************************
Function Declarations
**************************************************************************************************/
/*************************************************************************************************/
/*!
* \brief Generate random number.
*
* \return 32-bit random number.
*/
/*************************************************************************************************/
uint32_t LlMathRandNum(void);
/*************************************************************************************************/
/*!
* \brief Return the number of bits which are set.
*
* \param num Input parameter.
*
* \return Number of bits which are set.
*/
/*************************************************************************************************/
uint8_t LlMathGetNumBitsSet(uint64_t num);
/*************************************************************************************************/
/*!
* \brief Return result of a division.
*
* \param nu32 Numerator of size 32 bits.
* \param de32 Denominator of size 32 bits.
*
* \return Result of a division.
*/
/*************************************************************************************************/
uint32_t LlMathDivideUint32(uint32_t nu32, uint32_t de32);
#ifdef __cplusplus
};
#endif
#endif /* LL_API_H */
| kjbracey-arm/mbed | features/FEATURE_BLE/targets/TARGET_CORDIO_LL/stack/controller/include/ble/ll_math.h | C | apache-2.0 | 4,604 |
class Prefixsuffix < Formula
desc "GUI batch renaming utility"
homepage "https://github.com/murraycu/prefixsuffix"
url "https://download.gnome.org/sources/prefixsuffix/0.6/prefixsuffix-0.6.9.tar.xz"
sha256 "fc3202bddf2ebbb93ffd31fc2a079cfc05957e4bf219535f26e6d8784d859e9b"
bottle do
sha256 "cf1ee40aeaa52ad6fe92570c1f914d98275a3d9c2bbc6f93ca1ea9f061c0f973" => :sierra
sha256 "1143a29769e566e030bec8f3bf7a3f24a9c7fc69638511b6964571cc255b696f" => :el_capitan
sha256 "544f17fbc8873abb8725d469f2cb076245d93527008f805f7b29416b6b20a82f" => :yosemite
sha256 "eb984287bf98618cf61cf5e9ed85103077aaf4a36c8309fdcb6c9ecb736b4272" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "intltool" => :build
depends_on "gtkmm3"
needs :cxx11
def install
ENV.cxx11
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--disable-schemas-compile"
system "make", "install"
end
def post_install
system "#{Formula["glib"].opt_bin}/glib-compile-schemas", "#{HOMEBREW_PREFIX}/share/glib-2.0/schemas"
end
test do
system "#{bin}/prefixsuffix", "--version"
end
end
| kuahyeow/homebrew-core | Formula/prefixsuffix.rb | Ruby | bsd-2-clause | 1,250 |
This unofficial harmony branch has been removed.
Esprima 2.x continues to add supports for ES6 features (#1099). It is
recommended to use the latest 2.x release, e.g. from its official
[npm module](https://www.npmjs.com/package/esprima).
| dugaldmorrow/sequence-diagrams | node_modules/istanbul/node_modules/esprima/README.md | Markdown | bsd-2-clause | 239 |
class Multimarkdown < Formula
desc "Turn marked-up plain text into well-formatted documents"
homepage "http://fletcherpenney.net/multimarkdown/"
# Use git tag instead of the tarball to get submodules
url "https://github.com/fletcher/MultiMarkdown-5.git",
:tag => "5.4.0",
:revision => "193c09a5362eb8a6c6433cd5d5f1d7db3efe986a"
head "https://github.com/fletcher/MultiMarkdown-5.git"
bottle do
cellar :any_skip_relocation
sha256 "cc9f163eaa9eb53def1e66cd2e3871ea9f8274028a3d399d01e2944d8cf2ac6f" => :sierra
sha256 "72571c5521bda002ce2b140bc7e8fd224c0545e9f21b6268ad5a2ecedfe4e025" => :el_capitan
sha256 "7c5370be42b0e15b19da90d8ead5aec745e24c842aea2cf2c210f399d84b67d8" => :yosemite
sha256 "475aed59ab53d010d8238fb8d0646c43de994c46893baecabcbcfc33c99b15fc" => :mavericks
end
depends_on "cmake" => :build
conflicts_with "mtools", :because => "both install `mmd` binaries"
conflicts_with "markdown", :because => "both install `markdown` binaries"
conflicts_with "discount", :because => "both install `markdown` binaries"
def install
system "sh", "link_git_modules"
system "sh", "update_git_modules"
system "make"
cd "build" do
system "make"
bin.install "multimarkdown"
end
bin.install Dir["scripts/*"].reject { |f| f =~ /\.bat$/ }
end
test do
assert_equal "<p>foo <em>bar</em></p>\n", pipe_output(bin/"multimarkdown", "foo *bar*\n")
assert_equal "<p>foo <em>bar</em></p>\n", pipe_output(bin/"mmd", "foo *bar*\n")
end
end
| kunickiaj/homebrew-core | Formula/multimarkdown.rb | Ruby | bsd-2-clause | 1,528 |
cask 'fontexplorer-x-pro' do
version '6.0.2'
sha256 'f842e373d6126218dcd34bd116ceab29a7abb5c6ea22afec04ad86652f19a290'
url "http://fast.fontexplorerx.com/FontExplorerXPro#{version.no_dots}.dmg"
name 'FontExplorer X Pro'
homepage 'https://www.fontexplorerx.com/'
depends_on macos: '>= :mountain_lion'
app 'FontExplorer X Pro.app'
zap delete: [
'/Library/PrivilegedHelperTools/com.linotype.FontExplorerX.securityhelper',
'/Library/LaunchDaemons/com.linotype.FontExplorerX.securityhelper.plist',
'~/Library/Application Support/Linotype/FontExplorer X',
'~/Library/Application\ Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.linotype.fontexplorerx.sfl',
'~/Library/Caches/com.linotype.FontExplorerX',
'~/Library/Cookies/com.linotype.FontExplorerX.binarycookies',
'~/Library/LaunchAgents/com.linotype.FontFolderProtector.plist',
'~/Library/Preferences/com.linotype.FontExplorerX.plist',
'~/Library/Saved\ Application\ State/com.linotype.FontExplorerX.savedState',
]
end
| malford/homebrew-cask | Casks/fontexplorer-x-pro.rb | Ruby | bsd-2-clause | 1,187 |
/* Implementation of the SET_EXPONENT intrinsic
Copyright 2003 Free Software Foundation, Inc.
Contributed by Richard Henderson <rth@redhat.com>.
This file is part of the GNU Fortran 95 runtime library (libgfortran).
Libgfortran is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
In addition to the permissions in the GNU General Public License, the
Free Software Foundation gives you unlimited permission to link the
compiled version of this file into combinations with other programs,
and to distribute those combinations without any restriction coming
from the use of this file. (The General Public License restrictions
do apply in other respects; for example, they cover modification of
the file, and distribution when not linked into a combine
executable.)
Libgfortran is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public
License along with libgfortran; see the file COPYING. If not,
write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA. */
#include "config.h"
#include <math.h>
#include "libgfortran.h"
#if defined (HAVE_GFC_REAL_16) && defined (HAVE_SCALBNL) && defined (HAVE_FREXPL)
extern GFC_REAL_16 set_exponent_r16 (GFC_REAL_16 s, GFC_INTEGER_4 i);
export_proto(set_exponent_r16);
GFC_REAL_16
set_exponent_r16 (GFC_REAL_16 s, GFC_INTEGER_4 i)
{
int dummy_exp;
return scalbnl (frexpl (s, &dummy_exp), i);
}
#endif
| shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libgfortran/generated/set_exponent_r16.c | C | bsd-3-clause | 1,802 |
-a *.foo,-a ns|a{a:b}
| mgushee/chicken-sass | tests/test-cases/extend-tests/051_test_element_unification_with_namespaceless_universal_target/expected.compressed.css | CSS | bsd-3-clause | 22 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Service_DeveloperGarden_Request_RequestAbstract
*/
// require_once 'Zend/Service/DeveloperGarden/Request/RequestAbstract.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @author Marco Kaiser
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
extends Zend_Service_DeveloperGarden_Request_RequestAbstract
{
/**
* unique owner id
*
* @var string
*/
public $ownerId = null;
/**
* object with details for this conference
*
* @var Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail
*/
public $detail = null;
/**
* array with Zend_Service_DeveloperGarden_ConferenceCall_ParticipantDetail elements
*
* @var array
*/
public $participants = null;
/**
* constructor
*
* @param integer $environment
* @param string $ownerId
* @param Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $conferenceDetails
* @param array $conferenceParticipants
*/
public function __construct($environment, $ownerId,
Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $conferenceDetails,
array $conferenceParticipants = null
) {
parent::__construct($environment);
$this->setOwnerId($ownerId)
->setDetail($conferenceDetails)
->setParticipants($conferenceParticipants);
}
/**
* sets $participants
*
* @param array $participants
* @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
*/
public function setParticipants(array $participants = null)
{
$this->participants = $participants;
return $this;
}
/**
* sets $detail
*
* @param Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $detail
* @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
*/
public function setDetail(Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $detail)
{
$this->detail = $detail;
return $this;
}
/**
* sets $ownerId
*
* @param string $ownerId
* @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
*/
public function setOwnerId($ownerId)
{
$this->ownerId = $ownerId;
return $this;
}
}
| kanevbg/pimcore | pimcore/lib/Zend/Service/DeveloperGarden/Request/ConferenceCall/CreateConferenceTemplateRequest.php | PHP | bsd-3-clause | 3,379 |
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* Implements custom element observation and attached/detached callbacks
* @module observe
*/
window.CustomElements.addModule(function(scope){
// imports
var flags = scope.flags;
var forSubtree = scope.forSubtree;
var forDocumentTree = scope.forDocumentTree;
/*
Manage nodes attached to document trees
*/
// manage lifecycle on added node and it's subtree; upgrade the node and
// entire subtree if necessary and process attached for the node and entire
// subtree
function addedNode(node, isAttached) {
return added(node, isAttached) || addedSubtree(node, isAttached);
}
// manage lifecycle on added node; upgrade if necessary and process attached
function added(node, isAttached) {
if (scope.upgrade(node, isAttached)) {
// Return true to indicate
return true;
}
if (isAttached) {
attached(node);
}
}
// manage lifecycle on added node's subtree only; allows the entire subtree
// to upgrade if necessary and process attached
function addedSubtree(node, isAttached) {
forSubtree(node, function(e) {
if (added(e, isAttached)) {
return true;
}
});
}
// On platforms without MutationObserver, mutations may not be
// reliable and therefore attached/detached are not reliable.
// To make these callbacks less likely to fail, we defer all inserts and removes
// to give a chance for elements to be attached into dom.
// This ensures attachedCallback fires for elements that are created and
// immediately added to dom.
var hasPolyfillMutations = (!window.MutationObserver ||
(window.MutationObserver === window.JsMutationObserver));
scope.hasPolyfillMutations = hasPolyfillMutations;
var isPendingMutations = false;
var pendingMutations = [];
function deferMutation(fn) {
pendingMutations.push(fn);
if (!isPendingMutations) {
isPendingMutations = true;
setTimeout(takeMutations);
}
}
function takeMutations() {
isPendingMutations = false;
var $p = pendingMutations;
for (var i=0, l=$p.length, p; (i<l) && (p=$p[i]); i++) {
p();
}
pendingMutations = [];
}
function attached(element) {
if (hasPolyfillMutations) {
deferMutation(function() {
_attached(element);
});
} else {
_attached(element);
}
}
// NOTE: due to how MO works (see comments below), an element may be attached
// multiple times so we protect against extra processing here.
function _attached(element) {
// track element for insertion if it's upgraded and cares about insertion
// bail if the element is already marked as attached
if (element.__upgraded__ && !element.__attached) {
element.__attached = true;
if (element.attachedCallback) {
element.attachedCallback();
}
}
}
/*
Manage nodes detached from document trees
*/
// manage lifecycle on detached node and it's subtree; process detached
// for the node and entire subtree
function detachedNode(node) {
detached(node);
forSubtree(node, function(e) {
detached(e);
});
}
function detached(element) {
if (hasPolyfillMutations) {
deferMutation(function() {
_detached(element);
});
} else {
_detached(element);
}
}
// NOTE: due to how MO works (see comments below), an element may be detached
// multiple times so we protect against extra processing here.
function _detached(element) {
// track element for removal if it's upgraded and cares about removal
// bail if the element is already marked as not attached
if (element.__upgraded__ && element.__attached) {
element.__attached = false;
if (element.detachedCallback) {
element.detachedCallback();
}
}
}
// recurse up the tree to check if an element is actually in the main document.
function inDocument(element) {
var p = element;
var doc = window.wrap(document);
while (p) {
if (p == doc) {
return true;
}
p = p.parentNode || ((p.nodeType === Node.DOCUMENT_FRAGMENT_NODE) && p.host);
}
}
// Install an element observer on all shadowRoots owned by node.
function watchShadow(node) {
if (node.shadowRoot && !node.shadowRoot.__watched) {
flags.dom && console.log('watching shadow-root for: ', node.localName);
// watch all unwatched roots...
var root = node.shadowRoot;
while (root) {
observe(root);
root = root.olderShadowRoot;
}
}
}
/*
NOTE: In order to process all mutations, it's necessary to recurse into
any added nodes. However, it's not possible to determine a priori if a node
will get its own mutation record. This means
*nodes can be seen multiple times*.
Here's an example:
(1) In this case, recursion is required to see `child`:
node.innerHTML = '<div><child></child></div>'
(2) In this case, child will get its own mutation record:
node.appendChild(div).appendChild(child);
We cannot know ahead of time if we need to walk into the node in (1) so we
do and see child; however, if it was added via case (2) then it will have its
own record and therefore be seen 2x.
*/
function handler(root, mutations) {
// for logging only
if (flags.dom) {
var mx = mutations[0];
if (mx && mx.type === 'childList' && mx.addedNodes) {
if (mx.addedNodes) {
var d = mx.addedNodes[0];
while (d && d !== document && !d.host) {
d = d.parentNode;
}
var u = d && (d.URL || d._URL || (d.host && d.host.localName)) || '';
u = u.split('/?').shift().split('/').pop();
}
}
console.group('mutations (%d) [%s]', mutations.length, u || '');
}
// handle mutations
// NOTE: do an `inDocument` check dynamically here. It's possible that `root`
// is a document in which case the answer here can never change; however
// `root` may be an element like a shadowRoot that can be added/removed
// from the main document.
var isAttached = inDocument(root);
mutations.forEach(function(mx) {
if (mx.type === 'childList') {
forEach(mx.addedNodes, function(n) {
if (!n.localName) {
return;
}
addedNode(n, isAttached);
});
forEach(mx.removedNodes, function(n) {
if (!n.localName) {
return;
}
detachedNode(n);
});
}
});
flags.dom && console.groupEnd();
};
/*
When elements are added to the dom, upgrade and attached/detached may be
asynchronous. `CustomElements.takeRecords` can be called to process any
pending upgrades and attached/detached callbacks synchronously.
*/
function takeRecords(node) {
node = window.wrap(node);
// If the optional node is not supplied, assume we mean the whole document.
if (!node) {
node = window.wrap(document);
}
// Find the root of the tree, which will be an Document or ShadowRoot.
while (node.parentNode) {
node = node.parentNode;
}
var observer = node.__observer;
if (observer) {
handler(node, observer.takeRecords());
takeMutations();
}
}
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
// observe a node tree; bail if it's already being observed.
function observe(inRoot) {
if (inRoot.__observer) {
return;
}
// For each ShadowRoot, we create a new MutationObserver, so the root can be
// garbage collected once all references to the `inRoot` node are gone.
// Give the handler access to the root so that an 'in document' check can
// be done.
var observer = new MutationObserver(handler.bind(this, inRoot));
observer.observe(inRoot, {childList: true, subtree: true});
inRoot.__observer = observer;
}
// upgrade an entire document and observe it for elements changes.
function upgradeDocument(doc) {
doc = window.wrap(doc);
flags.dom && console.group('upgradeDocument: ', (doc.baseURI).split('/').pop());
var isMainDocument = (doc === window.wrap(document));
addedNode(doc, isMainDocument);
observe(doc);
flags.dom && console.groupEnd();
}
/*
This method is intended to be called when the document tree (including imports)
has pending custom elements to upgrade. It can be called multiple times and
should do nothing if no elements are in need of upgrade.
*/
function upgradeDocumentTree(doc) {
forDocumentTree(doc, upgradeDocument);
}
// Patch `createShadowRoot()` if Shadow DOM is available, otherwise leave
// undefined to aid feature detection of Shadow DOM.
var originalCreateShadowRoot = Element.prototype.createShadowRoot;
if (originalCreateShadowRoot) {
Element.prototype.createShadowRoot = function() {
var root = originalCreateShadowRoot.call(this);
window.CustomElements.watchShadow(this);
return root;
};
}
// exports
scope.watchShadow = watchShadow;
scope.upgradeDocumentTree = upgradeDocumentTree;
scope.upgradeDocument = upgradeDocument;
scope.upgradeSubtree = addedSubtree;
scope.upgradeAll = addedNode;
scope.attached = attached;
scope.takeRecords = takeRecords;
});
| tachyon1337/webcomponentsjs | src/CustomElements/observe.js | JavaScript | bsd-3-clause | 9,347 |
<?php
/**
* Squiz_Sniffs_Formatting_OperationBracketSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Squiz_Sniffs_Formatting_OperationBracketSniff.
*
* Tests that all arithmetic operations are bracketed.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @version Release: 1.4.3
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Squiz_Sniffs_Formatting_OperatorBracketSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return PHP_CodeSniffer_Tokens::$operators;
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($phpcsFile->tokenizerType === 'JS' && $tokens[$stackPtr]['code'] === T_PLUS) {
// JavaScript uses the plus operator for string concatenation as well
// so we cannot accurately determine if it is a string concat or addition.
// So just ignore it.
return;
}
// If the & is a reference, then we don't want to check for brackets.
if ($tokens[$stackPtr]['code'] === T_BITWISE_AND && $phpcsFile->isReference($stackPtr) === true) {
return;
}
// There is one instance where brackets aren't needed, which involves
// the minus sign being used to assign a negative number to a variable.
if ($tokens[$stackPtr]['code'] === T_MINUS) {
// Check to see if we are trying to return -n.
$prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($tokens[$prev]['code'] === T_RETURN) {
return;
}
$number = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$number]['code'] === T_LNUMBER || $tokens[$number]['code'] === T_DNUMBER) {
$previous = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
if ($previous !== false) {
$isAssignment = in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens);
$isEquality = in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$equalityTokens);
$isComparison = in_array($tokens[$previous]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens);
if ($isAssignment === true || $isEquality === true || $isComparison === true) {
// This is a negative assignment or comparion.
// We need to check that the minus and the number are
// adjacent.
if (($number - $stackPtr) !== 1) {
$error = 'No space allowed between minus sign and number';
$phpcsFile->addError($error, $stackPtr, 'SpacingAfterMinus');
}
return;
}
}
}
}//end if
$lastBracket = false;
if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
$parenthesis = array_reverse($tokens[$stackPtr]['nested_parenthesis'], true);
foreach ($parenthesis as $bracket => $endBracket) {
$prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($bracket - 1), null, true);
$prevCode = $tokens[$prevToken]['code'];
if ($prevCode === T_ISSET) {
// This operation is inside an isset() call, but has
// no bracket of it's own.
break;
}
if ($prevCode === T_STRING || $prevCode === T_SWITCH) {
// We allow very simple operations to not be bracketed.
// For example, ceil($one / $two).
$allowed = array(
T_VARIABLE,
T_LNUMBER,
T_DNUMBER,
T_STRING,
T_WHITESPACE,
T_THIS,
T_OBJECT_OPERATOR,
T_OPEN_SQUARE_BRACKET,
T_CLOSE_SQUARE_BRACKET,
T_MODULUS,
);
for ($prev = ($stackPtr - 1); $prev > $bracket; $prev--) {
if (in_array($tokens[$prev]['code'], $allowed) === true) {
continue;
}
if ($tokens[$prev]['code'] === T_CLOSE_PARENTHESIS) {
$prev = $tokens[$prev]['parenthesis_opener'];
} else {
break;
}
}
if ($prev !== $bracket) {
break;
}
for ($next = ($stackPtr + 1); $next < $endBracket; $next++) {
if (in_array($tokens[$next]['code'], $allowed) === true) {
continue;
}
if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) {
$next = $tokens[$next]['parenthesis_closer'];
} else {
break;
}
}
if ($next !== $endBracket) {
break;
}
}//end if
if (in_array($prevCode, PHP_CodeSniffer_Tokens::$scopeOpeners) === true) {
// This operation is inside a control structure like FOREACH
// or IF, but has no bracket of it's own.
// The only control structure allowed to do this is SWITCH.
if ($prevCode !== T_SWITCH) {
break;
}
}
if ($prevCode === T_OPEN_PARENTHESIS) {
// These are two open parenthesis in a row. If the current
// one doesn't enclose the operator, go to the previous one.
if ($endBracket < $stackPtr) {
continue;
}
}
$lastBracket = $bracket;
break;
}//end foreach
}//end if
if ($lastBracket === false) {
// It is not in a bracketed statement at all.
$previousToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true, null, true);
if ($previousToken !== false) {
// A list of tokens that indicate that the token is not
// part of an arithmetic operation.
$invalidTokens = array(
T_COMMA,
T_COLON,
T_OPEN_PARENTHESIS,
T_OPEN_SQUARE_BRACKET,
T_CASE,
);
if (in_array($tokens[$previousToken]['code'], $invalidTokens) === false) {
$error = 'Arithmetic operation must be bracketed';
$phpcsFile->addError($error, $stackPtr, 'MissingBrackets');
}
return;
}
} else if ($tokens[$lastBracket]['parenthesis_closer'] < $stackPtr) {
// There are a set of brackets in front of it that don't include it.
$error = 'Arithmetic operation must be bracketed';
$phpcsFile->addError($error, $stackPtr, 'MissingBrackets');
return;
} else {
// We are enclosed in a set of bracket, so the last thing to
// check is that we are not also enclosed in square brackets
// like this: ($array[$index + 1]), which is invalid.
$brackets = array(
T_OPEN_SQUARE_BRACKET,
T_CLOSE_SQUARE_BRACKET,
);
$squareBracket = $phpcsFile->findPrevious($brackets, ($stackPtr - 1), $lastBracket);
if ($squareBracket !== false && $tokens[$squareBracket]['code'] === T_OPEN_SQUARE_BRACKET) {
$closeSquareBracket = $phpcsFile->findNext($brackets, ($stackPtr + 1));
if ($closeSquareBracket !== false && $tokens[$closeSquareBracket]['code'] === T_CLOSE_SQUARE_BRACKET) {
$error = 'Arithmetic operation must be bracketed';
$phpcsFile->addError($error, $stackPtr, 'MissingBrackets');
}
}
return;
}//end if
$lastAssignment = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$assignmentTokens, $stackPtr, null, false, null, true);
if ($lastAssignment !== false && $lastAssignment > $lastBracket) {
$error = 'Arithmetic operation must be bracketed';
$phpcsFile->addError($error, $stackPtr, 'MissingBrackets');
}
}//end process()
}//end class
?>
| theghostbel/pimcore | tests/lib/PHP/CodeSniffer/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php | PHP | bsd-3-clause | 10,520 |
/*
* Copyright (C) 2010 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "core/workers/WorkerEventQueue.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/ExecutionContextTask.h"
#include "core/events/Event.h"
#include "core/inspector/InspectorInstrumentation.h"
namespace blink {
PassOwnPtrWillBeRawPtr<WorkerEventQueue> WorkerEventQueue::create(ExecutionContext* context)
{
return adoptPtrWillBeNoop(new WorkerEventQueue(context));
}
WorkerEventQueue::WorkerEventQueue(ExecutionContext* context)
: m_executionContext(context)
, m_isClosed(false)
{
}
WorkerEventQueue::~WorkerEventQueue()
{
ASSERT(m_eventTaskMap.isEmpty());
}
void WorkerEventQueue::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
visitor->trace(m_executionContext);
visitor->trace(m_eventTaskMap);
#endif
EventQueue::trace(visitor);
}
class WorkerEventQueue::EventDispatcherTask : public ExecutionContextTask {
public:
static PassOwnPtr<EventDispatcherTask> create(PassRefPtrWillBeRawPtr<Event> event, WorkerEventQueue* eventQueue)
{
return adoptPtr(new EventDispatcherTask(event, eventQueue));
}
virtual ~EventDispatcherTask()
{
if (m_event)
m_eventQueue->removeEvent(m_event.get());
}
void dispatchEvent(ExecutionContext*, PassRefPtrWillBeRawPtr<Event> event)
{
event->target()->dispatchEvent(event);
}
virtual void performTask(ExecutionContext* context)
{
if (m_isCancelled)
return;
m_eventQueue->removeEvent(m_event.get());
dispatchEvent(context, m_event);
m_event.clear();
}
void cancel()
{
m_isCancelled = true;
m_event.clear();
}
private:
EventDispatcherTask(PassRefPtrWillBeRawPtr<Event> event, WorkerEventQueue* eventQueue)
: m_event(event)
, m_eventQueue(eventQueue)
, m_isCancelled(false)
{
}
RefPtrWillBePersistent<Event> m_event;
WorkerEventQueue* m_eventQueue;
bool m_isCancelled;
};
void WorkerEventQueue::removeEvent(Event* event)
{
InspectorInstrumentation::didRemoveEvent(event->target(), event);
m_eventTaskMap.remove(event);
}
bool WorkerEventQueue::enqueueEvent(PassRefPtrWillBeRawPtr<Event> prpEvent)
{
if (m_isClosed)
return false;
RefPtrWillBeRawPtr<Event> event = prpEvent;
InspectorInstrumentation::didEnqueueEvent(event->target(), event.get());
OwnPtr<EventDispatcherTask> task = EventDispatcherTask::create(event, this);
m_eventTaskMap.add(event.release(), task.get());
m_executionContext->postTask(task.release());
return true;
}
bool WorkerEventQueue::cancelEvent(Event* event)
{
EventDispatcherTask* task = m_eventTaskMap.get(event);
if (!task)
return false;
task->cancel();
removeEvent(event);
return true;
}
void WorkerEventQueue::close()
{
m_isClosed = true;
for (EventTaskMap::iterator it = m_eventTaskMap.begin(); it != m_eventTaskMap.end(); ++it) {
Event* event = it->key.get();
EventDispatcherTask* task = it->value;
InspectorInstrumentation::didRemoveEvent(event->target(), event);
task->cancel();
}
m_eventTaskMap.clear();
}
}
| xin3liang/platform_external_chromium_org_third_party_WebKit | Source/core/workers/WorkerEventQueue.cpp | C++ | bsd-3-clause | 4,525 |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generator for C++ structs from api json files.
The purpose of this tool is to remove the need for hand-written code that
converts to and from base::Value types when receiving javascript api calls.
Originally written for generating code for extension apis. Reference schemas
are in chrome/common/extensions/api.
Usage example:
compiler.py --root /home/Work/src --namespace extensions windows.json
tabs.json
compiler.py --destdir gen --root /home/Work/src
--namespace extensions windows.json tabs.json
"""
import optparse
import os
import shlex
import sys
from cpp_bundle_generator import CppBundleGenerator
from cpp_generator import CppGenerator
from cpp_type_generator import CppTypeGenerator
from js_externs_generator import JsExternsGenerator
from js_interface_generator import JsInterfaceGenerator
import json_schema
from cpp_namespace_environment import CppNamespaceEnvironment
from model import Model
from schema_loader import SchemaLoader
# Names of supported code generators, as specified on the command-line.
# First is default.
GENERATORS = [
'cpp', 'cpp-bundle-registration', 'cpp-bundle-schema', 'externs', 'interface'
]
def GenerateSchema(generator_name,
file_paths,
root,
destdir,
cpp_namespace_pattern,
bundle_name,
impl_dir,
include_rules):
# Merge the source files into a single list of schemas.
api_defs = []
for file_path in file_paths:
schema = os.path.relpath(file_path, root)
schema_loader = SchemaLoader(
root,
os.path.dirname(schema),
include_rules,
cpp_namespace_pattern)
api_def = schema_loader.LoadSchema(schema)
# If compiling the C++ model code, delete 'nocompile' nodes.
if generator_name == 'cpp':
api_def = json_schema.DeleteNodes(api_def, 'nocompile')
# Delete all 'nodefine' nodes. They are only for documentation.
api_def = json_schema.DeleteNodes(api_def, 'nodefine')
api_defs.extend(api_def)
api_model = Model(allow_inline_enums=False)
# For single-schema compilation make sure that the first (i.e. only) schema
# is the default one.
default_namespace = None
# If we have files from multiple source paths, we'll use the common parent
# path as the source directory.
src_path = None
# Load the actual namespaces into the model.
for target_namespace, file_path in zip(api_defs, file_paths):
relpath = os.path.relpath(os.path.normpath(file_path), root)
namespace = api_model.AddNamespace(target_namespace,
relpath,
include_compiler_options=True,
environment=CppNamespaceEnvironment(
cpp_namespace_pattern))
if default_namespace is None:
default_namespace = namespace
if src_path is None:
src_path = namespace.source_file_dir
else:
src_path = os.path.commonprefix((src_path, namespace.source_file_dir))
_, filename = os.path.split(file_path)
filename_base, _ = os.path.splitext(filename)
# Construct the type generator with all the namespaces in this model.
type_generator = CppTypeGenerator(api_model,
schema_loader,
default_namespace)
if generator_name in ('cpp-bundle-registration', 'cpp-bundle-schema'):
cpp_bundle_generator = CppBundleGenerator(root,
api_model,
api_defs,
type_generator,
cpp_namespace_pattern,
bundle_name,
src_path,
impl_dir)
if generator_name == 'cpp-bundle-registration':
generators = [
('generated_api_registration.cc',
cpp_bundle_generator.api_cc_generator),
('generated_api_registration.h', cpp_bundle_generator.api_h_generator),
]
elif generator_name == 'cpp-bundle-schema':
generators = [
('generated_schemas.cc', cpp_bundle_generator.schemas_cc_generator),
('generated_schemas.h', cpp_bundle_generator.schemas_h_generator)
]
elif generator_name == 'cpp':
cpp_generator = CppGenerator(type_generator)
generators = [
('%s.h' % filename_base, cpp_generator.h_generator),
('%s.cc' % filename_base, cpp_generator.cc_generator)
]
elif generator_name == 'externs':
generators = [
('%s_externs.js' % namespace.unix_name, JsExternsGenerator())
]
elif generator_name == 'interface':
generators = [
('%s_interface.js' % namespace.unix_name, JsInterfaceGenerator())
]
else:
raise Exception('Unrecognised generator %s' % generator_name)
output_code = []
for filename, generator in generators:
code = generator.Generate(namespace).Render()
if destdir:
if generator_name == 'cpp-bundle-registration':
# Function registrations must be output to impl_dir, since they link in
# API implementations.
output_dir = os.path.join(destdir, impl_dir)
else:
output_dir = os.path.join(destdir, src_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(os.path.join(output_dir, filename), 'w') as f:
f.write(code)
# If multiple files are being output, add the filename for each file.
if len(generators) > 1:
output_code += [filename, '', code, '']
else:
output_code += [code]
return '\n'.join(output_code)
if __name__ == '__main__':
parser = optparse.OptionParser(
description='Generates a C++ model of an API from JSON schema',
usage='usage: %prog [option]... schema')
parser.add_option('-r', '--root', default='.',
help='logical include root directory. Path to schema files from specified'
' dir will be the include path.')
parser.add_option('-d', '--destdir',
help='root directory to output generated files.')
parser.add_option('-n', '--namespace', default='generated_api_schemas',
help='C++ namespace for generated files. e.g extensions::api.')
parser.add_option('-b', '--bundle-name', default='',
help='A string to prepend to generated bundle class names, so that '
'multiple bundle rules can be used without conflicting. '
'Only used with one of the cpp-bundle generators.')
parser.add_option('-g', '--generator', default=GENERATORS[0],
choices=GENERATORS,
help='The generator to use to build the output code. Supported values are'
' %s' % GENERATORS)
parser.add_option('-i', '--impl-dir', dest='impl_dir',
help='The root path of all API implementations')
parser.add_option('-I', '--include-rules',
help='A list of paths to include when searching for referenced objects,'
' with the namespace separated by a \':\'. Example: '
'/foo/bar:Foo::Bar::%(namespace)s')
(opts, file_paths) = parser.parse_args()
if not file_paths:
sys.exit(0) # This is OK as a no-op
# Unless in bundle mode, only one file should be specified.
if (opts.generator not in ('cpp-bundle-registration', 'cpp-bundle-schema') and
len(file_paths) > 1):
# TODO(sashab): Could also just use file_paths[0] here and not complain.
raise Exception(
"Unless in bundle mode, only one file can be specified at a time.")
def split_path_and_namespace(path_and_namespace):
if ':' not in path_and_namespace:
raise ValueError('Invalid include rule "%s". Rules must be of '
'the form path:namespace' % path_and_namespace)
return path_and_namespace.split(':', 1)
include_rules = []
if opts.include_rules:
include_rules = map(split_path_and_namespace,
shlex.split(opts.include_rules))
result = GenerateSchema(opts.generator, file_paths, opts.root, opts.destdir,
opts.namespace, opts.bundle_name, opts.impl_dir,
include_rules)
if not opts.destdir:
print result
| heke123/chromium-crosswalk | tools/json_schema_compiler/compiler.py | Python | bsd-3-clause | 8,474 |
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/licenses/publicdomain/
//-----------------------------------------------------------------------------
var BUGNUMBER = 565604;
var summary =
"Typed-array properties don't work when accessed from an object whose " +
"prototype (or further-descended prototype) is a typed array";
print(BUGNUMBER + ": " + summary);
/**************
* BEGIN TEST *
**************/
var o = Object.create(new Uint8Array(1));
assertEq(o.length, 1);
var o2 = Object.create(o);
assertEq(o2.length, 1);
var VARIABLE_OBJECT = {};
var props =
[
{ property: "length", value: 1 },
{ property: "byteLength", value: 1 },
{ property: "byteOffset", value: 0 },
{ property: "buffer", value: VARIABLE_OBJECT },
];
for (var i = 0, sz = props.length; i < sz; i++)
{
var p = props[i];
var o = Object.create(new Uint8Array(1));
var v = o[p.property];
if (p.value !== VARIABLE_OBJECT)
assertEq(o[p.property], p.value, "bad " + p.property + " (proto)");
var o2 = Object.create(o);
if (p.value !== VARIABLE_OBJECT)
assertEq(o2[p.property], p.value, "bad " + p.property + " (grand-proto)");
assertEq(o2[p.property], v, p.property + " mismatch");
}
reportCompare(true, true);
| darkrsw/safe | tests/browser_extensions/js1_8_5/extensions/typedarray-prototype.js | JavaScript | bsd-3-clause | 1,266 |
all: i3status.1
A2X?=a2x
i3status.1: asciidoc.conf i3status.man
${A2X} -f manpage --asciidoc-opts="-f asciidoc.conf" i3status.man
clean:
rm -f i3status.xml i3status.1 i3status.html
| oberon2007/i3status-manjaro | man/Makefile | Makefile | bsd-3-clause | 185 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_COMMON_VIEW_TYPE_H_
#define EXTENSIONS_COMMON_VIEW_TYPE_H_
namespace extensions {
// Icky RTTI used by a few systems to distinguish the host type of a given
// WebContents.
//
// TODO(aa): Remove this and teach those systems to keep track of their own
// data.
enum ViewType {
VIEW_TYPE_INVALID,
VIEW_TYPE_APP_WINDOW,
VIEW_TYPE_BACKGROUND_CONTENTS,
VIEW_TYPE_EXTENSION_BACKGROUND_PAGE,
VIEW_TYPE_EXTENSION_DIALOG,
VIEW_TYPE_EXTENSION_INFOBAR,
VIEW_TYPE_EXTENSION_POPUP,
VIEW_TYPE_PANEL,
VIEW_TYPE_TAB_CONTENTS,
VIEW_TYPE_VIRTUAL_KEYBOARD,
VIEW_TYPE_LAST = VIEW_TYPE_VIRTUAL_KEYBOARD
};
// Constant strings corresponding to the Type enumeration values. Used
// when converting JS arguments.
extern const char kViewTypeAll[];
extern const char kViewTypeAppWindow[];
extern const char kViewTypeBackgroundPage[];
extern const char kViewTypeExtensionDialog[];
extern const char kViewTypeInfobar[];
extern const char kViewTypePanel[];
extern const char kViewTypePopup[];
extern const char kViewTypeTabContents[];
} // namespace extensions
#endif // EXTENSIONS_COMMON_VIEW_TYPE_H_
| boundarydevices/android_external_chromium_org | extensions/common/view_type.h | C | bsd-3-clause | 1,293 |
//
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#ifndef SAMPLE_UTIL_TGA_UTILS_HPP
#define SAMPLE_UTIL_TGA_UTILS_HPP
#include <GLES2/gl2.h>
#include <array>
#include <vector>
typedef std::array<unsigned char, 4> Byte4;
struct TGAImage
{
size_t width;
size_t height;
std::vector<Byte4> data;
TGAImage();
};
bool LoadTGAImageFromFile(const std::string &path, TGAImage *image);
GLuint LoadTextureFromTGAImage(const TGAImage &image);
#endif // SAMPLE_UTIL_TGA_UTILS_HPP
| sgraham/nope | third_party/angle/samples/angle/sample_util/tga_utils.h | C | bsd-3-clause | 621 |
<header>òÅÄÁËÔÉÒÏ×ÁÎÉÅ çÒÕÐÐÙ</header>
äÁÎÎÁÑ ÆÏÒÍÁ ÐÏÚ×ÏÌÑÅÔ ×ÁÍ ÒÅÄÁËÔÉÒÏ×ÁÔØ ÐÁÒÁÍÅÔÒÙ ÓÕÝÅÓÔ×ÕÀÝÅÊ Unix ÇÒÕÐÐÙ. ÷ÓÅ ÐÁÒÁÍÅÔÒÙ ÇÒÕÐÐÙ ÍÏÖÎÏ ÉÚÍÅÎÉÔØ, ËÒÏÍÅ ÉÍÅÎÉ.
<hr>
| rcuvgd/Webmin22.01.2016 | useradmin/help/edit_group.ru_SU.html | HTML | bsd-3-clause | 173 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/rendering/RenderThemeChromiumFontProvider.h"
#include "core/CSSValueKeywords.h"
#include "platform/fonts/FontDescription.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/WTFString.h"
namespace blink {
// static
void RenderThemeChromiumFontProvider::setDefaultFontSize(int fontSize)
{
s_defaultFontSize = static_cast<float>(fontSize);
}
// static
void RenderThemeChromiumFontProvider::systemFont(CSSValueID valueID, FontDescription& fontDescription)
{
float fontSize = s_defaultFontSize;
switch (valueID) {
case CSSValueWebkitMiniControl:
case CSSValueWebkitSmallControl:
case CSSValueWebkitControl:
// Why 2 points smaller? Because that's what Gecko does. Note that we
// are assuming a 96dpi screen, which is the default that we use on
// Windows.
static const float pointsPerInch = 72.0f;
static const float pixelsPerInch = 96.0f;
fontSize -= (2.0f / pointsPerInch) * pixelsPerInch;
break;
default:
break;
}
fontDescription.firstFamily().setFamily(defaultGUIFont());
fontDescription.setSpecifiedSize(fontSize);
fontDescription.setIsAbsoluteSize(true);
fontDescription.setGenericFamily(FontDescription::NoFamily);
fontDescription.setWeight(FontWeightNormal);
fontDescription.setStyle(FontStyleNormal);
}
} // namespace blink
| temasek/android_external_chromium_org_third_party_WebKit | Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp | C++ | bsd-3-clause | 2,746 |
/******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#ifndef __fw_api_scan_h__
#define __fw_api_scan_h__
#include "fw-api.h"
/* Scan Commands, Responses, Notifications */
/* Masks for iwl_scan_channel.type flags */
#define SCAN_CHANNEL_TYPE_ACTIVE BIT(0)
#define SCAN_CHANNEL_NARROW_BAND BIT(22)
/* Max number of IEs for direct SSID scans in a command */
#define PROBE_OPTION_MAX 20
/**
* struct iwl_scan_channel - entry in REPLY_SCAN_CMD channel table
* @channel: band is selected by iwl_scan_cmd "flags" field
* @tx_gain: gain for analog radio
* @dsp_atten: gain for DSP
* @active_dwell: dwell time for active scan in TU, typically 5-50
* @passive_dwell: dwell time for passive scan in TU, typically 20-500
* @type: type is broken down to these bits:
* bit 0: 0 = passive, 1 = active
* bits 1-20: SSID direct bit map. If any of these bits is set then
* the corresponding SSID IE is transmitted in probe request
* (bit i adds IE in position i to the probe request)
* bit 22: channel width, 0 = regular, 1 = TGj narrow channel
*
* @iteration_count:
* @iteration_interval:
* This struct is used once for each channel in the scan list.
* Each channel can independently select:
* 1) SSID for directed active scans
* 2) Txpower setting (for rate specified within Tx command)
* 3) How long to stay on-channel (behavior may be modified by quiet_time,
* quiet_plcp_th, good_CRC_th)
*
* To avoid uCode errors, make sure the following are true (see comments
* under struct iwl_scan_cmd about max_out_time and quiet_time):
* 1) If using passive_dwell (i.e. passive_dwell != 0):
* active_dwell <= passive_dwell (< max_out_time if max_out_time != 0)
* 2) quiet_time <= active_dwell
* 3) If restricting off-channel time (i.e. max_out_time !=0):
* passive_dwell < max_out_time
* active_dwell < max_out_time
*/
struct iwl_scan_channel {
__le32 type;
__le16 channel;
__le16 iteration_count;
__le32 iteration_interval;
__le16 active_dwell;
__le16 passive_dwell;
} __packed; /* SCAN_CHANNEL_CONTROL_API_S_VER_1 */
/**
* struct iwl_ssid_ie - directed scan network information element
*
* Up to 20 of these may appear in REPLY_SCAN_CMD,
* selected by "type" bit field in struct iwl_scan_channel;
* each channel may select different ssids from among the 20 entries.
* SSID IEs get transmitted in reverse order of entry.
*/
struct iwl_ssid_ie {
u8 id;
u8 len;
u8 ssid[IEEE80211_MAX_SSID_LEN];
} __packed; /* SCAN_DIRECT_SSID_IE_API_S_VER_1 */
/**
* iwl_scan_flags - masks for scan command flags
*@SCAN_FLAGS_PERIODIC_SCAN:
*@SCAN_FLAGS_P2P_PUBLIC_ACTION_FRAME_TX:
*@SCAN_FLAGS_DELAYED_SCAN_LOWBAND:
*@SCAN_FLAGS_DELAYED_SCAN_HIGHBAND:
*@SCAN_FLAGS_FRAGMENTED_SCAN:
*@SCAN_FLAGS_PASSIVE2ACTIVE: use active scan on channels that was active
* in the past hour, even if they are marked as passive.
*/
enum iwl_scan_flags {
SCAN_FLAGS_PERIODIC_SCAN = BIT(0),
SCAN_FLAGS_P2P_PUBLIC_ACTION_FRAME_TX = BIT(1),
SCAN_FLAGS_DELAYED_SCAN_LOWBAND = BIT(2),
SCAN_FLAGS_DELAYED_SCAN_HIGHBAND = BIT(3),
SCAN_FLAGS_FRAGMENTED_SCAN = BIT(4),
SCAN_FLAGS_PASSIVE2ACTIVE = BIT(5),
};
/**
* enum iwl_scan_type - Scan types for scan command
* @SCAN_TYPE_FORCED:
* @SCAN_TYPE_BACKGROUND:
* @SCAN_TYPE_OS:
* @SCAN_TYPE_ROAMING:
* @SCAN_TYPE_ACTION:
* @SCAN_TYPE_DISCOVERY:
* @SCAN_TYPE_DISCOVERY_FORCED:
*/
enum iwl_scan_type {
SCAN_TYPE_FORCED = 0,
SCAN_TYPE_BACKGROUND = 1,
SCAN_TYPE_OS = 2,
SCAN_TYPE_ROAMING = 3,
SCAN_TYPE_ACTION = 4,
SCAN_TYPE_DISCOVERY = 5,
SCAN_TYPE_DISCOVERY_FORCED = 6,
}; /* SCAN_ACTIVITY_TYPE_E_VER_1 */
/* Maximal number of channels to scan */
#define MAX_NUM_SCAN_CHANNELS 0x24
/**
* struct iwl_scan_cmd - scan request command
* ( SCAN_REQUEST_CMD = 0x80 )
* @len: command length in bytes
* @scan_flags: scan flags from SCAN_FLAGS_*
* @channel_count: num of channels in channel list (1 - MAX_NUM_SCAN_CHANNELS)
* @quiet_time: in msecs, dwell this time for active scan on quiet channels
* @quiet_plcp_th: quiet PLCP threshold (channel is quiet if less than
* this number of packets were received (typically 1)
* @passive2active: is auto switching from passive to active during scan allowed
* @rxchain_sel_flags: RXON_RX_CHAIN_*
* @max_out_time: in usecs, max out of serving channel time
* @suspend_time: how long to pause scan when returning to service channel:
* bits 0-19: beacon interal in usecs (suspend before executing)
* bits 20-23: reserved
* bits 24-31: number of beacons (suspend between channels)
* @rxon_flags: RXON_FLG_*
* @filter_flags: RXON_FILTER_*
* @tx_cmd: for active scans (zero for passive), w/o payload,
* no RS so specify TX rate
* @direct_scan: direct scan SSIDs
* @type: one of SCAN_TYPE_*
* @repeats: how many time to repeat the scan
*/
struct iwl_scan_cmd {
__le16 len;
u8 scan_flags;
u8 channel_count;
__le16 quiet_time;
__le16 quiet_plcp_th;
__le16 passive2active;
__le16 rxchain_sel_flags;
__le32 max_out_time;
__le32 suspend_time;
/* RX_ON_FLAGS_API_S_VER_1 */
__le32 rxon_flags;
__le32 filter_flags;
struct iwl_tx_cmd tx_cmd;
struct iwl_ssid_ie direct_scan[PROBE_OPTION_MAX];
__le32 type;
__le32 repeats;
/*
* Probe request frame, followed by channel list.
*
* Size of probe request frame is specified by byte count in tx_cmd.
* Channel list follows immediately after probe request frame.
* Number of channels in list is specified by channel_count.
* Each channel in list is of type:
*
* struct iwl_scan_channel channels[0];
*
* NOTE: Only one band of channels can be scanned per pass. You
* must not mix 2.4GHz channels and 5.2GHz channels, and you must wait
* for one scan to complete (i.e. receive SCAN_COMPLETE_NOTIFICATION)
* before requesting another scan.
*/
u8 data[0];
} __packed; /* SCAN_REQUEST_FIXED_PART_API_S_VER_5 */
/* Response to scan request contains only status with one of these values */
#define SCAN_RESPONSE_OK 0x1
#define SCAN_RESPONSE_ERROR 0x2
/*
* SCAN_ABORT_CMD = 0x81
* When scan abort is requested, the command has no fields except the common
* header. The response contains only a status with one of these values.
*/
#define SCAN_ABORT_POSSIBLE 0x1
#define SCAN_ABORT_IGNORED 0x2 /* no pending scans */
/* TODO: complete documentation */
#define SCAN_OWNER_STATUS 0x1
#define MEASURE_OWNER_STATUS 0x2
/**
* struct iwl_scan_start_notif - notifies start of scan in the device
* ( SCAN_START_NOTIFICATION = 0x82 )
* @tsf_low: TSF timer (lower half) in usecs
* @tsf_high: TSF timer (higher half) in usecs
* @beacon_timer: structured as follows:
* bits 0:19 - beacon interval in usecs
* bits 20:23 - reserved (0)
* bits 24:31 - number of beacons
* @channel: which channel is scanned
* @band: 0 for 5.2 GHz, 1 for 2.4 GHz
* @status: one of *_OWNER_STATUS
*/
struct iwl_scan_start_notif {
__le32 tsf_low;
__le32 tsf_high;
__le32 beacon_timer;
u8 channel;
u8 band;
u8 reserved[2];
__le32 status;
} __packed; /* SCAN_START_NTF_API_S_VER_1 */
/* scan results probe_status first bit indicates success */
#define SCAN_PROBE_STATUS_OK 0
#define SCAN_PROBE_STATUS_TX_FAILED BIT(0)
/* error statuses combined with TX_FAILED */
#define SCAN_PROBE_STATUS_FAIL_TTL BIT(1)
#define SCAN_PROBE_STATUS_FAIL_BT BIT(2)
/* How many statistics are gathered for each channel */
#define SCAN_RESULTS_STATISTICS 1
/**
* enum iwl_scan_complete_status - status codes for scan complete notifications
* @SCAN_COMP_STATUS_OK: scan completed successfully
* @SCAN_COMP_STATUS_ABORT: scan was aborted by user
* @SCAN_COMP_STATUS_ERR_SLEEP: sending null sleep packet failed
* @SCAN_COMP_STATUS_ERR_CHAN_TIMEOUT: timeout before channel is ready
* @SCAN_COMP_STATUS_ERR_PROBE: sending probe request failed
* @SCAN_COMP_STATUS_ERR_WAKEUP: sending null wakeup packet failed
* @SCAN_COMP_STATUS_ERR_ANTENNAS: invalid antennas chosen at scan command
* @SCAN_COMP_STATUS_ERR_INTERNAL: internal error caused scan abort
* @SCAN_COMP_STATUS_ERR_COEX: medium was lost ot WiMax
* @SCAN_COMP_STATUS_P2P_ACTION_OK: P2P public action frame TX was successful
* (not an error!)
* @SCAN_COMP_STATUS_ITERATION_END: indicates end of one repeatition the driver
* asked for
* @SCAN_COMP_STATUS_ERR_ALLOC_TE: scan could not allocate time events
*/
enum iwl_scan_complete_status {
SCAN_COMP_STATUS_OK = 0x1,
SCAN_COMP_STATUS_ABORT = 0x2,
SCAN_COMP_STATUS_ERR_SLEEP = 0x3,
SCAN_COMP_STATUS_ERR_CHAN_TIMEOUT = 0x4,
SCAN_COMP_STATUS_ERR_PROBE = 0x5,
SCAN_COMP_STATUS_ERR_WAKEUP = 0x6,
SCAN_COMP_STATUS_ERR_ANTENNAS = 0x7,
SCAN_COMP_STATUS_ERR_INTERNAL = 0x8,
SCAN_COMP_STATUS_ERR_COEX = 0x9,
SCAN_COMP_STATUS_P2P_ACTION_OK = 0xA,
SCAN_COMP_STATUS_ITERATION_END = 0x0B,
SCAN_COMP_STATUS_ERR_ALLOC_TE = 0x0C,
};
/**
* struct iwl_scan_results_notif - scan results for one channel
* ( SCAN_RESULTS_NOTIFICATION = 0x83 )
* @channel: which channel the results are from
* @band: 0 for 5.2 GHz, 1 for 2.4 GHz
* @probe_status: SCAN_PROBE_STATUS_*, indicates success of probe request
* @num_probe_not_sent: # of request that weren't sent due to not enough time
* @duration: duration spent in channel, in usecs
* @statistics: statistics gathered for this channel
*/
struct iwl_scan_results_notif {
u8 channel;
u8 band;
u8 probe_status;
u8 num_probe_not_sent;
__le32 duration;
__le32 statistics[SCAN_RESULTS_STATISTICS];
} __packed; /* SCAN_RESULT_NTF_API_S_VER_2 */
/**
* struct iwl_scan_complete_notif - notifies end of scanning (all channels)
* ( SCAN_COMPLETE_NOTIFICATION = 0x84 )
* @scanned_channels: number of channels scanned (and number of valid results)
* @status: one of SCAN_COMP_STATUS_*
* @bt_status: BT on/off status
* @last_channel: last channel that was scanned
* @tsf_low: TSF timer (lower half) in usecs
* @tsf_high: TSF timer (higher half) in usecs
* @results: all scan results, only "scanned_channels" of them are valid
*/
struct iwl_scan_complete_notif {
u8 scanned_channels;
u8 status;
u8 bt_status;
u8 last_channel;
__le32 tsf_low;
__le32 tsf_high;
struct iwl_scan_results_notif results[MAX_NUM_SCAN_CHANNELS];
} __packed; /* SCAN_COMPLETE_NTF_API_S_VER_2 */
/* scan offload */
#define IWL_MAX_SCAN_CHANNELS 40
#define IWL_SCAN_MAX_BLACKLIST_LEN 64
#define IWL_SCAN_SHORT_BLACKLIST_LEN 16
#define IWL_SCAN_MAX_PROFILES 11
#define SCAN_OFFLOAD_PROBE_REQ_SIZE 512
/* Default watchdog (in MS) for scheduled scan iteration */
#define IWL_SCHED_SCAN_WATCHDOG cpu_to_le16(15000)
#define IWL_GOOD_CRC_TH_DEFAULT cpu_to_le16(1)
#define CAN_ABORT_STATUS 1
#define IWL_FULL_SCAN_MULTIPLIER 5
#define IWL_FAST_SCHED_SCAN_ITERATIONS 3
enum scan_framework_client {
SCAN_CLIENT_SCHED_SCAN = BIT(0),
SCAN_CLIENT_NETDETECT = BIT(1),
SCAN_CLIENT_ASSET_TRACKING = BIT(2),
};
/**
* struct iwl_scan_offload_cmd - SCAN_REQUEST_FIXED_PART_API_S_VER_6
* @scan_flags: see enum iwl_scan_flags
* @channel_count: channels in channel list
* @quiet_time: dwell time, in milisiconds, on quiet channel
* @quiet_plcp_th: quiet channel num of packets threshold
* @good_CRC_th: passive to active promotion threshold
* @rx_chain: RXON rx chain.
* @max_out_time: max uSec to be out of assoceated channel
* @suspend_time: pause scan this long when returning to service channel
* @flags: RXON flags
* @filter_flags: RXONfilter
* @tx_cmd: tx command for active scan; for 2GHz and for 5GHz.
* @direct_scan: list of SSIDs for directed active scan
* @scan_type: see enum iwl_scan_type.
* @rep_count: repetition count for each scheduled scan iteration.
*/
struct iwl_scan_offload_cmd {
__le16 len;
u8 scan_flags;
u8 channel_count;
__le16 quiet_time;
__le16 quiet_plcp_th;
__le16 good_CRC_th;
__le16 rx_chain;
__le32 max_out_time;
__le32 suspend_time;
/* RX_ON_FLAGS_API_S_VER_1 */
__le32 flags;
__le32 filter_flags;
struct iwl_tx_cmd tx_cmd[2];
/* SCAN_DIRECT_SSID_IE_API_S_VER_1 */
struct iwl_ssid_ie direct_scan[PROBE_OPTION_MAX];
__le32 scan_type;
__le32 rep_count;
} __packed;
enum iwl_scan_offload_channel_flags {
IWL_SCAN_OFFLOAD_CHANNEL_ACTIVE = BIT(0),
IWL_SCAN_OFFLOAD_CHANNEL_NARROW = BIT(22),
IWL_SCAN_OFFLOAD_CHANNEL_FULL = BIT(24),
IWL_SCAN_OFFLOAD_CHANNEL_PARTIAL = BIT(25),
};
/**
* iwl_scan_channel_cfg - SCAN_CHANNEL_CFG_S
* @type: bitmap - see enum iwl_scan_offload_channel_flags.
* 0: passive (0) or active (1) scan.
* 1-20: directed scan to i'th ssid.
* 22: channel width configuation - 1 for narrow.
* 24: full scan.
* 25: partial scan.
* @channel_number: channel number 1-13 etc.
* @iter_count: repetition count for the channel.
* @iter_interval: interval between two innteration on one channel.
* @dwell_time: entry 0 - active scan, entry 1 - passive scan.
*/
struct iwl_scan_channel_cfg {
__le32 type[IWL_MAX_SCAN_CHANNELS];
__le16 channel_number[IWL_MAX_SCAN_CHANNELS];
__le16 iter_count[IWL_MAX_SCAN_CHANNELS];
__le32 iter_interval[IWL_MAX_SCAN_CHANNELS];
u8 dwell_time[IWL_MAX_SCAN_CHANNELS][2];
} __packed;
/**
* iwl_scan_offload_cfg - SCAN_OFFLOAD_CONFIG_API_S
* @scan_cmd: scan command fixed part
* @channel_cfg: scan channel configuration
* @data: probe request frames (one per band)
*/
struct iwl_scan_offload_cfg {
struct iwl_scan_offload_cmd scan_cmd;
struct iwl_scan_channel_cfg channel_cfg;
u8 data[0];
} __packed;
/**
* iwl_scan_offload_blacklist - SCAN_OFFLOAD_BLACKLIST_S
* @ssid: MAC address to filter out
* @reported_rssi: AP rssi reported to the host
* @client_bitmap: clients ignore this entry - enum scan_framework_client
*/
struct iwl_scan_offload_blacklist {
u8 ssid[ETH_ALEN];
u8 reported_rssi;
u8 client_bitmap;
} __packed;
enum iwl_scan_offload_network_type {
IWL_NETWORK_TYPE_BSS = 1,
IWL_NETWORK_TYPE_IBSS = 2,
IWL_NETWORK_TYPE_ANY = 3,
};
enum iwl_scan_offload_band_selection {
IWL_SCAN_OFFLOAD_SELECT_2_4 = 0x4,
IWL_SCAN_OFFLOAD_SELECT_5_2 = 0x8,
IWL_SCAN_OFFLOAD_SELECT_ANY = 0xc,
};
/**
* iwl_scan_offload_profile - SCAN_OFFLOAD_PROFILE_S
* @ssid_index: index to ssid list in fixed part
* @unicast_cipher: encryption olgorithm to match - bitmap
* @aut_alg: authentication olgorithm to match - bitmap
* @network_type: enum iwl_scan_offload_network_type
* @band_selection: enum iwl_scan_offload_band_selection
* @client_bitmap: clients waiting for match - enum scan_framework_client
*/
struct iwl_scan_offload_profile {
u8 ssid_index;
u8 unicast_cipher;
u8 auth_alg;
u8 network_type;
u8 band_selection;
u8 client_bitmap;
u8 reserved[2];
} __packed;
/**
* iwl_scan_offload_profile_cfg - SCAN_OFFLOAD_PROFILES_CFG_API_S_VER_1
* @blaclist: AP list to filter off from scan results
* @profiles: profiles to search for match
* @blacklist_len: length of blacklist
* @num_profiles: num of profiles in the list
* @match_notify: clients waiting for match found notification
* @pass_match: clients waiting for the results
* @active_clients: active clients bitmap - enum scan_framework_client
* @any_beacon_notify: clients waiting for match notification without match
*/
struct iwl_scan_offload_profile_cfg {
struct iwl_scan_offload_profile profiles[IWL_SCAN_MAX_PROFILES];
u8 blacklist_len;
u8 num_profiles;
u8 match_notify;
u8 pass_match;
u8 active_clients;
u8 any_beacon_notify;
u8 reserved[2];
} __packed;
/**
* iwl_scan_offload_schedule - schedule of scan offload
* @delay: delay between iterations, in seconds.
* @iterations: num of scan iterations
* @full_scan_mul: number of partial scans before each full scan
*/
struct iwl_scan_offload_schedule {
u16 delay;
u8 iterations;
u8 full_scan_mul;
} __packed;
/*
* iwl_scan_offload_flags
*
* IWL_SCAN_OFFLOAD_FLAG_PASS_ALL: pass all results - no filtering.
* IWL_SCAN_OFFLOAD_FLAG_CACHED_CHANNEL: add cached channels to partial scan.
* IWL_SCAN_OFFLOAD_FLAG_ENERGY_SCAN: use energy based scan before partial scan
* on A band.
*/
enum iwl_scan_offload_flags {
IWL_SCAN_OFFLOAD_FLAG_PASS_ALL = BIT(0),
IWL_SCAN_OFFLOAD_FLAG_CACHED_CHANNEL = BIT(2),
IWL_SCAN_OFFLOAD_FLAG_ENERGY_SCAN = BIT(3),
};
/**
* iwl_scan_offload_req - scan offload request command
* @flags: bitmap - enum iwl_scan_offload_flags.
* @watchdog: maximum scan duration in TU.
* @delay: delay in seconds before first iteration.
* @schedule_line: scan offload schedule, for fast and regular scan.
*/
struct iwl_scan_offload_req {
__le16 flags;
__le16 watchdog;
__le16 delay;
__le16 reserved;
struct iwl_scan_offload_schedule schedule_line[2];
} __packed;
enum iwl_scan_offload_compleate_status {
IWL_SCAN_OFFLOAD_COMPLETED = 1,
IWL_SCAN_OFFLOAD_ABORTED = 2,
};
/**
* iwl_scan_offload_complete - SCAN_OFFLOAD_COMPLETE_NTF_API_S_VER_1
* @last_schedule_line: last schedule line executed (fast or regular)
* @last_schedule_iteration: last scan iteration executed before scan abort
* @status: enum iwl_scan_offload_compleate_status
*/
struct iwl_scan_offload_complete {
u8 last_schedule_line;
u8 last_schedule_iteration;
u8 status;
u8 reserved;
} __packed;
/**
* iwl_sched_scan_results - SCAN_OFFLOAD_MATCH_FOUND_NTF_API_S_VER_1
* @ssid_bitmap: SSIDs indexes found in this iteration
* @client_bitmap: clients that are active and wait for this notification
*/
struct iwl_sched_scan_results {
__le16 ssid_bitmap;
u8 client_bitmap;
u8 reserved;
};
#endif
| iwinoto/v4l-media_build-devel | media/drivers/net/wireless/iwlwifi/mvm/fw-api-scan.h | C | gpl-2.0 | 20,156 |
import AuthenticatedRoute from 'ghost/routes/authenticated';
import CurrentUserSettings from 'ghost/mixins/current-user-settings';
import styleBody from 'ghost/mixins/style-body';
var AppsRoute = AuthenticatedRoute.extend(styleBody, CurrentUserSettings, {
titleToken: 'Apps',
classNames: ['settings-view-apps'],
beforeModel: function () {
if (!this.get('config.apps')) {
return this.transitionTo('settings.general');
}
return this.get('session.user')
.then(this.transitionAuthor())
.then(this.transitionEditor());
},
model: function () {
return this.store.find('app');
}
});
export default AppsRoute;
| PepijnSenders/whatsontheotherside | core/client/app/routes/settings/apps.js | JavaScript | mit | 699 |
<?php
/**
* @file
* Contains \Drupal\Core\Entity\Query\Sql\Query.
*/
namespace Drupal\Core\Entity\Query\Sql;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Query\QueryBase;
use Drupal\Core\Entity\Query\QueryException;
use Drupal\Core\Entity\Query\QueryInterface;
/**
* The SQL storage entity query class.
*/
class Query extends QueryBase implements QueryInterface {
/**
* The build sql select query.
*
* @var \Drupal\Core\Database\Query\SelectInterface
*/
protected $sqlQuery;
/**
* An array of fields keyed by the field alias.
*
* Each entry correlates to the arguments of
* \Drupal\Core\Database\Query\SelectInterface::addField(), so the first one
* is the table alias, the second one the field and the last one optional the
* field alias.
*
* @var array
*/
protected $sqlFields = array();
/**
* An array of strings added as to the group by, keyed by the string to avoid
* duplicates.
*
* @var array
*/
protected $sqlGroupBy = array();
/**
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Stores the entity manager used by the query.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a query object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param string $conjunction
* - AND: all of the conditions on the query need to match.
* - OR: at least one of the conditions on the query need to match.
* @param \Drupal\Core\Database\Connection $connection
* The database connection to run the query against.
* @param array $namespaces
* List of potential namespaces of the classes belonging to this query.
*/
public function __construct(EntityTypeInterface $entity_type, $conjunction, Connection $connection, array $namespaces) {
parent::__construct($entity_type, $conjunction, $namespaces);
$this->connection = $connection;
}
/**
* Implements \Drupal\Core\Entity\Query\QueryInterface::execute().
*/
public function execute() {
return $this
->prepare()
->compile()
->addSort()
->finish()
->result();
}
/**
* Prepares the basic query with proper metadata/tags and base fields.
*
* @throws \Drupal\Core\Entity\Query\QueryException
* Thrown if the base table does not exists.
*
* @return \Drupal\Core\Entity\Query\Sql\Query
* Returns the called object.
*/
protected function prepare() {
if ($this->allRevisions) {
if (!$base_table = $this->entityType->getRevisionTable()) {
throw new QueryException("No revision table for " . $this->entityTypeId . ", invalid query.");
}
}
else {
if (!$base_table = $this->entityType->getBaseTable()) {
throw new QueryException("No base table for " . $this->entityTypeId . ", invalid query.");
}
}
$simple_query = TRUE;
if ($this->entityType->getDataTable()) {
$simple_query = FALSE;
}
$this->sqlQuery = $this->connection->select($base_table, 'base_table', array('conjunction' => $this->conjunction));
$this->sqlQuery->addMetaData('entity_type', $this->entityTypeId);
$id_field = $this->entityType->getKey('id');
// Add the key field for fetchAllKeyed().
if (!$revision_field = $this->entityType->getKey('revision')) {
// When there is no revision support, the key field is the entity key.
$this->sqlFields["base_table.$id_field"] = array('base_table', $id_field);
// Now add the value column for fetchAllKeyed(). This is always the
// entity id.
$this->sqlFields["base_table.$id_field" . '_1'] = array('base_table', $id_field);
}
else {
// When there is revision support, the key field is the revision key.
$this->sqlFields["base_table.$revision_field"] = array('base_table', $revision_field);
// Now add the value column for fetchAllKeyed(). This is always the
// entity id.
$this->sqlFields["base_table.$id_field"] = array('base_table', $id_field);
}
if ($this->accessCheck) {
$this->sqlQuery->addTag($this->entityTypeId . '_access');
}
$this->sqlQuery->addTag('entity_query');
$this->sqlQuery->addTag('entity_query_' . $this->entityTypeId);
// Add further tags added.
if (isset($this->alterTags)) {
foreach ($this->alterTags as $tag => $value) {
$this->sqlQuery->addTag($tag);
}
}
// Add further metadata added.
if (isset($this->alterMetaData)) {
foreach ($this->alterMetaData as $key => $value) {
$this->sqlQuery->addMetaData($key, $value);
}
}
// This now contains first the table containing entity properties and
// last the entity base table. They might be the same.
$this->sqlQuery->addMetaData('all_revisions', $this->allRevisions);
$this->sqlQuery->addMetaData('simple_query', $simple_query);
return $this;
}
/**
* Compiles the conditions.
*
* @return \Drupal\Core\Entity\Query\Sql\Query
* Returns the called object.
*/
protected function compile() {
$this->condition->compile($this->sqlQuery);
return $this;
}
/**
* Adds the sort to the build query.
*
* @return \Drupal\Core\Entity\Query\Sql\Query
* Returns the called object.
*/
protected function addSort() {
if ($this->count) {
$this->sort = array();
}
// Gather the SQL field aliases first to make sure every field table
// necessary is added. This might change whether the query is simple or
// not. See below for more on simple queries.
$sort = array();
if ($this->sort) {
foreach ($this->sort as $key => $data) {
$sort[$key] = $this->getSqlField($data['field'], $data['langcode']);
}
}
$simple_query = $this->isSimpleQuery();
// If the query is set up for paging either via pager or by range or a
// count is requested, then the correct amount of rows returned is
// important. If the entity has a data table or multiple value fields are
// involved then each revision might appear in several rows and this needs
// a significantly more complex query.
if (!$simple_query) {
// First, GROUP BY revision id (if it has been added) and entity id.
// Now each group contains a single revision of an entity.
foreach ($this->sqlFields as $field) {
$group_by = "$field[0].$field[1]";
$this->sqlGroupBy[$group_by] = $group_by;
}
}
// Now we know whether this is a simple query or not, actually do the
// sorting.
foreach ($sort as $key => $sql_alias) {
$direction = $this->sort[$key]['direction'];
if ($simple_query || isset($this->sqlGroupBy[$sql_alias])) {
// Simple queries, and the grouped columns of complicated queries
// can be ordered normally, without the aggregation function.
$this->sqlQuery->orderBy($sql_alias, $direction);
if (!isset($this->sqlFields[$sql_alias])) {
$this->sqlFields[$sql_alias] = explode('.', $sql_alias);
}
}
else {
// Order based on the smallest element of each group if the
// direction is ascending, or on the largest element of each group
// if the direction is descending.
$function = $direction == 'ASC' ? 'min' : 'max';
$expression = "$function($sql_alias)";
$expression_alias = $this->sqlQuery->addExpression($expression);
$this->sqlQuery->orderBy($expression_alias, $direction);
}
}
return $this;
}
/**
* Finish the query by adding fields, GROUP BY and range.
*
* @return \Drupal\Core\Entity\Query\Sql\Query
* Returns the called object.
*/
protected function finish() {
$this->initializePager();
if ($this->range) {
$this->sqlQuery->range($this->range['start'], $this->range['length']);
}
foreach ($this->sqlGroupBy as $field) {
$this->sqlQuery->groupBy($field);
}
foreach ($this->sqlFields as $field) {
$this->sqlQuery->addField($field[0], $field[1], isset($field[2]) ? $field[2] : NULL);
}
return $this;
}
/**
* Executes the query and returns the result.
*
* @return int|array
* Returns the query result as entity IDs.
*/
protected function result() {
if ($this->count) {
return $this->sqlQuery->countQuery()->execute()->fetchField();
}
// Return a keyed array of results. The key is either the revision_id or
// the entity_id depending on whether the entity type supports revisions.
// The value is always the entity id.
return $this->sqlQuery->execute()->fetchAllKeyed();
}
/**
* Constructs a select expression for a given field and language.
*
* @param string $field
* The name of the field being queried.
* @param string $langcode
* The language code of the field.
*
* @return string
* An expression that will select the given field for the given language in
* a SELECT query, such as 'base_table.id'.
*/
protected function getSqlField($field, $langcode) {
if (!isset($this->tables)) {
$this->tables = $this->getTables($this->sqlQuery);
}
$base_property = "base_table.$field";
if (isset($this->sqlFields[$base_property])) {
return $base_property;
}
else {
return $this->tables->addField($field, 'LEFT', $langcode);
}
}
/**
* Returns whether the query requires GROUP BY and ORDER BY MIN/MAX.
*
* @return bool
*/
protected function isSimpleQuery() {
return (!$this->pager && !$this->range && !$this->count) || $this->sqlQuery->getMetaData('simple_query');
}
/**
* Implements the magic __clone method.
*
* Reset fields and GROUP BY when cloning.
*/
public function __clone() {
parent::__clone();
$this->sqlFields = array();
$this->sqlGroupBy = array();
}
/**
* Gets the Tables object for this query.
*
* @param \Drupal\Core\Database\Query\SelectInterface $sql_query
* The SQL query object being built.
*
* @return \Drupal\Core\Entity\Query\Sql\TablesInterface
* The object that adds tables and fields to the SQL query object.
*/
public function getTables(SelectInterface $sql_query) {
$class = static::getClass($this->namespaces, 'Tables');
return new $class($sql_query);
}
}
| casivaagustin/drupalcon-mentoring | src/core/lib/Drupal/Core/Entity/Query/Sql/Query.php | PHP | mit | 10,521 |
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-hours',
templateUrl: 'hours.html',
})
export class HoursPage {
started: boolean = false;
stopped: boolean = true;
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
}
startstop() {
this.started = !this.started;
this.stopped = !this.stopped;
var date = new Date();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var day = date.getUTCDate();
var hour = date.getHours();
var mins = date.getMinutes();
var time = `${month}/${day}/${year} ${hour}:${mins}`;
var msg = `Time ${this.started ? 'in' : 'out'} ${time}`;
document.getElementById('startstops').innerHTML = "<div class='time'>" + msg + "</div>" + document.getElementById('startstops').innerHTML;
}
}
| HamidMosalla/allReady | AllReadyApp/Mobile-App/src/pages/hours/hours.ts | TypeScript | mit | 944 |
//---------------------------------------------------------------------
// <copyright file="QueryReferenceValue.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.Taupo.Query.Contracts
{
using System;
using System.Linq;
using Microsoft.Test.Taupo.Common;
/// <summary>
/// Result of a query evaluation which is a reference of entity
/// </summary>
public class QueryReferenceValue : QueryValue
{
internal QueryReferenceValue(QueryReferenceType type, QueryError evaluationError, IQueryEvaluationStrategy evaluationStrategy)
: base(evaluationError, evaluationStrategy)
{
ExceptionUtilities.CheckArgumentNotNull(type, "type");
this.Type = type;
}
/// <summary>
/// Gets the reference type.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "Must be the same as the base class.")]
public new QueryReferenceType Type { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is null.
/// </summary>
public override bool IsNull
{
get { return this.KeyValue == null; }
}
/// <summary>
/// Gets the entity value (for dereference)
/// </summary>
/// <remarks>For dangling reference, this should be null value</remarks>
public QueryStructuralValue EntityValue { get; private set; }
/// <summary>
/// Gets the entity set full name
/// </summary>
public string EntitySetFullName { get; private set; }
/// <summary>
/// Gets the key value
/// </summary>
public QueryRecordValue KeyValue { get; private set; }
/// <summary>
/// Casts a <see cref="QueryValue"/> to a <see cref="QueryType"/>. The cast will return the value type cast to the new type.
/// </summary>
/// <param name="type">The type for the cast operation.</param>
/// <returns><see cref="QueryValue"/> which is cast to the appropriate type</returns>
public override QueryValue Cast(QueryType type)
{
return type.CreateErrorValue(new QueryError("Cannot perform Cast on a reference value"));
}
/// <summary>
/// Checks if a <see cref="QueryValue"/> is of a particular <see cref="QueryType"/>. This operation will return a true if the value is of the specified type.
/// </summary>
/// <param name="type">The type for the IsOf operation.</param>
/// <param name="performExactMatch">Determines if an exact match needs to be performed.</param>
/// <returns>A <see cref="QueryValue"/> containing true or false depending on whether the value is of the specified type or not.</returns>
public override QueryValue IsOf(QueryType type, bool performExactMatch)
{
return type.CreateErrorValue(new QueryError("Cannot perform IsOf on a reference value"));
}
/// <summary>
/// Converts the <see cref="QueryValue"/> to a particular <see cref="QueryType"/>.
/// </summary>
/// <param name="type">The type for the As operation.</param>
/// <returns>The <see cref="QueryValue"/> converted to the specified type if successful. Returns null if this operation fails.</returns>
public override QueryValue TreatAs(QueryType type)
{
return type.CreateErrorValue(new QueryError("Cannot perform TreatAs on a reference value"));
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (this.EvaluationError != null)
{
return "Reference Value Error=" + this.EvaluationError + ", Type=" + this.Type.StringRepresentation;
}
else if (this.IsNull)
{
return "Null Reference, Type=" + this.Type.StringRepresentation;
}
else
{
return "Reference Value=" + this.EntitySetFullName + ", keyValue[" + this.KeyValue + "], Type=" + this.Type.StringRepresentation;
}
}
/// <summary>
/// The Accept method used to support the double-dispatch visitor pattern with a visitor that returns a result.
/// </summary>
/// <typeparam name="TResult">The result type returned by the visitor.</typeparam>
/// <param name="visitor">The visitor that is visiting this query value.</param>
/// <returns>The result of visiting this query value.</returns>
public override TResult Accept<TResult>(IQueryValueVisitor<TResult> visitor)
{
return visitor.Visit(this);
}
/// <summary>
/// Gets a <see cref="QueryReferenceValue"/> value indicating whether two values are equal.
/// </summary>
/// <param name="otherValue">The second value.</param>
/// <returns>
/// Instance of <see cref="QueryScalarValue"/> which represents the result of comparison.
/// </returns>
public QueryScalarValue EqualTo(QueryReferenceValue otherValue)
{
if ((this.IsNull && otherValue.IsNull) || object.ReferenceEquals(this.EntityValue, otherValue.EntityValue))
{
return new QueryScalarValue(EvaluationStrategy.BooleanType, true, this.EvaluationError, this.EvaluationStrategy);
}
else
{
return new QueryScalarValue(EvaluationStrategy.BooleanType, false, this.EvaluationError, this.EvaluationStrategy);
}
}
/// <summary>
/// Gets a <see cref="QueryReferenceValue"/> value indicating whether two values are not equal.
/// </summary>
/// <param name="otherValue">The second value.</param>
/// <returns>
/// Instance of <see cref="QueryScalarValue"/> which represents the result of comparison.
/// </returns>
public QueryScalarValue NotEqualTo(QueryReferenceValue otherValue)
{
bool areEqual = (bool)this.EqualTo(otherValue).Value;
return new QueryScalarValue(EvaluationStrategy.BooleanType, !areEqual, this.EvaluationError, this.EvaluationStrategy);
}
internal void SetReferenceValue(QueryStructuralValue entityValue)
{
ExceptionUtilities.CheckArgumentNotNull(entityValue, "entityValue");
this.EntityValue = entityValue;
// compute key value
QueryEntityType entityType = this.Type.QueryEntityType;
var keyType = new QueryRecordType(this.EvaluationStrategy);
keyType.AddProperties(entityType.Properties.Where(m => m.IsPrimaryKey));
this.KeyValue = keyType.CreateNewInstance();
for (int i = 0; i < keyType.Properties.Count; i++)
{
this.KeyValue.SetMemberValue(i, entityValue.GetValue(keyType.Properties[i].Name));
}
var set = entityType.EntitySet;
this.EntitySetFullName = set.Container.Name + "." + set.Name;
}
// this is only heppening when reading from product or creating dangling reference
internal void SetReferenceValue(string entitySetFullName, QueryRecordValue keyValue)
{
ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(entitySetFullName, "entitySetFullName");
ExceptionUtilities.CheckArgumentNotNull(keyValue, "keyValue");
this.EntitySetFullName = entitySetFullName;
this.KeyValue = keyValue;
this.EntityValue = this.Type.QueryEntityType.NullValue;
}
/// <summary>
/// Gets the type of the value.
/// </summary>
/// <returns>Type of the value.</returns>
protected override QueryType GetTypeInternal()
{
return this.Type;
}
}
}
| abkmr/odata.net | test/FunctionalTests/Taupo/Source/Taupo.Query/Contracts/QueryReferenceValue.cs | C# | mit | 8,618 |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.IO.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.IO
{
public enum HandleInheritability
{
None = 0,
Inheritable = 1,
}
}
| ndykman/CodeContracts | Microsoft.Research/Contracts/System.Core/Sources/System.IO.cs | C# | mit | 2,061 |
{% extends "base.html" %}
{% block preTitle %}
{{ project.display_name }} (Build) -
{% endblock %}
{% block bodyclass %}job_view{% endblock %}
{% block extra_head %}
<link rel="stylesheet" href="/styles/plugin-status-compiled.css">
{% endblock %}
{% block bodyContent %}
{% set page = "build" %}
<div class="app ng-cloak" ng-app="job-status">
<script>
var project = {{ project | scriptjson() | raw }};
var jobs = {{ jobs | scriptjson() | raw }};
var job = {{ job | scriptjson() | raw }};
var showStatus = {{ showStatus | scriptjson() | raw }};
var canAdminProject = {{ canAdminProject === true ? 'true' : 'false' }};
</script>
<base href="/{{ page_base }}/"></base>
<div id="build-page" class="main" ng-view></div>
<script id="build-tpl.html" type="text/ng-template">
<div class="span8">
<div class="row-fluid job-page-intro">
<div class="job-title">
{% pluginblock JobPagePreTitle %}{% endpluginblock %}
<h3 class="clearfix">
{% if currentUser %}
<span ng-hide="job.running || job.project.access_level < 1"
ng-click="startDeploy(job)"
title="Retest & Deploy"
class="clickable test-and-deploy-action">
<i class="fa fa-cloud-upload"></i>
</span>
<span ng-hide="job.running || job.project.access_level < 1"
ng-click="startTest(job)"
title="Retest" class="clickable test-only-action">
<i class="fa fa-refresh"></i>
</span>
{% endif %}
<span class='job-repo'>{{ project.display_name }}</span>
<a href="[[ project.display_url ]]" target="_blank">
<i class="fa fa-[[ project.provider.id ]]"></i>
</a>
{% if currentUser %}
<a href="/[[ project.name ]]/config" ng-hide="job.project.access_level < 2" title="Configure" class="btn btn-default pull-right">
<i class="fa fa-wrench"></i> Configure
</a>
{% endif %}
</h3>
{% pluginblock JobPagePostTitle %}{% endpluginblock %}
</div>
</div>
<div class='job-main'>
<div class='row-fluid job-wrap'>
{% pluginblock JobPagePreCols %}
{% endpluginblock %}
<div class='job-left-col'>
<div class="row-fluid [[ job.status ]]" id="build-metadata">
{% include "partials/build_metadata.html" %}
</div>
<div class='row job-pre-console'>
<div class='span12 job-pre-console-inner'>
{% pluginblock JobPagePreConsole %}
{% endpluginblock %}
</div>
</div>
{% for block in statusBlocks.runner %}
<div class="status-{{ loop.key }} plugin-status runner-status {{ block.attrs.class }}"
plugin-status="{{ loop.key }}"{% for val in block.attrs %}{% if loop.key != 'class' %} {{ loop.key }}="{{ val }}"{% endif %}{% endfor %}>
{{ block.html | raw }}
</div>
{% endfor %}
{% if statusBlocks.provider[project.provider.id] %}
<div class="status-{{ loop.key }} plugin-status provider-status {{ block.attrs.class }}"
plugin-status="{{ loop.key }}"{% for val in block.attrs %}{% if loop.key != 'class' %} {{ loop.key }}="{{ val }}"{% endif %}{% endfor %}>
{{ block.html | raw }}
</div>
{% endif %}
{% for block in statusBlocks.job %}
<div class="status-{{ loop.key }} plugin-status job-plugin-status {{ block.attrs.class }}"
plugin-status="{{ loop.key }}"{% for val in block.attrs %}{% if loop.key != 'class' %} {{ loop.key }}="{{ val }}"{% endif %}{% endfor %}>
{{ block.html | raw }}
</div>
{% endfor %}
<div class="build-error" ng-show="job.status === 'errored' && job.error">
<div class="alert alert-error">
<i class="fa fa-exclamation-triangle"></i>
[[ job.error.message ]]
<a href="#" class="pull-right" ng-click="toggleErrorDetails()" ng-if="job.error.stack">
<i class="fa fa-ellipsis-h"></i>
</a>
<pre ng-if="showErrorDetails" ng-show="job.error.stack">[[ job.error.stack ]]</pre>
</div>
</div>
<div class="console-output">
<i class="fa fa-gear fa-light fa-spin loading-icon" ng-show="loading"></i>
{% include "build/console.html" %}
</div>
<div class="footer">
<a href="https://github.com/Strider-CD/strider">Strider-CD <i class="fa fa-github"></i></a>
| <a href="https://github.com/Strider-CD/strider/issues?state=open">Get Help / Report a Bug</a>
| <a href="http://strider.readthedocs.org/en/latest/intro.html">Docs</a>
</div>
</div>
</div>
</div>
</div>
<div class="span4">
<div class='job-detail-sidebar'>
{% include "build/history.html" %}
</div>
</div>
</script>
</div>
{% pluginblock AfterJobPage %}{% endpluginblock %}
{% endblock %}
| yonglehou/strider | lib/views/build.html | HTML | mit | 5,439 |
# Date Field
Stores a `Date` in the model. Input is stripped to only store the Date part (no time).
Internally uses [moment.js](http://momentjs.com/) to manage date parsing, formatting and comparison.
If the `utc` option is set, `moment(value).utc()` is called in all methods to enable moment's utc mode.
String parsing with moment will be done using the `inputFormat` option, which defaults to `"'YYYY-MM-DD'"`.
## Methods
### `format(formatString)`
Formats the stored value using moment, with the provided format string.
`formatString` defaults to the `format` option, which defaults to `"Do MMM YYYY"`.
If no `formatString` is provided and the `format` option is false, the stored value will be returned.
When the stored value is `undefined` an empty string is returned.
### `moment`
Returns a moment instance initialised with the value stored in the item.
### `parse(value, formatString)`
Returns a moment instance initialised with the provided value. `formatString` defaults to the `inputFormat` option.
### `updateItem`
Updates with the provided value if it is different from the stored value.
Uses `this.parse()` to interpret the input as a date.
`null` and `""` can be used to clear the stored value.
### `validateInput`
Ensures the value, if provided, is either a Date object, a number that can be interpreted as epoch time, or a string that can be parsed into a valid date by moment.
Allows `null` and `""` to clear the field value.
### Inherits from [`Text`](../text)
* `validateRequiredInput`
| andreufirefly/keystone | fields/types/date/Readme.md | Markdown | mit | 1,528 |
<http:/
<https:/
<mailto:foobarbaz>
<http:/google
<foo@
| 1000ch/textlint | test/other/fixtures/input/auto-link-invalid.md | Markdown | mit | 61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.