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 |
|---|---|---|---|---|---|
<?php
/**
* @package Joomla.Site
* @subpackage com_newsfeeds
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* HTML View class for the Newsfeeds component
*
* @package Joomla.Site
* @subpackage com_newsfeeds
* @since 1.0
*/
class NewsfeedsViewNewsfeed extends JViewLegacy
{
/**
* @var object
* @since 1.6
*/
protected $state;
/**
* @var object
* @since 1.6
*/
protected $item;
/**
* @var boolean
* @since 1.6
*/
protected $print;
/**
* @since 1.6
*/
public function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get view related request variables.
$print = $app->input->getBool('print');
// Get model data.
$state = $this->get('State');
$item = $this->get('Item');
if ($item)
{
// Get Category Model data
$categoryModel = JModelLegacy::getInstance('Category', 'NewsfeedsModel', array('ignore_request' => true));
$categoryModel->setState('category.id', $item->catid);
$categoryModel->setState('list.ordering', 'a.name');
$categoryModel->setState('list.direction', 'asc');
// TODO: $items is not used. Remove this line?
$items = $categoryModel->getItems();
}
// Check for errors.
// @TODO Maybe this could go into JComponentHelper::raiseErrors($this->get('Errors'))
if (count($errors = $this->get('Errors')))
{
JError::raiseWarning(500, implode("\n", $errors));
return false;
}
// Add router helpers.
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
$item->catslug = $item->category_alias ? ($item->catid . ':' . $item->category_alias) : $item->catid;
$item->parent_slug = $item->category_alias ? ($item->parent_id . ':' . $item->parent_alias) : $item->parent_id;
// check if cache directory is writeable
$cacheDir = JPATH_CACHE . '/';
if (!is_writable($cacheDir))
{
JError::raiseNotice('0', JText::_('COM_NEWSFEEDS_CACHE_DIRECTORY_UNWRITABLE'));
return;
}
// Merge newsfeed params. If this is single-newsfeed view, menu params override newsfeed params
// Otherwise, newsfeed params override menu item params
$params = $state->get('params');
$newsfeed_params = clone $item->params;
$active = $app->getMenu()->getActive();
$temp = clone ($params);
// Check to see which parameters should take priority
if ($active)
{
$currentLink = $active->link;
// If the current view is the active item and an newsfeed view for this feed, then the menu item params take priority
if (strpos($currentLink, 'view=newsfeed') && (strpos($currentLink, '&id='.(string) $item->id)))
{
// $item->params are the newsfeed params, $temp are the menu item params
// Merge so that the menu item params take priority
$newsfeed_params->merge($temp);
$item->params = $newsfeed_params;
// Load layout from active query (in case it is an alternative menu item)
if (isset($active->query['layout']))
{
$this->setLayout($active->query['layout']);
}
}
else
{
// Current view is not a single newsfeed, so the newsfeed params take priority here
// Merge the menu item params with the newsfeed params so that the newsfeed params take priority
$temp->merge($newsfeed_params);
$item->params = $temp;
// Check for alternative layouts (since we are not in a single-newsfeed menu item)
if ($layout = $item->params->get('newsfeed_layout'))
{
$this->setLayout($layout);
}
}
}
else
{
// Merge so that newsfeed params take priority
$temp->merge($newsfeed_params);
$item->params = $temp;
// Check for alternative layouts (since we are not in a single-newsfeed menu item)
if ($layout = $item->params->get('newsfeed_layout'))
{
$this->setLayout($layout);
}
}
// Check the access to the newsfeed
$levels = $user->getAuthorisedViewLevels();
if (!in_array($item->access, $levels) or ((in_array($item->access, $levels) and (!in_array($item->category_access, $levels)))))
{
JError::raiseWarning(403, JText::_('JERROR_ALERTNOAUTHOR'));
return;
}
// Get the current menu item
$params = $app->getParams();
// Get the newsfeed
$newsfeed = $item;
$temp = new JRegistry;
$temp->loadString($item->params);
$params->merge($temp);
try
{
$feed = new JFeedFactory;
$this->rssDoc = $feed->getFeed($newsfeed->link);
}
catch (InvalidArgumentException $e)
{
$msg = JText::_('COM_NEWSFEEDS_ERRORS_FEED_NOT_RETRIEVED');
}
catch (RunTimeException $e)
{
$msg = JText::_('COM_NEWSFEEDS_ERRORS_FEED_NOT_RETRIEVED');
}
if (empty($this->rssDoc))
{
$msg = JText::_('COM_NEWSFEEDS_ERRORS_FEED_NOT_RETRIEVED');
}
$feed_display_order = $params->get('feed_display_order', 'des');
if ($feed_display_order == 'asc')
{
$newsfeed->items = array_reverse($newsfeed->items);
}
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assignRef('params', $params);
$this->assignRef('newsfeed', $newsfeed);
$this->assignRef('state', $state);
$this->assignRef('item', $item);
$this->assignRef('user', $user);
if (!empty($msg))
{
$this->assignRef('msg', $msg);
}
$this->print = $print;
$item->tags = new JHelperTags;
$item->tags->getItemTags('com_newsfeeds.newsfeed', $item->id);
$this->_prepareDocument();
parent::display($tpl);
}
/**
* Prepares the document
*
* @return void
* @since 1.6
*/
protected function _prepareDocument()
{
$app = JFactory::getApplication();
$menus = $app->getMenu();
$pathway = $app->getPathway();
$title = null;
// Because the application sets a default page title,
// we need to get it from the menu item itself
$menu = $menus->getActive();
if ($menu)
{
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
}
else
{
$this->params->def('page_heading', JText::_('COM_NEWSFEEDS_DEFAULT_PAGE_TITLE'));
}
$title = $this->params->get('page_title', '');
$id = (int) @$menu->query['id'];
// if the menu item does not concern this newsfeed
if ($menu && ($menu->query['option'] != 'com_newsfeeds' || $menu->query['view'] != 'newsfeed' || $id != $this->item->id))
{
// If this is not a single newsfeed menu item, set the page title to the newsfeed title
if ($this->item->name)
{
$title = $this->item->name;
}
$path = array(array('title' => $this->item->name, 'link' => ''));
$category = JCategories::getInstance('Newsfeeds')->get($this->item->catid);
while (($menu->query['option'] != 'com_newsfeeds' || $menu->query['view'] == 'newsfeed' || $id != $category->id) && $category->id > 1)
{
$path[] = array('title' => $category->title, 'link' => NewsfeedsHelperRoute::getCategoryRoute($category->id));
$category = $category->getParent();
}
$path = array_reverse($path);
foreach ($path as $item)
{
$pathway->addItem($item['title'], $item['link']);
}
}
if (empty($title))
{
$title = $app->getCfg('sitename');
}
elseif ($app->getCfg('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $title);
}
elseif ($app->getCfg('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->getCfg('sitename'));
}
if (empty($title))
{
$title = $this->item->name;
}
$this->document->setTitle($title);
if ($this->item->metadesc)
{
$this->document->setDescription($this->item->metadesc);
}
elseif (!$this->item->metadesc && $this->params->get('menu-meta_description'))
{
$this->document->setDescription($this->params->get('menu-meta_description'));
}
if ($this->item->metakey)
{
$this->document->setMetadata('keywords', $this->item->metakey);
}
elseif (!$this->item->metakey && $this->params->get('menu-meta_keywords'))
{
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
}
if ($this->params->get('robots'))
{
$this->document->setMetadata('robots', $this->params->get('robots'));
}
if ($app->getCfg('MetaTitle') == '1')
{
$this->document->setMetaData('title', $this->item->name);
}
if ($app->getCfg('MetaAuthor') == '1')
{
$this->document->setMetaData('author', $this->item->author);
}
$mdata = $this->item->metadata->toArray();
foreach ($mdata as $k => $v)
{
if ($v)
{
$this->document->setMetadata($k, $v);
}
}
}
}
| RCBiczok/ArticleRefs | src/test/lib/joomla/3_1_5/components/com_newsfeeds/views/newsfeed/view.html.php | PHP | gpl-3.0 | 8,625 |
// 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.
type an_int = int;
fn cmp(x: Option<an_int>, y: Option<int>) -> bool {
x == y
}
pub fn main() {
assert!(!cmp(Some(3), None));
assert!(!cmp(Some(3), Some(4)));
assert!(cmp(Some(3), Some(3)));
assert!(cmp(None, None));
}
| emk/rust | src/test/run-pass/compare-generic-enums.rs | Rust | apache-2.0 | 708 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai 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/ECL-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.sakaiproject.message.api;
import java.util.Collection;
import java.util.Stack;
import org.sakaiproject.entity.api.AttachmentContainer;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.user.api.User;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <p>
* MessageHeader is the base Interface for a Sakai Message headers. Header fields common to all message service message headers are defined here.
* </p>
*/
public interface MessageHeader extends AttachmentContainer
{
/**
* <p>
* MessageAccess enumerates different access modes for the message: channel-wide or grouped.
* </p>
*/
public class MessageAccess
{
private final String m_id;
private MessageAccess(String id)
{
m_id = id;
}
public String toString()
{
return m_id;
}
static public MessageAccess fromString(String access)
{
// if (PUBLIC.m_id.equals(access)) return PUBLIC;
if (CHANNEL.m_id.equals(access)) return CHANNEL;
if (GROUPED.m_id.equals(access)) return GROUPED;
return null;
}
/** public access to the message: pubview */
// public static final MessageAccess PUBLIC = new MessageAccess("public");
/** channel (site) level access to the message */
public static final MessageAccess CHANNEL = new MessageAccess("channel");
/** grouped access; only members of the getGroup() groups (authorization groups) have access */
public static final MessageAccess GROUPED = new MessageAccess("grouped");
}
/**
* Access the unique (within the channel) message id.
*
* @return The unique (within the channel) message id.
*/
String getId();
/**
* Access the date/time the message was sent to the channel.
*
* @return The date/time the message was sent to the channel.
*/
Time getDate();
/**
* Access the message order of the message was sent to the channel.
*
* @return The message order of the message was sent to the channel.
*/
Integer getMessage_order();
/**
* Access the User who sent the message to the channel.
*
* @return The User who sent the message to the channel.
*/
User getFrom();
/**
* Access the draft status of the message.
*
* @return True if the message is a draft, false if not.
*/
boolean getDraft();
/**
* Access the groups defined for this message.
*
* @return A Collection (String) of group refs (authorization group ids) defined for this message; empty if none are defined.
*/
Collection<String> getGroups();
/**
* Access the groups, as Group objects, defined for this message.
*
* @return A Collection (Group) of group objects defined for this message; empty if none are defined.
*/
Collection<Group> getGroupObjects();
/**
* Access the access mode for the message - how we compute who has access to the message.
*
* @return The MessageAccess access mode for the message.
*/
MessageAccess getAccess();
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
Element toXml(Document doc, Stack stack);
}
| conder/sakai | message/message-api/api/src/java/org/sakaiproject/message/api/MessageHeader.java | Java | apache-2.0 | 4,259 |
cask 'midi-monitor' do
version '1.3.2'
sha256 '1b2f0a2e1892247c3a5c0c9fc48c682dfcbd4e15881a26eeaaf6026c7f61f24c'
url "https://www.snoize.com/MIDIMonitor/MIDIMonitor_#{version.dots_to_underscores}.zip"
appcast 'https://www.snoize.com/MIDIMonitor/MIDIMonitor.xml',
checkpoint: 'eb0ebc4edfa5274c5a051c7753c3bcf924cc75392ec9a69d33176184732a29a5'
name 'MIDI Monitor'
homepage 'https://www.snoize.com/MIDIMonitor/'
depends_on macos: '>= :lion'
app 'MIDI Monitor.app'
uninstall quit: [
'com.snoize.MIDIMonitor',
'com.snoize.MIDIMonitorDriver',
'com.snoize.MIDISpyFramework',
'com.snoize.SnoizeMIDI',
]
zap delete: [
'~/Library/Preferences/com.snoize.MIDIMonitor.plist',
'~/Library/Caches/com.snoize.MIDIMonitor',
'~/Library/Saved Application State/com.snoize.MIDIMonitor.savedState',
]
end
| vitorgalvao/homebrew-cask | Casks/midi-monitor.rb | Ruby | bsd-2-clause | 978 |
---
layout: docs
title: Plugins
permalink: /docs/plugins/
---
Jekyll has a plugin system with hooks that allow you to create custom generated
content specific to your site. You can run custom code for your site without
having to modify the Jekyll source itself.
<div class="note info">
<h5>Plugins on GitHub Pages</h5>
<p>
<a href="http://pages.github.com/">GitHub Pages</a> is powered by Jekyll.
However, all Pages sites are generated using the <code>--safe</code> option
to disable custom plugins for security reasons. Unfortunately, this means
your plugins won’t work if you’re deploying to GitHub Pages.<br><br>
You can still use GitHub Pages to publish your site, but you’ll need to
convert the site locally and push the generated static files to your GitHub
repository instead of the Jekyll source files.
</p>
</div>
## Installing a plugin
You have 3 options for installing plugins:
1. In your site source root, make a `_plugins` directory. Place your plugins
here. Any file ending in `*.rb` inside this directory will be loaded before
Jekyll generates your site.
2. In your `_config.yml` file, add a new array with the key `gems` and the
values of the gem names of the plugins you'd like to use. An example:
gems: [jekyll-test-plugin, jekyll-jsonify, jekyll-assets]
# This will require each of these gems automatically.
3. Add the relevant plugins to a Bundler group in your `Gemfile`. An
example:
group :jekyll_plugins do
gem "my-jekyll-plugin"
end
<div class="note info">
<h5>
<code>_plugins</code>, <code>_config.yml</code> and <code>Gemfile</code>
can be used simultaneously
</h5>
<p>
You may use any of the aforementioned plugin options simultaneously in the
same site if you so choose. Use of one does not restrict the use of the
others.
</p>
</div>
In general, plugins you make will fall into one of four categories:
1. [Generators](#generators)
2. [Converters](#converters)
3. [Commands](#commands)
4. [Tags](#tags)
## Generators
You can create a generator when you need Jekyll to create additional content
based on your own rules.
A generator is a subclass of `Jekyll::Generator` that defines a `generate`
method, which receives an instance of
[`Jekyll::Site`]({{ site.repository }}/blob/master/lib/jekyll/site.rb). The
return value of `generate` is ignored.
Generators run after Jekyll has made an inventory of the existing content, and
before the site is generated. Pages with YAML Front Matters are stored as
instances of
[`Jekyll::Page`]({{ site.repository }}/blob/master/lib/jekyll/page.rb)
and are available via `site.pages`. Static files become instances of
[`Jekyll::StaticFile`]({{ site.repository }}/blob/master/lib/jekyll/static_file.rb)
and are available via `site.static_files`. See
[the Variables documentation page](/docs/variables/) and
[`Jekyll::Site`]({{ site.repository }}/blob/master/lib/jekyll/site.rb)
for more details.
For instance, a generator can inject values computed at build time for template
variables. In the following example the template `reading.html` has two
variables `ongoing` and `done` that we fill in the generator:
{% highlight ruby %}
module Reading
class Generator < Jekyll::Generator
def generate(site)
ongoing, done = Book.all.partition(&:ongoing?)
reading = site.pages.detect {|page| page.name == 'reading.html'}
reading.data['ongoing'] = ongoing
reading.data['done'] = done
end
end
end
{% endhighlight %}
This is a more complex generator that generates new pages:
{% highlight ruby %}
module Jekyll
class CategoryPage < Page
def initialize(site, base, dir, category)
@site = site
@base = base
@dir = dir
@name = 'index.html'
self.process(@name)
self.read_yaml(File.join(base, '_layouts'), 'category_index.html')
self.data['category'] = category
category_title_prefix = site.config['category_title_prefix'] || 'Category: '
self.data['title'] = "#{category_title_prefix}#{category}"
end
end
class CategoryPageGenerator < Generator
safe true
def generate(site)
if site.layouts.key? 'category_index'
dir = site.config['category_dir'] || 'categories'
site.categories.each_key do |category|
site.pages << CategoryPage.new(site, site.source, File.join(dir, category), category)
end
end
end
end
end
{% endhighlight %}
In this example, our generator will create a series of files under the
`categories` directory for each category, listing the posts in each category
using the `category_index.html` layout.
Generators are only required to implement one method:
<div class="mobile-side-scroller">
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p><code>generate</code></p>
</td>
<td>
<p>Generates content as a side-effect.</p>
</td>
</tr>
</tbody>
</table>
</div>
## Converters
If you have a new markup language you’d like to use with your site, you can
include it by implementing your own converter. Both the Markdown and
[Textile](https://github.com/jekyll/jekyll-textile-converter) markup
languages are implemented using this method.
<div class="note info">
<h5>Remember your YAML Front Matter</h5>
<p>
Jekyll will only convert files that have a YAML header at the top, even for
converters you add using a plugin.
</p>
</div>
Below is a converter that will take all posts ending in `.upcase` and process
them using the `UpcaseConverter`:
{% highlight ruby %}
module Jekyll
class UpcaseConverter < Converter
safe true
priority :low
def matches(ext)
ext =~ /^\.upcase$/i
end
def output_ext(ext)
".html"
end
def convert(content)
content.upcase
end
end
end
{% endhighlight %}
Converters should implement at a minimum 3 methods:
<div class="mobile-side-scroller">
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p><code>matches</code></p>
</td>
<td><p>
Does the given extension match this converter’s list of acceptable
extensions? Takes one argument: the file’s extension (including the
dot). Must return <code>true</code> if it matches, <code>false</code>
otherwise.
</p></td>
</tr>
<tr>
<td>
<p><code>output_ext</code></p>
</td>
<td><p>
The extension to be given to the output file (including the dot).
Usually this will be <code>".html"</code>.
</p></td>
</tr>
<tr>
<td>
<p><code>convert</code></p>
</td>
<td><p>
Logic to do the content conversion. Takes one argument: the raw content
of the file (without YAML Front Matter). Must return a String.
</p></td>
</tr>
</tbody>
</table>
</div>
In our example, `UpcaseConverter#matches` checks if our filename extension is
`.upcase`, and will render using the converter if it is. It will call
`UpcaseConverter#convert` to process the content. In our simple converter we’re
simply uppercasing the entire content string. Finally, when it saves the page,
it will do so with a `.html` extension.
## Commands
As of version 2.5.0, Jekyll can be extended with plugins which provide
subcommands for the `jekyll` executable. This is possible by including the
relevant plugins in a `Gemfile` group called `:jekyll_plugins`:
{% highlight ruby %}
group :jekyll_plugins do
gem "my_fancy_jekyll_plugin"
end
{% endhighlight %}
Each `Command` must be a subclass of the `Jekyll::Command` class and must
contain one class method: `init_with_program`. An example:
{% highlight ruby %}
class MyNewCommand < Jekyll::Command
class << self
def init_with_program(prog)
prog.command(:new) do |c|
c.syntax "new [options]"
c.description 'Create a new Jekyll site.'
c.option 'dest', '-d DEST', 'Where the site should go.'
c.action do |args, options|
Jekyll::Site.new_site_at(options['dest'])
end
end
end
end
end
{% endhighlight %}
Commands should implement this single class method:
<div class="mobile-side-scroller">
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p><code>init_with_program</code></p>
</td>
<td><p>
This method accepts one parameter, the
<code><a href="http://github.com/jekyll/mercenary#readme">Mercenary::Program</a></code>
instance, which is the Jekyll program itself. Upon the program,
commands may be created using the above syntax. For more details,
visit the Mercenary repository on GitHub.com.
</p></td>
</tr>
</tbody>
</table>
</div>
## Tags
If you’d like to include custom liquid tags in your site, you can do so by
hooking into the tagging system. Built-in examples added by Jekyll include the
`highlight` and `include` tags. Below is an example of a custom liquid tag that
will output the time the page was rendered:
{% highlight ruby %}
module Jekyll
class RenderTimeTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text
end
def render(context)
"#{@text} #{Time.now}"
end
end
end
Liquid::Template.register_tag('render_time', Jekyll::RenderTimeTag)
{% endhighlight %}
At a minimum, liquid tags must implement:
<div class="mobile-side-scroller">
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p><code>render</code></p>
</td>
<td>
<p>Outputs the content of the tag.</p>
</td>
</tr>
</tbody>
</table>
</div>
You must also register the custom tag with the Liquid template engine as
follows:
{% highlight ruby %}
Liquid::Template.register_tag('render_time', Jekyll::RenderTimeTag)
{% endhighlight %}
In the example above, we can place the following tag anywhere in one of our
pages:
{% highlight ruby %}
{% raw %}
<p>{% render_time page rendered at: %}</p>
{% endraw %}
{% endhighlight %}
And we would get something like this on the page:
{% highlight html %}
<p>page rendered at: Tue June 22 23:38:47 –0500 2010</p>
{% endhighlight %}
### Liquid filters
You can add your own filters to the Liquid template system much like you can
add tags above. Filters are simply modules that export their methods to liquid.
All methods will have to take at least one parameter which represents the input
of the filter. The return value will be the output of the filter.
{% highlight ruby %}
module Jekyll
module AssetFilter
def asset_url(input)
"http://www.example.com/#{input}?#{Time.now.to_i}"
end
end
end
Liquid::Template.register_filter(Jekyll::AssetFilter)
{% endhighlight %}
<div class="note">
<h5>ProTip™: Access the site object using Liquid</h5>
<p>
Jekyll lets you access the <code>site</code> object through the
<code>context.registers</code> feature of Liquid at <code>context.registers[:site]</code>. For example, you can
access the global configuration file <code>_config.yml</code> using
<code>context.registers[:site].config</code>.
</p>
</div>
### Flags
There are two flags to be aware of when writing a plugin:
<div class="mobile-side-scroller">
<table>
<thead>
<tr>
<th>Flag</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p><code>safe</code></p>
</td>
<td>
<p>
A boolean flag that informs Jekyll whether this plugin may be safely
executed in an environment where arbitrary code execution is not
allowed. This is used by GitHub Pages to determine which core plugins
may be used, and which are unsafe to run. If your plugin does not
allow for arbitrary code execution, set this to <code>true</code>.
GitHub Pages still won’t load your plugin, but if you submit it for
inclusion in core, it’s best for this to be correct!
</p>
</td>
</tr>
<tr>
<td>
<p><code>priority</code></p>
</td>
<td>
<p>
This flag determines what order the plugin is loaded in. Valid values
are: <code>:lowest</code>, <code>:low</code>, <code>:normal</code>,
<code>:high</code>, and <code>:highest</code>. Highest priority
matches are applied first, lowest priority are applied last.
</p>
</td>
</tr>
</tbody>
</table>
</div>
To use one of the example plugins above as an illustration, here is how you’d
specify these two flags:
{% highlight ruby %}
module Jekyll
class UpcaseConverter < Converter
safe true
priority :low
...
end
end
{% endhighlight %}
## Hooks
<div class="note unreleased">
<h5>Support for hooks is currently unreleased.</h5>
<p>
In order to use this feature, <a href="/docs/installation/#pre-releases">
install the latest development version of Jekyll</a>.
</p>
</div>
Using hooks, your plugin can exercise fine-grained control over various aspects
of the build process. If your plugin defines any hooks, Jekyll will call them
at pre-defined points.
Hooks are registered to a container and an event name. To register one, you
call Jekyll::Hooks.register, and pass the container, event name, and code to
call whenever the hook is triggered. For example, if you want to execute some
custom functionality every time Jekyll renders a post, you could register a
hook like this:
{% highlight ruby %}
Jekyll::Hooks.register :post, :post_render do |post|
# code to call after Jekyll renders a post
end
{% endhighlight %}
Jekyll provides hooks for <code>:site</code>, <code>:page</code>,
<code>:post</code>, and <code>:document</code>. In all cases, Jekyll calls your
hooks with the container object as the first callback parameter. But in the
case of <code>:pre_render</code>, your hook will also receive a payload hash as
a second parameter which allows you full control over the variables that are
available while rendering.
The complete list of available hooks is below:
<div class="mobile-side-scroller">
<table>
<thead>
<tr>
<th>Container</th>
<th>Event</th>
<th>Called</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p><code>:site</code></p>
</td>
<td>
<p><code>:after_reset</code></p>
</td>
<td>
<p>Just after site reset</p>
</td>
</tr>
<tr>
<td>
<p><code>:site</code></p>
</td>
<td>
<p><code>:pre_render</code></p>
</td>
<td>
<p>Just before rendering the whole site</p>
</td>
</tr>
<tr>
<td>
<p><code>:site</code></p>
</td>
<td>
<p><code>:post_render</code></p>
</td>
<td>
<p>After rendering the whole site, but before writing any files</p>
</td>
</tr>
<tr>
<td>
<p><code>:site</code></p>
</td>
<td>
<p><code>:post_write</code></p>
</td>
<td>
<p>After writing the whole site to disk</p>
</td>
</tr>
<tr>
<td>
<p><code>:page</code></p>
</td>
<td>
<p><code>:post_init</code></p>
</td>
<td>
<p>Whenever a page is initialized</p>
</td>
</tr>
<tr>
<td>
<p><code>:page</code></p>
</td>
<td>
<p><code>:pre_render</code></p>
</td>
<td>
<p>Just before rendering a page</p>
</td>
</tr>
<tr>
<td>
<p><code>:page</code></p>
</td>
<td>
<p><code>:post_render</code></p>
</td>
<td>
<p>After rendering a page, but before writing it to disk</p>
</td>
</tr>
<tr>
<td>
<p><code>:page</code></p>
</td>
<td>
<p><code>:post_write</code></p>
</td>
<td>
<p>After writing a page to disk</p>
</td>
</tr>
<tr>
<td>
<p><code>:post</code></p>
</td>
<td>
<p><code>:post_init</code></p>
</td>
<td>
<p>Whenever a post is initialized</p>
</td>
</tr>
<tr>
<td>
<p><code>:post</code></p>
</td>
<td>
<p><code>:pre_render</code></p>
</td>
<td>
<p>Just before rendering a post</p>
</td>
</tr>
<tr>
<td>
<p><code>:post</code></p>
</td>
<td>
<p><code>:post_render</code></p>
</td>
<td>
<p>After rendering a post, but before writing it to disk</p>
</td>
</tr>
<tr>
<td>
<p><code>:post</code></p>
</td>
<td>
<p><code>:post_write</code></p>
</td>
<td>
<p>After writing a post to disk</p>
</td>
</tr>
<tr>
<td>
<p><code>:document</code></p>
</td>
<td>
<p><code>:pre_render</code></p>
</td>
<td>
<p>Just before rendering a document</p>
</td>
</tr>
<tr>
<td>
<p><code>:document</code></p>
</td>
<td>
<p><code>:post_render</code></p>
</td>
<td>
<p>After rendering a document, but before writing it to disk</p>
</td>
</tr>
<tr>
<td>
<p><code>:document</code></p>
</td>
<td>
<p><code>:post_write</code></p>
</td>
<td>
<p>After writing a document to disk</p>
</td>
</tr>
</tbody>
</table>
</div>
## Available Plugins
You can find a few useful plugins at the following locations:
#### Generators
- [ArchiveGenerator by Ilkka Laukkanen](https://gist.github.com/707909): Uses [this archive page](https://gist.github.com/707020) to generate archives.
- [LESS.js Generator by Andy Fowler](https://gist.github.com/642739): Renders
LESS.js files during generation.
- [Version Reporter by Blake Smith](https://gist.github.com/449491): Creates a version.html file containing the Jekyll version.
- [Sitemap.xml Generator by Michael Levin](https://github.com/kinnetica/jekyll-plugins): Generates a sitemap.xml file by traversing all of the available posts and pages.
- [Full-text search by Pascal Widdershoven](https://github.com/PascalW/jekyll_indextank): Adds full-text search to your Jekyll site with a plugin and a bit of JavaScript.
- [AliasGenerator by Thomas Mango](https://github.com/tsmango/jekyll_alias_generator): Generates redirect pages for posts when an alias is specified in the YAML Front Matter.
- [Pageless Redirect Generator by Nick Quinlan](https://github.com/nquinlan/jekyll-pageless-redirects): Generates redirects based on files in the Jekyll root, with support for htaccess style redirects.
- [RssGenerator by Assaf Gelber](https://github.com/agelber/jekyll-rss): Automatically creates an RSS 2.0 feed from your posts.
- [Monthly archive generator by Shigeya Suzuki](https://github.com/shigeya/jekyll-monthly-archive-plugin): Generator and template which renders monthly archive like MovableType style, based on the work by Ilkka Laukkanen and others above.
- [Category archive generator by Shigeya Suzuki](https://github.com/shigeya/jekyll-category-archive-plugin): Generator and template which renders category archive like MovableType style, based on Monthly archive generator.
- [Emoji for Jekyll](https://github.com/yihangho/emoji-for-jekyll): Seamlessly enable emoji for all posts and pages.
- [Compass integration for Jekyll](https://github.com/mscharley/jekyll-compass): Easily integrate Compass and Sass with your Jekyll website.
- [Pages Directory by Ben Baker-Smith](https://github.com/bbakersmith/jekyll-pages-directory): Defines a `_pages` directory for page files which routes its output relative to the project root.
- [Page Collections by Jeff Kolesky](https://github.com/jeffkole/jekyll-page-collections): Generates collections of pages with functionality that resembles posts.
- [Windows 8.1 Live Tile Generation by Matt Sheehan](https://github.com/sheehamj13/jekyll-live-tiles): Generates Internet Explorer 11 config.xml file and Tile Templates for pinning your site to Windows 8.1.
- [Typescript Generator by Matt Sheehan](https://github.com/sheehamj13/jekyll_ts): Generate Javascript on build from your Typescript.
- [Jekyll::AutolinkEmail by Ivan Tse](https://github.com/ivantsepp/jekyll-autolink_email): Autolink your emails.
- [Jekyll::GitMetadata by Ivan Tse](https://github.com/ivantsepp/jekyll-git_metadata): Expose Git metadata for your templates.
- [Jekyll Http Basic Auth Plugin](https://gist.github.com/snrbrnjna/422a4b7e017192c284b3): Plugin to manage http basic auth for jekyll generated pages and directories.
- [Jekyll Auto Image by Merlos](https://github.com/merlos/jekyll-auto-image): Gets the first image of a post. Useful to list your posts with images or to add [twitter cards](https://dev.twitter.com/cards/overview) to your site.
- [Jekyll Portfolio Generator by Shannon Babincsak](https://github.com/codeinpink/jekyll-portfolio-generator): Generates project pages and computes related projects out of project data files.
- [Jekyll-Umlauts by Arne Gockeln](https://github.com/webchef/jekyll-umlauts): This generator replaces all german umlauts (äöüß) case sensitive with html.
#### Converters
- [Textile converter](https://github.com/jekyll/jekyll-textile-converter): Convert `.textile` files into HTML. Also includes the `textilize` Liquid filter.
- [Slim plugin](https://github.com/slim-template/jekyll-slim): Slim converter and includes for Jekyll with support for Liquid tags.
- [Jade plugin by John Papandriopoulos](https://github.com/snappylabs/jade-jekyll-plugin): Jade converter for Jekyll.
- [HAML plugin by Sam Z](https://gist.github.com/517556): HAML converter for Jekyll.
- [HAML-Sass Converter by Adam Pearson](https://gist.github.com/481456): Simple HAML-Sass converter for Jekyll. [Fork](https://gist.github.com/528642) by Sam X.
- [Sass SCSS Converter by Mark Wolfe](https://gist.github.com/960150): Sass converter which uses the new CSS compatible syntax, based Sam X’s fork above.
- [LESS Converter by Jason Graham](https://gist.github.com/639920): Convert LESS files to CSS.
- [LESS Converter by Josh Brown](https://gist.github.com/760265): Simple LESS converter.
- [Upcase Converter by Blake Smith](https://gist.github.com/449463): An example Jekyll converter.
- [CoffeeScript Converter by phaer](https://gist.github.com/959938): A [CoffeeScript](http://coffeescript.org) to Javascript converter.
- [Markdown References by Olov Lassus](https://github.com/olov/jekyll-references): Keep all your markdown reference-style link definitions in one \_references.md file.
- [Stylus Converter](https://gist.github.com/988201): Convert .styl to .css.
- [ReStructuredText Converter](https://github.com/xdissent/jekyll-rst): Converts ReST documents to HTML with Pygments syntax highlighting.
- [Jekyll-pandoc-plugin](https://github.com/dsanson/jekyll-pandoc-plugin): Use pandoc for rendering markdown.
- [Jekyll-pandoc-multiple-formats](https://github.com/fauno/jekyll-pandoc-multiple-formats) by [edsl](https://github.com/edsl): Use pandoc to generate your site in multiple formats. Supports pandoc’s markdown extensions.
- [Transform Layouts](https://gist.github.com/1472645): Allows HAML layouts (you need a HAML Converter plugin for this to work).
- [Org-mode Converter](https://gist.github.com/abhiyerra/7377603): Org-mode converter for Jekyll.
- [Customized Kramdown Converter](https://github.com/mvdbos/kramdown-with-pygments): Enable Pygments syntax highlighting for Kramdown-parsed fenced code blocks.
- [Bigfootnotes Plugin](https://github.com/TheFox/jekyll-bigfootnotes): Enables big footnotes for Kramdown.
- [AsciiDoc Plugin](https://github.com/asciidoctor/jekyll-asciidoc): AsciiDoc convertor for Jekyll using [Asciidoctor](http://asciidoctor.org/).
#### Filters
- [Truncate HTML](https://github.com/MattHall/truncatehtml) by [Matt Hall](http://codebeef.com): A Jekyll filter that truncates HTML while preserving markup structure.
- [Domain Name Filter by Lawrence Woodman](https://github.com/LawrenceWoodman/domain_name-liquid_filter): Filters the input text so that just the domain name is left.
- [Summarize Filter by Mathieu Arnold](https://gist.github.com/731597): Remove markup after a `<div id="extended">` tag.
- [i18n_filter](https://github.com/gacha/gacha.id.lv/blob/master/_plugins/i18n_filter.rb): Liquid filter to use I18n localization.
- [Smilify](https://github.com/SaswatPadhi/jekyll_smilify) by [SaswatPadhi](https://github.com/SaswatPadhi): Convert text emoticons in your content to themeable smiley pics.
- [Read in X Minutes](https://gist.github.com/zachleat/5792681) by [zachleat](https://github.com/zachleat): Estimates the reading time of a string (for blog post content).
- [Jekyll-timeago](https://github.com/markets/jekyll-timeago): Converts a time value to the time ago in words.
- [pluralize](https://github.com/bdesham/pluralize): Easily combine a number and a word into a grammatically-correct amount like “1 minute” or “2 minute**s**”.
- [reading_time](https://github.com/bdesham/reading_time): Count words and estimate reading time for a piece of text, ignoring HTML elements that are unlikely to contain running text.
- [Table of Content Generator](https://github.com/dafi/jekyll-toc-generator): Generate the HTML code containing a table of content (TOC), the TOC can be customized in many way, for example you can decide which pages can be without TOC.
- [jekyll-humanize](https://github.com/23maverick23/jekyll-humanize): This is a port of the Django app humanize which adds a "human touch" to data. Each method represents a Fluid type filter that can be used in your Jekyll site templates. Given that Jekyll produces static sites, some of the original methods do not make logical sense to port (e.g. naturaltime).
- [Jekyll-Ordinal](https://github.com/PatrickC8t/Jekyll-Ordinal): Jekyll liquid filter to output a date ordinal such as "st", "nd", "rd", or "th".
- [Deprecated articles keeper](https://github.com/kzykbys/JekyllPlugins) by [Kazuya Kobayashi](http://blog.kazuya.co/): A simple Jekyll filter which monitor how old an article is.
- [Jekyll-jalali](https://github.com/mehdisadeghi/jekyll-jalali) by [Mehdi Sadeghi](http://mehdix.ir): A simple Gregorian to Jalali date converter filter.
- [Jekyll Thumbnail Filter](https://github.com/matallo/jekyll-thumbnail-filter): Related posts thumbnail filter.
- [Jekyll-Smartify](https://github.com/pathawks/jekyll-smartify): SmartyPants filter. Make "quotes" “curly”
- [liquid-md5](https://github.com/pathawks/liquid-md5): Returns an MD5 hash. Helpful for generating Gravatars in templates.
#### Tags
- [Asset Path Tag](https://github.com/samrayner/jekyll-asset-path-plugin) by [Sam Rayner](http://www.samrayner.com/): Allows organisation of assets into subdirectories by outputting a path for a given file relative to the current post or page.
- [Delicious Plugin by Christian Hellsten](https://github.com/christianhellsten/jekyll-plugins): Fetches and renders bookmarks from delicious.com.
- [Ultraviolet Plugin by Steve Alex](https://gist.github.com/480380): Jekyll tag for the [Ultraviolet](https://github.com/grosser/ultraviolet) code highligher.
- [Tag Cloud Plugin by Ilkka Laukkanen](https://gist.github.com/710577): Generate a tag cloud that links to tag pages.
- [GIT Tag by Alexandre Girard](https://gist.github.com/730347): Add Git activity inside a list.
- [MathJax Liquid Tags by Jessy Cowan-Sharp](https://gist.github.com/834610): Simple liquid tags for Jekyll that convert inline math and block equations to the appropriate MathJax script tags.
- [Non-JS Gist Tag by Brandon Tilley](https://gist.github.com/1027674) A Liquid tag that embeds Gists and shows code for non-JavaScript enabled browsers and readers.
- [Render Time Tag by Blake Smith](https://gist.github.com/449509): Displays the time a Jekyll page was generated.
- [Status.net/OStatus Tag by phaer](https://gist.github.com/912466): Displays the notices in a given status.net/ostatus feed.
- [Embed.ly client by Robert Böhnke](https://github.com/robb/jekyll-embedly-client): Autogenerate embeds from URLs using oEmbed.
- [Logarithmic Tag Cloud](https://gist.github.com/2290195): Flexible. Logarithmic distribution. Documentation inline.
- [oEmbed Tag by Tammo van Lessen](https://gist.github.com/1455726): Enables easy content embedding (e.g. from YouTube, Flickr, Slideshare) via oEmbed.
- [FlickrSetTag by Thomas Mango](https://github.com/tsmango/jekyll_flickr_set_tag): Generates image galleries from Flickr sets.
- [Tweet Tag by Scott W. Bradley](https://github.com/scottwb/jekyll-tweet-tag): Liquid tag for [Embedded Tweets](https://dev.twitter.com/docs/embedded-tweets) using Twitter’s shortcodes.
- [Jekyll Twitter Plugin](https://github.com/rob-murray/jekyll-twitter-plugin): A Liquid tag plugin that renders Tweets from Twitter API. Currently supports the [oEmbed](https://dev.twitter.com/rest/reference/get/statuses/oembed) API.
- [Jekyll-contentblocks](https://github.com/rustygeldmacher/jekyll-contentblocks): Lets you use Rails-like content_for tags in your templates, for passing content from your posts up to your layouts.
- [Generate YouTube Embed](https://gist.github.com/1805814) by [joelverhagen](https://github.com/joelverhagen): Jekyll plugin which allows you to embed a YouTube video in your page with the YouTube ID. Optionally specify width and height dimensions. Like “oEmbed Tag” but just for YouTube.
- [Jekyll-beastiepress](https://github.com/okeeblow/jekyll-beastiepress): FreeBSD utility tags for Jekyll sites.
- [Jsonball](https://gist.github.com/1895282): Reads json files and produces maps for use in Jekyll files.
- [Bibjekyll](https://github.com/pablooliveira/bibjekyll): Render BibTeX-formatted bibliographies/citations included in posts and pages using bibtex2html.
- [Jekyll-citation](https://github.com/archome/jekyll-citation): Render BibTeX-formatted bibliographies/citations included in posts and pages (pure Ruby).
- [Jekyll Dribbble Set Tag](https://github.com/ericdfields/Jekyll-Dribbble-Set-Tag): Builds Dribbble image galleries from any user.
- [Debbugs](https://gist.github.com/2218470): Allows posting links to Debian BTS easily.
- [Refheap_tag](https://github.com/aburdette/refheap_tag): Liquid tag that allows embedding pastes from [refheap](https://www.refheap.com/).
- [Jekyll-devonly_tag](https://gist.github.com/2403522): A block tag for including markup only during development.
- [JekyllGalleryTag](https://github.com/redwallhp/JekyllGalleryTag) by [redwallhp](https://github.com/redwallhp): Generates thumbnails from a directory of images and displays them in a grid.
- [Youku and Tudou Embed](https://gist.github.com/Yexiaoxing/5891929): Liquid plugin for embedding Youku and Tudou videos.
- [Jekyll-swfobject](https://github.com/sectore/jekyll-swfobject): Liquid plugin for embedding Adobe Flash files (.swf) using [SWFObject](http://code.google.com/p/swfobject/).
- [Jekyll Picture Tag](https://github.com/robwierzbowski/jekyll-picture-tag): Easy responsive images for Jekyll. Based on the proposed [`<picture>`](https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element) element, polyfilled with Scott Jehl’s [Picturefill](https://github.com/scottjehl/picturefill).
- [Jekyll Image Tag](https://github.com/robwierzbowski/jekyll-image-tag): Better images for Jekyll. Save image presets, generate resized images, and add classes, alt text, and other attributes.
- [Ditaa Tag](https://github.com/matze/jekyll-ditaa) by [matze](https://github.com/matze): Renders ASCII diagram art into PNG images and inserts a figure tag.
- [Jekyll Suggested Tweet](https://github.com/davidensinger/jekyll-suggested-tweet) by [David Ensinger](https://github.com/davidensinger/): A Liquid tag for Jekyll that allows for the embedding of suggested tweets via Twitter’s Web Intents API.
- [Jekyll Date Chart](https://github.com/GSI/jekyll_date_chart) by [GSI](https://github.com/GSI): Block that renders date line charts based on textile-formatted tables.
- [Jekyll Image Encode](https://github.com/GSI/jekyll_image_encode) by [GSI](https://github.com/GSI): Tag that renders base64 codes of images fetched from the web.
- [Jekyll Quick Man](https://github.com/GSI/jekyll_quick_man) by [GSI](https://github.com/GSI): Tag that renders pretty links to man page sources on the internet.
- [jekyll-font-awesome](https://gist.github.com/23maverick23/8532525): Quickly and easily add Font Awesome icons to your posts.
- [Lychee Gallery Tag](https://gist.github.com/tobru/9171700) by [tobru](https://github.com/tobru): Include [Lychee](http://lychee.electerious.com/) albums into a post. For an introduction, see [Jekyll meets Lychee - A Liquid Tag plugin](https://tobrunet.ch/articles/jekyll-meets-lychee-a-liquid-tag-plugin/)
- [Image Set/Gallery Tag](https://github.com/callmeed/jekyll-image-set) by [callmeed](https://github.com/callmeed): Renders HTML for an image gallery from a folder in your Jekyll site. Just pass it a folder name and class/tag options.
- [jekyll_figure](https://github.com/lmullen/jekyll_figure): Generate figures and captions with links to the figure in a variety of formats
- [Jekyll Github Sample Tag](https://github.com/bwillis/jekyll-github-sample): A liquid tag to include a sample of a github repo file in your Jekyll site.
- [Jekyll Project Version Tag](https://github.com/rob-murray/jekyll-version-plugin): A Liquid tag plugin that renders a version identifier for your Jekyll site sourced from the git repository containing your code.
- [Piwigo Gallery](https://github.com/AlessandroLorenzi/piwigo_gallery) by [Alessandro Lorenzi](http://www.alorenzi.eu/): Jekyll plugin to generate thumbnails from a Piwigo gallery and display them with a Liquid tag
- [mathml.rb](https://github.com/tmthrgd/jekyll-plugins) by Tom Thorogood: A plugin to convert TeX mathematics into MathML for display.
- [webmention_io.rb](https://github.com/aarongustafson/jekyll-webmention_io) by [Aaron Gustafson](http://aaron-gustafson.com/): A plugin to enable [webmention](http://indiewebcamp.com/webmention) integration using [Webmention.io](http://webmention.io). Includes an optional JavaScript for updating webmentions automatically between publishes and, if available, in realtime using WebSockets.
- [Jekyll 500px Embed](https://github.com/lkorth/jekyll-500px-embed) by Luke Korth. A Liquid tag plugin that embeds [500px](https://500px.com/) photos.
- [inline\_highlight](https://github.com/bdesham/inline_highlight): A tag for inline syntax highlighting.
- [jekyll-mermaid](https://github.com/jasonbellamy/jekyll-mermaid): Simplify the creation of mermaid diagrams and flowcharts in your posts and pages.
- [twa](https://github.com/Ezmyrelda/twa): Twemoji Awesome plugin for Jekyll. Liquid tag allowing you to use twitter emoji in your jekyll pages.
- [jekyll-files](https://github.com/x43x61x69/jekyll-files) by [Zhi-Wei Cai](http://vox.vg/): Output relative path strings and other info regarding specific assets.
- [Fetch remote file content](https://github.com/dimitri-koenig/jekyll-plugins) by [Dimitri König](https://www.dimitrikoenig.net/): Using `remote_file_content` tag you can fetch the content of a remote file and include it as if you would put the content right into your markdown file yourself. Very useful for including code from github repo's to always have a current repo version.
- [jekyll-asciinema](https://github.com/mnuessler/jekyll-asciinema): A tag for embedding asciicasts recorded with [asciinema](https://asciinema.org) in your Jekyll pages.
- [Jekyll-Youtube](https://github.com/dommmel/jekyll-youtube) A Liquid tag that embeds Youtube videos. The default emded markup is responsive but you can also specify your own by using an include/partial.
#### Collections
- [Jekyll Plugins by Recursive Design](https://github.com/recurser/jekyll-plugins): Plugins to generate Project pages from GitHub readmes, a Category page, and a Sitemap generator.
- [Company website and blog plugins](https://github.com/flatterline/jekyll-plugins) by Flatterline, a [Ruby on Rails development company](http://flatterline.com/): Portfolio/project page generator, team/individual page generator, an author bio liquid tag for use on posts, and a few other smaller plugins.
- [Jekyll plugins by Aucor](https://github.com/aucor/jekyll-plugins): Plugins for trimming unwanted newlines/whitespace and sorting pages by weight attribute.
#### Other
- [ditaa-ditaa](https://github.com/tmthrgd/ditaa-ditaa) by Tom Thorogood: a drastic revision of jekyll-ditaa that renders diagrams drawn using ASCII art into PNG images.
- [Pygments Cache Path by Raimonds Simanovskis](https://github.com/rsim/blog.rayapps.com/blob/master/_plugins/pygments_cache_patch.rb): Plugin to cache syntax-highlighted code from Pygments.
- [Draft/Publish Plugin by Michael Ivey](https://gist.github.com/49630): Save posts as drafts.
- [Growl Notification Generator by Tate Johnson](https://gist.github.com/490101): Send Jekyll notifications to Growl.
- [Growl Notification Hook by Tate Johnson](https://gist.github.com/525267): Better alternative to the above, but requires his “hook” fork.
- [Related Posts by Lawrence Woodman](https://github.com/LawrenceWoodman/related_posts-jekyll_plugin): Overrides `site.related_posts` to use categories to assess relationship.
- [Tiered Archives by Eli Naeher](https://gist.github.com/88cda643aa7e3b0ca1e5): Create tiered template variable that allows you to group archives by year and month.
- [Jekyll-localization](https://github.com/blackwinter/jekyll-localization): Jekyll plugin that adds localization features to the rendering engine.
- [Jekyll-rendering](https://github.com/blackwinter/jekyll-rendering): Jekyll plugin to provide alternative rendering engines.
- [Jekyll-pagination](https://github.com/blackwinter/jekyll-pagination): Jekyll plugin to extend the pagination generator.
- [Jekyll-tagging](https://github.com/pattex/jekyll-tagging): Jekyll plugin to automatically generate a tag cloud and tag pages.
- [Jekyll-scholar](https://github.com/inukshuk/jekyll-scholar): Jekyll extensions for the blogging scholar.
- [Jekyll-asset_bundler](https://github.com/moshen/jekyll-asset_bundler): Bundles and minifies JavaScript and CSS.
- [Jekyll-assets](http://ixti.net/jekyll-assets/) by [ixti](https://github.com/ixti): Rails-alike assets pipeline (write assets in CoffeeScript, Sass, LESS etc; specify dependencies for automatic bundling using simple declarative comments in assets; minify and compress; use JST templates; cache bust; and many-many more).
- [JAPR](https://github.com/kitsched/japr): Jekyll Asset Pipeline Reborn - Powerful asset pipeline for Jekyll that collects, converts and compresses JavaScript and CSS assets.
- [File compressor](https://gist.github.com/2758691) by [mytharcher](https://github.com/mytharcher): Compress HTML and JavaScript files on site build.
- [Jekyll-minibundle](https://github.com/tkareine/jekyll-minibundle): Asset bundling and cache busting using external minification tool of your choice. No gem dependencies.
- [Singlepage-jekyll](https://github.com/JCB-K/singlepage-jekyll) by [JCB-K](https://github.com/JCB-K): Turns Jekyll into a dynamic one-page website.
- [generator-jekyllrb](https://github.com/robwierzbowski/generator-jekyllrb): A generator that wraps Jekyll in [Yeoman](http://yeoman.io/), a tool collection and workflow for builing modern web apps.
- [grunt-jekyll](https://github.com/dannygarcia/grunt-jekyll): A straightforward [Grunt](http://gruntjs.com/) plugin for Jekyll.
- [jekyll-postfiles](https://github.com/indirect/jekyll-postfiles): Add `_postfiles` directory and {% raw %}`{{ postfile }}`{% endraw %} tag so the files a post refers to will always be right there inside your repo.
- [A layout that compresses HTML](http://jch.penibelst.de/): Github Pages compatible, configurable way to compress HTML files on site build.
- [Jekyll CO₂](https://github.com/wdenton/jekyll-co2): Generates HTML showing the monthly change in atmospheric CO₂ at the Mauna Loa observatory in Hawaii.
- [remote-include](http://www.northfieldx.co.uk/remote-include/): Includes files using remote URLs
- [jekyll-minifier](https://github.com/digitalsparky/jekyll-minifier): Minifies HTML, XML, CSS, and Javascript both inline and as separate files utilising yui-compressor and htmlcompressor.
- [Jekyll views router](https://bitbucket.org/nyufac/jekyll-views-router): Simple router between generator plugins and templates.
#### Editors
- [sublime-jekyll](https://github.com/23maverick23/sublime-jekyll): A Sublime Text package for Jekyll static sites. This package should help creating Jekyll sites and posts easier by providing access to key template tags and filters, as well as common completions and a current date/datetime command (for dating posts). You can install this package manually via GitHub, or via [Package Control](https://packagecontrol.io/packages/Jekyll).
- [vim-jekyll](https://github.com/parkr/vim-jekyll): A vim plugin to generate
new posts and run `jekyll build` all without leaving vim.
- [markdown-writer](https://atom.io/packages/markdown-writer): An Atom package for Jekyll. It can create new posts/drafts, manage tags/categories, insert link/images and add many useful key mappings.
<div class="note info">
<h5>Jekyll Plugins Wanted</h5>
<p>
If you have a Jekyll plugin that you would like to see added to this list,
you should <a href="../contributing/">read the contributing page</a> to find
out how to make that happen.
</p>
</div>
| desidude03/jekyll | site/_docs/plugins.md | Markdown | mit | 41,890 |
// #docregion
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'hero-di',
template: `<h1>Hero: {{name}}</h1>`
})
export class HeroComponent {
name = '';
constructor(dataService: DataService) {
this.name = dataService.getHeroName();
}
}
// #enddocregion
| juleskremer/angular.io | public/docs/_examples/cb-ts-to-js/ts/src/app/hero-di.component.ts | TypeScript | mit | 333 |
#!/bin/zsh
# WARP
# ====
# oh-my-zsh plugin
#
# @github.com/mfaerevaag/wd
wd() {
. $ZSH/plugins/wd/wd.sh
}
| jjsanchez/oh-my-zsh | plugins/wd/wd.plugin.zsh | Shell | mit | 113 |
import css from './source.css';
__export__ = css;
export default css;
| webpack-contrib/css-loader | test/fixtures/postcss-present-env/source.js | JavaScript | mit | 72 |
require 'rails_helper'
require_dependency 'version'
describe Admin::VersionsController do
before do
Jobs::VersionCheck.any_instance.stubs(:execute).returns(true)
DiscourseUpdates.stubs(:updated_at).returns(2.hours.ago)
DiscourseUpdates.stubs(:latest_version).returns('1.2.33')
DiscourseUpdates.stubs(:critical_updates_available?).returns(false)
end
it "is a subclass of AdminController" do
expect(Admin::VersionsController < Admin::AdminController).to eq(true)
end
context 'while logged in as an admin' do
before do
@user = log_in(:admin)
end
describe 'show' do
subject { xhr :get, :show }
it { is_expected.to be_success }
it 'should return the currently available version' do
json = JSON.parse(subject.body)
expect(json['latest_version']).to eq('1.2.33')
end
it "should return the installed version" do
json = JSON.parse(subject.body)
expect(json['installed_version']).to eq(Discourse::VERSION::STRING)
end
end
end
end
| gsambrotta/discourse | spec/controllers/admin/versions_controller_spec.rb | Ruby | gpl-2.0 | 1,049 |
package fpinscala.testing.exhaustive
import language.implicitConversions
import language.postfixOps
/*
This source file contains the answers to the last two exercises in the section
"Test Case Minimization" of chapter 8 on property-based testing.
The Gen data type in this file incorporates exhaustive checking of finite domains.
*/
import fpinscala.laziness.{Stream,Cons,Empty}
import fpinscala.state._
import fpinscala.parallelism._
import fpinscala.parallelism.Par.Par
import Gen._
import Prop._
import Status._
import java.util.concurrent.{Executors,ExecutorService}
case class Prop(run: (MaxSize,TestCases,RNG) => Result) {
def &&(p: Prop) = Prop {
(max,n,rng) => run(max,n,rng) match {
case Right((a,n)) => p.run(max,n,rng).right.map { case (s,m) => (s,n+m) }
case l => l
}
}
def ||(p: Prop) = Prop {
(max,n,rng) => run(max,n,rng) match {
case Left(msg) => p.tag(msg).run(max,n,rng)
case r => r
}
}
/* This is rather simplistic - in the event of failure, we simply prepend
* the given message on a newline in front of the existing message.
*/
def tag(msg: String) = Prop {
(max,n,rng) => run(max,n,rng) match {
case Left(e) => Left(msg + "\n" + e)
case r => r
}
}
}
object Prop {
type TestCases = Int
type MaxSize = Int
type FailedCase = String
type Result = Either[FailedCase,(Status,TestCases)]
def forAll[A](a: Gen[A])(f: A => Boolean): Prop = Prop {
(n,rng) => {
def go(i: Int, j: Int, s: Stream[Option[A]], onEnd: Int => Result): Result =
if (i == j) Right((Unfalsified, i))
else s match {
case Cons(h,t) => h() match {
case Some(h) =>
try {
if (f(h)) go(i+1,j,t(),onEnd)
else Left(h.toString) }
catch { case e: Exception => Left(buildMsg(h, e)) }
case None => Right((Unfalsified,i))
}
case _ => onEnd(i)
}
go(0, n/3, a.exhaustive, i => Right((Proven, i))) match {
case Right((Unfalsified,_)) =>
val rands = randomStream(a)(rng).map(Some(_))
go(n/3, n, rands, i => Right((Unfalsified, i)))
case s => s // If proven or failed, stop immediately
}
}
}
def buildMsg[A](s: A, e: Exception): String =
"test case: " + s + "\n" +
"generated an exception: " + e.getMessage + "\n" +
"stack trace:\n" + e.getStackTrace.mkString("\n")
def apply(f: (TestCases,RNG) => Result): Prop =
Prop { (_,n,rng) => f(n,rng) }
/* We pattern match on the `SGen`, and delegate to our `Gen` version of `forAll`
* if `g` is unsized; otherwise, we call the sized version of `forAll` (below).
*/
def forAll[A](g: SGen[A])(f: A => Boolean): Prop = g match {
case Unsized(g2) => forAll(g2)(f)
case Sized(gs) => forAll(gs)(f)
}
/* The sized case of `forAll` is as before, though we convert from `Proven` to
* `Exhausted`. A sized generator can never be proven, since there are always
* larger-sized tests that were not run which may have failed.
*/
def forAll[A](g: Int => Gen[A])(f: A => Boolean): Prop = Prop {
(max,n,rng) =>
val casesPerSize = n / max + 1
val props: List[Prop] =
Stream.from(0).take(max+1).map(i => forAll(g(i))(f)).toList
val p: Prop = props.map(p => Prop((max,n,rng) => p.run(max,casesPerSize,rng))).
reduceLeft(_ && _)
p.run(max,n,rng).right.map {
case (Proven,n) => (Exhausted,n)
case x => x
}
}
def run(p: Prop,
maxSize: Int = 100, // A default argument of `200`
testCases: Int = 100,
rng: RNG = RNG.Simple(System.currentTimeMillis)): Unit = {
p.run(maxSize, testCases, rng) match {
case Left(msg) => println("! test failed:\n" + msg)
case Right((Unfalsified,n)) =>
println("+ property unfalsified, ran " + n + " tests")
case Right((Proven,n)) =>
println("+ property proven, ran " + n + " tests")
case Right((Exhausted,n)) =>
println("+ property unfalsified up to max size, ran " +
n + " tests")
}
}
val ES: ExecutorService = Executors.newCachedThreadPool
val p1 = Prop.forAll(Gen.unit(Par.unit(1)))(i =>
Par.map(i)(_ + 1)(ES).get == Par.unit(2)(ES).get)
def check(p: => Boolean): Prop = // Note that we are non-strict here
forAll(unit(()))(_ => p)
val p2 = check {
val p = Par.map(Par.unit(1))(_ + 1)
val p2 = Par.unit(2)
p(ES).get == p2(ES).get
}
def equal[A](p: Par[A], p2: Par[A]): Par[Boolean] =
Par.map2(p,p2)(_ == _)
val p3 = check {
equal (
Par.map(Par.unit(1))(_ + 1),
Par.unit(2)
) (ES) get
}
val S = weighted(
choose(1,4).map(Executors.newFixedThreadPool) -> .75,
unit(Executors.newCachedThreadPool) -> .25) // `a -> b` is syntax sugar for `(a,b)`
def forAllPar[A](g: Gen[A])(f: A => Par[Boolean]): Prop =
forAll(S.map2(g)((_,_))) { case (s,a) => f(a)(s).get }
def checkPar(p: Par[Boolean]): Prop =
forAllPar(Gen.unit(()))(_ => p)
def forAllPar2[A](g: Gen[A])(f: A => Par[Boolean]): Prop =
forAll(S ** g) { case (s,a) => f(a)(s).get }
def forAllPar3[A](g: Gen[A])(f: A => Par[Boolean]): Prop =
forAll(S ** g) { case s ** a => f(a)(s).get }
val pint = Gen.choose(0,10) map (Par.unit(_))
val p4 =
forAllPar(pint)(n => equal(Par.map(n)(y => y), n))
val forkProp = Prop.forAllPar(pint2)(i => equal(Par.fork(i), i)) tag "fork"
}
sealed trait Status {}
object Status {
case object Exhausted extends Status
case object Proven extends Status
case object Unfalsified extends Status
}
/*
The `Gen` type now has a random generator as well as an exhaustive stream.
Infinite domains will simply generate infinite streams of None.
A finite domain is exhausted when the stream reaches empty.
*/
case class Gen[+A](sample: State[RNG,A], exhaustive: Stream[Option[A]]) {
def map[B](f: A => B): Gen[B] =
Gen(sample.map(f), exhaustive.map(_.map(f)))
def map2[B,C](g: Gen[B])(f: (A,B) => C): Gen[C] =
Gen(sample.map2(g.sample)(f),
map2Stream(exhaustive,g.exhaustive)(map2Option(_,_)(f)))
def flatMap[B](f: A => Gen[B]): Gen[B] =
Gen(sample.flatMap(a => f(a).sample),
exhaustive.flatMap {
case None => unbounded
case Some(a) => f(a).exhaustive
})
/* A method alias for the function we wrote earlier. */
def listOfN(size: Int): Gen[List[A]] =
Gen.listOfN(size, this)
/* A version of `listOfN` that generates the size to use dynamically. */
def listOfN(size: Gen[Int]): Gen[List[A]] =
size flatMap (n => this.listOfN(n))
def listOf: SGen[List[A]] = Gen.listOf(this)
def listOf1: SGen[List[A]] = Gen.listOf1(this)
def unsized = Unsized(this)
def **[B](g: Gen[B]): Gen[(A,B)] =
(this map2 g)((_,_))
}
object Gen {
type Domain[+A] = Stream[Option[A]]
def bounded[A](a: Stream[A]): Domain[A] = a map (Some(_))
def unbounded: Domain[Nothing] = Stream(None)
def unit[A](a: => A): Gen[A] =
Gen(State.unit(a), bounded(Stream(a)))
def boolean: Gen[Boolean] =
Gen(State(RNG.boolean), bounded(Stream(true,false)))
def choose(start: Int, stopExclusive: Int): Gen[Int] =
Gen(State(RNG.nonNegativeInt).map(n => start + n % (stopExclusive-start)),
bounded(Stream.from(start).take(stopExclusive-start)))
/* This implementation is rather tricky, but almost impossible to get wrong
* if you follow the types. It relies on several helper functions (see below).
*/
def listOfN[A](n: Int, g: Gen[A]): Gen[List[A]] =
Gen(State.sequence(List.fill(n)(g.sample)),
cartesian(Stream.constant(g.exhaustive).take(n)).
map(l => sequenceOption(l.toList)))
/* `cartesian` generates all possible combinations of a `Stream[Stream[A]]`. For instance:
*
* cartesian(Stream(Stream(1,2), Stream(3), Stream(4,5))) ==
* Stream(Stream(1,3,4), Stream(1,3,5), Stream(2,3,4), Stream(2,3,5))
*/
def cartesian[A](s: Stream[Stream[A]]): Stream[Stream[A]] =
s.foldRight(Stream(Stream[A]()))((hs,ts) => map2Stream(hs,ts)(Stream.cons(_,_)))
/* `map2Option` and `map2Stream`. Notice the duplication! */
def map2Option[A,B,C](oa: Option[A], ob: Option[B])(f: (A,B) => C): Option[C] =
for { a <- oa; b <- ob } yield f(a,b)
/* This is not the same as `zipWith`, a function we've implemented before.
* We are generating all (A,B) combinations and using each to produce a `C`.
* This implementation desugars to sa.flatMap(a => sb.map(b => f(a,b))).
*/
def map2Stream[A,B,C](sa: Stream[A], sb: => Stream[B])(f: (A,=>B) => C): Stream[C] =
for { a <- sa; b <- sb } yield f(a,b)
/* This is a function we've implemented before. Unfortunately, it does not
* exist in the standard library. This implementation is uses a foldLeft,
* followed by a reverse, which is equivalent to a foldRight, but does not
* use any stack space.
*/
def sequenceOption[A](o: List[Option[A]]): Option[List[A]] =
o.foldLeft[Option[List[A]]](Some(List()))(
(t,h) => map2Option(h,t)(_ :: _)).map(_.reverse)
/* Notice we are using the `unbounded` definition here, which is just
* `Stream(None)` in our current representation of `exhaustive`.
*/
def uniform: Gen[Double] =
Gen(State(RNG.double), unbounded)
def choose(i: Double, j: Double): Gen[Double] =
Gen(State(RNG.double).map(d => i + d*(j-i)), unbounded)
/* Basic idea is add 1 to the result of `choose` if it is of the wrong
* parity, but we require some special handling to deal with the maximum
* integer in the range.
*/
def even(start: Int, stopExclusive: Int): Gen[Int] =
choose(start, if (stopExclusive%2 == 0) stopExclusive - 1 else stopExclusive).
map (n => if (n%2 != 0) n+1 else n)
def odd(start: Int, stopExclusive: Int): Gen[Int] =
choose(start, if (stopExclusive%2 != 0) stopExclusive - 1 else stopExclusive).
map (n => if (n%2 == 0) n+1 else n)
def sameParity(from: Int, to: Int): Gen[(Int,Int)] = for {
i <- choose(from,to)
j <- if (i%2 == 0) even(from,to) else odd(from,to)
} yield (i,j)
def listOfN_1[A](n: Int, g: Gen[A]): Gen[List[A]] =
List.fill(n)(g).foldRight(unit(List[A]()))((a,b) => a.map2(b)(_ :: _))
/* The simplest possible implementation. This will put all elements of one
* `Gen` before the other in the exhaustive traversal. It might be nice to
* interleave the two streams, so we get a more representative sample if we
* don't get to examine the entire exhaustive stream.
*/
def union_1[A](g1: Gen[A], g2: Gen[A]): Gen[A] =
boolean.flatMap(b => if (b) g1 else g2)
def union[A](g1: Gen[A], g2: Gen[A]): Gen[A] =
Gen(
State(RNG.boolean).flatMap(b => if (b) g1.sample else g2.sample),
interleave(g1.exhaustive, g2.exhaustive)
)
def interleave[A](s1: Stream[A], s2: Stream[A]): Stream[A] =
s1.zipAll(s2).flatMap { case (a,a2) => Stream((a.toList ++ a2.toList): _*) }
/* The random case is simple - we generate a double and use this to choose between
* the two random samplers. The exhaustive case is trickier if we want to try
* to produce a stream that does a weighted interleave of the two exhaustive streams.
*/
def weighted[A](g1: (Gen[A],Double), g2: (Gen[A],Double)): Gen[A] = {
/* The probability we should pull from `g1`. */
val g1Threshold = g1._2.abs / (g1._2.abs + g2._2.abs)
/* Some random booleans to use for selecting between g1 and g2 in the exhaustive case.
* Making up a seed locally is fine here, since we just want a deterministic schedule
* with the right distribution. */
def bools: Stream[Boolean] =
randomStream(uniform.map(_ < g1Threshold))(RNG.Simple(302837L))
Gen(State(RNG.double).flatMap(d => if (d < g1Threshold) g1._1.sample else g2._1.sample),
interleave(bools, g1._1.exhaustive, g2._1.exhaustive))
}
/* Produce an infinite random stream from a `Gen` and a starting `RNG`. */
def randomStream[A](g: Gen[A])(rng: RNG): Stream[A] =
Stream.unfold(rng)(rng => Some(g.sample.run(rng)))
/* Interleave the two streams, using `b` to control which stream to pull from at each step.
* A value of `true` attempts to pull from `s1`; `false` attempts to pull from `s1`.
* When either stream is exhausted, insert all remaining elements from the other stream.
*/
def interleave[A](b: Stream[Boolean], s1: Stream[A], s2: Stream[A]): Stream[A] =
b.headOption map { hd =>
if (hd) s1 match {
case Cons(h, t) => Stream.cons(h(), interleave(b drop 1, t(), s2))
case _ => s2
}
else s2 match {
case Cons(h, t) => Stream.cons(h(), interleave(b drop 1, s1, t()))
case _ => s1
}
} getOrElse Stream.empty
def listOf[A](g: Gen[A]): SGen[List[A]] =
Sized(n => g.listOfN(n))
/* Not the most efficient implementation, but it's simple.
* This generates ASCII strings.
*/
def stringN(n: Int): Gen[String] =
listOfN(n, choose(0,127)).map(_.map(_.toChar).mkString)
def string: SGen[String] = Sized(stringN)
case class Sized[+A](forSize: Int => Gen[A]) extends SGen[A]
case class Unsized[+A](get: Gen[A]) extends SGen[A]
implicit def unsized[A](g: Gen[A]): SGen[A] = Unsized(g)
val smallInt = Gen.choose(-10,10)
val maxProp = forAll(listOf(smallInt)) { l =>
val max = l.max
!l.exists(_ > max) // No value greater than `max` should exist in `l`
}
def listOf1[A](g: Gen[A]): SGen[List[A]] =
Sized(n => g.listOfN(n max 1))
val maxProp1 = forAll(listOf1(smallInt)) { l =>
val max = l.max
!l.exists(_ > max) // No value greater than `max` should exist in `l`
}
val sortedProp = forAll(listOf(smallInt)) { l =>
val ls = l.sorted
l.isEmpty || ls.tail.isEmpty || !l.zip(ls.tail).exists { case (a,b) => a > b }
}
object ** {
def unapply[A,B](p: (A,B)) = Some(p)
}
/* A `Gen[Par[Int]]` generated from a list summation that spawns a new parallel
* computation for each element of the input list summed to produce the final
* result. This is not the most compelling example, but it provides at least some
* variation in structure to use for testing.
*/
lazy val pint2: Gen[Par[Int]] = choose(-100,100).listOfN(choose(0,20)).map(l =>
l.foldLeft(Par.unit(0))((p,i) =>
Par.fork { Par.map2(p, Par.unit(i))(_ + _) }))
def genStringIntFn(g: Gen[Int]): Gen[String => Int] =
g map (i => (s => i))
}
trait SGen[+A] {
def map[B](f: A => B): SGen[B] = this match {
case Sized(g) => Sized(g andThen (_ map f))
case Unsized(g) => Unsized(g map f)
}
def flatMap[B](f: A => Gen[B]): SGen[B] = this match {
case Sized(g) => Sized(g andThen (_ flatMap f))
case Unsized(g) => Unsized(g flatMap f)
}
def **[B](s2: SGen[B]): SGen[(A,B)] = (this,s2) match {
case (Sized(g), Sized(g2)) => Sized(n => g(n) ** g2(n))
case (Unsized(g), Unsized(g2)) => Unsized(g ** g2)
case (Sized(g), Unsized(g2)) => Sized(n => g(n) ** g2)
case (Unsized(g), Sized(g2)) => Sized(n => g ** g2(n))
}
}
| stettix/fp-in-scala | src/main/scala/fpinscala/testing/Exhaustive.scala | Scala | apache-2.0 | 15,077 |
def f(x):
"""
Returns
-------
object
"""
return 42 | smmribeiro/intellij-community | python/testData/intentions/returnTypeInNewNumpyDocString_after.py | Python | apache-2.0 | 75 |
// errorcheck
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// issue 5358: incorrect error message when using f(g()) form on ... args.
package main
func f(x int, y ...int) {}
func g() (int, []int)
func main() {
f(g()) // ERROR "as type int in|incompatible type"
}
| vsekhar/elastic-go | test/fixedbugs/issue5358.go | GO | bsd-3-clause | 384 |
/*!
* Platform.js <http://mths.be/platform>
* Copyright 2010-2012 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window) {
/** Backup possible window/global object */
var oldWin = window,
/** Possible global object */
thisBinding = this,
/** Detect free variable `exports` */
freeExports = typeof exports == 'object' && exports,
/** Detect free variable `global` */
freeGlobal = typeof global == 'object' && global && (global == global.global ? (window = global) : global),
/** Used to check for own properties of an object */
hasOwnProperty = {}.hasOwnProperty,
/** Used to resolve a value's internal [[Class]] */
toString = {}.toString,
/** Detect Java environment */
java = /Java/.test(getClassOf(window.java)) && window.java,
/** A character to represent alpha */
alpha = java ? 'a' : '\u03b1',
/** A character to represent beta */
beta = java ? 'b' : '\u03b2',
/** Browser document object */
doc = window.document || {},
/** Browser navigator object */
nav = window.navigator || {},
/** Previous platform object */
old = window.platform,
/** Browser user agent string */
userAgent = nav.userAgent || '',
/**
* Detect Opera browser
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
opera = window.operamini || window.opera,
/** Opera regexp */
reOpera = /Opera/,
/** Opera [[Class]] */
operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null);
/*--------------------------------------------------------------------------*/
/**
* Capitalizes a string value.
* @private
* @param {String} string The string to capitalize.
* @returns {String} The capitalized string.
*/
function capitalize(string) {
string = String(string);
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* An iteration utility for arrays and objects.
* @private
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
*/
function each(object, callback) {
var index = -1,
length = object.length;
if (length == length >>> 0) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
*/
function forOwn(object, callback) {
for (var key in object) {
hasKey(object, key) && callback(object[key], key, object);
}
}
/**
* Trim and conditionally capitalize string values.
* @private
* @param {String} string The string to format.
* @returns {String} The formatted string.
*/
function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
}
/**
* Gets the internal [[Class]] of a value.
* @private
* @param {Mixed} value The value.
* @returns {String} The [[Class]].
*/
function getClassOf(value) {
return value == null
? capitalize(value)
: toString.call(value).slice(8, -1);
}
/**
* Checks if an object has the specified key as a direct property.
* @private
* @param {Object} object The object to check.
* @param {String} key The key to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
*/
function hasKey() {
// lazy define for others (not as accurate)
hasKey = function(object, key) {
var parent = object != null && (object.constructor || Object).prototype;
return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
};
// for modern browsers
if (getClassOf(hasOwnProperty) == 'Function') {
hasKey = function(object, key) {
return object != null && hasOwnProperty.call(object, key);
};
}
// for Safari 2
else if ({}.__proto__ == Object.prototype) {
hasKey = function(object, key) {
var result = false;
if (object != null) {
object = Object(object);
object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
}
return result;
};
}
return hasKey.apply(this, arguments);
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of object, function, or unknown.
* @private
* @param {Mixed} object The owner of the property.
* @param {String} property The property to check.
* @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* A bare-bones` Array#reduce` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} accumulator Initial value of the accumulator.
* @returns {Mixed} The accumulator.
*/
function reduce(array, callback) {
var accumulator = null;
each(array, function(value, index) {
accumulator = callback(accumulator, value, index, array);
});
return accumulator;
}
/**
* Prepares a string for use in a RegExp constructor by making hyphens and spaces optional.
* @private
* @param {String} string The string to qualify.
* @returns {String} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* Removes leading and trailing whitespace from a string.
* @private
* @param {String} string The string to trim.
* @returns {String} The trimmed string.
*/
function trim(string) {
return String(string).replace(/^ +| +$/g, '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new platform object.
* @memberOf platform
* @param {String} [ua = navigator.userAgent] The user agent string.
* @returns {Object} A platform object.
*/
function parse(ua) {
ua || (ua = userAgent);
/** Temporary variable used over the script's lifetime */
var data,
/** The CPU architecture */
arch = ua,
/** Platform description array */
description = [],
/** Platform alpha/beta indicator */
prerelease = null,
/** A flag to indicate that environment features should be used to resolve the platform */
useFeatures = ua == userAgent,
/** The browser/environment version */
version = useFeatures && opera && typeof opera.version == 'function' && opera.version(),
/* Detectable layout engines (order is important) */
layout = getLayout([
{ 'label': 'WebKit', 'pattern': 'AppleWebKit' },
'iCab',
'Presto',
'NetFront',
'Tasman',
'Trident',
'KHTML',
'Gecko'
]),
/* Detectable browser names (order is important) */
name = getName([
'Adobe AIR',
'Arora',
'Avant Browser',
'Camino',
'Epiphany',
'Fennec',
'Flock',
'Galeon',
'GreenBrowser',
'iCab',
'Iceweasel',
'Iron',
'K-Meleon',
'Konqueror',
'Lunascape',
'Maxthon',
'Midori',
'Nook Browser',
'PhantomJS',
'Raven',
'Rekonq',
'RockMelt',
'SeaMonkey',
{ 'label': 'Silk', 'pattern': '(?:Cloud9|Silk)' },
'Sleipnir',
'SlimBrowser',
'Sunrise',
'Swiftfox',
'WebPositive',
'Opera Mini',
'Opera',
'Chrome',
{ 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' },
{ 'label': 'IE', 'pattern': 'MSIE' },
'Safari'
]),
/* Detectable products (order is important) */
product = getProduct([
'BlackBerry',
{ 'label': 'Galaxy S', 'pattern': 'GT-I9000' },
{ 'label': 'Galaxy S2', 'pattern': 'GT-I9100' },
'iPad',
'iPod',
'iPhone',
'Kindle',
{ 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk)' },
'Nook',
'PlayBook',
'TouchPad',
'Transformer',
'Xoom'
]),
/* Detectable manufacturers */
manufacturer = getManufacturer({
'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 },
'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 },
'Asus': { 'Transformer': 1 },
'Barnes & Noble': { 'Nook': 1 },
'BlackBerry': { 'PlayBook': 1 },
'HP': { 'TouchPad': 1 },
'LG': { },
'Motorola': { 'Xoom': 1 },
'Nokia': { },
'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }
}),
/* Detectable OSes (order is important) */
os = getOS([
'Android',
'CentOS',
'Debian',
'Fedora',
'FreeBSD',
'Gentoo',
'Haiku',
'Kubuntu',
'Linux Mint',
'Red Hat',
'SuSE',
'Ubuntu',
'Xubuntu',
'Cygwin',
'Symbian OS',
'hpwOS',
'webOS ',
'webOS',
'Tablet OS',
'Linux',
'Mac OS X',
'Macintosh',
'Mac',
'Windows 98;',
'Windows '
]);
/*------------------------------------------------------------------------*/
/**
* Picks the layout engine from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected layout engine.
*/
function getLayout(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the manufacturer from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected manufacturer.
*/
function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// lookup the manufacturer by product or scan the UA for the manufacturer
return result || (
value[product] ||
value[0/*Opera 9.25 fix*/, /^[a-z]+/i.exec(product)] ||
RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && (key.label || key);
});
}
/**
* Picks the browser name from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected browser name.
*/
function getName(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the OS name from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected OS name.
*/
function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) {
// platform tokens defined at
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
data = {
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// detect Windows version from platform tokens
if (/^Win/i.test(result) &&
(data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) {
result = 'Windows ' + data;
}
// correct character case and cleanup
result = format(String(result)
.replace(RegExp(pattern, 'i'), guess.label || guess)
.replace(/ ce$/i, ' CE')
.replace(/hpw/i, 'web')
.replace(/Macintosh/, 'Mac OS')
.replace(/_PowerPC/i, ' OS')
.replace(/(OS X) [^ \d]+/i, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/x86\.64/gi, 'x86_64')
.split(' on ')[0]);
}
return result;
});
}
/**
* Picks the product name from an array of guesses.
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected product name.
*/
function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// split by forward slash and append product version if needed
if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// correct character case and cleanup
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2'));
}
return result;
});
}
/**
* Resolves the version using an array of UA patterns.
* @private
* @param {Array} patterns An array of UA patterns.
* @returns {String|Null} The detected version.
*/
function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/-]*)', 'i').exec(ua) || 0)[1] || null;
});
}
/*------------------------------------------------------------------------*/
/**
* Restores a previously overwritten platform object.
* @memberOf platform
* @type Function
* @returns {Object} The current platform object.
*/
function noConflict() {
window['platform'] = old;
return this;
}
/**
* Return platform description when the platform object is coerced to a string.
* @name toString
* @memberOf platform
* @type Function
* @returns {String} The platform description.
*/
function toStringPlatform() {
return this.description || '';
}
/*------------------------------------------------------------------------*/
// convert layout to an array so we can add extra details
layout && (layout = [layout]);
// detect product names that contain their manufacturer's name
if (manufacturer && !product) {
product = getProduct([manufacturer]);
}
// detect simulators
if (/\bSimulator\b/i.test(ua)) {
product = (product ? product + ' ' : '') + 'Simulator';
}
// detect iOS
if (/^iP/.test(product)) {
name || (name = 'Safari');
os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua))
? ' ' + data[1].replace(/_/g, '.')
: '');
}
// detect Kubuntu
else if (name == 'Konqueror' && !/buntu/i.test(os)) {
os = 'Kubuntu';
}
// detect Android browsers
else if (name == 'Chrome' && manufacturer) {
name = 'Android Browser';
os = /Android/.test(os) ? os : 'Android';
}
// detect false positives for Firefox/Safari
else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) {
// escape the `/` for Firefox 1
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// clear name of false positives
name = null;
}
// reassign a generic name
if ((data = product || manufacturer || os) &&
(product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) {
name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser';
}
}
// detect non-Opera versions (order is important)
if (!version) {
version = getVersion([
'(?:Cloud9|Opera ?Mini|Raven|Silk)',
'Version',
qualify(name),
'(?:Firefox|Minefield|NetFront)'
]);
}
// detect stubborn layout engines
if (layout == 'iCab' && parseFloat(version) > 3) {
layout = ['WebKit'];
} else if (name == 'Konqueror' && /\bKHTML\b/i.test(ua)) {
layout = ['KHTML'];
} else if (data =
/Opera/.test(name) && 'Presto' ||
/\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' ||
!layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) {
layout = [data];
}
// leverage environment features
if (useFeatures) {
// detect server-side environments
// Rhino has a global function while others have a global object
if (isHostType(thisBinding, 'global')) {
if (java) {
data = java.lang.System;
arch = data.getProperty('os.arch');
os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version');
}
if (typeof exports == 'object' && exports) {
// if `thisBinding` is the [ModuleScope]
if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) {
os || (os = data[0].os || null);
try {
data[1] = require('ringo/engine').version;
version = data[1].join('.');
name = 'RingoJS';
} catch(e) {
if (data[0].global == freeGlobal) {
name = 'Narwhal';
}
}
} else if (typeof process == 'object' && (data = process)) {
name = 'Node.js';
arch = data.arch;
os = data.platform;
version = /[\d.]+/.exec(data.version)[0];
}
} else if (getClassOf(window.environment) == 'Environment') {
name = 'Rhino';
}
}
// detect Adobe AIR
else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') {
name = 'Adobe AIR';
os = data.flash.system.Capabilities.os;
}
// detect PhantomJS
else if (getClassOf(data = window.phantom) == 'RuntimeObject') {
name = 'PhantomJS';
version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch);
}
// detect IE compatibility modes
else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) {
// we're in compatibility mode when the Trident version + 4 doesn't
// equal the document mode
version = [version, doc.documentMode];
if ((data = +data[1] + 4) != version[1]) {
description.push('IE ' + version[1] + ' mode');
layout[1] = '';
version[1] = data;
}
version = name == 'IE' ? String(version[1].toFixed(1)) : version[0];
}
os = os && format(os);
}
// detect prerelease phases
if (version && (data =
/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) ||
/(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) ||
/\bMinefield\b/i.test(ua) && 'a')) {
prerelease = /b/i.test(data) ? 'beta' : 'alpha';
version = version.replace(RegExp(data + '\\+?$'), '') +
(prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || '');
}
// obscure Maxthon's unreliable version
if (name == 'Maxthon' && version) {
version = version.replace(/\.[\d.]+/, '.x');
}
// detect Silk desktop/accelerated modes
else if (name == 'Silk') {
if (!/Mobi/i.test(ua)) {
os = 'Android';
description.unshift('desktop mode');
}
if (/Accelerated *= *true/i.test(ua)) {
description.unshift('accelerated');
}
}
// detect Windows Phone desktop mode
else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) {
name += ' Mobile';
os = 'Windows Phone OS ' + data + '.x';
description.unshift('desktop mode');
}
// add mobile postfix
else if ((name == 'IE' || name && !product && !/Browser/.test(name)) &&
(os == 'Windows CE' || /Mobi/i.test(ua))) {
name += ' Mobile';
}
// detect IE platform preview
else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) {
description.unshift('platform preview');
}
// detect BlackBerry OS version
// http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp
else if (/BlackBerry/.test(product) && (data =
(RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] ||
version)) {
os = 'Device Software ' + data;
version = null;
}
// detect Opera identifying/masking itself as another browser
// http://www.opera.com/support/kb/view/843/
else if (this != forOwn && (
(useFeatures && opera) ||
(/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) ||
(name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) ||
(name == 'IE' && (
(os && !/^Win/.test(os) && version > 5.5) ||
/Windows XP/.test(os) && version > 8 ||
version == 8 && !/Trident/.test(ua)
))
) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) {
// when "indentifying" the UA contains both Opera and the other browser's name
data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : '');
if (reOpera.test(name)) {
if (/IE/.test(data) && os == 'Mac OS') {
os = null;
}
data = 'identify' + data;
}
// when "masking" the UA contains only the other browser's name
else {
data = 'mask' + data;
if (operaClass) {
name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2'));
} else {
name = 'Opera';
}
if (/IE/.test(data)) {
os = null;
}
if (!useFeatures) {
version = null;
}
}
layout = ['Presto'];
description.push(data);
}
// detect WebKit Nightly and approximate Chrome/Safari versions
if ((data = (/AppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
// nightly builds are postfixed with a `+`
data = [parseFloat(data), data];
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
version = data[1].slice(0, -1);
}
// clear incorrect browser versions
else if (version == data[1] ||
version == (/Safari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) {
version = null;
}
// use the full Chrome version when available
data = [data[0], (/Chrome\/([\d.]+)/i.exec(ua) || 0)[1]];
// detect JavaScriptCore
// http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi
if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) {
layout[1] = 'like Safari';
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5');
} else {
layout[1] = 'like Chrome';
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.5 ? 3 : data < 533 ? 4 : data < 534.3 ? 5 : data < 534.7 ? 6 : data < 534.1 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.3 ? 11 : data < 535.1 ? 12 : data < 535.2 ? '13+' : data < 535.5 ? 15 : data < 535.7 ? 16 : '17');
}
// add the postfix of ".x" or "+" for approximate versions
layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+');
// obscure version for some Safari 1-2 releases
if (name == 'Safari' && (!version || parseInt(version) > 45)) {
version = data;
}
}
// strip incorrect OS versions
if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 &&
ua.indexOf('/' + data + '-') > -1) {
os = trim(os.replace(data, ''));
}
// add layout engine
if (layout && !/Avant|Nook/.test(name) && (
/Browser|Lunascape|Maxthon/.test(name) ||
/^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) {
// don't add layout details to description if they are falsey
(data = layout[layout.length - 1]) && description.push(data);
}
// combine contextual information
if (description.length) {
description = ['(' + description.join('; ') + ')'];
}
// append manufacturer
if (manufacturer && product && product.indexOf(manufacturer) < 0) {
description.push('on ' + manufacturer);
}
// append product
if (product) {
description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product);
}
// add browser/OS architecture
if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i).test(arch) && !/\bi686\b/i.test(arch)) {
os = os && os + (data.test(os) ? '' : ' 64-bit');
if (name && (/WOW64/i.test(ua) ||
(useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) {
description.unshift('32-bit');
}
}
ua || (ua = null);
/*------------------------------------------------------------------------*/
/**
* The platform object.
* @name platform
* @type Object
*/
return {
/**
* The browser/environment version.
* @memberOf platform
* @type String|Null
*/
'version': name && version && (description.unshift(version), version),
/**
* The name of the browser/environment.
* @memberOf platform
* @type String|Null
*/
'name': name && (description.unshift(name), name),
/**
* The name of the operating system.
* @memberOf platform
* @type String|Null
*/
'os': os && (name &&
!(os == os.split(' ')[0] && (os == name.split(' ')[0] || product)) &&
description.push(product ? '(' + os + ')' : 'on ' + os), os),
/**
* The platform description.
* @memberOf platform
* @type String|Null
*/
'description': description.length ? description.join(' ') : ua,
/**
* The name of the browser layout engine.
* @memberOf platform
* @type String|Null
*/
'layout': layout && layout[0],
/**
* The name of the product's manufacturer.
* @memberOf platform
* @type String|Null
*/
'manufacturer': manufacturer,
/**
* The alpha/beta release indicator.
* @memberOf platform
* @type String|Null
*/
'prerelease': prerelease,
/**
* The name of the product hosting the browser.
* @memberOf platform
* @type String|Null
*/
'product': product,
/**
* The browser's user agent string.
* @memberOf platform
* @type String|Null
*/
'ua': ua,
// avoid platform object conflicts in browsers
'noConflict': noConflict,
// parses a user agent string into a platform object
'parse': parse,
// returns the platform description
'toString': toStringPlatform
};
}
/*--------------------------------------------------------------------------*/
// expose platform
// in Narwhal, Node.js, or RingoJS
if (freeExports) {
forOwn(parse(), function(value, key) {
freeExports[key] = value;
});
}
// via curl.js or RequireJS
else if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
define('platform', function() {
return parse();
});
}
// in a browser or Rhino
else {
// use square bracket notation so Closure Compiler won't munge `platform`
// http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
window['platform'] = parse();
}
}(this)); | wayne-lewis/baiducdnstatic | libs/platform/0.4.0/platform.js | JavaScript | mit | 29,104 |
'use strict';
module.exports = function (t, a) {
var x;
a.throws(function () { t(0); }, TypeError, "0");
a.throws(function () { t(false); }, TypeError, "false");
a.throws(function () { t(''); }, TypeError, "''");
a(t(x = {}), x, "Object");
a(t(x = function () {}), x, "Function");
a(t(x = new String('raz')), x, "String object"); //jslint: ignore
a(t(x = new Date()), x, "Date");
a.throws(function () { t(); }, TypeError, "Undefined");
a.throws(function () { t(null); }, TypeError, "null");
};
| yuyang545262477/Resume | 项目二电商首页/node_modules/es5-ext/test/object/valid-object.js | JavaScript | mit | 506 |
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Definitions for the IP router.
*
* Version: @(#)route.h 1.0.4 05/27/93
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Fixes:
* Alan Cox : Reformatted. Added ip_rt_local()
* Alan Cox : Support for TCP parameters.
* Alexey Kuznetsov: Major changes for new routing code.
* Mike McLagan : Routing by source
* Robert Olsson : Added rt_cache statistics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#ifndef _ROUTE_H
#define _ROUTE_H
#include <net/dst.h>
#include <net/inetpeer.h>
#include <net/flow.h>
#include <net/inet_sock.h>
#include <linux/in_route.h>
#include <linux/rtnetlink.h>
#include <linux/rcupdate.h>
#include <linux/route.h>
#include <linux/ip.h>
#include <linux/cache.h>
#include <linux/security.h>
#define RTO_ONLINK 0x01
#define RT_CONN_FLAGS(sk) (RT_TOS(inet_sk(sk)->tos) | sock_flag(sk, SOCK_LOCALROUTE))
struct fib_nh;
struct fib_info;
struct rtable {
struct dst_entry dst;
int rt_genid;
unsigned int rt_flags;
__u16 rt_type;
__u8 rt_is_input;
__u8 rt_uses_gateway;
int rt_iif;
/* Info on neighbour */
__be32 rt_gateway;
/* Miscellaneous cached information */
u32 rt_pmtu;
struct list_head rt_uncached;
};
static inline bool rt_is_input_route(const struct rtable *rt)
{
return rt->rt_is_input != 0;
}
static inline bool rt_is_output_route(const struct rtable *rt)
{
return rt->rt_is_input == 0;
}
static inline __be32 rt_nexthop(const struct rtable *rt, __be32 daddr)
{
if (rt->rt_gateway)
return rt->rt_gateway;
return daddr;
}
struct ip_rt_acct {
__u32 o_bytes;
__u32 o_packets;
__u32 i_bytes;
__u32 i_packets;
};
struct rt_cache_stat {
unsigned int in_hit;
unsigned int in_slow_tot;
unsigned int in_slow_mc;
unsigned int in_no_route;
unsigned int in_brd;
unsigned int in_martian_dst;
unsigned int in_martian_src;
unsigned int out_hit;
unsigned int out_slow_tot;
unsigned int out_slow_mc;
unsigned int gc_total;
unsigned int gc_ignored;
unsigned int gc_goal_miss;
unsigned int gc_dst_overflow;
unsigned int in_hlist_search;
unsigned int out_hlist_search;
};
extern struct ip_rt_acct __percpu *ip_rt_acct;
struct in_device;
extern int ip_rt_init(void);
extern void rt_cache_flush(struct net *net);
extern void rt_flush_dev(struct net_device *dev);
extern struct rtable *__ip_route_output_key(struct net *, struct flowi4 *flp);
extern struct rtable *ip_route_output_flow(struct net *, struct flowi4 *flp,
struct sock *sk);
extern struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig);
static inline struct rtable *ip_route_output_key(struct net *net, struct flowi4 *flp)
{
return ip_route_output_flow(net, flp, NULL);
}
static inline struct rtable *ip_route_output(struct net *net, __be32 daddr,
__be32 saddr, u8 tos, int oif)
{
struct flowi4 fl4 = {
.flowi4_oif = oif,
.flowi4_tos = tos,
.daddr = daddr,
.saddr = saddr,
};
return ip_route_output_key(net, &fl4);
}
static inline struct rtable *ip_route_output_ports(struct net *net, struct flowi4 *fl4,
struct sock *sk,
__be32 daddr, __be32 saddr,
__be16 dport, __be16 sport,
__u8 proto, __u8 tos, int oif)
{
flowi4_init_output(fl4, oif, sk ? sk->sk_mark : 0, tos,
RT_SCOPE_UNIVERSE, proto,
sk ? inet_sk_flowi_flags(sk) : 0,
daddr, saddr, dport, sport, sock_net_uid(net, sk));
if (sk)
security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
return ip_route_output_flow(net, fl4, sk);
}
static inline struct rtable *ip_route_output_gre(struct net *net, struct flowi4 *fl4,
__be32 daddr, __be32 saddr,
__be32 gre_key, __u8 tos, int oif)
{
memset(fl4, 0, sizeof(*fl4));
fl4->flowi4_oif = oif;
fl4->daddr = daddr;
fl4->saddr = saddr;
fl4->flowi4_tos = tos;
fl4->flowi4_proto = IPPROTO_GRE;
fl4->fl4_gre_key = gre_key;
return ip_route_output_key(net, fl4);
}
extern int ip_route_input_noref(struct sk_buff *skb, __be32 dst, __be32 src,
u8 tos, struct net_device *devin);
static inline int ip_route_input(struct sk_buff *skb, __be32 dst, __be32 src,
u8 tos, struct net_device *devin)
{
int err;
rcu_read_lock();
err = ip_route_input_noref(skb, dst, src, tos, devin);
if (!err)
skb_dst_force(skb);
rcu_read_unlock();
return err;
}
extern void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu,
int oif, u32 mark, u8 protocol, int flow_flags);
extern void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu);
extern void ipv4_redirect(struct sk_buff *skb, struct net *net,
int oif, u32 mark, u8 protocol, int flow_flags);
extern void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk);
extern void ip_rt_send_redirect(struct sk_buff *skb);
extern unsigned int inet_addr_type(struct net *net, __be32 addr);
extern unsigned int inet_dev_addr_type(struct net *net, const struct net_device *dev, __be32 addr);
extern void ip_rt_multicast_event(struct in_device *);
extern int ip_rt_ioctl(struct net *, unsigned int cmd, void __user *arg);
extern void ip_rt_get_source(u8 *src, struct sk_buff *skb, struct rtable *rt);
extern int ip_rt_dump(struct sk_buff *skb, struct netlink_callback *cb);
struct in_ifaddr;
extern void fib_add_ifaddr(struct in_ifaddr *);
extern void fib_del_ifaddr(struct in_ifaddr *, struct in_ifaddr *);
static inline void ip_rt_put(struct rtable *rt)
{
/* dst_release() accepts a NULL parameter.
* We rely on dst being first structure in struct rtable
*/
BUILD_BUG_ON(offsetof(struct rtable, dst) != 0);
dst_release(&rt->dst);
}
#define IPTOS_RT_MASK (IPTOS_TOS_MASK & ~3)
extern const __u8 ip_tos2prio[16];
static inline char rt_tos2priority(u8 tos)
{
return ip_tos2prio[IPTOS_TOS(tos)>>1];
}
/* ip_route_connect() and ip_route_newports() work in tandem whilst
* binding a socket for a new outgoing connection.
*
* In order to use IPSEC properly, we must, in the end, have a
* route that was looked up using all available keys including source
* and destination ports.
*
* However, if a source port needs to be allocated (the user specified
* a wildcard source port) we need to obtain addressing information
* in order to perform that allocation.
*
* So ip_route_connect() looks up a route using wildcarded source and
* destination ports in the key, simply so that we can get a pair of
* addresses to use for port allocation.
*
* Later, once the ports are allocated, ip_route_newports() will make
* another route lookup if needed to make sure we catch any IPSEC
* rules keyed on the port information.
*
* The callers allocate the flow key on their stack, and must pass in
* the same flowi4 object to both the ip_route_connect() and the
* ip_route_newports() calls.
*/
static inline void ip_route_connect_init(struct flowi4 *fl4, __be32 dst, __be32 src,
u32 tos, int oif, u8 protocol,
__be16 sport, __be16 dport,
struct sock *sk, bool can_sleep)
{
__u8 flow_flags = 0;
if (inet_sk(sk)->transparent)
flow_flags |= FLOWI_FLAG_ANYSRC;
if (can_sleep)
flow_flags |= FLOWI_FLAG_CAN_SLEEP;
flowi4_init_output(fl4, oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE,
protocol, flow_flags, dst, src, dport, sport,
sk->sk_uid);
}
static inline struct rtable *ip_route_connect(struct flowi4 *fl4,
__be32 dst, __be32 src, u32 tos,
int oif, u8 protocol,
__be16 sport, __be16 dport,
struct sock *sk, bool can_sleep)
{
struct net *net = sock_net(sk);
struct rtable *rt;
ip_route_connect_init(fl4, dst, src, tos, oif, protocol,
sport, dport, sk, can_sleep);
if (!dst || !src) {
rt = __ip_route_output_key(net, fl4);
if (IS_ERR(rt))
return rt;
ip_rt_put(rt);
flowi4_update_output(fl4, oif, tos, fl4->daddr, fl4->saddr);
}
security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
return ip_route_output_flow(net, fl4, sk);
}
static inline struct rtable *ip_route_newports(struct flowi4 *fl4, struct rtable *rt,
__be16 orig_sport, __be16 orig_dport,
__be16 sport, __be16 dport,
struct sock *sk)
{
if (sport != orig_sport || dport != orig_dport) {
fl4->fl4_dport = dport;
fl4->fl4_sport = sport;
ip_rt_put(rt);
flowi4_update_output(fl4, sk->sk_bound_dev_if,
RT_CONN_FLAGS(sk), fl4->daddr,
fl4->saddr);
security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
return ip_route_output_flow(sock_net(sk), fl4, sk);
}
return rt;
}
static inline int inet_iif(const struct sk_buff *skb)
{
int iif = skb_rtable(skb)->rt_iif;
if (iif)
return iif;
return skb->skb_iif;
}
extern int sysctl_ip_default_ttl;
static inline int ip4_dst_hoplimit(const struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0)
hoplimit = sysctl_ip_default_ttl;
return hoplimit;
}
#endif /* _ROUTE_H */
| Khaon/android_kernel_samsung_a3xelte | include/net/route.h | C | gpl-2.0 | 9,365 |
#ifndef _NM256_H_
#define _NM256_H_
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include "ac97.h"
/* The revisions that we currently handle. */
enum nm256rev {
REV_NM256AV, REV_NM256ZX
};
/* Per-card structure. */
struct nm256_info
{
/* Magic number used to verify that this struct is valid. */
#define NM_MAGIC_SIG 0x55aa00ff
int magsig;
/* Revision number */
enum nm256rev rev;
struct ac97_hwint mdev;
/* Our audio device numbers. */
int dev[2];
/* The # of times each device has been opened. (Should only be
0 or 1). */
int opencnt[2];
/* We use two devices, because we can do simultaneous play and record.
This keeps track of which device is being used for what purpose;
these are the actual device numbers. */
int dev_for_play;
int dev_for_record;
spinlock_t lock;
/* The mixer device. */
int mixer_oss_dev;
/*
* Can only be opened once for each operation. These aren't set
* until an actual I/O operation is performed; this allows one
* device to be open for read/write without inhibiting I/O to
* the other device.
*/
int is_open_play;
int is_open_record;
/* Non-zero if we're currently playing a sample. */
int playing;
/* Ditto for recording a sample. */
int recording;
/* The two memory ports. */
struct nm256_ports {
/* Physical address of the port. */
u32 physaddr;
/* Our mapped-in pointer. */
char __iomem *ptr;
/* PTR's offset within the physical port. */
u32 start_offset;
/* And the offset of the end of the buffer. */
u32 end_offset;
} port[2];
/* The following are offsets within memory port 1. */
u32 coeffBuf;
u32 allCoeffBuf;
/* Record and playback buffers. */
u32 abuf1, abuf2;
/* Offset of the AC97 mixer in memory port 2. */
u32 mixer;
/* Offset of the mixer status register in memory port 2. */
u32 mixer_status_offset;
/* Non-zero if we have written initial values to the mixer. */
u8 mixer_values_init;
/*
* Status mask bit; (*mixer_status_loc & mixer_status_mask) == 0 means
* it's ready.
*/
u16 mixer_status_mask;
/* The sizes of the playback and record ring buffers. */
u32 playbackBufferSize;
u32 recordBufferSize;
/* Are the coefficient values in the memory cache current? */
u8 coeffsCurrent;
/* For writes, the amount we last wrote. */
u32 requested_amt;
/* The start of the block currently playing. */
u32 curPlayPos;
/* The amount of data we were requested to record. */
u32 requestedRecAmt;
/* The offset of the currently-recording block. */
u32 curRecPos;
/* The destination buffer. */
char *recBuf;
/* Our IRQ number. */
int irq;
/* A flag indicating how many times we've grabbed the IRQ. */
int has_irq;
/* The card interrupt service routine. */
irq_handler_t introutine;
/* Current audio config, cached. */
struct sinfo {
u32 samplerate;
u8 bits;
u8 stereo;
} sinfo[2]; /* goes with each device */
/* The cards are stored in a chain; this is the next card. */
struct nm256_info *next_card;
};
/* The BIOS signature. */
#define NM_SIGNATURE 0x4e4d0000
/* Signature mask. */
#define NM_SIG_MASK 0xffff0000
/* Size of the second memory area. */
#define NM_PORT2_SIZE 4096
/* The base offset of the mixer in the second memory area. */
#define NM_MIXER_OFFSET 0x600
/* The maximum size of a coefficient entry. */
#define NM_MAX_COEFFICIENT 0x5000
/* The interrupt register. */
#define NM_INT_REG 0xa04
/* And its bits. */
#define NM_PLAYBACK_INT 0x40
#define NM_RECORD_INT 0x100
#define NM_MISC_INT_1 0x4000
#define NM_MISC_INT_2 0x1
#define NM_ACK_INT(CARD, X) nm256_writePort16((CARD), 2, NM_INT_REG, (X) << 1)
/* The AV's "mixer ready" status bit and location. */
#define NM_MIXER_STATUS_OFFSET 0xa04
#define NM_MIXER_READY_MASK 0x0800
#define NM_MIXER_PRESENCE 0xa06
#define NM_PRESENCE_MASK 0x0050
#define NM_PRESENCE_VALUE 0x0040
/*
* For the ZX. It uses the same interrupt register, but it holds 32
* bits instead of 16.
*/
#define NM2_PLAYBACK_INT 0x10000
#define NM2_RECORD_INT 0x80000
#define NM2_MISC_INT_1 0x8
#define NM2_MISC_INT_2 0x2
#define NM2_ACK_INT(CARD, X) nm256_writePort32((CARD), 2, NM_INT_REG, (X))
/* The ZX's "mixer ready" status bit and location. */
#define NM2_MIXER_STATUS_OFFSET 0xa06
#define NM2_MIXER_READY_MASK 0x0800
/* The playback registers start from here. */
#define NM_PLAYBACK_REG_OFFSET 0x0
/* The record registers start from here. */
#define NM_RECORD_REG_OFFSET 0x200
/* The rate register is located 2 bytes from the start of the register area. */
#define NM_RATE_REG_OFFSET 2
/* Mono/stereo flag, number of bits on playback, and rate mask. */
#define NM_RATE_STEREO 1
#define NM_RATE_BITS_16 2
#define NM_RATE_MASK 0xf0
/* Playback enable register. */
#define NM_PLAYBACK_ENABLE_REG (NM_PLAYBACK_REG_OFFSET + 0x1)
#define NM_PLAYBACK_ENABLE_FLAG 1
#define NM_PLAYBACK_ONESHOT 2
#define NM_PLAYBACK_FREERUN 4
/* Mutes the audio output. */
#define NM_AUDIO_MUTE_REG (NM_PLAYBACK_REG_OFFSET + 0x18)
#define NM_AUDIO_MUTE_LEFT 0x8000
#define NM_AUDIO_MUTE_RIGHT 0x0080
/* Recording enable register. */
#define NM_RECORD_ENABLE_REG (NM_RECORD_REG_OFFSET + 0)
#define NM_RECORD_ENABLE_FLAG 1
#define NM_RECORD_FREERUN 2
#define NM_RBUFFER_START (NM_RECORD_REG_OFFSET + 0x4)
#define NM_RBUFFER_END (NM_RECORD_REG_OFFSET + 0x10)
#define NM_RBUFFER_WMARK (NM_RECORD_REG_OFFSET + 0xc)
#define NM_RBUFFER_CURRP (NM_RECORD_REG_OFFSET + 0x8)
#define NM_PBUFFER_START (NM_PLAYBACK_REG_OFFSET + 0x4)
#define NM_PBUFFER_END (NM_PLAYBACK_REG_OFFSET + 0x14)
#define NM_PBUFFER_WMARK (NM_PLAYBACK_REG_OFFSET + 0xc)
#define NM_PBUFFER_CURRP (NM_PLAYBACK_REG_OFFSET + 0x8)
/* A few trivial routines to make it easier to work with the registers
on the chip. */
/* This is a common code portion used to fix up the port offsets. */
#define NM_FIX_PORT \
if (port < 1 || port > 2 || card == NULL) \
return -1; \
\
if (offset < card->port[port - 1].start_offset \
|| offset >= card->port[port - 1].end_offset) { \
printk (KERN_ERR "Bad access: port %d, offset 0x%x\n", port, offset); \
return -1; \
} \
offset -= card->port[port - 1].start_offset;
#define DEFwritePortX(X, func) \
static inline int nm256_writePort##X (struct nm256_info *card,\
int port, int offset, int value)\
{\
u##X __iomem *addr;\
\
if (nm256_debug > 1)\
printk (KERN_DEBUG "Writing 0x%x to %d:0x%x\n", value, port, offset);\
\
NM_FIX_PORT;\
\
addr = (u##X __iomem *)(card->port[port - 1].ptr + offset);\
func (value, addr);\
return 0;\
}
DEFwritePortX (8, writeb)
DEFwritePortX (16, writew)
DEFwritePortX (32, writel)
#define DEFreadPortX(X, func) \
static inline u##X nm256_readPort##X (struct nm256_info *card,\
int port, int offset)\
{\
u##X __iomem *addr;\
\
NM_FIX_PORT\
\
addr = (u##X __iomem *)(card->port[port - 1].ptr + offset);\
return func(addr);\
}
DEFreadPortX (8, readb)
DEFreadPortX (16, readw)
DEFreadPortX (32, readl)
static inline int
nm256_writeBuffer8 (struct nm256_info *card, u8 *src, int port, int offset,
int amt)
{
NM_FIX_PORT;
memcpy_toio (card->port[port - 1].ptr + offset, src, amt);
return 0;
}
static inline int
nm256_readBuffer8 (struct nm256_info *card, u8 *dst, int port, int offset,
int amt)
{
NM_FIX_PORT;
memcpy_fromio (dst, card->port[port - 1].ptr + offset, amt);
return 0;
}
/* Returns a non-zero value if we should use the coefficient cache. */
static int nm256_cachedCoefficients (struct nm256_info *card);
#endif
/*
* Local variables:
* c-basic-offset: 4
* End:
*/
| JulianKemmerer/Drexel-CS370 | sound/oss/nm256.h | C | gpl-2.0 | 7,789 |
Kodi is provided under
SPDX-License-Identifier: GPL-2.0-or-later
Being under the terms of the GNU General Public License v2.0 or later, according with
LICENSES/GPL-2.0-or-later
In addition, other licenses may also apply. Please see
LICENSES/README.md
for more details.
| anthonyryan1/xbmc | LICENSE.md | Markdown | gpl-2.0 | 290 |
/*
* Configuation settings for the Freescale MCF54455 EVB board.
*
* Copyright (C) 2004-2007 Freescale Semiconductor, Inc.
* TsiChung Liew (Tsi-Chung.Liew@freescale.com)
*
* 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
*/
/*
* board/config.h - configuration options, board specific
*/
#ifndef _M54455EVB_H
#define _M54455EVB_H
/*
* High Level Configuration Options
* (easy to change)
*/
#define CONFIG_MCF5445x /* define processor family */
#define CONFIG_M54455 /* define processor type */
#define CONFIG_M54455EVB /* M54455EVB board */
#define CONFIG_MCFUART
#define CONFIG_SYS_UART_PORT (0)
#define CONFIG_BAUDRATE 115200
#define CONFIG_SYS_BAUDRATE_TABLE { 9600 , 19200 , 38400 , 57600, 115200 }
#undef CONFIG_WATCHDOG
#define CONFIG_TIMESTAMP /* Print image info with timestamp */
/*
* BOOTP options
*/
#define CONFIG_BOOTP_BOOTFILESIZE
#define CONFIG_BOOTP_BOOTPATH
#define CONFIG_BOOTP_GATEWAY
#define CONFIG_BOOTP_HOSTNAME
/* Command line configuration */
#include <config_cmd_default.h>
#define CONFIG_CMD_BOOTD
#define CONFIG_CMD_CACHE
#define CONFIG_CMD_DATE
#define CONFIG_CMD_DHCP
#define CONFIG_CMD_ELF
#define CONFIG_CMD_EXT2
#define CONFIG_CMD_FAT
#define CONFIG_CMD_FLASH
#define CONFIG_CMD_I2C
#define CONFIG_CMD_IDE
#define CONFIG_CMD_JFFS2
#define CONFIG_CMD_MEMORY
#define CONFIG_CMD_MISC
#define CONFIG_CMD_MII
#define CONFIG_CMD_NET
#undef CONFIG_CMD_PCI
#define CONFIG_CMD_PING
#define CONFIG_CMD_REGINFO
#define CONFIG_CMD_SPI
#define CONFIG_CMD_SF
#undef CONFIG_CMD_LOADB
#undef CONFIG_CMD_LOADS
/* Network configuration */
#define CONFIG_MCFFEC
#ifdef CONFIG_MCFFEC
# define CONFIG_NET_MULTI 1
# define CONFIG_MII 1
# define CONFIG_MII_INIT 1
# define CONFIG_SYS_DISCOVER_PHY
# define CONFIG_SYS_RX_ETH_BUFFER 8
# define CONFIG_SYS_FAULT_ECHO_LINK_DOWN
# define CONFIG_SYS_FEC0_PINMUX 0
# define CONFIG_SYS_FEC1_PINMUX 0
# define CONFIG_SYS_FEC0_MIIBASE CONFIG_SYS_FEC0_IOBASE
# define CONFIG_SYS_FEC1_MIIBASE CONFIG_SYS_FEC0_IOBASE
# define MCFFEC_TOUT_LOOP 50000
# define CONFIG_HAS_ETH1
# define CONFIG_BOOTDELAY 1 /* autoboot after 5 seconds */
# define CONFIG_BOOTARGS "root=/dev/mtdblock1 rw rootfstype=jffs2 ip=none mtdparts=physmap-flash.0:5M(kernel)ro,-(jffs2)"
# define CONFIG_ETHADDR 00:e0:0c:bc:e5:60
# define CONFIG_ETH1ADDR 00:e0:0c:bc:e5:61
# define CONFIG_ETHPRIME "FEC0"
# define CONFIG_IPADDR 192.162.1.2
# define CONFIG_NETMASK 255.255.255.0
# define CONFIG_SERVERIP 192.162.1.1
# define CONFIG_GATEWAYIP 192.162.1.1
# define CONFIG_OVERWRITE_ETHADDR_ONCE
/* If CONFIG_SYS_DISCOVER_PHY is not defined - hardcoded */
# ifndef CONFIG_SYS_DISCOVER_PHY
# define FECDUPLEX FULL
# define FECSPEED _100BASET
# else
# ifndef CONFIG_SYS_FAULT_ECHO_LINK_DOWN
# define CONFIG_SYS_FAULT_ECHO_LINK_DOWN
# endif
# endif /* CONFIG_SYS_DISCOVER_PHY */
#endif
#define CONFIG_HOSTNAME M54455EVB
#ifdef CONFIG_SYS_STMICRO_BOOT
/* ST Micro serial flash */
#define CONFIG_SYS_LOAD_ADDR2 0x40010013
#define CONFIG_EXTRA_ENV_SETTINGS \
"netdev=eth0\0" \
"inpclk=" MK_STR(CONFIG_SYS_INPUT_CLKSRC) "\0" \
"loadaddr=0x40010000\0" \
"sbfhdr=sbfhdr.bin\0" \
"uboot=u-boot.bin\0" \
"load=tftp ${loadaddr} ${sbfhdr};" \
"tftp " MK_STR(CONFIG_SYS_LOAD_ADDR2) " ${uboot} \0" \
"upd=run load; run prog\0" \
"prog=sf probe 0:1 10000 1;" \
"sf erase 0 30000;" \
"sf write ${loadaddr} 0 0x30000;" \
"save\0" \
""
#else
/* Atmel and Intel */
#ifdef CONFIG_SYS_ATMEL_BOOT
# define CONFIG_SYS_UBOOT_END 0x0403FFFF
#elif defined(CONFIG_SYS_INTEL_BOOT)
# define CONFIG_SYS_UBOOT_END 0x3FFFF
#endif
#define CONFIG_EXTRA_ENV_SETTINGS \
"netdev=eth0\0" \
"inpclk=" MK_STR(CONFIG_SYS_INPUT_CLKSRC) "\0" \
"loadaddr=0x40010000\0" \
"uboot=u-boot.bin\0" \
"load=tftp ${loadaddr} ${uboot}\0" \
"upd=run load; run prog\0" \
"prog=prot off " MK_STR(CONFIG_SYS_FLASH_BASE) \
" " MK_STR(CONFIG_SYS_UBOOT_END) ";" \
"era " MK_STR(CONFIG_SYS_FLASH_BASE) " " \
MK_STR(CONFIG_SYS_UBOOT_END) ";" \
"cp.b ${loadaddr} " MK_STR(CONFIG_SYS_FLASH_BASE) \
" ${filesize}; save\0" \
""
#endif
/* ATA configuration */
#define CONFIG_ISO_PARTITION
#define CONFIG_DOS_PARTITION
#define CONFIG_IDE_RESET 1
#define CONFIG_IDE_PREINIT 1
#define CONFIG_ATAPI
#undef CONFIG_LBA48
#define CONFIG_SYS_IDE_MAXBUS 1
#define CONFIG_SYS_IDE_MAXDEVICE 2
#define CONFIG_SYS_ATA_BASE_ADDR 0x90000000
#define CONFIG_SYS_ATA_IDE0_OFFSET 0
#define CONFIG_SYS_ATA_DATA_OFFSET 0xA0 /* Offset for data I/O */
#define CONFIG_SYS_ATA_REG_OFFSET 0xA0 /* Offset for normal register accesses */
#define CONFIG_SYS_ATA_ALT_OFFSET 0xC0 /* Offset for alternate registers */
#define CONFIG_SYS_ATA_STRIDE 4 /* Interval between registers */
/* Realtime clock */
#define CONFIG_MCFRTC
#undef RTC_DEBUG
#define CONFIG_SYS_RTC_OSCILLATOR (32 * CONFIG_SYS_HZ)
/* Timer */
#define CONFIG_MCFTMR
#undef CONFIG_MCFPIT
/* I2c */
#define CONFIG_FSL_I2C
#define CONFIG_HARD_I2C /* I2C with hardware support */
#undef CONFIG_SOFT_I2C /* I2C bit-banged */
#define CONFIG_SYS_I2C_SPEED 80000 /* I2C speed and slave address */
#define CONFIG_SYS_I2C_SLAVE 0x7F
#define CONFIG_SYS_I2C_OFFSET 0x58000
#define CONFIG_SYS_IMMR CONFIG_SYS_MBAR
/* DSPI and Serial Flash */
#define CONFIG_CF_SPI
#define CONFIG_CF_DSPI
#define CONFIG_HARD_SPI
#define CONFIG_SYS_SBFHDR_SIZE 0x13
#ifdef CONFIG_CMD_SPI
# define CONFIG_SPI_FLASH
# define CONFIG_SPI_FLASH_STMICRO
# define CONFIG_SYS_DSPI_CTAR0 (DSPI_CTAR_TRSZ(7) | \
DSPI_CTAR_PCSSCK_1CLK | \
DSPI_CTAR_PASC(0) | \
DSPI_CTAR_PDT(0) | \
DSPI_CTAR_CSSCK(0) | \
DSPI_CTAR_ASC(0) | \
DSPI_CTAR_DT(1))
#endif
/* PCI */
#ifdef CONFIG_CMD_PCI
#define CONFIG_PCI 1
#define CONFIG_PCI_PNP 1
#define CONFIG_PCIAUTO_SKIP_HOST_BRIDGE 1
#define CONFIG_SYS_PCI_CACHE_LINE_SIZE 4
#define CONFIG_SYS_PCI_MEM_BUS 0xA0000000
#define CONFIG_SYS_PCI_MEM_PHYS CONFIG_SYS_PCI_MEM_BUS
#define CONFIG_SYS_PCI_MEM_SIZE 0x10000000
#define CONFIG_SYS_PCI_IO_BUS 0xB1000000
#define CONFIG_SYS_PCI_IO_PHYS CONFIG_SYS_PCI_IO_BUS
#define CONFIG_SYS_PCI_IO_SIZE 0x01000000
#define CONFIG_SYS_PCI_CFG_BUS 0xB0000000
#define CONFIG_SYS_PCI_CFG_PHYS CONFIG_SYS_PCI_CFG_BUS
#define CONFIG_SYS_PCI_CFG_SIZE 0x01000000
#endif
/* FPGA - Spartan 2 */
/* experiment
#define CONFIG_FPGA CONFIG_SYS_SPARTAN3
#define CONFIG_FPGA_COUNT 1
#define CONFIG_SYS_FPGA_PROG_FEEDBACK
#define CONFIG_SYS_FPGA_CHECK_CTRLC
*/
/* Input, PCI, Flexbus, and VCO */
#define CONFIG_EXTRA_CLOCK
#define CONFIG_PRAM 2048 /* 2048 KB */
#define CONFIG_SYS_PROMPT "-> "
#define CONFIG_SYS_LONGHELP /* undef to save memory */
#if defined(CONFIG_CMD_KGDB)
#define CONFIG_SYS_CBSIZE 1024 /* Console I/O Buffer Size */
#else
#define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */
#endif
#define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE+sizeof(CONFIG_SYS_PROMPT)+16) /* Print Buffer Size */
#define CONFIG_SYS_MAXARGS 16 /* max number of command args */
#define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* Boot Argument Buffer Size */
#define CONFIG_SYS_LOAD_ADDR (CONFIG_SYS_SDRAM_BASE + 0x10000)
#define CONFIG_SYS_HZ 1000
#define CONFIG_SYS_MBAR 0xFC000000
/*
* Low Level Configuration Settings
* (address mappings, register initial values, etc.)
* You should know what you are doing if you make changes here.
*/
/*-----------------------------------------------------------------------
* Definitions for initial stack pointer and data area (in DPRAM)
*/
#define CONFIG_SYS_INIT_RAM_ADDR 0x80000000
#define CONFIG_SYS_INIT_RAM_SIZE 0x8000 /* Size of used area in internal SRAM */
#define CONFIG_SYS_INIT_RAM_CTRL 0x221
#define CONFIG_SYS_GBL_DATA_OFFSET ((CONFIG_SYS_INIT_RAM_SIZE - GENERATED_GBL_DATA_SIZE) - 32)
#define CONFIG_SYS_INIT_SP_OFFSET CONFIG_SYS_GBL_DATA_OFFSET
#define CONFIG_SYS_SBFHDR_DATA_OFFSET (CONFIG_SYS_INIT_RAM_SIZE - 32)
/*-----------------------------------------------------------------------
* Start addresses for the final memory configuration
* (Set up by the startup code)
* Please note that CONFIG_SYS_SDRAM_BASE _must_ start at 0
*/
#define CONFIG_SYS_SDRAM_BASE 0x40000000
#define CONFIG_SYS_SDRAM_BASE1 0x48000000
#define CONFIG_SYS_SDRAM_SIZE 256 /* SDRAM size in MB */
#define CONFIG_SYS_SDRAM_CFG1 0x65311610
#define CONFIG_SYS_SDRAM_CFG2 0x59670000
#define CONFIG_SYS_SDRAM_CTRL 0xEA0B2000
#define CONFIG_SYS_SDRAM_EMOD 0x40010000
#define CONFIG_SYS_SDRAM_MODE 0x00010033
#define CONFIG_SYS_SDRAM_DRV_STRENGTH 0xAA
#define CONFIG_SYS_MEMTEST_START CONFIG_SYS_SDRAM_BASE + 0x400
#define CONFIG_SYS_MEMTEST_END ((CONFIG_SYS_SDRAM_SIZE - 3) << 20)
#ifdef CONFIG_CF_SBF
# define CONFIG_SYS_MONITOR_BASE (CONFIG_SYS_TEXT_BASE + 0x400)
#else
# define CONFIG_SYS_MONITOR_BASE (CONFIG_SYS_FLASH_BASE + 0x400)
#endif
#define CONFIG_SYS_BOOTPARAMS_LEN 64*1024
#define CONFIG_SYS_MONITOR_LEN (256 << 10) /* Reserve 256 kB for Monitor */
#define CONFIG_SYS_MALLOC_LEN (128 << 10) /* Reserve 128 kB for malloc() */
/*
* For booting Linux, the board info and command line data
* have to be in the first 8 MB of memory, since this is
* the maximum mapped by the Linux kernel during initialization ??
*/
/* Initial Memory map for Linux */
#define CONFIG_SYS_BOOTMAPSZ (CONFIG_SYS_SDRAM_BASE + (CONFIG_SYS_SDRAM_SIZE << 20))
/*
* Configuration for environment
* Environment is embedded in u-boot in the second sector of the flash
*/
#ifdef CONFIG_CF_SBF
# define CONFIG_ENV_IS_IN_SPI_FLASH
# define CONFIG_ENV_SPI_CS 1
#else
# define CONFIG_ENV_IS_IN_FLASH 1
#endif
#undef CONFIG_ENV_OVERWRITE
/*-----------------------------------------------------------------------
* FLASH organization
*/
#ifdef CONFIG_SYS_STMICRO_BOOT
# define CONFIG_SYS_FLASH_BASE CONFIG_SYS_CS0_BASE
# define CONFIG_SYS_FLASH0_BASE CONFIG_SYS_CS1_BASE
# define CONFIG_ENV_OFFSET 0x30000
# define CONFIG_ENV_SIZE 0x2000
# define CONFIG_ENV_SECT_SIZE 0x10000
#endif
#ifdef CONFIG_SYS_ATMEL_BOOT
# define CONFIG_SYS_FLASH_BASE CONFIG_SYS_CS0_BASE
# define CONFIG_SYS_FLASH0_BASE CONFIG_SYS_CS0_BASE
# define CONFIG_SYS_FLASH1_BASE CONFIG_SYS_CS1_BASE
# define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + 0x4000)
# define CONFIG_ENV_SECT_SIZE 0x2000
#endif
#ifdef CONFIG_SYS_INTEL_BOOT
# define CONFIG_SYS_FLASH_BASE CONFIG_SYS_CS0_BASE
# define CONFIG_SYS_FLASH0_BASE CONFIG_SYS_CS0_BASE
# define CONFIG_SYS_FLASH1_BASE CONFIG_SYS_CS1_BASE
# define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + 0x40000)
# define CONFIG_ENV_SIZE 0x2000
# define CONFIG_ENV_SECT_SIZE 0x20000
#endif
#define CONFIG_SYS_FLASH_CFI
#ifdef CONFIG_SYS_FLASH_CFI
# define CONFIG_FLASH_CFI_DRIVER 1
# define CONFIG_SYS_FLASH_USE_BUFFER_WRITE 1
# define CONFIG_SYS_FLASH_SIZE 0x1000000 /* Max size that the board might have */
# define CONFIG_SYS_FLASH_CFI_WIDTH FLASH_CFI_8BIT
# define CONFIG_SYS_MAX_FLASH_BANKS 2 /* max number of memory banks */
# define CONFIG_SYS_MAX_FLASH_SECT 137 /* max number of sectors on one chip */
# define CONFIG_SYS_FLASH_PROTECTION /* "Real" (hardware) sectors protection */
# define CONFIG_SYS_FLASH_CHECKSUM
# define CONFIG_SYS_FLASH_BANKS_LIST { CONFIG_SYS_CS0_BASE, CONFIG_SYS_CS1_BASE }
# define CONFIG_FLASH_CFI_LEGACY
#ifdef CONFIG_FLASH_CFI_LEGACY
# define CONFIG_SYS_ATMEL_REGION 4
# define CONFIG_SYS_ATMEL_TOTALSECT 11
# define CONFIG_SYS_ATMEL_SECT {1, 2, 1, 7}
# define CONFIG_SYS_ATMEL_SECTSZ {0x4000, 0x2000, 0x8000, 0x10000}
#endif
#endif
/*
* This is setting for JFFS2 support in u-boot.
* NOTE: Enable CONFIG_CMD_JFFS2 for JFFS2 support.
*/
#ifdef CONFIG_CMD_JFFS2
#ifdef CF_STMICRO_BOOT
# define CONFIG_JFFS2_DEV "nor1"
# define CONFIG_JFFS2_PART_SIZE 0x01000000
# define CONFIG_JFFS2_PART_OFFSET (CONFIG_SYS_FLASH2_BASE + 0x500000)
#endif
#ifdef CONFIG_SYS_ATMEL_BOOT
# define CONFIG_JFFS2_DEV "nor1"
# define CONFIG_JFFS2_PART_SIZE 0x01000000
# define CONFIG_JFFS2_PART_OFFSET (CONFIG_SYS_FLASH1_BASE + 0x500000)
#endif
#ifdef CONFIG_SYS_INTEL_BOOT
# define CONFIG_JFFS2_DEV "nor0"
# define CONFIG_JFFS2_PART_SIZE (0x01000000 - 0x500000)
# define CONFIG_JFFS2_PART_OFFSET (CONFIG_SYS_FLASH0_BASE + 0x500000)
#endif
#endif
/*-----------------------------------------------------------------------
* Cache Configuration
*/
#define CONFIG_SYS_CACHELINE_SIZE 16
#define ICACHE_STATUS (CONFIG_SYS_INIT_RAM_ADDR + \
CONFIG_SYS_INIT_RAM_SIZE - 8)
#define DCACHE_STATUS (CONFIG_SYS_INIT_RAM_ADDR + \
CONFIG_SYS_INIT_RAM_SIZE - 4)
#define CONFIG_SYS_ICACHE_INV (CF_CACR_BCINVA + CF_CACR_ICINVA)
#define CONFIG_SYS_DCACHE_INV (CF_CACR_DCINVA)
#define CONFIG_SYS_CACHE_ACR2 (CONFIG_SYS_SDRAM_BASE | \
CF_ADDRMASK(CONFIG_SYS_SDRAM_SIZE) | \
CF_ACR_EN | CF_ACR_SM_ALL)
#define CONFIG_SYS_CACHE_ICACR (CF_CACR_BEC | CF_CACR_IEC | \
CF_CACR_ICINVA | CF_CACR_EUSP)
#define CONFIG_SYS_CACHE_DCACR ((CONFIG_SYS_CACHE_ICACR | \
CF_CACR_DEC | CF_CACR_DDCM_P | \
CF_CACR_DCINVA) & ~CF_CACR_ICINVA)
/*-----------------------------------------------------------------------
* Memory bank definitions
*/
/*
* CS0 - NOR Flash 1, 2, 4, or 8MB
* CS1 - CompactFlash and registers
* CS2 - CPLD
* CS3 - FPGA
* CS4 - Available
* CS5 - Available
*/
#if defined(CONFIG_SYS_ATMEL_BOOT) || defined(CONFIG_SYS_STMICRO_BOOT)
/* Atmel Flash */
#define CONFIG_SYS_CS0_BASE 0x04000000
#define CONFIG_SYS_CS0_MASK 0x00070001
#define CONFIG_SYS_CS0_CTRL 0x00001140
/* Intel Flash */
#define CONFIG_SYS_CS1_BASE 0x00000000
#define CONFIG_SYS_CS1_MASK 0x01FF0001
#define CONFIG_SYS_CS1_CTRL 0x00000D60
#define CONFIG_SYS_ATMEL_BASE CONFIG_SYS_CS0_BASE
#else
/* Intel Flash */
#define CONFIG_SYS_CS0_BASE 0x00000000
#define CONFIG_SYS_CS0_MASK 0x01FF0001
#define CONFIG_SYS_CS0_CTRL 0x00000D60
/* Atmel Flash */
#define CONFIG_SYS_CS1_BASE 0x04000000
#define CONFIG_SYS_CS1_MASK 0x00070001
#define CONFIG_SYS_CS1_CTRL 0x00001140
#define CONFIG_SYS_ATMEL_BASE CONFIG_SYS_CS1_BASE
#endif
/* CPLD */
#define CONFIG_SYS_CS2_BASE 0x08000000
#define CONFIG_SYS_CS2_MASK 0x00070001
#define CONFIG_SYS_CS2_CTRL 0x003f1140
/* FPGA */
#define CONFIG_SYS_CS3_BASE 0x09000000
#define CONFIG_SYS_CS3_MASK 0x00070001
#define CONFIG_SYS_CS3_CTRL 0x00000020
#endif /* _M54455EVB_H */
| InternetBowser/plutos | u-boot-s805/include/configs/M54455EVB.h | C | gpl-2.0 | 15,019 |
// ----------------------------------------------------------------------------------
//
// 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.
// ---
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Test.UnitTests.TSql;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Test.UnitTests.Database.Cmdlet
{
[TestClass]
public class SqlAuthv12MockTests
{
public static string username = "testlogin";
public static string password = "MyS3curePa$$w0rd";
public static string manageUrl = "https://mysvr2.database.windows.net";
[TestInitialize]
public void Setup()
{
}
[TestCleanup]
public void Cleanup()
{
// Do any test clean up here.
}
//[RecordMockDataResults("./")]
[TestMethod]
public void NewAzureSqlDatabaseWithSqlAuthv12()
{
var mockConn = new MockSqlConnection();
TSqlConnectionContext.MockSqlConnection = mockConn;
using (System.Management.Automation.PowerShell powershell =
System.Management.Automation.PowerShell.Create())
{
// Create a context
NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuthV12(
powershell,
manageUrl,
username,
password,
"$context");
Collection<PSObject> database1, database2, database3, database4;
database1 = powershell.InvokeBatchScript(
@"$testdb1 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 " +
@"-Force",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb2 " +
@"-Collation Japanese_CI_AS " +
@"-Edition Basic " +
@"-MaxSizeGB 2 " +
@"-Force",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb3 " +
@"-MaxSizeBytes 107374182400 " +
@"-Force",
@"$testdb3");
var slo = powershell.InvokeBatchScript(
@"$so = Get-AzureSqlDatabaseServiceObjective " +
@"-Context $context " +
@"-ServiceObjectiveName S2 ",
@"$so");
database4 = powershell.InvokeBatchScript(
@"$testdb4 = New-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb4 " +
@"-Edition Standard " +
@"-ServiceObjective $so " +
@"-Force",
@"$testdb4");
Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
powershell.Streams.ClearStreams();
Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database2.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb2", "Basic", 2, 2147483648L, "Japanese_CI_AS", false, DatabaseTestHelper.BasicSloGuid);
database = database3.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb3", "Standard", 100, 107374182400L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database4.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb4", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS2SloGuid);
}
}
//[RecordMockDataResults("./")]
[TestMethod]
public void GetAzureSqlDatabaseWithSqlAuthv12()
{
var mockConn = new MockSqlConnection();
TSqlConnectionContext.MockSqlConnection = mockConn;
using (System.Management.Automation.PowerShell powershell =
System.Management.Automation.PowerShell.Create())
{
// Create a context
NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuthV12(
powershell,
manageUrl,
username,
password,
"$context");
Collection<PSObject> database1, database2, database3;
database1 = powershell.InvokeBatchScript(
@"$testdb1 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 ",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-Database $testdb1 ",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = Get-AzureSqlDatabase " +
@"-Context $context ",
@"$testdb3");
Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
powershell.Streams.ClearStreams();
Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database2.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
Assert.IsTrue(database3.Count == 5);
foreach (var entry in database3)
{
var db = entry.BaseObject as Services.Server.Database;
Assert.IsTrue(db != null, "Expecting a Database object");
}
}
}
//[RecordMockDataResults("./")]
[TestMethod]
public void SetAzureSqlDatabaseWithSqlAuthv12()
{
var mockConn = new MockSqlConnection();
TSqlConnectionContext.MockSqlConnection = mockConn;
using (System.Management.Automation.PowerShell powershell =
System.Management.Automation.PowerShell.Create())
{
// Create a context
NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuthV12(
powershell,
manageUrl,
username,
password,
"$context");
Collection<PSObject> database1, database2, database3, database4;
database1 = powershell.InvokeBatchScript(
@"$testdb1 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 " +
@"-Edition Basic " +
@"-MaxSizeGb 1 " +
@"-Force " +
@"-PassThru ",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb2 " +
@"-Edition Standard " +
@"-MaxSizeBytes 107374182400 " +
@"-Force " +
@"-PassThru ",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb3 " +
@"-NewDatabaseName testdb3alt " +
@"-Force " +
@"-PassThru ",
@"$testdb3");
var slo = powershell.InvokeBatchScript(
@"$so = Get-AzureSqlDatabaseServiceObjective " +
@"-Context $context " +
@"-ServiceObjectiveName S0 ",
@"$so");
database4 = powershell.InvokeBatchScript(
@"$testdb4 = Set-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb4 " +
@"-ServiceObjective $so " +
@"-Force " +
@"-PassThru ",
@"$testdb4");
//
// Wait for operations to complete
//
database1 = powershell.InvokeBatchScript(
@"$testdb1 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb1 ",
@"$testdb1");
database2 = powershell.InvokeBatchScript(
@"$testdb2 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb2 ",
@"$testdb2");
database3 = powershell.InvokeBatchScript(
@"$testdb3 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb3alt ",
@"$testdb3");
database4 = powershell.InvokeBatchScript(
@"$testdb4 = Get-AzureSqlDatabase " +
@"-Context $context " +
@"-DatabaseName testdb4 ",
@"$testdb4");
Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
powershell.Streams.ClearStreams();
Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb1", "Basic", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.BasicSloGuid);
database = database2.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb2", "Standard", 100, 107374182400L, "Japanese_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database3.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb3alt", "Standard", 100, 107374182400L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
database = database4.Single().BaseObject as Services.Server.Database;
Assert.IsTrue(database != null, "Expecting a Database object");
ValidateDatabaseProperties(database, "testdb4", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", false, DatabaseTestHelper.StandardS0SloGuid);
}
}
#region Helpers
/// <summary>
/// Validate the properties of a database against the expected values supplied as input.
/// </summary>
/// <param name="database">The database object to validate</param>
/// <param name="name">The expected name of the database</param>
/// <param name="edition">The expected edition of the database</param>
/// <param name="maxSizeGb">The expected max size of the database in GB</param>
/// <param name="collation">The expected Collation of the database</param>
/// <param name="isSystem">Whether or not the database is expected to be a system object.</param>
internal static void ValidateDatabaseProperties(
Services.Server.Database database,
string name,
string edition,
int maxSizeGb,
long maxSizeBytes,
string collation,
bool isSystem,
Guid slo)
{
Assert.AreEqual(name, database.Name);
Assert.AreEqual(edition, database.Edition);
Assert.AreEqual(maxSizeGb, database.MaxSizeGB);
Assert.AreEqual(maxSizeBytes, database.MaxSizeBytes);
Assert.AreEqual(collation, database.CollationName);
Assert.AreEqual(isSystem, database.IsSystemObject);
// Assert.AreEqual(slo, database.ServiceObjectiveId);
}
#endregion
}
}
| mayurid/azure-powershell | src/ServiceManagement/Sql/Commands.SqlDatabase.Test/UnitTests/Database/Cmdlet/SqlAuthv12MockTests.cs | C# | apache-2.0 | 14,978 |
/* 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.
==============================================================================*/
package org.tensorflow.op.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used by classes to make TensorFlow operations conveniently accessible via {@code
* org.tensorflow.op.Ops}.
*
* <p>An annotation processor (TODO: not yet implemented) builds the {@code Ops} class by
* aggregating all classes annotated as {@code @Operator}s. Each annotated class <b>must</b> have at
* least one public static factory method named {@code create} that accepts a {@link
* org.tensorflow.op.Scope} as its first argument. The processor then adds a convenience method in
* the {@code Ops} class. For example:
*
* <pre>{@code
* @Operator
* public final class MyOp implements Op {
* public static MyOp create(Scope scope, Operand operand) {
* ...
* }
* }
* }</pre>
*
* <p>results in a method in the {@code Ops} class
*
* <pre>{@code
* import org.tensorflow.op.Ops;
* ...
* Ops ops = new Ops(graph);
* ...
* ops.myOp(operand);
* // and has exactly the same effect as calling
* // MyOp.create(ops.getScope(), operand);
* }</pre>
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Operator {
/**
* Specify an optional group within the {@code Ops} class.
*
* <p>By default, an annotation processor will create convenience methods directly in the {@code
* Ops} class. An annotated operator may optionally choose to place the method within a group. For
* example:
*
* <pre>{@code
* @Operator(group="math")
* public final class Add extends PrimitiveOp implements Operand {
* ...
* }
* }</pre>
*
* <p>results in the {@code add} method placed within a {@code math} group within the {@code Ops}
* class.
*
* <pre>{@code
* ops.math().add(...);
* }</pre>
*
* <p>The group name must be a <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java
* identifier</a>.
*/
String group() default "";
/**
* Name for the wrapper method used in the {@code Ops} class.
*
* <p>By default, a processor derives the method name in the {@code Ops} class from the class name
* of the operator. This attribute allow you to provide a different name instead. For example:
*
* <pre>{@code
* @Operator(name="myOperation")
* public final class MyRealOperation implements Operand {
* public static MyRealOperation create(...)
* }
* }</pre>
*
* <p>results in this method added to the {@code Ops} class
*
* <pre>{@code
* ops.myOperation(...);
* // and is the same as calling
* // MyRealOperation.create(...)
* }</pre>
*
* <p>The name must be a <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java
* identifier</a>.
*/
String name() default "";
}
| nburn42/tensorflow | tensorflow/java/src/main/java/org/tensorflow/op/annotation/Operator.java | Java | apache-2.0 | 3,654 |
<?php
PHPExcel_Autoloader::register();
// As we always try to run the autoloader before anything else, we can use it to do a few
// simple checks and initialisations
//PHPExcel_Shared_ZipStreamWrapper::register();
// check mbstring.func_overload
if (ini_get('mbstring.func_overload') & 2) {
throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
}
PHPExcel_Shared_String::buildCharacterSets();
/**
* PHPExcel
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_Autoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function register()
{
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true);
} else {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'));
}
}
/**
* Autoload a class identified by name
*
* @param string $pClassName Name of the object to load
*/
public static function load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
// Either already loaded, or not a PHPExcel class request
return false;
}
$pClassFilePath = PHPEXCEL_ROOT .
str_replace('_', DIRECTORY_SEPARATOR, $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
// Can't load
return false;
}
require($pClassFilePath);
}
}
| yysun2000/delibelight | yc/lib/PHPExcel/Autoloader.php | PHP | mit | 2,884 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Numerics.Tests
{
public class op_leftshiftTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunLeftShiftTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// LeftShift Method - Large BigIntegers - large + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomPosByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - small + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)s_random.Next(1, 32) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - 32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)32 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - large - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = GetRandomNegByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - small - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { unchecked((byte)s_random.Next(-31, 0)) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - -32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)0xe0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Large BigIntegers - 0 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { (byte)0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - large + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - small + Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)s_random.Next(1, 32) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - 32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)32 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - large - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = GetRandomNegByteArray(s_random, 2);
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - small - Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { unchecked((byte)s_random.Next(-31, 0)) };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - -32 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)0xe0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Small BigIntegers - 0 bit Shift
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 2);
tempByteArray2 = new byte[] { (byte)0 };
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Positive BigIntegers - Shift to 0
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 100);
tempByteArray2 = BitConverter.GetBytes(s_random.Next(-1000, -8 * tempByteArray1.Length));
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
// LeftShift Method - Negative BigIntegers - Shift to -1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 100);
tempByteArray2 = BitConverter.GetBytes(s_random.Next(-1000, -8 * tempByteArray1.Length));
VerifyLeftShiftString(Print(tempByteArray2) + Print(tempByteArray1) + "b<<");
}
}
private static void VerifyLeftShiftString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static Byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static Byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| DnlHarvey/corefx | src/System.Runtime.Numerics/tests/BigInteger/op_leftshift.cs | C# | mit | 8,031 |
<?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\Form\Guess;
/**
* Base class for guesses made by TypeGuesserInterface implementation
*
* Each instance contains a confidence value about the correctness of the guess.
* Thus an instance with confidence HIGH_CONFIDENCE is more likely to be
* correct than an instance with confidence LOW_CONFIDENCE.
*
* @author Bernhard Schussek <bernhard.schussek@symfony.com>
*/
abstract class Guess
{
/**
* Marks an instance with a value that is very likely to be correct
* @var integer
*/
const HIGH_CONFIDENCE = 2;
/**
* Marks an instance with a value that is likely to be correct
* @var integer
*/
const MEDIUM_CONFIDENCE = 1;
/**
* Marks an instance with a value that may be correct
* @var integer
*/
const LOW_CONFIDENCE = 0;
/**
* The list of allowed confidence values
* @var array
*/
private static $confidences = array(
self::HIGH_CONFIDENCE,
self::MEDIUM_CONFIDENCE,
self::LOW_CONFIDENCE,
);
/**
* The confidence about the correctness of the value
*
* One of HIGH_CONFIDENCE, MEDIUM_CONFIDENCE and LOW_CONFIDENCE.
*
* @var integer
*/
private $confidence;
/**
* Returns the guess most likely to be correct from a list of guesses
*
* If there are multiple guesses with the same, highest confidence, the
* returned guess is any of them.
*
* @param array $guesses A list of guesses
*
* @return Guess The guess with the highest confidence
*/
public static function getBestGuess(array $guesses)
{
usort($guesses, function ($a, $b) {
return $b->getConfidence() - $a->getConfidence();
});
return count($guesses) > 0 ? $guesses[0] : null;
}
/**
* Constructor
*
* @param integer $confidence The confidence
*/
public function __construct($confidence)
{
if (!in_array($confidence, self::$confidences)) {
throw new \UnexpectedValueException(sprintf('The confidence should be one of "%s"', implode('", "', self::$confidences)));
}
$this->confidence = $confidence;
}
/**
* Returns the confidence that the guessed value is correct
*
* @return integer One of the constants HIGH_CONFIDENCE, MEDIUM_CONFIDENCE
* and LOW_CONFIDENCE
*/
public function getConfidence()
{
return $this->confidence;
}
}
| winze/CMS-experience | vendor/symfony/src/Symfony/Component/Form/Guess/Guess.php | PHP | mit | 2,752 |
/*
* Driver O/S-independent utility routines
*
* Copyright (C) 1999-2016, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
*
* <<Broadcom-WL-IPTag/Open:>>
*
* $Id: bcmutils.c 591286 2015-10-07 11:59:26Z $
*/
#include <bcm_cfg.h>
#include <typedefs.h>
#include <bcmdefs.h>
#include <stdarg.h>
#ifdef BCMDRIVER
#include <osl.h>
#include <bcmutils.h>
#else /* !BCMDRIVER */
#include <stdio.h>
#include <string.h>
#include <bcmutils.h>
#if defined(BCMEXTSUP)
#include <bcm_osl.h>
#endif
#ifndef ASSERT
#define ASSERT(exp)
#endif
#endif /* !BCMDRIVER */
#include <bcmendian.h>
#include <bcmdevs.h>
#include <proto/ethernet.h>
#include <proto/vlan.h>
#include <proto/bcmip.h>
#include <proto/802.1d.h>
#include <proto/802.11.h>
void *_bcmutils_dummy_fn = NULL;
#ifdef BCMDRIVER
/* copy a pkt buffer chain into a buffer */
uint
pktcopy(osl_t *osh, void *p, uint offset, int len, uchar *buf)
{
uint n, ret = 0;
if (len < 0)
len = 4096; /* "infinite" */
/* skip 'offset' bytes */
for (; p && offset; p = PKTNEXT(osh, p)) {
if (offset < (uint)PKTLEN(osh, p))
break;
offset -= PKTLEN(osh, p);
}
if (!p)
return 0;
/* copy the data */
for (; p && len; p = PKTNEXT(osh, p)) {
n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len);
bcopy(PKTDATA(osh, p) + offset, buf, n);
buf += n;
len -= n;
ret += n;
offset = 0;
}
return ret;
}
/* copy a buffer into a pkt buffer chain */
uint
pktfrombuf(osl_t *osh, void *p, uint offset, int len, uchar *buf)
{
uint n, ret = 0;
/* skip 'offset' bytes */
for (; p && offset; p = PKTNEXT(osh, p)) {
if (offset < (uint)PKTLEN(osh, p))
break;
offset -= PKTLEN(osh, p);
}
if (!p)
return 0;
/* copy the data */
for (; p && len; p = PKTNEXT(osh, p)) {
n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len);
bcopy(buf, PKTDATA(osh, p) + offset, n);
buf += n;
len -= n;
ret += n;
offset = 0;
}
return ret;
}
/* return total length of buffer chain */
uint BCMFASTPATH
pkttotlen(osl_t *osh, void *p)
{
uint total;
int len;
total = 0;
for (; p; p = PKTNEXT(osh, p)) {
len = PKTLEN(osh, p);
total += len;
#ifdef BCMLFRAG
if (BCMLFRAG_ENAB()) {
if (PKTISFRAG(osh, p)) {
total += PKTFRAGTOTLEN(osh, p);
}
}
#endif
}
return (total);
}
/* return the last buffer of chained pkt */
void *
pktlast(osl_t *osh, void *p)
{
for (; PKTNEXT(osh, p); p = PKTNEXT(osh, p))
;
return (p);
}
/* count segments of a chained packet */
uint BCMFASTPATH
pktsegcnt(osl_t *osh, void *p)
{
uint cnt;
for (cnt = 0; p; p = PKTNEXT(osh, p)) {
cnt++;
#ifdef BCMLFRAG
if (BCMLFRAG_ENAB()) {
if (PKTISFRAG(osh, p)) {
cnt += PKTFRAGTOTNUM(osh, p);
}
}
#endif
}
return cnt;
}
/* count segments of a chained packet */
uint BCMFASTPATH
pktsegcnt_war(osl_t *osh, void *p)
{
uint cnt;
uint8 *pktdata;
uint len, remain, align64;
for (cnt = 0; p; p = PKTNEXT(osh, p)) {
cnt++;
len = PKTLEN(osh, p);
if (len > 128) {
pktdata = (uint8 *)PKTDATA(osh, p); /* starting address of data */
/* Check for page boundary straddle (2048B) */
if (((uintptr)pktdata & ~0x7ff) != ((uintptr)(pktdata+len) & ~0x7ff))
cnt++;
align64 = (uint)((uintptr)pktdata & 0x3f); /* aligned to 64B */
align64 = (64 - align64) & 0x3f;
len -= align64; /* bytes from aligned 64B to end */
/* if aligned to 128B, check for MOD 128 between 1 to 4B */
remain = len % 128;
if (remain > 0 && remain <= 4)
cnt++; /* add extra seg */
}
}
return cnt;
}
uint8 * BCMFASTPATH
pktdataoffset(osl_t *osh, void *p, uint offset)
{
uint total = pkttotlen(osh, p);
uint pkt_off = 0, len = 0;
uint8 *pdata = (uint8 *) PKTDATA(osh, p);
if (offset > total)
return NULL;
for (; p; p = PKTNEXT(osh, p)) {
pdata = (uint8 *) PKTDATA(osh, p);
pkt_off = offset - len;
len += PKTLEN(osh, p);
if (len > offset)
break;
}
return (uint8*) (pdata+pkt_off);
}
/* given a offset in pdata, find the pkt seg hdr */
void *
pktoffset(osl_t *osh, void *p, uint offset)
{
uint total = pkttotlen(osh, p);
uint len = 0;
if (offset > total)
return NULL;
for (; p; p = PKTNEXT(osh, p)) {
len += PKTLEN(osh, p);
if (len > offset)
break;
}
return p;
}
#endif /* BCMDRIVER */
#if !defined(BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS)
const unsigned char bcm_ctype[] = {
_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 0-7 */
_BCM_C, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C,
_BCM_C, /* 8-15 */
_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 16-23 */
_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 24-31 */
_BCM_S|_BCM_SP,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 32-39 */
_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 40-47 */
_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D, /* 48-55 */
_BCM_D,_BCM_D,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 56-63 */
_BCM_P, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X,
_BCM_U|_BCM_X, _BCM_U, /* 64-71 */
_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 72-79 */
_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 80-87 */
_BCM_U,_BCM_U,_BCM_U,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 88-95 */
_BCM_P, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X,
_BCM_L|_BCM_X, _BCM_L, /* 96-103 */
_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 104-111 */
_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 112-119 */
_BCM_L,_BCM_L,_BCM_L,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_C, /* 120-127 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128-143 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144-159 */
_BCM_S|_BCM_SP, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P,
_BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 160-175 */
_BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P,
_BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 176-191 */
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U,
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, /* 192-207 */
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_P, _BCM_U, _BCM_U, _BCM_U,
_BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_L, /* 208-223 */
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L,
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, /* 224-239 */
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_P, _BCM_L, _BCM_L, _BCM_L,
_BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L /* 240-255 */
};
ulong
bcm_strtoul(const char *cp, char **endp, uint base)
{
ulong result, last_result = 0, value;
bool minus;
minus = FALSE;
while (bcm_isspace(*cp))
cp++;
if (cp[0] == '+')
cp++;
else if (cp[0] == '-') {
minus = TRUE;
cp++;
}
if (base == 0) {
if (cp[0] == '0') {
if ((cp[1] == 'x') || (cp[1] == 'X')) {
base = 16;
cp = &cp[2];
} else {
base = 8;
cp = &cp[1];
}
} else
base = 10;
} else if (base == 16 && (cp[0] == '0') && ((cp[1] == 'x') || (cp[1] == 'X'))) {
cp = &cp[2];
}
result = 0;
while (bcm_isxdigit(*cp) &&
(value = bcm_isdigit(*cp) ? *cp-'0' : bcm_toupper(*cp)-'A'+10) < base) {
result = result*base + value;
/* Detected overflow */
if (result < last_result && !minus)
return (ulong)-1;
last_result = result;
cp++;
}
if (minus)
result = (ulong)(-(long)result);
if (endp)
*endp = DISCARD_QUAL(cp, char);
return (result);
}
int
bcm_atoi(const char *s)
{
return (int)bcm_strtoul(s, NULL, 10);
}
/* return pointer to location of substring 'needle' in 'haystack' */
char *
bcmstrstr(const char *haystack, const char *needle)
{
int len, nlen;
int i;
if ((haystack == NULL) || (needle == NULL))
return DISCARD_QUAL(haystack, char);
nlen = (int)strlen(needle);
len = (int)strlen(haystack) - nlen + 1;
for (i = 0; i < len; i++)
if (memcmp(needle, &haystack[i], nlen) == 0)
return DISCARD_QUAL(&haystack[i], char);
return (NULL);
}
char *
bcmstrnstr(const char *s, uint s_len, const char *substr, uint substr_len)
{
for (; s_len >= substr_len; s++, s_len--)
if (strncmp(s, substr, substr_len) == 0)
return DISCARD_QUAL(s, char);
return NULL;
}
char *
bcmstrcat(char *dest, const char *src)
{
char *p;
p = dest + strlen(dest);
while ((*p++ = *src++) != '\0')
;
return (dest);
}
char *
bcmstrncat(char *dest, const char *src, uint size)
{
char *endp;
char *p;
p = dest + strlen(dest);
endp = p + size;
while (p != endp && (*p++ = *src++) != '\0')
;
return (dest);
}
/****************************************************************************
* Function: bcmstrtok
*
* Purpose:
* Tokenizes a string. This function is conceptually similiar to ANSI C strtok(),
* but allows strToken() to be used by different strings or callers at the same
* time. Each call modifies '*string' by substituting a NULL character for the
* first delimiter that is encountered, and updates 'string' to point to the char
* after the delimiter. Leading delimiters are skipped.
*
* Parameters:
* string (mod) Ptr to string ptr, updated by token.
* delimiters (in) Set of delimiter characters.
* tokdelim (out) Character that delimits the returned token. (May
* be set to NULL if token delimiter is not required).
*
* Returns: Pointer to the next token found. NULL when no more tokens are found.
*****************************************************************************
*/
char *
bcmstrtok(char **string, const char *delimiters, char *tokdelim)
{
unsigned char *str;
unsigned long map[8];
int count;
char *nextoken;
if (tokdelim != NULL) {
/* Prime the token delimiter */
*tokdelim = '\0';
}
/* Clear control map */
for (count = 0; count < 8; count++) {
map[count] = 0;
}
/* Set bits in delimiter table */
do {
map[*delimiters >> 5] |= (1 << (*delimiters & 31));
}
while (*delimiters++);
str = (unsigned char*)*string;
/* Find beginning of token (skip over leading delimiters). Note that
* there is no token iff this loop sets str to point to the terminal
* null (*str == '\0')
*/
while (((map[*str >> 5] & (1 << (*str & 31))) && *str) || (*str == ' ')) {
str++;
}
nextoken = (char*)str;
/* Find the end of the token. If it is not the end of the string,
* put a null there.
*/
for (; *str; str++) {
if (map[*str >> 5] & (1 << (*str & 31))) {
if (tokdelim != NULL) {
*tokdelim = *str;
}
*str++ = '\0';
break;
}
}
*string = (char*)str;
/* Determine if a token has been found. */
if (nextoken == (char *) str) {
return NULL;
}
else {
return nextoken;
}
}
#define xToLower(C) \
((C >= 'A' && C <= 'Z') ? (char)((int)C - (int)'A' + (int)'a') : C)
/****************************************************************************
* Function: bcmstricmp
*
* Purpose: Compare to strings case insensitively.
*
* Parameters: s1 (in) First string to compare.
* s2 (in) Second string to compare.
*
* Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if
* t1 > t2, when ignoring case sensitivity.
*****************************************************************************
*/
int
bcmstricmp(const char *s1, const char *s2)
{
char dc, sc;
while (*s2 && *s1) {
dc = xToLower(*s1);
sc = xToLower(*s2);
if (dc < sc) return -1;
if (dc > sc) return 1;
s1++;
s2++;
}
if (*s1 && !*s2) return 1;
if (!*s1 && *s2) return -1;
return 0;
}
/****************************************************************************
* Function: bcmstrnicmp
*
* Purpose: Compare to strings case insensitively, upto a max of 'cnt'
* characters.
*
* Parameters: s1 (in) First string to compare.
* s2 (in) Second string to compare.
* cnt (in) Max characters to compare.
*
* Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if
* t1 > t2, when ignoring case sensitivity.
*****************************************************************************
*/
int
bcmstrnicmp(const char* s1, const char* s2, int cnt)
{
char dc, sc;
while (*s2 && *s1 && cnt) {
dc = xToLower(*s1);
sc = xToLower(*s2);
if (dc < sc) return -1;
if (dc > sc) return 1;
s1++;
s2++;
cnt--;
}
if (!cnt) return 0;
if (*s1 && !*s2) return 1;
if (!*s1 && *s2) return -1;
return 0;
}
/* parse a xx:xx:xx:xx:xx:xx format ethernet address */
int
bcm_ether_atoe(const char *p, struct ether_addr *ea)
{
int i = 0;
char *ep;
for (;;) {
ea->octet[i++] = (char) bcm_strtoul(p, &ep, 16);
p = ep;
if (!*p++ || i == 6)
break;
}
return (i == 6);
}
int
bcm_atoipv4(const char *p, struct ipv4_addr *ip)
{
int i = 0;
char *c;
for (;;) {
ip->addr[i++] = (uint8)bcm_strtoul(p, &c, 0);
if (*c++ != '.' || i == IPV4_ADDR_LEN)
break;
p = c;
}
return (i == IPV4_ADDR_LEN);
}
#endif /* !BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS */
#if defined(CONFIG_USBRNDIS_RETAIL) || defined(NDIS_MINIPORT_DRIVER)
/* registry routine buffer preparation utility functions:
* parameter order is like strncpy, but returns count
* of bytes copied. Minimum bytes copied is null char(1)/wchar(2)
*/
ulong
wchar2ascii(char *abuf, ushort *wbuf, ushort wbuflen, ulong abuflen)
{
ulong copyct = 1;
ushort i;
if (abuflen == 0)
return 0;
/* wbuflen is in bytes */
wbuflen /= sizeof(ushort);
for (i = 0; i < wbuflen; ++i) {
if (--abuflen == 0)
break;
*abuf++ = (char) *wbuf++;
++copyct;
}
*abuf = '\0';
return copyct;
}
#endif /* CONFIG_USBRNDIS_RETAIL || NDIS_MINIPORT_DRIVER */
char *
bcm_ether_ntoa(const struct ether_addr *ea, char *buf)
{
static const char hex[] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
const uint8 *octet = ea->octet;
char *p = buf;
int i;
for (i = 0; i < 6; i++, octet++) {
*p++ = hex[(*octet >> 4) & 0xf];
*p++ = hex[*octet & 0xf];
*p++ = ':';
}
*(p-1) = '\0';
return (buf);
}
char *
bcm_ip_ntoa(struct ipv4_addr *ia, char *buf)
{
snprintf(buf, 16, "%d.%d.%d.%d",
ia->addr[0], ia->addr[1], ia->addr[2], ia->addr[3]);
return (buf);
}
char *
bcm_ipv6_ntoa(void *ipv6, char *buf)
{
/* Implementing RFC 5952 Sections 4 + 5 */
/* Not thoroughly tested */
uint16 tmp[8];
uint16 *a = &tmp[0];
char *p = buf;
int i, i_max = -1, cnt = 0, cnt_max = 1;
uint8 *a4 = NULL;
memcpy((uint8 *)&tmp[0], (uint8 *)ipv6, IPV6_ADDR_LEN);
for (i = 0; i < IPV6_ADDR_LEN/2; i++) {
if (a[i]) {
if (cnt > cnt_max) {
cnt_max = cnt;
i_max = i - cnt;
}
cnt = 0;
} else
cnt++;
}
if (cnt > cnt_max) {
cnt_max = cnt;
i_max = i - cnt;
}
if (i_max == 0 &&
/* IPv4-translated: ::ffff:0:a.b.c.d */
((cnt_max == 4 && a[4] == 0xffff && a[5] == 0) ||
/* IPv4-mapped: ::ffff:a.b.c.d */
(cnt_max == 5 && a[5] == 0xffff)))
a4 = (uint8*) (a + 6);
for (i = 0; i < IPV6_ADDR_LEN/2; i++) {
if ((uint8*) (a + i) == a4) {
snprintf(p, 16, ":%u.%u.%u.%u", a4[0], a4[1], a4[2], a4[3]);
break;
} else if (i == i_max) {
*p++ = ':';
i += cnt_max - 1;
p[0] = ':';
p[1] = '\0';
} else {
if (i)
*p++ = ':';
p += snprintf(p, 8, "%x", ntoh16(a[i]));
}
}
return buf;
}
#ifdef BCMDRIVER
void
bcm_mdelay(uint ms)
{
uint i;
for (i = 0; i < ms; i++) {
OSL_DELAY(1000);
}
}
#if defined(DHD_DEBUG)
/* pretty hex print a pkt buffer chain */
void
prpkt(const char *msg, osl_t *osh, void *p0)
{
void *p;
if (msg && (msg[0] != '\0'))
printf("%s:\n", msg);
for (p = p0; p; p = PKTNEXT(osh, p))
prhex(NULL, PKTDATA(osh, p), PKTLEN(osh, p));
}
#endif
/* Takes an Ethernet frame and sets out-of-bound PKTPRIO.
* Also updates the inplace vlan tag if requested.
* For debugging, it returns an indication of what it did.
*/
uint BCMFASTPATH
pktsetprio(void *pkt, bool update_vtag)
{
struct ether_header *eh;
struct ethervlan_header *evh;
uint8 *pktdata;
int priority = 0;
int rc = 0;
pktdata = (uint8 *)PKTDATA(OSH_NULL, pkt);
ASSERT(ISALIGNED((uintptr)pktdata, sizeof(uint16)));
eh = (struct ether_header *) pktdata;
if (eh->ether_type == hton16(ETHER_TYPE_8021Q)) {
uint16 vlan_tag;
int vlan_prio, dscp_prio = 0;
evh = (struct ethervlan_header *)eh;
vlan_tag = ntoh16(evh->vlan_tag);
vlan_prio = (int) (vlan_tag >> VLAN_PRI_SHIFT) & VLAN_PRI_MASK;
if ((evh->ether_type == hton16(ETHER_TYPE_IP)) ||
(evh->ether_type == hton16(ETHER_TYPE_IPV6))) {
uint8 *ip_body = pktdata + sizeof(struct ethervlan_header);
uint8 tos_tc = IP_TOS46(ip_body);
dscp_prio = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT);
}
/* DSCP priority gets precedence over 802.1P (vlan tag) */
if (dscp_prio != 0) {
priority = dscp_prio;
rc |= PKTPRIO_VDSCP;
} else {
priority = vlan_prio;
rc |= PKTPRIO_VLAN;
}
/*
* If the DSCP priority is not the same as the VLAN priority,
* then overwrite the priority field in the vlan tag, with the
* DSCP priority value. This is required for Linux APs because
* the VLAN driver on Linux, overwrites the skb->priority field
* with the priority value in the vlan tag
*/
if (update_vtag && (priority != vlan_prio)) {
vlan_tag &= ~(VLAN_PRI_MASK << VLAN_PRI_SHIFT);
vlan_tag |= (uint16)priority << VLAN_PRI_SHIFT;
evh->vlan_tag = hton16(vlan_tag);
rc |= PKTPRIO_UPD;
}
#ifdef DHD_LOSSLESS_ROAMING
} else if (eh->ether_type == hton16(ETHER_TYPE_802_1X)) {
priority = PRIO_8021D_NC;
rc = PKTPRIO_DSCP;
#endif /* DHD_LOSSLESS_ROAMING */
} else if ((eh->ether_type == hton16(ETHER_TYPE_IP)) ||
(eh->ether_type == hton16(ETHER_TYPE_IPV6))) {
uint8 *ip_body = pktdata + sizeof(struct ether_header);
uint8 tos_tc = IP_TOS46(ip_body);
uint8 dscp = tos_tc >> IPV4_TOS_DSCP_SHIFT;
switch (dscp) {
case DSCP_EF:
priority = PRIO_8021D_VO;
break;
case DSCP_AF31:
case DSCP_AF32:
case DSCP_AF33:
priority = PRIO_8021D_CL;
break;
case DSCP_AF21:
case DSCP_AF22:
case DSCP_AF23:
case DSCP_AF11:
case DSCP_AF12:
case DSCP_AF13:
priority = PRIO_8021D_EE;
break;
default:
priority = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT);
break;
}
rc |= PKTPRIO_DSCP;
}
ASSERT(priority >= 0 && priority <= MAXPRIO);
PKTSETPRIO(pkt, priority);
return (rc | priority);
}
/* lookup user priority for specified DSCP */
static uint8
dscp2up(uint8 *up_table, uint8 dscp)
{
uint8 user_priority = 255;
/* lookup up from table if parameters valid */
if (up_table != NULL && dscp < UP_TABLE_MAX) {
user_priority = up_table[dscp];
}
/* 255 is unused value so return up from dscp */
if (user_priority == 255) {
user_priority = dscp >> (IPV4_TOS_PREC_SHIFT - IPV4_TOS_DSCP_SHIFT);
}
return user_priority;
}
/* set user priority by QoS Map Set table (UP table), table size is UP_TABLE_MAX */
uint BCMFASTPATH
pktsetprio_qms(void *pkt, uint8* up_table, bool update_vtag)
{
if (up_table) {
uint8 *pktdata;
uint pktlen;
uint8 dscp;
uint user_priority = 0;
uint rc = 0;
pktdata = (uint8 *)PKTDATA(OSH_NULL, pkt);
pktlen = PKTLEN(OSH_NULL, pkt);
if (pktgetdscp(pktdata, pktlen, &dscp)) {
rc = PKTPRIO_DSCP;
user_priority = dscp2up(up_table, dscp);
PKTSETPRIO(pkt, user_priority);
}
return (rc | user_priority);
} else {
return pktsetprio(pkt, update_vtag);
}
}
/* Returns TRUE and DSCP if IP header found, FALSE otherwise.
*/
bool BCMFASTPATH
pktgetdscp(uint8 *pktdata, uint pktlen, uint8 *dscp)
{
struct ether_header *eh;
struct ethervlan_header *evh;
uint8 *ip_body;
bool rc = FALSE;
/* minimum length is ether header and IP header */
if (pktlen < sizeof(struct ether_header) + IPV4_MIN_HEADER_LEN)
return FALSE;
eh = (struct ether_header *) pktdata;
if (eh->ether_type == HTON16(ETHER_TYPE_IP)) {
ip_body = pktdata + sizeof(struct ether_header);
*dscp = IP_DSCP46(ip_body);
rc = TRUE;
}
else if (eh->ether_type == HTON16(ETHER_TYPE_8021Q)) {
evh = (struct ethervlan_header *)eh;
/* minimum length is ethervlan header and IP header */
if (pktlen >= sizeof(struct ethervlan_header) + IPV4_MIN_HEADER_LEN &&
evh->ether_type == HTON16(ETHER_TYPE_IP)) {
ip_body = pktdata + sizeof(struct ethervlan_header);
*dscp = IP_DSCP46(ip_body);
rc = TRUE;
}
}
return rc;
}
/* The 0.5KB string table is not removed by compiler even though it's unused */
static char bcm_undeferrstr[32];
static const char *bcmerrorstrtable[] = BCMERRSTRINGTABLE;
/* Convert the error codes into related error strings */
const char *
bcmerrorstr(int bcmerror)
{
/* check if someone added a bcmerror code but forgot to add errorstring */
ASSERT(ABS(BCME_LAST) == (ARRAYSIZE(bcmerrorstrtable) - 1));
if (bcmerror > 0 || bcmerror < BCME_LAST) {
snprintf(bcm_undeferrstr, sizeof(bcm_undeferrstr), "Undefined error %d", bcmerror);
return bcm_undeferrstr;
}
ASSERT(strlen(bcmerrorstrtable[-bcmerror]) < BCME_STRLEN);
return bcmerrorstrtable[-bcmerror];
}
/* iovar table lookup */
/* could mandate sorted tables and do a binary search */
const bcm_iovar_t*
bcm_iovar_lookup(const bcm_iovar_t *table, const char *name)
{
const bcm_iovar_t *vi;
const char *lookup_name;
/* skip any ':' delimited option prefixes */
lookup_name = strrchr(name, ':');
if (lookup_name != NULL)
lookup_name++;
else
lookup_name = name;
ASSERT(table != NULL);
for (vi = table; vi->name; vi++) {
if (!strcmp(vi->name, lookup_name))
return vi;
}
/* ran to end of table */
return NULL; /* var name not found */
}
int
bcm_iovar_lencheck(const bcm_iovar_t *vi, void *arg, int len, bool set)
{
int bcmerror = 0;
/* length check on io buf */
switch (vi->type) {
case IOVT_BOOL:
case IOVT_INT8:
case IOVT_INT16:
case IOVT_INT32:
case IOVT_UINT8:
case IOVT_UINT16:
case IOVT_UINT32:
/* all integers are int32 sized args at the ioctl interface */
if (len < (int)sizeof(int)) {
bcmerror = BCME_BUFTOOSHORT;
}
break;
case IOVT_BUFFER:
/* buffer must meet minimum length requirement */
if (len < vi->minlen) {
bcmerror = BCME_BUFTOOSHORT;
}
break;
case IOVT_VOID:
if (!set) {
/* Cannot return nil... */
bcmerror = BCME_UNSUPPORTED;
} else if (len) {
/* Set is an action w/o parameters */
bcmerror = BCME_BUFTOOLONG;
}
break;
default:
/* unknown type for length check in iovar info */
ASSERT(0);
bcmerror = BCME_UNSUPPORTED;
}
return bcmerror;
}
#endif /* BCMDRIVER */
#ifdef BCM_OBJECT_TRACE
#define BCM_OBJECT_MERGE_SAME_OBJ 0
/* some place may add / remove the object to trace list for Linux: */
/* add: osl_alloc_skb dev_alloc_skb skb_realloc_headroom dhd_start_xmit */
/* remove: osl_pktfree dev_kfree_skb netif_rx */
#define BCM_OBJDBG_COUNT (1024 * 100)
static spinlock_t dbgobj_lock;
#define BCM_OBJDBG_LOCK_INIT() spin_lock_init(&dbgobj_lock)
#define BCM_OBJDBG_LOCK_DESTROY()
#define BCM_OBJDBG_LOCK spin_lock_irqsave
#define BCM_OBJDBG_UNLOCK spin_unlock_irqrestore
#define BCM_OBJDBG_ADDTOHEAD 0
#define BCM_OBJDBG_ADDTOTAIL 1
#define BCM_OBJDBG_CALLER_LEN 32
struct bcm_dbgobj {
struct bcm_dbgobj *prior;
struct bcm_dbgobj *next;
uint32 flag;
void *obj;
uint32 obj_sn;
uint32 obj_state;
uint32 line;
char caller[BCM_OBJDBG_CALLER_LEN];
};
static struct bcm_dbgobj *dbgobj_freehead = NULL;
static struct bcm_dbgobj *dbgobj_freetail = NULL;
static struct bcm_dbgobj *dbgobj_objhead = NULL;
static struct bcm_dbgobj *dbgobj_objtail = NULL;
static uint32 dbgobj_sn = 0;
static int dbgobj_count = 0;
static struct bcm_dbgobj bcm_dbg_objs[BCM_OBJDBG_COUNT];
void
bcm_object_trace_init(void)
{
int i = 0;
BCM_OBJDBG_LOCK_INIT();
memset(&bcm_dbg_objs, 0x00, sizeof(struct bcm_dbgobj) * BCM_OBJDBG_COUNT);
dbgobj_freehead = &bcm_dbg_objs[0];
dbgobj_freetail = &bcm_dbg_objs[BCM_OBJDBG_COUNT - 1];
for (i = 0; i < BCM_OBJDBG_COUNT; ++i) {
bcm_dbg_objs[i].next = (i == (BCM_OBJDBG_COUNT - 1)) ?
dbgobj_freehead : &bcm_dbg_objs[i + 1];
bcm_dbg_objs[i].prior = (i == 0) ?
dbgobj_freetail : &bcm_dbg_objs[i - 1];
}
}
void
bcm_object_trace_deinit(void)
{
if (dbgobj_objhead || dbgobj_objtail) {
printf("%s: not all objects are released\n", __FUNCTION__);
ASSERT(0);
}
BCM_OBJDBG_LOCK_DESTROY();
}
static void
bcm_object_rm_list(struct bcm_dbgobj **head, struct bcm_dbgobj **tail,
struct bcm_dbgobj *dbgobj)
{
if ((dbgobj == *head) && (dbgobj == *tail)) {
*head = NULL;
*tail = NULL;
} else if (dbgobj == *head) {
*head = (*head)->next;
} else if (dbgobj == *tail) {
*tail = (*tail)->prior;
}
dbgobj->next->prior = dbgobj->prior;
dbgobj->prior->next = dbgobj->next;
}
static void
bcm_object_add_list(struct bcm_dbgobj **head, struct bcm_dbgobj **tail,
struct bcm_dbgobj *dbgobj, int addtotail)
{
if (!(*head) && !(*tail)) {
*head = dbgobj;
*tail = dbgobj;
dbgobj->next = dbgobj;
dbgobj->prior = dbgobj;
} else if ((*head) && (*tail)) {
(*tail)->next = dbgobj;
(*head)->prior = dbgobj;
dbgobj->next = *head;
dbgobj->prior = *tail;
if (addtotail == BCM_OBJDBG_ADDTOTAIL)
*tail = dbgobj;
else
*head = dbgobj;
} else {
ASSERT(0); /* can't be this case */
}
}
static INLINE void
bcm_object_movetoend(struct bcm_dbgobj **head, struct bcm_dbgobj **tail,
struct bcm_dbgobj *dbgobj, int movetotail)
{
if ((*head) && (*tail)) {
if (movetotail == BCM_OBJDBG_ADDTOTAIL) {
if (dbgobj != (*tail)) {
bcm_object_rm_list(head, tail, dbgobj);
bcm_object_add_list(head, tail, dbgobj, movetotail);
}
} else {
if (dbgobj != (*head)) {
bcm_object_rm_list(head, tail, dbgobj);
bcm_object_add_list(head, tail, dbgobj, movetotail);
}
}
} else {
ASSERT(0); /* can't be this case */
}
}
void
bcm_object_trace_opr(void *obj, uint32 opt, const char *caller, int line)
{
struct bcm_dbgobj *dbgobj;
unsigned long flags;
BCM_REFERENCE(flags);
BCM_OBJDBG_LOCK(&dbgobj_lock, flags);
if (opt == BCM_OBJDBG_ADD_PKT ||
opt == BCM_OBJDBG_ADD) {
dbgobj = dbgobj_objtail;
while (dbgobj) {
if (dbgobj->obj == obj) {
printf("%s: obj %p allocated from %s(%d),"
" allocate again from %s(%d)\n",
__FUNCTION__, dbgobj->obj,
dbgobj->caller, dbgobj->line,
caller, line);
ASSERT(0);
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
#if BCM_OBJECT_MERGE_SAME_OBJ
dbgobj = dbgobj_freetail;
while (dbgobj) {
if (dbgobj->obj == obj) {
goto FREED_ENTRY_FOUND;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_freetail)
break;
}
#endif /* BCM_OBJECT_MERGE_SAME_OBJ */
dbgobj = dbgobj_freehead;
#if BCM_OBJECT_MERGE_SAME_OBJ
FREED_ENTRY_FOUND:
#endif /* BCM_OBJECT_MERGE_SAME_OBJ */
if (!dbgobj) {
printf("%s: already got %d objects ?????????????????????\n",
__FUNCTION__, BCM_OBJDBG_COUNT);
ASSERT(0);
goto EXIT;
}
bcm_object_rm_list(&dbgobj_freehead, &dbgobj_freetail, dbgobj);
dbgobj->obj = obj;
strncpy(dbgobj->caller, caller, BCM_OBJDBG_CALLER_LEN);
dbgobj->caller[BCM_OBJDBG_CALLER_LEN-1] = '\0';
dbgobj->line = line;
dbgobj->flag = 0;
if (opt == BCM_OBJDBG_ADD_PKT) {
dbgobj->obj_sn = dbgobj_sn++;
dbgobj->obj_state = 0;
/* first 4 bytes is pkt sn */
if (((unsigned long)PKTTAG(obj)) & 0x3)
printf("pkt tag address not aligned by 4: %p\n", PKTTAG(obj));
*(uint32*)PKTTAG(obj) = dbgobj->obj_sn;
}
bcm_object_add_list(&dbgobj_objhead, &dbgobj_objtail, dbgobj,
BCM_OBJDBG_ADDTOTAIL);
dbgobj_count++;
} else if (opt == BCM_OBJDBG_REMOVE) {
dbgobj = dbgobj_objtail;
while (dbgobj) {
if (dbgobj->obj == obj) {
if (dbgobj->flag) {
printf("%s: rm flagged obj %p flag 0x%08x from %s(%d)\n",
__FUNCTION__, obj, dbgobj->flag, caller, line);
}
bcm_object_rm_list(&dbgobj_objhead, &dbgobj_objtail, dbgobj);
memset(dbgobj->caller, 0x00, BCM_OBJDBG_CALLER_LEN);
strncpy(dbgobj->caller, caller, BCM_OBJDBG_CALLER_LEN);
dbgobj->caller[BCM_OBJDBG_CALLER_LEN-1] = '\0';
dbgobj->line = line;
bcm_object_add_list(&dbgobj_freehead, &dbgobj_freetail, dbgobj,
BCM_OBJDBG_ADDTOTAIL);
dbgobj_count--;
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
dbgobj = dbgobj_freetail;
while (dbgobj && dbgobj->obj) {
if (dbgobj->obj == obj) {
printf("%s: obj %p already freed from from %s(%d),"
" try free again from %s(%d)\n",
__FUNCTION__, obj,
dbgobj->caller, dbgobj->line,
caller, line);
//ASSERT(0); /* release same obj more than one time? */
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_freetail)
break;
}
printf("%s: ################### release none-existing obj %p from %s(%d)\n",
__FUNCTION__, obj, caller, line);
//ASSERT(0); /* release same obj more than one time? */
}
EXIT:
BCM_OBJDBG_UNLOCK(&dbgobj_lock, flags);
return;
}
void
bcm_object_trace_upd(void *obj, void *obj_new)
{
struct bcm_dbgobj *dbgobj;
unsigned long flags;
BCM_REFERENCE(flags);
BCM_OBJDBG_LOCK(&dbgobj_lock, flags);
dbgobj = dbgobj_objtail;
while (dbgobj) {
if (dbgobj->obj == obj) {
dbgobj->obj = obj_new;
if (dbgobj != dbgobj_objtail) {
bcm_object_movetoend(&dbgobj_objhead, &dbgobj_objtail,
dbgobj, BCM_OBJDBG_ADDTOTAIL);
}
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
EXIT:
BCM_OBJDBG_UNLOCK(&dbgobj_lock, flags);
return;
}
void
bcm_object_trace_chk(void *obj, uint32 chksn, uint32 sn,
const char *caller, int line)
{
struct bcm_dbgobj *dbgobj;
unsigned long flags;
BCM_REFERENCE(flags);
BCM_OBJDBG_LOCK(&dbgobj_lock, flags);
dbgobj = dbgobj_objtail;
while (dbgobj) {
if ((dbgobj->obj == obj) &&
((!chksn) || (dbgobj->obj_sn == sn))) {
if (dbgobj != dbgobj_objtail) {
bcm_object_movetoend(&dbgobj_objhead, &dbgobj_objtail,
dbgobj, BCM_OBJDBG_ADDTOTAIL);
}
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
dbgobj = dbgobj_freetail;
while (dbgobj) {
if ((dbgobj->obj == obj) &&
((!chksn) || (dbgobj->obj_sn == sn))) {
printf("%s: (%s:%d) obj %p (sn %d state %d) was freed from %s(%d)\n",
__FUNCTION__, caller, line,
dbgobj->obj, dbgobj->obj_sn, dbgobj->obj_state,
dbgobj->caller, dbgobj->line);
goto EXIT;
}
else if (dbgobj->obj == NULL) {
break;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_freetail)
break;
}
printf("%s: obj %p not found, check from %s(%d), chksn %s, sn %d\n",
__FUNCTION__, obj, caller, line, chksn ? "yes" : "no", sn);
dbgobj = dbgobj_objtail;
while (dbgobj) {
printf("%s: (%s:%d) obj %p sn %d was allocated from %s(%d)\n",
__FUNCTION__, caller, line,
dbgobj->obj, dbgobj->obj_sn, dbgobj->caller, dbgobj->line);
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
EXIT:
BCM_OBJDBG_UNLOCK(&dbgobj_lock, flags);
return;
}
void
bcm_object_feature_set(void *obj, uint32 type, uint32 value)
{
struct bcm_dbgobj *dbgobj;
unsigned long flags;
BCM_REFERENCE(flags);
BCM_OBJDBG_LOCK(&dbgobj_lock, flags);
dbgobj = dbgobj_objtail;
while (dbgobj) {
if (dbgobj->obj == obj) {
if (type == BCM_OBJECT_FEATURE_FLAG) {
if (value & BCM_OBJECT_FEATURE_CLEAR)
dbgobj->flag &= ~(value);
else
dbgobj->flag |= (value);
} else if (type == BCM_OBJECT_FEATURE_PKT_STATE) {
dbgobj->obj_state = value;
}
if (dbgobj != dbgobj_objtail) {
bcm_object_movetoend(&dbgobj_objhead, &dbgobj_objtail,
dbgobj, BCM_OBJDBG_ADDTOTAIL);
}
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
printf("%s: obj %p not found in active list\n", __FUNCTION__, obj);
ASSERT(0);
EXIT:
BCM_OBJDBG_UNLOCK(&dbgobj_lock, flags);
return;
}
int
bcm_object_feature_get(void *obj, uint32 type, uint32 value)
{
int rtn = 0;
struct bcm_dbgobj *dbgobj;
unsigned long flags;
BCM_REFERENCE(flags);
BCM_OBJDBG_LOCK(&dbgobj_lock, flags);
dbgobj = dbgobj_objtail;
while (dbgobj) {
if (dbgobj->obj == obj) {
if (type == BCM_OBJECT_FEATURE_FLAG) {
rtn = (dbgobj->flag & value) & (~BCM_OBJECT_FEATURE_CLEAR);
}
if (dbgobj != dbgobj_objtail) {
bcm_object_movetoend(&dbgobj_objhead, &dbgobj_objtail,
dbgobj, BCM_OBJDBG_ADDTOTAIL);
}
goto EXIT;
}
dbgobj = dbgobj->prior;
if (dbgobj == dbgobj_objtail)
break;
}
printf("%s: obj %p not found in active list\n", __FUNCTION__, obj);
ASSERT(0);
EXIT:
BCM_OBJDBG_UNLOCK(&dbgobj_lock, flags);
return rtn;
}
#endif /* BCM_OBJECT_TRACE */
uint8 *
bcm_write_tlv(int type, const void *data, int datalen, uint8 *dst)
{
uint8 *new_dst = dst;
bcm_tlv_t *dst_tlv = (bcm_tlv_t *)dst;
/* dst buffer should always be valid */
ASSERT(dst);
/* data len must be within valid range */
ASSERT((datalen >= 0) && (datalen <= BCM_TLV_MAX_DATA_SIZE));
/* source data buffer pointer should be valid, unless datalen is 0
* meaning no data with this TLV
*/
ASSERT((data != NULL) || (datalen == 0));
/* only do work if the inputs are valid
* - must have a dst to write to AND
* - datalen must be within range AND
* - the source data pointer must be non-NULL if datalen is non-zero
* (this last condition detects datalen > 0 with a NULL data pointer)
*/
if ((dst != NULL) &&
((datalen >= 0) && (datalen <= BCM_TLV_MAX_DATA_SIZE)) &&
((data != NULL) || (datalen == 0))) {
/* write type, len fields */
dst_tlv->id = (uint8)type;
dst_tlv->len = (uint8)datalen;
/* if data is present, copy to the output buffer and update
* pointer to output buffer
*/
if (datalen > 0) {
memcpy(dst_tlv->data, data, datalen);
}
/* update the output destination poitner to point past
* the TLV written
*/
new_dst = dst + BCM_TLV_HDR_SIZE + datalen;
}
return (new_dst);
}
uint8 *
bcm_write_tlv_safe(int type, const void *data, int datalen, uint8 *dst, int dst_maxlen)
{
uint8 *new_dst = dst;
if ((datalen >= 0) && (datalen <= BCM_TLV_MAX_DATA_SIZE)) {
/* if len + tlv hdr len is more than destlen, don't do anything
* just return the buffer untouched
*/
if ((int)(datalen + BCM_TLV_HDR_SIZE) <= dst_maxlen) {
new_dst = bcm_write_tlv(type, data, datalen, dst);
}
}
return (new_dst);
}
uint8 *
bcm_copy_tlv(const void *src, uint8 *dst)
{
uint8 *new_dst = dst;
const bcm_tlv_t *src_tlv = (const bcm_tlv_t *)src;
uint totlen;
ASSERT(dst && src);
if (dst && src) {
totlen = BCM_TLV_HDR_SIZE + src_tlv->len;
memcpy(dst, src_tlv, totlen);
new_dst = dst + totlen;
}
return (new_dst);
}
uint8 *bcm_copy_tlv_safe(const void *src, uint8 *dst, int dst_maxlen)
{
uint8 *new_dst = dst;
const bcm_tlv_t *src_tlv = (const bcm_tlv_t *)src;
ASSERT(src);
if (src) {
if (bcm_valid_tlv(src_tlv, dst_maxlen)) {
new_dst = bcm_copy_tlv(src, dst);
}
}
return (new_dst);
}
#if !defined(BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS)
/*******************************************************************************
* crc8
*
* Computes a crc8 over the input data using the polynomial:
*
* x^8 + x^7 +x^6 + x^4 + x^2 + 1
*
* The caller provides the initial value (either CRC8_INIT_VALUE
* or the previous returned value) to allow for processing of
* discontiguous blocks of data. When generating the CRC the
* caller is responsible for complementing the final return value
* and inserting it into the byte stream. When checking, a final
* return value of CRC8_GOOD_VALUE indicates a valid CRC.
*
* Reference: Dallas Semiconductor Application Note 27
* Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms",
* ver 3, Aug 1993, ross@guest.adelaide.edu.au, Rocksoft Pty Ltd.,
* ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt
*
* ****************************************************************************
*/
static const uint8 crc8_table[256] = {
0x00, 0xF7, 0xB9, 0x4E, 0x25, 0xD2, 0x9C, 0x6B,
0x4A, 0xBD, 0xF3, 0x04, 0x6F, 0x98, 0xD6, 0x21,
0x94, 0x63, 0x2D, 0xDA, 0xB1, 0x46, 0x08, 0xFF,
0xDE, 0x29, 0x67, 0x90, 0xFB, 0x0C, 0x42, 0xB5,
0x7F, 0x88, 0xC6, 0x31, 0x5A, 0xAD, 0xE3, 0x14,
0x35, 0xC2, 0x8C, 0x7B, 0x10, 0xE7, 0xA9, 0x5E,
0xEB, 0x1C, 0x52, 0xA5, 0xCE, 0x39, 0x77, 0x80,
0xA1, 0x56, 0x18, 0xEF, 0x84, 0x73, 0x3D, 0xCA,
0xFE, 0x09, 0x47, 0xB0, 0xDB, 0x2C, 0x62, 0x95,
0xB4, 0x43, 0x0D, 0xFA, 0x91, 0x66, 0x28, 0xDF,
0x6A, 0x9D, 0xD3, 0x24, 0x4F, 0xB8, 0xF6, 0x01,
0x20, 0xD7, 0x99, 0x6E, 0x05, 0xF2, 0xBC, 0x4B,
0x81, 0x76, 0x38, 0xCF, 0xA4, 0x53, 0x1D, 0xEA,
0xCB, 0x3C, 0x72, 0x85, 0xEE, 0x19, 0x57, 0xA0,
0x15, 0xE2, 0xAC, 0x5B, 0x30, 0xC7, 0x89, 0x7E,
0x5F, 0xA8, 0xE6, 0x11, 0x7A, 0x8D, 0xC3, 0x34,
0xAB, 0x5C, 0x12, 0xE5, 0x8E, 0x79, 0x37, 0xC0,
0xE1, 0x16, 0x58, 0xAF, 0xC4, 0x33, 0x7D, 0x8A,
0x3F, 0xC8, 0x86, 0x71, 0x1A, 0xED, 0xA3, 0x54,
0x75, 0x82, 0xCC, 0x3B, 0x50, 0xA7, 0xE9, 0x1E,
0xD4, 0x23, 0x6D, 0x9A, 0xF1, 0x06, 0x48, 0xBF,
0x9E, 0x69, 0x27, 0xD0, 0xBB, 0x4C, 0x02, 0xF5,
0x40, 0xB7, 0xF9, 0x0E, 0x65, 0x92, 0xDC, 0x2B,
0x0A, 0xFD, 0xB3, 0x44, 0x2F, 0xD8, 0x96, 0x61,
0x55, 0xA2, 0xEC, 0x1B, 0x70, 0x87, 0xC9, 0x3E,
0x1F, 0xE8, 0xA6, 0x51, 0x3A, 0xCD, 0x83, 0x74,
0xC1, 0x36, 0x78, 0x8F, 0xE4, 0x13, 0x5D, 0xAA,
0x8B, 0x7C, 0x32, 0xC5, 0xAE, 0x59, 0x17, 0xE0,
0x2A, 0xDD, 0x93, 0x64, 0x0F, 0xF8, 0xB6, 0x41,
0x60, 0x97, 0xD9, 0x2E, 0x45, 0xB2, 0xFC, 0x0B,
0xBE, 0x49, 0x07, 0xF0, 0x9B, 0x6C, 0x22, 0xD5,
0xF4, 0x03, 0x4D, 0xBA, 0xD1, 0x26, 0x68, 0x9F
};
#define CRC_INNER_LOOP(n, c, x) \
(c) = ((c) >> 8) ^ crc##n##_table[((c) ^ (x)) & 0xff]
uint8
hndcrc8(
uint8 *pdata, /* pointer to array of data to process */
uint nbytes, /* number of input data bytes to process */
uint8 crc /* either CRC8_INIT_VALUE or previous return value */
)
{
/* hard code the crc loop instead of using CRC_INNER_LOOP macro
* to avoid the undefined and unnecessary (uint8 >> 8) operation.
*/
while (nbytes-- > 0)
crc = crc8_table[(crc ^ *pdata++) & 0xff];
return crc;
}
/*******************************************************************************
* crc16
*
* Computes a crc16 over the input data using the polynomial:
*
* x^16 + x^12 +x^5 + 1
*
* The caller provides the initial value (either CRC16_INIT_VALUE
* or the previous returned value) to allow for processing of
* discontiguous blocks of data. When generating the CRC the
* caller is responsible for complementing the final return value
* and inserting it into the byte stream. When checking, a final
* return value of CRC16_GOOD_VALUE indicates a valid CRC.
*
* Reference: Dallas Semiconductor Application Note 27
* Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms",
* ver 3, Aug 1993, ross@guest.adelaide.edu.au, Rocksoft Pty Ltd.,
* ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt
*
* ****************************************************************************
*/
static const uint16 crc16_table[256] = {
0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78
};
uint16
hndcrc16(
uint8 *pdata, /* pointer to array of data to process */
uint nbytes, /* number of input data bytes to process */
uint16 crc /* either CRC16_INIT_VALUE or previous return value */
)
{
while (nbytes-- > 0)
CRC_INNER_LOOP(16, crc, *pdata++);
return crc;
}
static const uint32 crc32_table[256] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
/*
* crc input is CRC32_INIT_VALUE for a fresh start, or previous return value if
* accumulating over multiple pieces.
*/
uint32
hndcrc32(uint8 *pdata, uint nbytes, uint32 crc)
{
uint8 *pend;
pend = pdata + nbytes;
while (pdata < pend)
CRC_INNER_LOOP(32, crc, *pdata++);
return crc;
}
#ifdef notdef
#define CLEN 1499 /* CRC Length */
#define CBUFSIZ (CLEN+4)
#define CNBUFS 5 /* # of bufs */
void
testcrc32(void)
{
uint j, k, l;
uint8 *buf;
uint len[CNBUFS];
uint32 crcr;
uint32 crc32tv[CNBUFS] =
{0xd2cb1faa, 0xd385c8fa, 0xf5b4f3f3, 0x55789e20, 0x00343110};
ASSERT((buf = MALLOC(CBUFSIZ*CNBUFS)) != NULL);
/* step through all possible alignments */
for (l = 0; l <= 4; l++) {
for (j = 0; j < CNBUFS; j++) {
len[j] = CLEN;
for (k = 0; k < len[j]; k++)
*(buf + j*CBUFSIZ + (k+l)) = (j+k) & 0xff;
}
for (j = 0; j < CNBUFS; j++) {
crcr = crc32(buf + j*CBUFSIZ + l, len[j], CRC32_INIT_VALUE);
ASSERT(crcr == crc32tv[j]);
}
}
MFREE(buf, CBUFSIZ*CNBUFS);
return;
}
#endif /* notdef */
/*
* Advance from the current 1-byte tag/1-byte length/variable-length value
* triple, to the next, returning a pointer to the next.
* If the current or next TLV is invalid (does not fit in given buffer length),
* NULL is returned.
* *buflen is not modified if the TLV elt parameter is invalid, or is decremented
* by the TLV parameter's length if it is valid.
*/
bcm_tlv_t *
bcm_next_tlv(bcm_tlv_t *elt, int *buflen)
{
int len;
/* validate current elt */
if (!bcm_valid_tlv(elt, *buflen)) {
return NULL;
}
/* advance to next elt */
len = elt->len;
elt = (bcm_tlv_t*)(elt->data + len);
*buflen -= (TLV_HDR_LEN + len);
/* validate next elt */
if (!bcm_valid_tlv(elt, *buflen)) {
return NULL;
}
return elt;
}
/*
* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
*/
bcm_tlv_t *
bcm_parse_tlvs(void *buf, int buflen, uint key)
{
bcm_tlv_t *elt;
int totlen;
if ((elt = (bcm_tlv_t*)buf) == NULL) {
return NULL;
}
totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
int len = elt->len;
/* validate remaining totlen */
if ((elt->id == key) && (totlen >= (int)(len + TLV_HDR_LEN))) {
return (elt);
}
elt = (bcm_tlv_t*)((uint8*)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
/*
* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
* return NULL if not found or length field < min_varlen
*/
bcm_tlv_t *
bcm_parse_tlvs_min_bodylen(void *buf, int buflen, uint key, int min_bodylen)
{
bcm_tlv_t * ret = bcm_parse_tlvs(buf, buflen, key);
if (ret == NULL || ret->len < min_bodylen) {
return NULL;
}
return ret;
}
/*
* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag. Stop parsing when we see an element whose ID is greater
* than the target key.
*/
bcm_tlv_t *
bcm_parse_ordered_tlvs(void *buf, int buflen, uint key)
{
bcm_tlv_t *elt;
int totlen;
elt = (bcm_tlv_t*)buf;
totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
uint id = elt->id;
int len = elt->len;
/* Punt if we start seeing IDs > than target key */
if (id > key) {
return (NULL);
}
/* validate remaining totlen */
if ((id == key) && (totlen >= (int)(len + TLV_HDR_LEN))) {
return (elt);
}
elt = (bcm_tlv_t*)((uint8*)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
#endif /* !BCMROMOFFLOAD_EXCLUDE_BCMUTILS_FUNCS */
#if defined(WLMSG_PRHDRS) || defined(WLMSG_PRPKT) || defined(WLMSG_ASSOC) || \
defined(DHD_DEBUG)
int
bcm_format_field(const bcm_bit_desc_ex_t *bd, uint32 flags, char* buf, int len)
{
int i, slen = 0;
uint32 bit, mask;
const char *name;
mask = bd->mask;
if (len < 2 || !buf)
return 0;
buf[0] = '\0';
for (i = 0; (name = bd->bitfield[i].name) != NULL; i++) {
bit = bd->bitfield[i].bit;
if ((flags & mask) == bit) {
if (len > (int)strlen(name)) {
slen = strlen(name);
strncpy(buf, name, slen+1);
}
break;
}
}
return slen;
}
int
bcm_format_flags(const bcm_bit_desc_t *bd, uint32 flags, char* buf, int len)
{
int i;
char* p = buf;
char hexstr[16];
int slen = 0, nlen = 0;
uint32 bit;
const char* name;
if (len < 2 || !buf)
return 0;
buf[0] = '\0';
for (i = 0; flags != 0; i++) {
bit = bd[i].bit;
name = bd[i].name;
if (bit == 0 && flags != 0) {
/* print any unnamed bits */
snprintf(hexstr, 16, "0x%X", flags);
name = hexstr;
flags = 0; /* exit loop */
} else if ((flags & bit) == 0)
continue;
flags &= ~bit;
nlen = strlen(name);
slen += nlen;
/* count btwn flag space */
if (flags != 0)
slen += 1;
/* need NULL char as well */
if (len <= slen)
break;
/* copy NULL char but don't count it */
strncpy(p, name, nlen + 1);
p += nlen;
/* copy btwn flag space and NULL char */
if (flags != 0)
p += snprintf(p, 2, " ");
}
/* indicate the str was too short */
if (flags != 0) {
p += snprintf(p, 2, ">");
}
return (int)(p - buf);
}
#endif
/* print bytes formatted as hex to a string. return the resulting string length */
int
bcm_format_hex(char *str, const void *bytes, int len)
{
int i;
char *p = str;
const uint8 *src = (const uint8*)bytes;
for (i = 0; i < len; i++) {
p += snprintf(p, 3, "%02X", *src);
src++;
}
return (int)(p - str);
}
/* pretty hex print a contiguous buffer */
void
prhex(const char *msg, uchar *buf, uint nbytes)
{
char line[128], *p;
int len = sizeof(line);
int nchar;
uint i;
if (msg && (msg[0] != '\0'))
printf("%s:\n", msg);
p = line;
for (i = 0; i < nbytes; i++) {
if (i % 16 == 0) {
nchar = snprintf(p, len, " %04x: ", i); /* line prefix */
p += nchar;
len -= nchar;
}
if (len > 0) {
nchar = snprintf(p, len, "%02x ", buf[i]);
p += nchar;
len -= nchar;
}
if (i % 16 == 15) {
printf("%s\n", line); /* flush line */
p = line;
len = sizeof(line);
}
}
/* flush last partial line */
if (p != line)
printf("%s\n", line);
}
static const char *crypto_algo_names[] = {
"NONE",
"WEP1",
"TKIP",
"WEP128",
"AES_CCM",
"AES_OCB_MSDU",
"AES_OCB_MPDU",
#ifdef BCMCCX
"CKIP",
"CKIP_MMH",
"WEP_MMH",
"NALG",
#else
"NALG",
"UNDEF",
"UNDEF",
"UNDEF",
#endif /* BCMCCX */
#ifdef BCMWAPI_WAI
"WAPI",
#else
"UNDEF"
#endif
"PMK",
"BIP",
"AES_GCM",
"AES_CCM256",
"AES_GCM256",
"BIP_CMAC256",
"BIP_GMAC",
"BIP_GMAC256",
"UNDEF"
};
const char *
bcm_crypto_algo_name(uint algo)
{
return (algo < ARRAYSIZE(crypto_algo_names)) ? crypto_algo_names[algo] : "ERR";
}
char *
bcm_chipname(uint chipid, char *buf, uint len)
{
const char *fmt;
fmt = ((chipid > 0xa000) || (chipid < 0x4000)) ? "%d" : "%x";
snprintf(buf, len, fmt, chipid);
return buf;
}
/* Produce a human-readable string for boardrev */
char *
bcm_brev_str(uint32 brev, char *buf)
{
if (brev < 0x100)
snprintf(buf, 8, "%d.%d", (brev & 0xf0) >> 4, brev & 0xf);
else
snprintf(buf, 8, "%c%03x", ((brev & 0xf000) == 0x1000) ? 'P' : 'A', brev & 0xfff);
return (buf);
}
#define BUFSIZE_TODUMP_ATONCE 512 /* Buffer size */
/* dump large strings to console */
void
printbig(char *buf)
{
uint len, max_len;
char c;
len = (uint)strlen(buf);
max_len = BUFSIZE_TODUMP_ATONCE;
while (len > max_len) {
c = buf[max_len];
buf[max_len] = '\0';
printf("%s", buf);
buf[max_len] = c;
buf += max_len;
len -= max_len;
}
/* print the remaining string */
printf("%s\n", buf);
return;
}
/* routine to dump fields in a fileddesc structure */
uint
bcmdumpfields(bcmutl_rdreg_rtn read_rtn, void *arg0, uint arg1, struct fielddesc *fielddesc_array,
char *buf, uint32 bufsize)
{
uint filled_len;
int len;
struct fielddesc *cur_ptr;
filled_len = 0;
cur_ptr = fielddesc_array;
while (bufsize > 1) {
if (cur_ptr->nameandfmt == NULL)
break;
len = snprintf(buf, bufsize, cur_ptr->nameandfmt,
read_rtn(arg0, arg1, cur_ptr->offset));
/* check for snprintf overflow or error */
if (len < 0 || (uint32)len >= bufsize)
len = bufsize - 1;
buf += len;
bufsize -= len;
filled_len += len;
cur_ptr++;
}
return filled_len;
}
uint
bcm_mkiovar(const char *name, char *data, uint datalen, char *buf, uint buflen)
{
uint len;
len = (uint)strlen(name) + 1;
if ((len + datalen) > buflen)
return 0;
strncpy(buf, name, buflen);
/* append data onto the end of the name string */
memcpy(&buf[len], data, datalen);
len += datalen;
return len;
}
/* Quarter dBm units to mW
* Table starts at QDBM_OFFSET, so the first entry is mW for qdBm=153
* Table is offset so the last entry is largest mW value that fits in
* a uint16.
*/
#define QDBM_OFFSET 153 /* Offset for first entry */
#define QDBM_TABLE_LEN 40 /* Table size */
/* Smallest mW value that will round up to the first table entry, QDBM_OFFSET.
* Value is ( mW(QDBM_OFFSET - 1) + mW(QDBM_OFFSET) ) / 2
*/
#define QDBM_TABLE_LOW_BOUND 6493 /* Low bound */
/* Largest mW value that will round down to the last table entry,
* QDBM_OFFSET + QDBM_TABLE_LEN-1.
* Value is ( mW(QDBM_OFFSET + QDBM_TABLE_LEN - 1) + mW(QDBM_OFFSET + QDBM_TABLE_LEN) ) / 2.
*/
#define QDBM_TABLE_HIGH_BOUND 64938 /* High bound */
static const uint16 nqdBm_to_mW_map[QDBM_TABLE_LEN] = {
/* qdBm: +0 +1 +2 +3 +4 +5 +6 +7 */
/* 153: */ 6683, 7079, 7499, 7943, 8414, 8913, 9441, 10000,
/* 161: */ 10593, 11220, 11885, 12589, 13335, 14125, 14962, 15849,
/* 169: */ 16788, 17783, 18836, 19953, 21135, 22387, 23714, 25119,
/* 177: */ 26607, 28184, 29854, 31623, 33497, 35481, 37584, 39811,
/* 185: */ 42170, 44668, 47315, 50119, 53088, 56234, 59566, 63096
};
uint16
bcm_qdbm_to_mw(uint8 qdbm)
{
uint factor = 1;
int idx = qdbm - QDBM_OFFSET;
if (idx >= QDBM_TABLE_LEN) {
/* clamp to max uint16 mW value */
return 0xFFFF;
}
/* scale the qdBm index up to the range of the table 0-40
* where an offset of 40 qdBm equals a factor of 10 mW.
*/
while (idx < 0) {
idx += 40;
factor *= 10;
}
/* return the mW value scaled down to the correct factor of 10,
* adding in factor/2 to get proper rounding.
*/
return ((nqdBm_to_mW_map[idx] + factor/2) / factor);
}
uint8
bcm_mw_to_qdbm(uint16 mw)
{
uint8 qdbm;
int offset;
uint mw_uint = mw;
uint boundary;
/* handle boundary case */
if (mw_uint <= 1)
return 0;
offset = QDBM_OFFSET;
/* move mw into the range of the table */
while (mw_uint < QDBM_TABLE_LOW_BOUND) {
mw_uint *= 10;
offset -= 40;
}
for (qdbm = 0; qdbm < QDBM_TABLE_LEN-1; qdbm++) {
boundary = nqdBm_to_mW_map[qdbm] + (nqdBm_to_mW_map[qdbm+1] -
nqdBm_to_mW_map[qdbm])/2;
if (mw_uint < boundary) break;
}
qdbm += (uint8)offset;
return (qdbm);
}
uint
bcm_bitcount(uint8 *bitmap, uint length)
{
uint bitcount = 0, i;
uint8 tmp;
for (i = 0; i < length; i++) {
tmp = bitmap[i];
while (tmp) {
bitcount++;
tmp &= (tmp - 1);
}
}
return bitcount;
}
#if defined(BCMDRIVER) || defined(WL_UNITTEST)
/* triggers bcm_bprintf to print to kernel log */
bool bcm_bprintf_bypass = FALSE;
/* Initialization of bcmstrbuf structure */
void
bcm_binit(struct bcmstrbuf *b, char *buf, uint size)
{
b->origsize = b->size = size;
b->origbuf = b->buf = buf;
}
/* Buffer sprintf wrapper to guard against buffer overflow */
int
bcm_bprintf(struct bcmstrbuf *b, const char *fmt, ...)
{
va_list ap;
int r;
va_start(ap, fmt);
r = vsnprintf(b->buf, b->size, fmt, ap);
if (bcm_bprintf_bypass == TRUE) {
printf(b->buf);
goto exit;
}
/* Non Ansi C99 compliant returns -1,
* Ansi compliant return r >= b->size,
* bcmstdlib returns 0, handle all
*/
/* r == 0 is also the case when strlen(fmt) is zero.
* typically the case when "" is passed as argument.
*/
if ((r == -1) || (r >= (int)b->size)) {
b->size = 0;
} else {
b->size -= r;
b->buf += r;
}
exit:
va_end(ap);
return r;
}
void
bcm_bprhex(struct bcmstrbuf *b, const char *msg, bool newline, const uint8 *buf, int len)
{
int i;
if (msg != NULL && msg[0] != '\0')
bcm_bprintf(b, "%s", msg);
for (i = 0; i < len; i ++)
bcm_bprintf(b, "%02X", buf[i]);
if (newline)
bcm_bprintf(b, "\n");
}
void
bcm_inc_bytes(uchar *num, int num_bytes, uint8 amount)
{
int i;
for (i = 0; i < num_bytes; i++) {
num[i] += amount;
if (num[i] >= amount)
break;
amount = 1;
}
}
int
bcm_cmp_bytes(const uchar *arg1, const uchar *arg2, uint8 nbytes)
{
int i;
for (i = nbytes - 1; i >= 0; i--) {
if (arg1[i] != arg2[i])
return (arg1[i] - arg2[i]);
}
return 0;
}
void
bcm_print_bytes(const char *name, const uchar *data, int len)
{
int i;
int per_line = 0;
printf("%s: %d \n", name ? name : "", len);
for (i = 0; i < len; i++) {
printf("%02x ", *data++);
per_line++;
if (per_line == 16) {
per_line = 0;
printf("\n");
}
}
printf("\n");
}
/* Look for vendor-specific IE with specified OUI and optional type */
bcm_tlv_t *
bcm_find_vendor_ie(void *tlvs, int tlvs_len, const char *voui, uint8 *type, int type_len)
{
bcm_tlv_t *ie;
uint8 ie_len;
ie = (bcm_tlv_t*)tlvs;
/* make sure we are looking at a valid IE */
if (ie == NULL || !bcm_valid_tlv(ie, tlvs_len)) {
return NULL;
}
/* Walk through the IEs looking for an OUI match */
do {
ie_len = ie->len;
if ((ie->id == DOT11_MNG_PROPR_ID) &&
(ie_len >= (DOT11_OUI_LEN + type_len)) &&
!bcmp(ie->data, voui, DOT11_OUI_LEN))
{
/* compare optional type */
if (type_len == 0 ||
!bcmp(&ie->data[DOT11_OUI_LEN], type, type_len)) {
return (ie); /* a match */
}
}
} while ((ie = bcm_next_tlv(ie, &tlvs_len)) != NULL);
return NULL;
}
#if defined(WLTINYDUMP) || defined(WLMSG_INFORM) || defined(WLMSG_ASSOC) || \
defined(WLMSG_PRPKT) || defined(WLMSG_WSEC)
#define SSID_FMT_BUF_LEN ((4 * DOT11_MAX_SSID_LEN) + 1)
int
bcm_format_ssid(char* buf, const uchar ssid[], uint ssid_len)
{
uint i, c;
char *p = buf;
char *endp = buf + SSID_FMT_BUF_LEN;
if (ssid_len > DOT11_MAX_SSID_LEN) ssid_len = DOT11_MAX_SSID_LEN;
for (i = 0; i < ssid_len; i++) {
c = (uint)ssid[i];
if (c == '\\') {
*p++ = '\\';
*p++ = '\\';
} else if (bcm_isprint((uchar)c)) {
*p++ = (char)c;
} else {
p += snprintf(p, (endp - p), "\\x%02X", c);
}
}
*p = '\0';
ASSERT(p < endp);
return (int)(p - buf);
}
#endif
#endif /* BCMDRIVER || WL_UNITTEST */
/*
* ProcessVars:Takes a buffer of "<var>=<value>\n" lines read from a file and ending in a NUL.
* also accepts nvram files which are already in the format of <var1>=<value>\0\<var2>=<value2>\0
* Removes carriage returns, empty lines, comment lines, and converts newlines to NULs.
* Shortens buffer as needed and pads with NULs. End of buffer is marked by two NULs.
*/
unsigned int
process_nvram_vars(char *varbuf, unsigned int len)
{
char *dp;
bool findNewline;
int column;
unsigned int buf_len, n;
unsigned int pad = 0;
dp = varbuf;
findNewline = FALSE;
column = 0;
for (n = 0; n < len; n++) {
if (varbuf[n] == '\r')
continue;
if (findNewline && varbuf[n] != '\n')
continue;
findNewline = FALSE;
if (varbuf[n] == '#') {
findNewline = TRUE;
continue;
}
if (varbuf[n] == '\n') {
if (column == 0)
continue;
*dp++ = 0;
column = 0;
continue;
}
*dp++ = varbuf[n];
column++;
}
buf_len = (unsigned int)(dp - varbuf);
if (buf_len % 4) {
pad = 4 - buf_len % 4;
if (pad && (buf_len + pad <= len)) {
buf_len += pad;
}
}
while (dp < varbuf + n)
*dp++ = 0;
return buf_len;
}
/* calculate a * b + c */
void
bcm_uint64_multiple_add(uint32* r_high, uint32* r_low, uint32 a, uint32 b, uint32 c)
{
#define FORMALIZE(var) {cc += (var & 0x80000000) ? 1 : 0; var &= 0x7fffffff;}
uint32 r1, r0;
uint32 a1, a0, b1, b0, t, cc = 0;
a1 = a >> 16;
a0 = a & 0xffff;
b1 = b >> 16;
b0 = b & 0xffff;
r0 = a0 * b0;
FORMALIZE(r0);
t = (a1 * b0) << 16;
FORMALIZE(t);
r0 += t;
FORMALIZE(r0);
t = (a0 * b1) << 16;
FORMALIZE(t);
r0 += t;
FORMALIZE(r0);
FORMALIZE(c);
r0 += c;
FORMALIZE(r0);
r0 |= (cc % 2) ? 0x80000000 : 0;
r1 = a1 * b1 + ((a1 * b0) >> 16) + ((b1 * a0) >> 16) + (cc / 2);
*r_high = r1;
*r_low = r0;
}
/* calculate a / b */
void
bcm_uint64_divide(uint32* r, uint32 a_high, uint32 a_low, uint32 b)
{
uint32 a1 = a_high, a0 = a_low, r0 = 0;
if (b < 2)
return;
while (a1 != 0) {
r0 += (0xffffffff / b) * a1;
bcm_uint64_multiple_add(&a1, &a0, ((0xffffffff % b) + 1) % b, a1, a0);
}
r0 += a0 / b;
*r = r0;
}
#ifndef setbit /* As in the header file */
#ifdef BCMUTILS_BIT_MACROS_USE_FUNCS
/* Set bit in byte array. */
void
setbit(void *array, uint bit)
{
((uint8 *)array)[bit / NBBY] |= 1 << (bit % NBBY);
}
/* Clear bit in byte array. */
void
clrbit(void *array, uint bit)
{
((uint8 *)array)[bit / NBBY] &= ~(1 << (bit % NBBY));
}
/* Test if bit is set in byte array. */
bool
isset(const void *array, uint bit)
{
return (((const uint8 *)array)[bit / NBBY] & (1 << (bit % NBBY)));
}
/* Test if bit is clear in byte array. */
bool
isclr(const void *array, uint bit)
{
return ((((const uint8 *)array)[bit / NBBY] & (1 << (bit % NBBY))) == 0);
}
#endif /* BCMUTILS_BIT_MACROS_USE_FUNCS */
#endif /* setbit */
void
set_bitrange(void *array, uint start, uint end, uint maxbit)
{
uint startbyte = start/NBBY;
uint endbyte = end/NBBY;
uint i, startbytelastbit, endbytestartbit;
if (end >= start) {
if (endbyte - startbyte > 1)
{
startbytelastbit = (startbyte+1)*NBBY - 1;
endbytestartbit = endbyte*NBBY;
for (i = startbyte+1; i < endbyte; i++)
((uint8 *)array)[i] = 0xFF;
for (i = start; i <= startbytelastbit; i++)
setbit(array, i);
for (i = endbytestartbit; i <= end; i++)
setbit(array, i);
} else {
for (i = start; i <= end; i++)
setbit(array, i);
}
}
else {
set_bitrange(array, start, maxbit, maxbit);
set_bitrange(array, 0, end, maxbit);
}
}
void
bcm_bitprint32(const uint32 u32arg)
{
int i;
for (i = NBITS(uint32) - 1; i >= 0; i--) {
isbitset(u32arg, i) ? printf("1") : printf("0");
if ((i % NBBY) == 0) printf(" ");
}
printf("\n");
}
/* calculate checksum for ip header, tcp / udp header / data */
uint16
bcm_ip_cksum(uint8 *buf, uint32 len, uint32 sum)
{
while (len > 1) {
sum += (buf[0] << 8) | buf[1];
buf += 2;
len -= 2;
}
if (len > 0) {
sum += (*buf) << 8;
}
while (sum >> 16) {
sum = (sum & 0xffff) + (sum >> 16);
}
return ((uint16)~sum);
}
#if defined(BCMDRIVER) && !defined(_CFEZ_)
/*
* Hierarchical Multiword bitmap based small id allocator.
*
* Multilevel hierarchy bitmap. (maximum 2 levels)
* First hierarchy uses a multiword bitmap to identify 32bit words in the
* second hierarchy that have at least a single bit set. Each bit in a word of
* the second hierarchy represents a unique ID that may be allocated.
*
* BCM_MWBMAP_ITEMS_MAX: Maximum number of IDs managed.
* BCM_MWBMAP_BITS_WORD: Number of bits in a bitmap word word
* BCM_MWBMAP_WORDS_MAX: Maximum number of bitmap words needed for free IDs.
* BCM_MWBMAP_WDMAP_MAX: Maximum number of bitmap wordss identifying first non
* non-zero bitmap word carrying at least one free ID.
* BCM_MWBMAP_SHIFT_OP: Used in MOD, DIV and MUL operations.
* BCM_MWBMAP_INVALID_IDX: Value ~0U is treated as an invalid ID
*
* Design Notes:
* BCM_MWBMAP_USE_CNTSETBITS trades CPU for memory. A runtime count of how many
* bits are computed each time on allocation and deallocation, requiring 4
* array indexed access and 3 arithmetic operations. When not defined, a runtime
* count of set bits state is maintained. Upto 32 Bytes per 1024 IDs is needed.
* In a 4K max ID allocator, up to 128Bytes are hence used per instantiation.
* In a memory limited system e.g. dongle builds, a CPU for memory tradeoff may
* be used by defining BCM_MWBMAP_USE_CNTSETBITS.
*
* Note: wd_bitmap[] is statically declared and is not ROM friendly ... array
* size is fixed. No intention to support larger than 4K indice allocation. ID
* allocators for ranges smaller than 4K will have a wastage of only 12Bytes
* with savings in not having to use an indirect access, had it been dynamically
* allocated.
*/
#define BCM_MWBMAP_ITEMS_MAX (64 * 1024) /* May increase to 64K */
#define BCM_MWBMAP_BITS_WORD (NBITS(uint32))
#define BCM_MWBMAP_WORDS_MAX (BCM_MWBMAP_ITEMS_MAX / BCM_MWBMAP_BITS_WORD)
#define BCM_MWBMAP_WDMAP_MAX (BCM_MWBMAP_WORDS_MAX / BCM_MWBMAP_BITS_WORD)
#define BCM_MWBMAP_SHIFT_OP (5)
#define BCM_MWBMAP_MODOP(ix) ((ix) & (BCM_MWBMAP_BITS_WORD - 1))
#define BCM_MWBMAP_DIVOP(ix) ((ix) >> BCM_MWBMAP_SHIFT_OP)
#define BCM_MWBMAP_MULOP(ix) ((ix) << BCM_MWBMAP_SHIFT_OP)
/* Redefine PTR() and/or HDL() conversion to invoke audit for debugging */
#define BCM_MWBMAP_PTR(hdl) ((struct bcm_mwbmap *)(hdl))
#define BCM_MWBMAP_HDL(ptr) ((void *)(ptr))
#if defined(BCM_MWBMAP_DEBUG)
#define BCM_MWBMAP_AUDIT(mwb) \
do { \
ASSERT((mwb != NULL) && \
(((struct bcm_mwbmap *)(mwb))->magic == (void *)(mwb))); \
bcm_mwbmap_audit(mwb); \
} while (0)
#define MWBMAP_ASSERT(exp) ASSERT(exp)
#define MWBMAP_DBG(x) printf x
#else /* !BCM_MWBMAP_DEBUG */
#define BCM_MWBMAP_AUDIT(mwb) do {} while (0)
#define MWBMAP_ASSERT(exp) do {} while (0)
#define MWBMAP_DBG(x)
#endif /* !BCM_MWBMAP_DEBUG */
typedef struct bcm_mwbmap { /* Hierarchical multiword bitmap allocator */
uint16 wmaps; /* Total number of words in free wd bitmap */
uint16 imaps; /* Total number of words in free id bitmap */
int32 ifree; /* Count of free indices. Used only in audits */
uint16 total; /* Total indices managed by multiword bitmap */
void * magic; /* Audit handle parameter from user */
uint32 wd_bitmap[BCM_MWBMAP_WDMAP_MAX]; /* 1st level bitmap of */
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
int8 wd_count[BCM_MWBMAP_WORDS_MAX]; /* free id running count, 1st lvl */
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
uint32 id_bitmap[0]; /* Second level bitmap */
} bcm_mwbmap_t;
/* Incarnate a hierarchical multiword bitmap based small index allocator. */
struct bcm_mwbmap *
bcm_mwbmap_init(osl_t *osh, uint32 items_max)
{
struct bcm_mwbmap * mwbmap_p;
uint32 wordix, size, words, extra;
/* Implementation Constraint: Uses 32bit word bitmap */
MWBMAP_ASSERT(BCM_MWBMAP_BITS_WORD == 32U);
MWBMAP_ASSERT(BCM_MWBMAP_SHIFT_OP == 5U);
MWBMAP_ASSERT(ISPOWEROF2(BCM_MWBMAP_ITEMS_MAX));
MWBMAP_ASSERT((BCM_MWBMAP_ITEMS_MAX % BCM_MWBMAP_BITS_WORD) == 0U);
ASSERT(items_max <= BCM_MWBMAP_ITEMS_MAX);
/* Determine the number of words needed in the multiword bitmap */
extra = BCM_MWBMAP_MODOP(items_max);
words = BCM_MWBMAP_DIVOP(items_max) + ((extra != 0U) ? 1U : 0U);
/* Allocate runtime state of multiword bitmap */
/* Note: wd_count[] or wd_bitmap[] are not dynamically allocated */
size = sizeof(bcm_mwbmap_t) + (sizeof(uint32) * words);
mwbmap_p = (bcm_mwbmap_t *)MALLOC(osh, size);
if (mwbmap_p == (bcm_mwbmap_t *)NULL) {
ASSERT(0);
goto error1;
}
memset(mwbmap_p, 0, size);
/* Initialize runtime multiword bitmap state */
mwbmap_p->imaps = (uint16)words;
mwbmap_p->ifree = (int32)items_max;
mwbmap_p->total = (uint16)items_max;
/* Setup magic, for use in audit of handle */
mwbmap_p->magic = BCM_MWBMAP_HDL(mwbmap_p);
/* Setup the second level bitmap of free indices */
/* Mark all indices as available */
for (wordix = 0U; wordix < mwbmap_p->imaps; wordix++) {
mwbmap_p->id_bitmap[wordix] = (uint32)(~0U);
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
mwbmap_p->wd_count[wordix] = BCM_MWBMAP_BITS_WORD;
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
}
/* Ensure that extra indices are tagged as un-available */
if (extra) { /* fixup the free ids in last bitmap and wd_count */
uint32 * bmap_p = &mwbmap_p->id_bitmap[mwbmap_p->imaps - 1];
*bmap_p ^= (uint32)(~0U << extra); /* fixup bitmap */
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
mwbmap_p->wd_count[mwbmap_p->imaps - 1] = (int8)extra; /* fixup count */
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
}
/* Setup the first level bitmap hierarchy */
extra = BCM_MWBMAP_MODOP(mwbmap_p->imaps);
words = BCM_MWBMAP_DIVOP(mwbmap_p->imaps) + ((extra != 0U) ? 1U : 0U);
mwbmap_p->wmaps = (uint16)words;
for (wordix = 0U; wordix < mwbmap_p->wmaps; wordix++)
mwbmap_p->wd_bitmap[wordix] = (uint32)(~0U);
if (extra) {
uint32 * bmap_p = &mwbmap_p->wd_bitmap[mwbmap_p->wmaps - 1];
*bmap_p ^= (uint32)(~0U << extra); /* fixup bitmap */
}
return mwbmap_p;
error1:
return BCM_MWBMAP_INVALID_HDL;
}
/* Release resources used by multiword bitmap based small index allocator. */
void
bcm_mwbmap_fini(osl_t * osh, struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
MFREE(osh, mwbmap_p, sizeof(struct bcm_mwbmap)
+ (sizeof(uint32) * mwbmap_p->imaps));
return;
}
/* Allocate a unique small index using a multiword bitmap index allocator. */
uint32 BCMFASTPATH
bcm_mwbmap_alloc(struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
uint32 wordix, bitmap;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
/* Start with the first hierarchy */
for (wordix = 0; wordix < mwbmap_p->wmaps; ++wordix) {
bitmap = mwbmap_p->wd_bitmap[wordix]; /* get the word bitmap */
if (bitmap != 0U) {
uint32 count, bitix, *bitmap_p;
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
/* clear all except trailing 1 */
bitmap = (uint32)(((int)(bitmap)) & (-((int)(bitmap))));
MWBMAP_ASSERT(C_bcm_count_leading_zeros(bitmap) ==
bcm_count_leading_zeros(bitmap));
bitix = (BCM_MWBMAP_BITS_WORD - 1)
- bcm_count_leading_zeros(bitmap); /* use asm clz */
wordix = BCM_MWBMAP_MULOP(wordix) + bitix;
/* Clear bit if wd count is 0, without conditional branch */
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[wordix]) - 1;
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
mwbmap_p->wd_count[wordix]--;
count = mwbmap_p->wd_count[wordix];
MWBMAP_ASSERT(count ==
(bcm_cntsetbits(mwbmap_p->id_bitmap[wordix]) - 1));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
MWBMAP_ASSERT(count >= 0);
/* clear wd_bitmap bit if id_map count is 0 */
bitmap = (count == 0) << bitix;
MWBMAP_DBG((
"Lvl1: bitix<%02u> wordix<%02u>: %08x ^ %08x = %08x wfree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) ^ bitmap, count));
*bitmap_p ^= bitmap;
/* Use bitix in the second hierarchy */
bitmap_p = &mwbmap_p->id_bitmap[wordix];
bitmap = mwbmap_p->id_bitmap[wordix]; /* get the id bitmap */
MWBMAP_ASSERT(bitmap != 0U);
/* clear all except trailing 1 */
bitmap = (uint32)(((int)(bitmap)) & (-((int)(bitmap))));
MWBMAP_ASSERT(C_bcm_count_leading_zeros(bitmap) ==
bcm_count_leading_zeros(bitmap));
bitix = BCM_MWBMAP_MULOP(wordix)
+ (BCM_MWBMAP_BITS_WORD - 1)
- bcm_count_leading_zeros(bitmap); /* use asm clz */
mwbmap_p->ifree--; /* decrement system wide free count */
MWBMAP_ASSERT(mwbmap_p->ifree >= 0);
MWBMAP_DBG((
"Lvl2: bitix<%02u> wordix<%02u>: %08x ^ %08x = %08x ifree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) ^ bitmap,
mwbmap_p->ifree));
*bitmap_p ^= bitmap; /* mark as allocated = 1b0 */
return bitix;
}
}
ASSERT(mwbmap_p->ifree == 0);
return BCM_MWBMAP_INVALID_IDX;
}
/* Force an index at a specified position to be in use */
void
bcm_mwbmap_force(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix)
{
bcm_mwbmap_t * mwbmap_p;
uint32 count, wordix, bitmap, *bitmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(bitix < mwbmap_p->total);
/* Start with second hierarchy */
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap = (uint32)(1U << BCM_MWBMAP_MODOP(bitix));
bitmap_p = &mwbmap_p->id_bitmap[wordix];
ASSERT((*bitmap_p & bitmap) == bitmap);
mwbmap_p->ifree--; /* update free count */
ASSERT(mwbmap_p->ifree >= 0);
MWBMAP_DBG(("Lvl2: bitix<%u> wordix<%u>: %08x ^ %08x = %08x ifree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) ^ bitmap,
mwbmap_p->ifree));
*bitmap_p ^= bitmap; /* mark as in use */
/* Update first hierarchy */
bitix = wordix;
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
mwbmap_p->wd_count[bitix]--;
count = mwbmap_p->wd_count[bitix];
MWBMAP_ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
MWBMAP_ASSERT(count >= 0);
bitmap = (count == 0) << BCM_MWBMAP_MODOP(bitix);
MWBMAP_DBG(("Lvl1: bitix<%02lu> wordix<%02u>: %08x ^ %08x = %08x wfree %d",
BCM_MWBMAP_MODOP(bitix), wordix, *bitmap_p, bitmap,
(*bitmap_p) ^ bitmap, count));
*bitmap_p ^= bitmap; /* mark as in use */
return;
}
/* Free a previously allocated index back into the multiword bitmap allocator */
void BCMFASTPATH
bcm_mwbmap_free(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix)
{
bcm_mwbmap_t * mwbmap_p;
uint32 wordix, bitmap, *bitmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(bitix < mwbmap_p->total);
/* Start with second level hierarchy */
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap = (1U << BCM_MWBMAP_MODOP(bitix));
bitmap_p = &mwbmap_p->id_bitmap[wordix];
ASSERT((*bitmap_p & bitmap) == 0U); /* ASSERT not a double free */
mwbmap_p->ifree++; /* update free count */
ASSERT(mwbmap_p->ifree <= mwbmap_p->total);
MWBMAP_DBG(("Lvl2: bitix<%02u> wordix<%02u>: %08x | %08x = %08x ifree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) | bitmap,
mwbmap_p->ifree));
*bitmap_p |= bitmap; /* mark as available */
/* Now update first level hierarchy */
bitix = wordix;
wordix = BCM_MWBMAP_DIVOP(bitix); /* first level's word index */
bitmap = (1U << BCM_MWBMAP_MODOP(bitix));
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
#if !defined(BCM_MWBMAP_USE_CNTSETBITS)
mwbmap_p->wd_count[bitix]++;
#endif
#if defined(BCM_MWBMAP_DEBUG)
{
uint32 count;
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
count = mwbmap_p->wd_count[bitix];
MWBMAP_ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[bitix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
MWBMAP_ASSERT(count <= BCM_MWBMAP_BITS_WORD);
MWBMAP_DBG(("Lvl1: bitix<%02u> wordix<%02u>: %08x | %08x = %08x wfree %d",
bitix, wordix, *bitmap_p, bitmap, (*bitmap_p) | bitmap, count));
}
#endif /* BCM_MWBMAP_DEBUG */
*bitmap_p |= bitmap;
return;
}
/* Fetch the toal number of free indices in the multiword bitmap allocator */
uint32
bcm_mwbmap_free_cnt(struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(mwbmap_p->ifree >= 0);
return mwbmap_p->ifree;
}
/* Determine whether an index is inuse or free */
bool
bcm_mwbmap_isfree(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix)
{
bcm_mwbmap_t * mwbmap_p;
uint32 wordix, bitmap;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
ASSERT(bitix < mwbmap_p->total);
wordix = BCM_MWBMAP_DIVOP(bitix);
bitmap = (1U << BCM_MWBMAP_MODOP(bitix));
return ((mwbmap_p->id_bitmap[wordix] & bitmap) != 0U);
}
/* Debug dump a multiword bitmap allocator */
void
bcm_mwbmap_show(struct bcm_mwbmap * mwbmap_hdl)
{
uint32 ix, count;
bcm_mwbmap_t * mwbmap_p;
BCM_MWBMAP_AUDIT(mwbmap_hdl);
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
printf("mwbmap_p %p wmaps %u imaps %u ifree %d total %u\n", mwbmap_p,
mwbmap_p->wmaps, mwbmap_p->imaps, mwbmap_p->ifree, mwbmap_p->total);
for (ix = 0U; ix < mwbmap_p->wmaps; ix++) {
printf("\tWDMAP:%2u. 0x%08x\t", ix, mwbmap_p->wd_bitmap[ix]);
bcm_bitprint32(mwbmap_p->wd_bitmap[ix]);
printf("\n");
}
for (ix = 0U; ix < mwbmap_p->imaps; ix++) {
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[ix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
count = mwbmap_p->wd_count[ix];
MWBMAP_ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[ix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
printf("\tIDMAP:%2u. 0x%08x %02u\t", ix, mwbmap_p->id_bitmap[ix], count);
bcm_bitprint32(mwbmap_p->id_bitmap[ix]);
printf("\n");
}
return;
}
/* Audit a hierarchical multiword bitmap */
void
bcm_mwbmap_audit(struct bcm_mwbmap * mwbmap_hdl)
{
bcm_mwbmap_t * mwbmap_p;
uint32 count, free_cnt = 0U, wordix, idmap_ix, bitix, *bitmap_p;
mwbmap_p = BCM_MWBMAP_PTR(mwbmap_hdl);
for (wordix = 0U; wordix < mwbmap_p->wmaps; ++wordix) {
bitmap_p = &mwbmap_p->wd_bitmap[wordix];
for (bitix = 0U; bitix < BCM_MWBMAP_BITS_WORD; bitix++) {
if ((*bitmap_p) & (1 << bitix)) {
idmap_ix = BCM_MWBMAP_MULOP(wordix) + bitix;
#if defined(BCM_MWBMAP_USE_CNTSETBITS)
count = bcm_cntsetbits(mwbmap_p->id_bitmap[idmap_ix]);
#else /* ! BCM_MWBMAP_USE_CNTSETBITS */
count = mwbmap_p->wd_count[idmap_ix];
ASSERT(count == bcm_cntsetbits(mwbmap_p->id_bitmap[idmap_ix]));
#endif /* ! BCM_MWBMAP_USE_CNTSETBITS */
ASSERT(count != 0U);
free_cnt += count;
}
}
}
ASSERT((int)free_cnt == mwbmap_p->ifree);
}
/* END : Multiword bitmap based 64bit to Unique 32bit Id allocator. */
/* Simple 16bit Id allocator using a stack implementation. */
typedef struct id16_map {
uint32 failures; /* count of failures */
void *dbg; /* debug placeholder */
uint16 total; /* total number of ids managed by allocator */
uint16 start; /* start value of 16bit ids to be managed */
int stack_idx; /* index into stack of available ids */
uint16 stack[0]; /* stack of 16 bit ids */
} id16_map_t;
#define ID16_MAP_SZ(items) (sizeof(id16_map_t) + \
(sizeof(uint16) * (items)))
#if defined(BCM_DBG)
/* Uncomment BCM_DBG_ID16 to debug double free */
/* #define BCM_DBG_ID16 */
typedef struct id16_map_dbg {
uint16 total;
bool avail[0];
} id16_map_dbg_t;
#define ID16_MAP_DBG_SZ(items) (sizeof(id16_map_dbg_t) + \
(sizeof(bool) * (items)))
#define ID16_MAP_MSG(x) print x
#else
#define ID16_MAP_MSG(x)
#endif /* BCM_DBG */
void * /* Construct an id16 allocator: [start_val16 .. start_val16+total_ids) */
id16_map_init(osl_t *osh, uint16 total_ids, uint16 start_val16)
{
uint16 idx, val16;
id16_map_t * id16_map;
ASSERT(total_ids > 0);
/* A start_val16 of ID16_UNDEFINED, allows the caller to fill the id16 map
* with random values.
*/
ASSERT((start_val16 == ID16_UNDEFINED) ||
(start_val16 + total_ids) < ID16_INVALID);
id16_map = (id16_map_t *) MALLOC(osh, ID16_MAP_SZ(total_ids));
if (id16_map == NULL) {
return NULL;
}
id16_map->total = total_ids;
id16_map->start = start_val16;
id16_map->failures = 0;
id16_map->dbg = NULL;
/*
* Populate stack with 16bit id values, commencing with start_val16.
* if start_val16 is ID16_UNDEFINED, then do not populate the id16 map.
*/
id16_map->stack_idx = -1;
if (id16_map->start != ID16_UNDEFINED) {
val16 = start_val16;
for (idx = 0; idx < total_ids; idx++, val16++) {
id16_map->stack_idx = idx;
id16_map->stack[id16_map->stack_idx] = val16;
}
}
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->start != ID16_UNDEFINED) {
id16_map->dbg = MALLOC(osh, ID16_MAP_DBG_SZ(total_ids));
if (id16_map->dbg) {
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
id16_map_dbg->total = total_ids;
for (idx = 0; idx < total_ids; idx++) {
id16_map_dbg->avail[idx] = TRUE;
}
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
return (void *)id16_map;
}
void * /* Destruct an id16 allocator instance */
id16_map_fini(osl_t *osh, void * id16_map_hndl)
{
uint16 total_ids;
id16_map_t * id16_map;
if (id16_map_hndl == NULL)
return NULL;
id16_map = (id16_map_t *)id16_map_hndl;
total_ids = id16_map->total;
ASSERT(total_ids > 0);
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
MFREE(osh, id16_map->dbg, ID16_MAP_DBG_SZ(total_ids));
id16_map->dbg = NULL;
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
id16_map->total = 0;
MFREE(osh, id16_map, ID16_MAP_SZ(total_ids));
return NULL;
}
void
id16_map_clear(void * id16_map_hndl, uint16 total_ids, uint16 start_val16)
{
uint16 idx, val16;
id16_map_t * id16_map;
ASSERT(total_ids > 0);
/* A start_val16 of ID16_UNDEFINED, allows the caller to fill the id16 map
* with random values.
*/
ASSERT((start_val16 == ID16_UNDEFINED) ||
(start_val16 + total_ids) < ID16_INVALID);
id16_map = (id16_map_t *)id16_map_hndl;
if (id16_map == NULL) {
return;
}
id16_map->total = total_ids;
id16_map->start = start_val16;
id16_map->failures = 0;
/* Populate stack with 16bit id values, commencing with start_val16 */
id16_map->stack_idx = -1;
if (id16_map->start != ID16_UNDEFINED) {
val16 = start_val16;
for (idx = 0; idx < total_ids; idx++, val16++) {
id16_map->stack_idx = idx;
id16_map->stack[id16_map->stack_idx] = val16;
}
}
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->start != ID16_UNDEFINED) {
if (id16_map->dbg) {
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
id16_map_dbg->total = total_ids;
for (idx = 0; idx < total_ids; idx++) {
id16_map_dbg->avail[idx] = TRUE;
}
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
}
uint16 BCMFASTPATH /* Allocate a unique 16bit id */
id16_map_alloc(void * id16_map_hndl)
{
uint16 val16;
id16_map_t * id16_map;
ASSERT(id16_map_hndl != NULL);
id16_map = (id16_map_t *)id16_map_hndl;
ASSERT(id16_map->total > 0);
if (id16_map->stack_idx < 0) {
id16_map->failures++;
return ID16_INVALID;
}
val16 = id16_map->stack[id16_map->stack_idx];
id16_map->stack_idx--;
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
ASSERT((id16_map->start == ID16_UNDEFINED) ||
(val16 < (id16_map->start + id16_map->total)));
if (id16_map->dbg) { /* Validate val16 */
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
ASSERT(id16_map_dbg->avail[val16 - id16_map->start] == TRUE);
id16_map_dbg->avail[val16 - id16_map->start] = FALSE;
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
return val16;
}
void BCMFASTPATH /* Free a 16bit id value into the id16 allocator */
id16_map_free(void * id16_map_hndl, uint16 val16)
{
id16_map_t * id16_map;
ASSERT(id16_map_hndl != NULL);
id16_map = (id16_map_t *)id16_map_hndl;
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
ASSERT((id16_map->start == ID16_UNDEFINED) ||
(val16 < (id16_map->start + id16_map->total)));
if (id16_map->dbg) { /* Validate val16 */
id16_map_dbg_t *id16_map_dbg = (id16_map_dbg_t *)id16_map->dbg;
ASSERT(id16_map_dbg->avail[val16 - id16_map->start] == FALSE);
id16_map_dbg->avail[val16 - id16_map->start] = TRUE;
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
id16_map->stack_idx++;
id16_map->stack[id16_map->stack_idx] = val16;
}
uint32 /* Returns number of failures to allocate an unique id16 */
id16_map_failures(void * id16_map_hndl)
{
ASSERT(id16_map_hndl != NULL);
return ((id16_map_t *)id16_map_hndl)->failures;
}
bool
id16_map_audit(void * id16_map_hndl)
{
int idx;
int insane = 0;
id16_map_t * id16_map;
ASSERT(id16_map_hndl != NULL);
id16_map = (id16_map_t *)id16_map_hndl;
ASSERT(id16_map->stack_idx >= -1);
ASSERT(id16_map->stack_idx < (int)id16_map->total);
if (id16_map->start == ID16_UNDEFINED)
goto done;
for (idx = 0; idx <= id16_map->stack_idx; idx++) {
ASSERT(id16_map->stack[idx] >= id16_map->start);
ASSERT(id16_map->stack[idx] < (id16_map->start + id16_map->total));
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
uint16 val16 = id16_map->stack[idx];
if (((id16_map_dbg_t *)(id16_map->dbg))->avail[val16] != TRUE) {
insane |= 1;
ID16_MAP_MSG(("id16_map<%p>: stack_idx %u invalid val16 %u\n",
id16_map_hndl, idx, val16));
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
}
#if defined(BCM_DBG) && defined(BCM_DBG_ID16)
if (id16_map->dbg) {
uint16 avail = 0; /* Audit available ids counts */
for (idx = 0; idx < id16_map_dbg->total; idx++) {
if (((id16_map_dbg_t *)(id16_map->dbg))->avail[idx16] == TRUE)
avail++;
}
if (avail && (avail != (id16_map->stack_idx + 1))) {
insane |= 1;
ID16_MAP_MSG(("id16_map<%p>: avail %u stack_idx %u\n",
id16_map_hndl, avail, id16_map->stack_idx));
}
}
#endif /* BCM_DBG && BCM_DBG_ID16 */
done:
/* invoke any other system audits */
return (!!insane);
}
/* END: Simple id16 allocator */
#endif
/* calculate a >> b; and returns only lower 32 bits */
void
bcm_uint64_right_shift(uint32* r, uint32 a_high, uint32 a_low, uint32 b)
{
uint32 a1 = a_high, a0 = a_low, r0 = 0;
if (b == 0) {
r0 = a_low;
*r = r0;
return;
}
if (b < 32) {
a0 = a0 >> b;
a1 = a1 & ((1 << b) - 1);
a1 = a1 << (32 - b);
r0 = a0 | a1;
*r = r0;
return;
} else {
r0 = a1 >> (b - 32);
*r = r0;
return;
}
}
/* calculate a + b where a is a 64 bit number and b is a 32 bit number */
void
bcm_add_64(uint32* r_hi, uint32* r_lo, uint32 offset)
{
uint32 r1_lo = *r_lo;
(*r_lo) += offset;
if (*r_lo < r1_lo)
(*r_hi) ++;
}
/* calculate a - b where a is a 64 bit number and b is a 32 bit number */
void
bcm_sub_64(uint32* r_hi, uint32* r_lo, uint32 offset)
{
uint32 r1_lo = *r_lo;
(*r_lo) -= offset;
if (*r_lo > r1_lo)
(*r_hi) --;
}
#ifdef DEBUG_COUNTER
#if (OSL_SYSUPTIME_SUPPORT == TRUE)
void counter_printlog(counter_tbl_t *ctr_tbl)
{
uint32 now;
if (!ctr_tbl->enabled)
return;
now = OSL_SYSUPTIME();
if (now - ctr_tbl->prev_log_print > ctr_tbl->log_print_interval) {
uint8 i = 0;
printf("counter_print(%s %d):", ctr_tbl->name, now - ctr_tbl->prev_log_print);
for (i = 0; i < ctr_tbl->needed_cnt; i++) {
printf(" %u", ctr_tbl->cnt[i]);
}
printf("\n");
ctr_tbl->prev_log_print = now;
bzero(ctr_tbl->cnt, CNTR_TBL_MAX * sizeof(uint));
}
}
#else
/* OSL_SYSUPTIME is not supported so no way to get time */
#define counter_printlog(a) do {} while (0)
#endif /* OSL_SYSUPTIME_SUPPORT == TRUE */
#endif /* DEBUG_COUNTER */
#if defined(BCMDRIVER) && !defined(_CFEZ_)
void
dll_pool_detach(void * osh, dll_pool_t * pool, uint16 elems_max, uint16 elem_size)
{
uint32 mem_size;
mem_size = sizeof(dll_pool_t) + (elems_max * elem_size);
if (pool)
MFREE(osh, pool, mem_size);
}
dll_pool_t *
dll_pool_init(void * osh, uint16 elems_max, uint16 elem_size)
{
uint32 mem_size, i;
dll_pool_t * dll_pool_p;
dll_t * elem_p;
ASSERT(elem_size > sizeof(dll_t));
mem_size = sizeof(dll_pool_t) + (elems_max * elem_size);
if ((dll_pool_p = (dll_pool_t *)MALLOCZ(osh, mem_size)) == NULL) {
printf("dll_pool_init: elems_max<%u> elem_size<%u> malloc failure\n",
elems_max, elem_size);
ASSERT(0);
return dll_pool_p;
}
dll_init(&dll_pool_p->free_list);
dll_pool_p->elems_max = elems_max;
dll_pool_p->elem_size = elem_size;
elem_p = dll_pool_p->elements;
for (i = 0; i < elems_max; i++) {
dll_append(&dll_pool_p->free_list, elem_p);
elem_p = (dll_t *)((uintptr)elem_p + elem_size);
}
dll_pool_p->free_count = elems_max;
return dll_pool_p;
}
void *
dll_pool_alloc(dll_pool_t * dll_pool_p)
{
dll_t * elem_p;
if (dll_pool_p->free_count == 0) {
ASSERT(dll_empty(&dll_pool_p->free_list));
return NULL;
}
elem_p = dll_head_p(&dll_pool_p->free_list);
dll_delete(elem_p);
dll_pool_p->free_count -= 1;
return (void *)elem_p;
}
void
dll_pool_free(dll_pool_t * dll_pool_p, void * elem_p)
{
dll_t * node_p = (dll_t *)elem_p;
dll_prepend(&dll_pool_p->free_list, node_p);
dll_pool_p->free_count += 1;
}
void
dll_pool_free_tail(dll_pool_t * dll_pool_p, void * elem_p)
{
dll_t * node_p = (dll_t *)elem_p;
dll_append(&dll_pool_p->free_list, node_p);
dll_pool_p->free_count += 1;
}
#endif
| Fevax/exynos8890_stock | drivers/net/wireless/bcmdhd4359/bcmutils.c | C | gpl-2.0 | 90,245 |
<!--
@license
Copyright 2016 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.
-->
<script src="d3.js"></script>
| wangyum/tensorflow | tensorflow/tensorboard/components/tf_imports_d3v4/d3.html | HTML | apache-2.0 | 634 |
/* HORIZONTAL */
/* increase bottom margin to fit the pips */
.ui-slider-horizontal.ui-slider-pips {
margin-bottom: 1.4em;
}
/* default hide the labels and pips that arnt visible */
/* we just use css to hide incase we want to show certain */
/* labels/pips individually later */
.ui-slider-pips .ui-slider-label,
.ui-slider-pips .ui-slider-pip-hide {
display: none;
}
/* now we show any labels that we've set to show in the options */
.ui-slider-pips .ui-slider-pip-label .ui-slider-label {
display: block;
}
/* PIP/LABEL WRAPPER */
/* position each pip absolutely just below the default slider */
/* and also prevent accidental selection */
.ui-slider-pips .ui-slider-pip {
width: 2em;
height: 1em;
line-height: 1em;
position: absolute;
font-size: 0.8em;
color: #999;
overflow: visible;
text-align: center;
top: 20px;
left: 20px;
margin-left: -1em;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.ui-state-disabled.ui-slider-pips .ui-slider-pip {
cursor: default;
}
/* little pip/line position & size */
.ui-slider-pips .ui-slider-line {
background: #999;
width: 1px;
height: 3px;
position: absolute;
left: 50%;
}
/* the text label postion & size */
/* it overflows so no need for width to be accurate */
.ui-slider-pips .ui-slider-label {
position: absolute;
top: 5px;
left: 50%;
margin-left: -1em;
width: 2em;
}
/* make it easy to see when we hover a label */
.ui-slider-pips:not(.ui-slider-disabled) .ui-slider-pip:hover .ui-slider-label {
color: black;
font-weight: bold;
}
/* VERTICAL */
/* vertical slider needs right-margin, not bottom */
.ui-slider-vertical.ui-slider-pips {
margin-bottom: 1em;
margin-right: 2em;
}
/* align vertical pips left and to right of the slider */
.ui-slider-vertical.ui-slider-pips .ui-slider-pip {
text-align: left;
top: auto;
left: 20px;
margin-left: 0;
margin-bottom: -0.5em;
}
/* vertical line/pip should be horizontal instead */
.ui-slider-vertical.ui-slider-pips .ui-slider-line {
width: 3px;
height: 1px;
position: absolute;
top: 50%;
left: 0;
}
.ui-slider-vertical.ui-slider-pips .ui-slider-label {
top: 50%;
left: 0.5em;
margin-left: 0;
margin-top: -0.5em;
width: 2em;
}
/* FLOATING HORIZTONAL TOOLTIPS */
/* remove the godawful looking focus outline on handle and float */
.ui-slider-float .ui-slider-handle:focus,
.ui-slider-float .ui-slider-handle.ui-state-focus .ui-slider-tip-label,
.ui-slider-float .ui-slider-handle:focus .ui-slider-tip,
.ui-slider-float .ui-slider-handle.ui-state-focus .ui-slider-tip-label,
.ui-slider-float .ui-slider-handle:focus .ui-slider-tip-label
.ui-slider-float .ui-slider-handle.ui-state-focus .ui-slider-tip-label {
outline: none;
}
/* style tooltips on handles and on labels */
/* also has a nice transition */
.ui-slider-float .ui-slider-tip,
.ui-slider-float .ui-slider-tip-label {
position: absolute;
visibility: hidden;
top: -40px;
display: block;
width: 34px;
margin-left: -18px;
left: 50%;
height: 20px;
line-height: 20px;
background: white;
border-radius: 3px;
border: 1px solid #888;
text-align: center;
font-size: 12px;
opacity: 0;
color: #333;
-webkit-transition-property: opacity, top, visibility;
-moz-transition-property: opacity, top, visibility;
-ms-transition-property: opacity, top, visibility;
transition-property: opacity, top, visibility;
-webkit-transition-timing-function: ease-in;
-moz-transition-timing-function: ease-in;
-ms-transition-timing-function: ease-in;
transition-timing-function: ease-in;
-webkit-transition-duration: 200ms, 200ms, 0ms;
-moz-transition-duration: 200ms, 200ms, 0ms;
-ms-transition-duration: 200ms, 200ms, 0ms;
transition-duration: 200ms, 200ms, 0ms;
-webkit-transition-delay: 0ms, 0ms, 200ms;
-moz-transition-delay: 0ms, 0ms, 200ms;
-ms-transition-delay: 0ms, 0ms, 200ms;
transition-delay: 0ms, 0ms, 200ms;
}
/* show the tooltip on hover or focus */
/* also switch transition delay around */
.ui-slider-float .ui-slider-handle:hover .ui-slider-tip,
.ui-slider-float .ui-slider-handle.ui-state-hover .ui-slider-tip,
.ui-slider-float .ui-slider-handle:focus .ui-slider-tip,
.ui-slider-float .ui-slider-handle.ui-state-focus .ui-slider-tip,
.ui-slider-float .ui-slider-handle.ui-state-active .ui-slider-tip,
.ui-slider-float .ui-slider-pip:hover .ui-slider-tip-label {
opacity: 1;
top: -30px;
visibility: visible;
-webkit-transition-timing-function: ease-out;
-moz-transition-timing-function: ease-out;
-ms-transition-timing-function: ease-out;
transition-timing-function: ease-out;
-webkit-transition-delay:200ms, 200ms, 0ms;
-moz-transition-delay:200ms, 200ms, 0ms;
-ms-transition-delay:200ms, 200ms, 0ms;
transition-delay:200ms, 200ms, 0ms;
}
/* put label tooltips below slider */
.ui-slider-float .ui-slider-pip .ui-slider-tip-label {
top: 42px;
}
.ui-slider-float .ui-slider-pip:hover .ui-slider-tip-label {
top: 32px;
font-weight: normal;
}
/* give the tooltip a css triangle arrow */
.ui-slider-float .ui-slider-tip:after,
.ui-slider-float .ui-slider-pip .ui-slider-tip-label:after {
content: " ";
width: 0;
height: 0;
border: 5px solid rgba(255,255,255,0);
border-top-color: rgba(255,255,255,1);
position: absolute;
bottom: -10px;
left: 50%;
margin-left: -5px;
}
/* put a 1px border on the tooltip arrow to match tooltip border */
.ui-slider-float .ui-slider-tip:before,
.ui-slider-float .ui-slider-pip .ui-slider-tip-label:before {
content: " ";
width: 0;
height: 0;
border: 5px solid rgba(255,255,255,0);
border-top-color: #888;
position: absolute;
bottom: -11px;
left: 50%;
margin-left: -5px;
}
/* switch the arrow to top on labels */
.ui-slider-float .ui-slider-pip .ui-slider-tip-label:after {
border: 5px solid rgba(255,255,255,0);
border-bottom-color: rgba(255,255,255,1);
top: -10px;
}
.ui-slider-float .ui-slider-pip .ui-slider-tip-label:before {
border: 5px solid rgba(255,255,255,0);
border-bottom-color: #888;
top: -11px;
}
/* FLOATING VERTICAL TOOLTIPS */
/* tooltip floats to left of handle */
.ui-slider-vertical.ui-slider-float .ui-slider-tip,
.ui-slider-vertical.ui-slider-float .ui-slider-tip-label {
top: 50%;
margin-top: -11px;
width: 34px;
margin-left: 0px;
left: -60px;
color: #333;
-webkit-transition-duration: 200ms, 200ms, 0;
-moz-transition-duration: 200ms, 200ms, 0;
-ms-transition-duration: 200ms, 200ms, 0;
transition-duration: 200ms, 200ms, 0;
-webkit-transition-property: opacity, left, visibility;
-moz-transition-property: opacity, left, visibility;
-ms-transition-property: opacity, left, visibility;
transition-property: opacity, left, visibility;
-webkit-transition-delay: 0, 0, 200ms;
-moz-transition-delay: 0, 0, 200ms;
-ms-transition-delay: 0, 0, 200ms;
transition-delay: 0, 0, 200ms;
}
.ui-slider-vertical.ui-slider-float .ui-slider-handle:hover .ui-slider-tip,
.ui-slider-vertical.ui-slider-float .ui-slider-handle.ui-state-hover .ui-slider-tip,
.ui-slider-vertical.ui-slider-float .ui-slider-handle:focus .ui-slider-tip,
.ui-slider-vertical.ui-slider-float .ui-slider-handle.ui-state-focus .ui-slider-tip,
.ui-slider-vertical.ui-slider-float .ui-slider-handle.ui-state-active .ui-slider-tip,
.ui-slider-vertical.ui-slider-float .ui-slider-pip:hover .ui-slider-tip-label {
top: 50%;
margin-top: -11px;
left: -50px;
}
/* put label tooltips to right of slider */
.ui-slider-vertical.ui-slider-float .ui-slider-pip .ui-slider-tip-label {
left: 47px;
}
.ui-slider-vertical.ui-slider-float .ui-slider-pip:hover .ui-slider-tip-label {
left: 37px;
}
/* give the tooltip a css triangle arrow */
.ui-slider-vertical.ui-slider-float .ui-slider-tip:after,
.ui-slider-vertical.ui-slider-float .ui-slider-pip .ui-slider-tip-label:after {
border: 5px solid rgba(255,255,255,0);
border-left-color: rgba(255,255,255,1);
border-top-color: transparent;
position: absolute;
bottom: 50%;
margin-bottom: -5px;
right: -10px;
margin-left: 0;
top: auto;
left: auto;
}
.ui-slider-vertical.ui-slider-float .ui-slider-tip:before,
.ui-slider-vertical.ui-slider-float .ui-slider-pip .ui-slider-tip-label:before {
border: 5px solid rgba(255,255,255,0);
border-left-color: #888;
border-top-color: transparent;
position: absolute;
bottom: 50%;
margin-bottom: -5px;
right: -11px;
margin-left: 0;
top: auto;
left: auto;
}
.ui-slider-vertical.ui-slider-float .ui-slider-pip .ui-slider-tip-label:after {
border: 5px solid rgba(255,255,255,0);
border-right-color: rgba(255,255,255,1);
right: auto;
left: -10px;
}
.ui-slider-vertical.ui-slider-float .ui-slider-pip .ui-slider-tip-label:before {
border: 5px solid rgba(255,255,255,0);
border-right-color: #888;
right: auto;
left: -11px;
}
/* SELECTED STATES */
/* Comment out this chuck of code if you don't want to have
the new label colours shown */
.ui-slider-pips [class*=ui-slider-pip-initial] {
font-weight: bold;
color: #14CA82;
}
.ui-slider-pips .ui-slider-pip-initial-1 {
}
.ui-slider-pips .ui-slider-pip-initial-2 {
color: #1897C9;
}
.ui-slider-pips [class*=ui-slider-pip-selected] {
font-weight: bold;
color: #FF7A00;
}
.ui-slider-pips .ui-slider-pip-inrange {
color: black;
}
.ui-slider-pips .ui-slider-pip-selected-1 {
}
.ui-slider-pips .ui-slider-pip-selected-2 {
color: #E70081;
}
.ui-slider-pips [class*=ui-slider-pip-selected] .ui-slider-line,
.ui-slider-pips .ui-slider-pip-inrange .ui-slider-line {
background: black;
}
| Kangaroos/hystore | vendors/dashboard/js/plugins/jQuery-ui-Slider-Pips/jquery-ui-slider-pips.css | CSS | mit | 11,416 |
// SPDX-License-Identifier: GPL-2.0-only
/*
* QLogic iSCSI Offload Driver
* Copyright (c) 2016 Cavium Inc.
*/
#include "qedi.h"
#include "qedi_dbg.h"
#include <linux/uaccess.h>
#include <linux/debugfs.h>
#include <linux/module.h>
int qedi_do_not_recover;
static struct dentry *qedi_dbg_root;
void
qedi_dbg_host_init(struct qedi_dbg_ctx *qedi,
const struct qedi_debugfs_ops *dops,
const struct file_operations *fops)
{
char host_dirname[32];
sprintf(host_dirname, "host%u", qedi->host_no);
qedi->bdf_dentry = debugfs_create_dir(host_dirname, qedi_dbg_root);
while (dops) {
if (!(dops->name))
break;
debugfs_create_file(dops->name, 0600, qedi->bdf_dentry, qedi,
fops);
dops++;
fops++;
}
}
void
qedi_dbg_host_exit(struct qedi_dbg_ctx *qedi)
{
debugfs_remove_recursive(qedi->bdf_dentry);
qedi->bdf_dentry = NULL;
}
void
qedi_dbg_init(char *drv_name)
{
qedi_dbg_root = debugfs_create_dir(drv_name, NULL);
}
void
qedi_dbg_exit(void)
{
debugfs_remove_recursive(qedi_dbg_root);
qedi_dbg_root = NULL;
}
static ssize_t
qedi_dbg_do_not_recover_enable(struct qedi_dbg_ctx *qedi_dbg)
{
if (!qedi_do_not_recover)
qedi_do_not_recover = 1;
QEDI_INFO(qedi_dbg, QEDI_LOG_DEBUGFS, "do_not_recover=%d\n",
qedi_do_not_recover);
return 0;
}
static ssize_t
qedi_dbg_do_not_recover_disable(struct qedi_dbg_ctx *qedi_dbg)
{
if (qedi_do_not_recover)
qedi_do_not_recover = 0;
QEDI_INFO(qedi_dbg, QEDI_LOG_DEBUGFS, "do_not_recover=%d\n",
qedi_do_not_recover);
return 0;
}
static struct qedi_list_of_funcs qedi_dbg_do_not_recover_ops[] = {
{ "enable", qedi_dbg_do_not_recover_enable },
{ "disable", qedi_dbg_do_not_recover_disable },
{ NULL, NULL }
};
const struct qedi_debugfs_ops qedi_debugfs_ops[] = {
{ "gbl_ctx", NULL },
{ "do_not_recover", qedi_dbg_do_not_recover_ops},
{ "io_trace", NULL },
{ NULL, NULL }
};
static ssize_t
qedi_dbg_do_not_recover_cmd_write(struct file *filp, const char __user *buffer,
size_t count, loff_t *ppos)
{
size_t cnt = 0;
struct qedi_dbg_ctx *qedi_dbg =
(struct qedi_dbg_ctx *)filp->private_data;
struct qedi_list_of_funcs *lof = qedi_dbg_do_not_recover_ops;
if (*ppos)
return 0;
while (lof) {
if (!(lof->oper_str))
break;
if (!strncmp(lof->oper_str, buffer, strlen(lof->oper_str))) {
cnt = lof->oper_func(qedi_dbg);
break;
}
lof++;
}
return (count - cnt);
}
static ssize_t
qedi_dbg_do_not_recover_cmd_read(struct file *filp, char __user *buffer,
size_t count, loff_t *ppos)
{
size_t cnt = 0;
if (*ppos)
return 0;
cnt = sprintf(buffer, "do_not_recover=%d\n", qedi_do_not_recover);
cnt = min_t(int, count, cnt - *ppos);
*ppos += cnt;
return cnt;
}
static int
qedi_gbl_ctx_show(struct seq_file *s, void *unused)
{
struct qedi_fastpath *fp = NULL;
struct qed_sb_info *sb_info = NULL;
struct status_block_e4 *sb = NULL;
struct global_queue *que = NULL;
int id;
u16 prod_idx;
struct qedi_ctx *qedi = s->private;
unsigned long flags;
seq_puts(s, " DUMP CQ CONTEXT:\n");
for (id = 0; id < MIN_NUM_CPUS_MSIX(qedi); id++) {
spin_lock_irqsave(&qedi->hba_lock, flags);
seq_printf(s, "=========FAST CQ PATH [%d] ==========\n", id);
fp = &qedi->fp_array[id];
sb_info = fp->sb_info;
sb = sb_info->sb_virt;
prod_idx = (sb->pi_array[QEDI_PROTO_CQ_PROD_IDX] &
STATUS_BLOCK_E4_PROD_INDEX_MASK);
seq_printf(s, "SB PROD IDX: %d\n", prod_idx);
que = qedi->global_queues[fp->sb_id];
seq_printf(s, "DRV CONS IDX: %d\n", que->cq_cons_idx);
seq_printf(s, "CQ complete host memory: %d\n", fp->sb_id);
seq_puts(s, "=========== END ==================\n\n\n");
spin_unlock_irqrestore(&qedi->hba_lock, flags);
}
return 0;
}
static int
qedi_dbg_gbl_ctx_open(struct inode *inode, struct file *file)
{
struct qedi_dbg_ctx *qedi_dbg = inode->i_private;
struct qedi_ctx *qedi = container_of(qedi_dbg, struct qedi_ctx,
dbg_ctx);
return single_open(file, qedi_gbl_ctx_show, qedi);
}
static int
qedi_io_trace_show(struct seq_file *s, void *unused)
{
int id, idx = 0;
struct qedi_ctx *qedi = s->private;
struct qedi_io_log *io_log;
unsigned long flags;
seq_puts(s, " DUMP IO LOGS:\n");
spin_lock_irqsave(&qedi->io_trace_lock, flags);
idx = qedi->io_trace_idx;
for (id = 0; id < QEDI_IO_TRACE_SIZE; id++) {
io_log = &qedi->io_trace_buf[idx];
seq_printf(s, "iodir-%d:", io_log->direction);
seq_printf(s, "tid-0x%x:", io_log->task_id);
seq_printf(s, "cid-0x%x:", io_log->cid);
seq_printf(s, "lun-%d:", io_log->lun);
seq_printf(s, "op-0x%02x:", io_log->op);
seq_printf(s, "0x%02x%02x%02x%02x:", io_log->lba[0],
io_log->lba[1], io_log->lba[2], io_log->lba[3]);
seq_printf(s, "buflen-%d:", io_log->bufflen);
seq_printf(s, "sgcnt-%d:", io_log->sg_count);
seq_printf(s, "res-0x%08x:", io_log->result);
seq_printf(s, "jif-%lu:", io_log->jiffies);
seq_printf(s, "blk_req_cpu-%d:", io_log->blk_req_cpu);
seq_printf(s, "req_cpu-%d:", io_log->req_cpu);
seq_printf(s, "intr_cpu-%d:", io_log->intr_cpu);
seq_printf(s, "blk_rsp_cpu-%d\n", io_log->blk_rsp_cpu);
idx++;
if (idx == QEDI_IO_TRACE_SIZE)
idx = 0;
}
spin_unlock_irqrestore(&qedi->io_trace_lock, flags);
return 0;
}
static int
qedi_dbg_io_trace_open(struct inode *inode, struct file *file)
{
struct qedi_dbg_ctx *qedi_dbg = inode->i_private;
struct qedi_ctx *qedi = container_of(qedi_dbg, struct qedi_ctx,
dbg_ctx);
return single_open(file, qedi_io_trace_show, qedi);
}
const struct file_operations qedi_dbg_fops[] = {
qedi_dbg_fileops_seq(qedi, gbl_ctx),
qedi_dbg_fileops(qedi, do_not_recover),
qedi_dbg_fileops_seq(qedi, io_trace),
{ },
};
| CSE3320/kernel-code | linux-5.8/drivers/scsi/qedi/qedi_debugfs.c | C | gpl-2.0 | 5,629 |
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* Audio Codec driver supporting:
* AD1835A, AD1836, AD1837A, AD1838A, AD1839A
*
* Copyright 2009-2011 Analog Devices Inc.
*/
#ifndef __AD1836_H__
#define __AD1836_H__
#define AD1836_DAC_CTRL1 0
#define AD1836_DAC_POWERDOWN 2
#define AD1836_DAC_SERFMT_MASK 0xE0
#define AD1836_DAC_SERFMT_PCK256 (0x4 << 5)
#define AD1836_DAC_SERFMT_PCK128 (0x5 << 5)
#define AD1836_DAC_WORD_LEN_MASK 0x18
#define AD1836_DAC_WORD_LEN_OFFSET 3
#define AD1836_DAC_CTRL2 1
/* These macros are one-based. So AD183X_MUTE_LEFT(1) will return the mute bit
* for the first ADC/DAC */
#define AD1836_MUTE_LEFT(x) (((x) * 2) - 2)
#define AD1836_MUTE_RIGHT(x) (((x) * 2) - 1)
#define AD1836_DAC_L_VOL(x) ((x) * 2)
#define AD1836_DAC_R_VOL(x) (1 + ((x) * 2))
#define AD1836_ADC_CTRL1 12
#define AD1836_ADC_POWERDOWN 7
#define AD1836_ADC_HIGHPASS_FILTER 8
#define AD1836_ADC_CTRL2 13
#define AD1836_ADC_WORD_LEN_MASK 0x30
#define AD1836_ADC_WORD_OFFSET 4
#define AD1836_ADC_SERFMT_MASK (7 << 6)
#define AD1836_ADC_SERFMT_PCK256 (0x4 << 6)
#define AD1836_ADC_SERFMT_PCK128 (0x5 << 6)
#define AD1836_ADC_AUX (0x6 << 6)
#define AD1836_ADC_CTRL3 14
#define AD1836_NUM_REGS 16
#define AD1836_WORD_LEN_24 0x0
#define AD1836_WORD_LEN_20 0x1
#define AD1836_WORD_LEN_16 0x2
#endif
| Naoya-Horiguchi/linux | sound/soc/codecs/ad1836.h | C | gpl-2.0 | 1,498 |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Stereo and SAP detection for cx88
*
* Copyright (c) 2009 Marton Balint <cus@fazekas.hu>
*/
#include "cx88.h"
#include "cx88-reg.h"
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <asm/div64.h>
#define INT_PI ((s32)(3.141592653589 * 32768.0))
#define compat_remainder(a, b) \
((float)(((s32)((a) * 100)) % ((s32)((b) * 100))) / 100.0)
#define baseband_freq(carrier, srate, tone) ((s32)( \
(compat_remainder(carrier + tone, srate)) / srate * 2 * INT_PI))
/*
* We calculate the baseband frequencies of the carrier and the pilot tones
* based on the the sampling rate of the audio rds fifo.
*/
#define FREQ_A2_CARRIER baseband_freq(54687.5, 2689.36, 0.0)
#define FREQ_A2_DUAL baseband_freq(54687.5, 2689.36, 274.1)
#define FREQ_A2_STEREO baseband_freq(54687.5, 2689.36, 117.5)
/*
* The frequencies below are from the reference driver. They probably need
* further adjustments, because they are not tested at all. You may even need
* to play a bit with the registers of the chip to select the proper signal
* for the input of the audio rds fifo, and measure it's sampling rate to
* calculate the proper baseband frequencies...
*/
#define FREQ_A2M_CARRIER ((s32)(2.114516 * 32768.0))
#define FREQ_A2M_DUAL ((s32)(2.754916 * 32768.0))
#define FREQ_A2M_STEREO ((s32)(2.462326 * 32768.0))
#define FREQ_EIAJ_CARRIER ((s32)(1.963495 * 32768.0)) /* 5pi/8 */
#define FREQ_EIAJ_DUAL ((s32)(2.562118 * 32768.0))
#define FREQ_EIAJ_STEREO ((s32)(2.601053 * 32768.0))
#define FREQ_BTSC_DUAL ((s32)(1.963495 * 32768.0)) /* 5pi/8 */
#define FREQ_BTSC_DUAL_REF ((s32)(1.374446 * 32768.0)) /* 7pi/16 */
#define FREQ_BTSC_SAP ((s32)(2.471532 * 32768.0))
#define FREQ_BTSC_SAP_REF ((s32)(1.730072 * 32768.0))
/* The spectrum of the signal should be empty between these frequencies. */
#define FREQ_NOISE_START ((s32)(0.100000 * 32768.0))
#define FREQ_NOISE_END ((s32)(1.200000 * 32768.0))
static unsigned int dsp_debug;
module_param(dsp_debug, int, 0644);
MODULE_PARM_DESC(dsp_debug, "enable audio dsp debug messages");
#define dprintk(level, fmt, arg...) do { \
if (dsp_debug >= level) \
printk(KERN_DEBUG pr_fmt("%s: dsp:" fmt), \
__func__, ##arg); \
} while (0)
static s32 int_cos(u32 x)
{
u32 t2, t4, t6, t8;
s32 ret;
u16 period = x / INT_PI;
if (period % 2)
return -int_cos(x - INT_PI);
x = x % INT_PI;
if (x > INT_PI / 2)
return -int_cos(INT_PI / 2 - (x % (INT_PI / 2)));
/*
* Now x is between 0 and INT_PI/2.
* To calculate cos(x) we use it's Taylor polinom.
*/
t2 = x * x / 32768 / 2;
t4 = t2 * x / 32768 * x / 32768 / 3 / 4;
t6 = t4 * x / 32768 * x / 32768 / 5 / 6;
t8 = t6 * x / 32768 * x / 32768 / 7 / 8;
ret = 32768 - t2 + t4 - t6 + t8;
return ret;
}
static u32 int_goertzel(s16 x[], u32 N, u32 freq)
{
/*
* We use the Goertzel algorithm to determine the power of the
* given frequency in the signal
*/
s32 s_prev = 0;
s32 s_prev2 = 0;
s32 coeff = 2 * int_cos(freq);
u32 i;
u64 tmp;
u32 divisor;
for (i = 0; i < N; i++) {
s32 s = x[i] + ((s64)coeff * s_prev / 32768) - s_prev2;
s_prev2 = s_prev;
s_prev = s;
}
tmp = (s64)s_prev2 * s_prev2 + (s64)s_prev * s_prev -
(s64)coeff * s_prev2 * s_prev / 32768;
/*
* XXX: N must be low enough so that N*N fits in s32.
* Else we need two divisions.
*/
divisor = N * N;
do_div(tmp, divisor);
return (u32)tmp;
}
static u32 freq_magnitude(s16 x[], u32 N, u32 freq)
{
u32 sum = int_goertzel(x, N, freq);
return (u32)int_sqrt(sum);
}
static u32 noise_magnitude(s16 x[], u32 N, u32 freq_start, u32 freq_end)
{
int i;
u32 sum = 0;
u32 freq_step;
int samples = 5;
if (N > 192) {
/* The last 192 samples are enough for noise detection */
x += (N - 192);
N = 192;
}
freq_step = (freq_end - freq_start) / (samples - 1);
for (i = 0; i < samples; i++) {
sum += int_goertzel(x, N, freq_start);
freq_start += freq_step;
}
return (u32)int_sqrt(sum / samples);
}
static s32 detect_a2_a2m_eiaj(struct cx88_core *core, s16 x[], u32 N)
{
s32 carrier, stereo, dual, noise;
s32 carrier_freq, stereo_freq, dual_freq;
s32 ret;
switch (core->tvaudio) {
case WW_BG:
case WW_DK:
carrier_freq = FREQ_A2_CARRIER;
stereo_freq = FREQ_A2_STEREO;
dual_freq = FREQ_A2_DUAL;
break;
case WW_M:
carrier_freq = FREQ_A2M_CARRIER;
stereo_freq = FREQ_A2M_STEREO;
dual_freq = FREQ_A2M_DUAL;
break;
case WW_EIAJ:
carrier_freq = FREQ_EIAJ_CARRIER;
stereo_freq = FREQ_EIAJ_STEREO;
dual_freq = FREQ_EIAJ_DUAL;
break;
default:
pr_warn("unsupported audio mode %d for %s\n",
core->tvaudio, __func__);
return UNSET;
}
carrier = freq_magnitude(x, N, carrier_freq);
stereo = freq_magnitude(x, N, stereo_freq);
dual = freq_magnitude(x, N, dual_freq);
noise = noise_magnitude(x, N, FREQ_NOISE_START, FREQ_NOISE_END);
dprintk(1,
"detect a2/a2m/eiaj: carrier=%d, stereo=%d, dual=%d, noise=%d\n",
carrier, stereo, dual, noise);
if (stereo > dual)
ret = V4L2_TUNER_SUB_STEREO;
else
ret = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2;
if (core->tvaudio == WW_EIAJ) {
/* EIAJ checks may need adjustments */
if ((carrier > max(stereo, dual) * 2) &&
(carrier < max(stereo, dual) * 6) &&
(carrier > 20 && carrier < 200) &&
(max(stereo, dual) > min(stereo, dual))) {
/*
* For EIAJ the carrier is always present,
* so we probably don't need noise detection
*/
return ret;
}
} else {
if ((carrier > max(stereo, dual) * 2) &&
(carrier < max(stereo, dual) * 8) &&
(carrier > 20 && carrier < 200) &&
(noise < 10) &&
(max(stereo, dual) > min(stereo, dual) * 2)) {
return ret;
}
}
return V4L2_TUNER_SUB_MONO;
}
static s32 detect_btsc(struct cx88_core *core, s16 x[], u32 N)
{
s32 sap_ref = freq_magnitude(x, N, FREQ_BTSC_SAP_REF);
s32 sap = freq_magnitude(x, N, FREQ_BTSC_SAP);
s32 dual_ref = freq_magnitude(x, N, FREQ_BTSC_DUAL_REF);
s32 dual = freq_magnitude(x, N, FREQ_BTSC_DUAL);
dprintk(1, "detect btsc: dual_ref=%d, dual=%d, sap_ref=%d, sap=%d\n",
dual_ref, dual, sap_ref, sap);
/* FIXME: Currently not supported */
return UNSET;
}
static s16 *read_rds_samples(struct cx88_core *core, u32 *N)
{
const struct sram_channel *srch = &cx88_sram_channels[SRAM_CH27];
s16 *samples;
unsigned int i;
unsigned int bpl = srch->fifo_size / AUD_RDS_LINES;
unsigned int spl = bpl / 4;
unsigned int sample_count = spl * (AUD_RDS_LINES - 1);
u32 current_address = cx_read(srch->ptr1_reg);
u32 offset = (current_address - srch->fifo_start + bpl);
dprintk(1,
"read RDS samples: current_address=%08x (offset=%08x), sample_count=%d, aud_intstat=%08x\n",
current_address,
current_address - srch->fifo_start, sample_count,
cx_read(MO_AUD_INTSTAT));
samples = kmalloc_array(sample_count, sizeof(*samples), GFP_KERNEL);
if (!samples)
return NULL;
*N = sample_count;
for (i = 0; i < sample_count; i++) {
offset = offset % (AUD_RDS_LINES * bpl);
samples[i] = cx_read(srch->fifo_start + offset);
offset += 4;
}
dprintk(2, "RDS samples dump: %*ph\n", sample_count, samples);
return samples;
}
s32 cx88_dsp_detect_stereo_sap(struct cx88_core *core)
{
s16 *samples;
u32 N = 0;
s32 ret = UNSET;
/* If audio RDS fifo is disabled, we can't read the samples */
if (!(cx_read(MO_AUD_DMACNTRL) & 0x04))
return ret;
if (!(cx_read(AUD_CTL) & EN_FMRADIO_EN_RDS))
return ret;
/* Wait at least 500 ms after an audio standard change */
if (time_before(jiffies, core->last_change + msecs_to_jiffies(500)))
return ret;
samples = read_rds_samples(core, &N);
if (!samples)
return ret;
switch (core->tvaudio) {
case WW_BG:
case WW_DK:
case WW_EIAJ:
case WW_M:
ret = detect_a2_a2m_eiaj(core, samples, N);
break;
case WW_BTSC:
ret = detect_btsc(core, samples, N);
break;
case WW_NONE:
case WW_I:
case WW_L:
case WW_I2SPT:
case WW_FM:
case WW_I2SADC:
break;
}
kfree(samples);
if (ret != UNSET)
dprintk(1, "stereo/sap detection result:%s%s%s\n",
(ret & V4L2_TUNER_SUB_MONO) ? " mono" : "",
(ret & V4L2_TUNER_SUB_STEREO) ? " stereo" : "",
(ret & V4L2_TUNER_SUB_LANG2) ? " dual" : "");
return ret;
}
EXPORT_SYMBOL(cx88_dsp_detect_stereo_sap);
| CSE3320/kernel-code | linux-5.8/drivers/media/pci/cx88/cx88-dsp.c | C | gpl-2.0 | 8,319 |
// Boost.TypeErasure library
//
// Copyright 2011 Steven Watanabe
//
// 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)
//
// $Id$
#if !defined(BOOST_PP_IS_ITERATING)
#ifndef BOOST_TYPE_ERASURE_CALLABLE_HPP_INCLUDED
#define BOOST_TYPE_ERASURE_CALLABLE_HPP_INCLUDED
#include <boost/utility/declval.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/dec.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
#include <boost/type_erasure/config.hpp>
#include <boost/type_erasure/call.hpp>
#include <boost/type_erasure/concept_interface.hpp>
#include <boost/type_erasure/rebind_any.hpp>
#include <boost/type_erasure/param.hpp>
namespace boost {
namespace type_erasure {
template<class Sig, class F = _self>
struct callable;
namespace detail {
template<class Sig>
struct result_of_callable;
}
#if defined(BOOST_TYPE_ERASURE_DOXYGEN)
/**
* The @ref callable concept allows an @ref any to hold function objects.
* @c Sig is interpreted in the same way as for Boost.Function, except
* that the arguments and return type are allowed to be placeholders.
* @c F must be a @ref placeholder.
*
* Multiple instances of @ref callable can be used
* simultaneously. Overload resolution works normally.
* Note that unlike Boost.Function, @ref callable
* does not provide result_type. It does, however,
* support @c boost::result_of.
*/
template<class Sig, class F = _self>
struct callable
{
/**
* @c R is the result type of @c Sig and @c T is the argument
* types of @c Sig.
*/
static R apply(F& f, T... arg);
};
#elif !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template<class R, class... T, class F>
struct callable<R(T...), F>
{
static R apply(F& f, T... arg)
{
return f(std::forward<T>(arg)...);
}
};
template<class... T, class F>
struct callable<void(T...), F>
{
static void apply(F& f, T... arg)
{
f(std::forward<T>(arg)...);
}
};
template<class R, class F, class Base, class Enable, class... T>
struct concept_interface<callable<R(T...), F>, Base, F, Enable>
: Base
{
template<class Sig>
struct result :
::boost::type_erasure::detail::result_of_callable<Sig>
{};
typedef void _boost_type_erasure_is_callable;
typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[1];
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
typename ::boost::type_erasure::as_param<Base, T>::type...);
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(typename ::boost::type_erasure::as_param<Base, T>::type... arg)
{
return ::boost::type_erasure::call(callable<R(T...), F>(), *this,
::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...);
}
};
template<class R, class F, class Base, class Enable, class... T>
struct concept_interface<callable<R(T...), const F>, Base, F, Enable>
: Base
{
template<class Sig>
struct result :
::boost::type_erasure::detail::result_of_callable<Sig>
{};
typedef void _boost_type_erasure_is_callable;
typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[1];
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
typename ::boost::type_erasure::as_param<Base, T>::type...) const;
typename ::boost::type_erasure::rebind_any<Base, R>::type operator()(
typename ::boost::type_erasure::as_param<Base, T>::type... arg) const
{
return ::boost::type_erasure::call(callable<R(T...), const F>(), *this,
::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...);
}
};
template<class R, class F, class Base, class... T>
struct concept_interface<
callable<R(T...), F>,
Base,
F,
typename Base::_boost_type_erasure_is_callable
>
: Base
{
typedef typename ::boost::mpl::push_back<
typename Base::_boost_type_erasure_callable_results,
R
>::type _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[
::boost::mpl::size<_boost_type_erasure_callable_results>::value];
using Base::_boost_type_erasure_deduce_callable;
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
typename ::boost::type_erasure::as_param<Base, T>::type...);
using Base::operator();
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(typename ::boost::type_erasure::as_param<Base, T>::type... arg)
{
return ::boost::type_erasure::call(callable<R(T...), F>(), *this,
::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...);
}
};
template<class R, class F, class Base, class... T>
struct concept_interface<
callable<R(T...), const F>,
Base,
F,
typename Base::_boost_type_erasure_is_callable
>
: Base
{
typedef typename ::boost::mpl::push_back<
typename Base::_boost_type_erasure_callable_results,
R
>::type _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[
::boost::mpl::size<_boost_type_erasure_callable_results>::value];
using Base::_boost_type_erasure_deduce_callable;
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
typename ::boost::type_erasure::as_param<Base, T>::type...) const;
using Base::operator();
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(typename ::boost::type_erasure::as_param<Base, T>::type... arg) const
{
return ::boost::type_erasure::call(callable<R(T...), const F>(), *this,
::std::forward<typename ::boost::type_erasure::as_param<Base, T>::type>(arg)...);
}
};
namespace detail {
template<class This, class... T>
struct result_of_callable<This(T...)>
{
typedef typename ::boost::mpl::at_c<
typename This::_boost_type_erasure_callable_results,
sizeof(::boost::declval<This>().
_boost_type_erasure_deduce_callable(::boost::declval<T>()...)) - 1
>::type type;
};
}
#else
/** INTERNAL ONLY */
#define BOOST_PP_FILENAME_1 <boost/type_erasure/callable.hpp>
/** INTERNAL ONLY */
#define BOOST_PP_ITERATION_LIMITS (0, BOOST_PP_DEC(BOOST_TYPE_ERASURE_MAX_ARITY))
#include BOOST_PP_ITERATE()
#endif
}
}
#endif
#else
#define N BOOST_PP_ITERATION()
#define BOOST_TYPE_ERASURE_DECLVAL(z, n, data) ::boost::declval<BOOST_PP_CAT(T, n)>()
#define BOOST_TYPE_ERASURE_REBIND(z, n, data)\
typename ::boost::type_erasure::as_param<Base, BOOST_PP_CAT(T, n)>::type BOOST_PP_CAT(arg, n)
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
#define BOOST_TYPE_ERASURE_FORWARD(z, n, data) BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, data), n)
#define BOOST_TYPE_ERASURE_FORWARD_REBIND(z, n, data) BOOST_PP_CAT(arg, n)
#else
#define BOOST_TYPE_ERASURE_FORWARD(z, n, data) ::std::forward<BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 0, data), n)>(BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, data), n))
#define BOOST_TYPE_ERASURE_FORWARD_REBIND(z, n, data) ::std::forward<typename ::boost::type_erasure::as_param<Base, BOOST_PP_CAT(T, n)>::type>(BOOST_PP_CAT(arg, n))
#endif
template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F>
struct callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>
{
static R apply(F& f BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, T, arg))
{
return f(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_FORWARD, (T, arg)));
}
};
template<BOOST_PP_ENUM_PARAMS(N, class T) BOOST_PP_COMMA_IF(N) class F>
struct callable<void(BOOST_PP_ENUM_PARAMS(N, T)), F>
{
static void apply(F& f BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, T, arg))
{
f(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_FORWARD, (T, arg)));
}
};
template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base, class Enable>
struct concept_interface<
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>,
Base,
F,
Enable
>
: Base
{
template<class Sig>
struct result :
::boost::type_erasure::detail::result_of_callable<Sig>
{};
typedef void _boost_type_erasure_is_callable;
typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[1];
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~));
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~))
{
return ::boost::type_erasure::call(
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>(),
*this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~));
}
};
template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base, class Enable>
struct concept_interface<
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>,
Base,
F,
Enable
>
: Base
{
template<class Sig>
struct result :
::boost::type_erasure::detail::result_of_callable<Sig>
{};
typedef void _boost_type_erasure_is_callable;
typedef ::boost::mpl::vector<R> _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[1];
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const;
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const
{
return ::boost::type_erasure::call(
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>(),
*this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~));
}
};
template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base>
struct concept_interface<
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>,
Base,
F,
typename Base::_boost_type_erasure_is_callable
>
: Base
{
typedef typename ::boost::mpl::push_back<
typename Base::_boost_type_erasure_callable_results,
R
>::type _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[
::boost::mpl::size<_boost_type_erasure_callable_results>::value];
using Base::_boost_type_erasure_deduce_callable;
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~));
using Base::operator();
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~))
{
return ::boost::type_erasure::call(
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), F>(),
*this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~));
}
};
template<class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class T), class F, class Base>
struct concept_interface<
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>,
Base,
F,
typename Base::_boost_type_erasure_is_callable
>
: Base
{
typedef typename ::boost::mpl::push_back<
typename Base::_boost_type_erasure_callable_results,
R
>::type _boost_type_erasure_callable_results;
typedef char (&_boost_type_erasure_callable_size)[
::boost::mpl::size<_boost_type_erasure_callable_results>::value];
using Base::_boost_type_erasure_deduce_callable;
_boost_type_erasure_callable_size
_boost_type_erasure_deduce_callable(
BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const;
using Base::operator();
typename ::boost::type_erasure::rebind_any<Base, R>::type
operator()(BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_REBIND, ~)) const
{
return ::boost::type_erasure::call(
callable<R(BOOST_PP_ENUM_PARAMS(N, T)), const F>(),
*this BOOST_PP_ENUM_TRAILING(N, BOOST_TYPE_ERASURE_FORWARD_REBIND, ~));
}
};
namespace detail {
template<class This BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)>
struct result_of_callable<This(BOOST_PP_ENUM_PARAMS(N, T))>
{
typedef typename ::boost::mpl::at_c<
typename This::_boost_type_erasure_callable_results,
sizeof(::boost::declval<This>().
_boost_type_erasure_deduce_callable(
BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_DECLVAL, ~))) - 1
>::type type;
};
}
#undef BOOST_TYPE_ERASURE_DECLVAL
#undef BOOST_TYPE_ERASURE_REBIND
#undef N
#endif
| rkq/cxxexp | third-party/src/boost_1_56_0/boost/type_erasure/callable.hpp | C++ | mit | 13,033 |
# cs.???? = currentstate, any variable on the status tab in the planner can be used.
# Script = options are
# Script.Sleep(ms)
# Script.ChangeParam(name,value)
# Script.GetParam(name)
# Script.ChangeMode(mode) - same as displayed in mode setup screen 'AUTO'
# Script.WaitFor(string,timeout)
# Script.SendRC(channel,pwm,sendnow)
#
print 'Start Script'
for chan in range(1,9):
Script.SendRC(chan,1500,False)
Script.SendRC(3,Script.GetParam('RC3_MIN'),True)
Script.Sleep(5000)
while cs.lat == 0:
print 'Waiting for GPS'
Script.Sleep(1000)
print 'Got GPS'
jo = 10 * 13
print jo
Script.SendRC(3,1000,False)
Script.SendRC(4,2000,True)
cs.messages.Clear()
Script.WaitFor('ARMING MOTORS',30000)
Script.SendRC(4,1500,True)
print 'Motors Armed!'
Script.SendRC(3,1700,True)
while cs.alt < 50:
Script.Sleep(50)
Script.SendRC(5,2000,True) # acro
Script.SendRC(1,2000,False) # roll
Script.SendRC(3,1370,True) # throttle
while cs.roll > -45: # top hald 0 - 180
Script.Sleep(5)
while cs.roll < -45: # -180 - -45
Script.Sleep(5)
Script.SendRC(5,1500,False) # stabalise
Script.SendRC(1,1500,True) # level roll
Script.Sleep(2000) # 2 sec to stabalise
Script.SendRC(3,1300,True) # throttle back to land
thro = 1350 # will decend
while cs.alt > 0.1:
Script.Sleep(300)
Script.SendRC(3,1000,False)
Script.SendRC(4,1000,True)
Script.WaitFor('DISARMING MOTORS',30000)
Script.SendRC(4,1500,True)
print 'Roll complete' | vizual54/MissionPlanner | Scripts/example1.py | Python | gpl-3.0 | 1,491 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai 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/ECL-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 edu.amc.sakai.user;
import com.novell.ldap.LDAPConnection;
/**
* Pluggable strategy for verifying {@link LDAPConnection}
* "liveness". Typically injected into a
* {@link PooledLDAPConnectionFactory}.
*
* @author dmccallum@unicon.net
*
*/
public interface LdapConnectionLivenessValidator {
public boolean isConnectionAlive(LDAPConnection connectionToTest);
}
| marktriggs/nyu-sakai-10.4 | providers/jldap/src/java/edu/amc/sakai/user/LdapConnectionLivenessValidator.java | Java | apache-2.0 | 1,307 |
/*
* Copyright (C) 2012 - Virtual Open Systems and Columbia University
* Author: Christoffer Dall <c.dall@virtualopensystems.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <linux/kvm_host.h>
#include <asm/kvm_mmio.h>
#include <asm/kvm_emulate.h>
#include <trace/events/kvm.h>
#include "trace.h"
static void mmio_write_buf(char *buf, unsigned int len, unsigned long data)
{
void *datap = NULL;
union {
u8 byte;
u16 hword;
u32 word;
u64 dword;
} tmp;
switch (len) {
case 1:
tmp.byte = data;
datap = &tmp.byte;
break;
case 2:
tmp.hword = data;
datap = &tmp.hword;
break;
case 4:
tmp.word = data;
datap = &tmp.word;
break;
case 8:
tmp.dword = data;
datap = &tmp.dword;
break;
}
memcpy(buf, datap, len);
}
static unsigned long mmio_read_buf(char *buf, unsigned int len)
{
unsigned long data = 0;
union {
u16 hword;
u32 word;
u64 dword;
} tmp;
switch (len) {
case 1:
data = buf[0];
break;
case 2:
memcpy(&tmp.hword, buf, len);
data = tmp.hword;
break;
case 4:
memcpy(&tmp.word, buf, len);
data = tmp.word;
break;
case 8:
memcpy(&tmp.dword, buf, len);
data = tmp.dword;
break;
}
return data;
}
/**
* kvm_handle_mmio_return -- Handle MMIO loads after user space emulation
* @vcpu: The VCPU pointer
* @run: The VCPU run struct containing the mmio data
*
* This should only be called after returning from userspace for MMIO load
* emulation.
*/
int kvm_handle_mmio_return(struct kvm_vcpu *vcpu, struct kvm_run *run)
{
unsigned long data;
unsigned int len;
int mask;
if (!run->mmio.is_write) {
len = run->mmio.len;
if (len > sizeof(unsigned long))
return -EINVAL;
data = mmio_read_buf(run->mmio.data, len);
if (vcpu->arch.mmio_decode.sign_extend &&
len < sizeof(unsigned long)) {
mask = 1U << ((len * 8) - 1);
data = (data ^ mask) - mask;
}
trace_kvm_mmio(KVM_TRACE_MMIO_READ, len, run->mmio.phys_addr,
data);
data = vcpu_data_host_to_guest(vcpu, data, len);
vcpu_set_reg(vcpu, vcpu->arch.mmio_decode.rt, data);
}
return 0;
}
static int decode_hsr(struct kvm_vcpu *vcpu, bool *is_write, int *len)
{
unsigned long rt;
int access_size;
bool sign_extend;
if (kvm_vcpu_dabt_isextabt(vcpu)) {
/* cache operation on I/O addr, tell guest unsupported */
kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
return 1;
}
if (kvm_vcpu_dabt_iss1tw(vcpu)) {
/* page table accesses IO mem: tell guest to fix its TTBR */
kvm_inject_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
return 1;
}
access_size = kvm_vcpu_dabt_get_as(vcpu);
if (unlikely(access_size < 0))
return access_size;
*is_write = kvm_vcpu_dabt_iswrite(vcpu);
sign_extend = kvm_vcpu_dabt_issext(vcpu);
rt = kvm_vcpu_dabt_get_rd(vcpu);
*len = access_size;
vcpu->arch.mmio_decode.sign_extend = sign_extend;
vcpu->arch.mmio_decode.rt = rt;
/*
* The MMIO instruction is emulated and should not be re-executed
* in the guest.
*/
kvm_skip_instr(vcpu, kvm_vcpu_trap_il_is32bit(vcpu));
return 0;
}
int io_mem_abort(struct kvm_vcpu *vcpu, struct kvm_run *run,
phys_addr_t fault_ipa)
{
unsigned long data;
unsigned long rt;
int ret;
bool is_write;
int len;
u8 data_buf[8];
/*
* Prepare MMIO operation. First decode the syndrome data we get
* from the CPU. Then try if some in-kernel emulation feels
* responsible, otherwise let user space do its magic.
*/
if (kvm_vcpu_dabt_isvalid(vcpu)) {
ret = decode_hsr(vcpu, &is_write, &len);
if (ret)
return ret;
} else {
kvm_err("load/store instruction decoding not implemented\n");
return -ENOSYS;
}
rt = vcpu->arch.mmio_decode.rt;
if (is_write) {
data = vcpu_data_guest_to_host(vcpu, vcpu_get_reg(vcpu, rt),
len);
trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, len, fault_ipa, data);
mmio_write_buf(data_buf, len, data);
ret = kvm_io_bus_write(vcpu, KVM_MMIO_BUS, fault_ipa, len,
data_buf);
} else {
trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, len,
fault_ipa, 0);
ret = kvm_io_bus_read(vcpu, KVM_MMIO_BUS, fault_ipa, len,
data_buf);
}
/* Now prepare kvm_run for the potential return to userland. */
run->mmio.is_write = is_write;
run->mmio.phys_addr = fault_ipa;
run->mmio.len = len;
if (is_write)
memcpy(run->mmio.data, data_buf, len);
if (!ret) {
/* We handled the access successfully in the kernel. */
vcpu->stat.mmio_exit_kernel++;
kvm_handle_mmio_return(vcpu, run);
return 1;
} else {
vcpu->stat.mmio_exit_user++;
}
run->exit_reason = KVM_EXIT_MMIO;
return 0;
}
| mikedlowis-prototypes/albase | source/kernel/arch/arm/kvm/mmio.c | C | bsd-2-clause | 5,166 |
// 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.
cr.define('cr.ui', function() {
// require cr.ui.define
// require cr.ui.limitInputWidth
/**
* The number of pixels to indent per level.
* @type {number}
* @const
*/
var INDENT = 20;
/**
* Returns the computed style for an element.
* @param {!Element} el The element to get the computed style for.
* @return {!CSSStyleDeclaration} The computed style.
*/
function getComputedStyle(el) {
return el.ownerDocument.defaultView.getComputedStyle(el);
}
/**
* Helper function that finds the first ancestor tree item.
* @param {!Element} el The element to start searching from.
* @return {cr.ui.TreeItem} The found tree item or null if not found.
*/
function findTreeItem(el) {
while (el && !(el instanceof TreeItem)) {
el = el.parentNode;
}
return el;
}
/**
* Creates a new tree element.
* @param {Object=} opt_propertyBag Optional properties.
* @constructor
* @extends {HTMLElement}
*/
var Tree = cr.ui.define('tree');
Tree.prototype = {
__proto__: HTMLElement.prototype,
/**
* Initializes the element.
*/
decorate: function() {
// Make list focusable
if (!this.hasAttribute('tabindex'))
this.tabIndex = 0;
this.addEventListener('click', this.handleClick);
this.addEventListener('mousedown', this.handleMouseDown);
this.addEventListener('dblclick', this.handleDblClick);
this.addEventListener('keydown', this.handleKeyDown);
},
/**
* Returns the tree item that are children of this tree.
*/
get items() {
return this.children;
},
/**
* Adds a tree item to the tree.
* @param {!cr.ui.TreeItem} treeItem The item to add.
*/
add: function(treeItem) {
this.addAt(treeItem, 0xffffffff);
},
/**
* Adds a tree item at the given index.
* @param {!cr.ui.TreeItem} treeItem The item to add.
* @param {number} index The index where we want to add the item.
*/
addAt: function(treeItem, index) {
this.insertBefore(treeItem, this.children[index]);
treeItem.setDepth_(this.depth + 1);
},
/**
* Removes a tree item child.
* @param {!cr.ui.TreeItem} treeItem The tree item to remove.
*/
remove: function(treeItem) {
this.removeChild(treeItem);
},
/**
* The depth of the node. This is 0 for the tree itself.
* @type {number}
*/
get depth() {
return 0;
},
/**
* Handles click events on the tree and forwards the event to the relevant
* tree items as necesary.
* @param {Event} e The click event object.
*/
handleClick: function(e) {
var treeItem = findTreeItem(e.target);
if (treeItem)
treeItem.handleClick(e);
},
handleMouseDown: function(e) {
if (e.button == 2) // right
this.handleClick(e);
},
/**
* Handles double click events on the tree.
* @param {Event} e The dblclick event object.
*/
handleDblClick: function(e) {
var treeItem = findTreeItem(e.target);
if (treeItem)
treeItem.expanded = !treeItem.expanded;
},
/**
* Handles keydown events on the tree and updates selection and exanding
* of tree items.
* @param {Event} e The click event object.
*/
handleKeyDown: function(e) {
var itemToSelect;
if (e.ctrlKey)
return;
var item = this.selectedItem;
if (!item)
return;
var rtl = getComputedStyle(item).direction == 'rtl';
switch (e.keyIdentifier) {
case 'Up':
itemToSelect = item ? getPrevious(item) :
this.items[this.items.length - 1];
break;
case 'Down':
itemToSelect = item ? getNext(item) :
this.items[0];
break;
case 'Left':
case 'Right':
// Don't let back/forward keyboard shortcuts be used.
if (!cr.isMac && e.altKey || cr.isMac && e.metaKey)
break;
if (e.keyIdentifier == 'Left' && !rtl ||
e.keyIdentifier == 'Right' && rtl) {
if (item.expanded)
item.expanded = false;
else
itemToSelect = findTreeItem(item.parentNode);
} else {
if (!item.expanded)
item.expanded = true;
else
itemToSelect = item.items[0];
}
break;
case 'Home':
itemToSelect = this.items[0];
break;
case 'End':
itemToSelect = this.items[this.items.length - 1];
break;
}
if (itemToSelect) {
itemToSelect.selected = true;
e.preventDefault();
}
},
/**
* The selected tree item or null if none.
* @type {cr.ui.TreeItem}
*/
get selectedItem() {
return this.selectedItem_ || null;
},
set selectedItem(item) {
var oldSelectedItem = this.selectedItem_;
if (oldSelectedItem != item) {
// Set the selectedItem_ before deselecting the old item since we only
// want one change when moving between items.
this.selectedItem_ = item;
if (oldSelectedItem)
oldSelectedItem.selected = false;
if (item)
item.selected = true;
cr.dispatchSimpleEvent(this, 'change');
}
},
/**
* @return {!ClientRect} The rect to use for the context menu.
*/
getRectForContextMenu: function() {
// TODO(arv): Add trait support so we can share more code between trees
// and lists.
if (this.selectedItem)
return this.selectedItem.rowElement.getBoundingClientRect();
return this.getBoundingClientRect();
}
};
/**
* Determines the visibility of icons next to the treeItem labels. If set to
* 'hidden', no space is reserved for icons and no icons are displayed next
* to treeItem labels. If set to 'parent', folder icons will be displayed
* next to expandable parent nodes. If set to 'all' folder icons will be
* displayed next to all nodes. Icons can be set using the treeItem's icon
* property.
*/
cr.defineProperty(Tree, 'iconVisibility', cr.PropertyKind.ATTR);
/**
* This is used as a blueprint for new tree item elements.
* @type {!HTMLElement}
*/
var treeItemProto = (function() {
var treeItem = cr.doc.createElement('div');
treeItem.className = 'tree-item';
treeItem.innerHTML = '<div class=tree-row>' +
'<span class=expand-icon></span>' +
'<span class=tree-label></span>' +
'</div>' +
'<div class=tree-children></div>';
treeItem.setAttribute('role', 'treeitem');
return treeItem;
})();
/**
* Creates a new tree item.
* @param {Object=} opt_propertyBag Optional properties.
* @constructor
* @extends {HTMLElement}
*/
var TreeItem = cr.ui.define(function() {
return treeItemProto.cloneNode(true);
});
TreeItem.prototype = {
__proto__: HTMLElement.prototype,
/**
* Initializes the element.
*/
decorate: function() {
},
/**
* The tree items children.
*/
get items() {
return this.lastElementChild.children;
},
/**
* The depth of the tree item.
* @type {number}
*/
depth_: 0,
get depth() {
return this.depth_;
},
/**
* Sets the depth.
* @param {number} depth The new depth.
* @private
*/
setDepth_: function(depth) {
if (depth != this.depth_) {
this.rowElement.style.WebkitPaddingStart = Math.max(0, depth - 1) *
INDENT + 'px';
this.depth_ = depth;
var items = this.items;
for (var i = 0, item; item = items[i]; i++) {
item.setDepth_(depth + 1);
}
}
},
/**
* Adds a tree item as a child.
* @param {!cr.ui.TreeItem} child The child to add.
*/
add: function(child) {
this.addAt(child, 0xffffffff);
},
/**
* Adds a tree item as a child at a given index.
* @param {!cr.ui.TreeItem} child The child to add.
* @param {number} index The index where to add the child.
*/
addAt: function(child, index) {
this.lastElementChild.insertBefore(child, this.items[index]);
if (this.items.length == 1)
this.hasChildren = true;
child.setDepth_(this.depth + 1);
},
/**
* Removes a child.
* @param {!cr.ui.TreeItem} child The tree item child to remove.
*/
remove: function(child) {
// If we removed the selected item we should become selected.
var tree = this.tree;
var selectedItem = tree.selectedItem;
if (selectedItem && child.contains(selectedItem))
this.selected = true;
this.lastElementChild.removeChild(child);
if (this.items.length == 0)
this.hasChildren = false;
},
/**
* The parent tree item.
* @type {!cr.ui.Tree|cr.ui.TreeItem}
*/
get parentItem() {
var p = this.parentNode;
while (p && !(p instanceof TreeItem) && !(p instanceof Tree)) {
p = p.parentNode;
}
return p;
},
/**
* The tree that the tree item belongs to or null of no added to a tree.
* @type {cr.ui.Tree}
*/
get tree() {
var t = this.parentItem;
while (t && !(t instanceof Tree)) {
t = t.parentItem;
}
return t;
},
/**
* Whether the tree item is expanded or not.
* @type {boolean}
*/
get expanded() {
return this.hasAttribute('expanded');
},
set expanded(b) {
if (this.expanded == b)
return;
var treeChildren = this.lastElementChild;
if (b) {
if (this.mayHaveChildren_) {
this.setAttribute('expanded', '');
treeChildren.setAttribute('expanded', '');
cr.dispatchSimpleEvent(this, 'expand', true);
this.scrollIntoViewIfNeeded(false);
}
} else {
var tree = this.tree;
if (tree && !this.selected) {
var oldSelected = tree.selectedItem;
if (oldSelected && this.contains(oldSelected))
this.selected = true;
}
this.removeAttribute('expanded');
treeChildren.removeAttribute('expanded');
cr.dispatchSimpleEvent(this, 'collapse', true);
}
},
/**
* Expands all parent items.
*/
reveal: function() {
var pi = this.parentItem;
while (pi && !(pi instanceof Tree)) {
pi.expanded = true;
pi = pi.parentItem;
}
},
/**
* The element representing the row that gets highlighted.
* @type {!HTMLElement}
*/
get rowElement() {
return this.firstElementChild;
},
/**
* The element containing the label text and the icon.
* @type {!HTMLElement}
*/
get labelElement() {
return this.firstElementChild.lastElementChild;
},
/**
* The label text.
* @type {string}
*/
get label() {
return this.labelElement.textContent;
},
set label(s) {
this.labelElement.textContent = s;
},
/**
* The URL for the icon.
* @type {string}
*/
get icon() {
return getComputedStyle(this.labelElement).backgroundImage.slice(4, -1);
},
set icon(icon) {
return this.labelElement.style.backgroundImage = url(icon);
},
/**
* Whether the tree item is selected or not.
* @type {boolean}
*/
get selected() {
return this.hasAttribute('selected');
},
set selected(b) {
if (this.selected == b)
return;
var rowItem = this.firstElementChild;
var tree = this.tree;
if (b) {
this.setAttribute('selected', '');
rowItem.setAttribute('selected', '');
this.reveal();
this.labelElement.scrollIntoViewIfNeeded(false);
if (tree)
tree.selectedItem = this;
} else {
this.removeAttribute('selected');
rowItem.removeAttribute('selected');
if (tree && tree.selectedItem == this)
tree.selectedItem = null;
}
},
/**
* Whether the tree item has children.
* @type {boolean}
*/
get mayHaveChildren_() {
return this.hasAttribute('may-have-children');
},
set mayHaveChildren_(b) {
var rowItem = this.firstElementChild;
if (b) {
this.setAttribute('may-have-children', '');
rowItem.setAttribute('may-have-children', '');
} else {
this.removeAttribute('may-have-children');
rowItem.removeAttribute('may-have-children');
}
},
/**
* Whether the tree item has children.
* @type {boolean}
*/
get hasChildren() {
return !!this.items[0];
},
/**
* Whether the tree item has children.
* @type {boolean}
*/
set hasChildren(b) {
var rowItem = this.firstElementChild;
this.setAttribute('has-children', b);
rowItem.setAttribute('has-children', b);
if (b)
this.mayHaveChildren_ = true;
},
/**
* Called when the user clicks on a tree item. This is forwarded from the
* cr.ui.Tree.
* @param {Event} e The click event.
*/
handleClick: function(e) {
if (e.target.className == 'expand-icon')
this.expanded = !this.expanded;
else
this.selected = true;
},
/**
* Makes the tree item user editable. If the user renamed the item a
* bubbling {@code rename} event is fired.
* @type {boolean}
*/
set editing(editing) {
var oldEditing = this.editing;
if (editing == oldEditing)
return;
var self = this;
var labelEl = this.labelElement;
var text = this.label;
var input;
// Handles enter and escape which trigger reset and commit respectively.
function handleKeydown(e) {
// Make sure that the tree does not handle the key.
e.stopPropagation();
// Calling tree.focus blurs the input which will make the tree item
// non editable.
switch (e.keyIdentifier) {
case 'U+001B': // Esc
input.value = text;
// fall through
case 'Enter':
self.tree.focus();
}
}
function stopPropagation(e) {
e.stopPropagation();
}
if (editing) {
this.selected = true;
this.setAttribute('editing', '');
this.draggable = false;
// We create an input[type=text] and copy over the label value. When
// the input loses focus we set editing to false again.
input = this.ownerDocument.createElement('input');
input.value = text;
if (labelEl.firstChild)
labelEl.replaceChild(input, labelEl.firstChild);
else
labelEl.appendChild(input);
input.addEventListener('keydown', handleKeydown);
input.addEventListener('blur', (function() {
this.editing = false;
}).bind(this));
// Make sure that double clicks do not expand and collapse the tree
// item.
var eventsToStop = ['mousedown', 'mouseup', 'contextmenu', 'dblclick'];
eventsToStop.forEach(function(type) {
input.addEventListener(type, stopPropagation);
});
// Wait for the input element to recieve focus before sizing it.
var rowElement = this.rowElement;
function onFocus() {
input.removeEventListener('focus', onFocus);
// 20 = the padding and border of the tree-row
cr.ui.limitInputWidth(input, rowElement, 100);
}
input.addEventListener('focus', onFocus);
input.focus();
input.select();
this.oldLabel_ = text;
} else {
this.removeAttribute('editing');
this.draggable = true;
input = labelEl.firstChild;
var value = input.value;
if (/^\s*$/.test(value)) {
labelEl.textContent = this.oldLabel_;
} else {
labelEl.textContent = value;
if (value != this.oldLabel_) {
cr.dispatchSimpleEvent(this, 'rename', true);
}
}
delete this.oldLabel_;
}
},
get editing() {
return this.hasAttribute('editing');
}
};
/**
* Helper function that returns the next visible tree item.
* @param {cr.ui.TreeItem} item The tree item.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getNext(item) {
if (item.expanded) {
var firstChild = item.items[0];
if (firstChild) {
return firstChild;
}
}
return getNextHelper(item);
}
/**
* Another helper function that returns the next visible tree item.
* @param {cr.ui.TreeItem} item The tree item.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getNextHelper(item) {
if (!item)
return null;
var nextSibling = item.nextElementSibling;
if (nextSibling) {
return nextSibling;
}
return getNextHelper(item.parentItem);
}
/**
* Helper function that returns the previous visible tree item.
* @param {cr.ui.TreeItem} item The tree item.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getPrevious(item) {
var previousSibling = item.previousElementSibling;
return previousSibling ? getLastHelper(previousSibling) : item.parentItem;
}
/**
* Helper function that returns the last visible tree item in the subtree.
* @param {cr.ui.TreeItem} item The item to find the last visible item for.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getLastHelper(item) {
if (!item)
return null;
if (item.expanded && item.hasChildren) {
var lastChild = item.items[item.items.length - 1];
return getLastHelper(lastChild);
}
return item;
}
// Export
return {
Tree: Tree,
TreeItem: TreeItem
};
});
| aospx-kitkat/platform_external_chromium_org | ui/webui/resources/js/cr/ui/tree.js | JavaScript | bsd-3-clause | 18,164 |
<!DOCTYPE html>
<html>
<head>
<title>Inline text in the top element</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../test.js"></script>
<style>
span {
color:blue;
}
p {
background-color: green;
}
</style>
</head>
<body>
Some inline text <span> followed by text in span </span> followed by more inline text.
<p>Then a block level element.</p>
Then more inline text.
</body>
</html>
| robnightingale/ore-dashboard-beta | vendors/html2canvas/tests/cases/child-textnodes.html | HTML | mit | 584 |
/**
* @license Highcharts JS v4.2.2 (2016-02-04)
*
* (c) 2014 Highsoft AS
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*/
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function (H) {
var seriesTypes = H.seriesTypes,
map = H.map,
merge = H.merge,
extend = H.extend,
extendClass = H.extendClass,
defaultOptions = H.getOptions(),
plotOptions = defaultOptions.plotOptions,
noop = function () {
},
each = H.each,
grep = H.grep,
pick = H.pick,
Series = H.Series,
stableSort = H.stableSort,
Color = H.Color,
eachObject = function (list, func, context) {
var key;
context = context || this;
for (key in list) {
if (list.hasOwnProperty(key)) {
func.call(context, list[key], key, list);
}
}
},
reduce = function (arr, func, previous, context) {
context = context || this;
arr = arr || []; // @note should each be able to handle empty values automatically?
each(arr, function (current, i) {
previous = func.call(context, previous, current, i, arr);
});
return previous;
},
// @todo find correct name for this function.
recursive = function (item, func, context) {
var next;
context = context || this;
next = func.call(context, item);
if (next !== false) {
recursive(next, func, context);
}
};
// Define default options
plotOptions.treemap = merge(plotOptions.scatter, {
showInLegend: false,
marker: false,
borderColor: '#E0E0E0',
borderWidth: 1,
dataLabels: {
enabled: true,
defer: false,
verticalAlign: 'middle',
formatter: function () { // #2945
return this.point.name || this.point.id;
},
inside: true
},
tooltip: {
headerFormat: '',
pointFormat: '<b>{point.name}</b>: {point.node.val}</b><br/>'
},
layoutAlgorithm: 'sliceAndDice',
layoutStartingDirection: 'vertical',
alternateStartingDirection: false,
levelIsConstant: true,
states: {
hover: {
borderColor: '#A0A0A0',
brightness: seriesTypes.heatmap ? 0 : 0.1,
shadow: false
}
},
drillUpButton: {
position: {
align: 'right',
x: -10,
y: 10
}
}
});
// Stolen from heatmap
var colorSeriesMixin = {
// mapping between SVG attributes and the corresponding options
pointAttrToOptions: {},
pointArrayMap: ['value'],
axisTypes: seriesTypes.heatmap ? ['xAxis', 'yAxis', 'colorAxis'] : ['xAxis', 'yAxis'],
optionalAxis: 'colorAxis',
getSymbol: noop,
parallelArrays: ['x', 'y', 'value', 'colorValue'],
colorKey: 'colorValue', // Point color option key
translateColors: seriesTypes.heatmap && seriesTypes.heatmap.prototype.translateColors
};
// The Treemap series type
seriesTypes.treemap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, {
type: 'treemap',
trackerGroups: ['group', 'dataLabelsGroup'],
pointClass: extendClass(H.Point, {
setVisible: seriesTypes.pie.prototype.pointClass.prototype.setVisible
}),
/**
* Creates an object map from parent id to childrens index.
* @param {Array} data List of points set in options.
* @param {string} data[].parent Parent id of point.
* @param {Array} ids List of all point ids.
* @return {Object} Map from parent id to children index in data.
*/
getListOfParents: function (data, ids) {
var listOfParents = reduce(data, function (prev, curr, i) {
var parent = pick(curr.parent, '');
if (prev[parent] === undefined) {
prev[parent] = [];
}
prev[parent].push(i);
return prev;
}, {});
// If parent does not exist, hoist parent to root of tree.
eachObject(listOfParents, function (children, parent, list) {
if ((parent !== '') && (H.inArray(parent, ids) === -1)) {
each(children, function (child) {
list[''].push(child);
});
delete list[parent];
}
});
return listOfParents;
},
/**
* Creates a tree structured object from the series points
*/
getTree: function () {
var tree,
series = this,
allIds = map(this.data, function (d) {
return d.id;
}),
parentList = series.getListOfParents(this.data, allIds);
series.nodeMap = [];
tree = series.buildNode('', -1, 0, parentList, null);
recursive(this.nodeMap[this.rootNode], function (node) {
var next = false,
p = node.parent;
node.visible = true;
if (p || p === '') {
next = series.nodeMap[p];
}
return next;
});
recursive(this.nodeMap[this.rootNode].children, function (children) {
var next = false;
each(children, function (child) {
child.visible = true;
if (child.children.length) {
next = (next || []).concat(child.children);
}
});
return next;
});
this.setTreeValues(tree);
return tree;
},
init: function (chart, options) {
var series = this;
Series.prototype.init.call(series, chart, options);
if (series.options.allowDrillToNode) {
series.drillTo();
}
},
buildNode: function (id, i, level, list, parent) {
var series = this,
children = [],
point = series.points[i],
node,
child;
// Actions
each((list[id] || []), function (i) {
child = series.buildNode(series.points[i].id, i, (level + 1), list, id);
children.push(child);
});
node = {
id: id,
i: i,
children: children,
level: level,
parent: parent,
visible: false // @todo move this to better location
};
series.nodeMap[node.id] = node;
if (point) {
point.node = node;
}
return node;
},
setTreeValues: function (tree) {
var series = this,
options = series.options,
childrenTotal = 0,
children = [],
val,
point = series.points[tree.i];
// First give the children some values
each(tree.children, function (child) {
child = series.setTreeValues(child);
children.push(child);
if (!child.ignore) {
childrenTotal += child.val;
} else {
// @todo Add predicate to avoid looping already ignored children
recursive(child.children, function (children) {
var next = false;
each(children, function (node) {
extend(node, {
ignore: true,
isLeaf: false,
visible: false
});
if (node.children.length) {
next = (next || []).concat(node.children);
}
});
return next;
});
}
});
// Sort the children
stableSort(children, function (a, b) {
return a.sortIndex - b.sortIndex;
});
// Set the values
val = pick(point && point.value, childrenTotal);
extend(tree, {
children: children,
childrenTotal: childrenTotal,
// Ignore this node if point is not visible
ignore: !(pick(point && point.visible, true) && (val > 0)),
isLeaf: tree.visible && !childrenTotal,
levelDynamic: (options.levelIsConstant ? tree.level : (tree.level - series.nodeMap[series.rootNode].level)),
name: pick(point && point.name, ''),
sortIndex: pick(point && point.sortIndex, -val),
val: val
});
return tree;
},
/**
* Recursive function which calculates the area for all children of a node.
* @param {Object} node The node which is parent to the children.
* @param {Object} area The rectangular area of the parent.
*/
calculateChildrenAreas: function (parent, area) {
var series = this,
options = series.options,
level = this.levelMap[parent.levelDynamic + 1],
algorithm = pick((series[level && level.layoutAlgorithm] && level.layoutAlgorithm), options.layoutAlgorithm),
alternate = options.alternateStartingDirection,
childrenValues = [],
children;
// Collect all children which should be included
children = grep(parent.children, function (n) {
return !n.ignore;
});
if (level && level.layoutStartingDirection) {
area.direction = level.layoutStartingDirection === 'vertical' ? 0 : 1;
}
childrenValues = series[algorithm](area, children);
each(children, function (child, index) {
var values = childrenValues[index];
child.values = merge(values, {
val: child.childrenTotal,
direction: (alternate ? 1 - area.direction : area.direction)
});
child.pointValues = merge(values, {
x: (values.x / series.axisRatio),
width: (values.width / series.axisRatio)
});
// If node has children, then call method recursively
if (child.children.length) {
series.calculateChildrenAreas(child, child.values);
}
});
},
setPointValues: function () {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis;
each(series.points, function (point) {
var node = point.node,
values = node.pointValues,
x1,
x2,
y1,
y2;
// Points which is ignored, have no values.
if (values) {
x1 = Math.round(xAxis.translate(values.x, 0, 0, 0, 1));
x2 = Math.round(xAxis.translate(values.x + values.width, 0, 0, 0, 1));
y1 = Math.round(yAxis.translate(values.y, 0, 0, 0, 1));
y2 = Math.round(yAxis.translate(values.y + values.height, 0, 0, 0, 1));
// Set point values
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
point.plotX = point.shapeArgs.x + (point.shapeArgs.width / 2);
point.plotY = point.shapeArgs.y + (point.shapeArgs.height / 2);
} else {
// Reset visibility
delete point.plotX;
delete point.plotY;
}
});
},
setColorRecursive: function (node, color) {
var series = this,
point,
level;
if (node) {
point = series.points[node.i];
level = series.levelMap[node.levelDynamic];
// Select either point color, level color or inherited color.
color = pick(point && point.options.color, level && level.color, color);
if (point) {
point.color = color;
}
// Do it all again with the children
if (node.children.length) {
each(node.children, function (child) {
series.setColorRecursive(child, color);
});
}
}
},
algorithmGroup: function (h, w, d, p) {
this.height = h;
this.width = w;
this.plot = p;
this.direction = d;
this.startDirection = d;
this.total = 0;
this.nW = 0;
this.lW = 0;
this.nH = 0;
this.lH = 0;
this.elArr = [];
this.lP = {
total: 0,
lH: 0,
nH: 0,
lW: 0,
nW: 0,
nR: 0,
lR: 0,
aspectRatio: function (w, h) {
return Math.max((w / h), (h / w));
}
};
this.addElement = function (el) {
this.lP.total = this.elArr[this.elArr.length - 1];
this.total = this.total + el;
if (this.direction === 0) {
// Calculate last point old aspect ratio
this.lW = this.nW;
this.lP.lH = this.lP.total / this.lW;
this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH);
// Calculate last point new aspect ratio
this.nW = this.total / this.height;
this.lP.nH = this.lP.total / this.nW;
this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH);
} else {
// Calculate last point old aspect ratio
this.lH = this.nH;
this.lP.lW = this.lP.total / this.lH;
this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH);
// Calculate last point new aspect ratio
this.nH = this.total / this.width;
this.lP.nW = this.lP.total / this.nH;
this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH);
}
this.elArr.push(el);
};
this.reset = function () {
this.nW = 0;
this.lW = 0;
this.elArr = [];
this.total = 0;
};
},
algorithmCalcPoints: function (directionChange, last, group, childrenArea) {
var pX,
pY,
pW,
pH,
gW = group.lW,
gH = group.lH,
plot = group.plot,
keep,
i = 0,
end = group.elArr.length - 1;
if (last) {
gW = group.nW;
gH = group.nH;
} else {
keep = group.elArr[group.elArr.length - 1];
}
each(group.elArr, function (p) {
if (last || (i < end)) {
if (group.direction === 0) {
pX = plot.x;
pY = plot.y;
pW = gW;
pH = p / pW;
} else {
pX = plot.x;
pY = plot.y;
pH = gH;
pW = p / pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (group.direction === 0) {
plot.y = plot.y + pH;
} else {
plot.x = plot.x + pW;
}
}
i = i + 1;
});
// Reset variables
group.reset();
if (group.direction === 0) {
group.width = group.width - gW;
} else {
group.height = group.height - gH;
}
plot.y = plot.parent.y + (plot.parent.height - group.height);
plot.x = plot.parent.x + (plot.parent.width - group.width);
if (directionChange) {
group.direction = 1 - group.direction;
}
// If not last, then add uncalculated element
if (!last) {
group.addElement(keep);
}
},
algorithmLowAspectRatio: function (directionChange, parent, children) {
var childrenArea = [],
series = this,
pTot,
plot = {
x: parent.x,
y: parent.y,
parent: parent
},
direction = parent.direction,
i = 0,
end = children.length - 1,
group = new this.algorithmGroup(parent.height, parent.width, direction, plot);
// Loop through and calculate all areas
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
group.addElement(pTot);
if (group.lP.nR > group.lP.lR) {
series.algorithmCalcPoints(directionChange, false, group, childrenArea, plot);
}
// If last child, then calculate all remaining areas
if (i === end) {
series.algorithmCalcPoints(directionChange, true, group, childrenArea, plot);
}
i = i + 1;
});
return childrenArea;
},
algorithmFill: function (directionChange, parent, children) {
var childrenArea = [],
pTot,
direction = parent.direction,
x = parent.x,
y = parent.y,
width = parent.width,
height = parent.height,
pX,
pY,
pW,
pH;
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
pX = x;
pY = y;
if (direction === 0) {
pH = height;
pW = pTot / pH;
width = width - pW;
x = x + pW;
} else {
pW = width;
pH = pTot / pW;
height = height - pH;
y = y + pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (directionChange) {
direction = 1 - direction;
}
});
return childrenArea;
},
strip: function (parent, children) {
return this.algorithmLowAspectRatio(false, parent, children);
},
squarified: function (parent, children) {
return this.algorithmLowAspectRatio(true, parent, children);
},
sliceAndDice: function (parent, children) {
return this.algorithmFill(true, parent, children);
},
stripes: function (parent, children) {
return this.algorithmFill(false, parent, children);
},
translate: function () {
var pointValues,
seriesArea,
tree,
val;
// Call prototype function
Series.prototype.translate.call(this);
// Assign variables
this.rootNode = pick(this.options.rootId, '');
// Create a object map from level to options
this.levelMap = reduce(this.options.levels, function (arr, item) {
arr[item.level] = item;
return arr;
}, {});
tree = this.tree = this.getTree(); // @todo Only if series.isDirtyData is true
// Calculate plotting values.
this.axisRatio = (this.xAxis.len / this.yAxis.len);
this.nodeMap[''].pointValues = pointValues = { x: 0, y: 0, width: 100, height: 100 };
this.nodeMap[''].values = seriesArea = merge(pointValues, {
width: (pointValues.width * this.axisRatio),
direction: (this.options.layoutStartingDirection === 'vertical' ? 0 : 1),
val: tree.val
});
this.calculateChildrenAreas(tree, seriesArea);
// Logic for point colors
if (this.colorAxis) {
this.translateColors();
} else if (!this.options.colorByPoint) {
this.setColorRecursive(this.tree, undefined);
}
// Update axis extremes according to the root node.
val = this.nodeMap[this.rootNode].pointValues;
this.xAxis.setExtremes(val.x, val.x + val.width, false);
this.yAxis.setExtremes(val.y, val.y + val.height, false);
this.xAxis.setScale();
this.yAxis.setScale();
// Assign values to points.
this.setPointValues();
},
/**
* Extend drawDataLabels with logic to handle custom options related to the treemap series:
* - Points which is not a leaf node, has dataLabels disabled by default.
* - Options set on series.levels is merged in.
* - Width of the dataLabel is set to match the width of the point shape.
*/
drawDataLabels: function () {
var series = this,
points = grep(series.points, function (n) {
return n.node.visible;
}),
options,
level;
each(points, function (point) {
level = series.levelMap[point.node.levelDynamic];
// Set options to new object to avoid problems with scope
options = { style: {} };
// If not a leaf, then label should be disabled as default
if (!point.node.isLeaf) {
options.enabled = false;
}
// If options for level exists, include them as well
if (level && level.dataLabels) {
options = merge(options, level.dataLabels);
series._hasPointLabels = true;
}
// Set dataLabel width to the width of the point shape.
if (point.shapeArgs) {
options.style.width = point.shapeArgs.width;
}
// Merge custom options with point options
point.dlOptions = merge(options, point.options.dataLabels);
});
Series.prototype.drawDataLabels.call(this);
},
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
/**
* Get presentational attributes
*/
pointAttribs: function (point, state) {
var level = this.levelMap[point.node.levelDynamic] || {},
options = this.options,
attr,
stateOptions = (state && options.states[state]) || {};
// Set attributes by precedence. Point trumps level trumps series. Stroke width uses pick
// because it can be 0.
attr = {
'stroke': point.borderColor || level.borderColor || stateOptions.borderColor || options.borderColor,
'stroke-width': pick(point.borderWidth, level.borderWidth, stateOptions.borderWidth, options.borderWidth),
'dashstyle': point.borderDashStyle || level.borderDashStyle || stateOptions.borderDashStyle || options.borderDashStyle,
'fill': point.color || this.color,
'zIndex': state === 'hover' ? 1 : 0
};
if (point.node.level <= this.nodeMap[this.rootNode].level) {
// Hide levels above the current view
attr.fill = 'none';
attr['stroke-width'] = 0;
} else if (!point.node.isLeaf) {
// If not a leaf, then remove fill
// @todo let users set the opacity
attr.fill = pick(options.interactByLeaf, !options.allowDrillToNode) ? 'none' : Color(attr.fill).setOpacity(state === 'hover' ? 0.75 : 0.15).get();
} else if (state) {
// Brighten and hoist the hover nodes
attr.fill = Color(attr.fill).brighten(stateOptions.brightness).get();
}
return attr;
},
/**
* Extending ColumnSeries drawPoints
*/
drawPoints: function () {
var series = this,
points = grep(series.points, function (n) {
return n.node.visible;
});
each(points, function (point) {
var groupKey = 'levelGroup-' + point.node.levelDynamic;
if (!series[groupKey]) {
series[groupKey] = series.chart.renderer.g(groupKey)
.attr({
zIndex: 1000 - point.node.levelDynamic // @todo Set the zIndex based upon the number of levels, instead of using 1000
})
.add(series.group);
}
point.group = series[groupKey];
// Preliminary code in prepraration for HC5 that uses pointAttribs for all series
point.pointAttr = {
'': series.pointAttribs(point),
'hover': series.pointAttribs(point, 'hover'),
'select': {}
};
});
// Call standard drawPoints
seriesTypes.column.prototype.drawPoints.call(this);
// If drillToNode is allowed, set a point cursor on clickables & add drillId to point
if (series.options.allowDrillToNode) {
each(points, function (point) {
var cursor,
drillId;
if (point.graphic) {
drillId = point.drillId = series.options.interactByLeaf ? series.drillToByLeaf(point) : series.drillToByGroup(point);
cursor = drillId ? 'pointer' : 'default';
point.graphic.css({ cursor: cursor });
}
});
}
},
/**
* Add drilling on the suitable points
*/
drillTo: function () {
var series = this;
H.addEvent(series, 'click', function (event) {
var point = event.point,
drillId = point.drillId,
drillName;
// If a drill id is returned, add click event and cursor.
if (drillId) {
drillName = series.nodeMap[series.rootNode].name || series.rootNode;
point.setState(''); // Remove hover
series.drillToNode(drillId);
series.showDrillUpButton(drillName);
}
});
},
/**
* Finds the drill id for a parent node.
* Returns false if point should not have a click event
* @param {Object} point
* @return {string || boolean} Drill to id or false when point should not have a click event
*/
drillToByGroup: function (point) {
var series = this,
drillId = false;
if ((point.node.level - series.nodeMap[series.rootNode].level) === 1 && !point.node.isLeaf) {
drillId = point.id;
}
return drillId;
},
/**
* Finds the drill id for a leaf node.
* Returns false if point should not have a click event
* @param {Object} point
* @return {string || boolean} Drill to id or false when point should not have a click event
*/
drillToByLeaf: function (point) {
var series = this,
drillId = false,
nodeParent;
if ((point.node.parent !== series.rootNode) && (point.node.isLeaf)) {
nodeParent = point.node;
while (!drillId) {
nodeParent = series.nodeMap[nodeParent.parent];
if (nodeParent.parent === series.rootNode) {
drillId = nodeParent.id;
}
}
}
return drillId;
},
drillUp: function () {
var drillPoint = null,
node,
parent;
if (this.rootNode) {
node = this.nodeMap[this.rootNode];
if (node.parent !== null) {
drillPoint = this.nodeMap[node.parent];
} else {
drillPoint = this.nodeMap[''];
}
}
if (drillPoint !== null) {
this.drillToNode(drillPoint.id);
if (drillPoint.id === '') {
this.drillUpButton = this.drillUpButton.destroy();
} else {
parent = this.nodeMap[drillPoint.parent];
this.showDrillUpButton((parent.name || parent.id));
}
}
},
drillToNode: function (id) {
this.options.rootId = id;
this.isDirty = true; // Force redraw
this.chart.redraw();
},
showDrillUpButton: function (name) {
var series = this,
backText = (name || '< Back'),
buttonOptions = series.options.drillUpButton,
attr,
states;
if (buttonOptions.text) {
backText = buttonOptions.text;
}
if (!this.drillUpButton) {
attr = buttonOptions.theme;
states = attr && attr.states;
this.drillUpButton = this.chart.renderer.button(
backText,
null,
null,
function () {
series.drillUp();
},
attr,
states && states.hover,
states && states.select
)
.attr({
align: buttonOptions.position.align,
zIndex: 9
})
.add()
.align(buttonOptions.position, false, buttonOptions.relativeTo || 'plotBox');
} else {
this.drillUpButton.attr({
text: backText
})
.align();
}
},
buildKDTree: noop,
drawLegendSymbol: H.LegendSymbolMixin.drawRectangle,
getExtremes: function () {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.colorValueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
},
getExtremesFromAll: true,
bindAxes: function () {
var treeAxis = {
endOnTick: false,
gridLineWidth: 0,
lineWidth: 0,
min: 0,
dataMin: 0,
minPadding: 0,
max: 100,
dataMax: 100,
maxPadding: 0,
startOnTick: false,
title: null,
tickPositions: []
};
Series.prototype.bindAxes.call(this);
H.extend(this.yAxis.options, treeAxis);
H.extend(this.xAxis.options, treeAxis);
}
}));
}));
| morsaken/webim-cms | views/backend/default/layouts/js/plugins/highcharts/modules/treemap.src.js | JavaScript | mit | 24,507 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<title>OpenLayers OSM and Google Example</title>
<link rel="stylesheet" href="../theme/default/style.css" type="text/css">
<link rel="stylesheet" href="../theme/default/google.css" type="text/css">
<link rel="stylesheet" href="style.css" type="text/css">
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false"></script>
<script src="../lib/OpenLayers.js"></script>
<script src="osm-google.js"></script>
</head>
<body onload="init()">
<h1 id="title">OSM and Google Together</h1>
<p id="shortdesc">
Demonstrate use of an OSM layer and a Google layer as base layers.
</p>
<div id="tags">
openstreetmap google light
</div>
<div id="map" class="smallmap"></div>
<div id="docs">
<p>
The Google(v3) layer and the OSM are both in the same projection
- spherical mercator - and can be used on a map together.
See the <a href="osm-google.js" target="_blank">
osm-google.js source</a> to see how this is done.
</p>
</div>
</body>
</html>
| jcuanm/Japan-Digital-Archive | web/js/lib/OpenLayers-2.12/examples/osm-google.html | HTML | mit | 1,464 |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#ifndef __GAME_MISC_H__
#define __GAME_MISC_H__
/*
===============================================================================
idSpawnableEntity
A simple, spawnable entity with a model and no functionable ability of it's own.
For example, it can be used as a placeholder during development, for marking
locations on maps for script, or for simple placed models without any behavior
that can be bound to other entities. Should not be subclassed.
===============================================================================
*/
class idSpawnableEntity : public idEntity {
public:
CLASS_PROTOTYPE( idSpawnableEntity );
void Spawn( void );
private:
};
/*
===============================================================================
Potential spawning position for players.
The first time a player enters the game, they will be at an 'initial' spot.
Targets will be fired when someone spawns in on them.
When triggered, will cause player to be teleported to spawn spot.
===============================================================================
*/
class idPlayerStart : public idEntity {
public:
CLASS_PROTOTYPE( idPlayerStart );
enum {
EVENT_TELEPORTPLAYER = idEntity::EVENT_MAXEVENTS,
EVENT_MAXEVENTS
};
idPlayerStart( void );
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual bool ClientReceiveEvent( int event, int time, const idBitMsg &msg );
private:
int teleportStage;
void Event_TeleportPlayer( idEntity *activator );
void Event_TeleportStage( idEntity *player );
void TeleportPlayer( idPlayer *player );
};
/*
===============================================================================
Non-displayed entity used to activate triggers when it touches them.
Bind to a mover to have the mover activate a trigger as it moves.
When target by triggers, activating the trigger will toggle the
activator on and off. Check "start_off" to have it spawn disabled.
===============================================================================
*/
class idActivator : public idEntity {
public:
CLASS_PROTOTYPE( idActivator );
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual void Think( void );
private:
bool stay_on;
void Event_Activate( idEntity *activator );
};
/*
===============================================================================
Path entities for monsters to follow.
===============================================================================
*/
class idPathCorner : public idEntity {
public:
CLASS_PROTOTYPE( idPathCorner );
void Spawn( void );
static void DrawDebugInfo( void );
static idPathCorner *RandomPath( const idEntity *source, const idEntity *ignore );
private:
void Event_RandomPath( void );
};
/*
===============================================================================
Object that fires targets and changes shader parms when damaged.
===============================================================================
*/
class idDamagable : public idEntity {
public:
CLASS_PROTOTYPE( idDamagable );
idDamagable( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
void Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location );
private:
int count;
int nextTriggerTime;
void BecomeBroken( idEntity *activator );
void Event_BecomeBroken( idEntity *activator );
void Event_RestoreDamagable( void );
};
/*
===============================================================================
Hidden object that explodes when activated
===============================================================================
*/
class idExplodable : public idEntity {
public:
CLASS_PROTOTYPE( idExplodable );
void Spawn( void );
private:
void Event_Explode( idEntity *activator );
};
/*
===============================================================================
idSpring
===============================================================================
*/
class idSpring : public idEntity {
public:
CLASS_PROTOTYPE( idSpring );
void Spawn( void );
virtual void Think( void );
private:
idEntity * ent1;
idEntity * ent2;
int id1;
int id2;
idVec3 p1;
idVec3 p2;
idForce_Spring spring;
void Event_LinkSpring( void );
};
/*
===============================================================================
idForceField
===============================================================================
*/
class idForceField : public idEntity {
public:
CLASS_PROTOTYPE( idForceField );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
virtual void Think( void );
private:
idForce_Field forceField;
void Toggle( void );
void Event_Activate( idEntity *activator );
void Event_Toggle( void );
void Event_FindTargets( void );
};
/*
===============================================================================
idAnimated
===============================================================================
*/
class idAnimated : public idAFEntity_Gibbable {
public:
CLASS_PROTOTYPE( idAnimated );
idAnimated();
~idAnimated();
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
virtual bool LoadAF( void );
bool StartRagdoll( void );
virtual bool GetPhysicsToSoundTransform( idVec3 &origin, idMat3 &axis );
private:
int num_anims;
int current_anim_index;
int anim;
int blendFrames;
jointHandle_t soundJoint;
idEntityPtr<idEntity> activator;
bool activated;
void PlayNextAnim( void );
void Event_Activate( idEntity *activator );
void Event_Start( void );
void Event_StartRagdoll( void );
void Event_AnimDone( int animIndex );
void Event_Footstep( void );
void Event_LaunchMissiles( const char *projectilename, const char *sound, const char *launchjoint, const char *targetjoint, int numshots, int framedelay );
void Event_LaunchMissilesUpdate( int launchjoint, int targetjoint, int numshots, int framedelay );
};
/*
===============================================================================
idStaticEntity
===============================================================================
*/
class idStaticEntity : public idEntity {
public:
CLASS_PROTOTYPE( idStaticEntity );
idStaticEntity( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
void ShowEditingDialog( void );
virtual void Hide( void );
virtual void Show( void );
void Fade( const idVec4 &to, float fadeTime );
virtual void Think( void );
virtual void WriteToSnapshot( idBitMsgDelta &msg ) const;
virtual void ReadFromSnapshot( const idBitMsgDelta &msg );
private:
void Event_Activate( idEntity *activator );
int spawnTime;
bool active;
idVec4 fadeFrom;
idVec4 fadeTo;
int fadeStart;
int fadeEnd;
bool runGui;
};
/*
===============================================================================
idFuncEmitter
===============================================================================
*/
class idFuncEmitter : public idStaticEntity {
public:
CLASS_PROTOTYPE( idFuncEmitter );
idFuncEmitter( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Spawn( void );
void Event_Activate( idEntity *activator );
virtual void WriteToSnapshot( idBitMsgDelta &msg ) const;
virtual void ReadFromSnapshot( const idBitMsgDelta &msg );
private:
bool hidden;
};
/*
===============================================================================
idFuncSmoke
===============================================================================
*/
class idFuncSmoke : public idEntity {
public:
CLASS_PROTOTYPE( idFuncSmoke );
idFuncSmoke();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual void Think( void );
void Event_Activate( idEntity *activator );
private:
int smokeTime;
const idDeclParticle * smoke;
bool restart;
};
/*
===============================================================================
idFuncSplat
===============================================================================
*/
class idFuncSplat : public idFuncEmitter {
public:
CLASS_PROTOTYPE( idFuncSplat );
idFuncSplat( void );
void Spawn( void );
private:
void Event_Activate( idEntity *activator );
void Event_Splat();
};
/*
===============================================================================
idTextEntity
===============================================================================
*/
class idTextEntity : public idEntity {
public:
CLASS_PROTOTYPE( idTextEntity );
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual void Think( void );
private:
idStr text;
bool playerOriented;
};
/*
===============================================================================
idLocationEntity
===============================================================================
*/
class idLocationEntity : public idEntity {
public:
CLASS_PROTOTYPE( idLocationEntity );
void Spawn( void );
const char * GetLocation( void ) const;
private:
};
class idLocationSeparatorEntity : public idEntity {
public:
CLASS_PROTOTYPE( idLocationSeparatorEntity );
void Spawn( void );
private:
};
class idVacuumSeparatorEntity : public idEntity {
public:
CLASS_PROTOTYPE( idVacuumSeparatorEntity );
idVacuumSeparatorEntity( void );
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
void Event_Activate( idEntity *activator );
private:
qhandle_t portal;
};
class idVacuumEntity : public idEntity {
public:
CLASS_PROTOTYPE( idVacuumEntity );
void Spawn( void );
private:
};
/*
===============================================================================
idBeam
===============================================================================
*/
class idBeam : public idEntity {
public:
CLASS_PROTOTYPE( idBeam );
idBeam();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual void Think( void );
void SetMaster( idBeam *masterbeam );
void SetBeamTarget( const idVec3 &origin );
virtual void Show( void );
virtual void WriteToSnapshot( idBitMsgDelta &msg ) const;
virtual void ReadFromSnapshot( const idBitMsgDelta &msg );
private:
void Event_MatchTarget( void );
void Event_Activate( idEntity *activator );
idEntityPtr<idBeam> target;
idEntityPtr<idBeam> master;
};
/*
===============================================================================
idLiquid
===============================================================================
*/
class idRenderModelLiquid;
class idLiquid : public idEntity {
public:
CLASS_PROTOTYPE( idLiquid );
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
private:
void Event_Touch( idEntity *other, trace_t *trace );
idRenderModelLiquid *model;
};
/*
===============================================================================
idShaking
===============================================================================
*/
class idShaking : public idEntity {
public:
CLASS_PROTOTYPE( idShaking );
idShaking();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
private:
idPhysics_Parametric physicsObj;
bool active;
void BeginShaking( void );
void Event_Activate( idEntity *activator );
};
/*
===============================================================================
idEarthQuake
===============================================================================
*/
class idEarthQuake : public idEntity {
public:
CLASS_PROTOTYPE( idEarthQuake );
idEarthQuake();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual void Think( void );
private:
int nextTriggerTime;
int shakeStopTime;
float wait;
float random;
bool triggered;
bool playerOriented;
bool disabled;
float shakeTime;
void Event_Activate( idEntity *activator );
};
/*
===============================================================================
idFuncPortal
===============================================================================
*/
class idFuncPortal : public idEntity {
public:
CLASS_PROTOTYPE( idFuncPortal );
idFuncPortal();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
private:
qhandle_t portal;
bool state;
void Event_Activate( idEntity *activator );
};
/*
===============================================================================
idFuncAASPortal
===============================================================================
*/
class idFuncAASPortal : public idEntity {
public:
CLASS_PROTOTYPE( idFuncAASPortal );
idFuncAASPortal();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
private:
bool state;
void Event_Activate( idEntity *activator );
};
/*
===============================================================================
idFuncAASObstacle
===============================================================================
*/
class idFuncAASObstacle : public idEntity {
public:
CLASS_PROTOTYPE( idFuncAASObstacle );
idFuncAASObstacle();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
private:
bool state;
void Event_Activate( idEntity *activator );
};
/*
===============================================================================
idFuncRadioChatter
===============================================================================
*/
class idFuncRadioChatter : public idEntity {
public:
CLASS_PROTOTYPE( idFuncRadioChatter );
idFuncRadioChatter();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
private:
float time;
void Event_Activate( idEntity *activator );
void Event_ResetRadioHud( idEntity *activator );
};
/*
===============================================================================
idPhantomObjects
===============================================================================
*/
class idPhantomObjects : public idEntity {
public:
CLASS_PROTOTYPE( idPhantomObjects );
idPhantomObjects();
void Spawn( void );
void Save( idSaveGame *savefile ) const;
void Restore( idRestoreGame *savefile );
virtual void Think( void );
private:
void Event_Activate( idEntity *activator );
void Event_Throw( void );
void Event_ShakeObject( idEntity *object, int starttime );
int end_time;
float throw_time;
float shake_time;
idVec3 shake_ang;
float speed;
int min_wait;
int max_wait;
idEntityPtr<idActor>target;
idList<int> targetTime;
idList<idVec3> lastTargetPos;
};
#endif /* !__GAME_MISC_H__ */
| divyang4481/bclcontrib-scriptsharp | ref.neo/game/Misc.h | C | mit | 17,283 |
#include <linux/hw_breakpoint.h>
#include "util.h"
#include "../perf.h"
#include "evlist.h"
#include "evsel.h"
#include "parse-options.h"
#include "parse-events.h"
#include "exec_cmd.h"
#include "string.h"
#include "symbol.h"
#include "cache.h"
#include "header.h"
#include "debugfs.h"
#include "parse-events-bison.h"
#define YY_EXTRA_TYPE int
#include "parse-events-flex.h"
#include "pmu.h"
#define MAX_NAME_LEN 100
struct event_symbol {
const char *symbol;
const char *alias;
};
#ifdef PARSER_DEBUG
extern int parse_events_debug;
#endif
int parse_events_parse(void *data, void *scanner);
static struct event_symbol event_symbols_hw[PERF_COUNT_HW_MAX] = {
[PERF_COUNT_HW_CPU_CYCLES] = {
.symbol = "cpu-cycles",
.alias = "cycles",
},
[PERF_COUNT_HW_INSTRUCTIONS] = {
.symbol = "instructions",
.alias = "",
},
[PERF_COUNT_HW_CACHE_REFERENCES] = {
.symbol = "cache-references",
.alias = "",
},
[PERF_COUNT_HW_CACHE_MISSES] = {
.symbol = "cache-misses",
.alias = "",
},
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = {
.symbol = "branch-instructions",
.alias = "branches",
},
[PERF_COUNT_HW_BRANCH_MISSES] = {
.symbol = "branch-misses",
.alias = "",
},
[PERF_COUNT_HW_BUS_CYCLES] = {
.symbol = "bus-cycles",
.alias = "",
},
[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = {
.symbol = "stalled-cycles-frontend",
.alias = "idle-cycles-frontend",
},
[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = {
.symbol = "stalled-cycles-backend",
.alias = "idle-cycles-backend",
},
[PERF_COUNT_HW_REF_CPU_CYCLES] = {
.symbol = "ref-cycles",
.alias = "",
},
};
static struct event_symbol event_symbols_sw[PERF_COUNT_SW_MAX] = {
[PERF_COUNT_SW_CPU_CLOCK] = {
.symbol = "cpu-clock",
.alias = "",
},
[PERF_COUNT_SW_TASK_CLOCK] = {
.symbol = "task-clock",
.alias = "",
},
[PERF_COUNT_SW_PAGE_FAULTS] = {
.symbol = "page-faults",
.alias = "faults",
},
[PERF_COUNT_SW_CONTEXT_SWITCHES] = {
.symbol = "context-switches",
.alias = "cs",
},
[PERF_COUNT_SW_CPU_MIGRATIONS] = {
.symbol = "cpu-migrations",
.alias = "migrations",
},
[PERF_COUNT_SW_PAGE_FAULTS_MIN] = {
.symbol = "minor-faults",
.alias = "",
},
[PERF_COUNT_SW_PAGE_FAULTS_MAJ] = {
.symbol = "major-faults",
.alias = "",
},
[PERF_COUNT_SW_ALIGNMENT_FAULTS] = {
.symbol = "alignment-faults",
.alias = "",
},
[PERF_COUNT_SW_EMULATION_FAULTS] = {
.symbol = "emulation-faults",
.alias = "",
},
};
#define __PERF_EVENT_FIELD(config, name) \
((config & PERF_EVENT_##name##_MASK) >> PERF_EVENT_##name##_SHIFT)
#define PERF_EVENT_RAW(config) __PERF_EVENT_FIELD(config, RAW)
#define PERF_EVENT_CONFIG(config) __PERF_EVENT_FIELD(config, CONFIG)
#define PERF_EVENT_TYPE(config) __PERF_EVENT_FIELD(config, TYPE)
#define PERF_EVENT_ID(config) __PERF_EVENT_FIELD(config, EVENT)
#define for_each_subsystem(sys_dir, sys_dirent, sys_next) \
while (!readdir_r(sys_dir, &sys_dirent, &sys_next) && sys_next) \
if (sys_dirent.d_type == DT_DIR && \
(strcmp(sys_dirent.d_name, ".")) && \
(strcmp(sys_dirent.d_name, "..")))
static int tp_event_has_id(struct dirent *sys_dir, struct dirent *evt_dir)
{
char evt_path[MAXPATHLEN];
int fd;
snprintf(evt_path, MAXPATHLEN, "%s/%s/%s/id", tracing_events_path,
sys_dir->d_name, evt_dir->d_name);
fd = open(evt_path, O_RDONLY);
if (fd < 0)
return -EINVAL;
close(fd);
return 0;
}
#define for_each_event(sys_dirent, evt_dir, evt_dirent, evt_next) \
while (!readdir_r(evt_dir, &evt_dirent, &evt_next) && evt_next) \
if (evt_dirent.d_type == DT_DIR && \
(strcmp(evt_dirent.d_name, ".")) && \
(strcmp(evt_dirent.d_name, "..")) && \
(!tp_event_has_id(&sys_dirent, &evt_dirent)))
#define MAX_EVENT_LENGTH 512
struct tracepoint_path *tracepoint_id_to_path(u64 config)
{
struct tracepoint_path *path = NULL;
DIR *sys_dir, *evt_dir;
struct dirent *sys_next, *evt_next, sys_dirent, evt_dirent;
char id_buf[24];
int fd;
u64 id;
char evt_path[MAXPATHLEN];
char dir_path[MAXPATHLEN];
if (debugfs_valid_mountpoint(tracing_events_path))
return NULL;
sys_dir = opendir(tracing_events_path);
if (!sys_dir)
return NULL;
for_each_subsystem(sys_dir, sys_dirent, sys_next) {
snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
sys_dirent.d_name);
evt_dir = opendir(dir_path);
if (!evt_dir)
continue;
for_each_event(sys_dirent, evt_dir, evt_dirent, evt_next) {
snprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path,
evt_dirent.d_name);
fd = open(evt_path, O_RDONLY);
if (fd < 0)
continue;
if (read(fd, id_buf, sizeof(id_buf)) < 0) {
close(fd);
continue;
}
close(fd);
id = atoll(id_buf);
if (id == config) {
closedir(evt_dir);
closedir(sys_dir);
path = zalloc(sizeof(*path));
path->system = malloc(MAX_EVENT_LENGTH);
if (!path->system) {
free(path);
return NULL;
}
path->name = malloc(MAX_EVENT_LENGTH);
if (!path->name) {
free(path->system);
free(path);
return NULL;
}
strncpy(path->system, sys_dirent.d_name,
MAX_EVENT_LENGTH);
strncpy(path->name, evt_dirent.d_name,
MAX_EVENT_LENGTH);
return path;
}
}
closedir(evt_dir);
}
closedir(sys_dir);
return NULL;
}
const char *event_type(int type)
{
switch (type) {
case PERF_TYPE_HARDWARE:
return "hardware";
case PERF_TYPE_SOFTWARE:
return "software";
case PERF_TYPE_TRACEPOINT:
return "tracepoint";
case PERF_TYPE_HW_CACHE:
return "hardware-cache";
default:
break;
}
return "unknown";
}
static int __add_event(struct list_head **_list, int *idx,
struct perf_event_attr *attr,
char *name, struct cpu_map *cpus)
{
struct perf_evsel *evsel;
struct list_head *list = *_list;
if (!list) {
list = malloc(sizeof(*list));
if (!list)
return -ENOMEM;
INIT_LIST_HEAD(list);
}
event_attr_init(attr);
evsel = perf_evsel__new(attr, (*idx)++);
if (!evsel) {
free(list);
return -ENOMEM;
}
evsel->cpus = cpus;
if (name)
evsel->name = strdup(name);
list_add_tail(&evsel->node, list);
*_list = list;
return 0;
}
static int add_event(struct list_head **_list, int *idx,
struct perf_event_attr *attr, char *name)
{
return __add_event(_list, idx, attr, name, NULL);
}
static int parse_aliases(char *str, const char *names[][PERF_EVSEL__MAX_ALIASES], int size)
{
int i, j;
int n, longest = -1;
for (i = 0; i < size; i++) {
for (j = 0; j < PERF_EVSEL__MAX_ALIASES && names[i][j]; j++) {
n = strlen(names[i][j]);
if (n > longest && !strncasecmp(str, names[i][j], n))
longest = n;
}
if (longest > 0)
return i;
}
return -1;
}
int parse_events_add_cache(struct list_head **list, int *idx,
char *type, char *op_result1, char *op_result2)
{
struct perf_event_attr attr;
char name[MAX_NAME_LEN];
int cache_type = -1, cache_op = -1, cache_result = -1;
char *op_result[2] = { op_result1, op_result2 };
int i, n;
/*
* No fallback - if we cannot get a clear cache type
* then bail out:
*/
cache_type = parse_aliases(type, perf_evsel__hw_cache,
PERF_COUNT_HW_CACHE_MAX);
if (cache_type == -1)
return -EINVAL;
n = snprintf(name, MAX_NAME_LEN, "%s", type);
for (i = 0; (i < 2) && (op_result[i]); i++) {
char *str = op_result[i];
n += snprintf(name + n, MAX_NAME_LEN - n, "-%s", str);
if (cache_op == -1) {
cache_op = parse_aliases(str, perf_evsel__hw_cache_op,
PERF_COUNT_HW_CACHE_OP_MAX);
if (cache_op >= 0) {
if (!perf_evsel__is_cache_op_valid(cache_type, cache_op))
return -EINVAL;
continue;
}
}
if (cache_result == -1) {
cache_result = parse_aliases(str, perf_evsel__hw_cache_result,
PERF_COUNT_HW_CACHE_RESULT_MAX);
if (cache_result >= 0)
continue;
}
}
/*
* Fall back to reads:
*/
if (cache_op == -1)
cache_op = PERF_COUNT_HW_CACHE_OP_READ;
/*
* Fall back to accesses:
*/
if (cache_result == -1)
cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS;
memset(&attr, 0, sizeof(attr));
attr.config = cache_type | (cache_op << 8) | (cache_result << 16);
attr.type = PERF_TYPE_HW_CACHE;
return add_event(list, idx, &attr, name);
}
static int add_tracepoint(struct list_head **listp, int *idx,
char *sys_name, char *evt_name)
{
struct perf_evsel *evsel;
struct list_head *list = *listp;
if (!list) {
list = malloc(sizeof(*list));
if (!list)
return -ENOMEM;
INIT_LIST_HEAD(list);
}
evsel = perf_evsel__newtp(sys_name, evt_name, (*idx)++);
if (!evsel) {
free(list);
return -ENOMEM;
}
list_add_tail(&evsel->node, list);
*listp = list;
return 0;
}
static int add_tracepoint_multi_event(struct list_head **list, int *idx,
char *sys_name, char *evt_name)
{
char evt_path[MAXPATHLEN];
struct dirent *evt_ent;
DIR *evt_dir;
int ret = 0;
snprintf(evt_path, MAXPATHLEN, "%s/%s", tracing_events_path, sys_name);
evt_dir = opendir(evt_path);
if (!evt_dir) {
perror("Can't open event dir");
return -1;
}
while (!ret && (evt_ent = readdir(evt_dir))) {
if (!strcmp(evt_ent->d_name, ".")
|| !strcmp(evt_ent->d_name, "..")
|| !strcmp(evt_ent->d_name, "enable")
|| !strcmp(evt_ent->d_name, "filter"))
continue;
if (!strglobmatch(evt_ent->d_name, evt_name))
continue;
ret = add_tracepoint(list, idx, sys_name, evt_ent->d_name);
}
closedir(evt_dir);
return ret;
}
static int add_tracepoint_event(struct list_head **list, int *idx,
char *sys_name, char *evt_name)
{
return strpbrk(evt_name, "*?") ?
add_tracepoint_multi_event(list, idx, sys_name, evt_name) :
add_tracepoint(list, idx, sys_name, evt_name);
}
static int add_tracepoint_multi_sys(struct list_head **list, int *idx,
char *sys_name, char *evt_name)
{
struct dirent *events_ent;
DIR *events_dir;
int ret = 0;
events_dir = opendir(tracing_events_path);
if (!events_dir) {
perror("Can't open event dir");
return -1;
}
while (!ret && (events_ent = readdir(events_dir))) {
if (!strcmp(events_ent->d_name, ".")
|| !strcmp(events_ent->d_name, "..")
|| !strcmp(events_ent->d_name, "enable")
|| !strcmp(events_ent->d_name, "header_event")
|| !strcmp(events_ent->d_name, "header_page"))
continue;
if (!strglobmatch(events_ent->d_name, sys_name))
continue;
ret = add_tracepoint_event(list, idx, events_ent->d_name,
evt_name);
}
closedir(events_dir);
return ret;
}
int parse_events_add_tracepoint(struct list_head **list, int *idx,
char *sys, char *event)
{
int ret;
ret = debugfs_valid_mountpoint(tracing_events_path);
if (ret)
return ret;
if (strpbrk(sys, "*?"))
return add_tracepoint_multi_sys(list, idx, sys, event);
else
return add_tracepoint_event(list, idx, sys, event);
}
static int
parse_breakpoint_type(const char *type, struct perf_event_attr *attr)
{
int i;
for (i = 0; i < 3; i++) {
if (!type || !type[i])
break;
#define CHECK_SET_TYPE(bit) \
do { \
if (attr->bp_type & bit) \
return -EINVAL; \
else \
attr->bp_type |= bit; \
} while (0)
switch (type[i]) {
case 'r':
CHECK_SET_TYPE(HW_BREAKPOINT_R);
break;
case 'w':
CHECK_SET_TYPE(HW_BREAKPOINT_W);
break;
case 'x':
CHECK_SET_TYPE(HW_BREAKPOINT_X);
break;
default:
return -EINVAL;
}
}
#undef CHECK_SET_TYPE
if (!attr->bp_type) /* Default */
attr->bp_type = HW_BREAKPOINT_R | HW_BREAKPOINT_W;
return 0;
}
int parse_events_add_breakpoint(struct list_head **list, int *idx,
void *ptr, char *type)
{
struct perf_event_attr attr;
memset(&attr, 0, sizeof(attr));
attr.bp_addr = (unsigned long) ptr;
if (parse_breakpoint_type(type, &attr))
return -EINVAL;
/*
* We should find a nice way to override the access length
* Provide some defaults for now
*/
if (attr.bp_type == HW_BREAKPOINT_X)
attr.bp_len = sizeof(long);
else
attr.bp_len = HW_BREAKPOINT_LEN_4;
attr.type = PERF_TYPE_BREAKPOINT;
attr.sample_period = 1;
return add_event(list, idx, &attr, NULL);
}
static int config_term(struct perf_event_attr *attr,
struct parse_events_term *term)
{
#define CHECK_TYPE_VAL(type) \
do { \
if (PARSE_EVENTS__TERM_TYPE_ ## type != term->type_val) \
return -EINVAL; \
} while (0)
switch (term->type_term) {
case PARSE_EVENTS__TERM_TYPE_CONFIG:
CHECK_TYPE_VAL(NUM);
attr->config = term->val.num;
break;
case PARSE_EVENTS__TERM_TYPE_CONFIG1:
CHECK_TYPE_VAL(NUM);
attr->config1 = term->val.num;
break;
case PARSE_EVENTS__TERM_TYPE_CONFIG2:
CHECK_TYPE_VAL(NUM);
attr->config2 = term->val.num;
break;
case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
CHECK_TYPE_VAL(NUM);
attr->sample_period = term->val.num;
break;
case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
/*
* TODO uncomment when the field is available
* attr->branch_sample_type = term->val.num;
*/
break;
case PARSE_EVENTS__TERM_TYPE_NAME:
CHECK_TYPE_VAL(STR);
break;
default:
return -EINVAL;
}
return 0;
#undef CHECK_TYPE_VAL
}
static int config_attr(struct perf_event_attr *attr,
struct list_head *head, int fail)
{
struct parse_events_term *term;
list_for_each_entry(term, head, list)
if (config_term(attr, term) && fail)
return -EINVAL;
return 0;
}
int parse_events_add_numeric(struct list_head **list, int *idx,
u32 type, u64 config,
struct list_head *head_config)
{
struct perf_event_attr attr;
memset(&attr, 0, sizeof(attr));
attr.type = type;
attr.config = config;
if (head_config &&
config_attr(&attr, head_config, 1))
return -EINVAL;
return add_event(list, idx, &attr, NULL);
}
static int parse_events__is_name_term(struct parse_events_term *term)
{
return term->type_term == PARSE_EVENTS__TERM_TYPE_NAME;
}
static char *pmu_event_name(struct list_head *head_terms)
{
struct parse_events_term *term;
list_for_each_entry(term, head_terms, list)
if (parse_events__is_name_term(term))
return term->val.str;
return NULL;
}
int parse_events_add_pmu(struct list_head **list, int *idx,
char *name, struct list_head *head_config)
{
struct perf_event_attr attr;
struct perf_pmu *pmu;
pmu = perf_pmu__find(name);
if (!pmu)
return -EINVAL;
memset(&attr, 0, sizeof(attr));
if (perf_pmu__check_alias(pmu, head_config))
return -EINVAL;
/*
* Configure hardcoded terms first, no need to check
* return value when called with fail == 0 ;)
*/
config_attr(&attr, head_config, 0);
if (perf_pmu__config(pmu, &attr, head_config))
return -EINVAL;
return __add_event(list, idx, &attr, pmu_event_name(head_config),
pmu->cpus);
}
int parse_events__modifier_group(struct list_head *list,
char *event_mod)
{
return parse_events__modifier_event(list, event_mod, true);
}
void parse_events__set_leader(char *name, struct list_head *list)
{
struct perf_evsel *leader;
__perf_evlist__set_leader(list);
leader = list_entry(list->next, struct perf_evsel, node);
leader->group_name = name ? strdup(name) : NULL;
}
void parse_events_update_lists(struct list_head *list_event,
struct list_head *list_all)
{
/*
* Called for single event definition. Update the
* 'all event' list, and reinit the 'single event'
* list, for next event definition.
*/
list_splice_tail(list_event, list_all);
free(list_event);
}
struct event_modifier {
int eu;
int ek;
int eh;
int eH;
int eG;
int precise;
int exclude_GH;
};
static int get_event_modifier(struct event_modifier *mod, char *str,
struct perf_evsel *evsel)
{
int eu = evsel ? evsel->attr.exclude_user : 0;
int ek = evsel ? evsel->attr.exclude_kernel : 0;
int eh = evsel ? evsel->attr.exclude_hv : 0;
int eH = evsel ? evsel->attr.exclude_host : 0;
int eG = evsel ? evsel->attr.exclude_guest : 0;
int precise = evsel ? evsel->attr.precise_ip : 0;
int exclude = eu | ek | eh;
int exclude_GH = evsel ? evsel->exclude_GH : 0;
memset(mod, 0, sizeof(*mod));
while (*str) {
if (*str == 'u') {
if (!exclude)
exclude = eu = ek = eh = 1;
eu = 0;
} else if (*str == 'k') {
if (!exclude)
exclude = eu = ek = eh = 1;
ek = 0;
} else if (*str == 'h') {
if (!exclude)
exclude = eu = ek = eh = 1;
eh = 0;
} else if (*str == 'G') {
if (!exclude_GH)
exclude_GH = eG = eH = 1;
eG = 0;
} else if (*str == 'H') {
if (!exclude_GH)
exclude_GH = eG = eH = 1;
eH = 0;
} else if (*str == 'p') {
precise++;
/* use of precise requires exclude_guest */
if (!exclude_GH)
eG = 1;
} else
break;
++str;
}
/*
* precise ip:
*
* 0 - SAMPLE_IP can have arbitrary skid
* 1 - SAMPLE_IP must have constant skid
* 2 - SAMPLE_IP requested to have 0 skid
* 3 - SAMPLE_IP must have 0 skid
*
* See also PERF_RECORD_MISC_EXACT_IP
*/
if (precise > 3)
return -EINVAL;
mod->eu = eu;
mod->ek = ek;
mod->eh = eh;
mod->eH = eH;
mod->eG = eG;
mod->precise = precise;
mod->exclude_GH = exclude_GH;
return 0;
}
/*
* Basic modifier sanity check to validate it contains only one
* instance of any modifier (apart from 'p') present.
*/
static int check_modifier(char *str)
{
char *p = str;
/* The sizeof includes 0 byte as well. */
if (strlen(str) > (sizeof("ukhGHppp") - 1))
return -1;
while (*p) {
if (*p != 'p' && strchr(p + 1, *p))
return -1;
p++;
}
return 0;
}
int parse_events__modifier_event(struct list_head *list, char *str, bool add)
{
struct perf_evsel *evsel;
struct event_modifier mod;
if (str == NULL)
return 0;
if (check_modifier(str))
return -EINVAL;
if (!add && get_event_modifier(&mod, str, NULL))
return -EINVAL;
list_for_each_entry(evsel, list, node) {
if (add && get_event_modifier(&mod, str, evsel))
return -EINVAL;
evsel->attr.exclude_user = mod.eu;
evsel->attr.exclude_kernel = mod.ek;
evsel->attr.exclude_hv = mod.eh;
evsel->attr.precise_ip = mod.precise;
evsel->attr.exclude_host = mod.eH;
evsel->attr.exclude_guest = mod.eG;
evsel->exclude_GH = mod.exclude_GH;
}
return 0;
}
int parse_events_name(struct list_head *list, char *name)
{
struct perf_evsel *evsel;
list_for_each_entry(evsel, list, node) {
if (!evsel->name)
evsel->name = strdup(name);
}
return 0;
}
static int parse_events__scanner(const char *str, void *data, int start_token)
{
YY_BUFFER_STATE buffer;
void *scanner;
int ret;
ret = parse_events_lex_init_extra(start_token, &scanner);
if (ret)
return ret;
buffer = parse_events__scan_string(str, scanner);
#ifdef PARSER_DEBUG
parse_events_debug = 1;
#endif
ret = parse_events_parse(data, scanner);
parse_events__flush_buffer(buffer, scanner);
parse_events__delete_buffer(buffer, scanner);
parse_events_lex_destroy(scanner);
return ret;
}
/*
* parse event config string, return a list of event terms.
*/
int parse_events_terms(struct list_head *terms, const char *str)
{
struct parse_events_terms data = {
.terms = NULL,
};
int ret;
ret = parse_events__scanner(str, &data, PE_START_TERMS);
if (!ret) {
list_splice(data.terms, terms);
free(data.terms);
return 0;
}
parse_events__free_terms(data.terms);
return ret;
}
int parse_events(struct perf_evlist *evlist, const char *str)
{
struct parse_events_evlist data = {
.list = LIST_HEAD_INIT(data.list),
.idx = evlist->nr_entries,
};
int ret;
ret = parse_events__scanner(str, &data, PE_START_EVENTS);
if (!ret) {
int entries = data.idx - evlist->nr_entries;
perf_evlist__splice_list_tail(evlist, &data.list, entries);
evlist->nr_groups += data.nr_groups;
return 0;
}
/*
* There are 2 users - builtin-record and builtin-test objects.
* Both call perf_evlist__delete in case of error, so we dont
* need to bother.
*/
return ret;
}
int parse_events_option(const struct option *opt, const char *str,
int unset __maybe_unused)
{
struct perf_evlist *evlist = *(struct perf_evlist **)opt->value;
int ret = parse_events(evlist, str);
if (ret) {
fprintf(stderr, "invalid or unsupported event: '%s'\n", str);
fprintf(stderr, "Run 'perf list' for a list of valid events\n");
}
return ret;
}
int parse_filter(const struct option *opt, const char *str,
int unset __maybe_unused)
{
struct perf_evlist *evlist = *(struct perf_evlist **)opt->value;
struct perf_evsel *last = NULL;
if (evlist->nr_entries > 0)
last = perf_evlist__last(evlist);
if (last == NULL || last->attr.type != PERF_TYPE_TRACEPOINT) {
fprintf(stderr,
"-F option should follow a -e tracepoint option\n");
return -1;
}
last->filter = strdup(str);
if (last->filter == NULL) {
fprintf(stderr, "not enough memory to hold filter string\n");
return -1;
}
return 0;
}
static const char * const event_type_descriptors[] = {
"Hardware event",
"Software event",
"Tracepoint event",
"Hardware cache event",
"Raw hardware event descriptor",
"Hardware breakpoint",
};
/*
* Print the events from <debugfs_mount_point>/tracing/events
*/
void print_tracepoint_events(const char *subsys_glob, const char *event_glob,
bool name_only)
{
DIR *sys_dir, *evt_dir;
struct dirent *sys_next, *evt_next, sys_dirent, evt_dirent;
char evt_path[MAXPATHLEN];
char dir_path[MAXPATHLEN];
if (debugfs_valid_mountpoint(tracing_events_path))
return;
sys_dir = opendir(tracing_events_path);
if (!sys_dir)
return;
for_each_subsystem(sys_dir, sys_dirent, sys_next) {
if (subsys_glob != NULL &&
!strglobmatch(sys_dirent.d_name, subsys_glob))
continue;
snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
sys_dirent.d_name);
evt_dir = opendir(dir_path);
if (!evt_dir)
continue;
for_each_event(sys_dirent, evt_dir, evt_dirent, evt_next) {
if (event_glob != NULL &&
!strglobmatch(evt_dirent.d_name, event_glob))
continue;
if (name_only) {
printf("%s:%s ", sys_dirent.d_name, evt_dirent.d_name);
continue;
}
snprintf(evt_path, MAXPATHLEN, "%s:%s",
sys_dirent.d_name, evt_dirent.d_name);
printf(" %-50s [%s]\n", evt_path,
event_type_descriptors[PERF_TYPE_TRACEPOINT]);
}
closedir(evt_dir);
}
closedir(sys_dir);
}
/*
* Check whether event is in <debugfs_mount_point>/tracing/events
*/
int is_valid_tracepoint(const char *event_string)
{
DIR *sys_dir, *evt_dir;
struct dirent *sys_next, *evt_next, sys_dirent, evt_dirent;
char evt_path[MAXPATHLEN];
char dir_path[MAXPATHLEN];
if (debugfs_valid_mountpoint(tracing_events_path))
return 0;
sys_dir = opendir(tracing_events_path);
if (!sys_dir)
return 0;
for_each_subsystem(sys_dir, sys_dirent, sys_next) {
snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
sys_dirent.d_name);
evt_dir = opendir(dir_path);
if (!evt_dir)
continue;
for_each_event(sys_dirent, evt_dir, evt_dirent, evt_next) {
snprintf(evt_path, MAXPATHLEN, "%s:%s",
sys_dirent.d_name, evt_dirent.d_name);
if (!strcmp(evt_path, event_string)) {
closedir(evt_dir);
closedir(sys_dir);
return 1;
}
}
closedir(evt_dir);
}
closedir(sys_dir);
return 0;
}
static void __print_events_type(u8 type, struct event_symbol *syms,
unsigned max)
{
char name[64];
unsigned i;
for (i = 0; i < max ; i++, syms++) {
if (strlen(syms->alias))
snprintf(name, sizeof(name), "%s OR %s",
syms->symbol, syms->alias);
else
snprintf(name, sizeof(name), "%s", syms->symbol);
printf(" %-50s [%s]\n", name,
event_type_descriptors[type]);
}
}
void print_events_type(u8 type)
{
if (type == PERF_TYPE_SOFTWARE)
__print_events_type(type, event_symbols_sw, PERF_COUNT_SW_MAX);
else
__print_events_type(type, event_symbols_hw, PERF_COUNT_HW_MAX);
}
int print_hwcache_events(const char *event_glob, bool name_only)
{
unsigned int type, op, i, printed = 0;
char name[64];
for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
/* skip invalid cache type */
if (!perf_evsel__is_cache_op_valid(type, op))
continue;
for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
__perf_evsel__hw_cache_type_op_res_name(type, op, i,
name, sizeof(name));
if (event_glob != NULL && !strglobmatch(name, event_glob))
continue;
if (name_only)
printf("%s ", name);
else
printf(" %-50s [%s]\n", name,
event_type_descriptors[PERF_TYPE_HW_CACHE]);
++printed;
}
}
}
return printed;
}
static void print_symbol_events(const char *event_glob, unsigned type,
struct event_symbol *syms, unsigned max,
bool name_only)
{
unsigned i, printed = 0;
char name[MAX_NAME_LEN];
for (i = 0; i < max; i++, syms++) {
if (event_glob != NULL &&
!(strglobmatch(syms->symbol, event_glob) ||
(syms->alias && strglobmatch(syms->alias, event_glob))))
continue;
if (name_only) {
printf("%s ", syms->symbol);
continue;
}
if (strlen(syms->alias))
snprintf(name, MAX_NAME_LEN, "%s OR %s", syms->symbol, syms->alias);
else
strncpy(name, syms->symbol, MAX_NAME_LEN);
printf(" %-50s [%s]\n", name, event_type_descriptors[type]);
printed++;
}
if (printed)
printf("\n");
}
/*
* Print the help text for the event symbols:
*/
void print_events(const char *event_glob, bool name_only)
{
if (!name_only) {
printf("\n");
printf("List of pre-defined events (to be used in -e):\n");
}
print_symbol_events(event_glob, PERF_TYPE_HARDWARE,
event_symbols_hw, PERF_COUNT_HW_MAX, name_only);
print_symbol_events(event_glob, PERF_TYPE_SOFTWARE,
event_symbols_sw, PERF_COUNT_SW_MAX, name_only);
print_hwcache_events(event_glob, name_only);
if (event_glob != NULL)
return;
if (!name_only) {
printf("\n");
printf(" %-50s [%s]\n",
"rNNN",
event_type_descriptors[PERF_TYPE_RAW]);
printf(" %-50s [%s]\n",
"cpu/t1=v1[,t2=v2,t3 ...]/modifier",
event_type_descriptors[PERF_TYPE_RAW]);
printf(" (see 'man perf-list' on how to encode it)\n");
printf("\n");
printf(" %-50s [%s]\n",
"mem:<addr>[:access]",
event_type_descriptors[PERF_TYPE_BREAKPOINT]);
printf("\n");
}
print_tracepoint_events(NULL, NULL, name_only);
}
int parse_events__is_hardcoded_term(struct parse_events_term *term)
{
return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
}
static int new_term(struct parse_events_term **_term, int type_val,
int type_term, char *config,
char *str, u64 num)
{
struct parse_events_term *term;
term = zalloc(sizeof(*term));
if (!term)
return -ENOMEM;
INIT_LIST_HEAD(&term->list);
term->type_val = type_val;
term->type_term = type_term;
term->config = config;
switch (type_val) {
case PARSE_EVENTS__TERM_TYPE_NUM:
term->val.num = num;
break;
case PARSE_EVENTS__TERM_TYPE_STR:
term->val.str = str;
break;
default:
return -EINVAL;
}
*_term = term;
return 0;
}
int parse_events_term__num(struct parse_events_term **term,
int type_term, char *config, u64 num)
{
return new_term(term, PARSE_EVENTS__TERM_TYPE_NUM, type_term,
config, NULL, num);
}
int parse_events_term__str(struct parse_events_term **term,
int type_term, char *config, char *str)
{
return new_term(term, PARSE_EVENTS__TERM_TYPE_STR, type_term,
config, str, 0);
}
int parse_events_term__sym_hw(struct parse_events_term **term,
char *config, unsigned idx)
{
struct event_symbol *sym;
BUG_ON(idx >= PERF_COUNT_HW_MAX);
sym = &event_symbols_hw[idx];
if (config)
return new_term(term, PARSE_EVENTS__TERM_TYPE_STR,
PARSE_EVENTS__TERM_TYPE_USER, config,
(char *) sym->symbol, 0);
else
return new_term(term, PARSE_EVENTS__TERM_TYPE_STR,
PARSE_EVENTS__TERM_TYPE_USER,
(char *) "event", (char *) sym->symbol, 0);
}
int parse_events_term__clone(struct parse_events_term **new,
struct parse_events_term *term)
{
return new_term(new, term->type_val, term->type_term, term->config,
term->val.str, term->val.num);
}
void parse_events__free_terms(struct list_head *terms)
{
struct parse_events_term *term, *h;
list_for_each_entry_safe(term, h, terms, list)
free(term);
free(terms);
}
| aps243/kernel-imx | tools/perf/util/parse-events.c | C | gpl-2.0 | 28,075 |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2010-2014, The Linux Foundation. All rights reserved.
*/
#include <linux/device.h>
#include <linux/interrupt.h>
#include <crypto/internal/hash.h>
#include "common.h"
#include "core.h"
#include "sha.h"
/* crypto hw padding constant for first operation */
#define SHA_PADDING 64
#define SHA_PADDING_MASK (SHA_PADDING - 1)
static LIST_HEAD(ahash_algs);
static const u32 std_iv_sha1[SHA256_DIGEST_SIZE / sizeof(u32)] = {
SHA1_H0, SHA1_H1, SHA1_H2, SHA1_H3, SHA1_H4, 0, 0, 0
};
static const u32 std_iv_sha256[SHA256_DIGEST_SIZE / sizeof(u32)] = {
SHA256_H0, SHA256_H1, SHA256_H2, SHA256_H3,
SHA256_H4, SHA256_H5, SHA256_H6, SHA256_H7
};
static void qce_ahash_done(void *data)
{
struct crypto_async_request *async_req = data;
struct ahash_request *req = ahash_request_cast(async_req);
struct crypto_ahash *ahash = crypto_ahash_reqtfm(req);
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
struct qce_alg_template *tmpl = to_ahash_tmpl(async_req->tfm);
struct qce_device *qce = tmpl->qce;
struct qce_result_dump *result = qce->dma.result_buf;
unsigned int digestsize = crypto_ahash_digestsize(ahash);
int error;
u32 status;
error = qce_dma_terminate_all(&qce->dma);
if (error)
dev_dbg(qce->dev, "ahash dma termination error (%d)\n", error);
dma_unmap_sg(qce->dev, req->src, rctx->src_nents, DMA_TO_DEVICE);
dma_unmap_sg(qce->dev, &rctx->result_sg, 1, DMA_FROM_DEVICE);
memcpy(rctx->digest, result->auth_iv, digestsize);
if (req->result)
memcpy(req->result, result->auth_iv, digestsize);
rctx->byte_count[0] = cpu_to_be32(result->auth_byte_count[0]);
rctx->byte_count[1] = cpu_to_be32(result->auth_byte_count[1]);
error = qce_check_status(qce, &status);
if (error < 0)
dev_dbg(qce->dev, "ahash operation error (%x)\n", status);
req->src = rctx->src_orig;
req->nbytes = rctx->nbytes_orig;
rctx->last_blk = false;
rctx->first_blk = false;
qce->async_req_done(tmpl->qce, error);
}
static int qce_ahash_async_req_handle(struct crypto_async_request *async_req)
{
struct ahash_request *req = ahash_request_cast(async_req);
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
struct qce_sha_ctx *ctx = crypto_tfm_ctx(async_req->tfm);
struct qce_alg_template *tmpl = to_ahash_tmpl(async_req->tfm);
struct qce_device *qce = tmpl->qce;
unsigned long flags = rctx->flags;
int ret;
if (IS_SHA_HMAC(flags)) {
rctx->authkey = ctx->authkey;
rctx->authklen = QCE_SHA_HMAC_KEY_SIZE;
} else if (IS_CMAC(flags)) {
rctx->authkey = ctx->authkey;
rctx->authklen = AES_KEYSIZE_128;
}
rctx->src_nents = sg_nents_for_len(req->src, req->nbytes);
if (rctx->src_nents < 0) {
dev_err(qce->dev, "Invalid numbers of src SG.\n");
return rctx->src_nents;
}
ret = dma_map_sg(qce->dev, req->src, rctx->src_nents, DMA_TO_DEVICE);
if (ret < 0)
return ret;
sg_init_one(&rctx->result_sg, qce->dma.result_buf, QCE_RESULT_BUF_SZ);
ret = dma_map_sg(qce->dev, &rctx->result_sg, 1, DMA_FROM_DEVICE);
if (ret < 0)
goto error_unmap_src;
ret = qce_dma_prep_sgs(&qce->dma, req->src, rctx->src_nents,
&rctx->result_sg, 1, qce_ahash_done, async_req);
if (ret)
goto error_unmap_dst;
qce_dma_issue_pending(&qce->dma);
ret = qce_start(async_req, tmpl->crypto_alg_type, 0, 0);
if (ret)
goto error_terminate;
return 0;
error_terminate:
qce_dma_terminate_all(&qce->dma);
error_unmap_dst:
dma_unmap_sg(qce->dev, &rctx->result_sg, 1, DMA_FROM_DEVICE);
error_unmap_src:
dma_unmap_sg(qce->dev, req->src, rctx->src_nents, DMA_TO_DEVICE);
return ret;
}
static int qce_ahash_init(struct ahash_request *req)
{
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
struct qce_alg_template *tmpl = to_ahash_tmpl(req->base.tfm);
const u32 *std_iv = tmpl->std_iv;
memset(rctx, 0, sizeof(*rctx));
rctx->first_blk = true;
rctx->last_blk = false;
rctx->flags = tmpl->alg_flags;
memcpy(rctx->digest, std_iv, sizeof(rctx->digest));
return 0;
}
static int qce_ahash_export(struct ahash_request *req, void *out)
{
struct crypto_ahash *ahash = crypto_ahash_reqtfm(req);
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
unsigned long flags = rctx->flags;
unsigned int digestsize = crypto_ahash_digestsize(ahash);
unsigned int blocksize =
crypto_tfm_alg_blocksize(crypto_ahash_tfm(ahash));
if (IS_SHA1(flags) || IS_SHA1_HMAC(flags)) {
struct sha1_state *out_state = out;
out_state->count = rctx->count;
qce_cpu_to_be32p_array((__be32 *)out_state->state,
rctx->digest, digestsize);
memcpy(out_state->buffer, rctx->buf, blocksize);
} else if (IS_SHA256(flags) || IS_SHA256_HMAC(flags)) {
struct sha256_state *out_state = out;
out_state->count = rctx->count;
qce_cpu_to_be32p_array((__be32 *)out_state->state,
rctx->digest, digestsize);
memcpy(out_state->buf, rctx->buf, blocksize);
} else {
return -EINVAL;
}
return 0;
}
static int qce_import_common(struct ahash_request *req, u64 in_count,
const u32 *state, const u8 *buffer, bool hmac)
{
struct crypto_ahash *ahash = crypto_ahash_reqtfm(req);
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
unsigned int digestsize = crypto_ahash_digestsize(ahash);
unsigned int blocksize;
u64 count = in_count;
blocksize = crypto_tfm_alg_blocksize(crypto_ahash_tfm(ahash));
rctx->count = in_count;
memcpy(rctx->buf, buffer, blocksize);
if (in_count <= blocksize) {
rctx->first_blk = 1;
} else {
rctx->first_blk = 0;
/*
* For HMAC, there is a hardware padding done when first block
* is set. Therefore the byte_count must be incremened by 64
* after the first block operation.
*/
if (hmac)
count += SHA_PADDING;
}
rctx->byte_count[0] = (__force __be32)(count & ~SHA_PADDING_MASK);
rctx->byte_count[1] = (__force __be32)(count >> 32);
qce_cpu_to_be32p_array((__be32 *)rctx->digest, (const u8 *)state,
digestsize);
rctx->buflen = (unsigned int)(in_count & (blocksize - 1));
return 0;
}
static int qce_ahash_import(struct ahash_request *req, const void *in)
{
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
unsigned long flags = rctx->flags;
bool hmac = IS_SHA_HMAC(flags);
int ret = -EINVAL;
if (IS_SHA1(flags) || IS_SHA1_HMAC(flags)) {
const struct sha1_state *state = in;
ret = qce_import_common(req, state->count, state->state,
state->buffer, hmac);
} else if (IS_SHA256(flags) || IS_SHA256_HMAC(flags)) {
const struct sha256_state *state = in;
ret = qce_import_common(req, state->count, state->state,
state->buf, hmac);
}
return ret;
}
static int qce_ahash_update(struct ahash_request *req)
{
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
struct qce_alg_template *tmpl = to_ahash_tmpl(req->base.tfm);
struct qce_device *qce = tmpl->qce;
struct scatterlist *sg_last, *sg;
unsigned int total, len;
unsigned int hash_later;
unsigned int nbytes;
unsigned int blocksize;
blocksize = crypto_tfm_alg_blocksize(crypto_ahash_tfm(tfm));
rctx->count += req->nbytes;
/* check for buffer from previous updates and append it */
total = req->nbytes + rctx->buflen;
if (total <= blocksize) {
scatterwalk_map_and_copy(rctx->buf + rctx->buflen, req->src,
0, req->nbytes, 0);
rctx->buflen += req->nbytes;
return 0;
}
/* save the original req structure fields */
rctx->src_orig = req->src;
rctx->nbytes_orig = req->nbytes;
/*
* if we have data from previous update copy them on buffer. The old
* data will be combined with current request bytes.
*/
if (rctx->buflen)
memcpy(rctx->tmpbuf, rctx->buf, rctx->buflen);
/* calculate how many bytes will be hashed later */
hash_later = total % blocksize;
if (hash_later) {
unsigned int src_offset = req->nbytes - hash_later;
scatterwalk_map_and_copy(rctx->buf, req->src, src_offset,
hash_later, 0);
}
/* here nbytes is multiple of blocksize */
nbytes = total - hash_later;
len = rctx->buflen;
sg = sg_last = req->src;
while (len < nbytes && sg) {
if (len + sg_dma_len(sg) > nbytes)
break;
len += sg_dma_len(sg);
sg_last = sg;
sg = sg_next(sg);
}
if (!sg_last)
return -EINVAL;
sg_mark_end(sg_last);
if (rctx->buflen) {
sg_init_table(rctx->sg, 2);
sg_set_buf(rctx->sg, rctx->tmpbuf, rctx->buflen);
sg_chain(rctx->sg, 2, req->src);
req->src = rctx->sg;
}
req->nbytes = nbytes;
rctx->buflen = hash_later;
return qce->async_req_enqueue(tmpl->qce, &req->base);
}
static int qce_ahash_final(struct ahash_request *req)
{
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
struct qce_alg_template *tmpl = to_ahash_tmpl(req->base.tfm);
struct qce_device *qce = tmpl->qce;
if (!rctx->buflen)
return 0;
rctx->last_blk = true;
rctx->src_orig = req->src;
rctx->nbytes_orig = req->nbytes;
memcpy(rctx->tmpbuf, rctx->buf, rctx->buflen);
sg_init_one(rctx->sg, rctx->tmpbuf, rctx->buflen);
req->src = rctx->sg;
req->nbytes = rctx->buflen;
return qce->async_req_enqueue(tmpl->qce, &req->base);
}
static int qce_ahash_digest(struct ahash_request *req)
{
struct qce_sha_reqctx *rctx = ahash_request_ctx(req);
struct qce_alg_template *tmpl = to_ahash_tmpl(req->base.tfm);
struct qce_device *qce = tmpl->qce;
int ret;
ret = qce_ahash_init(req);
if (ret)
return ret;
rctx->src_orig = req->src;
rctx->nbytes_orig = req->nbytes;
rctx->first_blk = true;
rctx->last_blk = true;
return qce->async_req_enqueue(tmpl->qce, &req->base);
}
static int qce_ahash_hmac_setkey(struct crypto_ahash *tfm, const u8 *key,
unsigned int keylen)
{
unsigned int digestsize = crypto_ahash_digestsize(tfm);
struct qce_sha_ctx *ctx = crypto_tfm_ctx(&tfm->base);
struct crypto_wait wait;
struct ahash_request *req;
struct scatterlist sg;
unsigned int blocksize;
struct crypto_ahash *ahash_tfm;
u8 *buf;
int ret;
const char *alg_name;
blocksize = crypto_tfm_alg_blocksize(crypto_ahash_tfm(tfm));
memset(ctx->authkey, 0, sizeof(ctx->authkey));
if (keylen <= blocksize) {
memcpy(ctx->authkey, key, keylen);
return 0;
}
if (digestsize == SHA1_DIGEST_SIZE)
alg_name = "sha1-qce";
else if (digestsize == SHA256_DIGEST_SIZE)
alg_name = "sha256-qce";
else
return -EINVAL;
ahash_tfm = crypto_alloc_ahash(alg_name, 0, 0);
if (IS_ERR(ahash_tfm))
return PTR_ERR(ahash_tfm);
req = ahash_request_alloc(ahash_tfm, GFP_KERNEL);
if (!req) {
ret = -ENOMEM;
goto err_free_ahash;
}
crypto_init_wait(&wait);
ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
crypto_req_done, &wait);
crypto_ahash_clear_flags(ahash_tfm, ~0);
buf = kzalloc(keylen + QCE_MAX_ALIGN_SIZE, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto err_free_req;
}
memcpy(buf, key, keylen);
sg_init_one(&sg, buf, keylen);
ahash_request_set_crypt(req, &sg, ctx->authkey, keylen);
ret = crypto_wait_req(crypto_ahash_digest(req), &wait);
if (ret)
crypto_ahash_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
kfree(buf);
err_free_req:
ahash_request_free(req);
err_free_ahash:
crypto_free_ahash(ahash_tfm);
return ret;
}
static int qce_ahash_cra_init(struct crypto_tfm *tfm)
{
struct crypto_ahash *ahash = __crypto_ahash_cast(tfm);
struct qce_sha_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_ahash_set_reqsize(ahash, sizeof(struct qce_sha_reqctx));
memset(ctx, 0, sizeof(*ctx));
return 0;
}
struct qce_ahash_def {
unsigned long flags;
const char *name;
const char *drv_name;
unsigned int digestsize;
unsigned int blocksize;
unsigned int statesize;
const u32 *std_iv;
};
static const struct qce_ahash_def ahash_def[] = {
{
.flags = QCE_HASH_SHA1,
.name = "sha1",
.drv_name = "sha1-qce",
.digestsize = SHA1_DIGEST_SIZE,
.blocksize = SHA1_BLOCK_SIZE,
.statesize = sizeof(struct sha1_state),
.std_iv = std_iv_sha1,
},
{
.flags = QCE_HASH_SHA256,
.name = "sha256",
.drv_name = "sha256-qce",
.digestsize = SHA256_DIGEST_SIZE,
.blocksize = SHA256_BLOCK_SIZE,
.statesize = sizeof(struct sha256_state),
.std_iv = std_iv_sha256,
},
{
.flags = QCE_HASH_SHA1_HMAC,
.name = "hmac(sha1)",
.drv_name = "hmac-sha1-qce",
.digestsize = SHA1_DIGEST_SIZE,
.blocksize = SHA1_BLOCK_SIZE,
.statesize = sizeof(struct sha1_state),
.std_iv = std_iv_sha1,
},
{
.flags = QCE_HASH_SHA256_HMAC,
.name = "hmac(sha256)",
.drv_name = "hmac-sha256-qce",
.digestsize = SHA256_DIGEST_SIZE,
.blocksize = SHA256_BLOCK_SIZE,
.statesize = sizeof(struct sha256_state),
.std_iv = std_iv_sha256,
},
};
static int qce_ahash_register_one(const struct qce_ahash_def *def,
struct qce_device *qce)
{
struct qce_alg_template *tmpl;
struct ahash_alg *alg;
struct crypto_alg *base;
int ret;
tmpl = kzalloc(sizeof(*tmpl), GFP_KERNEL);
if (!tmpl)
return -ENOMEM;
tmpl->std_iv = def->std_iv;
alg = &tmpl->alg.ahash;
alg->init = qce_ahash_init;
alg->update = qce_ahash_update;
alg->final = qce_ahash_final;
alg->digest = qce_ahash_digest;
alg->export = qce_ahash_export;
alg->import = qce_ahash_import;
if (IS_SHA_HMAC(def->flags))
alg->setkey = qce_ahash_hmac_setkey;
alg->halg.digestsize = def->digestsize;
alg->halg.statesize = def->statesize;
base = &alg->halg.base;
base->cra_blocksize = def->blocksize;
base->cra_priority = 300;
base->cra_flags = CRYPTO_ALG_ASYNC;
base->cra_ctxsize = sizeof(struct qce_sha_ctx);
base->cra_alignmask = 0;
base->cra_module = THIS_MODULE;
base->cra_init = qce_ahash_cra_init;
snprintf(base->cra_name, CRYPTO_MAX_ALG_NAME, "%s", def->name);
snprintf(base->cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s",
def->drv_name);
INIT_LIST_HEAD(&tmpl->entry);
tmpl->crypto_alg_type = CRYPTO_ALG_TYPE_AHASH;
tmpl->alg_flags = def->flags;
tmpl->qce = qce;
ret = crypto_register_ahash(alg);
if (ret) {
kfree(tmpl);
dev_err(qce->dev, "%s registration failed\n", base->cra_name);
return ret;
}
list_add_tail(&tmpl->entry, &ahash_algs);
dev_dbg(qce->dev, "%s is registered\n", base->cra_name);
return 0;
}
static void qce_ahash_unregister(struct qce_device *qce)
{
struct qce_alg_template *tmpl, *n;
list_for_each_entry_safe(tmpl, n, &ahash_algs, entry) {
crypto_unregister_ahash(&tmpl->alg.ahash);
list_del(&tmpl->entry);
kfree(tmpl);
}
}
static int qce_ahash_register(struct qce_device *qce)
{
int ret, i;
for (i = 0; i < ARRAY_SIZE(ahash_def); i++) {
ret = qce_ahash_register_one(&ahash_def[i], qce);
if (ret)
goto err;
}
return 0;
err:
qce_ahash_unregister(qce);
return ret;
}
const struct qce_algo_ops ahash_ops = {
.type = CRYPTO_ALG_TYPE_AHASH,
.register_algs = qce_ahash_register,
.unregister_algs = qce_ahash_unregister,
.async_req_handle = qce_ahash_async_req_handle,
};
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-5.4/drivers/crypto/qce/sha.c | C | gpl-2.0 | 14,645 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.stresstest.indexing;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import java.util.concurrent.ThreadLocalRandom;
/**
*/
public class BulkIndexingStressTest {
public static void main(String[] args) {
final int NUMBER_OF_NODES = 4;
final int NUMBER_OF_INDICES = 600;
final int BATCH = 300;
final Settings nodeSettings = ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2).build();
// ESLogger logger = Loggers.getLogger("org.elasticsearch");
// logger.setLevel("DEBUG");
Node[] nodes = new Node[NUMBER_OF_NODES];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = NodeBuilder.nodeBuilder().settings(nodeSettings).node();
}
Client client = nodes.length == 1 ? nodes[0].client() : nodes[1].client();
while (true) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (int i = 0; i < BATCH; i++) {
bulkRequest.add(Requests.indexRequest("test" + ThreadLocalRandom.current().nextInt(NUMBER_OF_INDICES)).type("type").source("field", "value"));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
for (BulkItemResponse item : bulkResponse) {
if (item.isFailed()) {
System.out.println("failed response:" + item.getFailureMessage());
}
}
throw new RuntimeException("Failed responses");
}
;
}
}
}
| corochoone/elasticsearch | src/test/java/org/elasticsearch/stresstest/indexing/BulkIndexingStressTest.java | Java | apache-2.0 | 2,807 |
/*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function constructDefaults(string, object, value) {
/* eslint no-return-assign: 0 */
string.split(',').forEach(function (i) { return object[i] = value; });
}
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var strictProps = {};
var booleanProps = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
screenWidth = window.screen.width;
screenHeight = window.screen.height;
lastScrollTime = performance.now();
};
}
function Lifecycle() {
this._listeners = [];
this.scrollX = null;
this.scrollY = null;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
if (this._blockSetState === false) {
queueStateChanges(this, newState, callback);
} else {
throw Error('Inferno Warning: Cannot update state via setState() in componentWillUpdate()');
}
};
Component.prototype.componentDidMount = function componentDidMount () {
};
Component.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) {
if ( opts === void 0 ) opts = EMPTY$1;
var reg = /(?:\?([^#]*))?(#.*)?$/,
c = url.match(reg),
matches = {},
ret;
if (c && c[1]) {
var p = c[1].split('&');
for (var i = 0; i < p.length; i++) {
var r = p[i].split('=');
matches[decodeURIComponent(r[0])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
}
function pathRankSort(a, b) {
var aAttr = a.attrs || EMPTY$1,
bAttr = b.attrs || EMPTY$1;
var diff = rank(bAttr.path) - rank(aAttr.path);
return diff || (bAttr.path.length - aAttr.path.length);
}
function rank(url) {
return (strip(url).match(/\/+/g) || '').length;
}
var Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); | dlueth/cdnjs | ajax/libs/inferno/0.7.14/inferno-router.js | JavaScript | mit | 18,182 |
# Requiring test environment file
require 'spec_helper'
# Requiring test subject file
require_relative File.join(APP_CONTROLLERS, "static")
# Test cases
describe 'Routing for root' do
it "has ok response when get '/' is called." do
get '/'
expect(last_response).to be_ok
end
end | hollowaykeanho/airbnb-accessment | spec/static_spec.rb | Ruby | mit | 286 |
/*
Copyright (C) 2010 Willow Garage <http://www.willowgarage.com>
Copyright (C) 2004 - 2010 Ivo van Doorn <IvDoorn@gmail.com>
<http://rt2x00.serialmonkey.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/>.
*/
/*
Module: rt2x00usb
Abstract: rt2x00 generic usb device routines.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/bug.h>
#include "rt2x00.h"
#include "rt2x00usb.h"
/*
* Interfacing with the HW.
*/
int rt2x00usb_vendor_request(struct rt2x00_dev *rt2x00dev,
const u8 request, const u8 requesttype,
const u16 offset, const u16 value,
void *buffer, const u16 buffer_length,
const int timeout)
{
struct usb_device *usb_dev = to_usb_device_intf(rt2x00dev->dev);
int status;
unsigned int pipe =
(requesttype == USB_VENDOR_REQUEST_IN) ?
usb_rcvctrlpipe(usb_dev, 0) : usb_sndctrlpipe(usb_dev, 0);
unsigned long expire = jiffies + msecs_to_jiffies(timeout);
if (!test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags))
return -ENODEV;
do {
status = usb_control_msg(usb_dev, pipe, request, requesttype,
value, offset, buffer, buffer_length,
timeout / 2);
if (status >= 0)
return 0;
if (status == -ENODEV) {
/* Device has disappeared. */
clear_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags);
break;
}
} while (time_before(jiffies, expire));
rt2x00_err(rt2x00dev,
"Vendor Request 0x%02x failed for offset 0x%04x with error %d\n",
request, offset, status);
return status;
}
EXPORT_SYMBOL_GPL(rt2x00usb_vendor_request);
int rt2x00usb_vendor_req_buff_lock(struct rt2x00_dev *rt2x00dev,
const u8 request, const u8 requesttype,
const u16 offset, void *buffer,
const u16 buffer_length, const int timeout)
{
int status;
BUG_ON(!mutex_is_locked(&rt2x00dev->csr_mutex));
/*
* Check for Cache availability.
*/
if (unlikely(!rt2x00dev->csr.cache || buffer_length > CSR_CACHE_SIZE)) {
rt2x00_err(rt2x00dev, "CSR cache not available\n");
return -ENOMEM;
}
if (requesttype == USB_VENDOR_REQUEST_OUT)
memcpy(rt2x00dev->csr.cache, buffer, buffer_length);
status = rt2x00usb_vendor_request(rt2x00dev, request, requesttype,
offset, 0, rt2x00dev->csr.cache,
buffer_length, timeout);
if (!status && requesttype == USB_VENDOR_REQUEST_IN)
memcpy(buffer, rt2x00dev->csr.cache, buffer_length);
return status;
}
EXPORT_SYMBOL_GPL(rt2x00usb_vendor_req_buff_lock);
int rt2x00usb_vendor_request_buff(struct rt2x00_dev *rt2x00dev,
const u8 request, const u8 requesttype,
const u16 offset, void *buffer,
const u16 buffer_length)
{
int status = 0;
unsigned char *tb;
u16 off, len, bsize;
mutex_lock(&rt2x00dev->csr_mutex);
tb = (char *)buffer;
off = offset;
len = buffer_length;
while (len && !status) {
bsize = min_t(u16, CSR_CACHE_SIZE, len);
status = rt2x00usb_vendor_req_buff_lock(rt2x00dev, request,
requesttype, off, tb,
bsize, REGISTER_TIMEOUT);
tb += bsize;
len -= bsize;
off += bsize;
}
mutex_unlock(&rt2x00dev->csr_mutex);
return status;
}
EXPORT_SYMBOL_GPL(rt2x00usb_vendor_request_buff);
int rt2x00usb_regbusy_read(struct rt2x00_dev *rt2x00dev,
const unsigned int offset,
const struct rt2x00_field32 field,
u32 *reg)
{
unsigned int i;
if (!test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags))
return -ENODEV;
for (i = 0; i < REGISTER_USB_BUSY_COUNT; i++) {
*reg = rt2x00usb_register_read_lock(rt2x00dev, offset);
if (!rt2x00_get_field32(*reg, field))
return 1;
udelay(REGISTER_BUSY_DELAY);
}
rt2x00_err(rt2x00dev, "Indirect register access failed: offset=0x%.08x, value=0x%.08x\n",
offset, *reg);
*reg = ~0;
return 0;
}
EXPORT_SYMBOL_GPL(rt2x00usb_regbusy_read);
struct rt2x00_async_read_data {
__le32 reg;
struct usb_ctrlrequest cr;
struct rt2x00_dev *rt2x00dev;
bool (*callback)(struct rt2x00_dev *, int, u32);
};
static void rt2x00usb_register_read_async_cb(struct urb *urb)
{
struct rt2x00_async_read_data *rd = urb->context;
if (rd->callback(rd->rt2x00dev, urb->status, le32_to_cpu(rd->reg))) {
usb_anchor_urb(urb, rd->rt2x00dev->anchor);
if (usb_submit_urb(urb, GFP_ATOMIC) < 0) {
usb_unanchor_urb(urb);
kfree(rd);
}
} else
kfree(rd);
}
void rt2x00usb_register_read_async(struct rt2x00_dev *rt2x00dev,
const unsigned int offset,
bool (*callback)(struct rt2x00_dev*, int, u32))
{
struct usb_device *usb_dev = to_usb_device_intf(rt2x00dev->dev);
struct urb *urb;
struct rt2x00_async_read_data *rd;
rd = kmalloc(sizeof(*rd), GFP_ATOMIC);
if (!rd)
return;
urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!urb) {
kfree(rd);
return;
}
rd->rt2x00dev = rt2x00dev;
rd->callback = callback;
rd->cr.bRequestType = USB_VENDOR_REQUEST_IN;
rd->cr.bRequest = USB_MULTI_READ;
rd->cr.wValue = 0;
rd->cr.wIndex = cpu_to_le16(offset);
rd->cr.wLength = cpu_to_le16(sizeof(u32));
usb_fill_control_urb(urb, usb_dev, usb_rcvctrlpipe(usb_dev, 0),
(unsigned char *)(&rd->cr), &rd->reg, sizeof(rd->reg),
rt2x00usb_register_read_async_cb, rd);
usb_anchor_urb(urb, rt2x00dev->anchor);
if (usb_submit_urb(urb, GFP_ATOMIC) < 0) {
usb_unanchor_urb(urb);
kfree(rd);
}
usb_free_urb(urb);
}
EXPORT_SYMBOL_GPL(rt2x00usb_register_read_async);
/*
* TX data handlers.
*/
static void rt2x00usb_work_txdone_entry(struct queue_entry *entry)
{
/*
* If the transfer to hardware succeeded, it does not mean the
* frame was send out correctly. It only means the frame
* was successfully pushed to the hardware, we have no
* way to determine the transmission status right now.
* (Only indirectly by looking at the failed TX counters
* in the register).
*/
if (test_bit(ENTRY_DATA_IO_FAILED, &entry->flags))
rt2x00lib_txdone_noinfo(entry, TXDONE_FAILURE);
else
rt2x00lib_txdone_noinfo(entry, TXDONE_UNKNOWN);
}
static void rt2x00usb_work_txdone(struct work_struct *work)
{
struct rt2x00_dev *rt2x00dev =
container_of(work, struct rt2x00_dev, txdone_work);
struct data_queue *queue;
struct queue_entry *entry;
tx_queue_for_each(rt2x00dev, queue) {
while (!rt2x00queue_empty(queue)) {
entry = rt2x00queue_get_entry(queue, Q_INDEX_DONE);
if (test_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags) ||
!test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))
break;
rt2x00usb_work_txdone_entry(entry);
}
}
}
static void rt2x00usb_interrupt_txdone(struct urb *urb)
{
struct queue_entry *entry = (struct queue_entry *)urb->context;
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
if (!test_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags))
return;
/*
* Check if the frame was correctly uploaded
*/
if (urb->status)
set_bit(ENTRY_DATA_IO_FAILED, &entry->flags);
/*
* Report the frame as DMA done
*/
rt2x00lib_dmadone(entry);
if (rt2x00dev->ops->lib->tx_dma_done)
rt2x00dev->ops->lib->tx_dma_done(entry);
/*
* Schedule the delayed work for reading the TX status
* from the device.
*/
if (!rt2x00_has_cap_flag(rt2x00dev, REQUIRE_TXSTATUS_FIFO) ||
!kfifo_is_empty(&rt2x00dev->txstatus_fifo))
queue_work(rt2x00dev->workqueue, &rt2x00dev->txdone_work);
}
static bool rt2x00usb_kick_tx_entry(struct queue_entry *entry, void *data)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
struct usb_device *usb_dev = to_usb_device_intf(rt2x00dev->dev);
struct queue_entry_priv_usb *entry_priv = entry->priv_data;
u32 length;
int status;
if (!test_and_clear_bit(ENTRY_DATA_PENDING, &entry->flags) ||
test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))
return false;
/*
* USB devices require certain padding at the end of each frame
* and urb. Those paddings are not included in skbs. Pass entry
* to the driver to determine what the overall length should be.
*/
length = rt2x00dev->ops->lib->get_tx_data_len(entry);
status = skb_padto(entry->skb, length);
if (unlikely(status)) {
/* TODO: report something more appropriate than IO_FAILED. */
rt2x00_warn(rt2x00dev, "TX SKB padding error, out of memory\n");
set_bit(ENTRY_DATA_IO_FAILED, &entry->flags);
rt2x00lib_dmadone(entry);
return false;
}
usb_fill_bulk_urb(entry_priv->urb, usb_dev,
usb_sndbulkpipe(usb_dev, entry->queue->usb_endpoint),
entry->skb->data, length,
rt2x00usb_interrupt_txdone, entry);
status = usb_submit_urb(entry_priv->urb, GFP_ATOMIC);
if (status) {
if (status == -ENODEV)
clear_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags);
set_bit(ENTRY_DATA_IO_FAILED, &entry->flags);
rt2x00lib_dmadone(entry);
}
return false;
}
/*
* RX data handlers.
*/
static void rt2x00usb_work_rxdone(struct work_struct *work)
{
struct rt2x00_dev *rt2x00dev =
container_of(work, struct rt2x00_dev, rxdone_work);
struct queue_entry *entry;
struct skb_frame_desc *skbdesc;
u8 rxd[32];
while (!rt2x00queue_empty(rt2x00dev->rx)) {
entry = rt2x00queue_get_entry(rt2x00dev->rx, Q_INDEX_DONE);
if (test_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags) ||
!test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))
break;
/*
* Fill in desc fields of the skb descriptor
*/
skbdesc = get_skb_frame_desc(entry->skb);
skbdesc->desc = rxd;
skbdesc->desc_len = entry->queue->desc_size;
/*
* Send the frame to rt2x00lib for further processing.
*/
rt2x00lib_rxdone(entry, GFP_KERNEL);
}
}
static void rt2x00usb_interrupt_rxdone(struct urb *urb)
{
struct queue_entry *entry = (struct queue_entry *)urb->context;
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
if (!test_and_clear_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags))
return;
/*
* Report the frame as DMA done
*/
rt2x00lib_dmadone(entry);
/*
* Check if the received data is simply too small
* to be actually valid, or if the urb is signaling
* a problem.
*/
if (urb->actual_length < entry->queue->desc_size || urb->status)
set_bit(ENTRY_DATA_IO_FAILED, &entry->flags);
/*
* Schedule the delayed work for reading the RX status
* from the device.
*/
queue_work(rt2x00dev->workqueue, &rt2x00dev->rxdone_work);
}
static bool rt2x00usb_kick_rx_entry(struct queue_entry *entry, void *data)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
struct usb_device *usb_dev = to_usb_device_intf(rt2x00dev->dev);
struct queue_entry_priv_usb *entry_priv = entry->priv_data;
int status;
if (test_and_set_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags) ||
test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))
return false;
rt2x00lib_dmastart(entry);
usb_fill_bulk_urb(entry_priv->urb, usb_dev,
usb_rcvbulkpipe(usb_dev, entry->queue->usb_endpoint),
entry->skb->data, entry->skb->len,
rt2x00usb_interrupt_rxdone, entry);
status = usb_submit_urb(entry_priv->urb, GFP_ATOMIC);
if (status) {
if (status == -ENODEV)
clear_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags);
set_bit(ENTRY_DATA_IO_FAILED, &entry->flags);
rt2x00lib_dmadone(entry);
}
return false;
}
void rt2x00usb_kick_queue(struct data_queue *queue)
{
switch (queue->qid) {
case QID_AC_VO:
case QID_AC_VI:
case QID_AC_BE:
case QID_AC_BK:
if (!rt2x00queue_empty(queue))
rt2x00queue_for_each_entry(queue,
Q_INDEX_DONE,
Q_INDEX,
NULL,
rt2x00usb_kick_tx_entry);
break;
case QID_RX:
if (!rt2x00queue_full(queue))
rt2x00queue_for_each_entry(queue,
Q_INDEX,
Q_INDEX_DONE,
NULL,
rt2x00usb_kick_rx_entry);
break;
default:
break;
}
}
EXPORT_SYMBOL_GPL(rt2x00usb_kick_queue);
static bool rt2x00usb_flush_entry(struct queue_entry *entry, void *data)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
struct queue_entry_priv_usb *entry_priv = entry->priv_data;
struct queue_entry_priv_usb_bcn *bcn_priv = entry->priv_data;
if (!test_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags))
return false;
usb_kill_urb(entry_priv->urb);
/*
* Kill guardian urb (if required by driver).
*/
if ((entry->queue->qid == QID_BEACON) &&
(rt2x00_has_cap_flag(rt2x00dev, REQUIRE_BEACON_GUARD)))
usb_kill_urb(bcn_priv->guardian_urb);
return false;
}
void rt2x00usb_flush_queue(struct data_queue *queue, bool drop)
{
struct work_struct *completion;
unsigned int i;
if (drop)
rt2x00queue_for_each_entry(queue, Q_INDEX_DONE, Q_INDEX, NULL,
rt2x00usb_flush_entry);
/*
* Obtain the queue completion handler
*/
switch (queue->qid) {
case QID_AC_VO:
case QID_AC_VI:
case QID_AC_BE:
case QID_AC_BK:
completion = &queue->rt2x00dev->txdone_work;
break;
case QID_RX:
completion = &queue->rt2x00dev->rxdone_work;
break;
default:
return;
}
for (i = 0; i < 10; i++) {
/*
* Check if the driver is already done, otherwise we
* have to sleep a little while to give the driver/hw
* the oppurtunity to complete interrupt process itself.
*/
if (rt2x00queue_empty(queue))
break;
/*
* Schedule the completion handler manually, when this
* worker function runs, it should cleanup the queue.
*/
queue_work(queue->rt2x00dev->workqueue, completion);
/*
* Wait for a little while to give the driver
* the oppurtunity to recover itself.
*/
msleep(50);
}
}
EXPORT_SYMBOL_GPL(rt2x00usb_flush_queue);
static void rt2x00usb_watchdog_tx_dma(struct data_queue *queue)
{
rt2x00_warn(queue->rt2x00dev, "TX queue %d DMA timed out, invoke forced forced reset\n",
queue->qid);
rt2x00queue_stop_queue(queue);
rt2x00queue_flush_queue(queue, true);
rt2x00queue_start_queue(queue);
}
static int rt2x00usb_dma_timeout(struct data_queue *queue)
{
struct queue_entry *entry;
entry = rt2x00queue_get_entry(queue, Q_INDEX_DMA_DONE);
return rt2x00queue_dma_timeout(entry);
}
void rt2x00usb_watchdog(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
tx_queue_for_each(rt2x00dev, queue) {
if (!rt2x00queue_empty(queue)) {
if (rt2x00usb_dma_timeout(queue))
rt2x00usb_watchdog_tx_dma(queue);
}
}
}
EXPORT_SYMBOL_GPL(rt2x00usb_watchdog);
/*
* Radio handlers
*/
void rt2x00usb_disable_radio(struct rt2x00_dev *rt2x00dev)
{
rt2x00usb_vendor_request_sw(rt2x00dev, USB_RX_CONTROL, 0, 0,
REGISTER_TIMEOUT);
}
EXPORT_SYMBOL_GPL(rt2x00usb_disable_radio);
/*
* Device initialization handlers.
*/
void rt2x00usb_clear_entry(struct queue_entry *entry)
{
entry->flags = 0;
if (entry->queue->qid == QID_RX)
rt2x00usb_kick_rx_entry(entry, NULL);
}
EXPORT_SYMBOL_GPL(rt2x00usb_clear_entry);
static void rt2x00usb_assign_endpoint(struct data_queue *queue,
struct usb_endpoint_descriptor *ep_desc)
{
struct usb_device *usb_dev = to_usb_device_intf(queue->rt2x00dev->dev);
int pipe;
queue->usb_endpoint = usb_endpoint_num(ep_desc);
if (queue->qid == QID_RX) {
pipe = usb_rcvbulkpipe(usb_dev, queue->usb_endpoint);
queue->usb_maxpacket = usb_maxpacket(usb_dev, pipe, 0);
} else {
pipe = usb_sndbulkpipe(usb_dev, queue->usb_endpoint);
queue->usb_maxpacket = usb_maxpacket(usb_dev, pipe, 1);
}
if (!queue->usb_maxpacket)
queue->usb_maxpacket = 1;
}
static int rt2x00usb_find_endpoints(struct rt2x00_dev *rt2x00dev)
{
struct usb_interface *intf = to_usb_interface(rt2x00dev->dev);
struct usb_host_interface *intf_desc = intf->cur_altsetting;
struct usb_endpoint_descriptor *ep_desc;
struct data_queue *queue = rt2x00dev->tx;
struct usb_endpoint_descriptor *tx_ep_desc = NULL;
unsigned int i;
/*
* Walk through all available endpoints to search for "bulk in"
* and "bulk out" endpoints. When we find such endpoints collect
* the information we need from the descriptor and assign it
* to the queue.
*/
for (i = 0; i < intf_desc->desc.bNumEndpoints; i++) {
ep_desc = &intf_desc->endpoint[i].desc;
if (usb_endpoint_is_bulk_in(ep_desc)) {
rt2x00usb_assign_endpoint(rt2x00dev->rx, ep_desc);
} else if (usb_endpoint_is_bulk_out(ep_desc) &&
(queue != queue_end(rt2x00dev))) {
rt2x00usb_assign_endpoint(queue, ep_desc);
queue = queue_next(queue);
tx_ep_desc = ep_desc;
}
}
/*
* At least 1 endpoint for RX and 1 endpoint for TX must be available.
*/
if (!rt2x00dev->rx->usb_endpoint || !rt2x00dev->tx->usb_endpoint) {
rt2x00_err(rt2x00dev, "Bulk-in/Bulk-out endpoints not found\n");
return -EPIPE;
}
/*
* It might be possible not all queues have a dedicated endpoint.
* Loop through all TX queues and copy the endpoint information
* which we have gathered from already assigned endpoints.
*/
txall_queue_for_each(rt2x00dev, queue) {
if (!queue->usb_endpoint)
rt2x00usb_assign_endpoint(queue, tx_ep_desc);
}
return 0;
}
static int rt2x00usb_alloc_entries(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
struct queue_entry_priv_usb *entry_priv;
struct queue_entry_priv_usb_bcn *bcn_priv;
unsigned int i;
for (i = 0; i < queue->limit; i++) {
entry_priv = queue->entries[i].priv_data;
entry_priv->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!entry_priv->urb)
return -ENOMEM;
}
/*
* If this is not the beacon queue or
* no guardian byte was required for the beacon,
* then we are done.
*/
if (queue->qid != QID_BEACON ||
!rt2x00_has_cap_flag(rt2x00dev, REQUIRE_BEACON_GUARD))
return 0;
for (i = 0; i < queue->limit; i++) {
bcn_priv = queue->entries[i].priv_data;
bcn_priv->guardian_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!bcn_priv->guardian_urb)
return -ENOMEM;
}
return 0;
}
static void rt2x00usb_free_entries(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
struct queue_entry_priv_usb *entry_priv;
struct queue_entry_priv_usb_bcn *bcn_priv;
unsigned int i;
if (!queue->entries)
return;
for (i = 0; i < queue->limit; i++) {
entry_priv = queue->entries[i].priv_data;
usb_kill_urb(entry_priv->urb);
usb_free_urb(entry_priv->urb);
}
/*
* If this is not the beacon queue or
* no guardian byte was required for the beacon,
* then we are done.
*/
if (queue->qid != QID_BEACON ||
!rt2x00_has_cap_flag(rt2x00dev, REQUIRE_BEACON_GUARD))
return;
for (i = 0; i < queue->limit; i++) {
bcn_priv = queue->entries[i].priv_data;
usb_kill_urb(bcn_priv->guardian_urb);
usb_free_urb(bcn_priv->guardian_urb);
}
}
int rt2x00usb_initialize(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
int status;
/*
* Find endpoints for each queue
*/
status = rt2x00usb_find_endpoints(rt2x00dev);
if (status)
goto exit;
/*
* Allocate DMA
*/
queue_for_each(rt2x00dev, queue) {
status = rt2x00usb_alloc_entries(queue);
if (status)
goto exit;
}
return 0;
exit:
rt2x00usb_uninitialize(rt2x00dev);
return status;
}
EXPORT_SYMBOL_GPL(rt2x00usb_initialize);
void rt2x00usb_uninitialize(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
usb_kill_anchored_urbs(rt2x00dev->anchor);
hrtimer_cancel(&rt2x00dev->txstatus_timer);
cancel_work_sync(&rt2x00dev->rxdone_work);
cancel_work_sync(&rt2x00dev->txdone_work);
queue_for_each(rt2x00dev, queue)
rt2x00usb_free_entries(queue);
}
EXPORT_SYMBOL_GPL(rt2x00usb_uninitialize);
/*
* USB driver handlers.
*/
static void rt2x00usb_free_reg(struct rt2x00_dev *rt2x00dev)
{
kfree(rt2x00dev->rf);
rt2x00dev->rf = NULL;
kfree(rt2x00dev->eeprom);
rt2x00dev->eeprom = NULL;
kfree(rt2x00dev->csr.cache);
rt2x00dev->csr.cache = NULL;
}
static int rt2x00usb_alloc_reg(struct rt2x00_dev *rt2x00dev)
{
rt2x00dev->csr.cache = kzalloc(CSR_CACHE_SIZE, GFP_KERNEL);
if (!rt2x00dev->csr.cache)
goto exit;
rt2x00dev->eeprom = kzalloc(rt2x00dev->ops->eeprom_size, GFP_KERNEL);
if (!rt2x00dev->eeprom)
goto exit;
rt2x00dev->rf = kzalloc(rt2x00dev->ops->rf_size, GFP_KERNEL);
if (!rt2x00dev->rf)
goto exit;
return 0;
exit:
rt2x00_probe_err("Failed to allocate registers\n");
rt2x00usb_free_reg(rt2x00dev);
return -ENOMEM;
}
int rt2x00usb_probe(struct usb_interface *usb_intf,
const struct rt2x00_ops *ops)
{
struct usb_device *usb_dev = interface_to_usbdev(usb_intf);
struct ieee80211_hw *hw;
struct rt2x00_dev *rt2x00dev;
int retval;
usb_dev = usb_get_dev(usb_dev);
usb_reset_device(usb_dev);
hw = ieee80211_alloc_hw(sizeof(struct rt2x00_dev), ops->hw);
if (!hw) {
rt2x00_probe_err("Failed to allocate hardware\n");
retval = -ENOMEM;
goto exit_put_device;
}
usb_set_intfdata(usb_intf, hw);
rt2x00dev = hw->priv;
rt2x00dev->dev = &usb_intf->dev;
rt2x00dev->ops = ops;
rt2x00dev->hw = hw;
rt2x00_set_chip_intf(rt2x00dev, RT2X00_CHIP_INTF_USB);
INIT_WORK(&rt2x00dev->rxdone_work, rt2x00usb_work_rxdone);
INIT_WORK(&rt2x00dev->txdone_work, rt2x00usb_work_txdone);
hrtimer_init(&rt2x00dev->txstatus_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL);
retval = rt2x00usb_alloc_reg(rt2x00dev);
if (retval)
goto exit_free_device;
rt2x00dev->anchor = devm_kmalloc(&usb_dev->dev,
sizeof(struct usb_anchor),
GFP_KERNEL);
if (!rt2x00dev->anchor) {
retval = -ENOMEM;
goto exit_free_reg;
}
init_usb_anchor(rt2x00dev->anchor);
retval = rt2x00lib_probe_dev(rt2x00dev);
if (retval)
goto exit_free_anchor;
return 0;
exit_free_anchor:
usb_kill_anchored_urbs(rt2x00dev->anchor);
exit_free_reg:
rt2x00usb_free_reg(rt2x00dev);
exit_free_device:
ieee80211_free_hw(hw);
exit_put_device:
usb_put_dev(usb_dev);
usb_set_intfdata(usb_intf, NULL);
return retval;
}
EXPORT_SYMBOL_GPL(rt2x00usb_probe);
void rt2x00usb_disconnect(struct usb_interface *usb_intf)
{
struct ieee80211_hw *hw = usb_get_intfdata(usb_intf);
struct rt2x00_dev *rt2x00dev = hw->priv;
/*
* Free all allocated data.
*/
rt2x00lib_remove_dev(rt2x00dev);
rt2x00usb_free_reg(rt2x00dev);
ieee80211_free_hw(hw);
/*
* Free the USB device data.
*/
usb_set_intfdata(usb_intf, NULL);
usb_put_dev(interface_to_usbdev(usb_intf));
}
EXPORT_SYMBOL_GPL(rt2x00usb_disconnect);
#ifdef CONFIG_PM
int rt2x00usb_suspend(struct usb_interface *usb_intf, pm_message_t state)
{
struct ieee80211_hw *hw = usb_get_intfdata(usb_intf);
struct rt2x00_dev *rt2x00dev = hw->priv;
return rt2x00lib_suspend(rt2x00dev, state);
}
EXPORT_SYMBOL_GPL(rt2x00usb_suspend);
int rt2x00usb_resume(struct usb_interface *usb_intf)
{
struct ieee80211_hw *hw = usb_get_intfdata(usb_intf);
struct rt2x00_dev *rt2x00dev = hw->priv;
return rt2x00lib_resume(rt2x00dev);
}
EXPORT_SYMBOL_GPL(rt2x00usb_resume);
#endif /* CONFIG_PM */
/*
* rt2x00usb module information.
*/
MODULE_AUTHOR(DRV_PROJECT);
MODULE_VERSION(DRV_VERSION);
MODULE_DESCRIPTION("rt2x00 usb library");
MODULE_LICENSE("GPL");
| Isopod/linux | drivers/net/wireless/ralink/rt2x00/rt2x00usb.c | C | gpl-2.0 | 23,035 |
// SPDX-License-Identifier: GPL-2.0-only
/*
* DMA Engine test module
*
* Copyright (C) 2007 Atmel Corporation
* Copyright (C) 2013 Intel Corporation
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/freezer.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/sched/task.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/wait.h>
static unsigned int test_buf_size = 16384;
module_param(test_buf_size, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(test_buf_size, "Size of the memcpy test buffer");
static char test_device[32];
module_param_string(device, test_device, sizeof(test_device),
S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(device, "Bus ID of the DMA Engine to test (default: any)");
static unsigned int threads_per_chan = 1;
module_param(threads_per_chan, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(threads_per_chan,
"Number of threads to start per channel (default: 1)");
static unsigned int max_channels;
module_param(max_channels, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(max_channels,
"Maximum number of channels to use (default: all)");
static unsigned int iterations;
module_param(iterations, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(iterations,
"Iterations before stopping test (default: infinite)");
static unsigned int dmatest;
module_param(dmatest, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(dmatest,
"dmatest 0-memcpy 1-memset (default: 0)");
static unsigned int xor_sources = 3;
module_param(xor_sources, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(xor_sources,
"Number of xor source buffers (default: 3)");
static unsigned int pq_sources = 3;
module_param(pq_sources, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(pq_sources,
"Number of p+q source buffers (default: 3)");
static int timeout = 3000;
module_param(timeout, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(timeout, "Transfer Timeout in msec (default: 3000), "
"Pass 0xFFFFFFFF (4294967295) for maximum timeout");
static bool noverify;
module_param(noverify, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(noverify, "Disable data verification (default: verify)");
static bool norandom;
module_param(norandom, bool, 0644);
MODULE_PARM_DESC(norandom, "Disable random offset setup (default: random)");
static bool polled;
module_param(polled, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(polled, "Use polling for completion instead of interrupts");
static bool verbose;
module_param(verbose, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(verbose, "Enable \"success\" result messages (default: off)");
static int alignment = -1;
module_param(alignment, int, 0644);
MODULE_PARM_DESC(alignment, "Custom data address alignment taken as 2^(alignment) (default: not used (-1))");
static unsigned int transfer_size;
module_param(transfer_size, uint, 0644);
MODULE_PARM_DESC(transfer_size, "Optional custom transfer size in bytes (default: not used (0))");
/**
* struct dmatest_params - test parameters.
* @buf_size: size of the memcpy test buffer
* @channel: bus ID of the channel to test
* @device: bus ID of the DMA Engine to test
* @threads_per_chan: number of threads to start per channel
* @max_channels: maximum number of channels to use
* @iterations: iterations before stopping test
* @xor_sources: number of xor source buffers
* @pq_sources: number of p+q source buffers
* @timeout: transfer timeout in msec, 0 - 0xFFFFFFFF (4294967295)
*/
struct dmatest_params {
unsigned int buf_size;
char channel[20];
char device[32];
unsigned int threads_per_chan;
unsigned int max_channels;
unsigned int iterations;
unsigned int xor_sources;
unsigned int pq_sources;
unsigned int timeout;
bool noverify;
bool norandom;
int alignment;
unsigned int transfer_size;
bool polled;
};
/**
* struct dmatest_info - test information.
* @params: test parameters
* @lock: access protection to the fields of this structure
*/
static struct dmatest_info {
/* Test parameters */
struct dmatest_params params;
/* Internal state */
struct list_head channels;
unsigned int nr_channels;
struct mutex lock;
bool did_init;
} test_info = {
.channels = LIST_HEAD_INIT(test_info.channels),
.lock = __MUTEX_INITIALIZER(test_info.lock),
};
static int dmatest_run_set(const char *val, const struct kernel_param *kp);
static int dmatest_run_get(char *val, const struct kernel_param *kp);
static const struct kernel_param_ops run_ops = {
.set = dmatest_run_set,
.get = dmatest_run_get,
};
static bool dmatest_run;
module_param_cb(run, &run_ops, &dmatest_run, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(run, "Run the test (default: false)");
static int dmatest_chan_set(const char *val, const struct kernel_param *kp);
static int dmatest_chan_get(char *val, const struct kernel_param *kp);
static const struct kernel_param_ops multi_chan_ops = {
.set = dmatest_chan_set,
.get = dmatest_chan_get,
};
static char test_channel[20];
static struct kparam_string newchan_kps = {
.string = test_channel,
.maxlen = 20,
};
module_param_cb(channel, &multi_chan_ops, &newchan_kps, 0644);
MODULE_PARM_DESC(channel, "Bus ID of the channel to test (default: any)");
static int dmatest_test_list_get(char *val, const struct kernel_param *kp);
static const struct kernel_param_ops test_list_ops = {
.get = dmatest_test_list_get,
};
module_param_cb(test_list, &test_list_ops, NULL, 0444);
MODULE_PARM_DESC(test_list, "Print current test list");
/* Maximum amount of mismatched bytes in buffer to print */
#define MAX_ERROR_COUNT 32
/*
* Initialization patterns. All bytes in the source buffer has bit 7
* set, all bytes in the destination buffer has bit 7 cleared.
*
* Bit 6 is set for all bytes which are to be copied by the DMA
* engine. Bit 5 is set for all bytes which are to be overwritten by
* the DMA engine.
*
* The remaining bits are the inverse of a counter which increments by
* one for each byte address.
*/
#define PATTERN_SRC 0x80
#define PATTERN_DST 0x00
#define PATTERN_COPY 0x40
#define PATTERN_OVERWRITE 0x20
#define PATTERN_COUNT_MASK 0x1f
#define PATTERN_MEMSET_IDX 0x01
/* Fixed point arithmetic ops */
#define FIXPT_SHIFT 8
#define FIXPNT_MASK 0xFF
#define FIXPT_TO_INT(a) ((a) >> FIXPT_SHIFT)
#define INT_TO_FIXPT(a) ((a) << FIXPT_SHIFT)
#define FIXPT_GET_FRAC(a) ((((a) & FIXPNT_MASK) * 100) >> FIXPT_SHIFT)
/* poor man's completion - we want to use wait_event_freezable() on it */
struct dmatest_done {
bool done;
wait_queue_head_t *wait;
};
struct dmatest_data {
u8 **raw;
u8 **aligned;
unsigned int cnt;
unsigned int off;
};
struct dmatest_thread {
struct list_head node;
struct dmatest_info *info;
struct task_struct *task;
struct dma_chan *chan;
struct dmatest_data src;
struct dmatest_data dst;
enum dma_transaction_type type;
wait_queue_head_t done_wait;
struct dmatest_done test_done;
bool done;
bool pending;
};
struct dmatest_chan {
struct list_head node;
struct dma_chan *chan;
struct list_head threads;
};
static DECLARE_WAIT_QUEUE_HEAD(thread_wait);
static bool wait;
static bool is_threaded_test_run(struct dmatest_info *info)
{
struct dmatest_chan *dtc;
list_for_each_entry(dtc, &info->channels, node) {
struct dmatest_thread *thread;
list_for_each_entry(thread, &dtc->threads, node) {
if (!thread->done)
return true;
}
}
return false;
}
static bool is_threaded_test_pending(struct dmatest_info *info)
{
struct dmatest_chan *dtc;
list_for_each_entry(dtc, &info->channels, node) {
struct dmatest_thread *thread;
list_for_each_entry(thread, &dtc->threads, node) {
if (thread->pending)
return true;
}
}
return false;
}
static int dmatest_wait_get(char *val, const struct kernel_param *kp)
{
struct dmatest_info *info = &test_info;
struct dmatest_params *params = &info->params;
if (params->iterations)
wait_event(thread_wait, !is_threaded_test_run(info));
wait = true;
return param_get_bool(val, kp);
}
static const struct kernel_param_ops wait_ops = {
.get = dmatest_wait_get,
.set = param_set_bool,
};
module_param_cb(wait, &wait_ops, &wait, S_IRUGO);
MODULE_PARM_DESC(wait, "Wait for tests to complete (default: false)");
static bool dmatest_match_channel(struct dmatest_params *params,
struct dma_chan *chan)
{
if (params->channel[0] == '\0')
return true;
return strcmp(dma_chan_name(chan), params->channel) == 0;
}
static bool dmatest_match_device(struct dmatest_params *params,
struct dma_device *device)
{
if (params->device[0] == '\0')
return true;
return strcmp(dev_name(device->dev), params->device) == 0;
}
static unsigned long dmatest_random(void)
{
unsigned long buf;
prandom_bytes(&buf, sizeof(buf));
return buf;
}
static inline u8 gen_inv_idx(u8 index, bool is_memset)
{
u8 val = is_memset ? PATTERN_MEMSET_IDX : index;
return ~val & PATTERN_COUNT_MASK;
}
static inline u8 gen_src_value(u8 index, bool is_memset)
{
return PATTERN_SRC | gen_inv_idx(index, is_memset);
}
static inline u8 gen_dst_value(u8 index, bool is_memset)
{
return PATTERN_DST | gen_inv_idx(index, is_memset);
}
static void dmatest_init_srcs(u8 **bufs, unsigned int start, unsigned int len,
unsigned int buf_size, bool is_memset)
{
unsigned int i;
u8 *buf;
for (; (buf = *bufs); bufs++) {
for (i = 0; i < start; i++)
buf[i] = gen_src_value(i, is_memset);
for ( ; i < start + len; i++)
buf[i] = gen_src_value(i, is_memset) | PATTERN_COPY;
for ( ; i < buf_size; i++)
buf[i] = gen_src_value(i, is_memset);
buf++;
}
}
static void dmatest_init_dsts(u8 **bufs, unsigned int start, unsigned int len,
unsigned int buf_size, bool is_memset)
{
unsigned int i;
u8 *buf;
for (; (buf = *bufs); bufs++) {
for (i = 0; i < start; i++)
buf[i] = gen_dst_value(i, is_memset);
for ( ; i < start + len; i++)
buf[i] = gen_dst_value(i, is_memset) |
PATTERN_OVERWRITE;
for ( ; i < buf_size; i++)
buf[i] = gen_dst_value(i, is_memset);
}
}
static void dmatest_mismatch(u8 actual, u8 pattern, unsigned int index,
unsigned int counter, bool is_srcbuf, bool is_memset)
{
u8 diff = actual ^ pattern;
u8 expected = pattern | gen_inv_idx(counter, is_memset);
const char *thread_name = current->comm;
if (is_srcbuf)
pr_warn("%s: srcbuf[0x%x] overwritten! Expected %02x, got %02x\n",
thread_name, index, expected, actual);
else if ((pattern & PATTERN_COPY)
&& (diff & (PATTERN_COPY | PATTERN_OVERWRITE)))
pr_warn("%s: dstbuf[0x%x] not copied! Expected %02x, got %02x\n",
thread_name, index, expected, actual);
else if (diff & PATTERN_SRC)
pr_warn("%s: dstbuf[0x%x] was copied! Expected %02x, got %02x\n",
thread_name, index, expected, actual);
else
pr_warn("%s: dstbuf[0x%x] mismatch! Expected %02x, got %02x\n",
thread_name, index, expected, actual);
}
static unsigned int dmatest_verify(u8 **bufs, unsigned int start,
unsigned int end, unsigned int counter, u8 pattern,
bool is_srcbuf, bool is_memset)
{
unsigned int i;
unsigned int error_count = 0;
u8 actual;
u8 expected;
u8 *buf;
unsigned int counter_orig = counter;
for (; (buf = *bufs); bufs++) {
counter = counter_orig;
for (i = start; i < end; i++) {
actual = buf[i];
expected = pattern | gen_inv_idx(counter, is_memset);
if (actual != expected) {
if (error_count < MAX_ERROR_COUNT)
dmatest_mismatch(actual, pattern, i,
counter, is_srcbuf,
is_memset);
error_count++;
}
counter++;
}
}
if (error_count > MAX_ERROR_COUNT)
pr_warn("%s: %u errors suppressed\n",
current->comm, error_count - MAX_ERROR_COUNT);
return error_count;
}
static void dmatest_callback(void *arg)
{
struct dmatest_done *done = arg;
struct dmatest_thread *thread =
container_of(done, struct dmatest_thread, test_done);
if (!thread->done) {
done->done = true;
wake_up_all(done->wait);
} else {
/*
* If thread->done, it means that this callback occurred
* after the parent thread has cleaned up. This can
* happen in the case that driver doesn't implement
* the terminate_all() functionality and a dma operation
* did not occur within the timeout period
*/
WARN(1, "dmatest: Kernel memory may be corrupted!!\n");
}
}
static unsigned int min_odd(unsigned int x, unsigned int y)
{
unsigned int val = min(x, y);
return val % 2 ? val : val - 1;
}
static void result(const char *err, unsigned int n, unsigned int src_off,
unsigned int dst_off, unsigned int len, unsigned long data)
{
pr_info("%s: result #%u: '%s' with src_off=0x%x dst_off=0x%x len=0x%x (%lu)\n",
current->comm, n, err, src_off, dst_off, len, data);
}
static void dbg_result(const char *err, unsigned int n, unsigned int src_off,
unsigned int dst_off, unsigned int len,
unsigned long data)
{
pr_debug("%s: result #%u: '%s' with src_off=0x%x dst_off=0x%x len=0x%x (%lu)\n",
current->comm, n, err, src_off, dst_off, len, data);
}
#define verbose_result(err, n, src_off, dst_off, len, data) ({ \
if (verbose) \
result(err, n, src_off, dst_off, len, data); \
else \
dbg_result(err, n, src_off, dst_off, len, data);\
})
static unsigned long long dmatest_persec(s64 runtime, unsigned int val)
{
unsigned long long per_sec = 1000000;
if (runtime <= 0)
return 0;
/* drop precision until runtime is 32-bits */
while (runtime > UINT_MAX) {
runtime >>= 1;
per_sec <<= 1;
}
per_sec *= val;
per_sec = INT_TO_FIXPT(per_sec);
do_div(per_sec, runtime);
return per_sec;
}
static unsigned long long dmatest_KBs(s64 runtime, unsigned long long len)
{
return FIXPT_TO_INT(dmatest_persec(runtime, len >> 10));
}
static void __dmatest_free_test_data(struct dmatest_data *d, unsigned int cnt)
{
unsigned int i;
for (i = 0; i < cnt; i++)
kfree(d->raw[i]);
kfree(d->aligned);
kfree(d->raw);
}
static void dmatest_free_test_data(struct dmatest_data *d)
{
__dmatest_free_test_data(d, d->cnt);
}
static int dmatest_alloc_test_data(struct dmatest_data *d,
unsigned int buf_size, u8 align)
{
unsigned int i = 0;
d->raw = kcalloc(d->cnt + 1, sizeof(u8 *), GFP_KERNEL);
if (!d->raw)
return -ENOMEM;
d->aligned = kcalloc(d->cnt + 1, sizeof(u8 *), GFP_KERNEL);
if (!d->aligned)
goto err;
for (i = 0; i < d->cnt; i++) {
d->raw[i] = kmalloc(buf_size + align, GFP_KERNEL);
if (!d->raw[i])
goto err;
/* align to alignment restriction */
if (align)
d->aligned[i] = PTR_ALIGN(d->raw[i], align);
else
d->aligned[i] = d->raw[i];
}
return 0;
err:
__dmatest_free_test_data(d, i);
return -ENOMEM;
}
/*
* This function repeatedly tests DMA transfers of various lengths and
* offsets for a given operation type until it is told to exit by
* kthread_stop(). There may be multiple threads running this function
* in parallel for a single channel, and there may be multiple channels
* being tested in parallel.
*
* Before each test, the source and destination buffer is initialized
* with a known pattern. This pattern is different depending on
* whether it's in an area which is supposed to be copied or
* overwritten, and different in the source and destination buffers.
* So if the DMA engine doesn't copy exactly what we tell it to copy,
* we'll notice.
*/
static int dmatest_func(void *data)
{
struct dmatest_thread *thread = data;
struct dmatest_done *done = &thread->test_done;
struct dmatest_info *info;
struct dmatest_params *params;
struct dma_chan *chan;
struct dma_device *dev;
unsigned int error_count;
unsigned int failed_tests = 0;
unsigned int total_tests = 0;
dma_cookie_t cookie;
enum dma_status status;
enum dma_ctrl_flags flags;
u8 *pq_coefs = NULL;
int ret;
unsigned int buf_size;
struct dmatest_data *src;
struct dmatest_data *dst;
int i;
ktime_t ktime, start, diff;
ktime_t filltime = 0;
ktime_t comparetime = 0;
s64 runtime = 0;
unsigned long long total_len = 0;
unsigned long long iops = 0;
u8 align = 0;
bool is_memset = false;
dma_addr_t *srcs;
dma_addr_t *dma_pq;
set_freezable();
ret = -ENOMEM;
smp_rmb();
thread->pending = false;
info = thread->info;
params = &info->params;
chan = thread->chan;
dev = chan->device;
src = &thread->src;
dst = &thread->dst;
if (thread->type == DMA_MEMCPY) {
align = params->alignment < 0 ? dev->copy_align :
params->alignment;
src->cnt = dst->cnt = 1;
} else if (thread->type == DMA_MEMSET) {
align = params->alignment < 0 ? dev->fill_align :
params->alignment;
src->cnt = dst->cnt = 1;
is_memset = true;
} else if (thread->type == DMA_XOR) {
/* force odd to ensure dst = src */
src->cnt = min_odd(params->xor_sources | 1, dev->max_xor);
dst->cnt = 1;
align = params->alignment < 0 ? dev->xor_align :
params->alignment;
} else if (thread->type == DMA_PQ) {
/* force odd to ensure dst = src */
src->cnt = min_odd(params->pq_sources | 1, dma_maxpq(dev, 0));
dst->cnt = 2;
align = params->alignment < 0 ? dev->pq_align :
params->alignment;
pq_coefs = kmalloc(params->pq_sources + 1, GFP_KERNEL);
if (!pq_coefs)
goto err_thread_type;
for (i = 0; i < src->cnt; i++)
pq_coefs[i] = 1;
} else
goto err_thread_type;
/* Check if buffer count fits into map count variable (u8) */
if ((src->cnt + dst->cnt) >= 255) {
pr_err("too many buffers (%d of 255 supported)\n",
src->cnt + dst->cnt);
goto err_free_coefs;
}
buf_size = params->buf_size;
if (1 << align > buf_size) {
pr_err("%u-byte buffer too small for %d-byte alignment\n",
buf_size, 1 << align);
goto err_free_coefs;
}
if (dmatest_alloc_test_data(src, buf_size, align) < 0)
goto err_free_coefs;
if (dmatest_alloc_test_data(dst, buf_size, align) < 0)
goto err_src;
set_user_nice(current, 10);
srcs = kcalloc(src->cnt, sizeof(dma_addr_t), GFP_KERNEL);
if (!srcs)
goto err_dst;
dma_pq = kcalloc(dst->cnt, sizeof(dma_addr_t), GFP_KERNEL);
if (!dma_pq)
goto err_srcs_array;
/*
* src and dst buffers are freed by ourselves below
*/
if (params->polled)
flags = DMA_CTRL_ACK;
else
flags = DMA_CTRL_ACK | DMA_PREP_INTERRUPT;
ktime = ktime_get();
while (!kthread_should_stop()
&& !(params->iterations && total_tests >= params->iterations)) {
struct dma_async_tx_descriptor *tx = NULL;
struct dmaengine_unmap_data *um;
dma_addr_t *dsts;
unsigned int len;
total_tests++;
if (params->transfer_size) {
if (params->transfer_size >= buf_size) {
pr_err("%u-byte transfer size must be lower than %u-buffer size\n",
params->transfer_size, buf_size);
break;
}
len = params->transfer_size;
} else if (params->norandom) {
len = buf_size;
} else {
len = dmatest_random() % buf_size + 1;
}
/* Do not alter transfer size explicitly defined by user */
if (!params->transfer_size) {
len = (len >> align) << align;
if (!len)
len = 1 << align;
}
total_len += len;
if (params->norandom) {
src->off = 0;
dst->off = 0;
} else {
src->off = dmatest_random() % (buf_size - len + 1);
dst->off = dmatest_random() % (buf_size - len + 1);
src->off = (src->off >> align) << align;
dst->off = (dst->off >> align) << align;
}
if (!params->noverify) {
start = ktime_get();
dmatest_init_srcs(src->aligned, src->off, len,
buf_size, is_memset);
dmatest_init_dsts(dst->aligned, dst->off, len,
buf_size, is_memset);
diff = ktime_sub(ktime_get(), start);
filltime = ktime_add(filltime, diff);
}
um = dmaengine_get_unmap_data(dev->dev, src->cnt + dst->cnt,
GFP_KERNEL);
if (!um) {
failed_tests++;
result("unmap data NULL", total_tests,
src->off, dst->off, len, ret);
continue;
}
um->len = buf_size;
for (i = 0; i < src->cnt; i++) {
void *buf = src->aligned[i];
struct page *pg = virt_to_page(buf);
unsigned long pg_off = offset_in_page(buf);
um->addr[i] = dma_map_page(dev->dev, pg, pg_off,
um->len, DMA_TO_DEVICE);
srcs[i] = um->addr[i] + src->off;
ret = dma_mapping_error(dev->dev, um->addr[i]);
if (ret) {
result("src mapping error", total_tests,
src->off, dst->off, len, ret);
goto error_unmap_continue;
}
um->to_cnt++;
}
/* map with DMA_BIDIRECTIONAL to force writeback/invalidate */
dsts = &um->addr[src->cnt];
for (i = 0; i < dst->cnt; i++) {
void *buf = dst->aligned[i];
struct page *pg = virt_to_page(buf);
unsigned long pg_off = offset_in_page(buf);
dsts[i] = dma_map_page(dev->dev, pg, pg_off, um->len,
DMA_BIDIRECTIONAL);
ret = dma_mapping_error(dev->dev, dsts[i]);
if (ret) {
result("dst mapping error", total_tests,
src->off, dst->off, len, ret);
goto error_unmap_continue;
}
um->bidi_cnt++;
}
if (thread->type == DMA_MEMCPY)
tx = dev->device_prep_dma_memcpy(chan,
dsts[0] + dst->off,
srcs[0], len, flags);
else if (thread->type == DMA_MEMSET)
tx = dev->device_prep_dma_memset(chan,
dsts[0] + dst->off,
*(src->aligned[0] + src->off),
len, flags);
else if (thread->type == DMA_XOR)
tx = dev->device_prep_dma_xor(chan,
dsts[0] + dst->off,
srcs, src->cnt,
len, flags);
else if (thread->type == DMA_PQ) {
for (i = 0; i < dst->cnt; i++)
dma_pq[i] = dsts[i] + dst->off;
tx = dev->device_prep_dma_pq(chan, dma_pq, srcs,
src->cnt, pq_coefs,
len, flags);
}
if (!tx) {
result("prep error", total_tests, src->off,
dst->off, len, ret);
msleep(100);
goto error_unmap_continue;
}
done->done = false;
if (!params->polled) {
tx->callback = dmatest_callback;
tx->callback_param = done;
}
cookie = tx->tx_submit(tx);
if (dma_submit_error(cookie)) {
result("submit error", total_tests, src->off,
dst->off, len, ret);
msleep(100);
goto error_unmap_continue;
}
if (params->polled) {
status = dma_sync_wait(chan, cookie);
dmaengine_terminate_sync(chan);
if (status == DMA_COMPLETE)
done->done = true;
} else {
dma_async_issue_pending(chan);
wait_event_freezable_timeout(thread->done_wait,
done->done,
msecs_to_jiffies(params->timeout));
status = dma_async_is_tx_complete(chan, cookie, NULL,
NULL);
}
if (!done->done) {
result("test timed out", total_tests, src->off, dst->off,
len, 0);
goto error_unmap_continue;
} else if (status != DMA_COMPLETE) {
result(status == DMA_ERROR ?
"completion error status" :
"completion busy status", total_tests, src->off,
dst->off, len, ret);
goto error_unmap_continue;
}
dmaengine_unmap_put(um);
if (params->noverify) {
verbose_result("test passed", total_tests, src->off,
dst->off, len, 0);
continue;
}
start = ktime_get();
pr_debug("%s: verifying source buffer...\n", current->comm);
error_count = dmatest_verify(src->aligned, 0, src->off,
0, PATTERN_SRC, true, is_memset);
error_count += dmatest_verify(src->aligned, src->off,
src->off + len, src->off,
PATTERN_SRC | PATTERN_COPY, true, is_memset);
error_count += dmatest_verify(src->aligned, src->off + len,
buf_size, src->off + len,
PATTERN_SRC, true, is_memset);
pr_debug("%s: verifying dest buffer...\n", current->comm);
error_count += dmatest_verify(dst->aligned, 0, dst->off,
0, PATTERN_DST, false, is_memset);
error_count += dmatest_verify(dst->aligned, dst->off,
dst->off + len, src->off,
PATTERN_SRC | PATTERN_COPY, false, is_memset);
error_count += dmatest_verify(dst->aligned, dst->off + len,
buf_size, dst->off + len,
PATTERN_DST, false, is_memset);
diff = ktime_sub(ktime_get(), start);
comparetime = ktime_add(comparetime, diff);
if (error_count) {
result("data error", total_tests, src->off, dst->off,
len, error_count);
failed_tests++;
} else {
verbose_result("test passed", total_tests, src->off,
dst->off, len, 0);
}
continue;
error_unmap_continue:
dmaengine_unmap_put(um);
failed_tests++;
}
ktime = ktime_sub(ktime_get(), ktime);
ktime = ktime_sub(ktime, comparetime);
ktime = ktime_sub(ktime, filltime);
runtime = ktime_to_us(ktime);
ret = 0;
kfree(dma_pq);
err_srcs_array:
kfree(srcs);
err_dst:
dmatest_free_test_data(dst);
err_src:
dmatest_free_test_data(src);
err_free_coefs:
kfree(pq_coefs);
err_thread_type:
iops = dmatest_persec(runtime, total_tests);
pr_info("%s: summary %u tests, %u failures %llu.%02llu iops %llu KB/s (%d)\n",
current->comm, total_tests, failed_tests,
FIXPT_TO_INT(iops), FIXPT_GET_FRAC(iops),
dmatest_KBs(runtime, total_len), ret);
/* terminate all transfers on specified channels */
if (ret || failed_tests)
dmaengine_terminate_sync(chan);
thread->done = true;
wake_up(&thread_wait);
return ret;
}
static void dmatest_cleanup_channel(struct dmatest_chan *dtc)
{
struct dmatest_thread *thread;
struct dmatest_thread *_thread;
int ret;
list_for_each_entry_safe(thread, _thread, &dtc->threads, node) {
ret = kthread_stop(thread->task);
pr_debug("thread %s exited with status %d\n",
thread->task->comm, ret);
list_del(&thread->node);
put_task_struct(thread->task);
kfree(thread);
}
/* terminate all transfers on specified channels */
dmaengine_terminate_sync(dtc->chan);
kfree(dtc);
}
static int dmatest_add_threads(struct dmatest_info *info,
struct dmatest_chan *dtc, enum dma_transaction_type type)
{
struct dmatest_params *params = &info->params;
struct dmatest_thread *thread;
struct dma_chan *chan = dtc->chan;
char *op;
unsigned int i;
if (type == DMA_MEMCPY)
op = "copy";
else if (type == DMA_MEMSET)
op = "set";
else if (type == DMA_XOR)
op = "xor";
else if (type == DMA_PQ)
op = "pq";
else
return -EINVAL;
for (i = 0; i < params->threads_per_chan; i++) {
thread = kzalloc(sizeof(struct dmatest_thread), GFP_KERNEL);
if (!thread) {
pr_warn("No memory for %s-%s%u\n",
dma_chan_name(chan), op, i);
break;
}
thread->info = info;
thread->chan = dtc->chan;
thread->type = type;
thread->test_done.wait = &thread->done_wait;
init_waitqueue_head(&thread->done_wait);
smp_wmb();
thread->task = kthread_create(dmatest_func, thread, "%s-%s%u",
dma_chan_name(chan), op, i);
if (IS_ERR(thread->task)) {
pr_warn("Failed to create thread %s-%s%u\n",
dma_chan_name(chan), op, i);
kfree(thread);
break;
}
/* srcbuf and dstbuf are allocated by the thread itself */
get_task_struct(thread->task);
list_add_tail(&thread->node, &dtc->threads);
thread->pending = true;
}
return i;
}
static int dmatest_add_channel(struct dmatest_info *info,
struct dma_chan *chan)
{
struct dmatest_chan *dtc;
struct dma_device *dma_dev = chan->device;
unsigned int thread_count = 0;
int cnt;
dtc = kmalloc(sizeof(struct dmatest_chan), GFP_KERNEL);
if (!dtc) {
pr_warn("No memory for %s\n", dma_chan_name(chan));
return -ENOMEM;
}
dtc->chan = chan;
INIT_LIST_HEAD(&dtc->threads);
if (dma_has_cap(DMA_MEMCPY, dma_dev->cap_mask)) {
if (dmatest == 0) {
cnt = dmatest_add_threads(info, dtc, DMA_MEMCPY);
thread_count += cnt > 0 ? cnt : 0;
}
}
if (dma_has_cap(DMA_MEMSET, dma_dev->cap_mask)) {
if (dmatest == 1) {
cnt = dmatest_add_threads(info, dtc, DMA_MEMSET);
thread_count += cnt > 0 ? cnt : 0;
}
}
if (dma_has_cap(DMA_XOR, dma_dev->cap_mask)) {
cnt = dmatest_add_threads(info, dtc, DMA_XOR);
thread_count += cnt > 0 ? cnt : 0;
}
if (dma_has_cap(DMA_PQ, dma_dev->cap_mask)) {
cnt = dmatest_add_threads(info, dtc, DMA_PQ);
thread_count += cnt > 0 ? cnt : 0;
}
pr_info("Added %u threads using %s\n",
thread_count, dma_chan_name(chan));
list_add_tail(&dtc->node, &info->channels);
info->nr_channels++;
return 0;
}
static bool filter(struct dma_chan *chan, void *param)
{
struct dmatest_params *params = param;
if (!dmatest_match_channel(params, chan) ||
!dmatest_match_device(params, chan->device))
return false;
else
return true;
}
static void request_channels(struct dmatest_info *info,
enum dma_transaction_type type)
{
dma_cap_mask_t mask;
dma_cap_zero(mask);
dma_cap_set(type, mask);
for (;;) {
struct dmatest_params *params = &info->params;
struct dma_chan *chan;
chan = dma_request_channel(mask, filter, params);
if (chan) {
if (dmatest_add_channel(info, chan)) {
dma_release_channel(chan);
break; /* add_channel failed, punt */
}
} else
break; /* no more channels available */
if (params->max_channels &&
info->nr_channels >= params->max_channels)
break; /* we have all we need */
}
}
static void add_threaded_test(struct dmatest_info *info)
{
struct dmatest_params *params = &info->params;
/* Copy test parameters */
params->buf_size = test_buf_size;
strlcpy(params->channel, strim(test_channel), sizeof(params->channel));
strlcpy(params->device, strim(test_device), sizeof(params->device));
params->threads_per_chan = threads_per_chan;
params->max_channels = max_channels;
params->iterations = iterations;
params->xor_sources = xor_sources;
params->pq_sources = pq_sources;
params->timeout = timeout;
params->noverify = noverify;
params->norandom = norandom;
params->alignment = alignment;
params->transfer_size = transfer_size;
params->polled = polled;
request_channels(info, DMA_MEMCPY);
request_channels(info, DMA_MEMSET);
request_channels(info, DMA_XOR);
request_channels(info, DMA_PQ);
}
static void run_pending_tests(struct dmatest_info *info)
{
struct dmatest_chan *dtc;
unsigned int thread_count = 0;
list_for_each_entry(dtc, &info->channels, node) {
struct dmatest_thread *thread;
thread_count = 0;
list_for_each_entry(thread, &dtc->threads, node) {
wake_up_process(thread->task);
thread_count++;
}
pr_info("Started %u threads using %s\n",
thread_count, dma_chan_name(dtc->chan));
}
}
static void stop_threaded_test(struct dmatest_info *info)
{
struct dmatest_chan *dtc, *_dtc;
struct dma_chan *chan;
list_for_each_entry_safe(dtc, _dtc, &info->channels, node) {
list_del(&dtc->node);
chan = dtc->chan;
dmatest_cleanup_channel(dtc);
pr_debug("dropped channel %s\n", dma_chan_name(chan));
dma_release_channel(chan);
}
info->nr_channels = 0;
}
static void start_threaded_tests(struct dmatest_info *info)
{
/* we might be called early to set run=, defer running until all
* parameters have been evaluated
*/
if (!info->did_init)
return;
run_pending_tests(info);
}
static int dmatest_run_get(char *val, const struct kernel_param *kp)
{
struct dmatest_info *info = &test_info;
mutex_lock(&info->lock);
if (is_threaded_test_run(info)) {
dmatest_run = true;
} else {
if (!is_threaded_test_pending(info))
stop_threaded_test(info);
dmatest_run = false;
}
mutex_unlock(&info->lock);
return param_get_bool(val, kp);
}
static int dmatest_run_set(const char *val, const struct kernel_param *kp)
{
struct dmatest_info *info = &test_info;
int ret;
mutex_lock(&info->lock);
ret = param_set_bool(val, kp);
if (ret) {
mutex_unlock(&info->lock);
return ret;
} else if (dmatest_run) {
if (is_threaded_test_pending(info))
start_threaded_tests(info);
else
pr_info("Could not start test, no channels configured\n");
} else {
stop_threaded_test(info);
}
mutex_unlock(&info->lock);
return ret;
}
static int dmatest_chan_set(const char *val, const struct kernel_param *kp)
{
struct dmatest_info *info = &test_info;
struct dmatest_chan *dtc;
char chan_reset_val[20];
int ret = 0;
mutex_lock(&info->lock);
ret = param_set_copystring(val, kp);
if (ret) {
mutex_unlock(&info->lock);
return ret;
}
/*Clear any previously run threads */
if (!is_threaded_test_run(info) && !is_threaded_test_pending(info))
stop_threaded_test(info);
/* Reject channels that are already registered */
if (is_threaded_test_pending(info)) {
list_for_each_entry(dtc, &info->channels, node) {
if (strcmp(dma_chan_name(dtc->chan),
strim(test_channel)) == 0) {
dtc = list_last_entry(&info->channels,
struct dmatest_chan,
node);
strlcpy(chan_reset_val,
dma_chan_name(dtc->chan),
sizeof(chan_reset_val));
ret = -EBUSY;
goto add_chan_err;
}
}
}
add_threaded_test(info);
/* Check if channel was added successfully */
dtc = list_last_entry(&info->channels, struct dmatest_chan, node);
if (dtc->chan) {
/*
* if new channel was not successfully added, revert the
* "test_channel" string to the name of the last successfully
* added channel. exception for when users issues empty string
* to channel parameter.
*/
if ((strcmp(dma_chan_name(dtc->chan), strim(test_channel)) != 0)
&& (strcmp("", strim(test_channel)) != 0)) {
ret = -EINVAL;
strlcpy(chan_reset_val, dma_chan_name(dtc->chan),
sizeof(chan_reset_val));
goto add_chan_err;
}
} else {
/* Clear test_channel if no channels were added successfully */
strlcpy(chan_reset_val, "", sizeof(chan_reset_val));
ret = -EBUSY;
goto add_chan_err;
}
mutex_unlock(&info->lock);
return ret;
add_chan_err:
param_set_copystring(chan_reset_val, kp);
mutex_unlock(&info->lock);
return ret;
}
static int dmatest_chan_get(char *val, const struct kernel_param *kp)
{
struct dmatest_info *info = &test_info;
mutex_lock(&info->lock);
if (!is_threaded_test_run(info) && !is_threaded_test_pending(info)) {
stop_threaded_test(info);
strlcpy(test_channel, "", sizeof(test_channel));
}
mutex_unlock(&info->lock);
return param_get_string(val, kp);
}
static int dmatest_test_list_get(char *val, const struct kernel_param *kp)
{
struct dmatest_info *info = &test_info;
struct dmatest_chan *dtc;
unsigned int thread_count = 0;
list_for_each_entry(dtc, &info->channels, node) {
struct dmatest_thread *thread;
thread_count = 0;
list_for_each_entry(thread, &dtc->threads, node) {
thread_count++;
}
pr_info("%u threads using %s\n",
thread_count, dma_chan_name(dtc->chan));
}
return 0;
}
static int __init dmatest_init(void)
{
struct dmatest_info *info = &test_info;
struct dmatest_params *params = &info->params;
if (dmatest_run) {
mutex_lock(&info->lock);
add_threaded_test(info);
run_pending_tests(info);
mutex_unlock(&info->lock);
}
if (params->iterations && wait)
wait_event(thread_wait, !is_threaded_test_run(info));
/* module parameters are stable, inittime tests are started,
* let userspace take over 'run' control
*/
info->did_init = true;
return 0;
}
/* when compiled-in wait for drivers to load first */
late_initcall(dmatest_init);
static void __exit dmatest_exit(void)
{
struct dmatest_info *info = &test_info;
mutex_lock(&info->lock);
stop_threaded_test(info);
mutex_unlock(&info->lock);
}
module_exit(dmatest_exit);
MODULE_AUTHOR("Haavard Skinnemoen (Atmel)");
MODULE_LICENSE("GPL v2");
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-5.4/drivers/dma/dmatest.c | C | gpl-2.0 | 34,898 |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example104-jquery</title>
<script src="../../components/jquery-2.1.1/jquery.js"></script>
<script src="../../../angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="orderByExample">
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:'-age'">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</body>
</html> | keithbox/PPSP-360_Degree_Evaluation_System | web_root/third-party/angularjs/angular-1.5.0/docs/examples/example-example104/index-jquery.html | HTML | gpl-3.0 | 661 |
/* 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.
==============================================================================*/
#include "tensorflow/core/grappler/clusters/utils.h"
#include "third_party/eigen3/Eigen/Core"
#if GOOGLE_CUDA
#include "cuda/include/cuda.h"
#include "cuda/include/cuda_runtime_api.h"
#include "cuda/include/cudnn.h"
#endif
#ifdef EIGEN_USE_LIBXSMM
#include "include/libxsmm.h"
#endif
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/cpu_info.h"
namespace tensorflow {
namespace grappler {
DeviceProperties GetLocalCPUInfo() {
DeviceProperties device;
device.set_type("CPU");
device.set_vendor(port::CPUVendorIDString());
// Combine cpu family and model into the model string.
device.set_model(
strings::StrCat((port::CPUFamily() << 4) + port::CPUModelNum()));
device.set_frequency(port::NominalCPUFrequency() * 1e-6);
device.set_num_cores(port::NumSchedulableCPUs());
device.set_l1_cache_size(Eigen::l1CacheSize());
device.set_l2_cache_size(Eigen::l2CacheSize());
device.set_l3_cache_size(Eigen::l3CacheSize());
(*device.mutable_environment())["cpu_instruction_set"] =
Eigen::SimdInstructionSetsInUse();
(*device.mutable_environment())["eigen"] = strings::StrCat(
EIGEN_WORLD_VERSION, ".", EIGEN_MAJOR_VERSION, ".", EIGEN_MINOR_VERSION);
#ifdef EIGEN_USE_LIBXSMM
(*device.mutable_environment())["libxsmm"] = LIBXSMM_VERSION;
#endif
return device;
}
DeviceProperties GetLocalGPUInfo(int gpu_id) {
DeviceProperties device;
device.set_type("GPU");
#if GOOGLE_CUDA
cudaDeviceProp properties;
cudaError_t error = cudaGetDeviceProperties(&properties, gpu_id);
if (error == cudaSuccess) {
device.set_vendor("NVidia");
device.set_model(properties.name);
device.set_frequency(properties.clockRate * 1e-3);
device.set_num_cores(properties.multiProcessorCount);
device.set_num_registers(properties.regsPerMultiprocessor);
// For compute capability less than 5, l1 cache size is configurable to
// either 16 KB or 48 KB. We use the initial configuration 16 KB here. For
// compute capability larger or equal to 5, l1 cache (unified with texture
// cache) size is 24 KB. This number may need to be updated for future
// compute capabilities.
device.set_l1_cache_size((properties.major < 5) ? 16 * 1024 : 24 * 1024);
device.set_l2_cache_size(properties.l2CacheSize);
device.set_l3_cache_size(0);
device.set_shared_memory_size_per_multiprocessor(
properties.sharedMemPerMultiprocessor);
device.set_memory_size(properties.totalGlobalMem);
// 8 is the number of bits per byte. 2 is accounted for
// double data rate (DDR).
device.set_bandwidth(properties.memoryBusWidth / 8 *
properties.memoryClockRate * 2);
}
(*device.mutable_environment())["architecture"] =
strings::StrCat(properties.major, ".", properties.minor);
(*device.mutable_environment())["cuda"] = strings::StrCat(CUDA_VERSION);
(*device.mutable_environment())["cudnn"] = strings::StrCat(CUDNN_VERSION);
#endif
return device;
}
DeviceProperties GetDeviceInfo(const DeviceNameUtils::ParsedName& device) {
if (device.type == "CPU") {
return GetLocalCPUInfo();
} else if (device.type == "GPU") {
if (device.has_id) {
return GetLocalGPUInfo(device.id);
} else {
return GetLocalGPUInfo(0);
}
}
DeviceProperties result;
result.set_type("UNKNOWN");
return result;
}
} // end namespace grappler
} // end namespace tensorflow
| npuichigo/ttsflow | third_party/tensorflow/tensorflow/core/grappler/clusters/utils.cc | C++ | apache-2.0 | 4,151 |
/* SPDX-License-Identifier: GPL-2.0 */
/*
* ioport.h Definitions of routines for detecting, reserving and
* allocating system resources.
*
* Authors: Linus Torvalds
*/
#ifndef _LINUX_IOPORT_H
#define _LINUX_IOPORT_H
#ifndef __ASSEMBLY__
#include <linux/compiler.h>
#include <linux/types.h>
#include <linux/bits.h>
/*
* Resources are tree-like, allowing
* nesting etc..
*/
struct resource {
resource_size_t start;
resource_size_t end;
const char *name;
unsigned long flags;
unsigned long desc;
struct resource *parent, *sibling, *child;
};
/*
* IO resources have these defined flags.
*
* PCI devices expose these flags to userspace in the "resource" sysfs file,
* so don't move them.
*/
#define IORESOURCE_BITS 0x000000ff /* Bus-specific bits */
#define IORESOURCE_TYPE_BITS 0x00001f00 /* Resource type */
#define IORESOURCE_IO 0x00000100 /* PCI/ISA I/O ports */
#define IORESOURCE_MEM 0x00000200
#define IORESOURCE_REG 0x00000300 /* Register offsets */
#define IORESOURCE_IRQ 0x00000400
#define IORESOURCE_DMA 0x00000800
#define IORESOURCE_BUS 0x00001000
#define IORESOURCE_PREFETCH 0x00002000 /* No side effects */
#define IORESOURCE_READONLY 0x00004000
#define IORESOURCE_CACHEABLE 0x00008000
#define IORESOURCE_RANGELENGTH 0x00010000
#define IORESOURCE_SHADOWABLE 0x00020000
#define IORESOURCE_SIZEALIGN 0x00040000 /* size indicates alignment */
#define IORESOURCE_STARTALIGN 0x00080000 /* start field is alignment */
#define IORESOURCE_MEM_64 0x00100000
#define IORESOURCE_WINDOW 0x00200000 /* forwarded by bridge */
#define IORESOURCE_MUXED 0x00400000 /* Resource is software muxed */
#define IORESOURCE_EXT_TYPE_BITS 0x01000000 /* Resource extended types */
#define IORESOURCE_SYSRAM 0x01000000 /* System RAM (modifier) */
#define IORESOURCE_EXCLUSIVE 0x08000000 /* Userland may not map this resource */
#define IORESOURCE_DISABLED 0x10000000
#define IORESOURCE_UNSET 0x20000000 /* No address assigned yet */
#define IORESOURCE_AUTO 0x40000000
#define IORESOURCE_BUSY 0x80000000 /* Driver has marked this resource busy */
/* I/O resource extended types */
#define IORESOURCE_SYSTEM_RAM (IORESOURCE_MEM|IORESOURCE_SYSRAM)
/* PnP IRQ specific bits (IORESOURCE_BITS) */
#define IORESOURCE_IRQ_HIGHEDGE (1<<0)
#define IORESOURCE_IRQ_LOWEDGE (1<<1)
#define IORESOURCE_IRQ_HIGHLEVEL (1<<2)
#define IORESOURCE_IRQ_LOWLEVEL (1<<3)
#define IORESOURCE_IRQ_SHAREABLE (1<<4)
#define IORESOURCE_IRQ_OPTIONAL (1<<5)
/* PnP DMA specific bits (IORESOURCE_BITS) */
#define IORESOURCE_DMA_TYPE_MASK (3<<0)
#define IORESOURCE_DMA_8BIT (0<<0)
#define IORESOURCE_DMA_8AND16BIT (1<<0)
#define IORESOURCE_DMA_16BIT (2<<0)
#define IORESOURCE_DMA_MASTER (1<<2)
#define IORESOURCE_DMA_BYTE (1<<3)
#define IORESOURCE_DMA_WORD (1<<4)
#define IORESOURCE_DMA_SPEED_MASK (3<<6)
#define IORESOURCE_DMA_COMPATIBLE (0<<6)
#define IORESOURCE_DMA_TYPEA (1<<6)
#define IORESOURCE_DMA_TYPEB (2<<6)
#define IORESOURCE_DMA_TYPEF (3<<6)
/* PnP memory I/O specific bits (IORESOURCE_BITS) */
#define IORESOURCE_MEM_WRITEABLE (1<<0) /* dup: IORESOURCE_READONLY */
#define IORESOURCE_MEM_CACHEABLE (1<<1) /* dup: IORESOURCE_CACHEABLE */
#define IORESOURCE_MEM_RANGELENGTH (1<<2) /* dup: IORESOURCE_RANGELENGTH */
#define IORESOURCE_MEM_TYPE_MASK (3<<3)
#define IORESOURCE_MEM_8BIT (0<<3)
#define IORESOURCE_MEM_16BIT (1<<3)
#define IORESOURCE_MEM_8AND16BIT (2<<3)
#define IORESOURCE_MEM_32BIT (3<<3)
#define IORESOURCE_MEM_SHADOWABLE (1<<5) /* dup: IORESOURCE_SHADOWABLE */
#define IORESOURCE_MEM_EXPANSIONROM (1<<6)
#define IORESOURCE_MEM_DRIVER_MANAGED (1<<7)
/* PnP I/O specific bits (IORESOURCE_BITS) */
#define IORESOURCE_IO_16BIT_ADDR (1<<0)
#define IORESOURCE_IO_FIXED (1<<1)
#define IORESOURCE_IO_SPARSE (1<<2)
/* PCI ROM control bits (IORESOURCE_BITS) */
#define IORESOURCE_ROM_ENABLE (1<<0) /* ROM is enabled, same as PCI_ROM_ADDRESS_ENABLE */
#define IORESOURCE_ROM_SHADOW (1<<1) /* Use RAM image, not ROM BAR */
/* PCI control bits. Shares IORESOURCE_BITS with above PCI ROM. */
#define IORESOURCE_PCI_FIXED (1<<4) /* Do not move resource */
#define IORESOURCE_PCI_EA_BEI (1<<5) /* BAR Equivalent Indicator */
/*
* I/O Resource Descriptors
*
* Descriptors are used by walk_iomem_res_desc() and region_intersects()
* for searching a specific resource range in the iomem table. Assign
* a new descriptor when a resource range supports the search interfaces.
* Otherwise, resource.desc must be set to IORES_DESC_NONE (0).
*/
enum {
IORES_DESC_NONE = 0,
IORES_DESC_CRASH_KERNEL = 1,
IORES_DESC_ACPI_TABLES = 2,
IORES_DESC_ACPI_NV_STORAGE = 3,
IORES_DESC_PERSISTENT_MEMORY = 4,
IORES_DESC_PERSISTENT_MEMORY_LEGACY = 5,
IORES_DESC_DEVICE_PRIVATE_MEMORY = 6,
IORES_DESC_RESERVED = 7,
IORES_DESC_SOFT_RESERVED = 8,
};
/*
* Flags controlling ioremap() behavior.
*/
enum {
IORES_MAP_SYSTEM_RAM = BIT(0),
IORES_MAP_ENCRYPTED = BIT(1),
};
/* helpers to define resources */
#define DEFINE_RES_NAMED(_start, _size, _name, _flags) \
{ \
.start = (_start), \
.end = (_start) + (_size) - 1, \
.name = (_name), \
.flags = (_flags), \
.desc = IORES_DESC_NONE, \
}
#define DEFINE_RES_IO_NAMED(_start, _size, _name) \
DEFINE_RES_NAMED((_start), (_size), (_name), IORESOURCE_IO)
#define DEFINE_RES_IO(_start, _size) \
DEFINE_RES_IO_NAMED((_start), (_size), NULL)
#define DEFINE_RES_MEM_NAMED(_start, _size, _name) \
DEFINE_RES_NAMED((_start), (_size), (_name), IORESOURCE_MEM)
#define DEFINE_RES_MEM(_start, _size) \
DEFINE_RES_MEM_NAMED((_start), (_size), NULL)
#define DEFINE_RES_IRQ_NAMED(_irq, _name) \
DEFINE_RES_NAMED((_irq), 1, (_name), IORESOURCE_IRQ)
#define DEFINE_RES_IRQ(_irq) \
DEFINE_RES_IRQ_NAMED((_irq), NULL)
#define DEFINE_RES_DMA_NAMED(_dma, _name) \
DEFINE_RES_NAMED((_dma), 1, (_name), IORESOURCE_DMA)
#define DEFINE_RES_DMA(_dma) \
DEFINE_RES_DMA_NAMED((_dma), NULL)
/* PC/ISA/whatever - the normal PC address spaces: IO and memory */
extern struct resource ioport_resource;
extern struct resource iomem_resource;
extern struct resource *request_resource_conflict(struct resource *root, struct resource *new);
extern int request_resource(struct resource *root, struct resource *new);
extern int release_resource(struct resource *new);
void release_child_resources(struct resource *new);
extern void reserve_region_with_split(struct resource *root,
resource_size_t start, resource_size_t end,
const char *name);
extern struct resource *insert_resource_conflict(struct resource *parent, struct resource *new);
extern int insert_resource(struct resource *parent, struct resource *new);
extern void insert_resource_expand_to_fit(struct resource *root, struct resource *new);
extern int remove_resource(struct resource *old);
extern void arch_remove_reservations(struct resource *avail);
extern int allocate_resource(struct resource *root, struct resource *new,
resource_size_t size, resource_size_t min,
resource_size_t max, resource_size_t align,
resource_size_t (*alignf)(void *,
const struct resource *,
resource_size_t,
resource_size_t),
void *alignf_data);
struct resource *lookup_resource(struct resource *root, resource_size_t start);
int adjust_resource(struct resource *res, resource_size_t start,
resource_size_t size);
resource_size_t resource_alignment(struct resource *res);
static inline resource_size_t resource_size(const struct resource *res)
{
return res->end - res->start + 1;
}
static inline unsigned long resource_type(const struct resource *res)
{
return res->flags & IORESOURCE_TYPE_BITS;
}
static inline unsigned long resource_ext_type(const struct resource *res)
{
return res->flags & IORESOURCE_EXT_TYPE_BITS;
}
/* True iff r1 completely contains r2 */
static inline bool resource_contains(struct resource *r1, struct resource *r2)
{
if (resource_type(r1) != resource_type(r2))
return false;
if (r1->flags & IORESOURCE_UNSET || r2->flags & IORESOURCE_UNSET)
return false;
return r1->start <= r2->start && r1->end >= r2->end;
}
/* Convenience shorthand with allocation */
#define request_region(start,n,name) __request_region(&ioport_resource, (start), (n), (name), 0)
#define request_muxed_region(start,n,name) __request_region(&ioport_resource, (start), (n), (name), IORESOURCE_MUXED)
#define __request_mem_region(start,n,name, excl) __request_region(&iomem_resource, (start), (n), (name), excl)
#define request_mem_region(start,n,name) __request_region(&iomem_resource, (start), (n), (name), 0)
#define request_mem_region_exclusive(start,n,name) \
__request_region(&iomem_resource, (start), (n), (name), IORESOURCE_EXCLUSIVE)
#define rename_region(region, newname) do { (region)->name = (newname); } while (0)
extern struct resource * __request_region(struct resource *,
resource_size_t start,
resource_size_t n,
const char *name, int flags);
/* Compatibility cruft */
#define release_region(start,n) __release_region(&ioport_resource, (start), (n))
#define release_mem_region(start,n) __release_region(&iomem_resource, (start), (n))
extern void __release_region(struct resource *, resource_size_t,
resource_size_t);
#ifdef CONFIG_MEMORY_HOTREMOVE
extern int release_mem_region_adjustable(struct resource *, resource_size_t,
resource_size_t);
#endif
/* Wrappers for managed devices */
struct device;
extern int devm_request_resource(struct device *dev, struct resource *root,
struct resource *new);
extern void devm_release_resource(struct device *dev, struct resource *new);
#define devm_request_region(dev,start,n,name) \
__devm_request_region(dev, &ioport_resource, (start), (n), (name))
#define devm_request_mem_region(dev,start,n,name) \
__devm_request_region(dev, &iomem_resource, (start), (n), (name))
extern struct resource * __devm_request_region(struct device *dev,
struct resource *parent, resource_size_t start,
resource_size_t n, const char *name);
#define devm_release_region(dev, start, n) \
__devm_release_region(dev, &ioport_resource, (start), (n))
#define devm_release_mem_region(dev, start, n) \
__devm_release_region(dev, &iomem_resource, (start), (n))
extern void __devm_release_region(struct device *dev, struct resource *parent,
resource_size_t start, resource_size_t n);
extern int iomem_map_sanity_check(resource_size_t addr, unsigned long size);
extern bool iomem_is_exclusive(u64 addr);
extern int
walk_system_ram_range(unsigned long start_pfn, unsigned long nr_pages,
void *arg, int (*func)(unsigned long, unsigned long, void *));
extern int
walk_mem_res(u64 start, u64 end, void *arg,
int (*func)(struct resource *, void *));
extern int
walk_system_ram_res(u64 start, u64 end, void *arg,
int (*func)(struct resource *, void *));
extern int
walk_iomem_res_desc(unsigned long desc, unsigned long flags, u64 start, u64 end,
void *arg, int (*func)(struct resource *, void *));
/* True if any part of r1 overlaps r2 */
static inline bool resource_overlaps(struct resource *r1, struct resource *r2)
{
return (r1->start <= r2->end && r1->end >= r2->start);
}
struct resource *devm_request_free_mem_region(struct device *dev,
struct resource *base, unsigned long size);
struct resource *request_free_mem_region(struct resource *base,
unsigned long size, const char *name);
#ifdef CONFIG_IO_STRICT_DEVMEM
void revoke_devmem(struct resource *res);
#else
static inline void revoke_devmem(struct resource *res) { };
#endif
#endif /* __ASSEMBLY__ */
#endif /* _LINUX_IOPORT_H */
| CSE3320/kernel-code | linux-5.8/include/linux/ioport.h | C | gpl-2.0 | 11,581 |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) 2012 Russell King
*/
#include <linux/clk.h>
#include <linux/component.h>
#include <linux/module.h>
#include <linux/of_graph.h>
#include <linux/platform_device.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_drv.h>
#include <drm/drm_ioctl.h>
#include <drm/drm_managed.h>
#include <drm/drm_prime.h>
#include <drm/drm_probe_helper.h>
#include <drm/drm_fb_helper.h>
#include <drm/drm_of.h>
#include <drm/drm_vblank.h>
#include "armada_crtc.h"
#include "armada_drm.h"
#include "armada_gem.h"
#include "armada_fb.h"
#include "armada_hw.h"
#include <drm/armada_drm.h>
#include "armada_ioctlP.h"
static struct drm_ioctl_desc armada_ioctls[] = {
DRM_IOCTL_DEF_DRV(ARMADA_GEM_CREATE, armada_gem_create_ioctl,0),
DRM_IOCTL_DEF_DRV(ARMADA_GEM_MMAP, armada_gem_mmap_ioctl, 0),
DRM_IOCTL_DEF_DRV(ARMADA_GEM_PWRITE, armada_gem_pwrite_ioctl, 0),
};
DEFINE_DRM_GEM_FOPS(armada_drm_fops);
static struct drm_driver armada_drm_driver = {
.lastclose = drm_fb_helper_lastclose,
.gem_free_object_unlocked = armada_gem_free_object,
.prime_handle_to_fd = drm_gem_prime_handle_to_fd,
.prime_fd_to_handle = drm_gem_prime_fd_to_handle,
.gem_prime_export = armada_gem_prime_export,
.gem_prime_import = armada_gem_prime_import,
.dumb_create = armada_gem_dumb_create,
.gem_vm_ops = &armada_gem_vm_ops,
.major = 1,
.minor = 0,
.name = "armada-drm",
.desc = "Armada SoC DRM",
.date = "20120730",
.driver_features = DRIVER_GEM | DRIVER_MODESET | DRIVER_ATOMIC,
.ioctls = armada_ioctls,
.fops = &armada_drm_fops,
};
static const struct drm_mode_config_funcs armada_drm_mode_config_funcs = {
.fb_create = armada_fb_create,
.output_poll_changed = drm_fb_helper_output_poll_changed,
.atomic_check = drm_atomic_helper_check,
.atomic_commit = drm_atomic_helper_commit,
};
static int armada_drm_bind(struct device *dev)
{
struct armada_private *priv;
struct resource *mem = NULL;
int ret, n;
for (n = 0; ; n++) {
struct resource *r = platform_get_resource(to_platform_device(dev),
IORESOURCE_MEM, n);
if (!r)
break;
/* Resources above 64K are graphics memory */
if (resource_size(r) > SZ_64K)
mem = r;
else
return -EINVAL;
}
if (!mem)
return -ENXIO;
if (!devm_request_mem_region(dev, mem->start, resource_size(mem),
"armada-drm"))
return -EBUSY;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/*
* The drm_device structure must be at the start of
* armada_private for drm_dev_put() to work correctly.
*/
BUILD_BUG_ON(offsetof(struct armada_private, drm) != 0);
ret = drm_dev_init(&priv->drm, &armada_drm_driver, dev);
if (ret) {
dev_err(dev, "[" DRM_NAME ":%s] drm_dev_init failed: %d\n",
__func__, ret);
kfree(priv);
return ret;
}
drmm_add_final_kfree(&priv->drm, priv);
/* Remove early framebuffers */
ret = drm_fb_helper_remove_conflicting_framebuffers(NULL,
"armada-drm-fb",
false);
if (ret) {
dev_err(dev, "[" DRM_NAME ":%s] can't kick out simple-fb: %d\n",
__func__, ret);
kfree(priv);
return ret;
}
priv->drm.dev_private = priv;
dev_set_drvdata(dev, &priv->drm);
/* Mode setting support */
drm_mode_config_init(&priv->drm);
priv->drm.mode_config.min_width = 320;
priv->drm.mode_config.min_height = 200;
/*
* With vscale enabled, the maximum width is 1920 due to the
* 1920 by 3 lines RAM
*/
priv->drm.mode_config.max_width = 1920;
priv->drm.mode_config.max_height = 2048;
priv->drm.mode_config.preferred_depth = 24;
priv->drm.mode_config.funcs = &armada_drm_mode_config_funcs;
drm_mm_init(&priv->linear, mem->start, resource_size(mem));
mutex_init(&priv->linear_lock);
ret = component_bind_all(dev, &priv->drm);
if (ret)
goto err_kms;
ret = drm_vblank_init(&priv->drm, priv->drm.mode_config.num_crtc);
if (ret)
goto err_comp;
priv->drm.irq_enabled = true;
drm_mode_config_reset(&priv->drm);
ret = armada_fbdev_init(&priv->drm);
if (ret)
goto err_comp;
drm_kms_helper_poll_init(&priv->drm);
ret = drm_dev_register(&priv->drm, 0);
if (ret)
goto err_poll;
#ifdef CONFIG_DEBUG_FS
armada_drm_debugfs_init(priv->drm.primary);
#endif
return 0;
err_poll:
drm_kms_helper_poll_fini(&priv->drm);
armada_fbdev_fini(&priv->drm);
err_comp:
component_unbind_all(dev, &priv->drm);
err_kms:
drm_mode_config_cleanup(&priv->drm);
drm_mm_takedown(&priv->linear);
drm_dev_put(&priv->drm);
return ret;
}
static void armada_drm_unbind(struct device *dev)
{
struct drm_device *drm = dev_get_drvdata(dev);
struct armada_private *priv = drm->dev_private;
drm_kms_helper_poll_fini(&priv->drm);
armada_fbdev_fini(&priv->drm);
drm_dev_unregister(&priv->drm);
drm_atomic_helper_shutdown(&priv->drm);
component_unbind_all(dev, &priv->drm);
drm_mode_config_cleanup(&priv->drm);
drm_mm_takedown(&priv->linear);
drm_dev_put(&priv->drm);
}
static int compare_of(struct device *dev, void *data)
{
return dev->of_node == data;
}
static int compare_dev_name(struct device *dev, void *data)
{
const char *name = data;
return !strcmp(dev_name(dev), name);
}
static void armada_add_endpoints(struct device *dev,
struct component_match **match, struct device_node *dev_node)
{
struct device_node *ep, *remote;
for_each_endpoint_of_node(dev_node, ep) {
remote = of_graph_get_remote_port_parent(ep);
if (remote && of_device_is_available(remote))
drm_of_component_match_add(dev, match, compare_of,
remote);
of_node_put(remote);
}
}
static const struct component_master_ops armada_master_ops = {
.bind = armada_drm_bind,
.unbind = armada_drm_unbind,
};
static int armada_drm_probe(struct platform_device *pdev)
{
struct component_match *match = NULL;
struct device *dev = &pdev->dev;
int ret;
ret = drm_of_component_probe(dev, compare_dev_name, &armada_master_ops);
if (ret != -EINVAL)
return ret;
if (dev->platform_data) {
char **devices = dev->platform_data;
struct device *d;
int i;
for (i = 0; devices[i]; i++)
component_match_add(dev, &match, compare_dev_name,
devices[i]);
if (i == 0) {
dev_err(dev, "missing 'ports' property\n");
return -ENODEV;
}
for (i = 0; devices[i]; i++) {
d = bus_find_device_by_name(&platform_bus_type, NULL,
devices[i]);
if (d && d->of_node)
armada_add_endpoints(dev, &match, d->of_node);
put_device(d);
}
}
return component_master_add_with_match(&pdev->dev, &armada_master_ops,
match);
}
static int armada_drm_remove(struct platform_device *pdev)
{
component_master_del(&pdev->dev, &armada_master_ops);
return 0;
}
static const struct platform_device_id armada_drm_platform_ids[] = {
{
.name = "armada-drm",
}, {
.name = "armada-510-drm",
},
{ },
};
MODULE_DEVICE_TABLE(platform, armada_drm_platform_ids);
static struct platform_driver armada_drm_platform_driver = {
.probe = armada_drm_probe,
.remove = armada_drm_remove,
.driver = {
.name = "armada-drm",
},
.id_table = armada_drm_platform_ids,
};
static int __init armada_drm_init(void)
{
int ret;
armada_drm_driver.num_ioctls = ARRAY_SIZE(armada_ioctls);
ret = platform_driver_register(&armada_lcd_platform_driver);
if (ret)
return ret;
ret = platform_driver_register(&armada_drm_platform_driver);
if (ret)
platform_driver_unregister(&armada_lcd_platform_driver);
return ret;
}
module_init(armada_drm_init);
static void __exit armada_drm_exit(void)
{
platform_driver_unregister(&armada_drm_platform_driver);
platform_driver_unregister(&armada_lcd_platform_driver);
}
module_exit(armada_drm_exit);
MODULE_AUTHOR("Russell King <rmk+kernel@armlinux.org.uk>");
MODULE_DESCRIPTION("Armada DRM Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:armada-drm");
| CSE3320/kernel-code | linux-5.8/drivers/gpu/drm/armada/armada_drv.c | C | gpl-2.0 | 7,766 |
/* 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/. */
#![cfg(test)]
extern crate servo_config;
mod opts;
mod prefs;
| shinglyu/servo | tests/unit/servo_config/lib.rs | Rust | mpl-2.0 | 270 |
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 65px; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; }
| xplico/CapAnalysis | www/app/webroot/css/jquery-ui-timepicker-addon.css | CSS | gpl-2.0 | 349 |
<?php
/**
* @file
* Contains \Drupal\filter\FilterProcessResult.
*/
namespace Drupal\filter;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Template\Attribute;
/**
* Used to return values from a text filter plugin's processing method.
*
* The typical use case for a text filter plugin's processing method is to just
* apply some filtering to the given text, but for more advanced use cases,
* it may be necessary to also:
* - Declare asset libraries to be loaded.
* - Declare cache tags that the filtered text depends upon, so when either of
* those cache tags is invalidated, the filtered text should also be
* invalidated.
* - Declare cache context to vary by, e.g. 'language' to do language-specific
* filtering.
* - Declare a maximum age for the filtered text.
* - Apply uncacheable filtering, for example because it differs per user.
*
* In case a filter needs one or more of these advanced use cases, it can use
* the additional methods available.
*
* The typical use case:
* @code
* public function process($text, $langcode) {
* // Modify $text.
*
* return new FilterProcess($text);
* }
* @endcode
*
* The advanced use cases:
* @code
* public function process($text, $langcode) {
* // Modify $text.
*
* $result = new FilterProcess($text);
*
* // Associate assets to be attached.
* $result->setAttachments(array(
* 'library' => array(
* 'filter/caption',
* ),
* ));
*
* // Associate cache contexts to vary by.
* $result->setCacheContexts(['language']);
*
* // Associate cache tags to be invalidated by.
* $result->setCacheTags($node->getCacheTags());
*
* // Associate a maximum age.
* $result->setCacheMaxAge(300); // 5 minutes.
*
* return $result;
* }
* @endcode
*/
class FilterProcessResult extends BubbleableMetadata {
/**
* The processed text.
*
* @see \Drupal\filter\Plugin\FilterInterface::process()
*
* @var string
*/
protected $processedText;
/**
* Constructs a FilterProcessResult object.
*
* @param string $processed_text
* The text as processed by a text filter.
*/
public function __construct($processed_text) {
$this->processedText = $processed_text;
}
/**
* Gets the processed text.
*
* @return string
*/
public function getProcessedText() {
return $this->processedText;
}
/**
* Gets the processed text.
*
* @return string
*/
public function __toString() {
return $this->getProcessedText();
}
/**
* Sets the processed text.
*
* @param string $processed_text
* The text as processed by a text filter.
*
* @return $this
*/
public function setProcessedText($processed_text) {
$this->processedText = $processed_text;
return $this;
}
/**
* Creates a placeholder.
*
* This generates its own placeholder markup for one major reason: to not have
* FilterProcessResult depend on the Renderer service, because this is a value
* object. As a side-effect and added benefit, this makes it easier to
* distinguish placeholders for filtered text versus generic render system
* placeholders.
*
* @param string $callback
* The #lazy_builder callback that will replace the placeholder with its
* eventual markup.
* @param array $args
* The arguments for the #lazy_builder callback.
*
* @return string
* The placeholder markup.
*/
public function createPlaceholder($callback, array $args) {
// Generate placeholder markup.
// @see \Drupal\Core\Render\Renderer::createPlaceholder()
$attributes = new Attribute();
$attributes['callback'] = $callback;
$attributes['arguments'] = UrlHelper::buildQuery($args);
$attributes['token'] = hash('sha1', serialize([$callback, $args]));
$placeholder_markup = Html::normalize('<drupal-filter-placeholder' . $attributes . '></drupal-filter-placeholder>');
// Add the placeholder attachment.
$this->addAttachments([
'placeholders' => [
$placeholder_markup => [
'#lazy_builder' => [$callback, $args],
]
],
]);
// Return the placeholder markup, so that the filter wanting to use a
// placeholder can actually insert the placeholder markup where it needs the
// placeholder to be replaced.
return $placeholder_markup;
}
}
| komejo/d8demo-dev | web/core/modules/filter/src/FilterProcessResult.php | PHP | mit | 4,448 |
/*
* Linux-DVB Driver for DiBcom's DiB9000 and demodulator-family.
*
* Copyright (C) 2005-10 DiBcom (http://www.dibcom.fr/)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include "dvb_math.h"
#include "dvb_frontend.h"
#include "dib9000.h"
#include "dibx000_common.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "turn on debugging (default: 0)");
#define dprintk(fmt, arg...) do { \
if (debug) \
printk(KERN_DEBUG pr_fmt("%s: " fmt), \
__func__, ##arg); \
} while (0)
#define MAX_NUMBER_OF_FRONTENDS 6
struct i2c_device {
struct i2c_adapter *i2c_adap;
u8 i2c_addr;
u8 *i2c_read_buffer;
u8 *i2c_write_buffer;
};
struct dib9000_pid_ctrl {
#define DIB9000_PID_FILTER_CTRL 0
#define DIB9000_PID_FILTER 1
u8 cmd;
u8 id;
u16 pid;
u8 onoff;
};
struct dib9000_state {
struct i2c_device i2c;
struct dibx000_i2c_master i2c_master;
struct i2c_adapter tuner_adap;
struct i2c_adapter component_bus;
u16 revision;
u8 reg_offs;
enum frontend_tune_state tune_state;
u32 status;
struct dvb_frontend_parametersContext channel_status;
u8 fe_id;
#define DIB9000_GPIO_DEFAULT_DIRECTIONS 0xffff
u16 gpio_dir;
#define DIB9000_GPIO_DEFAULT_VALUES 0x0000
u16 gpio_val;
#define DIB9000_GPIO_DEFAULT_PWM_POS 0xffff
u16 gpio_pwm_pos;
union { /* common for all chips */
struct {
u8 mobile_mode:1;
} host;
struct {
struct dib9000_fe_memory_map {
u16 addr;
u16 size;
} fe_mm[18];
u8 memcmd;
struct mutex mbx_if_lock; /* to protect read/write operations */
struct mutex mbx_lock; /* to protect the whole mailbox handling */
struct mutex mem_lock; /* to protect the memory accesses */
struct mutex mem_mbx_lock; /* to protect the memory-based mailbox */
#define MBX_MAX_WORDS (256 - 200 - 2)
#define DIB9000_MSG_CACHE_SIZE 2
u16 message_cache[DIB9000_MSG_CACHE_SIZE][MBX_MAX_WORDS];
u8 fw_is_running;
} risc;
} platform;
union { /* common for all platforms */
struct {
struct dib9000_config cfg;
} d9;
} chip;
struct dvb_frontend *fe[MAX_NUMBER_OF_FRONTENDS];
u16 component_bus_speed;
/* for the I2C transfer */
struct i2c_msg msg[2];
u8 i2c_write_buffer[255];
u8 i2c_read_buffer[255];
struct mutex demod_lock;
u8 get_frontend_internal;
struct dib9000_pid_ctrl pid_ctrl[10];
s8 pid_ctrl_index; /* -1: empty list; -2: do not use the list */
};
static const u32 fe_info[44] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
enum dib9000_power_mode {
DIB9000_POWER_ALL = 0,
DIB9000_POWER_NO,
DIB9000_POWER_INTERF_ANALOG_AGC,
DIB9000_POWER_COR4_DINTLV_ICIRM_EQUAL_CFROD,
DIB9000_POWER_COR4_CRY_ESRAM_MOUT_NUD,
DIB9000_POWER_INTERFACE_ONLY,
};
enum dib9000_out_messages {
OUT_MSG_HBM_ACK,
OUT_MSG_HOST_BUF_FAIL,
OUT_MSG_REQ_VERSION,
OUT_MSG_BRIDGE_I2C_W,
OUT_MSG_BRIDGE_I2C_R,
OUT_MSG_BRIDGE_APB_W,
OUT_MSG_BRIDGE_APB_R,
OUT_MSG_SCAN_CHANNEL,
OUT_MSG_MONIT_DEMOD,
OUT_MSG_CONF_GPIO,
OUT_MSG_DEBUG_HELP,
OUT_MSG_SUBBAND_SEL,
OUT_MSG_ENABLE_TIME_SLICE,
OUT_MSG_FE_FW_DL,
OUT_MSG_FE_CHANNEL_SEARCH,
OUT_MSG_FE_CHANNEL_TUNE,
OUT_MSG_FE_SLEEP,
OUT_MSG_FE_SYNC,
OUT_MSG_CTL_MONIT,
OUT_MSG_CONF_SVC,
OUT_MSG_SET_HBM,
OUT_MSG_INIT_DEMOD,
OUT_MSG_ENABLE_DIVERSITY,
OUT_MSG_SET_OUTPUT_MODE,
OUT_MSG_SET_PRIORITARY_CHANNEL,
OUT_MSG_ACK_FRG,
OUT_MSG_INIT_PMU,
};
enum dib9000_in_messages {
IN_MSG_DATA,
IN_MSG_FRAME_INFO,
IN_MSG_CTL_MONIT,
IN_MSG_ACK_FREE_ITEM,
IN_MSG_DEBUG_BUF,
IN_MSG_MPE_MONITOR,
IN_MSG_RAWTS_MONITOR,
IN_MSG_END_BRIDGE_I2C_RW,
IN_MSG_END_BRIDGE_APB_RW,
IN_MSG_VERSION,
IN_MSG_END_OF_SCAN,
IN_MSG_MONIT_DEMOD,
IN_MSG_ERROR,
IN_MSG_FE_FW_DL_DONE,
IN_MSG_EVENT,
IN_MSG_ACK_CHANGE_SVC,
IN_MSG_HBM_PROF,
};
/* memory_access requests */
#define FE_MM_W_CHANNEL 0
#define FE_MM_W_FE_INFO 1
#define FE_MM_RW_SYNC 2
#define FE_SYNC_CHANNEL 1
#define FE_SYNC_W_GENERIC_MONIT 2
#define FE_SYNC_COMPONENT_ACCESS 3
#define FE_MM_R_CHANNEL_SEARCH_STATE 3
#define FE_MM_R_CHANNEL_UNION_CONTEXT 4
#define FE_MM_R_FE_INFO 5
#define FE_MM_R_FE_MONITOR 6
#define FE_MM_W_CHANNEL_HEAD 7
#define FE_MM_W_CHANNEL_UNION 8
#define FE_MM_W_CHANNEL_CONTEXT 9
#define FE_MM_R_CHANNEL_UNION 10
#define FE_MM_R_CHANNEL_CONTEXT 11
#define FE_MM_R_CHANNEL_TUNE_STATE 12
#define FE_MM_R_GENERIC_MONITORING_SIZE 13
#define FE_MM_W_GENERIC_MONITORING 14
#define FE_MM_R_GENERIC_MONITORING 15
#define FE_MM_W_COMPONENT_ACCESS 16
#define FE_MM_RW_COMPONENT_ACCESS_BUFFER 17
static int dib9000_risc_apb_access_read(struct dib9000_state *state, u32 address, u16 attribute, const u8 * tx, u32 txlen, u8 * b, u32 len);
static int dib9000_risc_apb_access_write(struct dib9000_state *state, u32 address, u16 attribute, const u8 * b, u32 len);
static u16 to_fw_output_mode(u16 mode)
{
switch (mode) {
case OUTMODE_HIGH_Z:
return 0;
case OUTMODE_MPEG2_PAR_GATED_CLK:
return 4;
case OUTMODE_MPEG2_PAR_CONT_CLK:
return 8;
case OUTMODE_MPEG2_SERIAL:
return 16;
case OUTMODE_DIVERSITY:
return 128;
case OUTMODE_MPEG2_FIFO:
return 2;
case OUTMODE_ANALOG_ADC:
return 1;
default:
return 0;
}
}
static int dib9000_read16_attr(struct dib9000_state *state, u16 reg, u8 *b, u32 len, u16 attribute)
{
u32 chunk_size = 126;
u32 l;
int ret;
if (state->platform.risc.fw_is_running && (reg < 1024))
return dib9000_risc_apb_access_read(state, reg, attribute, NULL, 0, b, len);
memset(state->msg, 0, 2 * sizeof(struct i2c_msg));
state->msg[0].addr = state->i2c.i2c_addr >> 1;
state->msg[0].flags = 0;
state->msg[0].buf = state->i2c_write_buffer;
state->msg[0].len = 2;
state->msg[1].addr = state->i2c.i2c_addr >> 1;
state->msg[1].flags = I2C_M_RD;
state->msg[1].buf = b;
state->msg[1].len = len;
state->i2c_write_buffer[0] = reg >> 8;
state->i2c_write_buffer[1] = reg & 0xff;
if (attribute & DATA_BUS_ACCESS_MODE_8BIT)
state->i2c_write_buffer[0] |= (1 << 5);
if (attribute & DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT)
state->i2c_write_buffer[0] |= (1 << 4);
do {
l = len < chunk_size ? len : chunk_size;
state->msg[1].len = l;
state->msg[1].buf = b;
ret = i2c_transfer(state->i2c.i2c_adap, state->msg, 2) != 2 ? -EREMOTEIO : 0;
if (ret != 0) {
dprintk("i2c read error on %d\n", reg);
return -EREMOTEIO;
}
b += l;
len -= l;
if (!(attribute & DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT))
reg += l / 2;
} while ((ret == 0) && len);
return 0;
}
static u16 dib9000_i2c_read16(struct i2c_device *i2c, u16 reg)
{
struct i2c_msg msg[2] = {
{.addr = i2c->i2c_addr >> 1, .flags = 0,
.buf = i2c->i2c_write_buffer, .len = 2},
{.addr = i2c->i2c_addr >> 1, .flags = I2C_M_RD,
.buf = i2c->i2c_read_buffer, .len = 2},
};
i2c->i2c_write_buffer[0] = reg >> 8;
i2c->i2c_write_buffer[1] = reg & 0xff;
if (i2c_transfer(i2c->i2c_adap, msg, 2) != 2) {
dprintk("read register %x error\n", reg);
return 0;
}
return (i2c->i2c_read_buffer[0] << 8) | i2c->i2c_read_buffer[1];
}
static inline u16 dib9000_read_word(struct dib9000_state *state, u16 reg)
{
if (dib9000_read16_attr(state, reg, state->i2c_read_buffer, 2, 0) != 0)
return 0;
return (state->i2c_read_buffer[0] << 8) | state->i2c_read_buffer[1];
}
static inline u16 dib9000_read_word_attr(struct dib9000_state *state, u16 reg, u16 attribute)
{
if (dib9000_read16_attr(state, reg, state->i2c_read_buffer, 2,
attribute) != 0)
return 0;
return (state->i2c_read_buffer[0] << 8) | state->i2c_read_buffer[1];
}
#define dib9000_read16_noinc_attr(state, reg, b, len, attribute) dib9000_read16_attr(state, reg, b, len, (attribute) | DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT)
static int dib9000_write16_attr(struct dib9000_state *state, u16 reg, const u8 *buf, u32 len, u16 attribute)
{
u32 chunk_size = 126;
u32 l;
int ret;
if (state->platform.risc.fw_is_running && (reg < 1024)) {
if (dib9000_risc_apb_access_write
(state, reg, DATA_BUS_ACCESS_MODE_16BIT | DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT | attribute, buf, len) != 0)
return -EINVAL;
return 0;
}
memset(&state->msg[0], 0, sizeof(struct i2c_msg));
state->msg[0].addr = state->i2c.i2c_addr >> 1;
state->msg[0].flags = 0;
state->msg[0].buf = state->i2c_write_buffer;
state->msg[0].len = len + 2;
state->i2c_write_buffer[0] = (reg >> 8) & 0xff;
state->i2c_write_buffer[1] = (reg) & 0xff;
if (attribute & DATA_BUS_ACCESS_MODE_8BIT)
state->i2c_write_buffer[0] |= (1 << 5);
if (attribute & DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT)
state->i2c_write_buffer[0] |= (1 << 4);
do {
l = len < chunk_size ? len : chunk_size;
state->msg[0].len = l + 2;
memcpy(&state->i2c_write_buffer[2], buf, l);
ret = i2c_transfer(state->i2c.i2c_adap, state->msg, 1) != 1 ? -EREMOTEIO : 0;
buf += l;
len -= l;
if (!(attribute & DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT))
reg += l / 2;
} while ((ret == 0) && len);
return ret;
}
static int dib9000_i2c_write16(struct i2c_device *i2c, u16 reg, u16 val)
{
struct i2c_msg msg = {
.addr = i2c->i2c_addr >> 1, .flags = 0,
.buf = i2c->i2c_write_buffer, .len = 4
};
i2c->i2c_write_buffer[0] = (reg >> 8) & 0xff;
i2c->i2c_write_buffer[1] = reg & 0xff;
i2c->i2c_write_buffer[2] = (val >> 8) & 0xff;
i2c->i2c_write_buffer[3] = val & 0xff;
return i2c_transfer(i2c->i2c_adap, &msg, 1) != 1 ? -EREMOTEIO : 0;
}
static inline int dib9000_write_word(struct dib9000_state *state, u16 reg, u16 val)
{
u8 b[2] = { val >> 8, val & 0xff };
return dib9000_write16_attr(state, reg, b, 2, 0);
}
static inline int dib9000_write_word_attr(struct dib9000_state *state, u16 reg, u16 val, u16 attribute)
{
u8 b[2] = { val >> 8, val & 0xff };
return dib9000_write16_attr(state, reg, b, 2, attribute);
}
#define dib9000_write(state, reg, buf, len) dib9000_write16_attr(state, reg, buf, len, 0)
#define dib9000_write16_noinc(state, reg, buf, len) dib9000_write16_attr(state, reg, buf, len, DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT)
#define dib9000_write16_noinc_attr(state, reg, buf, len, attribute) dib9000_write16_attr(state, reg, buf, len, DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT | (attribute))
#define dib9000_mbx_send(state, id, data, len) dib9000_mbx_send_attr(state, id, data, len, 0)
#define dib9000_mbx_get_message(state, id, msg, len) dib9000_mbx_get_message_attr(state, id, msg, len, 0)
#define MAC_IRQ (1 << 1)
#define IRQ_POL_MSK (1 << 4)
#define dib9000_risc_mem_read_chunks(state, b, len) dib9000_read16_attr(state, 1063, b, len, DATA_BUS_ACCESS_MODE_8BIT | DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT)
#define dib9000_risc_mem_write_chunks(state, buf, len) dib9000_write16_attr(state, 1063, buf, len, DATA_BUS_ACCESS_MODE_8BIT | DATA_BUS_ACCESS_MODE_NO_ADDRESS_INCREMENT)
static void dib9000_risc_mem_setup_cmd(struct dib9000_state *state, u32 addr, u32 len, u8 reading)
{
u8 b[14] = { 0 };
/* dprintk("%d memcmd: %d %d %d\n", state->fe_id, addr, addr+len, len); */
/* b[0] = 0 << 7; */
b[1] = 1;
/* b[2] = 0; */
/* b[3] = 0; */
b[4] = (u8) (addr >> 8);
b[5] = (u8) (addr & 0xff);
/* b[10] = 0; */
/* b[11] = 0; */
b[12] = (u8) (addr >> 8);
b[13] = (u8) (addr & 0xff);
addr += len;
/* b[6] = 0; */
/* b[7] = 0; */
b[8] = (u8) (addr >> 8);
b[9] = (u8) (addr & 0xff);
dib9000_write(state, 1056, b, 14);
if (reading)
dib9000_write_word(state, 1056, (1 << 15) | 1);
state->platform.risc.memcmd = -1; /* if it was called directly reset it - to force a future setup-call to set it */
}
static void dib9000_risc_mem_setup(struct dib9000_state *state, u8 cmd)
{
struct dib9000_fe_memory_map *m = &state->platform.risc.fe_mm[cmd & 0x7f];
/* decide whether we need to "refresh" the memory controller */
if (state->platform.risc.memcmd == cmd && /* same command */
!(cmd & 0x80 && m->size < 67)) /* and we do not want to read something with less than 67 bytes looping - working around a bug in the memory controller */
return;
dib9000_risc_mem_setup_cmd(state, m->addr, m->size, cmd & 0x80);
state->platform.risc.memcmd = cmd;
}
static int dib9000_risc_mem_read(struct dib9000_state *state, u8 cmd, u8 * b, u16 len)
{
if (!state->platform.risc.fw_is_running)
return -EIO;
if (mutex_lock_interruptible(&state->platform.risc.mem_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
dib9000_risc_mem_setup(state, cmd | 0x80);
dib9000_risc_mem_read_chunks(state, b, len);
mutex_unlock(&state->platform.risc.mem_lock);
return 0;
}
static int dib9000_risc_mem_write(struct dib9000_state *state, u8 cmd, const u8 * b)
{
struct dib9000_fe_memory_map *m = &state->platform.risc.fe_mm[cmd];
if (!state->platform.risc.fw_is_running)
return -EIO;
if (mutex_lock_interruptible(&state->platform.risc.mem_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
dib9000_risc_mem_setup(state, cmd);
dib9000_risc_mem_write_chunks(state, b, m->size);
mutex_unlock(&state->platform.risc.mem_lock);
return 0;
}
static int dib9000_firmware_download(struct dib9000_state *state, u8 risc_id, u16 key, const u8 * code, u32 len)
{
u16 offs;
if (risc_id == 1)
offs = 16;
else
offs = 0;
/* config crtl reg */
dib9000_write_word(state, 1024 + offs, 0x000f);
dib9000_write_word(state, 1025 + offs, 0);
dib9000_write_word(state, 1031 + offs, key);
dprintk("going to download %dB of microcode\n", len);
if (dib9000_write16_noinc(state, 1026 + offs, (u8 *) code, (u16) len) != 0) {
dprintk("error while downloading microcode for RISC %c\n", 'A' + risc_id);
return -EIO;
}
dprintk("Microcode for RISC %c loaded\n", 'A' + risc_id);
return 0;
}
static int dib9000_mbx_host_init(struct dib9000_state *state, u8 risc_id)
{
u16 mbox_offs;
u16 reset_reg;
u16 tries = 1000;
if (risc_id == 1)
mbox_offs = 16;
else
mbox_offs = 0;
/* Reset mailbox */
dib9000_write_word(state, 1027 + mbox_offs, 0x8000);
/* Read reset status */
do {
reset_reg = dib9000_read_word(state, 1027 + mbox_offs);
msleep(100);
} while ((reset_reg & 0x8000) && --tries);
if (reset_reg & 0x8000) {
dprintk("MBX: init ERROR, no response from RISC %c\n", 'A' + risc_id);
return -EIO;
}
dprintk("MBX: initialized\n");
return 0;
}
#define MAX_MAILBOX_TRY 100
static int dib9000_mbx_send_attr(struct dib9000_state *state, u8 id, u16 * data, u8 len, u16 attr)
{
u8 *d, b[2];
u16 tmp;
u16 size;
u32 i;
int ret = 0;
if (!state->platform.risc.fw_is_running)
return -EINVAL;
if (mutex_lock_interruptible(&state->platform.risc.mbx_if_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
tmp = MAX_MAILBOX_TRY;
do {
size = dib9000_read_word_attr(state, 1043, attr) & 0xff;
if ((size + len + 1) > MBX_MAX_WORDS && --tmp) {
dprintk("MBX: RISC mbx full, retrying\n");
msleep(100);
} else
break;
} while (1);
/*dprintk( "MBX: size: %d\n", size); */
if (tmp == 0) {
ret = -EINVAL;
goto out;
}
#ifdef DUMP_MSG
dprintk("--> %02x %d %*ph\n", id, len + 1, len, data);
#endif
/* byte-order conversion - works on big (where it is not necessary) or little endian */
d = (u8 *) data;
for (i = 0; i < len; i++) {
tmp = data[i];
*d++ = tmp >> 8;
*d++ = tmp & 0xff;
}
/* write msg */
b[0] = id;
b[1] = len + 1;
if (dib9000_write16_noinc_attr(state, 1045, b, 2, attr) != 0 || dib9000_write16_noinc_attr(state, 1045, (u8 *) data, len * 2, attr) != 0) {
ret = -EIO;
goto out;
}
/* update register nb_mes_in_RX */
ret = (u8) dib9000_write_word_attr(state, 1043, 1 << 14, attr);
out:
mutex_unlock(&state->platform.risc.mbx_if_lock);
return ret;
}
static u8 dib9000_mbx_read(struct dib9000_state *state, u16 * data, u8 risc_id, u16 attr)
{
#ifdef DUMP_MSG
u16 *d = data;
#endif
u16 tmp, i;
u8 size;
u8 mc_base;
if (!state->platform.risc.fw_is_running)
return 0;
if (mutex_lock_interruptible(&state->platform.risc.mbx_if_lock) < 0) {
dprintk("could not get the lock\n");
return 0;
}
if (risc_id == 1)
mc_base = 16;
else
mc_base = 0;
/* Length and type in the first word */
*data = dib9000_read_word_attr(state, 1029 + mc_base, attr);
size = *data & 0xff;
if (size <= MBX_MAX_WORDS) {
data++;
size--; /* Initial word already read */
dib9000_read16_noinc_attr(state, 1029 + mc_base, (u8 *) data, size * 2, attr);
/* to word conversion */
for (i = 0; i < size; i++) {
tmp = *data;
*data = (tmp >> 8) | (tmp << 8);
data++;
}
#ifdef DUMP_MSG
dprintk("<--\n");
for (i = 0; i < size + 1; i++)
dprintk("%04x\n", d[i]);
dprintk("\n");
#endif
} else {
dprintk("MBX: message is too big for message cache (%d), flushing message\n", size);
size--; /* Initial word already read */
while (size--)
dib9000_read16_noinc_attr(state, 1029 + mc_base, (u8 *) data, 2, attr);
}
/* Update register nb_mes_in_TX */
dib9000_write_word_attr(state, 1028 + mc_base, 1 << 14, attr);
mutex_unlock(&state->platform.risc.mbx_if_lock);
return size + 1;
}
static int dib9000_risc_debug_buf(struct dib9000_state *state, u16 * data, u8 size)
{
u32 ts = data[1] << 16 | data[0];
char *b = (char *)&data[2];
b[2 * (size - 2) - 1] = '\0'; /* Bullet proof the buffer */
if (*b == '~') {
b++;
dprintk("%s\n", b);
} else
dprintk("RISC%d: %d.%04d %s\n",
state->fe_id,
ts / 10000, ts % 10000, *b ? b : "<empty>");
return 1;
}
static int dib9000_mbx_fetch_to_cache(struct dib9000_state *state, u16 attr)
{
int i;
u8 size;
u16 *block;
/* find a free slot */
for (i = 0; i < DIB9000_MSG_CACHE_SIZE; i++) {
block = state->platform.risc.message_cache[i];
if (*block == 0) {
size = dib9000_mbx_read(state, block, 1, attr);
/* dprintk( "MBX: fetched %04x message to cache\n", *block); */
switch (*block >> 8) {
case IN_MSG_DEBUG_BUF:
dib9000_risc_debug_buf(state, block + 1, size); /* debug-messages are going to be printed right away */
*block = 0; /* free the block */
break;
#if 0
case IN_MSG_DATA: /* FE-TRACE */
dib9000_risc_data_process(state, block + 1, size);
*block = 0;
break;
#endif
default:
break;
}
return 1;
}
}
dprintk("MBX: no free cache-slot found for new message...\n");
return -1;
}
static u8 dib9000_mbx_count(struct dib9000_state *state, u8 risc_id, u16 attr)
{
if (risc_id == 0)
return (u8) (dib9000_read_word_attr(state, 1028, attr) >> 10) & 0x1f; /* 5 bit field */
else
return (u8) (dib9000_read_word_attr(state, 1044, attr) >> 8) & 0x7f; /* 7 bit field */
}
static int dib9000_mbx_process(struct dib9000_state *state, u16 attr)
{
int ret = 0;
if (!state->platform.risc.fw_is_running)
return -1;
if (mutex_lock_interruptible(&state->platform.risc.mbx_lock) < 0) {
dprintk("could not get the lock\n");
return -1;
}
if (dib9000_mbx_count(state, 1, attr)) /* 1=RiscB */
ret = dib9000_mbx_fetch_to_cache(state, attr);
dib9000_read_word_attr(state, 1229, attr); /* Clear the IRQ */
/* if (tmp) */
/* dprintk( "cleared IRQ: %x\n", tmp); */
mutex_unlock(&state->platform.risc.mbx_lock);
return ret;
}
static int dib9000_mbx_get_message_attr(struct dib9000_state *state, u16 id, u16 * msg, u8 * size, u16 attr)
{
u8 i;
u16 *block;
u16 timeout = 30;
*msg = 0;
do {
/* dib9000_mbx_get_from_cache(); */
for (i = 0; i < DIB9000_MSG_CACHE_SIZE; i++) {
block = state->platform.risc.message_cache[i];
if ((*block >> 8) == id) {
*size = (*block & 0xff) - 1;
memcpy(msg, block + 1, (*size) * 2);
*block = 0; /* free the block */
i = 0; /* signal that we found a message */
break;
}
}
if (i == 0)
break;
if (dib9000_mbx_process(state, attr) == -1) /* try to fetch one message - if any */
return -1;
} while (--timeout);
if (timeout == 0) {
dprintk("waiting for message %d timed out\n", id);
return -1;
}
return i == 0;
}
static int dib9000_risc_check_version(struct dib9000_state *state)
{
u8 r[4];
u8 size;
u16 fw_version = 0;
if (dib9000_mbx_send(state, OUT_MSG_REQ_VERSION, &fw_version, 1) != 0)
return -EIO;
if (dib9000_mbx_get_message(state, IN_MSG_VERSION, (u16 *) r, &size) < 0)
return -EIO;
fw_version = (r[0] << 8) | r[1];
dprintk("RISC: ver: %d.%02d (IC: %d)\n", fw_version >> 10, fw_version & 0x3ff, (r[2] << 8) | r[3]);
if ((fw_version >> 10) != 7)
return -EINVAL;
switch (fw_version & 0x3ff) {
case 11:
case 12:
case 14:
case 15:
case 16:
case 17:
break;
default:
dprintk("RISC: invalid firmware version");
return -EINVAL;
}
dprintk("RISC: valid firmware version");
return 0;
}
static int dib9000_fw_boot(struct dib9000_state *state, const u8 * codeA, u32 lenA, const u8 * codeB, u32 lenB)
{
/* Reconfig pool mac ram */
dib9000_write_word(state, 1225, 0x02); /* A: 8k C, 4 k D - B: 32k C 6 k D - IRAM 96k */
dib9000_write_word(state, 1226, 0x05);
/* Toggles IP crypto to Host APB interface. */
dib9000_write_word(state, 1542, 1);
/* Set jump and no jump in the dma box */
dib9000_write_word(state, 1074, 0);
dib9000_write_word(state, 1075, 0);
/* Set MAC as APB Master. */
dib9000_write_word(state, 1237, 0);
/* Reset the RISCs */
if (codeA != NULL)
dib9000_write_word(state, 1024, 2);
else
dib9000_write_word(state, 1024, 15);
if (codeB != NULL)
dib9000_write_word(state, 1040, 2);
if (codeA != NULL)
dib9000_firmware_download(state, 0, 0x1234, codeA, lenA);
if (codeB != NULL)
dib9000_firmware_download(state, 1, 0x1234, codeB, lenB);
/* Run the RISCs */
if (codeA != NULL)
dib9000_write_word(state, 1024, 0);
if (codeB != NULL)
dib9000_write_word(state, 1040, 0);
if (codeA != NULL)
if (dib9000_mbx_host_init(state, 0) != 0)
return -EIO;
if (codeB != NULL)
if (dib9000_mbx_host_init(state, 1) != 0)
return -EIO;
msleep(100);
state->platform.risc.fw_is_running = 1;
if (dib9000_risc_check_version(state) != 0)
return -EINVAL;
state->platform.risc.memcmd = 0xff;
return 0;
}
static u16 dib9000_identify(struct i2c_device *client)
{
u16 value;
value = dib9000_i2c_read16(client, 896);
if (value != 0x01b3) {
dprintk("wrong Vendor ID (0x%x)\n", value);
return 0;
}
value = dib9000_i2c_read16(client, 897);
if (value != 0x4000 && value != 0x4001 && value != 0x4002 && value != 0x4003 && value != 0x4004 && value != 0x4005) {
dprintk("wrong Device ID (0x%x)\n", value);
return 0;
}
/* protect this driver to be used with 7000PC */
if (value == 0x4000 && dib9000_i2c_read16(client, 769) == 0x4000) {
dprintk("this driver does not work with DiB7000PC\n");
return 0;
}
switch (value) {
case 0x4000:
dprintk("found DiB7000MA/PA/MB/PB\n");
break;
case 0x4001:
dprintk("found DiB7000HC\n");
break;
case 0x4002:
dprintk("found DiB7000MC\n");
break;
case 0x4003:
dprintk("found DiB9000A\n");
break;
case 0x4004:
dprintk("found DiB9000H\n");
break;
case 0x4005:
dprintk("found DiB9000M\n");
break;
}
return value;
}
static void dib9000_set_power_mode(struct dib9000_state *state, enum dib9000_power_mode mode)
{
/* by default everything is going to be powered off */
u16 reg_903 = 0x3fff, reg_904 = 0xffff, reg_905 = 0xffff, reg_906;
u8 offset;
if (state->revision == 0x4003 || state->revision == 0x4004 || state->revision == 0x4005)
offset = 1;
else
offset = 0;
reg_906 = dib9000_read_word(state, 906 + offset) | 0x3; /* keep settings for RISC */
/* now, depending on the requested mode, we power on */
switch (mode) {
/* power up everything in the demod */
case DIB9000_POWER_ALL:
reg_903 = 0x0000;
reg_904 = 0x0000;
reg_905 = 0x0000;
reg_906 = 0x0000;
break;
/* just leave power on the control-interfaces: GPIO and (I2C or SDIO or SRAM) */
case DIB9000_POWER_INTERFACE_ONLY: /* TODO power up either SDIO or I2C or SRAM */
reg_905 &= ~((1 << 7) | (1 << 6) | (1 << 5) | (1 << 2));
break;
case DIB9000_POWER_INTERF_ANALOG_AGC:
reg_903 &= ~((1 << 15) | (1 << 14) | (1 << 11) | (1 << 10));
reg_905 &= ~((1 << 7) | (1 << 6) | (1 << 5) | (1 << 4) | (1 << 2));
reg_906 &= ~((1 << 0));
break;
case DIB9000_POWER_COR4_DINTLV_ICIRM_EQUAL_CFROD:
reg_903 = 0x0000;
reg_904 = 0x801f;
reg_905 = 0x0000;
reg_906 &= ~((1 << 0));
break;
case DIB9000_POWER_COR4_CRY_ESRAM_MOUT_NUD:
reg_903 = 0x0000;
reg_904 = 0x8000;
reg_905 = 0x010b;
reg_906 &= ~((1 << 0));
break;
default:
case DIB9000_POWER_NO:
break;
}
/* always power down unused parts */
if (!state->platform.host.mobile_mode)
reg_904 |= (1 << 7) | (1 << 6) | (1 << 4) | (1 << 2) | (1 << 1);
/* P_sdio_select_clk = 0 on MC and after */
if (state->revision != 0x4000)
reg_906 <<= 1;
dib9000_write_word(state, 903 + offset, reg_903);
dib9000_write_word(state, 904 + offset, reg_904);
dib9000_write_word(state, 905 + offset, reg_905);
dib9000_write_word(state, 906 + offset, reg_906);
}
static int dib9000_fw_reset(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
dib9000_write_word(state, 1817, 0x0003);
dib9000_write_word(state, 1227, 1);
dib9000_write_word(state, 1227, 0);
switch ((state->revision = dib9000_identify(&state->i2c))) {
case 0x4003:
case 0x4004:
case 0x4005:
state->reg_offs = 1;
break;
default:
return -EINVAL;
}
/* reset the i2c-master to use the host interface */
dibx000_reset_i2c_master(&state->i2c_master);
dib9000_set_power_mode(state, DIB9000_POWER_ALL);
/* unforce divstr regardless whether i2c enumeration was done or not */
dib9000_write_word(state, 1794, dib9000_read_word(state, 1794) & ~(1 << 1));
dib9000_write_word(state, 1796, 0);
dib9000_write_word(state, 1805, 0x805);
/* restart all parts */
dib9000_write_word(state, 898, 0xffff);
dib9000_write_word(state, 899, 0xffff);
dib9000_write_word(state, 900, 0x0001);
dib9000_write_word(state, 901, 0xff19);
dib9000_write_word(state, 902, 0x003c);
dib9000_write_word(state, 898, 0);
dib9000_write_word(state, 899, 0);
dib9000_write_word(state, 900, 0);
dib9000_write_word(state, 901, 0);
dib9000_write_word(state, 902, 0);
dib9000_write_word(state, 911, state->chip.d9.cfg.if_drives);
dib9000_set_power_mode(state, DIB9000_POWER_INTERFACE_ONLY);
return 0;
}
static int dib9000_risc_apb_access_read(struct dib9000_state *state, u32 address, u16 attribute, const u8 * tx, u32 txlen, u8 * b, u32 len)
{
u16 mb[10];
u8 i, s;
if (address >= 1024 || !state->platform.risc.fw_is_running)
return -EINVAL;
/* dprintk( "APB access thru rd fw %d %x\n", address, attribute); */
mb[0] = (u16) address;
mb[1] = len / 2;
dib9000_mbx_send_attr(state, OUT_MSG_BRIDGE_APB_R, mb, 2, attribute);
switch (dib9000_mbx_get_message_attr(state, IN_MSG_END_BRIDGE_APB_RW, mb, &s, attribute)) {
case 1:
s--;
for (i = 0; i < s; i++) {
b[i * 2] = (mb[i + 1] >> 8) & 0xff;
b[i * 2 + 1] = (mb[i + 1]) & 0xff;
}
return 0;
default:
return -EIO;
}
return -EIO;
}
static int dib9000_risc_apb_access_write(struct dib9000_state *state, u32 address, u16 attribute, const u8 * b, u32 len)
{
u16 mb[10];
u8 s, i;
if (address >= 1024 || !state->platform.risc.fw_is_running)
return -EINVAL;
if (len > 18)
return -EINVAL;
/* dprintk( "APB access thru wr fw %d %x\n", address, attribute); */
mb[0] = (u16)address;
for (i = 0; i + 1 < len; i += 2)
mb[1 + i / 2] = b[i] << 8 | b[i + 1];
if (len & 1)
mb[1 + len / 2] = b[len - 1] << 8;
dib9000_mbx_send_attr(state, OUT_MSG_BRIDGE_APB_W, mb, (3 + len) / 2, attribute);
return dib9000_mbx_get_message_attr(state, IN_MSG_END_BRIDGE_APB_RW, mb, &s, attribute) == 1 ? 0 : -EINVAL;
}
static int dib9000_fw_memmbx_sync(struct dib9000_state *state, u8 i)
{
u8 index_loop = 10;
if (!state->platform.risc.fw_is_running)
return 0;
dib9000_risc_mem_write(state, FE_MM_RW_SYNC, &i);
do {
dib9000_risc_mem_read(state, FE_MM_RW_SYNC, state->i2c_read_buffer, 1);
} while (state->i2c_read_buffer[0] && index_loop--);
if (index_loop > 0)
return 0;
return -EIO;
}
static int dib9000_fw_init(struct dib9000_state *state)
{
struct dibGPIOFunction *f;
u16 b[40] = { 0 };
u8 i;
u8 size;
if (dib9000_fw_boot(state, NULL, 0, state->chip.d9.cfg.microcode_B_fe_buffer, state->chip.d9.cfg.microcode_B_fe_size) != 0)
return -EIO;
/* initialize the firmware */
for (i = 0; i < ARRAY_SIZE(state->chip.d9.cfg.gpio_function); i++) {
f = &state->chip.d9.cfg.gpio_function[i];
if (f->mask) {
switch (f->function) {
case BOARD_GPIO_FUNCTION_COMPONENT_ON:
b[0] = (u16) f->mask;
b[1] = (u16) f->direction;
b[2] = (u16) f->value;
break;
case BOARD_GPIO_FUNCTION_COMPONENT_OFF:
b[3] = (u16) f->mask;
b[4] = (u16) f->direction;
b[5] = (u16) f->value;
break;
}
}
}
if (dib9000_mbx_send(state, OUT_MSG_CONF_GPIO, b, 15) != 0)
return -EIO;
/* subband */
b[0] = state->chip.d9.cfg.subband.size; /* type == 0 -> GPIO - PWM not yet supported */
for (i = 0; i < state->chip.d9.cfg.subband.size; i++) {
b[1 + i * 4] = state->chip.d9.cfg.subband.subband[i].f_mhz;
b[2 + i * 4] = (u16) state->chip.d9.cfg.subband.subband[i].gpio.mask;
b[3 + i * 4] = (u16) state->chip.d9.cfg.subband.subband[i].gpio.direction;
b[4 + i * 4] = (u16) state->chip.d9.cfg.subband.subband[i].gpio.value;
}
b[1 + i * 4] = 0; /* fe_id */
if (dib9000_mbx_send(state, OUT_MSG_SUBBAND_SEL, b, 2 + 4 * i) != 0)
return -EIO;
/* 0 - id, 1 - no_of_frontends */
b[0] = (0 << 8) | 1;
/* 0 = i2c-address demod, 0 = tuner */
b[1] = (0 << 8) | (0);
b[2] = (u16) (((state->chip.d9.cfg.xtal_clock_khz * 1000) >> 16) & 0xffff);
b[3] = (u16) (((state->chip.d9.cfg.xtal_clock_khz * 1000)) & 0xffff);
b[4] = (u16) ((state->chip.d9.cfg.vcxo_timer >> 16) & 0xffff);
b[5] = (u16) ((state->chip.d9.cfg.vcxo_timer) & 0xffff);
b[6] = (u16) ((state->chip.d9.cfg.timing_frequency >> 16) & 0xffff);
b[7] = (u16) ((state->chip.d9.cfg.timing_frequency) & 0xffff);
b[29] = state->chip.d9.cfg.if_drives;
if (dib9000_mbx_send(state, OUT_MSG_INIT_DEMOD, b, ARRAY_SIZE(b)) != 0)
return -EIO;
if (dib9000_mbx_send(state, OUT_MSG_FE_FW_DL, NULL, 0) != 0)
return -EIO;
if (dib9000_mbx_get_message(state, IN_MSG_FE_FW_DL_DONE, b, &size) < 0)
return -EIO;
if (size > ARRAY_SIZE(b)) {
dprintk("error : firmware returned %dbytes needed but the used buffer has only %dbytes\n Firmware init ABORTED", size,
(int)ARRAY_SIZE(b));
return -EINVAL;
}
for (i = 0; i < size; i += 2) {
state->platform.risc.fe_mm[i / 2].addr = b[i + 0];
state->platform.risc.fe_mm[i / 2].size = b[i + 1];
}
return 0;
}
static void dib9000_fw_set_channel_head(struct dib9000_state *state)
{
u8 b[9];
u32 freq = state->fe[0]->dtv_property_cache.frequency / 1000;
if (state->fe_id % 2)
freq += 101;
b[0] = (u8) ((freq >> 0) & 0xff);
b[1] = (u8) ((freq >> 8) & 0xff);
b[2] = (u8) ((freq >> 16) & 0xff);
b[3] = (u8) ((freq >> 24) & 0xff);
b[4] = (u8) ((state->fe[0]->dtv_property_cache.bandwidth_hz / 1000 >> 0) & 0xff);
b[5] = (u8) ((state->fe[0]->dtv_property_cache.bandwidth_hz / 1000 >> 8) & 0xff);
b[6] = (u8) ((state->fe[0]->dtv_property_cache.bandwidth_hz / 1000 >> 16) & 0xff);
b[7] = (u8) ((state->fe[0]->dtv_property_cache.bandwidth_hz / 1000 >> 24) & 0xff);
b[8] = 0x80; /* do not wait for CELL ID when doing autosearch */
if (state->fe[0]->dtv_property_cache.delivery_system == SYS_DVBT)
b[8] |= 1;
dib9000_risc_mem_write(state, FE_MM_W_CHANNEL_HEAD, b);
}
static int dib9000_fw_get_channel(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
struct dibDVBTChannel {
s8 spectrum_inversion;
s8 nfft;
s8 guard;
s8 constellation;
s8 hrch;
s8 alpha;
s8 code_rate_hp;
s8 code_rate_lp;
s8 select_hp;
s8 intlv_native;
};
struct dibDVBTChannel *ch;
int ret = 0;
if (mutex_lock_interruptible(&state->platform.risc.mem_mbx_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
if (dib9000_fw_memmbx_sync(state, FE_SYNC_CHANNEL) < 0) {
ret = -EIO;
goto error;
}
dib9000_risc_mem_read(state, FE_MM_R_CHANNEL_UNION,
state->i2c_read_buffer, sizeof(struct dibDVBTChannel));
ch = (struct dibDVBTChannel *)state->i2c_read_buffer;
switch (ch->spectrum_inversion & 0x7) {
case 1:
state->fe[0]->dtv_property_cache.inversion = INVERSION_ON;
break;
case 0:
state->fe[0]->dtv_property_cache.inversion = INVERSION_OFF;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.inversion = INVERSION_AUTO;
break;
}
switch (ch->nfft) {
case 0:
state->fe[0]->dtv_property_cache.transmission_mode = TRANSMISSION_MODE_2K;
break;
case 2:
state->fe[0]->dtv_property_cache.transmission_mode = TRANSMISSION_MODE_4K;
break;
case 1:
state->fe[0]->dtv_property_cache.transmission_mode = TRANSMISSION_MODE_8K;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.transmission_mode = TRANSMISSION_MODE_AUTO;
break;
}
switch (ch->guard) {
case 0:
state->fe[0]->dtv_property_cache.guard_interval = GUARD_INTERVAL_1_32;
break;
case 1:
state->fe[0]->dtv_property_cache.guard_interval = GUARD_INTERVAL_1_16;
break;
case 2:
state->fe[0]->dtv_property_cache.guard_interval = GUARD_INTERVAL_1_8;
break;
case 3:
state->fe[0]->dtv_property_cache.guard_interval = GUARD_INTERVAL_1_4;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.guard_interval = GUARD_INTERVAL_AUTO;
break;
}
switch (ch->constellation) {
case 2:
state->fe[0]->dtv_property_cache.modulation = QAM_64;
break;
case 1:
state->fe[0]->dtv_property_cache.modulation = QAM_16;
break;
case 0:
state->fe[0]->dtv_property_cache.modulation = QPSK;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.modulation = QAM_AUTO;
break;
}
switch (ch->hrch) {
case 0:
state->fe[0]->dtv_property_cache.hierarchy = HIERARCHY_NONE;
break;
case 1:
state->fe[0]->dtv_property_cache.hierarchy = HIERARCHY_1;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.hierarchy = HIERARCHY_AUTO;
break;
}
switch (ch->code_rate_hp) {
case 1:
state->fe[0]->dtv_property_cache.code_rate_HP = FEC_1_2;
break;
case 2:
state->fe[0]->dtv_property_cache.code_rate_HP = FEC_2_3;
break;
case 3:
state->fe[0]->dtv_property_cache.code_rate_HP = FEC_3_4;
break;
case 5:
state->fe[0]->dtv_property_cache.code_rate_HP = FEC_5_6;
break;
case 7:
state->fe[0]->dtv_property_cache.code_rate_HP = FEC_7_8;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.code_rate_HP = FEC_AUTO;
break;
}
switch (ch->code_rate_lp) {
case 1:
state->fe[0]->dtv_property_cache.code_rate_LP = FEC_1_2;
break;
case 2:
state->fe[0]->dtv_property_cache.code_rate_LP = FEC_2_3;
break;
case 3:
state->fe[0]->dtv_property_cache.code_rate_LP = FEC_3_4;
break;
case 5:
state->fe[0]->dtv_property_cache.code_rate_LP = FEC_5_6;
break;
case 7:
state->fe[0]->dtv_property_cache.code_rate_LP = FEC_7_8;
break;
default:
case -1:
state->fe[0]->dtv_property_cache.code_rate_LP = FEC_AUTO;
break;
}
error:
mutex_unlock(&state->platform.risc.mem_mbx_lock);
return ret;
}
static int dib9000_fw_set_channel_union(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
struct dibDVBTChannel {
s8 spectrum_inversion;
s8 nfft;
s8 guard;
s8 constellation;
s8 hrch;
s8 alpha;
s8 code_rate_hp;
s8 code_rate_lp;
s8 select_hp;
s8 intlv_native;
};
struct dibDVBTChannel ch;
switch (state->fe[0]->dtv_property_cache.inversion) {
case INVERSION_ON:
ch.spectrum_inversion = 1;
break;
case INVERSION_OFF:
ch.spectrum_inversion = 0;
break;
default:
case INVERSION_AUTO:
ch.spectrum_inversion = -1;
break;
}
switch (state->fe[0]->dtv_property_cache.transmission_mode) {
case TRANSMISSION_MODE_2K:
ch.nfft = 0;
break;
case TRANSMISSION_MODE_4K:
ch.nfft = 2;
break;
case TRANSMISSION_MODE_8K:
ch.nfft = 1;
break;
default:
case TRANSMISSION_MODE_AUTO:
ch.nfft = 1;
break;
}
switch (state->fe[0]->dtv_property_cache.guard_interval) {
case GUARD_INTERVAL_1_32:
ch.guard = 0;
break;
case GUARD_INTERVAL_1_16:
ch.guard = 1;
break;
case GUARD_INTERVAL_1_8:
ch.guard = 2;
break;
case GUARD_INTERVAL_1_4:
ch.guard = 3;
break;
default:
case GUARD_INTERVAL_AUTO:
ch.guard = -1;
break;
}
switch (state->fe[0]->dtv_property_cache.modulation) {
case QAM_64:
ch.constellation = 2;
break;
case QAM_16:
ch.constellation = 1;
break;
case QPSK:
ch.constellation = 0;
break;
default:
case QAM_AUTO:
ch.constellation = -1;
break;
}
switch (state->fe[0]->dtv_property_cache.hierarchy) {
case HIERARCHY_NONE:
ch.hrch = 0;
break;
case HIERARCHY_1:
case HIERARCHY_2:
case HIERARCHY_4:
ch.hrch = 1;
break;
default:
case HIERARCHY_AUTO:
ch.hrch = -1;
break;
}
ch.alpha = 1;
switch (state->fe[0]->dtv_property_cache.code_rate_HP) {
case FEC_1_2:
ch.code_rate_hp = 1;
break;
case FEC_2_3:
ch.code_rate_hp = 2;
break;
case FEC_3_4:
ch.code_rate_hp = 3;
break;
case FEC_5_6:
ch.code_rate_hp = 5;
break;
case FEC_7_8:
ch.code_rate_hp = 7;
break;
default:
case FEC_AUTO:
ch.code_rate_hp = -1;
break;
}
switch (state->fe[0]->dtv_property_cache.code_rate_LP) {
case FEC_1_2:
ch.code_rate_lp = 1;
break;
case FEC_2_3:
ch.code_rate_lp = 2;
break;
case FEC_3_4:
ch.code_rate_lp = 3;
break;
case FEC_5_6:
ch.code_rate_lp = 5;
break;
case FEC_7_8:
ch.code_rate_lp = 7;
break;
default:
case FEC_AUTO:
ch.code_rate_lp = -1;
break;
}
ch.select_hp = 1;
ch.intlv_native = 1;
dib9000_risc_mem_write(state, FE_MM_W_CHANNEL_UNION, (u8 *) &ch);
return 0;
}
static int dib9000_fw_tune(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
int ret = 10, search = state->channel_status.status == CHANNEL_STATUS_PARAMETERS_UNKNOWN;
s8 i;
switch (state->tune_state) {
case CT_DEMOD_START:
dib9000_fw_set_channel_head(state);
/* write the channel context - a channel is initialized to 0, so it is OK */
dib9000_risc_mem_write(state, FE_MM_W_CHANNEL_CONTEXT, (u8 *) fe_info);
dib9000_risc_mem_write(state, FE_MM_W_FE_INFO, (u8 *) fe_info);
if (search)
dib9000_mbx_send(state, OUT_MSG_FE_CHANNEL_SEARCH, NULL, 0);
else {
dib9000_fw_set_channel_union(fe);
dib9000_mbx_send(state, OUT_MSG_FE_CHANNEL_TUNE, NULL, 0);
}
state->tune_state = CT_DEMOD_STEP_1;
break;
case CT_DEMOD_STEP_1:
if (search)
dib9000_risc_mem_read(state, FE_MM_R_CHANNEL_SEARCH_STATE, state->i2c_read_buffer, 1);
else
dib9000_risc_mem_read(state, FE_MM_R_CHANNEL_TUNE_STATE, state->i2c_read_buffer, 1);
i = (s8)state->i2c_read_buffer[0];
switch (i) { /* something happened */
case 0:
break;
case -2: /* tps locks are "slower" than MPEG locks -> even in autosearch data is OK here */
if (search)
state->status = FE_STATUS_DEMOD_SUCCESS;
else {
state->tune_state = CT_DEMOD_STOP;
state->status = FE_STATUS_LOCKED;
}
break;
default:
state->status = FE_STATUS_TUNE_FAILED;
state->tune_state = CT_DEMOD_STOP;
break;
}
break;
default:
ret = FE_CALLBACK_TIME_NEVER;
break;
}
return ret;
}
static int dib9000_fw_set_diversity_in(struct dvb_frontend *fe, int onoff)
{
struct dib9000_state *state = fe->demodulator_priv;
u16 mode = (u16) onoff;
return dib9000_mbx_send(state, OUT_MSG_ENABLE_DIVERSITY, &mode, 1);
}
static int dib9000_fw_set_output_mode(struct dvb_frontend *fe, int mode)
{
struct dib9000_state *state = fe->demodulator_priv;
u16 outreg, smo_mode;
dprintk("setting output mode for demod %p to %d\n", fe, mode);
switch (mode) {
case OUTMODE_MPEG2_PAR_GATED_CLK:
outreg = (1 << 10); /* 0x0400 */
break;
case OUTMODE_MPEG2_PAR_CONT_CLK:
outreg = (1 << 10) | (1 << 6); /* 0x0440 */
break;
case OUTMODE_MPEG2_SERIAL:
outreg = (1 << 10) | (2 << 6) | (0 << 1); /* 0x0482 */
break;
case OUTMODE_DIVERSITY:
outreg = (1 << 10) | (4 << 6); /* 0x0500 */
break;
case OUTMODE_MPEG2_FIFO:
outreg = (1 << 10) | (5 << 6);
break;
case OUTMODE_HIGH_Z:
outreg = 0;
break;
default:
dprintk("Unhandled output_mode passed to be set for demod %p\n", &state->fe[0]);
return -EINVAL;
}
dib9000_write_word(state, 1795, outreg);
switch (mode) {
case OUTMODE_MPEG2_PAR_GATED_CLK:
case OUTMODE_MPEG2_PAR_CONT_CLK:
case OUTMODE_MPEG2_SERIAL:
case OUTMODE_MPEG2_FIFO:
smo_mode = (dib9000_read_word(state, 295) & 0x0010) | (1 << 1);
if (state->chip.d9.cfg.output_mpeg2_in_188_bytes)
smo_mode |= (1 << 5);
dib9000_write_word(state, 295, smo_mode);
break;
}
outreg = to_fw_output_mode(mode);
return dib9000_mbx_send(state, OUT_MSG_SET_OUTPUT_MODE, &outreg, 1);
}
static int dib9000_tuner_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg msg[], int num)
{
struct dib9000_state *state = i2c_get_adapdata(i2c_adap);
u16 i, len, t, index_msg;
for (index_msg = 0; index_msg < num; index_msg++) {
if (msg[index_msg].flags & I2C_M_RD) { /* read */
len = msg[index_msg].len;
if (len > 16)
len = 16;
if (dib9000_read_word(state, 790) != 0)
dprintk("TunerITF: read busy\n");
dib9000_write_word(state, 784, (u16) (msg[index_msg].addr));
dib9000_write_word(state, 787, (len / 2) - 1);
dib9000_write_word(state, 786, 1); /* start read */
i = 1000;
while (dib9000_read_word(state, 790) != (len / 2) && i)
i--;
if (i == 0)
dprintk("TunerITF: read failed\n");
for (i = 0; i < len; i += 2) {
t = dib9000_read_word(state, 785);
msg[index_msg].buf[i] = (t >> 8) & 0xff;
msg[index_msg].buf[i + 1] = (t) & 0xff;
}
if (dib9000_read_word(state, 790) != 0)
dprintk("TunerITF: read more data than expected\n");
} else {
i = 1000;
while (dib9000_read_word(state, 789) && i)
i--;
if (i == 0)
dprintk("TunerITF: write busy\n");
len = msg[index_msg].len;
if (len > 16)
len = 16;
for (i = 0; i < len; i += 2)
dib9000_write_word(state, 785, (msg[index_msg].buf[i] << 8) | msg[index_msg].buf[i + 1]);
dib9000_write_word(state, 784, (u16) msg[index_msg].addr);
dib9000_write_word(state, 787, (len / 2) - 1);
dib9000_write_word(state, 786, 0); /* start write */
i = 1000;
while (dib9000_read_word(state, 791) > 0 && i)
i--;
if (i == 0)
dprintk("TunerITF: write failed\n");
}
}
return num;
}
int dib9000_fw_set_component_bus_speed(struct dvb_frontend *fe, u16 speed)
{
struct dib9000_state *state = fe->demodulator_priv;
state->component_bus_speed = speed;
return 0;
}
EXPORT_SYMBOL(dib9000_fw_set_component_bus_speed);
static int dib9000_fw_component_bus_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg msg[], int num)
{
struct dib9000_state *state = i2c_get_adapdata(i2c_adap);
u8 type = 0; /* I2C */
u8 port = DIBX000_I2C_INTERFACE_GPIO_3_4;
u16 scl = state->component_bus_speed; /* SCL frequency */
struct dib9000_fe_memory_map *m = &state->platform.risc.fe_mm[FE_MM_RW_COMPONENT_ACCESS_BUFFER];
u8 p[13] = { 0 };
p[0] = type;
p[1] = port;
p[2] = msg[0].addr << 1;
p[3] = (u8) scl & 0xff; /* scl */
p[4] = (u8) (scl >> 8);
p[7] = 0;
p[8] = 0;
p[9] = (u8) (msg[0].len);
p[10] = (u8) (msg[0].len >> 8);
if ((num > 1) && (msg[1].flags & I2C_M_RD)) {
p[11] = (u8) (msg[1].len);
p[12] = (u8) (msg[1].len >> 8);
} else {
p[11] = 0;
p[12] = 0;
}
if (mutex_lock_interruptible(&state->platform.risc.mem_mbx_lock) < 0) {
dprintk("could not get the lock\n");
return 0;
}
dib9000_risc_mem_write(state, FE_MM_W_COMPONENT_ACCESS, p);
{ /* write-part */
dib9000_risc_mem_setup_cmd(state, m->addr, msg[0].len, 0);
dib9000_risc_mem_write_chunks(state, msg[0].buf, msg[0].len);
}
/* do the transaction */
if (dib9000_fw_memmbx_sync(state, FE_SYNC_COMPONENT_ACCESS) < 0) {
mutex_unlock(&state->platform.risc.mem_mbx_lock);
return 0;
}
/* read back any possible result */
if ((num > 1) && (msg[1].flags & I2C_M_RD))
dib9000_risc_mem_read(state, FE_MM_RW_COMPONENT_ACCESS_BUFFER, msg[1].buf, msg[1].len);
mutex_unlock(&state->platform.risc.mem_mbx_lock);
return num;
}
static u32 dib9000_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static const struct i2c_algorithm dib9000_tuner_algo = {
.master_xfer = dib9000_tuner_xfer,
.functionality = dib9000_i2c_func,
};
static const struct i2c_algorithm dib9000_component_bus_algo = {
.master_xfer = dib9000_fw_component_bus_xfer,
.functionality = dib9000_i2c_func,
};
struct i2c_adapter *dib9000_get_tuner_interface(struct dvb_frontend *fe)
{
struct dib9000_state *st = fe->demodulator_priv;
return &st->tuner_adap;
}
EXPORT_SYMBOL(dib9000_get_tuner_interface);
struct i2c_adapter *dib9000_get_component_bus_interface(struct dvb_frontend *fe)
{
struct dib9000_state *st = fe->demodulator_priv;
return &st->component_bus;
}
EXPORT_SYMBOL(dib9000_get_component_bus_interface);
struct i2c_adapter *dib9000_get_i2c_master(struct dvb_frontend *fe, enum dibx000_i2c_interface intf, int gating)
{
struct dib9000_state *st = fe->demodulator_priv;
return dibx000_get_i2c_adapter(&st->i2c_master, intf, gating);
}
EXPORT_SYMBOL(dib9000_get_i2c_master);
int dib9000_set_i2c_adapter(struct dvb_frontend *fe, struct i2c_adapter *i2c)
{
struct dib9000_state *st = fe->demodulator_priv;
st->i2c.i2c_adap = i2c;
return 0;
}
EXPORT_SYMBOL(dib9000_set_i2c_adapter);
static int dib9000_cfg_gpio(struct dib9000_state *st, u8 num, u8 dir, u8 val)
{
st->gpio_dir = dib9000_read_word(st, 773);
st->gpio_dir &= ~(1 << num); /* reset the direction bit */
st->gpio_dir |= (dir & 0x1) << num; /* set the new direction */
dib9000_write_word(st, 773, st->gpio_dir);
st->gpio_val = dib9000_read_word(st, 774);
st->gpio_val &= ~(1 << num); /* reset the direction bit */
st->gpio_val |= (val & 0x01) << num; /* set the new value */
dib9000_write_word(st, 774, st->gpio_val);
dprintk("gpio dir: %04x: gpio val: %04x\n", st->gpio_dir, st->gpio_val);
return 0;
}
int dib9000_set_gpio(struct dvb_frontend *fe, u8 num, u8 dir, u8 val)
{
struct dib9000_state *state = fe->demodulator_priv;
return dib9000_cfg_gpio(state, num, dir, val);
}
EXPORT_SYMBOL(dib9000_set_gpio);
int dib9000_fw_pid_filter_ctrl(struct dvb_frontend *fe, u8 onoff)
{
struct dib9000_state *state = fe->demodulator_priv;
u16 val;
int ret;
if ((state->pid_ctrl_index != -2) && (state->pid_ctrl_index < 9)) {
/* postpone the pid filtering cmd */
dprintk("pid filter cmd postpone\n");
state->pid_ctrl_index++;
state->pid_ctrl[state->pid_ctrl_index].cmd = DIB9000_PID_FILTER_CTRL;
state->pid_ctrl[state->pid_ctrl_index].onoff = onoff;
return 0;
}
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
val = dib9000_read_word(state, 294 + 1) & 0xffef;
val |= (onoff & 0x1) << 4;
dprintk("PID filter enabled %d\n", onoff);
ret = dib9000_write_word(state, 294 + 1, val);
mutex_unlock(&state->demod_lock);
return ret;
}
EXPORT_SYMBOL(dib9000_fw_pid_filter_ctrl);
int dib9000_fw_pid_filter(struct dvb_frontend *fe, u8 id, u16 pid, u8 onoff)
{
struct dib9000_state *state = fe->demodulator_priv;
int ret;
if (state->pid_ctrl_index != -2) {
/* postpone the pid filtering cmd */
dprintk("pid filter postpone\n");
if (state->pid_ctrl_index < 9) {
state->pid_ctrl_index++;
state->pid_ctrl[state->pid_ctrl_index].cmd = DIB9000_PID_FILTER;
state->pid_ctrl[state->pid_ctrl_index].id = id;
state->pid_ctrl[state->pid_ctrl_index].pid = pid;
state->pid_ctrl[state->pid_ctrl_index].onoff = onoff;
} else
dprintk("can not add any more pid ctrl cmd\n");
return 0;
}
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
dprintk("Index %x, PID %d, OnOff %d\n", id, pid, onoff);
ret = dib9000_write_word(state, 300 + 1 + id,
onoff ? (1 << 13) | pid : 0);
mutex_unlock(&state->demod_lock);
return ret;
}
EXPORT_SYMBOL(dib9000_fw_pid_filter);
int dib9000_firmware_post_pll_init(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
return dib9000_fw_init(state);
}
EXPORT_SYMBOL(dib9000_firmware_post_pll_init);
static void dib9000_release(struct dvb_frontend *demod)
{
struct dib9000_state *st = demod->demodulator_priv;
u8 index_frontend;
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (st->fe[index_frontend] != NULL); index_frontend++)
dvb_frontend_detach(st->fe[index_frontend]);
dibx000_exit_i2c_master(&st->i2c_master);
i2c_del_adapter(&st->tuner_adap);
i2c_del_adapter(&st->component_bus);
kfree(st->fe[0]);
kfree(st);
}
static int dib9000_wakeup(struct dvb_frontend *fe)
{
return 0;
}
static int dib9000_sleep(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
u8 index_frontend;
int ret = 0;
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
ret = state->fe[index_frontend]->ops.sleep(state->fe[index_frontend]);
if (ret < 0)
goto error;
}
ret = dib9000_mbx_send(state, OUT_MSG_FE_SLEEP, NULL, 0);
error:
mutex_unlock(&state->demod_lock);
return ret;
}
static int dib9000_fe_get_tune_settings(struct dvb_frontend *fe, struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 1000;
return 0;
}
static int dib9000_get_frontend(struct dvb_frontend *fe,
struct dtv_frontend_properties *c)
{
struct dib9000_state *state = fe->demodulator_priv;
u8 index_frontend, sub_index_frontend;
enum fe_status stat;
int ret = 0;
if (state->get_frontend_internal == 0) {
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
}
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
state->fe[index_frontend]->ops.read_status(state->fe[index_frontend], &stat);
if (stat & FE_HAS_SYNC) {
dprintk("TPS lock on the slave%i\n", index_frontend);
/* synchronize the cache with the other frontends */
state->fe[index_frontend]->ops.get_frontend(state->fe[index_frontend], c);
for (sub_index_frontend = 0; (sub_index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[sub_index_frontend] != NULL);
sub_index_frontend++) {
if (sub_index_frontend != index_frontend) {
state->fe[sub_index_frontend]->dtv_property_cache.modulation =
state->fe[index_frontend]->dtv_property_cache.modulation;
state->fe[sub_index_frontend]->dtv_property_cache.inversion =
state->fe[index_frontend]->dtv_property_cache.inversion;
state->fe[sub_index_frontend]->dtv_property_cache.transmission_mode =
state->fe[index_frontend]->dtv_property_cache.transmission_mode;
state->fe[sub_index_frontend]->dtv_property_cache.guard_interval =
state->fe[index_frontend]->dtv_property_cache.guard_interval;
state->fe[sub_index_frontend]->dtv_property_cache.hierarchy =
state->fe[index_frontend]->dtv_property_cache.hierarchy;
state->fe[sub_index_frontend]->dtv_property_cache.code_rate_HP =
state->fe[index_frontend]->dtv_property_cache.code_rate_HP;
state->fe[sub_index_frontend]->dtv_property_cache.code_rate_LP =
state->fe[index_frontend]->dtv_property_cache.code_rate_LP;
state->fe[sub_index_frontend]->dtv_property_cache.rolloff =
state->fe[index_frontend]->dtv_property_cache.rolloff;
}
}
ret = 0;
goto return_value;
}
}
/* get the channel from master chip */
ret = dib9000_fw_get_channel(fe);
if (ret != 0)
goto return_value;
/* synchronize the cache with the other frontends */
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
state->fe[index_frontend]->dtv_property_cache.inversion = c->inversion;
state->fe[index_frontend]->dtv_property_cache.transmission_mode = c->transmission_mode;
state->fe[index_frontend]->dtv_property_cache.guard_interval = c->guard_interval;
state->fe[index_frontend]->dtv_property_cache.modulation = c->modulation;
state->fe[index_frontend]->dtv_property_cache.hierarchy = c->hierarchy;
state->fe[index_frontend]->dtv_property_cache.code_rate_HP = c->code_rate_HP;
state->fe[index_frontend]->dtv_property_cache.code_rate_LP = c->code_rate_LP;
state->fe[index_frontend]->dtv_property_cache.rolloff = c->rolloff;
}
ret = 0;
return_value:
if (state->get_frontend_internal == 0)
mutex_unlock(&state->demod_lock);
return ret;
}
static int dib9000_set_tune_state(struct dvb_frontend *fe, enum frontend_tune_state tune_state)
{
struct dib9000_state *state = fe->demodulator_priv;
state->tune_state = tune_state;
if (tune_state == CT_DEMOD_START)
state->status = FE_STATUS_TUNE_PENDING;
return 0;
}
static u32 dib9000_get_status(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
return state->status;
}
static int dib9000_set_channel_status(struct dvb_frontend *fe, struct dvb_frontend_parametersContext *channel_status)
{
struct dib9000_state *state = fe->demodulator_priv;
memcpy(&state->channel_status, channel_status, sizeof(struct dvb_frontend_parametersContext));
return 0;
}
static int dib9000_set_frontend(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
int sleep_time, sleep_time_slave;
u32 frontend_status;
u8 nbr_pending, exit_condition, index_frontend, index_frontend_success;
struct dvb_frontend_parametersContext channel_status;
/* check that the correct parameters are set */
if (state->fe[0]->dtv_property_cache.frequency == 0) {
dprintk("dib9000: must specify frequency\n");
return 0;
}
if (state->fe[0]->dtv_property_cache.bandwidth_hz == 0) {
dprintk("dib9000: must specify bandwidth\n");
return 0;
}
state->pid_ctrl_index = -1; /* postpone the pid filtering cmd */
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return 0;
}
fe->dtv_property_cache.delivery_system = SYS_DVBT;
/* set the master status */
if (state->fe[0]->dtv_property_cache.transmission_mode == TRANSMISSION_MODE_AUTO ||
state->fe[0]->dtv_property_cache.guard_interval == GUARD_INTERVAL_AUTO ||
state->fe[0]->dtv_property_cache.modulation == QAM_AUTO ||
state->fe[0]->dtv_property_cache.code_rate_HP == FEC_AUTO) {
/* no channel specified, autosearch the channel */
state->channel_status.status = CHANNEL_STATUS_PARAMETERS_UNKNOWN;
} else
state->channel_status.status = CHANNEL_STATUS_PARAMETERS_SET;
/* set mode and status for the different frontends */
for (index_frontend = 0; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
dib9000_fw_set_diversity_in(state->fe[index_frontend], 1);
/* synchronization of the cache */
memcpy(&state->fe[index_frontend]->dtv_property_cache, &fe->dtv_property_cache, sizeof(struct dtv_frontend_properties));
state->fe[index_frontend]->dtv_property_cache.delivery_system = SYS_DVBT;
dib9000_fw_set_output_mode(state->fe[index_frontend], OUTMODE_HIGH_Z);
dib9000_set_channel_status(state->fe[index_frontend], &state->channel_status);
dib9000_set_tune_state(state->fe[index_frontend], CT_DEMOD_START);
}
/* actual tune */
exit_condition = 0; /* 0: tune pending; 1: tune failed; 2:tune success */
index_frontend_success = 0;
do {
sleep_time = dib9000_fw_tune(state->fe[0]);
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
sleep_time_slave = dib9000_fw_tune(state->fe[index_frontend]);
if (sleep_time == FE_CALLBACK_TIME_NEVER)
sleep_time = sleep_time_slave;
else if ((sleep_time_slave != FE_CALLBACK_TIME_NEVER) && (sleep_time_slave > sleep_time))
sleep_time = sleep_time_slave;
}
if (sleep_time != FE_CALLBACK_TIME_NEVER)
msleep(sleep_time / 10);
else
break;
nbr_pending = 0;
exit_condition = 0;
index_frontend_success = 0;
for (index_frontend = 0; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
frontend_status = -dib9000_get_status(state->fe[index_frontend]);
if (frontend_status > -FE_STATUS_TUNE_PENDING) {
exit_condition = 2; /* tune success */
index_frontend_success = index_frontend;
break;
}
if (frontend_status == -FE_STATUS_TUNE_PENDING)
nbr_pending++; /* some frontends are still tuning */
}
if ((exit_condition != 2) && (nbr_pending == 0))
exit_condition = 1; /* if all tune are done and no success, exit: tune failed */
} while (exit_condition == 0);
/* check the tune result */
if (exit_condition == 1) { /* tune failed */
dprintk("tune failed\n");
mutex_unlock(&state->demod_lock);
/* tune failed; put all the pid filtering cmd to junk */
state->pid_ctrl_index = -1;
return 0;
}
dprintk("tune success on frontend%i\n", index_frontend_success);
/* synchronize all the channel cache */
state->get_frontend_internal = 1;
dib9000_get_frontend(state->fe[0], &state->fe[0]->dtv_property_cache);
state->get_frontend_internal = 0;
/* retune the other frontends with the found channel */
channel_status.status = CHANNEL_STATUS_PARAMETERS_SET;
for (index_frontend = 0; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
/* only retune the frontends which was not tuned success */
if (index_frontend != index_frontend_success) {
dib9000_set_channel_status(state->fe[index_frontend], &channel_status);
dib9000_set_tune_state(state->fe[index_frontend], CT_DEMOD_START);
}
}
do {
sleep_time = FE_CALLBACK_TIME_NEVER;
for (index_frontend = 0; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
if (index_frontend != index_frontend_success) {
sleep_time_slave = dib9000_fw_tune(state->fe[index_frontend]);
if (sleep_time == FE_CALLBACK_TIME_NEVER)
sleep_time = sleep_time_slave;
else if ((sleep_time_slave != FE_CALLBACK_TIME_NEVER) && (sleep_time_slave > sleep_time))
sleep_time = sleep_time_slave;
}
}
if (sleep_time != FE_CALLBACK_TIME_NEVER)
msleep(sleep_time / 10);
else
break;
nbr_pending = 0;
for (index_frontend = 0; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
if (index_frontend != index_frontend_success) {
frontend_status = -dib9000_get_status(state->fe[index_frontend]);
if ((index_frontend != index_frontend_success) && (frontend_status == -FE_STATUS_TUNE_PENDING))
nbr_pending++; /* some frontends are still tuning */
}
}
} while (nbr_pending != 0);
/* set the output mode */
dib9000_fw_set_output_mode(state->fe[0], state->chip.d9.cfg.output_mode);
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++)
dib9000_fw_set_output_mode(state->fe[index_frontend], OUTMODE_DIVERSITY);
/* turn off the diversity for the last frontend */
dib9000_fw_set_diversity_in(state->fe[index_frontend - 1], 0);
mutex_unlock(&state->demod_lock);
if (state->pid_ctrl_index >= 0) {
u8 index_pid_filter_cmd;
u8 pid_ctrl_index = state->pid_ctrl_index;
state->pid_ctrl_index = -2;
for (index_pid_filter_cmd = 0;
index_pid_filter_cmd <= pid_ctrl_index;
index_pid_filter_cmd++) {
if (state->pid_ctrl[index_pid_filter_cmd].cmd == DIB9000_PID_FILTER_CTRL)
dib9000_fw_pid_filter_ctrl(state->fe[0],
state->pid_ctrl[index_pid_filter_cmd].onoff);
else if (state->pid_ctrl[index_pid_filter_cmd].cmd == DIB9000_PID_FILTER)
dib9000_fw_pid_filter(state->fe[0],
state->pid_ctrl[index_pid_filter_cmd].id,
state->pid_ctrl[index_pid_filter_cmd].pid,
state->pid_ctrl[index_pid_filter_cmd].onoff);
}
}
/* do not postpone any more the pid filtering */
state->pid_ctrl_index = -2;
return 0;
}
static u16 dib9000_read_lock(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
return dib9000_read_word(state, 535);
}
static int dib9000_read_status(struct dvb_frontend *fe, enum fe_status *stat)
{
struct dib9000_state *state = fe->demodulator_priv;
u8 index_frontend;
u16 lock = 0, lock_slave = 0;
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++)
lock_slave |= dib9000_read_lock(state->fe[index_frontend]);
lock = dib9000_read_word(state, 535);
*stat = 0;
if ((lock & 0x8000) || (lock_slave & 0x8000))
*stat |= FE_HAS_SIGNAL;
if ((lock & 0x3000) || (lock_slave & 0x3000))
*stat |= FE_HAS_CARRIER;
if ((lock & 0x0100) || (lock_slave & 0x0100))
*stat |= FE_HAS_VITERBI;
if (((lock & 0x0038) == 0x38) || ((lock_slave & 0x0038) == 0x38))
*stat |= FE_HAS_SYNC;
if ((lock & 0x0008) || (lock_slave & 0x0008))
*stat |= FE_HAS_LOCK;
mutex_unlock(&state->demod_lock);
return 0;
}
static int dib9000_read_ber(struct dvb_frontend *fe, u32 * ber)
{
struct dib9000_state *state = fe->demodulator_priv;
u16 *c;
int ret = 0;
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
if (mutex_lock_interruptible(&state->platform.risc.mem_mbx_lock) < 0) {
dprintk("could not get the lock\n");
ret = -EINTR;
goto error;
}
if (dib9000_fw_memmbx_sync(state, FE_SYNC_CHANNEL) < 0) {
mutex_unlock(&state->platform.risc.mem_mbx_lock);
ret = -EIO;
goto error;
}
dib9000_risc_mem_read(state, FE_MM_R_FE_MONITOR,
state->i2c_read_buffer, 16 * 2);
mutex_unlock(&state->platform.risc.mem_mbx_lock);
c = (u16 *)state->i2c_read_buffer;
*ber = c[10] << 16 | c[11];
error:
mutex_unlock(&state->demod_lock);
return ret;
}
static int dib9000_read_signal_strength(struct dvb_frontend *fe, u16 * strength)
{
struct dib9000_state *state = fe->demodulator_priv;
u8 index_frontend;
u16 *c = (u16 *)state->i2c_read_buffer;
u16 val;
int ret = 0;
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
*strength = 0;
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++) {
state->fe[index_frontend]->ops.read_signal_strength(state->fe[index_frontend], &val);
if (val > 65535 - *strength)
*strength = 65535;
else
*strength += val;
}
if (mutex_lock_interruptible(&state->platform.risc.mem_mbx_lock) < 0) {
dprintk("could not get the lock\n");
ret = -EINTR;
goto error;
}
if (dib9000_fw_memmbx_sync(state, FE_SYNC_CHANNEL) < 0) {
mutex_unlock(&state->platform.risc.mem_mbx_lock);
ret = -EIO;
goto error;
}
dib9000_risc_mem_read(state, FE_MM_R_FE_MONITOR, (u8 *) c, 16 * 2);
mutex_unlock(&state->platform.risc.mem_mbx_lock);
val = 65535 - c[4];
if (val > 65535 - *strength)
*strength = 65535;
else
*strength += val;
error:
mutex_unlock(&state->demod_lock);
return ret;
}
static u32 dib9000_get_snr(struct dvb_frontend *fe)
{
struct dib9000_state *state = fe->demodulator_priv;
u16 *c = (u16 *)state->i2c_read_buffer;
u32 n, s, exp;
u16 val;
if (mutex_lock_interruptible(&state->platform.risc.mem_mbx_lock) < 0) {
dprintk("could not get the lock\n");
return 0;
}
if (dib9000_fw_memmbx_sync(state, FE_SYNC_CHANNEL) < 0) {
mutex_unlock(&state->platform.risc.mem_mbx_lock);
return 0;
}
dib9000_risc_mem_read(state, FE_MM_R_FE_MONITOR, (u8 *) c, 16 * 2);
mutex_unlock(&state->platform.risc.mem_mbx_lock);
val = c[7];
n = (val >> 4) & 0xff;
exp = ((val & 0xf) << 2);
val = c[8];
exp += ((val >> 14) & 0x3);
if ((exp & 0x20) != 0)
exp -= 0x40;
n <<= exp + 16;
s = (val >> 6) & 0xFF;
exp = (val & 0x3F);
if ((exp & 0x20) != 0)
exp -= 0x40;
s <<= exp + 16;
if (n > 0) {
u32 t = (s / n) << 16;
return t + ((s << 16) - n * t) / n;
}
return 0xffffffff;
}
static int dib9000_read_snr(struct dvb_frontend *fe, u16 * snr)
{
struct dib9000_state *state = fe->demodulator_priv;
u8 index_frontend;
u32 snr_master;
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
snr_master = dib9000_get_snr(fe);
for (index_frontend = 1; (index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL); index_frontend++)
snr_master += dib9000_get_snr(state->fe[index_frontend]);
if ((snr_master >> 16) != 0) {
snr_master = 10 * intlog10(snr_master >> 16);
*snr = snr_master / ((1 << 24) / 10);
} else
*snr = 0;
mutex_unlock(&state->demod_lock);
return 0;
}
static int dib9000_read_unc_blocks(struct dvb_frontend *fe, u32 * unc)
{
struct dib9000_state *state = fe->demodulator_priv;
u16 *c = (u16 *)state->i2c_read_buffer;
int ret = 0;
if (mutex_lock_interruptible(&state->demod_lock) < 0) {
dprintk("could not get the lock\n");
return -EINTR;
}
if (mutex_lock_interruptible(&state->platform.risc.mem_mbx_lock) < 0) {
dprintk("could not get the lock\n");
ret = -EINTR;
goto error;
}
if (dib9000_fw_memmbx_sync(state, FE_SYNC_CHANNEL) < 0) {
mutex_unlock(&state->platform.risc.mem_mbx_lock);
ret = -EIO;
goto error;
}
dib9000_risc_mem_read(state, FE_MM_R_FE_MONITOR, (u8 *) c, 16 * 2);
mutex_unlock(&state->platform.risc.mem_mbx_lock);
*unc = c[12];
error:
mutex_unlock(&state->demod_lock);
return ret;
}
int dib9000_i2c_enumeration(struct i2c_adapter *i2c, int no_of_demods, u8 default_addr, u8 first_addr)
{
int k = 0, ret = 0;
u8 new_addr = 0;
struct i2c_device client = {.i2c_adap = i2c };
client.i2c_write_buffer = kzalloc(4 * sizeof(u8), GFP_KERNEL);
if (!client.i2c_write_buffer) {
dprintk("%s: not enough memory\n", __func__);
return -ENOMEM;
}
client.i2c_read_buffer = kzalloc(4 * sizeof(u8), GFP_KERNEL);
if (!client.i2c_read_buffer) {
dprintk("%s: not enough memory\n", __func__);
ret = -ENOMEM;
goto error_memory;
}
client.i2c_addr = default_addr + 16;
dib9000_i2c_write16(&client, 1796, 0x0);
for (k = no_of_demods - 1; k >= 0; k--) {
/* designated i2c address */
new_addr = first_addr + (k << 1);
client.i2c_addr = default_addr;
dib9000_i2c_write16(&client, 1817, 3);
dib9000_i2c_write16(&client, 1796, 0);
dib9000_i2c_write16(&client, 1227, 1);
dib9000_i2c_write16(&client, 1227, 0);
client.i2c_addr = new_addr;
dib9000_i2c_write16(&client, 1817, 3);
dib9000_i2c_write16(&client, 1796, 0);
dib9000_i2c_write16(&client, 1227, 1);
dib9000_i2c_write16(&client, 1227, 0);
if (dib9000_identify(&client) == 0) {
client.i2c_addr = default_addr;
if (dib9000_identify(&client) == 0) {
dprintk("DiB9000 #%d: not identified\n", k);
ret = -EIO;
goto error;
}
}
dib9000_i2c_write16(&client, 1795, (1 << 10) | (4 << 6));
dib9000_i2c_write16(&client, 1794, (new_addr << 2) | 2);
dprintk("IC %d initialized (to i2c_address 0x%x)\n", k, new_addr);
}
for (k = 0; k < no_of_demods; k++) {
new_addr = first_addr | (k << 1);
client.i2c_addr = new_addr;
dib9000_i2c_write16(&client, 1794, (new_addr << 2));
dib9000_i2c_write16(&client, 1795, 0);
}
error:
kfree(client.i2c_read_buffer);
error_memory:
kfree(client.i2c_write_buffer);
return ret;
}
EXPORT_SYMBOL(dib9000_i2c_enumeration);
int dib9000_set_slave_frontend(struct dvb_frontend *fe, struct dvb_frontend *fe_slave)
{
struct dib9000_state *state = fe->demodulator_priv;
u8 index_frontend = 1;
while ((index_frontend < MAX_NUMBER_OF_FRONTENDS) && (state->fe[index_frontend] != NULL))
index_frontend++;
if (index_frontend < MAX_NUMBER_OF_FRONTENDS) {
dprintk("set slave fe %p to index %i\n", fe_slave, index_frontend);
state->fe[index_frontend] = fe_slave;
return 0;
}
dprintk("too many slave frontend\n");
return -ENOMEM;
}
EXPORT_SYMBOL(dib9000_set_slave_frontend);
struct dvb_frontend *dib9000_get_slave_frontend(struct dvb_frontend *fe, int slave_index)
{
struct dib9000_state *state = fe->demodulator_priv;
if (slave_index >= MAX_NUMBER_OF_FRONTENDS)
return NULL;
return state->fe[slave_index];
}
EXPORT_SYMBOL(dib9000_get_slave_frontend);
static const struct dvb_frontend_ops dib9000_ops;
struct dvb_frontend *dib9000_attach(struct i2c_adapter *i2c_adap, u8 i2c_addr, const struct dib9000_config *cfg)
{
struct dvb_frontend *fe;
struct dib9000_state *st;
st = kzalloc(sizeof(struct dib9000_state), GFP_KERNEL);
if (st == NULL)
return NULL;
fe = kzalloc(sizeof(struct dvb_frontend), GFP_KERNEL);
if (fe == NULL) {
kfree(st);
return NULL;
}
memcpy(&st->chip.d9.cfg, cfg, sizeof(struct dib9000_config));
st->i2c.i2c_adap = i2c_adap;
st->i2c.i2c_addr = i2c_addr;
st->i2c.i2c_write_buffer = st->i2c_write_buffer;
st->i2c.i2c_read_buffer = st->i2c_read_buffer;
st->gpio_dir = DIB9000_GPIO_DEFAULT_DIRECTIONS;
st->gpio_val = DIB9000_GPIO_DEFAULT_VALUES;
st->gpio_pwm_pos = DIB9000_GPIO_DEFAULT_PWM_POS;
mutex_init(&st->platform.risc.mbx_if_lock);
mutex_init(&st->platform.risc.mbx_lock);
mutex_init(&st->platform.risc.mem_lock);
mutex_init(&st->platform.risc.mem_mbx_lock);
mutex_init(&st->demod_lock);
st->get_frontend_internal = 0;
st->pid_ctrl_index = -2;
st->fe[0] = fe;
fe->demodulator_priv = st;
memcpy(&st->fe[0]->ops, &dib9000_ops, sizeof(struct dvb_frontend_ops));
/* Ensure the output mode remains at the previous default if it's
* not specifically set by the caller.
*/
if ((st->chip.d9.cfg.output_mode != OUTMODE_MPEG2_SERIAL) && (st->chip.d9.cfg.output_mode != OUTMODE_MPEG2_PAR_GATED_CLK))
st->chip.d9.cfg.output_mode = OUTMODE_MPEG2_FIFO;
if (dib9000_identify(&st->i2c) == 0)
goto error;
dibx000_init_i2c_master(&st->i2c_master, DIB7000MC, st->i2c.i2c_adap, st->i2c.i2c_addr);
st->tuner_adap.dev.parent = i2c_adap->dev.parent;
strncpy(st->tuner_adap.name, "DIB9000_FW TUNER ACCESS", sizeof(st->tuner_adap.name));
st->tuner_adap.algo = &dib9000_tuner_algo;
st->tuner_adap.algo_data = NULL;
i2c_set_adapdata(&st->tuner_adap, st);
if (i2c_add_adapter(&st->tuner_adap) < 0)
goto error;
st->component_bus.dev.parent = i2c_adap->dev.parent;
strncpy(st->component_bus.name, "DIB9000_FW COMPONENT BUS ACCESS", sizeof(st->component_bus.name));
st->component_bus.algo = &dib9000_component_bus_algo;
st->component_bus.algo_data = NULL;
st->component_bus_speed = 340;
i2c_set_adapdata(&st->component_bus, st);
if (i2c_add_adapter(&st->component_bus) < 0)
goto component_bus_add_error;
dib9000_fw_reset(fe);
return fe;
component_bus_add_error:
i2c_del_adapter(&st->tuner_adap);
error:
kfree(st);
return NULL;
}
EXPORT_SYMBOL(dib9000_attach);
static const struct dvb_frontend_ops dib9000_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "DiBcom 9000",
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 62500,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_RECOVER | FE_CAN_HIERARCHY_AUTO,
},
.release = dib9000_release,
.init = dib9000_wakeup,
.sleep = dib9000_sleep,
.set_frontend = dib9000_set_frontend,
.get_tune_settings = dib9000_fe_get_tune_settings,
.get_frontend = dib9000_get_frontend,
.read_status = dib9000_read_status,
.read_ber = dib9000_read_ber,
.read_signal_strength = dib9000_read_signal_strength,
.read_snr = dib9000_read_snr,
.read_ucblocks = dib9000_read_unc_blocks,
};
MODULE_AUTHOR("Patrick Boettcher <patrick.boettcher@posteo.de>");
MODULE_AUTHOR("Olivier Grenie <olivier.grenie@parrot.com>");
MODULE_DESCRIPTION("Driver for the DiBcom 9000 COFDM demodulator");
MODULE_LICENSE("GPL");
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.14/drivers/media/dvb-frontends/dib9000.c | C | gpl-2.0 | 72,259 |
/**
* React Starter Kit (http://www.reactstarterkit.com/)
*
* Copyright © 2014-2015 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import cp from 'child_process';
/**
* Launches Node.js/Express web server in a separate (forked) process.
*/
export default () => new Promise((resolve, reject) => {
console.log('serve');
const server = cp.fork(path.join(__dirname, '../build/server.js'), {
env: Object.assign({NODE_ENV: 'development'}, process.env)
});
server.once('message', message => {
if (message.match(/^online$/)) {
resolve();
}
});
server.once('error', err => reject(error));
process.on('exit', () => server.kill('SIGTERM'));
});
| SFDevLabs/react-starter-kit | tools/serve.js | JavaScript | mit | 825 |
<!DOCTYPE html>
<title>Reference for WebVTT rendering, one line cue and cue that wraps - both should be fully visible</title>
<style>
html { overflow:hidden }
body { margin:0 }
.video {
display: inline-block;
width: 320px;
height: 180px;
position: relative;
font-size: 9px;
}
.cue {
position: absolute;
bottom: 0;
left: 15%;
right: 0;
width: 70%;
text-align: center
}
.cue > span {
font-family: Ahem, sans-serif;
background: rgba(0,0,0,0.8);
color: green;
}
</style>
<div class="video"><span class="cue"><span>This is a test subtitle<br>This test subtitle wraps and should be visible</span></span></div>
| totallybradical/temp_servo2 | tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/one_line_cue_plus_wrapped_cue-ref.html | HTML | mpl-2.0 | 660 |
// Copyright 2004-2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
// TODO(omaha): this code should be updated according to code published by
// Microsoft at http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx.
// We need a more rigorous clasification of versions.
#ifndef OMAHA_BASE_SYSTEM_INFO_H_
#define OMAHA_BASE_SYSTEM_INFO_H_
#include <windows.h>
#include <tchar.h>
namespace omaha {
// TODO(omaha): refactor to use a namespace.
class SystemInfo {
public:
// Find out if the OS is at least Windows 2000
// Service pack 4. If OS version is less than that
// will return false, all other cases true.
static bool OSWin2KSP4OrLater() {
// Use GetVersionEx to get OS and Service Pack information.
OSVERSIONINFOEX osviex;
::ZeroMemory(&osviex, sizeof(osviex));
osviex.dwOSVersionInfoSize = sizeof(osviex);
BOOL success = ::GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&osviex));
// If this failed we're on Win9X or a pre NT4SP6 OS.
if (!success) {
return false;
}
if (osviex.dwMajorVersion < 5) {
return false;
}
if (osviex.dwMajorVersion > 5) {
return true; // way beyond Windows XP.
}
if (osviex.dwMinorVersion >= 1) {
return true; // Windows XP or better.
}
if (osviex.wServicePackMajor >= 4) {
return true; // Windows 2000 SP4.
}
return false; // Windows 2000, < SP4.
}
// Returns true if the OS is at least XP SP2.
static bool OSWinXPSP2OrLater();
// CategorizeOS returns a categorization of what operating system is running,
// and the service pack level.
// NOTE: Please keep this in the order of increasing OS versions
enum OSVersionType {
OS_WINDOWS_UNKNOWN = 1,
OS_WINDOWS_9X_OR_NT,
OS_WINDOWS_2000,
OS_WINDOWS_XP,
OS_WINDOWS_SERVER_2003,
OS_WINDOWS_VISTA,
OS_WINDOWS_7
};
static HRESULT CategorizeOS(OSVersionType* os_version, DWORD* service_pack);
static const wchar_t* OSVersionTypeAsString(OSVersionType t);
// Returns true if the current operating system is Windows 2000.
static bool IsRunningOnW2K();
// Are we running on Windows XP or later.
static bool IsRunningOnXPOrLater();
// Are we running on Windows XP SP1 or later.
static bool IsRunningOnXPSP1OrLater();
// Are we running on Windows Vista or later.
static bool IsRunningOnVistaOrLater();
static bool IsRunningOnVistaRTM();
// Returns the version and the name of the operating system.
static bool GetSystemVersion(int* major_version,
int* minor_version,
int* service_pack_major,
int* service_pack_minor,
TCHAR* name_buf,
size_t name_buf_len);
// Returns the processor architecture. We use wProcessorArchitecture in
// SYSTEM_INFO returned by ::GetNativeSystemInfo() to detect the processor
// architecture of the installed operating system. Note the "Native" in the
// function name - this is important. See
// http://msdn.microsoft.com/en-us/library/ms724340.aspx.
static DWORD GetProcessorArchitecture();
// Returns whether this is a 64-bit Windows system.
static bool Is64BitWindows();
};
} // namespace omaha
#endif // OMAHA_BASE_SYSTEM_INFO_H_
| priaonehaha/omaha | base/system_info.h | C | apache-2.0 | 3,921 |
// Copyright 2014 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.
// #11612
// We weren't updating the auto adjustments with all the resolved
// type information after type check.
// pretty-expanded FIXME #23616
trait A { fn dummy(&self) { } }
struct B<'a, T:'a> {
f: &'a T
}
impl<'a, T> A for B<'a, T> {}
fn foo(_: &A) {}
fn bar<G>(b: &B<G>) {
foo(b); // Coercion should work
foo(b as &A); // Explicit cast should work as well
}
fn main() {}
| seanrivera/rust | src/test/run-pass/issue-11612.rs | Rust | apache-2.0 | 869 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.maps.android;
import static java.lang.Math.*;
/**
* Utility functions that are used my both PolyUtil and SphericalUtil.
*/
class MathUtil {
/**
* The earth's radius, in meters.
* Mean radius as defined by IUGG.
*/
static final double EARTH_RADIUS = 6371009;
/**
* Restrict x to the range [low, high].
*/
static double clamp(double x, double low, double high) {
return x < low ? low : (x > high ? high : x);
}
/**
* Wraps the given value into the inclusive-exclusive interval between min and max.
* @param n The value to wrap.
* @param min The minimum.
* @param max The maximum.
*/
static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
}
/**
* Returns the non-negative remainder of x / m.
* @param x The operand.
* @param m The modulus.
*/
static double mod(double x, double m) {
return ((x % m) + m) % m;
}
/**
* Returns mercator Y corresponding to latitude.
* See http://en.wikipedia.org/wiki/Mercator_projection .
*/
static double mercator(double lat) {
return log(tan(lat * 0.5 + PI/4));
}
/**
* Returns latitude from mercator Y.
*/
static double inverseMercator(double y) {
return 2 * atan(exp(y)) - PI / 2;
}
/**
* Returns haversine(angle-in-radians).
* hav(x) == (1 - cos(x)) / 2 == sin(x / 2)^2.
*/
static double hav(double x) {
double sinHalf = sin(x * 0.5);
return sinHalf * sinHalf;
}
/**
* Computes inverse haversine. Has good numerical stability around 0.
* arcHav(x) == acos(1 - 2 * x) == 2 * asin(sqrt(x)).
* The argument must be in [0, 1], and the result is positive.
*/
static double arcHav(double x) {
return 2 * asin(sqrt(x));
}
// Given h==hav(x), returns sin(abs(x)).
static double sinFromHav(double h) {
return 2 * sqrt(h * (1 - h));
}
// Returns hav(asin(x)).
static double havFromSin(double x) {
double x2 = x * x;
return x2 / (1 + sqrt(1 - x2)) * .5;
}
// Returns sin(arcHav(x) + arcHav(y)).
static double sinSumFromHav(double x, double y) {
double a = sqrt(x * (1 - x));
double b = sqrt(y * (1 - y));
return 2 * (a + b - 2 * (a * y + b * x));
}
/**
* Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere.
*/
static double havDistance(double lat1, double lat2, double dLng) {
return hav(lat1 - lat2) + hav(dLng) * cos(lat1) * cos(lat2);
}
}
| davidmrtz/TrackingApp | myMapa/library/src/com/google/maps/android/MathUtil.java | Java | apache-2.0 | 3,305 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.maxcube.internal.exceptions;
/**
* Will be thrown when there is an attempt to put a new message line into the message processor,
* but the processor is currently processing an other message type.
*
* @author Christian Rockrohr <christian@rockrohr.de>
*/
public class IncorrectMultilineIndexException extends Exception {
private static final long serialVersionUID = -2261755876987011907L;
}
| cyclingengineer/UpnpHomeAutomationBridge | src/org/openhab/binding/maxcube/internal/exceptions/IncorrectMultilineIndexException.java | Java | epl-1.0 | 737 |
/*
FUNCTION
<<strcasestr>>---case-insensitive character string search
INDEX
strcasestr
ANSI_SYNOPSIS
#include <string.h>
char *strcasestr(const char *<[s]>, const char *<[find]>);
TRAD_SYNOPSIS
#include <string.h>
int strcasecmp(<[s]>, <[find]>)
char *<[s]>;
char *<[find]>;
DESCRIPTION
<<strcasestr>> searchs the string <[s]> for
the first occurrence of the sequence <[find]>. <<strcasestr>>
is identical to <<strstr>> except the search is
case-insensitive.
RETURNS
A pointer to the first case-insensitive occurrence of the sequence
<[find]> or <<NULL>> if no match was found.
PORTABILITY
<<strcasestr>> is in the Berkeley Software Distribution.
<<strcasestr>> requires no supporting OS subroutines. It uses
tolower() from elsewhere in this library.
QUICKREF
strcasestr
*/
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* The quadratic code is derived from software contributed to Berkeley by
* Chris Torek.
*
* 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.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
/* Linear algorithm Copyright (C) 2008 Eric Blake
* Permission to use, copy, modify, and distribute the linear portion of
* software is freely granted, provided that this notice is preserved.
*/
#include <sys/cdefs.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
# define RETURN_TYPE char *
# define AVAILABLE(h, h_l, j, n_l) \
(!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \
&& ((h_l) = (j) + (n_l)))
# define CANON_ELEMENT(c) tolower (c)
#if __GNUC_PREREQ (4, 2)
/* strncasecmp uses signed char, CMP_FUNC is expected to use unsigned char. */
#pragma GCC diagnostic ignored "-Wpointer-sign"
#endif
# define CMP_FUNC strncasecmp
# include "str-two-way.h"
#endif
/*
* Find the first occurrence of find in s, ignore case.
*/
char *
_DEFUN (strcasestr, (s, find),
_CONST char *s _AND
_CONST char *find)
{
#if defined(PREFER_SIZE_OVER_SPEED) || defined(__OPTIMIZE_SIZE__)
/* Less code size, but quadratic performance in the worst case. */
char c, sc;
size_t len;
if ((c = *find++) != 0) {
c = tolower((unsigned char)c);
len = strlen(find);
do {
do {
if ((sc = *s++) == 0)
return (NULL);
} while ((char)tolower((unsigned char)sc) != c);
} while (strncasecmp(s, find, len) != 0);
s--;
}
return ((char *)s);
#else /* compilation for speed */
/* Larger code size, but guaranteed linear performance. */
const char *haystack = s;
const char *needle = find;
size_t needle_len; /* Length of NEEDLE. */
size_t haystack_len; /* Known minimum length of HAYSTACK. */
int ok = 1; /* True if NEEDLE is prefix of HAYSTACK. */
/* Determine length of NEEDLE, and in the process, make sure
HAYSTACK is at least as long (no point processing all of a long
NEEDLE if HAYSTACK is too short). */
while (*haystack && *needle)
ok &= (tolower ((unsigned char) *haystack++)
== tolower ((unsigned char) *needle++));
if (*needle)
return NULL;
if (ok)
return (char *) s;
needle_len = needle - find;
haystack = s + 1;
haystack_len = needle_len - 1;
/* Perform the search. */
if (needle_len < LONG_NEEDLE_THRESHOLD)
return two_way_short_needle ((const unsigned char *) haystack,
haystack_len,
(const unsigned char *) find, needle_len);
return two_way_long_needle ((const unsigned char *) haystack, haystack_len,
(const unsigned char *) find, needle_len);
#endif /* compilation for speed */
}
| GarethNelson/Zoidberg | userland/newlib/newlib/libc/string/strcasestr.c | C | gpl-2.0 | 4,975 |
// Copyright John Maddock 2007.
// Copyright Paul A. Bristow 2010.
// Use, modification and distribution are subject to 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)
// Note that this file contains quickbook mark-up as well as code
// and comments, don't change any of the special comment mark-ups!
//[policy_ref_snip7
#include <boost/math/distributions/negative_binomial.hpp>
using boost::math::negative_binomial_distribution;
using namespace boost::math::policies;
typedef negative_binomial_distribution<
double,
policy<discrete_quantile<integer_round_inwards> >
> dist_type;
// Lower quantile rounded up:
double x = quantile(dist_type(20, 0.3), 0.05); // 28 rounded up from 27.3898
// Upper quantile rounded down:
double y = quantile(complement(dist_type(20, 0.3), 0.05)); // 68 rounded down from 68.1584
//] //[/policy_ref_snip7]
#include <iostream>
using std::cout; using std::endl;
int main()
{
cout << "using policy<discrete_quantile<integer_round_inwards> > " << endl
<< "quantile(dist_type(20, 0.3), 0.05) = " << x << endl
<< "quantile(complement(dist_type(20, 0.3), 0.05)) = " << y << endl;
}
/*
Output:
using policy<discrete_quantile<integer_round_inwards> >
quantile(dist_type(20, 0.3), 0.05) = 28
quantile(complement(dist_type(20, 0.3), 0.05)) = 68
*/
| NixaSoftware/CVis | venv/bin/libs/math/example/policy_ref_snip7.cpp | C++ | apache-2.0 | 1,412 |
/******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek 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
*
*
******************************************************************************/
#ifndef __RTL8188E_RECV_H__
#define __RTL8188E_RECV_H__
#include <rtl8192c_recv.h>
#define TX_RPT1_PKT_LEN 8
typedef struct rxreport_8188e
{
//Offset 0
u32 pktlen:14;
u32 crc32:1;
u32 icverr:1;
u32 drvinfosize:4;
u32 security:3;
u32 qos:1;
u32 shift:2;
u32 physt:1;
u32 swdec:1;
u32 ls:1;
u32 fs:1;
u32 eor:1;
u32 own:1;
//Offset 4
u32 macid:5;
u32 tid:4;
u32 hwrsvd:4;
u32 amsdu:1;
u32 paggr:1;
u32 faggr:1;
u32 a1fit:4;
u32 a2fit:4;
u32 pam:1;
u32 pwr:1;
u32 md:1;
u32 mf:1;
u32 type:2;
u32 mc:1;
u32 bc:1;
//Offset 8
u32 seq:12;
u32 frag:4;
u32 nextpktlen:14;
u32 nextind:1;
u32 rsvd0831:1;
//Offset 12
u32 rxmcs:6;
u32 rxht:1;
u32 gf:1;
u32 splcp:1;
u32 bw:1;
u32 htc:1;
u32 eosp:1;
u32 bssidfit:2;
u32 rpt_sel:2;
u32 rsvd1216:13;
u32 pattern_match:1;
u32 unicastwake:1;
u32 magicwake:1;
//Offset 16
/*
u32 pattern0match:1;
u32 pattern1match:1;
u32 pattern2match:1;
u32 pattern3match:1;
u32 pattern4match:1;
u32 pattern5match:1;
u32 pattern6match:1;
u32 pattern7match:1;
u32 pattern8match:1;
u32 pattern9match:1;
u32 patternamatch:1;
u32 patternbmatch:1;
u32 patterncmatch:1;
u32 rsvd1613:19;
*/
u32 rsvd16;
//Offset 20
u32 tsfl;
//Offset 24
u32 bassn:12;
u32 bavld:1;
u32 rsvd2413:19;
} RXREPORT, *PRXREPORT;
#ifdef CONFIG_SDIO_HCI
s32 rtl8188es_init_recv_priv(PADAPTER padapter);
void rtl8188es_free_recv_priv(PADAPTER padapter);
void rtl8188es_recv_hdl(PADAPTER padapter, struct recv_buf *precvbuf);
#endif
#ifdef CONFIG_USB_HCI
#define INTERRUPT_MSG_FORMAT_LEN 60
void rtl8188eu_init_recvbuf(_adapter *padapter, struct recv_buf *precvbuf);
s32 rtl8188eu_init_recv_priv(PADAPTER padapter);
void rtl8188eu_free_recv_priv(PADAPTER padapter);
void rtl8188eu_recv_hdl(PADAPTER padapter, struct recv_buf *precvbuf);
void rtl8188eu_recv_tasklet(void *priv);
#endif
#ifdef CONFIG_PCI_HCI
s32 rtl8188ee_init_recv_priv(PADAPTER padapter);
void rtl8188ee_free_recv_priv(PADAPTER padapter);
#endif
void rtl8188e_query_rx_phy_status(union recv_frame *prframe, struct phy_stat *pphy_stat);
void rtl8188e_process_phy_info(PADAPTER padapter, void *prframe);
void update_recvframe_phyinfo_88e(union recv_frame *precvframe,struct phy_stat *pphy_status);
void update_recvframe_attrib_88e( union recv_frame *precvframe, struct recv_stat *prxstat);
#endif
| francescosganga/remixos-kernel | drivers/staging/rtl8812au/include/rtl8188e_recv.h | C | gpl-2.0 | 3,225 |
/**
* 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.hadoop.hdfs;
import java.io.IOException;
/**
* For sharing between the local and remote block reader implementations.
*/
class BlockReaderUtil {
/* See {@link BlockReader#readAll(byte[], int, int)} */
public static int readAll(BlockReader reader,
byte[] buf, int offset, int len) throws IOException {
int n = 0;
for (;;) {
int nread = reader.read(buf, offset + n, len - n);
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
}
}
/* See {@link BlockReader#readFully(byte[], int, int)} */
public static void readFully(BlockReader reader,
byte[] buf, int off, int len) throws IOException {
int toRead = len;
while (toRead > 0) {
int ret = reader.read(buf, off, toRead);
if (ret < 0) {
throw new IOException("Premature EOF from inputStream");
}
toRead -= ret;
off += ret;
}
}
} | tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/BlockReaderUtil.java | Java | apache-2.0 | 1,761 |
require File.expand_path('../../../spec_helper', __FILE__)
require 'bigdecimal'
describe "BigDecimal#remainder" do
before(:each) do
@zero = BigDecimal("0")
@one = BigDecimal("0")
@mixed = BigDecimal("1.23456789")
@pos_int = BigDecimal("2E5555")
@neg_int = BigDecimal("-2E5555")
@pos_frac = BigDecimal("2E-9999")
@neg_frac = BigDecimal("-2E-9999")
@nan = BigDecimal("NaN")
@infinity = BigDecimal("Infinity")
@infinity_minus = BigDecimal("-Infinity")
@one_minus = BigDecimal("-1")
@frac_1 = BigDecimal("1E-99999")
@frac_2 = BigDecimal("0.9E-99999")
end
it "it equals modulo, if both values are of same sign" do
BigDecimal('1234567890123456789012345679').remainder(BigDecimal('1')).should == @zero
BigDecimal('123456789').remainder(BigDecimal('333333333333333333333333333E-50')).should == BigDecimal('0.12233333333333333333345679E-24')
@mixed.remainder(@pos_frac).should == @mixed % @pos_frac
@pos_int.remainder(@pos_frac).should == @pos_int % @pos_frac
@neg_frac.remainder(@neg_int).should == @neg_frac % @neg_int
@neg_int.remainder(@neg_frac).should == @neg_int % @neg_frac
end
it "means self-arg*(self/arg).truncate" do
@mixed.remainder(@neg_frac).should == @mixed - @neg_frac * (@mixed / @neg_frac).truncate
@pos_int.remainder(@neg_frac).should == @pos_int - @neg_frac * (@pos_int / @neg_frac).truncate
@neg_frac.remainder(@pos_int).should == @neg_frac - @pos_int * (@neg_frac / @pos_int).truncate
@neg_int.remainder(@pos_frac).should == @neg_int - @pos_frac * (@neg_int / @pos_frac).truncate
end
it "returns NaN used with zero" do
@mixed.remainder(@zero).nan?.should == true
@zero.remainder(@zero).nan?.should == true
end
it "returns zero if used on zero" do
@zero.remainder(@mixed).should == @zero
end
it "returns NaN if NaN is involved" do
@nan.remainder(@nan).nan?.should == true
@nan.remainder(@one).nan?.should == true
@one.remainder(@nan).nan?.should == true
@infinity.remainder(@nan).nan?.should == true
@nan.remainder(@infinity).nan?.should == true
end
it "returns NaN if Infinity is involved" do
@infinity.remainder(@infinity).nan?.should == true
@infinity.remainder(@one).nan?.should == true
@infinity.remainder(@mixed).nan?.should == true
@infinity.remainder(@one_minus).nan?.should == true
@infinity.remainder(@frac_1).nan?.should == true
@one.remainder(@infinity).nan?.should == true
@infinity_minus.remainder(@infinity_minus).nan?.should == true
@infinity_minus.remainder(@one).nan?.should == true
@one.remainder(@infinity_minus).nan?.should == true
@frac_2.remainder(@infinity_minus).nan?.should == true
@infinity.remainder(@infinity_minus).nan?.should == true
@infinity_minus.remainder(@infinity).nan?.should == true
end
it "coerces arguments to BigDecimal if possible" do
@one.remainder(2).should == @one
end
it "raises TypeError if the argument cannot be coerced to BigDecimal" do
lambda {
@one.remainder('2')
}.should raise_error(TypeError)
end
end
| takano32/rubinius | spec/ruby/library/bigdecimal/remainder_spec.rb | Ruby | bsd-3-clause | 3,111 |
/*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
'use strict';
angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function buildSensor() {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map | GuilhouT/angular-gantt | dist/angular-gantt-resizeSensor-plugin.js | JavaScript | mit | 2,694 |
/*
Copyright 2015 Google Inc. 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.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CModuleFunctions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module.Component.CModuleNodeComponent;
import com.google.security.zynamics.binnavi.disassembly.CProjectContainer;
import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleContainer;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.gui.SwingInvoker;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Represents module nodes in the project tree.
*/
public final class CModuleNode extends CProjectTreeNode<INaviModule> {
/**
* Used for serialization.
*/
private static final long serialVersionUID = -5643276356053733957L;
/**
* Icon used for loaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png"));
/**
* Icon used for unloaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_GRAY =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png"));
/**
* Icon used for incomplete modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_BROKEN =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_broken.png"));
/**
* Icon used for not yet converted modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_UNCONVERTED =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_light_gray.png"));
/**
* The module described by the node.
*/
private final INaviModule m_module;
/**
* Context in which views of the represented module are opened.
*/
private final IViewContainer m_contextContainer;
/**
* Updates the node on important changes in the represented module.
*/
private final InternalModuleListener m_listener;
/**
* Constructor for modules inside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param addressSpace The address space the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree,
final DefaultMutableTreeNode parentNode,
final IDatabase database,
final INaviAddressSpace addressSpace,
final INaviModule module,
final CProjectContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, addressSpace, module,
contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
addressSpace,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01972: Database argument can't be null");
Preconditions.checkNotNull(addressSpace, "IE01973: Address space can't be null");
m_module = Preconditions.checkNotNull(module, "IE01974: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Constructor for modules outside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree, final DefaultMutableTreeNode parentNode,
final IDatabase database, final INaviModule module, final CModuleContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, null, module, contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
null,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01970: Database can't be null");
m_module = Preconditions.checkNotNull(module, "IE01971: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Creates the child nodes of the module node. One node is added for the native Call graph of the
* module, another node is added that contains all native Flow graph views of the module.
*/
@Override
protected void createChildren() {}
@Override
public void dispose() {
super.dispose();
m_contextContainer.dispose();
m_module.removeListener(m_listener);
deleteChildren();
}
@Override
public void doubleClicked() {
if (m_module.getConfiguration().getRawModule().isComplete() && !m_module.isLoaded()) {
CModuleFunctions.loadModules(getProjectTree(), new INaviModule[] {m_module});
}
}
@Override
public CModuleNodeComponent getComponent() {
return (CModuleNodeComponent) super.getComponent();
}
@Override
public Icon getIcon() {
if (m_module.getConfiguration().getRawModule().isComplete() && m_module.isInitialized()) {
return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY;
} else if (m_module.getConfiguration().getRawModule().isComplete()
&& !m_module.isInitialized()) {
return ICON_MODULE_UNCONVERTED;
} else {
return ICON_MODULE_BROKEN;
}
}
@Override
public String toString() {
return m_module.getConfiguration().getName() + " (" + m_module.getFunctionCount() + "/"
+ m_module.getCustomViewCount() + ")";
}
/**
* Updates the node on important changes in the represented module.
*/
private class InternalModuleListener extends CModuleListenerAdapter {
@Override
public void addedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void changedName(final INaviModule module, final String name) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void deletedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
/**
* When the module is loaded, create the child nodes.
*/
@Override
public void loadedModule(final INaviModule module) {
new SwingInvoker() {
@Override
protected void operation() {
createChildren();
getTreeModel().nodeStructureChanged(CModuleNode.this);
}
}.invokeAndWait();
}
}
}
| dgrif/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/Module/CModuleNode.java | Java | apache-2.0 | 8,652 |
// SPDX-License-Identifier: GPL-2.0
/*
* camss-csiphy-2ph-1-0.c
*
* Qualcomm MSM Camera Subsystem - CSIPHY Module 2phase v1.0
*
* Copyright (c) 2011-2015, The Linux Foundation. All rights reserved.
* Copyright (C) 2016-2018 Linaro Ltd.
*/
#include "camss-csiphy.h"
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#define CAMSS_CSI_PHY_LNn_CFG2(n) (0x004 + 0x40 * (n))
#define CAMSS_CSI_PHY_LNn_CFG3(n) (0x008 + 0x40 * (n))
#define CAMSS_CSI_PHY_GLBL_RESET 0x140
#define CAMSS_CSI_PHY_GLBL_PWR_CFG 0x144
#define CAMSS_CSI_PHY_GLBL_IRQ_CMD 0x164
#define CAMSS_CSI_PHY_HW_VERSION 0x188
#define CAMSS_CSI_PHY_INTERRUPT_STATUSn(n) (0x18c + 0x4 * (n))
#define CAMSS_CSI_PHY_INTERRUPT_MASKn(n) (0x1ac + 0x4 * (n))
#define CAMSS_CSI_PHY_INTERRUPT_CLEARn(n) (0x1cc + 0x4 * (n))
#define CAMSS_CSI_PHY_GLBL_T_INIT_CFG0 0x1ec
#define CAMSS_CSI_PHY_T_WAKEUP_CFG0 0x1f4
static void csiphy_hw_version_read(struct csiphy_device *csiphy,
struct device *dev)
{
u8 hw_version = readl_relaxed(csiphy->base +
CAMSS_CSI_PHY_HW_VERSION);
dev_dbg(dev, "CSIPHY HW Version = 0x%02x\n", hw_version);
}
/*
* csiphy_reset - Perform software reset on CSIPHY module
* @csiphy: CSIPHY device
*/
static void csiphy_reset(struct csiphy_device *csiphy)
{
writel_relaxed(0x1, csiphy->base + CAMSS_CSI_PHY_GLBL_RESET);
usleep_range(5000, 8000);
writel_relaxed(0x0, csiphy->base + CAMSS_CSI_PHY_GLBL_RESET);
}
/*
* csiphy_settle_cnt_calc - Calculate settle count value
*
* Helper function to calculate settle count value. This is
* based on the CSI2 T_hs_settle parameter which in turn
* is calculated based on the CSI2 transmitter link frequency.
*
* Return settle count value or 0 if the CSI2 link frequency
* is not available
*/
static u8 csiphy_settle_cnt_calc(s64 link_freq, u32 timer_clk_rate)
{
u32 ui; /* ps */
u32 timer_period; /* ps */
u32 t_hs_prepare_max; /* ps */
u32 t_hs_prepare_zero_min; /* ps */
u32 t_hs_settle; /* ps */
u8 settle_cnt;
if (link_freq <= 0)
return 0;
ui = div_u64(1000000000000LL, link_freq);
ui /= 2;
t_hs_prepare_max = 85000 + 6 * ui;
t_hs_prepare_zero_min = 145000 + 10 * ui;
t_hs_settle = (t_hs_prepare_max + t_hs_prepare_zero_min) / 2;
timer_period = div_u64(1000000000000LL, timer_clk_rate);
settle_cnt = t_hs_settle / timer_period - 1;
return settle_cnt;
}
static void csiphy_lanes_enable(struct csiphy_device *csiphy,
struct csiphy_config *cfg,
s64 link_freq, u8 lane_mask)
{
struct csiphy_lanes_cfg *c = &cfg->csi2->lane_cfg;
u8 settle_cnt;
u8 val, l = 0;
int i = 0;
settle_cnt = csiphy_settle_cnt_calc(link_freq, csiphy->timer_clk_rate);
writel_relaxed(0x1, csiphy->base +
CAMSS_CSI_PHY_GLBL_T_INIT_CFG0);
writel_relaxed(0x1, csiphy->base +
CAMSS_CSI_PHY_T_WAKEUP_CFG0);
val = 0x1;
val |= lane_mask << 1;
writel_relaxed(val, csiphy->base + CAMSS_CSI_PHY_GLBL_PWR_CFG);
val = cfg->combo_mode << 4;
writel_relaxed(val, csiphy->base + CAMSS_CSI_PHY_GLBL_RESET);
for (i = 0; i <= c->num_data; i++) {
if (i == c->num_data)
l = c->clk.pos;
else
l = c->data[i].pos;
writel_relaxed(0x10, csiphy->base +
CAMSS_CSI_PHY_LNn_CFG2(l));
writel_relaxed(settle_cnt, csiphy->base +
CAMSS_CSI_PHY_LNn_CFG3(l));
writel_relaxed(0x3f, csiphy->base +
CAMSS_CSI_PHY_INTERRUPT_MASKn(l));
writel_relaxed(0x3f, csiphy->base +
CAMSS_CSI_PHY_INTERRUPT_CLEARn(l));
}
}
static void csiphy_lanes_disable(struct csiphy_device *csiphy,
struct csiphy_config *cfg)
{
struct csiphy_lanes_cfg *c = &cfg->csi2->lane_cfg;
u8 l = 0;
int i = 0;
for (i = 0; i <= c->num_data; i++) {
if (i == c->num_data)
l = c->clk.pos;
else
l = c->data[i].pos;
writel_relaxed(0x0, csiphy->base +
CAMSS_CSI_PHY_LNn_CFG2(l));
}
writel_relaxed(0x0, csiphy->base + CAMSS_CSI_PHY_GLBL_PWR_CFG);
}
/*
* csiphy_isr - CSIPHY module interrupt handler
* @irq: Interrupt line
* @dev: CSIPHY device
*
* Return IRQ_HANDLED on success
*/
static irqreturn_t csiphy_isr(int irq, void *dev)
{
struct csiphy_device *csiphy = dev;
u8 i;
for (i = 0; i < 8; i++) {
u8 val = readl_relaxed(csiphy->base +
CAMSS_CSI_PHY_INTERRUPT_STATUSn(i));
writel_relaxed(val, csiphy->base +
CAMSS_CSI_PHY_INTERRUPT_CLEARn(i));
writel_relaxed(0x1, csiphy->base + CAMSS_CSI_PHY_GLBL_IRQ_CMD);
writel_relaxed(0x0, csiphy->base + CAMSS_CSI_PHY_GLBL_IRQ_CMD);
writel_relaxed(0x0, csiphy->base +
CAMSS_CSI_PHY_INTERRUPT_CLEARn(i));
}
return IRQ_HANDLED;
}
const struct csiphy_hw_ops csiphy_ops_2ph_1_0 = {
.hw_version_read = csiphy_hw_version_read,
.reset = csiphy_reset,
.lanes_enable = csiphy_lanes_enable,
.lanes_disable = csiphy_lanes_disable,
.isr = csiphy_isr,
};
| HinTak/linux | drivers/media/platform/qcom/camss/camss-csiphy-2ph-1-0.c | C | gpl-2.0 | 4,783 |
/* Copyright (c) 2008-2010, 2012 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "msm_fb.h"
#include "mddihost.h"
#include "mddihosti.h"
#define SHARP_QVGA_PRIM 1
#define SHARP_128X128_SECD 2
extern uint32 mddi_host_core_version;
static boolean mddi_debug_prim_wait = FALSE;
static boolean mddi_sharp_vsync_wake = TRUE;
static boolean mddi_sharp_monitor_refresh_value = TRUE;
static boolean mddi_sharp_report_refresh_measurements = FALSE;
static uint32 mddi_sharp_rows_per_second = 13830; /* 5200000/376 */
static uint32 mddi_sharp_rows_per_refresh = 338;
static uint32 mddi_sharp_usecs_per_refresh = 24440; /* (376+338)/5200000 */
static boolean mddi_sharp_debug_60hz_refresh = FALSE;
extern mddi_gpio_info_type mddi_gpio;
extern boolean mddi_vsync_detect_enabled;
static msm_fb_vsync_handler_type mddi_sharp_vsync_handler;
static void *mddi_sharp_vsync_handler_arg;
static uint16 mddi_sharp_vsync_attempts;
static void mddi_sharp_prim_lcd_init(void);
static void mddi_sharp_sub_lcd_init(void);
static void mddi_sharp_lcd_set_backlight(struct msm_fb_data_type *mfd);
static void mddi_sharp_vsync_set_handler(msm_fb_vsync_handler_type handler,
void *);
static void mddi_sharp_lcd_vsync_detected(boolean detected);
static struct msm_panel_common_pdata *mddi_sharp_pdata;
#define REG_SYSCTL 0x0000
#define REG_INTR 0x0006
#define REG_CLKCNF 0x000C
#define REG_CLKDIV1 0x000E
#define REG_CLKDIV2 0x0010
#define REG_GIOD 0x0040
#define REG_GIOA 0x0042
#define REG_AGM 0x010A
#define REG_FLFT 0x0110
#define REG_FRGT 0x0112
#define REG_FTOP 0x0114
#define REG_FBTM 0x0116
#define REG_FSTRX 0x0118
#define REG_FSTRY 0x011A
#define REG_VRAM 0x0202
#define REG_SSDCTL 0x0330
#define REG_SSD0 0x0332
#define REG_PSTCTL1 0x0400
#define REG_PSTCTL2 0x0402
#define REG_PTGCTL 0x042A
#define REG_PTHP 0x042C
#define REG_PTHB 0x042E
#define REG_PTHW 0x0430
#define REG_PTHF 0x0432
#define REG_PTVP 0x0434
#define REG_PTVB 0x0436
#define REG_PTVW 0x0438
#define REG_PTVF 0x043A
#define REG_VBLKS 0x0458
#define REG_VBLKE 0x045A
#define REG_SUBCTL 0x0700
#define REG_SUBTCMD 0x0702
#define REG_SUBTCMDD 0x0704
#define REG_REVBYTE 0x0A02
#define REG_REVCNT 0x0A04
#define REG_REVATTR 0x0A06
#define REG_REVFMT 0x0A08
#define SHARP_SUB_UNKNOWN 0xffffffff
#define SHARP_SUB_HYNIX 1
#define SHARP_SUB_ROHM 2
static uint32 sharp_subpanel_type = SHARP_SUB_UNKNOWN;
static void sub_through_write(int sub_rs, uint32 sub_data)
{
mddi_queue_register_write(REG_SUBTCMDD, sub_data, FALSE, 0);
/* CS=1,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x000e | sub_rs, FALSE, 0);
/* CS=0,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x0006 | sub_rs, FALSE, 0);
/* CS=0,RD=1,WE=0,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x0004 | sub_rs, FALSE, 0);
/* CS=0,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x0006 | sub_rs, FALSE, 0);
/* CS=1,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x000e | sub_rs, TRUE, 0);
}
static uint32 sub_through_read(int sub_rs)
{
uint32 sub_data;
/* CS=1,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x000e | sub_rs, FALSE, 0);
/* CS=0,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x0006 | sub_rs, FALSE, 0);
/* CS=0,RD=1,WE=0,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x0002 | sub_rs, TRUE, 0);
mddi_queue_register_read(REG_SUBTCMDD, &sub_data, TRUE, 0);
/* CS=0,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x0006 | sub_rs, FALSE, 0);
/* CS=1,RD=1,WE=1,RS=sub_rs */
mddi_queue_register_write(REG_SUBTCMD, 0x000e | sub_rs, TRUE, 0);
return sub_data;
}
static void serigo(uint32 ssd)
{
uint32 ssdctl;
mddi_queue_register_read(REG_SSDCTL, &ssdctl, TRUE, 0);
ssdctl = ((ssdctl & 0xE7) | 0x02);
mddi_queue_register_write(REG_SSD0, ssd, FALSE, 0);
mddi_queue_register_write(REG_SSDCTL, ssdctl, TRUE, 0);
do {
mddi_queue_register_read(REG_SSDCTL, &ssdctl, TRUE, 0);
} while ((ssdctl & 0x0002) != 0);
if (mddi_debug_prim_wait)
mddi_wait(2);
}
static void mddi_sharp_lcd_powerdown(void)
{
serigo(0x0131);
serigo(0x0300);
mddi_wait(40);
serigo(0x0135);
mddi_wait(20);
serigo(0x2122);
mddi_wait(20);
serigo(0x0201);
mddi_wait(20);
serigo(0x2100);
mddi_wait(20);
serigo(0x2000);
mddi_wait(20);
mddi_queue_register_write(REG_PSTCTL1, 0x1, TRUE, 0);
mddi_wait(100);
mddi_queue_register_write(REG_PSTCTL1, 0x0, TRUE, 0);
mddi_wait(2);
mddi_queue_register_write(REG_SYSCTL, 0x1, TRUE, 0);
mddi_wait(2);
mddi_queue_register_write(REG_CLKDIV1, 0x3, TRUE, 0);
mddi_wait(2);
mddi_queue_register_write(REG_SSDCTL, 0x0000, TRUE, 0); /* SSDRESET */
mddi_queue_register_write(REG_SYSCTL, 0x0, TRUE, 0);
mddi_wait(2);
}
static void mddi_sharp_lcd_set_backlight(struct msm_fb_data_type *mfd)
{
uint32 regdata;
int32 level;
int max = mfd->panel_info.bl_max;
int min = mfd->panel_info.bl_min;
if (mddi_sharp_pdata && mddi_sharp_pdata->backlight_level) {
level = mddi_sharp_pdata->backlight_level(mfd->bl_level,
max,
min);
if (level < 0)
return;
/* use Rodem GPIO(2:0) to give 8 levels of backlight (7-0) */
/* Set lower 3 GPIOs as Outputs (set to 0) */
mddi_queue_register_read(REG_GIOA, ®data, TRUE, 0);
mddi_queue_register_write(REG_GIOA, regdata & 0xfff8, TRUE, 0);
/* Set lower 3 GPIOs as level */
mddi_queue_register_read(REG_GIOD, ®data, TRUE, 0);
mddi_queue_register_write(REG_GIOD,
(regdata & 0xfff8) | (0x07 & level), TRUE, 0);
}
}
static void mddi_sharp_prim_lcd_init(void)
{
mddi_queue_register_write(REG_SYSCTL, 0x4000, TRUE, 0);
mddi_wait(1);
mddi_queue_register_write(REG_SYSCTL, 0x0000, TRUE, 0);
mddi_wait(5);
mddi_queue_register_write(REG_SYSCTL, 0x0001, FALSE, 0);
mddi_queue_register_write(REG_CLKDIV1, 0x000b, FALSE, 0);
/* new reg write below */
if (mddi_sharp_debug_60hz_refresh)
mddi_queue_register_write(REG_CLKCNF, 0x070d, FALSE, 0);
else
mddi_queue_register_write(REG_CLKCNF, 0x0708, FALSE, 0);
mddi_queue_register_write(REG_SYSCTL, 0x0201, FALSE, 0);
mddi_queue_register_write(REG_PTGCTL, 0x0010, FALSE, 0);
mddi_queue_register_write(REG_PTHP, 4, FALSE, 0);
mddi_queue_register_write(REG_PTHB, 40, FALSE, 0);
mddi_queue_register_write(REG_PTHW, 240, FALSE, 0);
if (mddi_sharp_debug_60hz_refresh)
mddi_queue_register_write(REG_PTHF, 12, FALSE, 0);
else
mddi_queue_register_write(REG_PTHF, 92, FALSE, 0);
mddi_wait(1);
mddi_queue_register_write(REG_PTVP, 1, FALSE, 0);
mddi_queue_register_write(REG_PTVB, 2, FALSE, 0);
mddi_queue_register_write(REG_PTVW, 320, FALSE, 0);
mddi_queue_register_write(REG_PTVF, 15, FALSE, 0);
mddi_wait(1);
/* vram_color set REG_AGM???? */
mddi_queue_register_write(REG_AGM, 0x0000, TRUE, 0);
mddi_queue_register_write(REG_SSDCTL, 0x0000, FALSE, 0);
mddi_queue_register_write(REG_SSDCTL, 0x0001, TRUE, 0);
mddi_wait(1);
mddi_queue_register_write(REG_PSTCTL1, 0x0001, TRUE, 0);
mddi_wait(10);
serigo(0x0701);
/* software reset */
mddi_wait(1);
/* Wait over 50us */
serigo(0x0400);
/* DCLK~ACHSYNC~ACVSYNC polarity setting */
serigo(0x2900);
/* EEPROM start read address setting */
serigo(0x2606);
/* EEPROM start read register setting */
mddi_wait(20);
/* Wait over 20ms */
serigo(0x0503);
/* Horizontal timing setting */
serigo(0x062C);
/* Veritical timing setting */
serigo(0x2001);
/* power initialize setting(VDC2) */
mddi_wait(20);
/* Wait over 20ms */
serigo(0x2120);
/* Initialize power setting(CPS) */
mddi_wait(20);
/* Wait over 20ms */
serigo(0x2130);
/* Initialize power setting(CPS) */
mddi_wait(20);
/* Wait over 20ms */
serigo(0x2132);
/* Initialize power setting(CPS) */
mddi_wait(10);
/* Wait over 10ms */
serigo(0x2133);
/* Initialize power setting(CPS) */
mddi_wait(20);
/* Wait over 20ms */
serigo(0x0200);
/* Panel initialize release(INIT) */
mddi_wait(1);
/* Wait over 1ms */
serigo(0x0131);
/* Panel setting(CPS) */
mddi_wait(1);
/* Wait over 1ms */
mddi_queue_register_write(REG_PSTCTL1, 0x0003, TRUE, 0);
/* if (FFA LCD is upside down) -> serigo(0x0100); */
serigo(0x0130);
/* Black mask release(display ON) */
mddi_wait(1);
/* Wait over 1ms */
if (mddi_sharp_vsync_wake) {
mddi_queue_register_write(REG_VBLKS, 0x1001, TRUE, 0);
mddi_queue_register_write(REG_VBLKE, 0x1002, TRUE, 0);
}
/* Set the MDP pixel data attributes for Primary Display */
mddi_host_write_pix_attr_reg(0x00C3);
return;
}
void mddi_sharp_sub_lcd_init(void)
{
mddi_queue_register_write(REG_SYSCTL, 0x4000, FALSE, 0);
mddi_queue_register_write(REG_SYSCTL, 0x0000, TRUE, 0);
mddi_wait(100);
mddi_queue_register_write(REG_SYSCTL, 0x0001, FALSE, 0);
mddi_queue_register_write(REG_CLKDIV1, 0x000b, FALSE, 0);
mddi_queue_register_write(REG_CLKCNF, 0x0708, FALSE, 0);
mddi_queue_register_write(REG_SYSCTL, 0x0201, FALSE, 0);
mddi_queue_register_write(REG_PTGCTL, 0x0010, FALSE, 0);
mddi_queue_register_write(REG_PTHP, 4, FALSE, 0);
mddi_queue_register_write(REG_PTHB, 40, FALSE, 0);
mddi_queue_register_write(REG_PTHW, 128, FALSE, 0);
mddi_queue_register_write(REG_PTHF, 92, FALSE, 0);
mddi_queue_register_write(REG_PTVP, 1, FALSE, 0);
mddi_queue_register_write(REG_PTVB, 2, FALSE, 0);
mddi_queue_register_write(REG_PTVW, 128, FALSE, 0);
mddi_queue_register_write(REG_PTVF, 15, FALSE, 0);
/* Now the sub display..... */
/* Reset High */
mddi_queue_register_write(REG_SUBCTL, 0x0200, FALSE, 0);
/* CS=1,RD=1,WE=1,RS=1 */
mddi_queue_register_write(REG_SUBTCMD, 0x000f, TRUE, 0);
mddi_wait(1);
/* Wait 5us */
if (sharp_subpanel_type == SHARP_SUB_UNKNOWN) {
uint32 data;
sub_through_write(1, 0x05);
sub_through_write(1, 0x6A);
sub_through_write(1, 0x1D);
sub_through_write(1, 0x05);
data = sub_through_read(1);
if (data == 0x6A) {
sharp_subpanel_type = SHARP_SUB_HYNIX;
} else {
sub_through_write(0, 0x36);
sub_through_write(1, 0xA8);
sub_through_write(0, 0x09);
data = sub_through_read(1);
data = sub_through_read(1);
if (data == 0x54) {
sub_through_write(0, 0x36);
sub_through_write(1, 0x00);
sharp_subpanel_type = SHARP_SUB_ROHM;
}
}
}
if (sharp_subpanel_type == SHARP_SUB_HYNIX) {
sub_through_write(1, 0x00); /* Display setting 1 */
sub_through_write(1, 0x04);
sub_through_write(1, 0x01);
sub_through_write(1, 0x05);
sub_through_write(1, 0x0280);
sub_through_write(1, 0x0301);
sub_through_write(1, 0x0402);
sub_through_write(1, 0x0500);
sub_through_write(1, 0x0681);
sub_through_write(1, 0x077F);
sub_through_write(1, 0x08C0);
sub_through_write(1, 0x0905);
sub_through_write(1, 0x0A02);
sub_through_write(1, 0x0B00);
sub_through_write(1, 0x0C00);
sub_through_write(1, 0x0D00);
sub_through_write(1, 0x0E00);
sub_through_write(1, 0x0F00);
sub_through_write(1, 0x100B); /* Display setting 2 */
sub_through_write(1, 0x1103);
sub_through_write(1, 0x1237);
sub_through_write(1, 0x1300);
sub_through_write(1, 0x1400);
sub_through_write(1, 0x1500);
sub_through_write(1, 0x1605);
sub_through_write(1, 0x1700);
sub_through_write(1, 0x1800);
sub_through_write(1, 0x192E);
sub_through_write(1, 0x1A00);
sub_through_write(1, 0x1B00);
sub_through_write(1, 0x1C00);
sub_through_write(1, 0x151A); /* Power setting */
sub_through_write(1, 0x2002); /* Gradation Palette setting */
sub_through_write(1, 0x2107);
sub_through_write(1, 0x220C);
sub_through_write(1, 0x2310);
sub_through_write(1, 0x2414);
sub_through_write(1, 0x2518);
sub_through_write(1, 0x261C);
sub_through_write(1, 0x2720);
sub_through_write(1, 0x2824);
sub_through_write(1, 0x2928);
sub_through_write(1, 0x2A2B);
sub_through_write(1, 0x2B2E);
sub_through_write(1, 0x2C31);
sub_through_write(1, 0x2D34);
sub_through_write(1, 0x2E37);
sub_through_write(1, 0x2F3A);
sub_through_write(1, 0x303C);
sub_through_write(1, 0x313E);
sub_through_write(1, 0x323F);
sub_through_write(1, 0x3340);
sub_through_write(1, 0x3441);
sub_through_write(1, 0x3543);
sub_through_write(1, 0x3646);
sub_through_write(1, 0x3749);
sub_through_write(1, 0x384C);
sub_through_write(1, 0x394F);
sub_through_write(1, 0x3A52);
sub_through_write(1, 0x3B59);
sub_through_write(1, 0x3C60);
sub_through_write(1, 0x3D67);
sub_through_write(1, 0x3E6E);
sub_through_write(1, 0x3F7F);
sub_through_write(1, 0x4001);
sub_through_write(1, 0x4107);
sub_through_write(1, 0x420C);
sub_through_write(1, 0x4310);
sub_through_write(1, 0x4414);
sub_through_write(1, 0x4518);
sub_through_write(1, 0x461C);
sub_through_write(1, 0x4720);
sub_through_write(1, 0x4824);
sub_through_write(1, 0x4928);
sub_through_write(1, 0x4A2B);
sub_through_write(1, 0x4B2E);
sub_through_write(1, 0x4C31);
sub_through_write(1, 0x4D34);
sub_through_write(1, 0x4E37);
sub_through_write(1, 0x4F3A);
sub_through_write(1, 0x503C);
sub_through_write(1, 0x513E);
sub_through_write(1, 0x523F);
sub_through_write(1, 0x5340);
sub_through_write(1, 0x5441);
sub_through_write(1, 0x5543);
sub_through_write(1, 0x5646);
sub_through_write(1, 0x5749);
sub_through_write(1, 0x584C);
sub_through_write(1, 0x594F);
sub_through_write(1, 0x5A52);
sub_through_write(1, 0x5B59);
sub_through_write(1, 0x5C60);
sub_through_write(1, 0x5D67);
sub_through_write(1, 0x5E6E);
sub_through_write(1, 0x5F7E);
sub_through_write(1, 0x6000);
sub_through_write(1, 0x6107);
sub_through_write(1, 0x620C);
sub_through_write(1, 0x6310);
sub_through_write(1, 0x6414);
sub_through_write(1, 0x6518);
sub_through_write(1, 0x661C);
sub_through_write(1, 0x6720);
sub_through_write(1, 0x6824);
sub_through_write(1, 0x6928);
sub_through_write(1, 0x6A2B);
sub_through_write(1, 0x6B2E);
sub_through_write(1, 0x6C31);
sub_through_write(1, 0x6D34);
sub_through_write(1, 0x6E37);
sub_through_write(1, 0x6F3A);
sub_through_write(1, 0x703C);
sub_through_write(1, 0x713E);
sub_through_write(1, 0x723F);
sub_through_write(1, 0x7340);
sub_through_write(1, 0x7441);
sub_through_write(1, 0x7543);
sub_through_write(1, 0x7646);
sub_through_write(1, 0x7749);
sub_through_write(1, 0x784C);
sub_through_write(1, 0x794F);
sub_through_write(1, 0x7A52);
sub_through_write(1, 0x7B59);
sub_through_write(1, 0x7C60);
sub_through_write(1, 0x7D67);
sub_through_write(1, 0x7E6E);
sub_through_write(1, 0x7F7D);
sub_through_write(1, 0x1851); /* Display on */
mddi_queue_register_write(REG_AGM, 0x0000, TRUE, 0);
/* 1 pixel / 1 post clock */
mddi_queue_register_write(REG_CLKDIV2, 0x3b00, FALSE, 0);
/* SUB LCD select */
mddi_queue_register_write(REG_PSTCTL2, 0x0080, FALSE, 0);
/* RS=0,command initiate number=0,select master mode */
mddi_queue_register_write(REG_SUBCTL, 0x0202, FALSE, 0);
/* Sub LCD Data transform start */
mddi_queue_register_write(REG_PSTCTL1, 0x0003, FALSE, 0);
} else if (sharp_subpanel_type == SHARP_SUB_ROHM) {
sub_through_write(0, 0x01); /* Display setting */
sub_through_write(1, 0x00);
mddi_wait(1);
/* Wait 100us <----- ******* Update 2005/01/24 */
sub_through_write(0, 0xB6);
sub_through_write(1, 0x0C);
sub_through_write(1, 0x4A);
sub_through_write(1, 0x20);
sub_through_write(0, 0x3A);
sub_through_write(1, 0x05);
sub_through_write(0, 0xB7);
sub_through_write(1, 0x01);
sub_through_write(0, 0xBA);
sub_through_write(1, 0x20);
sub_through_write(1, 0x02);
sub_through_write(0, 0x25);
sub_through_write(1, 0x4F);
sub_through_write(0, 0xBB);
sub_through_write(1, 0x00);
sub_through_write(0, 0x36);
sub_through_write(1, 0x00);
sub_through_write(0, 0xB1);
sub_through_write(1, 0x05);
sub_through_write(0, 0xBE);
sub_through_write(1, 0x80);
sub_through_write(0, 0x26);
sub_through_write(1, 0x01);
sub_through_write(0, 0x2A);
sub_through_write(1, 0x02);
sub_through_write(1, 0x81);
sub_through_write(0, 0x2B);
sub_through_write(1, 0x00);
sub_through_write(1, 0x7F);
sub_through_write(0, 0x2C);
sub_through_write(0, 0x11); /* Sleep mode off */
mddi_wait(1);
/* Wait 100 ms <----- ******* Update 2005/01/24 */
sub_through_write(0, 0x29); /* Display on */
sub_through_write(0, 0xB3);
sub_through_write(1, 0x20);
sub_through_write(1, 0xAA);
sub_through_write(1, 0xA0);
sub_through_write(1, 0x20);
sub_through_write(1, 0x30);
sub_through_write(1, 0xA6);
sub_through_write(1, 0xFF);
sub_through_write(1, 0x9A);
sub_through_write(1, 0x9F);
sub_through_write(1, 0xAF);
sub_through_write(1, 0xBC);
sub_through_write(1, 0xCF);
sub_through_write(1, 0xDF);
sub_through_write(1, 0x20);
sub_through_write(1, 0x9C);
sub_through_write(1, 0x8A);
sub_through_write(0, 0x002C); /* Display on */
/* 1 pixel / 2 post clock */
mddi_queue_register_write(REG_CLKDIV2, 0x7b00, FALSE, 0);
/* SUB LCD select */
mddi_queue_register_write(REG_PSTCTL2, 0x0080, FALSE, 0);
/* RS=1,command initiate number=0,select master mode */
mddi_queue_register_write(REG_SUBCTL, 0x0242, FALSE, 0);
/* Sub LCD Data transform start */
mddi_queue_register_write(REG_PSTCTL1, 0x0003, FALSE, 0);
}
/* Set the MDP pixel data attributes for Sub Display */
mddi_host_write_pix_attr_reg(0x00C0);
}
void mddi_sharp_lcd_vsync_detected(boolean detected)
{
/* static timetick_type start_time = 0; */
static struct timeval start_time;
static boolean first_time = TRUE;
/* uint32 mdp_cnt_val = 0; */
/* timetick_type elapsed_us; */
struct timeval now;
uint32 elapsed_us;
uint32 num_vsyncs;
if ((detected) || (mddi_sharp_vsync_attempts > 5)) {
if ((detected) && (mddi_sharp_monitor_refresh_value)) {
/* if (start_time != 0) */
if (!first_time) {
jiffies_to_timeval(jiffies, &now);
elapsed_us =
(now.tv_sec - start_time.tv_sec) * 1000000 +
now.tv_usec - start_time.tv_usec;
/*
* LCD is configured for a refresh every usecs,
* so to determine the number of vsyncs that
* have occurred since the last measurement add
* half that to the time difference and divide
* by the refresh rate.
*/
num_vsyncs = (elapsed_us +
(mddi_sharp_usecs_per_refresh >>
1)) /
mddi_sharp_usecs_per_refresh;
/*
* LCD is configured for * hsyncs (rows) per
* refresh cycle. Calculate new rows_per_second
* value based upon these new measurements.
* MDP can update with this new value.
*/
mddi_sharp_rows_per_second =
(mddi_sharp_rows_per_refresh * 1000 *
num_vsyncs) / (elapsed_us / 1000);
}
/* start_time = timetick_get(); */
first_time = FALSE;
jiffies_to_timeval(jiffies, &start_time);
if (mddi_sharp_report_refresh_measurements) {
/* mdp_cnt_val = MDP_LINE_COUNT; */
}
}
/* if detected = TRUE, client initiated wakeup was detected */
if (mddi_sharp_vsync_handler != NULL) {
(*mddi_sharp_vsync_handler)
(mddi_sharp_vsync_handler_arg);
mddi_sharp_vsync_handler = NULL;
}
mddi_vsync_detect_enabled = FALSE;
mddi_sharp_vsync_attempts = 0;
/* need to clear this vsync wakeup */
if (!mddi_queue_register_write_int(REG_INTR, 0x0000)) {
MDDI_MSG_ERR("Vsync interrupt clear failed!\n");
}
if (!detected) {
/* give up after 5 failed attempts but show error */
MDDI_MSG_NOTICE("Vsync detection failed!\n");
} else if ((mddi_sharp_monitor_refresh_value) &&
(mddi_sharp_report_refresh_measurements)) {
MDDI_MSG_NOTICE(" Lines Per Second=%d!\n",
mddi_sharp_rows_per_second);
}
} else
/* if detected = FALSE, we woke up from hibernation, but did not
* detect client initiated wakeup.
*/
mddi_sharp_vsync_attempts++;
}
/* ISR to be executed */
void mddi_sharp_vsync_set_handler(msm_fb_vsync_handler_type handler, void *arg)
{
boolean error = FALSE;
unsigned long flags;
/* Disable interrupts */
spin_lock_irqsave(&mddi_host_spin_lock, flags);
/* INTLOCK(); */
if (mddi_sharp_vsync_handler != NULL)
error = TRUE;
/* Register the handler for this particular GROUP interrupt source */
mddi_sharp_vsync_handler = handler;
mddi_sharp_vsync_handler_arg = arg;
/* Restore interrupts */
spin_unlock_irqrestore(&mddi_host_spin_lock, flags);
/* INTFREE(); */
if (error)
MDDI_MSG_ERR("MDDI: Previous Vsync handler never called\n");
/* Enable the vsync wakeup */
mddi_queue_register_write(REG_INTR, 0x8100, FALSE, 0);
mddi_sharp_vsync_attempts = 1;
mddi_vsync_detect_enabled = TRUE;
} /* mddi_sharp_vsync_set_handler */
static int mddi_sharp_lcd_on(struct platform_device *pdev)
{
struct msm_fb_data_type *mfd;
mfd = platform_get_drvdata(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
mddi_host_client_cnt_reset();
if (mfd->panel.id == SHARP_QVGA_PRIM)
mddi_sharp_prim_lcd_init();
else
mddi_sharp_sub_lcd_init();
return 0;
}
static int mddi_sharp_lcd_off(struct platform_device *pdev)
{
if (mddi_sharp_vsync_handler != NULL) {
(*mddi_sharp_vsync_handler)
(mddi_sharp_vsync_handler_arg);
mddi_sharp_vsync_handler = NULL;
printk(KERN_INFO "%s: clean up vsyn_handler=%x\n", __func__,
(int)mddi_sharp_vsync_handler);
}
mddi_sharp_lcd_powerdown();
return 0;
}
static int __devinit mddi_sharp_probe(struct platform_device *pdev)
{
if (pdev->id == 0) {
mddi_sharp_pdata = pdev->dev.platform_data;
return 0;
}
msm_fb_add_device(pdev);
return 0;
}
static struct platform_driver this_driver = {
.probe = mddi_sharp_probe,
.driver = {
.name = "mddi_sharp_qvga",
},
};
static struct msm_fb_panel_data mddi_sharp_panel_data0 = {
.on = mddi_sharp_lcd_on,
.off = mddi_sharp_lcd_off,
.set_backlight = mddi_sharp_lcd_set_backlight,
.set_vsync_notifier = mddi_sharp_vsync_set_handler,
};
static struct platform_device this_device_0 = {
.name = "mddi_sharp_qvga",
.id = SHARP_QVGA_PRIM,
.dev = {
.platform_data = &mddi_sharp_panel_data0,
}
};
static struct msm_fb_panel_data mddi_sharp_panel_data1 = {
.on = mddi_sharp_lcd_on,
.off = mddi_sharp_lcd_off,
};
static struct platform_device this_device_1 = {
.name = "mddi_sharp_qvga",
.id = SHARP_128X128_SECD,
.dev = {
.platform_data = &mddi_sharp_panel_data1,
}
};
static int __init mddi_sharp_init(void)
{
int ret;
struct msm_panel_info *pinfo;
#ifdef CONFIG_FB_MSM_MDDI_AUTO_DETECT
u32 id;
ret = msm_fb_detect_client("mddi_sharp_qvga");
if (ret == -ENODEV)
return 0;
if (ret) {
id = mddi_get_client_id();
if (((id >> 16) != 0x0) || ((id & 0xffff) != 0x8835))
return 0;
}
#endif
if (mddi_host_core_version > 8) {
/* can use faster refresh with newer hw revisions */
mddi_sharp_debug_60hz_refresh = TRUE;
/* Timing variables for tracking vsync */
/* dot_clock = 6.00MHz
* horizontal count = 296
* vertical count = 338
* refresh rate = 6000000/(296+338) = 60Hz
*/
mddi_sharp_rows_per_second = 20270; /* 6000000/296 */
mddi_sharp_rows_per_refresh = 338;
mddi_sharp_usecs_per_refresh = 16674; /* (296+338)/6000000 */
} else {
/* Timing variables for tracking vsync */
/* dot_clock = 5.20MHz
* horizontal count = 376
* vertical count = 338
* refresh rate = 5200000/(376+338) = 41Hz
*/
mddi_sharp_rows_per_second = 13830; /* 5200000/376 */
mddi_sharp_rows_per_refresh = 338;
mddi_sharp_usecs_per_refresh = 24440; /* (376+338)/5200000 */
}
ret = platform_driver_register(&this_driver);
if (!ret) {
pinfo = &mddi_sharp_panel_data0.panel_info;
pinfo->xres = 240;
pinfo->yres = 320;
MSM_FB_SINGLE_MODE_PANEL(pinfo);
pinfo->type = MDDI_PANEL;
pinfo->pdest = DISPLAY_1;
pinfo->mddi.vdopkt = MDDI_DEFAULT_PRIM_PIX_ATTR;
pinfo->wait_cycle = 0;
pinfo->bpp = 18;
pinfo->fb_num = 2;
pinfo->clk_rate = 122880000;
pinfo->clk_min = 120000000;
pinfo->clk_max = 125000000;
pinfo->lcd.vsync_enable = TRUE;
pinfo->mddi.is_type1 = TRUE;
pinfo->lcd.refx100 =
(mddi_sharp_rows_per_second * 100) /
mddi_sharp_rows_per_refresh;
pinfo->lcd.v_back_porch = 12;
pinfo->lcd.v_front_porch = 6;
pinfo->lcd.v_pulse_width = 0;
pinfo->lcd.hw_vsync_mode = FALSE;
pinfo->lcd.vsync_notifier_period = (1 * HZ);
pinfo->bl_max = 7;
pinfo->bl_min = 1;
ret = platform_device_register(&this_device_0);
if (ret)
platform_driver_unregister(&this_driver);
pinfo = &mddi_sharp_panel_data1.panel_info;
pinfo->xres = 128;
pinfo->yres = 128;
MSM_FB_SINGLE_MODE_PANEL(pinfo);
pinfo->type = MDDI_PANEL;
pinfo->pdest = DISPLAY_2;
pinfo->mddi.vdopkt = 0x400;
pinfo->wait_cycle = 0;
pinfo->bpp = 18;
pinfo->clk_rate = 122880000;
pinfo->clk_min = 120000000;
pinfo->clk_max = 125000000;
pinfo->fb_num = 2;
ret = platform_device_register(&this_device_1);
if (ret) {
platform_device_unregister(&this_device_0);
platform_driver_unregister(&this_driver);
}
}
if (!ret)
mddi_lcd.vsync_detected = mddi_sharp_lcd_vsync_detected;
return ret;
}
module_init(mddi_sharp_init);
| Jarbu12/Xperia-M-Kernel | kernel/drivers/video/msm/mddi_sharp.c | C | gpl-3.0 | 25,454 |
/*
AngularJS v1.6.2
(c) 2010-2017 Google, Inc. http://angularjs.org
License: MIT
*/
(function(x,n){'use strict';function s(f,k){var e=!1,a=!1;this.ngClickOverrideEnabled=function(b){return n.isDefined(b)?(b&&!a&&(a=!0,t.$$moduleName="ngTouch",k.directive("ngClick",t),f.decorator("ngClickDirective",["$delegate",function(a){if(e)a.shift();else for(var b=a.length-1;0<=b;){if("ngTouch"===a[b].$$moduleName){a.splice(b,1);break}b--}return a}])),e=b,this):e};this.$get=function(){return{ngClickOverrideEnabled:function(){return e}}}}function v(f,k,e){p.directive(f,["$parse","$swipe",function(a,
b){return function(l,u,g){function h(c){if(!d)return!1;var a=Math.abs(c.y-d.y);c=(c.x-d.x)*k;return r&&75>a&&0<c&&30<c&&.3>a/c}var m=a(g[f]),d,r,c=["touch"];n.isDefined(g.ngSwipeDisableMouse)||c.push("mouse");b.bind(u,{start:function(c,a){d=c;r=!0},cancel:function(c){r=!1},end:function(c,d){h(c)&&l.$apply(function(){u.triggerHandler(e);m(l,{$event:d})})}},c)}}])}var p=n.module("ngTouch",[]);p.provider("$touch",s);s.$inject=["$provide","$compileProvider"];p.factory("$swipe",[function(){function f(a){a=
a.originalEvent||a;var b=a.touches&&a.touches.length?a.touches:[a];a=a.changedTouches&&a.changedTouches[0]||b[0];return{x:a.clientX,y:a.clientY}}function k(a,b){var l=[];n.forEach(a,function(a){(a=e[a][b])&&l.push(a)});return l.join(" ")}var e={mouse:{start:"mousedown",move:"mousemove",end:"mouseup"},touch:{start:"touchstart",move:"touchmove",end:"touchend",cancel:"touchcancel"},pointer:{start:"pointerdown",move:"pointermove",end:"pointerup",cancel:"pointercancel"}};return{bind:function(a,b,l){var e,
g,h,m,d=!1;l=l||["mouse","touch","pointer"];a.on(k(l,"start"),function(c){h=f(c);d=!0;g=e=0;m=h;b.start&&b.start(h,c)});var r=k(l,"cancel");if(r)a.on(r,function(c){d=!1;b.cancel&&b.cancel(c)});a.on(k(l,"move"),function(c){if(d&&h){var a=f(c);e+=Math.abs(a.x-m.x);g+=Math.abs(a.y-m.y);m=a;10>e&&10>g||(g>e?(d=!1,b.cancel&&b.cancel(c)):(c.preventDefault(),b.move&&b.move(a,c)))}});a.on(k(l,"end"),function(c){d&&(d=!1,b.end&&b.end(f(c),c))})}}}]);var t=["$parse","$timeout","$rootElement",function(f,k,e){function a(a,
d,b){for(var c=0;c<a.length;c+=2){var g=a[c+1],e=b;if(25>Math.abs(a[c]-d)&&25>Math.abs(g-e))return a.splice(c,c+2),!0}return!1}function b(b){if(!(2500<Date.now()-u)){var d=b.touches&&b.touches.length?b.touches:[b],e=d[0].clientX,d=d[0].clientY;if(!(1>e&&1>d||h&&h[0]===e&&h[1]===d)){h&&(h=null);var c=b.target;"label"===n.lowercase(c.nodeName||c[0]&&c[0].nodeName)&&(h=[e,d]);a(g,e,d)||(b.stopPropagation(),b.preventDefault(),b.target&&b.target.blur&&b.target.blur())}}}function l(a){a=a.touches&&a.touches.length?
a.touches:[a];var b=a[0].clientX,e=a[0].clientY;g.push(b,e);k(function(){for(var a=0;a<g.length;a+=2)if(g[a]===b&&g[a+1]===e){g.splice(a,a+2);break}},2500,!1)}var u,g,h;return function(h,d,k){var c=f(k.ngClick),w=!1,q,p,s,t;d.on("touchstart",function(a){w=!0;q=a.target?a.target:a.srcElement;3===q.nodeType&&(q=q.parentNode);d.addClass("ng-click-active");p=Date.now();a=a.originalEvent||a;a=(a.touches&&a.touches.length?a.touches:[a])[0];s=a.clientX;t=a.clientY});d.on("touchcancel",function(a){w=!1;d.removeClass("ng-click-active")});
d.on("touchend",function(c){var h=Date.now()-p,f=c.originalEvent||c,m=(f.changedTouches&&f.changedTouches.length?f.changedTouches:f.touches&&f.touches.length?f.touches:[f])[0],f=m.clientX,m=m.clientY,v=Math.sqrt(Math.pow(f-s,2)+Math.pow(m-t,2));w&&750>h&&12>v&&(g||(e[0].addEventListener("click",b,!0),e[0].addEventListener("touchstart",l,!0),g=[]),u=Date.now(),a(g,f,m),q&&q.blur(),n.isDefined(k.disabled)&&!1!==k.disabled||d.triggerHandler("click",[c]));w=!1;d.removeClass("ng-click-active")});d.onclick=
function(a){};d.on("click",function(a,b){h.$apply(function(){c(h,{$event:b||a})})});d.on("mousedown",function(a){d.addClass("ng-click-active")});d.on("mousemove mouseup",function(a){d.removeClass("ng-click-active")})}}];v("ngSwipeLeft",-1,"swipeleft");v("ngSwipeRight",1,"swiperight")})(window,window.angular);
//# sourceMappingURL=angular-touch.min.js.map
| carlosgonzg/intermapa | public/libraries/angular-touch/angular-touch.min.js | JavaScript | mit | 4,041 |
// Copyright (c) 2011 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 CHROME_BROWSER_SYNC_GLUE_PREFERENCE_CHANGE_PROCESSOR_H_
#define CHROME_BROWSER_SYNC_GLUE_PREFERENCE_CHANGE_PROCESSOR_H_
#pragma once
#include <string>
#include "chrome/browser/prefs/pref_change_registrar.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/sync/engine/syncapi.h"
#include "chrome/browser/sync/glue/change_processor.h"
#include "chrome/browser/sync/glue/sync_backend_host.h"
#include "content/common/notification_observer.h"
namespace browser_sync {
class PreferenceModelAssociator;
class UnrecoverableErrorHandler;
// This class is responsible for taking changes from the PrefService and
// applying them to the sync_api 'syncable' model, and vice versa. All
// operations and use of this class are from the UI thread.
class PreferenceChangeProcessor : public ChangeProcessor,
public NotificationObserver {
public:
PreferenceChangeProcessor(PreferenceModelAssociator* model_associator,
UnrecoverableErrorHandler* error_handler);
virtual ~PreferenceChangeProcessor();
// NotificationObserver implementation.
// PrefService -> sync_api model change application.
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
// sync_api model -> PrefService change application.
virtual void ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::SyncManager::ChangeRecord* changes,
int change_count);
protected:
virtual void StartImpl(Profile* profile);
virtual void StopImpl();
private:
Value* ReadPreference(sync_api::ReadNode* node, std::string* name);
void StartObserving();
void StopObserving();
// The model we are processing changes from. Non-NULL when |running_| is true.
PrefService* pref_service_;
// The two models should be associated according to this ModelAssociator.
PreferenceModelAssociator* model_associator_;
// Whether we are currently processing a preference change notification.
bool processing_pref_change_;
PrefChangeRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(PreferenceChangeProcessor);
};
} // namespace browser_sync
#endif // CHROME_BROWSER_SYNC_GLUE_PREFERENCE_CHANGE_PROCESSOR_H_
| xdajog/samsung_sources_i927 | external/chromium/chrome/browser/sync/glue/preference_change_processor.h | C | gpl-2.0 | 2,496 |
package daemon
import (
"errors"
"io"
"os"
"path/filepath"
"strings"
"github.com/docker/docker/builder"
"github.com/docker/docker/container"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/chrootarchive"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/system"
"github.com/docker/engine-api/types"
)
// ErrExtractPointNotDirectory is used to convey that the operation to extract
// a tar archive to a directory in a container has failed because the specified
// path does not refer to a directory.
var ErrExtractPointNotDirectory = errors.New("extraction point is not a directory")
// ContainerCopy performs a deprecated operation of archiving the resource at
// the specified path in the container identified by the given name.
func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, error) {
container, err := daemon.GetContainer(name)
if err != nil {
return nil, err
}
if res[0] == '/' || res[0] == '\\' {
res = res[1:]
}
return daemon.containerCopy(container, res)
}
// ContainerStatPath stats the filesystem resource at the specified path in the
// container identified by the given name.
func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) {
container, err := daemon.GetContainer(name)
if err != nil {
return nil, err
}
return daemon.containerStatPath(container, path)
}
// ContainerArchivePath creates an archive of the filesystem resource at the
// specified path in the container identified by the given name. Returns a
// tar archive of the resource and whether it was a directory or a single file.
func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) {
container, err := daemon.GetContainer(name)
if err != nil {
return nil, nil, err
}
return daemon.containerArchivePath(container, path)
}
// ContainerExtractToDir extracts the given archive to the specified location
// in the filesystem of the container identified by the given name. The given
// path must be of a directory in the container. If it is not, the error will
// be ErrExtractPointNotDirectory. If noOverwriteDirNonDir is true then it will
// be an error if unpacking the given content would cause an existing directory
// to be replaced with a non-directory and vice versa.
func (daemon *Daemon) ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error {
container, err := daemon.GetContainer(name)
if err != nil {
return err
}
return daemon.containerExtractToDir(container, path, noOverwriteDirNonDir, content)
}
// containerStatPath stats the filesystem resource at the specified path in this
// container. Returns stat info about the resource.
func (daemon *Daemon) containerStatPath(container *container.Container, path string) (stat *types.ContainerPathStat, err error) {
container.Lock()
defer container.Unlock()
if err = daemon.Mount(container); err != nil {
return nil, err
}
defer daemon.Unmount(container)
err = daemon.mountVolumes(container)
defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
if err != nil {
return nil, err
}
resolvedPath, absPath, err := container.ResolvePath(path)
if err != nil {
return nil, err
}
return container.StatPath(resolvedPath, absPath)
}
// containerArchivePath creates an archive of the filesystem resource at the specified
// path in this container. Returns a tar archive of the resource and stat info
// about the resource.
func (daemon *Daemon) containerArchivePath(container *container.Container, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) {
container.Lock()
defer func() {
if err != nil {
// Wait to unlock the container until the archive is fully read
// (see the ReadCloseWrapper func below) or if there is an error
// before that occurs.
container.Unlock()
}
}()
if err = daemon.Mount(container); err != nil {
return nil, nil, err
}
defer func() {
if err != nil {
// unmount any volumes
container.UnmountVolumes(true, daemon.LogVolumeEvent)
// unmount the container's rootfs
daemon.Unmount(container)
}
}()
if err = daemon.mountVolumes(container); err != nil {
return nil, nil, err
}
resolvedPath, absPath, err := container.ResolvePath(path)
if err != nil {
return nil, nil, err
}
stat, err = container.StatPath(resolvedPath, absPath)
if err != nil {
return nil, nil, err
}
// We need to rebase the archive entries if the last element of the
// resolved path was a symlink that was evaluated and is now different
// than the requested path. For example, if the given path was "/foo/bar/",
// but it resolved to "/var/lib/docker/containers/{id}/foo/baz/", we want
// to ensure that the archive entries start with "bar" and not "baz". This
// also catches the case when the root directory of the container is
// requested: we want the archive entries to start with "/" and not the
// container ID.
data, err := archive.TarResourceRebase(resolvedPath, filepath.Base(absPath))
if err != nil {
return nil, nil, err
}
content = ioutils.NewReadCloserWrapper(data, func() error {
err := data.Close()
container.UnmountVolumes(true, daemon.LogVolumeEvent)
daemon.Unmount(container)
container.Unlock()
return err
})
daemon.LogContainerEvent(container, "archive-path")
return content, stat, nil
}
// containerExtractToDir extracts the given tar archive to the specified location in the
// filesystem of this container. The given path must be of a directory in the
// container. If it is not, the error will be ErrExtractPointNotDirectory. If
// noOverwriteDirNonDir is true then it will be an error if unpacking the
// given content would cause an existing directory to be replaced with a non-
// directory and vice versa.
func (daemon *Daemon) containerExtractToDir(container *container.Container, path string, noOverwriteDirNonDir bool, content io.Reader) (err error) {
container.Lock()
defer container.Unlock()
if err = daemon.Mount(container); err != nil {
return err
}
defer daemon.Unmount(container)
err = daemon.mountVolumes(container)
defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
if err != nil {
return err
}
// Check if a drive letter supplied, it must be the system drive. No-op except on Windows
path, err = system.CheckSystemDriveAndRemoveDriveLetter(path)
if err != nil {
return err
}
// The destination path needs to be resolved to a host path, with all
// symbolic links followed in the scope of the container's rootfs. Note
// that we do not use `container.ResolvePath(path)` here because we need
// to also evaluate the last path element if it is a symlink. This is so
// that you can extract an archive to a symlink that points to a directory.
// Consider the given path as an absolute path in the container.
absPath := archive.PreserveTrailingDotOrSeparator(filepath.Join(string(filepath.Separator), path), path)
// This will evaluate the last path element if it is a symlink.
resolvedPath, err := container.GetResourcePath(absPath)
if err != nil {
return err
}
stat, err := os.Lstat(resolvedPath)
if err != nil {
return err
}
if !stat.IsDir() {
return ErrExtractPointNotDirectory
}
// Need to check if the path is in a volume. If it is, it cannot be in a
// read-only volume. If it is not in a volume, the container cannot be
// configured with a read-only rootfs.
// Use the resolved path relative to the container rootfs as the new
// absPath. This way we fully follow any symlinks in a volume that may
// lead back outside the volume.
//
// The Windows implementation of filepath.Rel in golang 1.4 does not
// support volume style file path semantics. On Windows when using the
// filter driver, we are guaranteed that the path will always be
// a volume file path.
var baseRel string
if strings.HasPrefix(resolvedPath, `\\?\Volume{`) {
if strings.HasPrefix(resolvedPath, container.BaseFS) {
baseRel = resolvedPath[len(container.BaseFS):]
if baseRel[:1] == `\` {
baseRel = baseRel[1:]
}
}
} else {
baseRel, err = filepath.Rel(container.BaseFS, resolvedPath)
}
if err != nil {
return err
}
// Make it an absolute path.
absPath = filepath.Join(string(filepath.Separator), baseRel)
toVolume, err := checkIfPathIsInAVolume(container, absPath)
if err != nil {
return err
}
if !toVolume && container.HostConfig.ReadonlyRootfs {
return ErrRootFSReadOnly
}
uid, gid := daemon.GetRemappedUIDGID()
options := &archive.TarOptions{
NoOverwriteDirNonDir: noOverwriteDirNonDir,
ChownOpts: &archive.TarChownOptions{
UID: uid, GID: gid, // TODO: should all ownership be set to root (either real or remapped)?
},
}
if err := chrootarchive.Untar(content, resolvedPath, options); err != nil {
return err
}
daemon.LogContainerEvent(container, "extract-to-dir")
return nil
}
func (daemon *Daemon) containerCopy(container *container.Container, resource string) (rc io.ReadCloser, err error) {
container.Lock()
defer func() {
if err != nil {
// Wait to unlock the container until the archive is fully read
// (see the ReadCloseWrapper func below) or if there is an error
// before that occurs.
container.Unlock()
}
}()
if err := daemon.Mount(container); err != nil {
return nil, err
}
defer func() {
if err != nil {
// unmount any volumes
container.UnmountVolumes(true, daemon.LogVolumeEvent)
// unmount the container's rootfs
daemon.Unmount(container)
}
}()
if err := daemon.mountVolumes(container); err != nil {
return nil, err
}
basePath, err := container.GetResourcePath(resource)
if err != nil {
return nil, err
}
stat, err := os.Stat(basePath)
if err != nil {
return nil, err
}
var filter []string
if !stat.IsDir() {
d, f := filepath.Split(basePath)
basePath = d
filter = []string{f}
} else {
filter = []string{filepath.Base(basePath)}
basePath = filepath.Dir(basePath)
}
archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
Compression: archive.Uncompressed,
IncludeFiles: filter,
})
if err != nil {
return nil, err
}
reader := ioutils.NewReadCloserWrapper(archive, func() error {
err := archive.Close()
container.UnmountVolumes(true, daemon.LogVolumeEvent)
daemon.Unmount(container)
container.Unlock()
return err
})
daemon.LogContainerEvent(container, "copy")
return reader, nil
}
// CopyOnBuild copies/extracts a source FileInfo to a destination path inside a container
// specified by a container object.
// TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already).
// CopyOnBuild should take in abstract paths (with slashes) and the implementation should convert it to OS-specific paths.
func (daemon *Daemon) CopyOnBuild(cID string, destPath string, src builder.FileInfo, decompress bool) error {
srcPath := src.Path()
destExists := true
destDir := false
rootUID, rootGID := daemon.GetRemappedUIDGID()
// Work in daemon-local OS specific file paths
destPath = filepath.FromSlash(destPath)
c, err := daemon.GetContainer(cID)
if err != nil {
return err
}
err = daemon.Mount(c)
if err != nil {
return err
}
defer daemon.Unmount(c)
dest, err := c.GetResourcePath(destPath)
if err != nil {
return err
}
// Preserve the trailing slash
// TODO: why are we appending another path separator if there was already one?
if strings.HasSuffix(destPath, string(os.PathSeparator)) || destPath == "." {
destDir = true
dest += string(os.PathSeparator)
}
destPath = dest
destStat, err := os.Stat(destPath)
if err != nil {
if !os.IsNotExist(err) {
//logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err)
return err
}
destExists = false
}
uidMaps, gidMaps := daemon.GetUIDGIDMaps()
archiver := &archive.Archiver{
Untar: chrootarchive.Untar,
UIDMaps: uidMaps,
GIDMaps: gidMaps,
}
if src.IsDir() {
// copy as directory
if err := archiver.CopyWithTar(srcPath, destPath); err != nil {
return err
}
return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
}
if decompress && archive.IsArchivePath(srcPath) {
// Only try to untar if it is a file and that we've been told to decompress (when ADD-ing a remote file)
// First try to unpack the source as an archive
// to support the untar feature we need to clean up the path a little bit
// because tar is very forgiving. First we need to strip off the archive's
// filename from the path but this is only added if it does not end in slash
tarDest := destPath
if strings.HasSuffix(tarDest, string(os.PathSeparator)) {
tarDest = filepath.Dir(destPath)
}
// try to successfully untar the orig
err := archiver.UntarPath(srcPath, tarDest)
/*
if err != nil {
logrus.Errorf("Couldn't untar to %s: %v", tarDest, err)
}
*/
return err
}
// only needed for fixPermissions, but might as well put it before CopyFileWithTar
if destDir || (destExists && destStat.IsDir()) {
destPath = filepath.Join(destPath, src.Name())
}
if err := idtools.MkdirAllNewAs(filepath.Dir(destPath), 0755, rootUID, rootGID); err != nil {
return err
}
if err := archiver.CopyFileWithTar(srcPath, destPath); err != nil {
return err
}
return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
}
| albamc/gorb | vendor/github.com/docker/docker/daemon/archive.go | GO | lgpl-3.0 | 13,485 |
cask 'dsp-radio' do
version '1.4.1'
sha256 'b04ff63d41a47923455499340e32706df83a184c54c590d70191072b8fdbbbc9'
url "https://dl2sdr.homepage.t-online.de/files/DSP_Radio_#{version.delete('.')}.zip"
name 'DSP Radio'
homepage 'https://dl2sdr.homepage.t-online.de/'
license :gratis
app "DSP Radio #{version}.app"
end
| JosephViolago/homebrew-cask | Casks/dsp-radio.rb | Ruby | bsd-2-clause | 327 |
/*
* Copyright (C) 2012 Avionic Design GmbH
* Copyright (C) 2012-2013 NVIDIA CORPORATION. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/host1x.h>
#include "drm.h"
#include "gem.h"
#define DRIVER_NAME "tegra"
#define DRIVER_DESC "NVIDIA Tegra graphics"
#define DRIVER_DATE "20120330"
#define DRIVER_MAJOR 0
#define DRIVER_MINOR 0
#define DRIVER_PATCHLEVEL 0
struct tegra_drm_file {
struct list_head contexts;
};
static int tegra_drm_load(struct drm_device *drm, unsigned long flags)
{
struct host1x_device *device = to_host1x_device(drm->dev);
struct tegra_drm *tegra;
int err;
tegra = kzalloc(sizeof(*tegra), GFP_KERNEL);
if (!tegra)
return -ENOMEM;
dev_set_drvdata(drm->dev, tegra);
mutex_init(&tegra->clients_lock);
INIT_LIST_HEAD(&tegra->clients);
drm->dev_private = tegra;
tegra->drm = drm;
drm_mode_config_init(drm);
err = host1x_device_init(device);
if (err < 0)
return err;
/*
* We don't use the drm_irq_install() helpers provided by the DRM
* core, so we need to set this manually in order to allow the
* DRM_IOCTL_WAIT_VBLANK to operate correctly.
*/
drm->irq_enabled = true;
err = drm_vblank_init(drm, drm->mode_config.num_crtc);
if (err < 0)
return err;
err = tegra_drm_fb_init(drm);
if (err < 0)
return err;
drm_kms_helper_poll_init(drm);
return 0;
}
static int tegra_drm_unload(struct drm_device *drm)
{
struct host1x_device *device = to_host1x_device(drm->dev);
int err;
drm_kms_helper_poll_fini(drm);
tegra_drm_fb_exit(drm);
drm_vblank_cleanup(drm);
drm_mode_config_cleanup(drm);
err = host1x_device_exit(device);
if (err < 0)
return err;
return 0;
}
static int tegra_drm_open(struct drm_device *drm, struct drm_file *filp)
{
struct tegra_drm_file *fpriv;
fpriv = kzalloc(sizeof(*fpriv), GFP_KERNEL);
if (!fpriv)
return -ENOMEM;
INIT_LIST_HEAD(&fpriv->contexts);
filp->driver_priv = fpriv;
return 0;
}
static void tegra_drm_context_free(struct tegra_drm_context *context)
{
context->client->ops->close_channel(context);
kfree(context);
}
static void tegra_drm_lastclose(struct drm_device *drm)
{
struct tegra_drm *tegra = drm->dev_private;
tegra_fbdev_restore_mode(tegra->fbdev);
}
static struct host1x_bo *
host1x_bo_lookup(struct drm_device *drm, struct drm_file *file, u32 handle)
{
struct drm_gem_object *gem;
struct tegra_bo *bo;
gem = drm_gem_object_lookup(drm, file, handle);
if (!gem)
return NULL;
mutex_lock(&drm->struct_mutex);
drm_gem_object_unreference(gem);
mutex_unlock(&drm->struct_mutex);
bo = to_tegra_bo(gem);
return &bo->base;
}
int tegra_drm_submit(struct tegra_drm_context *context,
struct drm_tegra_submit *args, struct drm_device *drm,
struct drm_file *file)
{
unsigned int num_cmdbufs = args->num_cmdbufs;
unsigned int num_relocs = args->num_relocs;
unsigned int num_waitchks = args->num_waitchks;
struct drm_tegra_cmdbuf __user *cmdbufs =
(void __user *)(uintptr_t)args->cmdbufs;
struct drm_tegra_reloc __user *relocs =
(void __user *)(uintptr_t)args->relocs;
struct drm_tegra_waitchk __user *waitchks =
(void __user *)(uintptr_t)args->waitchks;
struct drm_tegra_syncpt syncpt;
struct host1x_job *job;
int err;
/* We don't yet support other than one syncpt_incr struct per submit */
if (args->num_syncpts != 1)
return -EINVAL;
job = host1x_job_alloc(context->channel, args->num_cmdbufs,
args->num_relocs, args->num_waitchks);
if (!job)
return -ENOMEM;
job->num_relocs = args->num_relocs;
job->num_waitchk = args->num_waitchks;
job->client = (u32)args->context;
job->class = context->client->base.class;
job->serialize = true;
while (num_cmdbufs) {
struct drm_tegra_cmdbuf cmdbuf;
struct host1x_bo *bo;
if (copy_from_user(&cmdbuf, cmdbufs, sizeof(cmdbuf))) {
err = -EFAULT;
goto fail;
}
bo = host1x_bo_lookup(drm, file, cmdbuf.handle);
if (!bo) {
err = -ENOENT;
goto fail;
}
host1x_job_add_gather(job, bo, cmdbuf.words, cmdbuf.offset);
num_cmdbufs--;
cmdbufs++;
}
if (copy_from_user(job->relocarray, relocs,
sizeof(*relocs) * num_relocs)) {
err = -EFAULT;
goto fail;
}
while (num_relocs--) {
struct host1x_reloc *reloc = &job->relocarray[num_relocs];
struct host1x_bo *cmdbuf, *target;
cmdbuf = host1x_bo_lookup(drm, file, (u32)reloc->cmdbuf);
target = host1x_bo_lookup(drm, file, (u32)reloc->target);
reloc->cmdbuf = cmdbuf;
reloc->target = target;
if (!reloc->target || !reloc->cmdbuf) {
err = -ENOENT;
goto fail;
}
}
if (copy_from_user(job->waitchk, waitchks,
sizeof(*waitchks) * num_waitchks)) {
err = -EFAULT;
goto fail;
}
if (copy_from_user(&syncpt, (void __user *)(uintptr_t)args->syncpts,
sizeof(syncpt))) {
err = -EFAULT;
goto fail;
}
job->is_addr_reg = context->client->ops->is_addr_reg;
job->syncpt_incrs = syncpt.incrs;
job->syncpt_id = syncpt.id;
job->timeout = 10000;
if (args->timeout && args->timeout < 10000)
job->timeout = args->timeout;
err = host1x_job_pin(job, context->client->base.dev);
if (err)
goto fail;
err = host1x_job_submit(job);
if (err)
goto fail_submit;
args->fence = job->syncpt_end;
host1x_job_put(job);
return 0;
fail_submit:
host1x_job_unpin(job);
fail:
host1x_job_put(job);
return err;
}
#ifdef CONFIG_DRM_TEGRA_STAGING
static struct tegra_drm_context *tegra_drm_get_context(__u64 context)
{
return (struct tegra_drm_context *)(uintptr_t)context;
}
static bool tegra_drm_file_owns_context(struct tegra_drm_file *file,
struct tegra_drm_context *context)
{
struct tegra_drm_context *ctx;
list_for_each_entry(ctx, &file->contexts, list)
if (ctx == context)
return true;
return false;
}
static int tegra_gem_create(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct drm_tegra_gem_create *args = data;
struct tegra_bo *bo;
bo = tegra_bo_create_with_handle(file, drm, args->size, args->flags,
&args->handle);
if (IS_ERR(bo))
return PTR_ERR(bo);
return 0;
}
static int tegra_gem_mmap(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct drm_tegra_gem_mmap *args = data;
struct drm_gem_object *gem;
struct tegra_bo *bo;
gem = drm_gem_object_lookup(drm, file, args->handle);
if (!gem)
return -EINVAL;
bo = to_tegra_bo(gem);
args->offset = drm_vma_node_offset_addr(&bo->gem.vma_node);
drm_gem_object_unreference(gem);
return 0;
}
static int tegra_syncpt_read(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct host1x *host = dev_get_drvdata(drm->dev->parent);
struct drm_tegra_syncpt_read *args = data;
struct host1x_syncpt *sp;
sp = host1x_syncpt_get(host, args->id);
if (!sp)
return -EINVAL;
args->value = host1x_syncpt_read_min(sp);
return 0;
}
static int tegra_syncpt_incr(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct host1x *host1x = dev_get_drvdata(drm->dev->parent);
struct drm_tegra_syncpt_incr *args = data;
struct host1x_syncpt *sp;
sp = host1x_syncpt_get(host1x, args->id);
if (!sp)
return -EINVAL;
return host1x_syncpt_incr(sp);
}
static int tegra_syncpt_wait(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct host1x *host1x = dev_get_drvdata(drm->dev->parent);
struct drm_tegra_syncpt_wait *args = data;
struct host1x_syncpt *sp;
sp = host1x_syncpt_get(host1x, args->id);
if (!sp)
return -EINVAL;
return host1x_syncpt_wait(sp, args->thresh, args->timeout,
&args->value);
}
static int tegra_open_channel(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct tegra_drm_file *fpriv = file->driver_priv;
struct tegra_drm *tegra = drm->dev_private;
struct drm_tegra_open_channel *args = data;
struct tegra_drm_context *context;
struct tegra_drm_client *client;
int err = -ENODEV;
context = kzalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return -ENOMEM;
list_for_each_entry(client, &tegra->clients, list)
if (client->base.class == args->client) {
err = client->ops->open_channel(client, context);
if (err)
break;
list_add(&context->list, &fpriv->contexts);
args->context = (uintptr_t)context;
context->client = client;
return 0;
}
kfree(context);
return err;
}
static int tegra_close_channel(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct tegra_drm_file *fpriv = file->driver_priv;
struct drm_tegra_close_channel *args = data;
struct tegra_drm_context *context;
context = tegra_drm_get_context(args->context);
if (!tegra_drm_file_owns_context(fpriv, context))
return -EINVAL;
list_del(&context->list);
tegra_drm_context_free(context);
return 0;
}
static int tegra_get_syncpt(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct tegra_drm_file *fpriv = file->driver_priv;
struct drm_tegra_get_syncpt *args = data;
struct tegra_drm_context *context;
struct host1x_syncpt *syncpt;
context = tegra_drm_get_context(args->context);
if (!tegra_drm_file_owns_context(fpriv, context))
return -ENODEV;
if (args->index >= context->client->base.num_syncpts)
return -EINVAL;
syncpt = context->client->base.syncpts[args->index];
args->id = host1x_syncpt_id(syncpt);
return 0;
}
static int tegra_submit(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct tegra_drm_file *fpriv = file->driver_priv;
struct drm_tegra_submit *args = data;
struct tegra_drm_context *context;
context = tegra_drm_get_context(args->context);
if (!tegra_drm_file_owns_context(fpriv, context))
return -ENODEV;
return context->client->ops->submit(context, args, drm, file);
}
static int tegra_get_syncpt_base(struct drm_device *drm, void *data,
struct drm_file *file)
{
struct tegra_drm_file *fpriv = file->driver_priv;
struct drm_tegra_get_syncpt_base *args = data;
struct tegra_drm_context *context;
struct host1x_syncpt_base *base;
struct host1x_syncpt *syncpt;
context = tegra_drm_get_context(args->context);
if (!tegra_drm_file_owns_context(fpriv, context))
return -ENODEV;
if (args->syncpt >= context->client->base.num_syncpts)
return -EINVAL;
syncpt = context->client->base.syncpts[args->syncpt];
base = host1x_syncpt_get_base(syncpt);
if (!base)
return -ENXIO;
args->id = host1x_syncpt_base_id(base);
return 0;
}
#endif
static const struct drm_ioctl_desc tegra_drm_ioctls[] = {
#ifdef CONFIG_DRM_TEGRA_STAGING
DRM_IOCTL_DEF_DRV(TEGRA_GEM_CREATE, tegra_gem_create, DRM_UNLOCKED | DRM_AUTH),
DRM_IOCTL_DEF_DRV(TEGRA_GEM_MMAP, tegra_gem_mmap, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_SYNCPT_READ, tegra_syncpt_read, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_SYNCPT_INCR, tegra_syncpt_incr, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_SYNCPT_WAIT, tegra_syncpt_wait, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_OPEN_CHANNEL, tegra_open_channel, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_CLOSE_CHANNEL, tegra_close_channel, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_GET_SYNCPT, tegra_get_syncpt, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_SUBMIT, tegra_submit, DRM_UNLOCKED),
DRM_IOCTL_DEF_DRV(TEGRA_GET_SYNCPT_BASE, tegra_get_syncpt_base, DRM_UNLOCKED),
#endif
};
static const struct file_operations tegra_drm_fops = {
.owner = THIS_MODULE,
.open = drm_open,
.release = drm_release,
.unlocked_ioctl = drm_ioctl,
.mmap = tegra_drm_mmap,
.poll = drm_poll,
.read = drm_read,
#ifdef CONFIG_COMPAT
.compat_ioctl = drm_compat_ioctl,
#endif
.llseek = noop_llseek,
};
static struct drm_crtc *tegra_crtc_from_pipe(struct drm_device *drm, int pipe)
{
struct drm_crtc *crtc;
list_for_each_entry(crtc, &drm->mode_config.crtc_list, head) {
struct tegra_dc *dc = to_tegra_dc(crtc);
if (dc->pipe == pipe)
return crtc;
}
return NULL;
}
static u32 tegra_drm_get_vblank_counter(struct drm_device *dev, int crtc)
{
/* TODO: implement real hardware counter using syncpoints */
return drm_vblank_count(dev, crtc);
}
static int tegra_drm_enable_vblank(struct drm_device *drm, int pipe)
{
struct drm_crtc *crtc = tegra_crtc_from_pipe(drm, pipe);
struct tegra_dc *dc = to_tegra_dc(crtc);
if (!crtc)
return -ENODEV;
tegra_dc_enable_vblank(dc);
return 0;
}
static void tegra_drm_disable_vblank(struct drm_device *drm, int pipe)
{
struct drm_crtc *crtc = tegra_crtc_from_pipe(drm, pipe);
struct tegra_dc *dc = to_tegra_dc(crtc);
if (crtc)
tegra_dc_disable_vblank(dc);
}
static void tegra_drm_preclose(struct drm_device *drm, struct drm_file *file)
{
struct tegra_drm_file *fpriv = file->driver_priv;
struct tegra_drm_context *context, *tmp;
struct drm_crtc *crtc;
list_for_each_entry(crtc, &drm->mode_config.crtc_list, head)
tegra_dc_cancel_page_flip(crtc, file);
list_for_each_entry_safe(context, tmp, &fpriv->contexts, list)
tegra_drm_context_free(context);
kfree(fpriv);
}
#ifdef CONFIG_DEBUG_FS
static int tegra_debugfs_framebuffers(struct seq_file *s, void *data)
{
struct drm_info_node *node = (struct drm_info_node *)s->private;
struct drm_device *drm = node->minor->dev;
struct drm_framebuffer *fb;
mutex_lock(&drm->mode_config.fb_lock);
list_for_each_entry(fb, &drm->mode_config.fb_list, head) {
seq_printf(s, "%3d: user size: %d x %d, depth %d, %d bpp, refcount %d\n",
fb->base.id, fb->width, fb->height, fb->depth,
fb->bits_per_pixel,
atomic_read(&fb->refcount.refcount));
}
mutex_unlock(&drm->mode_config.fb_lock);
return 0;
}
static struct drm_info_list tegra_debugfs_list[] = {
{ "framebuffers", tegra_debugfs_framebuffers, 0 },
};
static int tegra_debugfs_init(struct drm_minor *minor)
{
return drm_debugfs_create_files(tegra_debugfs_list,
ARRAY_SIZE(tegra_debugfs_list),
minor->debugfs_root, minor);
}
static void tegra_debugfs_cleanup(struct drm_minor *minor)
{
drm_debugfs_remove_files(tegra_debugfs_list,
ARRAY_SIZE(tegra_debugfs_list), minor);
}
#endif
static struct drm_driver tegra_drm_driver = {
.driver_features = DRIVER_MODESET | DRIVER_GEM,
.load = tegra_drm_load,
.unload = tegra_drm_unload,
.open = tegra_drm_open,
.preclose = tegra_drm_preclose,
.lastclose = tegra_drm_lastclose,
.get_vblank_counter = tegra_drm_get_vblank_counter,
.enable_vblank = tegra_drm_enable_vblank,
.disable_vblank = tegra_drm_disable_vblank,
#if defined(CONFIG_DEBUG_FS)
.debugfs_init = tegra_debugfs_init,
.debugfs_cleanup = tegra_debugfs_cleanup,
#endif
.gem_free_object = tegra_bo_free_object,
.gem_vm_ops = &tegra_bo_vm_ops,
.dumb_create = tegra_bo_dumb_create,
.dumb_map_offset = tegra_bo_dumb_map_offset,
.dumb_destroy = drm_gem_dumb_destroy,
.ioctls = tegra_drm_ioctls,
.num_ioctls = ARRAY_SIZE(tegra_drm_ioctls),
.fops = &tegra_drm_fops,
.name = DRIVER_NAME,
.desc = DRIVER_DESC,
.date = DRIVER_DATE,
.major = DRIVER_MAJOR,
.minor = DRIVER_MINOR,
.patchlevel = DRIVER_PATCHLEVEL,
};
int tegra_drm_register_client(struct tegra_drm *tegra,
struct tegra_drm_client *client)
{
mutex_lock(&tegra->clients_lock);
list_add_tail(&client->list, &tegra->clients);
mutex_unlock(&tegra->clients_lock);
return 0;
}
int tegra_drm_unregister_client(struct tegra_drm *tegra,
struct tegra_drm_client *client)
{
mutex_lock(&tegra->clients_lock);
list_del_init(&client->list);
mutex_unlock(&tegra->clients_lock);
return 0;
}
static int host1x_drm_probe(struct host1x_device *device)
{
return drm_host1x_init(&tegra_drm_driver, device);
}
static int host1x_drm_remove(struct host1x_device *device)
{
drm_host1x_exit(&tegra_drm_driver, device);
return 0;
}
static const struct of_device_id host1x_drm_subdevs[] = {
{ .compatible = "nvidia,tegra20-dc", },
{ .compatible = "nvidia,tegra20-hdmi", },
{ .compatible = "nvidia,tegra20-gr2d", },
{ .compatible = "nvidia,tegra20-gr3d", },
{ .compatible = "nvidia,tegra30-dc", },
{ .compatible = "nvidia,tegra30-hdmi", },
{ .compatible = "nvidia,tegra30-gr2d", },
{ .compatible = "nvidia,tegra30-gr3d", },
{ .compatible = "nvidia,tegra114-hdmi", },
{ .compatible = "nvidia,tegra114-gr3d", },
{ /* sentinel */ }
};
static struct host1x_driver host1x_drm_driver = {
.name = "drm",
.probe = host1x_drm_probe,
.remove = host1x_drm_remove,
.subdevs = host1x_drm_subdevs,
};
static int __init host1x_drm_init(void)
{
int err;
err = host1x_driver_register(&host1x_drm_driver);
if (err < 0)
return err;
err = platform_driver_register(&tegra_dc_driver);
if (err < 0)
goto unregister_host1x;
err = platform_driver_register(&tegra_hdmi_driver);
if (err < 0)
goto unregister_dc;
err = platform_driver_register(&tegra_gr2d_driver);
if (err < 0)
goto unregister_hdmi;
err = platform_driver_register(&tegra_gr3d_driver);
if (err < 0)
goto unregister_gr2d;
return 0;
unregister_gr2d:
platform_driver_unregister(&tegra_gr2d_driver);
unregister_hdmi:
platform_driver_unregister(&tegra_hdmi_driver);
unregister_dc:
platform_driver_unregister(&tegra_dc_driver);
unregister_host1x:
host1x_driver_unregister(&host1x_drm_driver);
return err;
}
module_init(host1x_drm_init);
static void __exit host1x_drm_exit(void)
{
platform_driver_unregister(&tegra_gr3d_driver);
platform_driver_unregister(&tegra_gr2d_driver);
platform_driver_unregister(&tegra_hdmi_driver);
platform_driver_unregister(&tegra_dc_driver);
host1x_driver_unregister(&host1x_drm_driver);
}
module_exit(host1x_drm_exit);
MODULE_AUTHOR("Thierry Reding <thierry.reding@avionic-design.de>");
MODULE_DESCRIPTION("NVIDIA Tegra DRM driver");
MODULE_LICENSE("GPL v2");
| ziqiaozhou/cachebar | source/drivers/gpu/drm/tegra/drm.c | C | gpl-2.0 | 17,587 |
/* Copyright (C) 1993, 1995, 1996, 1997 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1993.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#include <errno.h>
#include <malloc.h>
#include <string.h>
#define __USE_GNU
#ifndef __set_errno
#define __set_errno(e) errno = (e)
#endif
#include <search.h>
/* [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
[Knuth] The Art of Computer Programming, part 3 (6.4) */
/* The reentrant version has no static variables to maintain the state.
Instead the interface of all functions is extended to take an argument
which describes the current status. */
typedef struct _ENTRY
{
unsigned int used;
ENTRY entry;
}
_ENTRY;
/* For the used double hash method the table size has to be a prime. To
correct the user given table size we need a prime test. This trivial
algorithm is adequate because
a) the code is (most probably) called a few times per program run and
b) the number is small because the table must fit in the core */
static int
isprime (unsigned int number)
{
/* no even number will be passed */
unsigned int div = 3;
while (div * div < number && number % div != 0)
div += 2;
return number % div != 0;
}
/* Before using the hash table we must allocate memory for it.
Test for an existing table are done. We allocate one element
more as the found prime number says. This is done for more effective
indexing as explained in the comment for the hsearch function.
The contents of the table is zeroed, especially the field used
becomes zero. */
int
hcreate_r (nel, htab)
size_t nel;
struct hsearch_data *htab;
{
/* Test for correct arguments. */
if (htab == NULL)
{
__set_errno (EINVAL);
return 0;
}
/* There is still another table active. Return with error. */
if (htab->table != NULL)
return 0;
/* Change nel to the first prime number not smaller as nel. */
nel |= 1; /* make odd */
while (!isprime (nel))
nel += 2;
htab->size = nel;
htab->filled = 0;
/* allocate memory and zero out */
htab->table = (_ENTRY *) calloc (htab->size + 1, sizeof (_ENTRY));
if (htab->table == NULL)
return 0;
/* everything went alright */
return 1;
}
/* After using the hash table it has to be destroyed. The used memory can
be freed and the local static variable can be marked as not used. */
void
hdestroy_r (htab)
struct hsearch_data *htab;
{
/* Test for correct arguments. */
if (htab == NULL)
{
__set_errno (EINVAL);
return;
}
if (htab->table != NULL)
/* free used memory */
free (htab->table);
/* the sign for an existing table is an value != NULL in htable */
htab->table = NULL;
}
/* This is the search function. It uses double hashing with open addressing.
The argument item.key has to be a pointer to an zero terminated, most
probably strings of chars. The function for generating a number of the
strings is simple but fast. It can be replaced by a more complex function
like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
We use an trick to speed up the lookup. The table is created by hcreate
with one more element available. This enables us to use the index zero
special. This index will never be used because we store the first hash
index in the field used where zero means not used. Every other value
means used. The used field can be used as a first fast comparison for
equality of the stored and the parameter value. This helps to prevent
unnecessary expensive calls of strcmp. */
int
hsearch_r (item, action, retval, htab)
ENTRY item;
ACTION action;
ENTRY **retval;
struct hsearch_data *htab;
{
unsigned int hval;
unsigned int count;
unsigned int len = strlen (item.key);
unsigned int idx;
/* Compute an value for the given string. Perhaps use a better method. */
hval = len;
count = len;
while (count-- > 0)
{
hval <<= 4;
hval += item.key[count];
}
/* First hash function: simply take the modulo but prevent zero. */
hval %= htab->size;
if (hval == 0)
++hval;
/* The first index tried. */
idx = hval;
if (htab->table[idx].used)
{
/* Further action might be required according to the action value. */
unsigned hval2;
if (htab->table[idx].used == hval
&& strcmp (item.key, htab->table[idx].entry.key) == 0)
{
if (action == ENTER)
htab->table[idx].entry.data = item.data;
*retval = &htab->table[idx].entry;
return 1;
}
/* Second hash function, as suggested in [Knuth] */
hval2 = 1 + hval % (htab->size - 2);
do
{
/* Because SIZE is prime this guarantees to step through all
available indexes. */
if (idx <= hval2)
idx = htab->size + idx - hval2;
else
idx -= hval2;
/* If we visited all entries leave the loop unsuccessfully. */
if (idx == hval)
break;
/* If entry is found use it. */
if (htab->table[idx].used == hval
&& strcmp (item.key, htab->table[idx].entry.key) == 0)
{
if (action == ENTER)
htab->table[idx].entry.data = item.data;
*retval = &htab->table[idx].entry;
return 1;
}
}
while (htab->table[idx].used);
}
/* An empty bucket has been found. */
if (action == ENTER)
{
/* If table is full and another entry should be entered return
with error. */
if (action == ENTER && htab->filled == htab->size)
{
__set_errno (ENOMEM);
*retval = NULL;
return 0;
}
htab->table[idx].used = hval;
htab->table[idx].entry = item;
++htab->filled;
*retval = &htab->table[idx].entry;
return 1;
}
__set_errno (ESRCH);
*retval = NULL;
return 0;
}
| voku/external-alsa-lib | src/compat/hsearch_r.c | C | lgpl-2.1 | 6,640 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.mock;
import com.intellij.lang.FileASTNode;
import com.intellij.lang.Language;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MockPsiFile extends MockPsiElement implements PsiFile {
private final long myModStamp = LocalTimeCounter.currentTime();
private VirtualFile myVirtualFile = null;
public boolean valid = true;
public String text = "";
private final FileViewProvider myFileViewProvider;
private final PsiManager myPsiManager;
public MockPsiFile(@NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), new LightVirtualFile("noname", getFileType(), ""));
}
public MockPsiFile(@NotNull VirtualFile virtualFile, @NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myVirtualFile = virtualFile;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), virtualFile);
}
@Override
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@Override
public boolean processChildren(final PsiElementProcessor<PsiFileSystemItem> processor) {
return true;
}
@Override
@NotNull
public String getName() {
return "mock.file";
}
@Override
@Nullable
public ItemPresentation getPresentation() {
return null;
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public void checkSetName(String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public PsiDirectory getContainingDirectory() {
return null;
}
@Nullable
public PsiDirectory getParentDirectory() {
throw new UnsupportedOperationException("Method getParentDirectory is not yet implemented in " + getClass().getName());
}
@Override
public long getModificationStamp() {
return myModStamp;
}
@Override
@NotNull
public PsiFile getOriginalFile() {
return this;
}
@Override
@NotNull
public FileType getFileType() {
return StdFileTypes.JAVA;
}
@Override
@NotNull
public Language getLanguage() {
return StdFileTypes.JAVA.getLanguage();
}
@Override
@NotNull
public PsiFile[] getPsiRoots() {
return new PsiFile[]{this};
}
@Override
@NotNull
public FileViewProvider getViewProvider() {
return myFileViewProvider;
}
@Override
public PsiManager getManager() {
return myPsiManager;
}
@Override
@NotNull
public PsiElement[] getChildren() {
return PsiElement.EMPTY_ARRAY;
}
@Override
public PsiDirectory getParent() {
return null;
}
@Override
public PsiElement getFirstChild() {
return null;
}
@Override
public PsiElement getLastChild() {
return null;
}
@Override
public void acceptChildren(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement getNextSibling() {
return null;
}
@Override
public PsiElement getPrevSibling() {
return null;
}
@Override
public PsiFile getContainingFile() {
return null;
}
@Override
public TextRange getTextRange() {
return null;
}
@Override
public int getStartOffsetInParent() {
return 0;
}
@Override
public int getTextLength() {
return 0;
}
@Override
public PsiElement findElementAt(int offset) {
return null;
}
@Override
public PsiReference findReferenceAt(int offset) {
return null;
}
@Override
public int getTextOffset() {
return 0;
}
@Override
public String getText() {
return text;
}
@Override
@NotNull
public char[] textToCharArray() {
return ArrayUtil.EMPTY_CHAR_ARRAY;
}
@Override
public boolean textMatches(@NotNull CharSequence text) {
return false;
}
@Override
public boolean textMatches(@NotNull PsiElement element) {
return false;
}
@Override
public boolean textContains(char c) {
return false;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement copy() {
return null;
}
@Override
public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException {
}
@Override
public PsiElement addRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeBefore(@NotNull PsiElement first, @NotNull PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeAfter(PsiElement first, PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public void delete() throws IncorrectOperationException {
}
@Override
public void checkDelete() throws IncorrectOperationException {
}
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
}
@Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
return null;
}
@Override
public boolean isValid() {
return valid;
}
@Override
public boolean isWritable() {
return false;
}
@Override
public PsiReference getReference() {
return null;
}
@Override
@NotNull
public PsiReference[] getReferences() {
return PsiReference.EMPTY_ARRAY;
}
@Override
public <T> T getCopyableUserData(@NotNull Key<T> key) {
return null;
}
@Override
public <T> void putCopyableUserData(@NotNull Key<T> key, T value) {
}
@Override
@NotNull
public Project getProject() {
final PsiManager manager = getManager();
if (manager == null) throw new PsiInvalidElementAccessException(this);
return manager.getProject();
}
@Override
public boolean isPhysical() {
return true;
}
@Override
public PsiElement getNavigationElement() {
return this;
}
@Override
public PsiElement getOriginalElement() {
return this;
}
@Override
@NotNull
public GlobalSearchScope getResolveScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
@NotNull
public SearchScope getUseScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
public FileASTNode getNode() {
return null;
}
@Override
public void subtreeChanged() {
}
@Override
public void navigate(boolean requestFocus) {
}
@Override
public boolean canNavigate() {
return false;
}
@Override
public boolean canNavigateToSource() {
return false;
}
@Override
public PsiElement getContext() {
return FileContextUtil.getFileContext(this);
}
}
| idea4bsd/idea4bsd | platform/testFramework/src/com/intellij/mock/MockPsiFile.java | Java | apache-2.0 | 8,673 |
#miniTip,#miniTip_a{position:absolute;top:0;left:0}#miniTip{background-color:#262626;max-width:250px;color:#fff;display:none;border-radius:3;opacity:.95;border:4px solid #000}#miniTip .bottom,#miniTip .top{border-left:8px solid transparent;border-right:8px solid transparent}#miniTip_a{width:0;height:0}#miniTip .top{border-top:8px solid #000;border-bottom:0}#miniTip .bottom{border-bottom:8px solid #000;border-top:0}#miniTip .left,#miniTip .right{border-bottom:8px solid transparent;border-top:8px solid transparent}#miniTip .right{border-right:8px solid #000;border-left:0}#miniTip .left{border-left:8px solid #000;border-right:0}#miniTip_t{padding:4 6;background-color:#191919;font-weight:700}#miniTip_c{padding:6px}
| dc-js/cdnjs | ajax/libs/miniTip/0.3/miniTip.min.css | CSS | mit | 721 |
/*******************************************************************************
*
* Copyright (c) 2015-2016 Intel Corporation. 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
* OpenFabrics.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 "i40iw_osdep.h"
#include "i40iw_register.h"
#include "i40iw_status.h"
#include "i40iw_hmc.h"
#include "i40iw_d.h"
#include "i40iw_type.h"
#include "i40iw_p.h"
#include "i40iw_virtchnl.h"
/**
* vchnl_vf_send_get_ver_req - Request Channel version
* @dev: IWARP device pointer
* @vchnl_req: Virtual channel message request pointer
*/
static enum i40iw_status_code vchnl_vf_send_get_ver_req(struct i40iw_sc_dev *dev,
struct i40iw_virtchnl_req *vchnl_req)
{
enum i40iw_status_code ret_code = I40IW_ERR_NOT_READY;
struct i40iw_virtchnl_op_buf *vchnl_msg = vchnl_req->vchnl_msg;
if (!dev->vchnl_up)
return ret_code;
memset(vchnl_msg, 0, sizeof(*vchnl_msg));
vchnl_msg->iw_chnl_op_ctx = (uintptr_t)vchnl_req;
vchnl_msg->iw_chnl_buf_len = sizeof(*vchnl_msg);
vchnl_msg->iw_op_code = I40IW_VCHNL_OP_GET_VER;
vchnl_msg->iw_op_ver = I40IW_VCHNL_OP_GET_VER_V0;
ret_code = dev->vchnl_if.vchnl_send(dev, 0, (u8 *)vchnl_msg, vchnl_msg->iw_chnl_buf_len);
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
return ret_code;
}
/**
* vchnl_vf_send_get_hmc_fcn_req - Request HMC Function from VF
* @dev: IWARP device pointer
* @vchnl_req: Virtual channel message request pointer
*/
static enum i40iw_status_code vchnl_vf_send_get_hmc_fcn_req(struct i40iw_sc_dev *dev,
struct i40iw_virtchnl_req *vchnl_req)
{
enum i40iw_status_code ret_code = I40IW_ERR_NOT_READY;
struct i40iw_virtchnl_op_buf *vchnl_msg = vchnl_req->vchnl_msg;
if (!dev->vchnl_up)
return ret_code;
memset(vchnl_msg, 0, sizeof(*vchnl_msg));
vchnl_msg->iw_chnl_op_ctx = (uintptr_t)vchnl_req;
vchnl_msg->iw_chnl_buf_len = sizeof(*vchnl_msg);
vchnl_msg->iw_op_code = I40IW_VCHNL_OP_GET_HMC_FCN;
vchnl_msg->iw_op_ver = I40IW_VCHNL_OP_GET_HMC_FCN_V0;
ret_code = dev->vchnl_if.vchnl_send(dev, 0, (u8 *)vchnl_msg, vchnl_msg->iw_chnl_buf_len);
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
return ret_code;
}
/**
* vchnl_vf_send_get_pe_stats_req - Request PE stats from VF
* @dev: IWARP device pointer
* @vchnl_req: Virtual channel message request pointer
*/
static enum i40iw_status_code vchnl_vf_send_get_pe_stats_req(struct i40iw_sc_dev *dev,
struct i40iw_virtchnl_req *vchnl_req)
{
enum i40iw_status_code ret_code = I40IW_ERR_NOT_READY;
struct i40iw_virtchnl_op_buf *vchnl_msg = vchnl_req->vchnl_msg;
if (!dev->vchnl_up)
return ret_code;
memset(vchnl_msg, 0, sizeof(*vchnl_msg));
vchnl_msg->iw_chnl_op_ctx = (uintptr_t)vchnl_req;
vchnl_msg->iw_chnl_buf_len = sizeof(*vchnl_msg) + sizeof(struct i40iw_dev_hw_stats) - 1;
vchnl_msg->iw_op_code = I40IW_VCHNL_OP_GET_STATS;
vchnl_msg->iw_op_ver = I40IW_VCHNL_OP_GET_STATS_V0;
ret_code = dev->vchnl_if.vchnl_send(dev, 0, (u8 *)vchnl_msg, vchnl_msg->iw_chnl_buf_len);
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
return ret_code;
}
/**
* vchnl_vf_send_add_hmc_objs_req - Add HMC objects
* @dev: IWARP device pointer
* @vchnl_req: Virtual channel message request pointer
*/
static enum i40iw_status_code vchnl_vf_send_add_hmc_objs_req(struct i40iw_sc_dev *dev,
struct i40iw_virtchnl_req *vchnl_req,
enum i40iw_hmc_rsrc_type rsrc_type,
u32 start_index,
u32 rsrc_count)
{
enum i40iw_status_code ret_code = I40IW_ERR_NOT_READY;
struct i40iw_virtchnl_op_buf *vchnl_msg = vchnl_req->vchnl_msg;
struct i40iw_virtchnl_hmc_obj_range *add_hmc_obj;
if (!dev->vchnl_up)
return ret_code;
add_hmc_obj = (struct i40iw_virtchnl_hmc_obj_range *)vchnl_msg->iw_chnl_buf;
memset(vchnl_msg, 0, sizeof(*vchnl_msg));
memset(add_hmc_obj, 0, sizeof(*add_hmc_obj));
vchnl_msg->iw_chnl_op_ctx = (uintptr_t)vchnl_req;
vchnl_msg->iw_chnl_buf_len = sizeof(*vchnl_msg) + sizeof(struct i40iw_virtchnl_hmc_obj_range) - 1;
vchnl_msg->iw_op_code = I40IW_VCHNL_OP_ADD_HMC_OBJ_RANGE;
vchnl_msg->iw_op_ver = I40IW_VCHNL_OP_ADD_HMC_OBJ_RANGE_V0;
add_hmc_obj->obj_type = (u16)rsrc_type;
add_hmc_obj->start_index = start_index;
add_hmc_obj->obj_count = rsrc_count;
ret_code = dev->vchnl_if.vchnl_send(dev, 0, (u8 *)vchnl_msg, vchnl_msg->iw_chnl_buf_len);
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
return ret_code;
}
/**
* vchnl_vf_send_del_hmc_objs_req - del HMC objects
* @dev: IWARP device pointer
* @vchnl_req: Virtual channel message request pointer
* @ rsrc_type - resource type to delete
* @ start_index - starting index for resource
* @ rsrc_count - number of resource type to delete
*/
static enum i40iw_status_code vchnl_vf_send_del_hmc_objs_req(struct i40iw_sc_dev *dev,
struct i40iw_virtchnl_req *vchnl_req,
enum i40iw_hmc_rsrc_type rsrc_type,
u32 start_index,
u32 rsrc_count)
{
enum i40iw_status_code ret_code = I40IW_ERR_NOT_READY;
struct i40iw_virtchnl_op_buf *vchnl_msg = vchnl_req->vchnl_msg;
struct i40iw_virtchnl_hmc_obj_range *add_hmc_obj;
if (!dev->vchnl_up)
return ret_code;
add_hmc_obj = (struct i40iw_virtchnl_hmc_obj_range *)vchnl_msg->iw_chnl_buf;
memset(vchnl_msg, 0, sizeof(*vchnl_msg));
memset(add_hmc_obj, 0, sizeof(*add_hmc_obj));
vchnl_msg->iw_chnl_op_ctx = (uintptr_t)vchnl_req;
vchnl_msg->iw_chnl_buf_len = sizeof(*vchnl_msg) + sizeof(struct i40iw_virtchnl_hmc_obj_range) - 1;
vchnl_msg->iw_op_code = I40IW_VCHNL_OP_DEL_HMC_OBJ_RANGE;
vchnl_msg->iw_op_ver = I40IW_VCHNL_OP_DEL_HMC_OBJ_RANGE_V0;
add_hmc_obj->obj_type = (u16)rsrc_type;
add_hmc_obj->start_index = start_index;
add_hmc_obj->obj_count = rsrc_count;
ret_code = dev->vchnl_if.vchnl_send(dev, 0, (u8 *)vchnl_msg, vchnl_msg->iw_chnl_buf_len);
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
return ret_code;
}
/**
* vchnl_pf_send_get_ver_resp - Send channel version to VF
* @dev: IWARP device pointer
* @vf_id: Virtual function ID associated with the message
* @vchnl_msg: Virtual channel message buffer pointer
*/
static void vchnl_pf_send_get_ver_resp(struct i40iw_sc_dev *dev,
u32 vf_id,
struct i40iw_virtchnl_op_buf *vchnl_msg)
{
enum i40iw_status_code ret_code;
u8 resp_buffer[sizeof(struct i40iw_virtchnl_resp_buf) + sizeof(u32) - 1];
struct i40iw_virtchnl_resp_buf *vchnl_msg_resp = (struct i40iw_virtchnl_resp_buf *)resp_buffer;
memset(resp_buffer, 0, sizeof(*resp_buffer));
vchnl_msg_resp->iw_chnl_op_ctx = vchnl_msg->iw_chnl_op_ctx;
vchnl_msg_resp->iw_chnl_buf_len = sizeof(resp_buffer);
vchnl_msg_resp->iw_op_ret_code = I40IW_SUCCESS;
*((u32 *)vchnl_msg_resp->iw_chnl_buf) = I40IW_VCHNL_CHNL_VER_V0;
ret_code = dev->vchnl_if.vchnl_send(dev, vf_id, resp_buffer, sizeof(resp_buffer));
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
}
/**
* vchnl_pf_send_get_hmc_fcn_resp - Send HMC Function to VF
* @dev: IWARP device pointer
* @vf_id: Virtual function ID associated with the message
* @vchnl_msg: Virtual channel message buffer pointer
*/
static void vchnl_pf_send_get_hmc_fcn_resp(struct i40iw_sc_dev *dev,
u32 vf_id,
struct i40iw_virtchnl_op_buf *vchnl_msg,
u16 hmc_fcn)
{
enum i40iw_status_code ret_code;
u8 resp_buffer[sizeof(struct i40iw_virtchnl_resp_buf) + sizeof(u16) - 1];
struct i40iw_virtchnl_resp_buf *vchnl_msg_resp = (struct i40iw_virtchnl_resp_buf *)resp_buffer;
memset(resp_buffer, 0, sizeof(*resp_buffer));
vchnl_msg_resp->iw_chnl_op_ctx = vchnl_msg->iw_chnl_op_ctx;
vchnl_msg_resp->iw_chnl_buf_len = sizeof(resp_buffer);
vchnl_msg_resp->iw_op_ret_code = I40IW_SUCCESS;
*((u16 *)vchnl_msg_resp->iw_chnl_buf) = hmc_fcn;
ret_code = dev->vchnl_if.vchnl_send(dev, vf_id, resp_buffer, sizeof(resp_buffer));
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
}
/**
* vchnl_pf_send_get_pe_stats_resp - Send PE Stats to VF
* @dev: IWARP device pointer
* @vf_id: Virtual function ID associated with the message
* @vchnl_msg: Virtual channel message buffer pointer
* @hw_stats: HW Stats struct
*/
static void vchnl_pf_send_get_pe_stats_resp(struct i40iw_sc_dev *dev,
u32 vf_id,
struct i40iw_virtchnl_op_buf *vchnl_msg,
struct i40iw_dev_hw_stats *hw_stats)
{
enum i40iw_status_code ret_code;
u8 resp_buffer[sizeof(struct i40iw_virtchnl_resp_buf) + sizeof(struct i40iw_dev_hw_stats) - 1];
struct i40iw_virtchnl_resp_buf *vchnl_msg_resp = (struct i40iw_virtchnl_resp_buf *)resp_buffer;
memset(resp_buffer, 0, sizeof(*resp_buffer));
vchnl_msg_resp->iw_chnl_op_ctx = vchnl_msg->iw_chnl_op_ctx;
vchnl_msg_resp->iw_chnl_buf_len = sizeof(resp_buffer);
vchnl_msg_resp->iw_op_ret_code = I40IW_SUCCESS;
*((struct i40iw_dev_hw_stats *)vchnl_msg_resp->iw_chnl_buf) = *hw_stats;
ret_code = dev->vchnl_if.vchnl_send(dev, vf_id, resp_buffer, sizeof(resp_buffer));
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
}
/**
* vchnl_pf_send_error_resp - Send an error response to VF
* @dev: IWARP device pointer
* @vf_id: Virtual function ID associated with the message
* @vchnl_msg: Virtual channel message buffer pointer
*/
static void vchnl_pf_send_error_resp(struct i40iw_sc_dev *dev, u32 vf_id,
struct i40iw_virtchnl_op_buf *vchnl_msg,
u16 op_ret_code)
{
enum i40iw_status_code ret_code;
u8 resp_buffer[sizeof(struct i40iw_virtchnl_resp_buf)];
struct i40iw_virtchnl_resp_buf *vchnl_msg_resp = (struct i40iw_virtchnl_resp_buf *)resp_buffer;
memset(resp_buffer, 0, sizeof(resp_buffer));
vchnl_msg_resp->iw_chnl_op_ctx = vchnl_msg->iw_chnl_op_ctx;
vchnl_msg_resp->iw_chnl_buf_len = sizeof(resp_buffer);
vchnl_msg_resp->iw_op_ret_code = (u16)op_ret_code;
ret_code = dev->vchnl_if.vchnl_send(dev, vf_id, resp_buffer, sizeof(resp_buffer));
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: virt channel send failed 0x%x\n", __func__, ret_code);
}
/**
* pf_cqp_get_hmc_fcn_callback - Callback for Get HMC Fcn
* @cqp_req_param: CQP Request param value
* @not_used: unused CQP callback parameter
*/
static void pf_cqp_get_hmc_fcn_callback(struct i40iw_sc_dev *dev, void *callback_param,
struct i40iw_ccq_cqe_info *cqe_info)
{
struct i40iw_vfdev *vf_dev = callback_param;
struct i40iw_virt_mem vf_dev_mem;
if (cqe_info->error) {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"CQP Completion Error on Get HMC Function. Maj = 0x%04x, Minor = 0x%04x\n",
cqe_info->maj_err_code, cqe_info->min_err_code);
dev->vf_dev[vf_dev->iw_vf_idx] = NULL;
vchnl_pf_send_error_resp(dev, vf_dev->vf_id, &vf_dev->vf_msg_buffer.vchnl_msg,
(u16)I40IW_ERR_CQP_COMPL_ERROR);
vf_dev_mem.va = vf_dev;
vf_dev_mem.size = sizeof(*vf_dev);
i40iw_free_virt_mem(dev->hw, &vf_dev_mem);
} else {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"CQP Completion Operation Return information = 0x%08x\n",
cqe_info->op_ret_val);
vf_dev->pmf_index = (u16)cqe_info->op_ret_val;
vf_dev->msg_count--;
vchnl_pf_send_get_hmc_fcn_resp(dev,
vf_dev->vf_id,
&vf_dev->vf_msg_buffer.vchnl_msg,
vf_dev->pmf_index);
}
}
/**
* pf_add_hmc_obj - Callback for Add HMC Object
* @vf_dev: pointer to the VF Device
*/
static void pf_add_hmc_obj_callback(void *work_vf_dev)
{
struct i40iw_vfdev *vf_dev = (struct i40iw_vfdev *)work_vf_dev;
struct i40iw_hmc_info *hmc_info = &vf_dev->hmc_info;
struct i40iw_virtchnl_op_buf *vchnl_msg = &vf_dev->vf_msg_buffer.vchnl_msg;
struct i40iw_hmc_create_obj_info info;
struct i40iw_virtchnl_hmc_obj_range *add_hmc_obj;
enum i40iw_status_code ret_code;
if (!vf_dev->pf_hmc_initialized) {
ret_code = i40iw_pf_init_vfhmc(vf_dev->pf_dev, (u8)vf_dev->pmf_index, NULL);
if (ret_code)
goto add_out;
vf_dev->pf_hmc_initialized = true;
}
add_hmc_obj = (struct i40iw_virtchnl_hmc_obj_range *)vchnl_msg->iw_chnl_buf;
memset(&info, 0, sizeof(info));
info.hmc_info = hmc_info;
info.is_pf = false;
info.rsrc_type = (u32)add_hmc_obj->obj_type;
info.entry_type = (info.rsrc_type == I40IW_HMC_IW_PBLE) ? I40IW_SD_TYPE_PAGED : I40IW_SD_TYPE_DIRECT;
info.start_idx = add_hmc_obj->start_index;
info.count = add_hmc_obj->obj_count;
i40iw_debug(vf_dev->pf_dev, I40IW_DEBUG_VIRT,
"I40IW_VCHNL_OP_ADD_HMC_OBJ_RANGE. Add %u type %u objects\n",
info.count, info.rsrc_type);
ret_code = i40iw_sc_create_hmc_obj(vf_dev->pf_dev, &info);
if (!ret_code)
vf_dev->hmc_info.hmc_obj[add_hmc_obj->obj_type].cnt = add_hmc_obj->obj_count;
add_out:
vf_dev->msg_count--;
vchnl_pf_send_error_resp(vf_dev->pf_dev, vf_dev->vf_id, vchnl_msg, (u16)ret_code);
}
/**
* pf_del_hmc_obj_callback - Callback for delete HMC Object
* @work_vf_dev: pointer to the VF Device
*/
static void pf_del_hmc_obj_callback(void *work_vf_dev)
{
struct i40iw_vfdev *vf_dev = (struct i40iw_vfdev *)work_vf_dev;
struct i40iw_hmc_info *hmc_info = &vf_dev->hmc_info;
struct i40iw_virtchnl_op_buf *vchnl_msg = &vf_dev->vf_msg_buffer.vchnl_msg;
struct i40iw_hmc_del_obj_info info;
struct i40iw_virtchnl_hmc_obj_range *del_hmc_obj;
enum i40iw_status_code ret_code = I40IW_SUCCESS;
if (!vf_dev->pf_hmc_initialized)
goto del_out;
del_hmc_obj = (struct i40iw_virtchnl_hmc_obj_range *)vchnl_msg->iw_chnl_buf;
memset(&info, 0, sizeof(info));
info.hmc_info = hmc_info;
info.is_pf = false;
info.rsrc_type = (u32)del_hmc_obj->obj_type;
info.start_idx = del_hmc_obj->start_index;
info.count = del_hmc_obj->obj_count;
i40iw_debug(vf_dev->pf_dev, I40IW_DEBUG_VIRT,
"I40IW_VCHNL_OP_DEL_HMC_OBJ_RANGE. Delete %u type %u objects\n",
info.count, info.rsrc_type);
ret_code = i40iw_sc_del_hmc_obj(vf_dev->pf_dev, &info, false);
del_out:
vf_dev->msg_count--;
vchnl_pf_send_error_resp(vf_dev->pf_dev, vf_dev->vf_id, vchnl_msg, (u16)ret_code);
}
/**
* i40iw_vf_init_pestat - Initialize stats for VF
* @devL pointer to the VF Device
* @stats: Statistics structure pointer
* @index: Stats index
*/
static void i40iw_vf_init_pestat(struct i40iw_sc_dev *dev, struct i40iw_vsi_pestat *stats, u16 index)
{
stats->hw = dev->hw;
i40iw_hw_stats_init(stats, (u8)index, false);
spin_lock_init(&stats->lock);
}
/**
* i40iw_vchnl_recv_pf - Receive PF virtual channel messages
* @dev: IWARP device pointer
* @vf_id: Virtual function ID associated with the message
* @msg: Virtual channel message buffer pointer
* @len: Length of the virtual channels message
*/
enum i40iw_status_code i40iw_vchnl_recv_pf(struct i40iw_sc_dev *dev,
u32 vf_id,
u8 *msg,
u16 len)
{
struct i40iw_virtchnl_op_buf *vchnl_msg = (struct i40iw_virtchnl_op_buf *)msg;
struct i40iw_vfdev *vf_dev = NULL;
struct i40iw_hmc_fcn_info hmc_fcn_info;
u16 iw_vf_idx;
u16 first_avail_iw_vf = I40IW_MAX_PE_ENABLED_VF_COUNT;
struct i40iw_virt_mem vf_dev_mem;
struct i40iw_virtchnl_work_info work_info;
struct i40iw_vsi_pestat *stats;
enum i40iw_status_code ret_code;
if (!dev || !msg || !len)
return I40IW_ERR_PARAM;
if (!dev->vchnl_up)
return I40IW_ERR_NOT_READY;
if (vchnl_msg->iw_op_code == I40IW_VCHNL_OP_GET_VER) {
if (vchnl_msg->iw_op_ver != I40IW_VCHNL_OP_GET_VER_V0)
vchnl_pf_send_get_ver_resp(dev, vf_id, vchnl_msg);
else
vchnl_pf_send_get_ver_resp(dev, vf_id, vchnl_msg);
return I40IW_SUCCESS;
}
for (iw_vf_idx = 0; iw_vf_idx < I40IW_MAX_PE_ENABLED_VF_COUNT; iw_vf_idx++) {
if (!dev->vf_dev[iw_vf_idx]) {
if (first_avail_iw_vf == I40IW_MAX_PE_ENABLED_VF_COUNT)
first_avail_iw_vf = iw_vf_idx;
continue;
}
if (dev->vf_dev[iw_vf_idx]->vf_id == vf_id) {
vf_dev = dev->vf_dev[iw_vf_idx];
break;
}
}
if (vf_dev) {
if (!vf_dev->msg_count) {
vf_dev->msg_count++;
} else {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"VF%u already has a channel message in progress.\n",
vf_id);
return I40IW_SUCCESS;
}
}
switch (vchnl_msg->iw_op_code) {
case I40IW_VCHNL_OP_GET_HMC_FCN:
if (!vf_dev &&
(first_avail_iw_vf != I40IW_MAX_PE_ENABLED_VF_COUNT)) {
ret_code = i40iw_allocate_virt_mem(dev->hw, &vf_dev_mem, sizeof(struct i40iw_vfdev) +
(sizeof(struct i40iw_hmc_obj_info) * I40IW_HMC_IW_MAX));
if (!ret_code) {
vf_dev = vf_dev_mem.va;
vf_dev->stats_initialized = false;
vf_dev->pf_dev = dev;
vf_dev->msg_count = 1;
vf_dev->vf_id = vf_id;
vf_dev->iw_vf_idx = first_avail_iw_vf;
vf_dev->pf_hmc_initialized = false;
vf_dev->hmc_info.hmc_obj = (struct i40iw_hmc_obj_info *)(&vf_dev[1]);
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"vf_dev %p, hmc_info %p, hmc_obj %p\n",
vf_dev, &vf_dev->hmc_info, vf_dev->hmc_info.hmc_obj);
dev->vf_dev[first_avail_iw_vf] = vf_dev;
iw_vf_idx = first_avail_iw_vf;
} else {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"VF%u Unable to allocate a VF device structure.\n",
vf_id);
vchnl_pf_send_error_resp(dev, vf_id, vchnl_msg, (u16)I40IW_ERR_NO_MEMORY);
return I40IW_SUCCESS;
}
memcpy(&vf_dev->vf_msg_buffer.vchnl_msg, vchnl_msg, len);
hmc_fcn_info.callback_fcn = pf_cqp_get_hmc_fcn_callback;
hmc_fcn_info.vf_id = vf_id;
hmc_fcn_info.iw_vf_idx = vf_dev->iw_vf_idx;
hmc_fcn_info.cqp_callback_param = vf_dev;
hmc_fcn_info.free_fcn = false;
ret_code = i40iw_cqp_manage_hmc_fcn_cmd(dev, &hmc_fcn_info);
if (ret_code)
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"VF%u error CQP HMC Function operation.\n",
vf_id);
i40iw_vf_init_pestat(dev, &vf_dev->pestat, vf_dev->pmf_index);
vf_dev->stats_initialized = true;
} else {
if (vf_dev) {
vf_dev->msg_count--;
vchnl_pf_send_get_hmc_fcn_resp(dev, vf_id, vchnl_msg, vf_dev->pmf_index);
} else {
vchnl_pf_send_error_resp(dev, vf_id, vchnl_msg,
(u16)I40IW_ERR_NO_MEMORY);
}
}
break;
case I40IW_VCHNL_OP_ADD_HMC_OBJ_RANGE:
if (!vf_dev)
return I40IW_ERR_BAD_PTR;
work_info.worker_vf_dev = vf_dev;
work_info.callback_fcn = pf_add_hmc_obj_callback;
memcpy(&vf_dev->vf_msg_buffer.vchnl_msg, vchnl_msg, len);
i40iw_cqp_spawn_worker(dev, &work_info, vf_dev->iw_vf_idx);
break;
case I40IW_VCHNL_OP_DEL_HMC_OBJ_RANGE:
if (!vf_dev)
return I40IW_ERR_BAD_PTR;
work_info.worker_vf_dev = vf_dev;
work_info.callback_fcn = pf_del_hmc_obj_callback;
memcpy(&vf_dev->vf_msg_buffer.vchnl_msg, vchnl_msg, len);
i40iw_cqp_spawn_worker(dev, &work_info, vf_dev->iw_vf_idx);
break;
case I40IW_VCHNL_OP_GET_STATS:
if (!vf_dev)
return I40IW_ERR_BAD_PTR;
stats = &vf_dev->pestat;
i40iw_hw_stats_read_all(stats, &stats->hw_stats);
vf_dev->msg_count--;
vchnl_pf_send_get_pe_stats_resp(dev, vf_id, vchnl_msg, &stats->hw_stats);
break;
default:
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"40iw_vchnl_recv_pf: Invalid OpCode 0x%x\n",
vchnl_msg->iw_op_code);
vchnl_pf_send_error_resp(dev, vf_id,
vchnl_msg, (u16)I40IW_ERR_NOT_IMPLEMENTED);
}
return I40IW_SUCCESS;
}
/**
* i40iw_vchnl_recv_vf - Receive VF virtual channel messages
* @dev: IWARP device pointer
* @vf_id: Virtual function ID associated with the message
* @msg: Virtual channel message buffer pointer
* @len: Length of the virtual channels message
*/
enum i40iw_status_code i40iw_vchnl_recv_vf(struct i40iw_sc_dev *dev,
u32 vf_id,
u8 *msg,
u16 len)
{
struct i40iw_virtchnl_resp_buf *vchnl_msg_resp = (struct i40iw_virtchnl_resp_buf *)msg;
struct i40iw_virtchnl_req *vchnl_req;
vchnl_req = (struct i40iw_virtchnl_req *)(uintptr_t)vchnl_msg_resp->iw_chnl_op_ctx;
vchnl_req->ret_code = (enum i40iw_status_code)vchnl_msg_resp->iw_op_ret_code;
if (len == (sizeof(*vchnl_msg_resp) + vchnl_req->parm_len - 1)) {
if (vchnl_req->parm_len && vchnl_req->parm)
memcpy(vchnl_req->parm, vchnl_msg_resp->iw_chnl_buf, vchnl_req->parm_len);
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: Got response, data size %u\n", __func__,
vchnl_req->parm_len);
} else {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s: error length on response, Got %u, expected %u\n", __func__,
len, (u32)(sizeof(*vchnl_msg_resp) + vchnl_req->parm_len - 1));
}
return I40IW_SUCCESS;
}
/**
* i40iw_vchnl_vf_get_ver - Request Channel version
* @dev: IWARP device pointer
* @vchnl_ver: Virtual channel message version pointer
*/
enum i40iw_status_code i40iw_vchnl_vf_get_ver(struct i40iw_sc_dev *dev,
u32 *vchnl_ver)
{
struct i40iw_virtchnl_req vchnl_req;
enum i40iw_status_code ret_code;
if (!i40iw_vf_clear_to_send(dev))
return I40IW_ERR_TIMEOUT;
memset(&vchnl_req, 0, sizeof(vchnl_req));
vchnl_req.dev = dev;
vchnl_req.parm = vchnl_ver;
vchnl_req.parm_len = sizeof(*vchnl_ver);
vchnl_req.vchnl_msg = &dev->vchnl_vf_msg_buf.vchnl_msg;
ret_code = vchnl_vf_send_get_ver_req(dev, &vchnl_req);
if (ret_code) {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s Send message failed 0x%0x\n", __func__, ret_code);
return ret_code;
}
ret_code = i40iw_vf_wait_vchnl_resp(dev);
if (ret_code)
return ret_code;
else
return vchnl_req.ret_code;
}
/**
* i40iw_vchnl_vf_get_hmc_fcn - Request HMC Function
* @dev: IWARP device pointer
* @hmc_fcn: HMC function index pointer
*/
enum i40iw_status_code i40iw_vchnl_vf_get_hmc_fcn(struct i40iw_sc_dev *dev,
u16 *hmc_fcn)
{
struct i40iw_virtchnl_req vchnl_req;
enum i40iw_status_code ret_code;
if (!i40iw_vf_clear_to_send(dev))
return I40IW_ERR_TIMEOUT;
memset(&vchnl_req, 0, sizeof(vchnl_req));
vchnl_req.dev = dev;
vchnl_req.parm = hmc_fcn;
vchnl_req.parm_len = sizeof(*hmc_fcn);
vchnl_req.vchnl_msg = &dev->vchnl_vf_msg_buf.vchnl_msg;
ret_code = vchnl_vf_send_get_hmc_fcn_req(dev, &vchnl_req);
if (ret_code) {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s Send message failed 0x%0x\n", __func__, ret_code);
return ret_code;
}
ret_code = i40iw_vf_wait_vchnl_resp(dev);
if (ret_code)
return ret_code;
else
return vchnl_req.ret_code;
}
/**
* i40iw_vchnl_vf_add_hmc_objs - Add HMC Object
* @dev: IWARP device pointer
* @rsrc_type: HMC Resource type
* @start_index: Starting index of the objects to be added
* @rsrc_count: Number of resources to be added
*/
enum i40iw_status_code i40iw_vchnl_vf_add_hmc_objs(struct i40iw_sc_dev *dev,
enum i40iw_hmc_rsrc_type rsrc_type,
u32 start_index,
u32 rsrc_count)
{
struct i40iw_virtchnl_req vchnl_req;
enum i40iw_status_code ret_code;
if (!i40iw_vf_clear_to_send(dev))
return I40IW_ERR_TIMEOUT;
memset(&vchnl_req, 0, sizeof(vchnl_req));
vchnl_req.dev = dev;
vchnl_req.vchnl_msg = &dev->vchnl_vf_msg_buf.vchnl_msg;
ret_code = vchnl_vf_send_add_hmc_objs_req(dev,
&vchnl_req,
rsrc_type,
start_index,
rsrc_count);
if (ret_code) {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s Send message failed 0x%0x\n", __func__, ret_code);
return ret_code;
}
ret_code = i40iw_vf_wait_vchnl_resp(dev);
if (ret_code)
return ret_code;
else
return vchnl_req.ret_code;
}
/**
* i40iw_vchnl_vf_del_hmc_obj - del HMC obj
* @dev: IWARP device pointer
* @rsrc_type: HMC Resource type
* @start_index: Starting index of the object to delete
* @rsrc_count: Number of resources to be delete
*/
enum i40iw_status_code i40iw_vchnl_vf_del_hmc_obj(struct i40iw_sc_dev *dev,
enum i40iw_hmc_rsrc_type rsrc_type,
u32 start_index,
u32 rsrc_count)
{
struct i40iw_virtchnl_req vchnl_req;
enum i40iw_status_code ret_code;
if (!i40iw_vf_clear_to_send(dev))
return I40IW_ERR_TIMEOUT;
memset(&vchnl_req, 0, sizeof(vchnl_req));
vchnl_req.dev = dev;
vchnl_req.vchnl_msg = &dev->vchnl_vf_msg_buf.vchnl_msg;
ret_code = vchnl_vf_send_del_hmc_objs_req(dev,
&vchnl_req,
rsrc_type,
start_index,
rsrc_count);
if (ret_code) {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s Send message failed 0x%0x\n", __func__, ret_code);
return ret_code;
}
ret_code = i40iw_vf_wait_vchnl_resp(dev);
if (ret_code)
return ret_code;
else
return vchnl_req.ret_code;
}
/**
* i40iw_vchnl_vf_get_pe_stats - Get PE stats
* @dev: IWARP device pointer
* @hw_stats: HW stats struct
*/
enum i40iw_status_code i40iw_vchnl_vf_get_pe_stats(struct i40iw_sc_dev *dev,
struct i40iw_dev_hw_stats *hw_stats)
{
struct i40iw_virtchnl_req vchnl_req;
enum i40iw_status_code ret_code;
if (!i40iw_vf_clear_to_send(dev))
return I40IW_ERR_TIMEOUT;
memset(&vchnl_req, 0, sizeof(vchnl_req));
vchnl_req.dev = dev;
vchnl_req.parm = hw_stats;
vchnl_req.parm_len = sizeof(*hw_stats);
vchnl_req.vchnl_msg = &dev->vchnl_vf_msg_buf.vchnl_msg;
ret_code = vchnl_vf_send_get_pe_stats_req(dev, &vchnl_req);
if (ret_code) {
i40iw_debug(dev, I40IW_DEBUG_VIRT,
"%s Send message failed 0x%0x\n", __func__, ret_code);
return ret_code;
}
ret_code = i40iw_vf_wait_vchnl_resp(dev);
if (ret_code)
return ret_code;
else
return vchnl_req.ret_code;
}
| bas-t/linux_media | drivers/infiniband/hw/i40iw/i40iw_virtchnl.c | C | gpl-2.0 | 26,514 |
/*
This file is part of libmicrohttpd
(C) 2007, 2008 Christian Grothoff
libmicrohttpd 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.
libmicrohttpd 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 libmicrohttpd; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/**
* @file daemontest_post.c
* @brief Testcase for libmicrohttpd POST operations using URL-encoding
* @author Christian Grothoff
*/
#include "MHD_config.h"
#include "platform.h"
#include <curl/curl.h>
#include <microhttpd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef WINDOWS
#include <unistd.h>
#endif
#include "socat.c"
#define POST_DATA "name=daniel&project=curl"
static int oneone;
struct CBC
{
char *buf;
size_t pos;
size_t size;
};
static size_t
copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
{
struct CBC *cbc = ctx;
if (cbc->pos + size * nmemb > cbc->size)
return 0; /* overflow */
memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
cbc->pos += size * nmemb;
return size * nmemb;
}
/**
* Note that this post_iterator is not perfect
* in that it fails to support incremental processing.
* (to be fixed in the future)
*/
static int
post_iterator (void *cls,
enum MHD_ValueKind kind,
const char *key,
const char *filename,
const char *content_type,
const char *transfer_encoding,
const char *value, uint64_t off, size_t size)
{
int *eok = cls;
if ((0 == strcmp (key, "name")) &&
(size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size)))
(*eok) |= 1;
if ((0 == strcmp (key, "project")) &&
(size == strlen ("curl")) && (0 == strncmp (value, "curl", size)))
(*eok) |= 2;
return MHD_YES;
}
static int
ahc_echo (void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method,
const char *version,
const char *upload_data, size_t *upload_data_size,
void **unused)
{
static int eok;
struct MHD_Response *response;
struct MHD_PostProcessor *pp;
int ret;
if (0 != strcmp ("POST", method))
{
return MHD_NO; /* unexpected method */
}
pp = *unused;
if (pp == NULL)
{
eok = 0;
pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok);
*unused = pp;
}
MHD_post_process (pp, upload_data, *upload_data_size);
if ((eok == 3) && (0 == *upload_data_size))
{
response = MHD_create_response_from_data (strlen (url),
(void *) url,
MHD_NO, MHD_YES);
ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
MHD_destroy_response (response);
MHD_destroy_post_processor (pp);
*unused = NULL;
return ret;
}
*upload_data_size = 0;
return MHD_YES;
}
static int
testInternalPost ()
{
struct MHD_Daemon *d;
CURL *c;
char buf[2048];
struct CBC cbc;
int i;
cbc.buf = buf;
cbc.size = 2048;
cbc.pos = 0;
d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY /* | MHD_USE_DEBUG */ ,
11080, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
if (d == NULL)
return 1;
zzuf_socat_start ();
for (i = 0; i < LOOP_COUNT; i++)
{
fprintf (stderr, ".");
c = curl_easy_init ();
curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer);
curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
curl_easy_setopt (c, CURLOPT_POST, 1L);
curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
if (oneone)
curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
else
curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
// NOTE: use of CONNECTTIMEOUT without also
// setting NOSIGNAL results in really weird
// crashes on my system!
curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
curl_easy_perform (c);
curl_easy_cleanup (c);
}
fprintf (stderr, "\n");
zzuf_socat_stop ();
MHD_stop_daemon (d);
return 0;
}
static int
testMultithreadedPost ()
{
struct MHD_Daemon *d;
CURL *c;
char buf[2048];
struct CBC cbc;
int i;
cbc.buf = buf;
cbc.size = 2048;
cbc.pos = 0;
d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION /* | MHD_USE_DEBUG */ ,
11080, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
if (d == NULL)
return 16;
zzuf_socat_start ();
for (i = 0; i < LOOP_COUNT; i++)
{
fprintf (stderr, ".");
c = curl_easy_init ();
curl_easy_setopt (c, CURLOPT_URL, "http://localhost:11081/hello_world");
curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer);
curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
curl_easy_setopt (c, CURLOPT_POST, 1L);
curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
if (oneone)
curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
else
curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
// NOTE: use of CONNECTTIMEOUT without also
// setting NOSIGNAL results in really weird
// crashes on my system!
curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
curl_easy_perform (c);
curl_easy_cleanup (c);
}
fprintf (stderr, "\n");
zzuf_socat_stop ();
MHD_stop_daemon (d);
return 0;
}
static int
testExternalPost ()
{
struct MHD_Daemon *d;
CURL *c;
char buf[2048];
struct CBC cbc;
CURLM *multi;
CURLMcode mret;
fd_set rs;
fd_set ws;
fd_set es;
int max;
int running;
time_t start;
struct timeval tv;
int i;
multi = NULL;
cbc.buf = buf;
cbc.size = 2048;
cbc.pos = 0;
d = MHD_start_daemon (MHD_NO_FLAG /* | MHD_USE_DEBUG */ ,
1082, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END);
if (d == NULL)
return 256;
multi = curl_multi_init ();
if (multi == NULL)
{
MHD_stop_daemon (d);
return 512;
}
zzuf_socat_start ();
for (i = 0; i < LOOP_COUNT; i++)
{
fprintf (stderr, ".");
c = curl_easy_init ();
curl_easy_setopt (c, CURLOPT_URL, "http://localhost:1082/hello_world");
curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer);
curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc);
curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA);
curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA));
curl_easy_setopt (c, CURLOPT_POST, 1L);
curl_easy_setopt (c, CURLOPT_FAILONERROR, 1);
curl_easy_setopt (c, CURLOPT_TIMEOUT_MS, CURL_TIMEOUT);
if (oneone)
curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
else
curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT_MS, CURL_TIMEOUT);
// NOTE: use of CONNECTTIMEOUT without also
// setting NOSIGNAL results in really weird
// crashes on my system!
curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1);
mret = curl_multi_add_handle (multi, c);
if (mret != CURLM_OK)
{
curl_multi_cleanup (multi);
curl_easy_cleanup (c);
zzuf_socat_stop ();
MHD_stop_daemon (d);
return 1024;
}
start = time (NULL);
while ((time (NULL) - start < 5) && (c != NULL))
{
max = 0;
FD_ZERO (&rs);
FD_ZERO (&ws);
FD_ZERO (&es);
curl_multi_perform (multi, &running);
mret = curl_multi_fdset (multi, &rs, &ws, &es, &max);
if (mret != CURLM_OK)
{
curl_multi_remove_handle (multi, c);
curl_multi_cleanup (multi);
curl_easy_cleanup (c);
zzuf_socat_stop ();
MHD_stop_daemon (d);
return 2048;
}
if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
{
curl_multi_remove_handle (multi, c);
curl_multi_cleanup (multi);
curl_easy_cleanup (c);
zzuf_socat_stop ();
MHD_stop_daemon (d);
return 4096;
}
tv.tv_sec = 0;
tv.tv_usec = 1000;
select (max + 1, &rs, &ws, &es, &tv);
curl_multi_perform (multi, &running);
if (running == 0)
{
curl_multi_info_read (multi, &running);
curl_multi_remove_handle (multi, c);
curl_easy_cleanup (c);
c = NULL;
}
MHD_run (d);
}
if (c != NULL)
{
curl_multi_remove_handle (multi, c);
curl_easy_cleanup (c);
}
}
fprintf (stderr, "\n");
curl_multi_cleanup (multi);
zzuf_socat_stop ();
MHD_stop_daemon (d);
return 0;
}
int
main (int argc, char *const *argv)
{
unsigned int errorCount = 0;
oneone = NULL != strstr (argv[0], "11");
if (0 != curl_global_init (CURL_GLOBAL_WIN32))
return 2;
errorCount += testInternalPost ();
errorCount += testMultithreadedPost ();
errorCount += testExternalPost ();
if (errorCount != 0)
fprintf (stderr, "Error (code: %u)\n", errorCount);
curl_global_cleanup ();
return errorCount != 0; /* 0 == pass */
}
| izenecloud/icma | source/libmicrohttpd/src/testzzuf/daemontest_post.c | C | apache-2.0 | 10,485 |
// Type definitions for lodash-webpack-plugin 0.11
// Project: https://github.com/lodash/lodash-webpack-plugin#readme
// Definitions by: Benjamin Lim <https://github.com/bumbleblym>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { Plugin } from 'webpack';
export = LodashModuleReplacementPlugin;
declare class LodashModuleReplacementPlugin extends Plugin {
constructor(options?: LodashModuleReplacementPlugin.Options);
}
declare namespace LodashModuleReplacementPlugin {
interface Options {
caching?: boolean;
chaining?: boolean;
cloning?: boolean;
coercions?: boolean;
collections?: boolean;
currying?: boolean;
deburring?: boolean;
exotics?: boolean;
flattening?: boolean;
guards?: boolean;
memoizing?: boolean;
metadata?: boolean;
paths?: boolean;
placeholders?: boolean;
shorthands?: boolean;
unicode?: boolean;
}
}
| borisyankov/DefinitelyTyped | types/lodash-webpack-plugin/index.d.ts | TypeScript | mit | 913 |
/*
* drivers/media/video/exynos/hevc/hevc_opr.c
*
* Samsung HEVC driver
* This file contains hw related functions.
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
e This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define DEBUG
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/firmware.h>
#include <linux/err.h>
#include <linux/sched.h>
#include <linux/dma-mapping.h>
#include <asm/cacheflush.h>
#ifdef CONFIG_EXYNOS_CONTENT_PATH_PROTECTION
#include <config/exynos/iovmm.h>
#endif
#include "hevc_common.h"
#include "hevc_cmd.h"
#include "hevc_mem.h"
#include "hevc_intr.h"
#include "hevc_inst.h"
#include "hevc_pm.h"
#include "hevc_debug.h"
#include "hevc_dec.h"
#include "hevc_opr.h"
#include "regs-hevc.h"
#include "hevc_reg.h"
/* #define HEVC_DEBUG_REGWRITE */
#ifdef HEVC_DEBUG_REGWRITE
#undef writel
#define writel(v, r) \
do { \
printk(KERN_ERR "HEVCWRITE(%p): %08x\n", r, (unsigned int)v); \
__raw_writel(v, r); \
} while (0)
#endif /* HEVC_DEBUG_REGWRITE */
#define READL(offset) readl(dev->regs_base + (offset))
#define WRITEL(data, offset) writel((data), dev->regs_base + (offset))
#define OFFSETA(x) (((x) - dev->port_a) >> HEVC_MEM_OFFSET)
#define OFFSETB(x) (((x) - dev->port_b) >> HEVC_MEM_OFFSET)
/* Allocate codec buffers */
int hevc_alloc_codec_buffers(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
unsigned int mb_width, mb_height;
void *alloc_ctx;
int i;
int lcu_width, lcu_height;
hevc_debug_enter();
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
alloc_ctx = dev->alloc_ctx[HEVC_BANK_A_ALLOC_CTX];
mb_width = mb_width(ctx->img_width);
mb_height = mb_height(ctx->img_height);
if (ctx->type == HEVCINST_DECODER) {
for (i = 0; i < ctx->raw_buf.num_planes; i++)
hevc_debug(2, "Plane[%d] size:%d\n",
i, ctx->raw_buf.plane_size[i]);
hevc_debug(2, "MV size: %d, Totals bufs: %d\n",
ctx->mv_size, dec->total_dpb_count);
} else {
return -EINVAL;
}
ctx->lcu_size = 64;
hevc_info("ctx->lcu_size : %d\n", ctx->lcu_size);
lcu_width = ALIGN(ctx->img_width, ctx->lcu_size);
lcu_height = ALIGN(ctx->img_height, ctx->lcu_size);
ctx->scratch_buf_size =
DEC_HEVC_SCRATCH_SIZE(lcu_width , lcu_height);
ctx->scratch_buf_size = ALIGN(ctx->scratch_buf_size, 256);
ctx->port_a_size =
ctx->scratch_buf_size +
(dec->mv_count * ctx->mv_size);
if (ctx->is_drm)
alloc_ctx = dev->alloc_ctx_drm;
/* Allocate only if memory from bank 1 is necessary */
if (ctx->port_a_size > 0) {
ctx->port_a_buf = hevc_mem_alloc_priv(
alloc_ctx, ctx->port_a_size);
if (IS_ERR(ctx->port_a_buf)) {
ctx->port_a_buf = 0;
printk(KERN_ERR
"Buf alloc for decoding failed (port A).\n");
return -ENOMEM;
}
ctx->port_a_phys = hevc_mem_daddr_priv(ctx->port_a_buf);
}
hevc_debug_leave();
return 0;
}
/* Release buffers allocated for codec */
void hevc_release_codec_buffers(struct hevc_ctx *ctx)
{
if (!ctx) {
hevc_err("no hevc context to run\n");
return;
}
if (ctx->port_a_buf) {
hevc_mem_free_priv(ctx->port_a_buf);
ctx->port_a_buf = 0;
ctx->port_a_phys = 0;
ctx->port_a_size = 0;
}
}
/* Allocate memory for instance data buffer */
int hevc_alloc_instance_buffer(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_buf_size_v6 *buf_size;
void *alloc_ctx;
hevc_debug_enter();
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
buf_size = dev->variant->buf_size->buf;
alloc_ctx = dev->alloc_ctx[HEVC_BANK_A_ALLOC_CTX];
ctx->ctx_buf_size = buf_size->dec_ctx;
if (ctx->is_drm)
alloc_ctx = dev->alloc_ctx_drm;
ctx->ctx.alloc = hevc_mem_alloc_priv(alloc_ctx, ctx->ctx_buf_size);
if (IS_ERR(ctx->ctx.alloc)) {
hevc_err("Allocating context buffer failed.\n");
return PTR_ERR(ctx->ctx.alloc);
}
ctx->ctx.ofs = hevc_mem_daddr_priv(ctx->ctx.alloc);
ctx->ctx.virt = hevc_mem_vaddr_priv(ctx->ctx.alloc);
if (!ctx->ctx.virt) {
hevc_mem_free_priv(ctx->ctx.alloc);
ctx->ctx.alloc = NULL;
ctx->ctx.ofs = 0;
ctx->ctx.virt = NULL;
hevc_err("Remapping context buffer failed.\n");
return -ENOMEM;
}
hevc_debug_leave();
return 0;
}
/* Release instance buffer */
void hevc_release_instance_buffer(struct hevc_ctx *ctx)
{
hevc_debug_enter();
if (!ctx) {
hevc_err("no hevc context to run\n");
return;
}
if (ctx->ctx.alloc) {
hevc_mem_free_priv(ctx->ctx.alloc);
ctx->ctx.alloc = NULL;
ctx->ctx.ofs = 0;
ctx->ctx.virt = NULL;
}
hevc_debug_leave();
}
/* Allocate context buffers for SYS_INIT */
int hevc_alloc_dev_context_buffer(struct hevc_dev *dev)
{
struct hevc_buf_size_v6 *buf_size;
void *alloc_ctx;
hevc_debug_enter();
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
buf_size = dev->variant->buf_size->buf;
alloc_ctx = dev->alloc_ctx[HEVC_BANK_A_ALLOC_CTX];
hevc_info("dev context buf_size : %d\n", buf_size->dev_ctx);
#ifdef CONFIG_EXYNOS_CONTENT_PATH_PROTECTION
if (dev->num_drm_inst)
alloc_ctx = dev->alloc_ctx_drm;
#endif
dev->ctx_buf.alloc =
hevc_mem_alloc_priv(alloc_ctx, buf_size->dev_ctx);
if (IS_ERR(dev->ctx_buf.alloc)) {
hevc_err("Allocating DESC buffer failed.\n");
return PTR_ERR(dev->ctx_buf.alloc);
}
dev->ctx_buf.ofs = hevc_mem_daddr_priv(dev->ctx_buf.alloc);
dev->ctx_buf.virt = hevc_mem_vaddr_priv(dev->ctx_buf.alloc);
if (!dev->ctx_buf.virt) {
hevc_mem_free_priv(dev->ctx_buf.alloc);
dev->ctx_buf.alloc = NULL;
dev->ctx_buf.ofs = 0;
hevc_err("Remapping DESC buffer failed.\n");
return -ENOMEM;
}
hevc_debug_leave();
return 0;
}
/* Release context buffers for SYS_INIT */
void hevc_release_dev_context_buffer(struct hevc_dev *dev)
{
if (!dev) {
hevc_err("no hevc device to run\n");
return;
}
if (dev->ctx_buf.alloc) {
hevc_mem_free_priv(dev->ctx_buf.alloc);
dev->ctx_buf.alloc = NULL;
dev->ctx_buf.ofs = 0;
dev->ctx_buf.virt = NULL;
}
}
static int calc_plane(int width, int height, int is_tiled)
{
int mbX, mbY;
mbX = (width + 15)/16;
mbY = (height + 15)/16;
/* Alignment for interlaced processing */
if (is_tiled)
mbY = (mbY + 1) / 2 * 2;
return (mbX * 16) * (mbY * 16);
}
static void set_linear_stride_size(struct hevc_ctx *ctx, struct hevc_fmt *fmt)
{
struct hevc_raw_info *raw;
int i;
raw = &ctx->raw_buf;
switch (fmt->fourcc) {
case V4L2_PIX_FMT_YUV420M:
case V4L2_PIX_FMT_YVU420M:
ctx->raw_buf.stride[0] = ctx->img_width;
ctx->raw_buf.stride[1] = ctx->img_width >> 1;
ctx->raw_buf.stride[2] = ctx->img_width >> 1;
break;
case V4L2_PIX_FMT_NV12MT_16X16:
case V4L2_PIX_FMT_NV12MT:
case V4L2_PIX_FMT_NV12M:
case V4L2_PIX_FMT_NV21M:
raw->stride[0] = ctx->img_width;
raw->stride[1] = ctx->img_width;
raw->stride[2] = 0;
break;
case V4L2_PIX_FMT_RGB24:
ctx->raw_buf.stride[0] = ctx->img_width * 3;
ctx->raw_buf.stride[1] = 0;
ctx->raw_buf.stride[2] = 0;
break;
case V4L2_PIX_FMT_RGB565:
ctx->raw_buf.stride[0] = ctx->img_width * 2;
ctx->raw_buf.stride[1] = 0;
ctx->raw_buf.stride[2] = 0;
break;
case V4L2_PIX_FMT_RGB32X:
case V4L2_PIX_FMT_BGR32:
ctx->raw_buf.stride[0] = ctx->img_width * 4;
ctx->raw_buf.stride[1] = 0;
ctx->raw_buf.stride[2] = 0;
break;
default:
break;
}
/* Decoder needs multiple of 16 alignment for stride */
if (ctx->type == HEVCINST_DECODER) {
for (i = 0; i < 3; i++)
ctx->raw_buf.stride[i] =
ALIGN(ctx->raw_buf.stride[i], 16);
}
}
void hevc_dec_calc_dpb_size(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
struct hevc_raw_info *raw;
int i;
if (!ctx) {
hevc_err("no hevc context to run\n");
return;
}
dev = ctx->dev;
raw = &ctx->raw_buf;
dec = ctx->dec_priv;
ctx->buf_width = ALIGN(ctx->img_width, 16);
ctx->buf_height = ALIGN(ctx->img_height, 16);
hevc_info("SEQ Done: Movie dimensions %dx%d, "
"buffer dimensions: %dx%d\n", ctx->img_width,
ctx->img_height, ctx->buf_width, ctx->buf_height);
switch (ctx->dst_fmt->fourcc) {
case V4L2_PIX_FMT_NV12M:
case V4L2_PIX_FMT_NV21M:
raw->plane_size[0] = ctx->buf_width*ctx->img_height;
raw->plane_size[1] = ctx->buf_width*(ctx->img_height >> 1);
raw->plane_size[2] = 0;
break;
case V4L2_PIX_FMT_YUV420M:
case V4L2_PIX_FMT_YVU420M:
raw->plane_size[0] =
calc_plane(ctx->img_width, ctx->img_height, 0);
raw->plane_size[1] =
calc_plane(ctx->img_width >> 1, ctx->img_height >> 1, 0);
raw->plane_size[2] =
calc_plane(ctx->img_width >> 1, ctx->img_height >> 1, 0);
break;
default:
raw->plane_size[0] = 0;
raw->plane_size[1] = 0;
raw->plane_size[2] = 0;
hevc_err("Invalid pixelformat : %s\n", ctx->dst_fmt->name);
break;
}
set_linear_stride_size(ctx, ctx->dst_fmt);
for (i = 0; i < raw->num_planes; i++)
hevc_debug(2, "Plane[%d] size = %d, stride = %d\n",
i, raw->plane_size[i], raw->stride[i]);
switch (ctx->dst_fmt->fourcc) {
case V4L2_PIX_FMT_NV12M:
case V4L2_PIX_FMT_NV21M:
raw->plane_size[0] += 64;
raw->plane_size[1] += 64;
break;
case V4L2_PIX_FMT_YUV420M:
case V4L2_PIX_FMT_YVU420M:
raw->plane_size[0] += 64;
raw->plane_size[1] += 64;
raw->plane_size[2] += 64;
break;
default:
break;
}
hevc_info("codec mode : %d\n", ctx->codec_mode);
if (ctx->codec_mode == EXYNOS_CODEC_HEVC_DEC) {
ctx->mv_size = hevc_dec_mv_size(ctx->img_width,
ctx->img_height);
ctx->mv_size = ALIGN(ctx->mv_size, 32);
} else {
ctx->mv_size = 0;
}
}
/* Set registers for decoding stream buffer */
int hevc_set_dec_stream_buffer(struct hevc_ctx *ctx, dma_addr_t buf_addr,
unsigned int start_num_byte, unsigned int strm_size)
{
struct hevc_dec *dec;
struct hevc_dev *dev;
size_t cpb_buf_size;
hevc_debug_enter();
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
if (!dec) {
hevc_err("no mfc decoder to run\n");
return -EINVAL;
}
cpb_buf_size = ALIGN(dec->src_buf_size, HEVC_NV12M_HALIGN);
hevc_debug(2, "inst_no: %d, buf_addr: 0x%x\n", ctx->inst_no, buf_addr);
hevc_debug(2, "strm_size: 0x%08x cpb_buf_size: 0x%x\n",
strm_size, cpb_buf_size);
WRITEL(strm_size, HEVC_D_STREAM_DATA_SIZE);
WRITEL(buf_addr, HEVC_D_CPB_BUFFER_ADDR);
WRITEL(cpb_buf_size, HEVC_D_CPB_BUFFER_SIZE);
WRITEL(start_num_byte, HEVC_D_CPB_BUFFER_OFFSET);
hevc_debug_leave();
return 0;
}
/* Set display buffer through shared memory at INIT_BUFFER */
int hevc_set_dec_stride_buffer(struct hevc_ctx *ctx, struct list_head *buf_queue)
{
struct hevc_dev *dev = ctx->dev;
int i;
for (i = 0; i < ctx->raw_buf.num_planes; i++) {
WRITEL(ctx->raw_buf.stride[i],
HEVC_D_FIRST_PLANE_DPB_STRIDE_SIZE + (i * 4));
hevc_debug(2, "# plane%d.size = %d, stride = %d\n", i,
ctx->raw_buf.plane_size[i], ctx->raw_buf.stride[i]);
}
return 0;
}
/* Set decoding frame buffer */
int hevc_set_dec_frame_buffer(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
unsigned int i, frame_size_mv;
size_t buf_addr1;
int buf_size1;
int align_gap;
struct hevc_buf *buf;
struct hevc_raw_info *raw;
struct list_head *buf_queue;
unsigned char *dpb_vir;
int j;
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
if (!dec) {
hevc_err("no hevc decoder to run\n");
return -EINVAL;
}
raw = &ctx->raw_buf;
buf_addr1 = ctx->port_a_phys;
buf_size1 = ctx->port_a_size;
hevc_debug(2, "Buf1: %p (%d)\n", (void *)buf_addr1, buf_size1);
hevc_info("Total DPB COUNT: %d\n", dec->total_dpb_count);
hevc_debug(2, "Setting display delay to %d\n", dec->display_delay);
hevc_debug(2, "ctx->scratch_buf_size %d\n", ctx->scratch_buf_size);
WRITEL(dec->total_dpb_count, HEVC_D_NUM_DPB);
hevc_debug(2, "raw->num_planes %d\n", raw->num_planes);
for (i = 0; i < raw->num_planes; i++) {
hevc_debug(2, "raw->plane_size[%d]= %d\n", i, raw->plane_size[i]);
WRITEL(raw->plane_size[i], HEVC_D_FIRST_PLANE_DPB_SIZE + i*4);
}
if (dec->is_dynamic_dpb)
WRITEL((0x1 << HEVC_D_OPT_DYNAMIC_DPB_SET_SHIFT), HEVC_D_INIT_BUFFER_OPTIONS);
WRITEL(buf_addr1, HEVC_D_SCRATCH_BUFFER_ADDR);
WRITEL(ctx->scratch_buf_size, HEVC_D_SCRATCH_BUFFER_SIZE);
buf_addr1 += ctx->scratch_buf_size;
buf_size1 -= ctx->scratch_buf_size;
WRITEL(ctx->mv_size, HEVC_D_MV_BUFFER_SIZE);
frame_size_mv = ctx->mv_size;
hevc_debug(2, "Frame size: %d, %d, %d, mv: %d\n",
raw->plane_size[0], raw->plane_size[1],
raw->plane_size[2], frame_size_mv);
if (dec->dst_memtype == V4L2_MEMORY_USERPTR || dec->dst_memtype == V4L2_MEMORY_DMABUF)
buf_queue = &ctx->dst_queue;
else
buf_queue = &dec->dpb_queue;
i = 0;
list_for_each_entry(buf, buf_queue, list) {
/* Do not setting DPB */
if (dec->is_dynamic_dpb)
break;
for (j = 0; j < raw->num_planes; j++) {
hevc_debug(2, "buf->planes.raw[%d] = 0x%x\n", j, buf->planes.raw[j]);
WRITEL(buf->planes.raw[j], HEVC_D_FIRST_PLANE_DPB0 + (j*0x100 + i*4));
}
if ((i == 0) && (!ctx->is_drm)) {
int j, color[3] = { 0x0, 0x80, 0x80 };
for (j = 0; j < raw->num_planes; j++) {
dpb_vir = vb2_plane_vaddr(&buf->vb, j);
if (dpb_vir)
memset(dpb_vir, color[j],
raw->plane_size[j]);
}
hevc_mem_clean_vb(&buf->vb, j);
}
i++;
}
hevc_set_dec_stride_buffer(ctx, buf_queue);
WRITEL(dec->mv_count, HEVC_D_NUM_MV);
for (i = 0; i < dec->mv_count; i++) {
/* To test alignment */
align_gap = buf_addr1;
buf_addr1 = ALIGN(buf_addr1, 16);
align_gap = buf_addr1 - align_gap;
buf_size1 -= align_gap;
hevc_debug(2, "\tBuf1: %x, size: %d\n", buf_addr1, buf_size1);
WRITEL(buf_addr1, HEVC_D_MV_BUFFER0 + i * 4);
buf_addr1 += frame_size_mv;
buf_size1 -= frame_size_mv;
}
hevc_debug(2, "Buf1: %u, buf_size1: %d (frames %d)\n",
buf_addr1, buf_size1, dec->total_dpb_count);
if (buf_size1 < 0) {
hevc_debug(2, "Not enough memory has been allocated.\n");
return -ENOMEM;
}
WRITEL(ctx->inst_no, HEVC_INSTANCE_ID);
hevc_cmd_host2risc(HEVC_CH_INIT_BUFS, NULL);
hevc_debug(2, "After setting buffers.\n");
return 0;
}
/* Initialize decoding */
int hevc_init_decode(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
unsigned int reg = 0, pix_val;
int fmo_aso_ctrl = 0;
hevc_debug_enter();
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
if (!dec) {
hevc_err("no hevc decoder to run\n");
return -EINVAL;
}
hevc_debug(2, "InstNo: %d/%d\n", ctx->inst_no, HEVC_CH_SEQ_HEADER);
hevc_debug(2, "BUFs: %08x %08x %08x\n",
READL(HEVC_D_CPB_BUFFER_ADDR),
READL(HEVC_D_CPB_BUFFER_ADDR),
READL(HEVC_D_CPB_BUFFER_ADDR));
reg |= (dec->idr_decoding << HEVC_D_OPT_IDR_DECODING_SHFT);
/* FMO_ASO_CTRL - 0: Enable, 1: Disable */
reg |= (fmo_aso_ctrl << HEVC_D_OPT_FMO_ASO_CTRL_MASK);
/* When user sets desplay_delay to 0,
* It works as "display_delay enable" and delay set to 0.
* If user wants display_delay disable, It should be
* set to negative value. */
if (dec->display_delay >= 0) {
reg |= (0x1 << HEVC_D_OPT_DDELAY_EN_SHIFT);
WRITEL(dec->display_delay, HEVC_D_DISPLAY_DELAY);
}
if (ctx->dst_fmt->fourcc == V4L2_PIX_FMT_NV12MT_16X16)
reg |= (0x1 << HEVC_D_OPT_TILE_MODE_SHIFT);
hevc_debug(2, "HEVC_D_DEC_OPTIONS : 0x%x\n", reg);
WRITEL(0x20, HEVC_D_DEC_OPTIONS);
switch (ctx->dst_fmt->fourcc) {
case V4L2_PIX_FMT_NV12M:
case V4L2_PIX_FMT_NV12MT_16X16:
pix_val = 0;
break;
case V4L2_PIX_FMT_NV21M:
pix_val = 1;
break;
case V4L2_PIX_FMT_YVU420M:
pix_val = 2;
break;
case V4L2_PIX_FMT_YUV420M:
pix_val = 3;
break;
default:
pix_val = 0;
break;
}
hevc_debug(2, "pixel format: %d\n", pix_val);
WRITEL(pix_val, HEVC_PIXEL_FORMAT);
/* sei parse */
reg = dec->sei_parse;
hevc_debug(2, "sei parse: %d\n", dec->sei_parse);
/* Enable realloc interface if SEI is enabled */
if (dec->sei_parse)
reg |= (0x1 << HEVC_D_SEI_NEED_INIT_BUFFER_SHIFT);
WRITEL(reg, HEVC_D_SEI_ENABLE);
WRITEL(ctx->inst_no, HEVC_INSTANCE_ID);
WRITEL(0xffffffff, HEVC_D_AVAILABLE_DPB_FLAG_UPPER);
WRITEL(0xffffffff, HEVC_D_AVAILABLE_DPB_FLAG_LOWER);
hevc_cmd_host2risc(HEVC_CH_SEQ_HEADER, NULL);
hevc_debug_leave();
return 0;
}
/* Decode a single frame */
int hevc_decode_one_frame(struct hevc_ctx *ctx, int last_frame)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
if (!dec) {
hevc_err("no hevc decoder to run\n");
return -EINVAL;
}
hevc_debug(2, "Setting flags to %08lx (free:%d WTF:%d)\n",
dec->dpb_status, ctx->dst_queue_cnt,
dec->dpb_queue_cnt);
if (dec->is_dynamic_dpb) {
hevc_debug(2, "Dynamic:0x%08x, Available:0x%08lx\n",
dec->dynamic_set, dec->dpb_status);
WRITEL(dec->dynamic_set, HEVC_D_DYNAMIC_DPB_FLAG_LOWER);
WRITEL(0x0, HEVC_D_DYNAMIC_DPB_FLAG_UPPER);
}
WRITEL(dec->dpb_status, HEVC_D_AVAILABLE_DPB_FLAG_LOWER);
WRITEL(0x0, HEVC_D_AVAILABLE_DPB_FLAG_UPPER);
WRITEL(dec->slice_enable, HEVC_D_SLICE_IF_ENABLE);
hevc_debug(2, "dec->slice_enable : %d\n", dec->slice_enable);
hevc_debug(2, "inst_no : %d last_frame : %d\n", ctx->inst_no, last_frame);
WRITEL(ctx->inst_no, HEVC_INSTANCE_ID);
/* Issue different commands to instance basing on whether it
* is the last frame or not. */
switch (last_frame) {
case 0:
hevc_cmd_host2risc(HEVC_CH_FRAME_START, NULL);
break;
case 1:
hevc_cmd_host2risc(HEVC_CH_LAST_FRAME, NULL);
break;
}
hevc_debug(2, "Decoding a usual frame.\n");
return 0;
}
static inline int hevc_get_new_ctx(struct hevc_dev *dev)
{
int new_ctx;
int cnt;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
hevc_debug(2, "Previous context: %d (bits %08lx)\n", dev->curr_ctx,
dev->ctx_work_bits);
if (dev->preempt_ctx > HEVC_NO_INSTANCE_SET)
return dev->preempt_ctx;
else
new_ctx = (dev->curr_ctx + 1) % HEVC_NUM_CONTEXTS;
cnt = 0;
while (!test_bit(new_ctx, &dev->ctx_work_bits)) {
new_ctx = (new_ctx + 1) % HEVC_NUM_CONTEXTS;
cnt++;
if (cnt > HEVC_NUM_CONTEXTS) {
/* No contexts to run */
return -EAGAIN;
}
}
return new_ctx;
}
static int hevc_set_dynamic_dpb(struct hevc_ctx *ctx, struct hevc_buf *dst_vb)
{
struct hevc_dev *dev = ctx->dev;
struct hevc_dec *dec = ctx->dec_priv;
struct hevc_raw_info *raw = &ctx->raw_buf;
int dst_index;
int i;
dst_index = dst_vb->vb.v4l2_buf.index;
dec->dynamic_set = 1 << dst_index;
dst_vb->used = 1;
set_bit(dst_index, &dec->dpb_status);
hevc_debug(2, "ADDING Flag after: %lx\n", dec->dpb_status);
hevc_debug(2, "Dst addr [%d] = 0x%x\n", dst_index,
dst_vb->planes.raw[0]);
for (i = 0; i < raw->num_planes; i++) {
WRITEL(raw->plane_size[i], HEVC_D_FIRST_PLANE_DPB_SIZE + i*4);
WRITEL(dst_vb->planes.raw[i],
HEVC_D_FIRST_PLANE_DPB0 + (i*0x100 + dst_index*4));
}
return 0;
}
static inline int hevc_run_dec_last_frames(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_buf *temp_vb, *dst_vb;
struct hevc_dec *dec;
unsigned long flags;
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
spin_lock_irqsave(&dev->irqlock, flags);
if ((dec->is_dynamic_dpb) && (ctx->dst_queue_cnt == 0)) {
hevc_debug(2, "No dst buffer\n");
spin_unlock_irqrestore(&dev->irqlock, flags);
return -EAGAIN;
}
/* Frames are being decoded */
if (list_empty(&ctx->src_queue)) {
hevc_debug(2, "No src buffers.\n");
hevc_set_dec_stream_buffer(ctx, 0, 0, 0);
} else {
/* Get the next source buffer */
temp_vb = list_entry(ctx->src_queue.next,
struct hevc_buf, list);
temp_vb->used = 1;
hevc_set_dec_stream_buffer(ctx,
hevc_mem_plane_addr(ctx, &temp_vb->vb, 0), 0, 0);
}
if (dec->is_dynamic_dpb) {
dst_vb = list_entry(ctx->dst_queue.next,
struct hevc_buf, list);
hevc_set_dynamic_dpb(ctx, dst_vb);
}
spin_unlock_irqrestore(&dev->irqlock, flags);
dev->curr_ctx = ctx->num;
hevc_clean_ctx_int_flags(ctx);
hevc_decode_one_frame(ctx, 1);
return 0;
}
static inline int hevc_run_dec_frame(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_buf *temp_vb, *dst_vb;
struct hevc_dec *dec;
unsigned long flags;
int last_frame = 0;
unsigned int index;
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
spin_lock_irqsave(&dev->irqlock, flags);
/* Frames are being decoded */
if (list_empty(&ctx->src_queue)) {
hevc_debug(2, "No src buffers.\n");
spin_unlock_irqrestore(&dev->irqlock, flags);
return -EAGAIN;
}
if ((dec->is_dynamic_dpb && ctx->dst_queue_cnt == 0) ||
(!dec->is_dynamic_dpb && ctx->dst_queue_cnt < ctx->dpb_count)) {
spin_unlock_irqrestore(&dev->irqlock, flags);
return -EAGAIN;
}
/* Get the next source buffer */
temp_vb = list_entry(ctx->src_queue.next, struct hevc_buf, list);
temp_vb->used = 1;
hevc_debug(2, "Temp vb: %p\n", temp_vb);
hevc_debug(2, "Src Addr: 0x%08lx\n",
(unsigned long)hevc_mem_plane_addr(ctx, &temp_vb->vb, 0));
hevc_set_dec_stream_buffer(ctx,
hevc_mem_plane_addr(ctx, &temp_vb->vb, 0),
dec->src_offset, temp_vb->vb.v4l2_planes[0].bytesused);
index = temp_vb->vb.v4l2_buf.index;
if (call_cop(ctx, set_buf_ctrls_val, ctx, &ctx->src_ctrls[index]) < 0)
hevc_err("failed in set_buf_ctrls_val\n");
if (dec->is_dynamic_dpb) {
dst_vb = list_entry(ctx->dst_queue.next,
struct hevc_buf, list);
hevc_set_dynamic_dpb(ctx, dst_vb);
}
spin_unlock_irqrestore(&dev->irqlock, flags);
dev->curr_ctx = ctx->num;
hevc_clean_ctx_int_flags(ctx);
if (temp_vb->vb.v4l2_planes[0].bytesused == 0 ||
temp_vb->vb.v4l2_buf.reserved2 == FLAG_LAST_FRAME) {
last_frame = 1;
hevc_debug(2, "Setting ctx->state to FINISHING\n");
ctx->state = HEVCINST_FINISHING;
}
hevc_decode_one_frame(ctx, last_frame);
return 0;
}
static inline void hevc_run_init_dec(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
unsigned long flags;
struct hevc_buf *temp_vb;
if (!ctx) {
hevc_err("no hevc context to run\n");
return;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return;
}
dec = ctx->dec_priv;
/* Initializing decoding - parsing header */
spin_lock_irqsave(&dev->irqlock, flags);
hevc_info("Preparing to init decoding.\n");
temp_vb = list_entry(ctx->src_queue.next, struct hevc_buf, list);
hevc_info("Header size: %d\n", temp_vb->vb.v4l2_planes[0].bytesused);
hevc_set_dec_stream_buffer(ctx,
hevc_mem_plane_addr(ctx, &temp_vb->vb, 0),
dec->src_offset, temp_vb->vb.v4l2_planes[0].bytesused);
spin_unlock_irqrestore(&dev->irqlock, flags);
dev->curr_ctx = ctx->num;
hevc_debug(2, "Header addr: 0x%08lx\n",
(unsigned long)hevc_mem_plane_addr(ctx, &temp_vb->vb, 0));
hevc_clean_ctx_int_flags(ctx);
hevc_init_decode(ctx);
}
static inline int hevc_run_init_dec_buffers(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
struct hevc_dec *dec;
int ret;
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dec = ctx->dec_priv;
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
/* Initializing decoding - parsing header */
/* Header was parsed now starting processing
* First set the output frame buffers
* hevc_alloc_dec_buffers(ctx); */
if (!dec->is_dynamic_dpb && (ctx->capture_state != QUEUE_BUFS_MMAPED)) {
hevc_err("It seems that not all destionation buffers were "
"mmaped.\nHEVC requires that all destination are mmaped "
"before starting processing.\n");
return -EAGAIN;
}
dev->curr_ctx = ctx->num;
hevc_clean_ctx_int_flags(ctx);
ret = hevc_set_dec_frame_buffer(ctx);
if (ret) {
hevc_err("Failed to alloc frame mem.\n");
ctx->state = HEVCINST_ERROR;
}
return ret;
}
static inline int hevc_abort_inst(struct hevc_ctx *ctx)
{
struct hevc_dev *dev;
if (!ctx) {
hevc_err("no hevc context to run\n");
return -EINVAL;
}
dev = ctx->dev;
if (!dev) {
hevc_err("no hevc device to run\n");
return -EINVAL;
}
dev->curr_ctx = ctx->num;
hevc_clean_ctx_int_flags(ctx);
WRITEL(ctx->inst_no, HEVC_INSTANCE_ID);
hevc_cmd_host2risc(HEVC_CH_NAL_ABORT, NULL);
return 0;
}
static inline int hevc_dec_dpb_flush(struct hevc_ctx *ctx)
{
struct hevc_dev *dev = ctx->dev;
dev->curr_ctx = ctx->num;
hevc_clean_ctx_int_flags(ctx);
WRITEL(ctx->inst_no, HEVC_INSTANCE_ID);
hevc_cmd_host2risc(HEVC_H2R_CMD_FLUSH, NULL);
return 0;
}
static inline int hevc_ctx_ready(struct hevc_ctx *ctx)
{
if (ctx->type == HEVCINST_DECODER)
return hevc_dec_ctx_ready(ctx);
return 0;
}
/* Try running an operation on hardware */
void hevc_try_run(struct hevc_dev *dev)
{
struct hevc_ctx *ctx;
int new_ctx;
unsigned int ret = 0;
hevc_debug(1, "Try run dev: %p\n", dev);
if (!dev) {
hevc_err("no hevc device to run\n");
return;
}
spin_lock_irq(&dev->condlock);
/* Check whether hardware is not running */
if (dev->hw_lock != 0) {
spin_unlock_irq(&dev->condlock);
/* This is perfectly ok, the scheduled ctx should wait */
hevc_debug(1, "Couldn't lock HW.\n");
return;
}
/* Choose the context to run */
new_ctx = hevc_get_new_ctx(dev);
if (new_ctx < 0) {
/* No contexts to run */
spin_unlock_irq(&dev->condlock);
hevc_debug(1, "No ctx is scheduled to be run.\n");
return;
}
ctx = dev->ctx[new_ctx];
if (!ctx) {
spin_unlock_irq(&dev->condlock);
hevc_err("no hevc context to run\n");
return;
}
if (test_and_set_bit(ctx->num, &dev->hw_lock) != 0) {
spin_unlock_irq(&dev->condlock);
hevc_err("Failed to lock hardware.\n");
return;
}
spin_unlock_irq(&dev->condlock);
hevc_debug(1, "New context: %d\n", new_ctx);
hevc_debug(1, "Seting new context to %p\n", ctx);
/* Got context to run in ctx */
hevc_debug(1, "ctx->dst_queue_cnt=%d ctx->dpb_count=%d ctx->src_queue_cnt=%d\n",
ctx->dst_queue_cnt, ctx->dpb_count, ctx->src_queue_cnt);
hevc_debug(1, "ctx->state=%d\n", ctx->state);
/* Last frame has already been sent to HEVC
* Now obtaining frames from HEVC buffer */
dev->curr_ctx_drm = ctx->is_drm;
hevc_clock_on();
if (ctx->type == HEVCINST_DECODER) {
switch (ctx->state) {
case HEVCINST_FINISHING:
ret = hevc_run_dec_last_frames(ctx);
break;
case HEVCINST_RUNNING:
ret = hevc_run_dec_frame(ctx);
break;
case HEVCINST_INIT:
ret = hevc_open_inst(ctx);
break;
case HEVCINST_RETURN_INST:
ret = hevc_close_inst(ctx);
break;
case HEVCINST_GOT_INST:
hevc_run_init_dec(ctx);
break;
case HEVCINST_HEAD_PARSED:
ret = hevc_run_init_dec_buffers(ctx);
break;
case HEVCINST_RES_CHANGE_INIT:
ret = hevc_run_dec_last_frames(ctx);
break;
case HEVCINST_RES_CHANGE_FLUSH:
ret = hevc_run_dec_last_frames(ctx);
break;
case HEVCINST_RES_CHANGE_END:
hevc_debug(2, "Finished remaining frames after resolution change.\n");
ctx->capture_state = QUEUE_FREE;
hevc_debug(2, "Will re-init the codec`.\n");
hevc_run_init_dec(ctx);
break;
case HEVCINST_DPB_FLUSHING:
ret = hevc_dec_dpb_flush(ctx);
break;
default:
ret = -EAGAIN;
}
} else {
hevc_err("invalid context type: %d\n", ctx->type);
ret = -EAGAIN;
}
if (ret) {
/* Check again the ctx condition and clear work bits
* if ctx is not available. */
if (hevc_ctx_ready(ctx) == 0) {
spin_lock_irq(&dev->condlock);
clear_bit(ctx->num, &dev->ctx_work_bits);
spin_unlock_irq(&dev->condlock);
}
/* Free hardware lock */
if (hevc_clear_hw_bit(ctx) == 0)
hevc_err("Failed to unlock hardware.\n");
hevc_clock_off();
/* Trigger again if other instance's work is waiting */
spin_lock_irq(&dev->condlock);
if (dev->ctx_work_bits)
queue_work(dev->sched_wq, &dev->sched_work);
spin_unlock_irq(&dev->condlock);
}
}
void hevc_cleanup_queue(struct list_head *lh, struct vb2_queue *vq)
{
struct hevc_buf *b;
int i;
while (!list_empty(lh)) {
b = list_entry(lh->next, struct hevc_buf, list);
for (i = 0; i < b->vb.num_planes; i++)
vb2_set_plane_payload(&b->vb, i, 0);
vb2_buffer_done(&b->vb, VB2_BUF_STATE_ERROR);
list_del(&b->list);
}
}
void hevc_write_info(struct hevc_ctx *ctx, unsigned int data, unsigned int ofs)
{
struct hevc_dev *dev = ctx->dev;
if (dev->hw_lock) {
WRITEL(data, ofs);
} else {
hevc_clock_on();
WRITEL(data, ofs);
hevc_clock_off();
}
}
unsigned int hevc_read_info(struct hevc_ctx *ctx, unsigned int ofs)
{
struct hevc_dev *dev = ctx->dev;
int ret;
if (dev->hw_lock) {
ret = READL(ofs);
} else {
hevc_clock_on();
ret = READL(ofs);
hevc_clock_off();
}
return ret;
}
| Galaxy-Tab-S2/android_kernel_samsung_gts28wifi | drivers/media/platform/exynos/hevc/hevc_opr.c | C | gpl-2.0 | 29,287 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.psi.impl.source.xml;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.psi.xml.XmlMarkupDecl;
/**
* @author Mike
*/
public class XmlMarkupDeclImpl extends XmlElementImpl implements XmlMarkupDecl {
public XmlMarkupDeclImpl() {
super(XmlElementType.XML_MARKUP_DECL);
}
@Override
public PsiMetaData getMetaData(){
return MetaRegistry.getMeta(this);
}
}
| asedunov/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlMarkupDeclImpl.java | Java | apache-2.0 | 1,100 |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
public class btConvexHullComputer extends BulletBase {
private long swigCPtr;
protected btConvexHullComputer(final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexHullComputer, normally you should not need this constructor it's intended for low-level usage. */
public btConvexHullComputer(long cPtr, boolean cMemoryOwn) {
this("btConvexHullComputer", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset(long cPtr, boolean cMemoryOwn) {
if (!destroyed)
destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr(btConvexHullComputer obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize() throws Throwable {
if (!destroyed)
destroy();
super.finalize();
}
@Override protected synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
LinearMathJNI.delete_btConvexHullComputer(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
static public class Edge extends BulletBase {
private long swigCPtr;
protected Edge(final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new Edge, normally you should not need this constructor it's intended for low-level usage. */
public Edge(long cPtr, boolean cMemoryOwn) {
this("Edge", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset(long cPtr, boolean cMemoryOwn) {
if (!destroyed)
destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr(Edge obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize() throws Throwable {
if (!destroyed)
destroy();
super.finalize();
}
@Override protected synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
LinearMathJNI.delete_btConvexHullComputer_Edge(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public int getSourceVertex() {
return LinearMathJNI.btConvexHullComputer_Edge_getSourceVertex(swigCPtr, this);
}
public int getTargetVertex() {
return LinearMathJNI.btConvexHullComputer_Edge_getTargetVertex(swigCPtr, this);
}
public btConvexHullComputer.Edge getNextEdgeOfVertex() {
long cPtr = LinearMathJNI.btConvexHullComputer_Edge_getNextEdgeOfVertex(swigCPtr, this);
return (cPtr == 0) ? null : new btConvexHullComputer.Edge(cPtr, false);
}
public btConvexHullComputer.Edge getNextEdgeOfFace() {
long cPtr = LinearMathJNI.btConvexHullComputer_Edge_getNextEdgeOfFace(swigCPtr, this);
return (cPtr == 0) ? null : new btConvexHullComputer.Edge(cPtr, false);
}
public btConvexHullComputer.Edge getReverseEdge() {
long cPtr = LinearMathJNI.btConvexHullComputer_Edge_getReverseEdge(swigCPtr, this);
return (cPtr == 0) ? null : new btConvexHullComputer.Edge(cPtr, false);
}
public Edge() {
this(LinearMathJNI.new_btConvexHullComputer_Edge(), true);
}
}
public void setVertices(btVector3Array value) {
LinearMathJNI.btConvexHullComputer_vertices_set(swigCPtr, this, btVector3Array.getCPtr(value), value);
}
public btVector3Array getVertices() {
long cPtr = LinearMathJNI.btConvexHullComputer_vertices_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3Array(cPtr, false);
}
public void setEdges(SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t value) {
LinearMathJNI.btConvexHullComputer_edges_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t getEdges() {
long cPtr = LinearMathJNI.btConvexHullComputer_edges_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t(cPtr, false);
}
public void setFaces(SWIGTYPE_p_btAlignedObjectArrayT_int_t value) {
LinearMathJNI.btConvexHullComputer_faces_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_int_t getFaces() {
long cPtr = LinearMathJNI.btConvexHullComputer_faces_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_int_t(cPtr, false);
}
public float compute(java.nio.FloatBuffer coords, int stride, int count, float shrink, float shrinkClamp) {
assert coords.isDirect() : "Buffer must be allocated direct.";
{
return LinearMathJNI.btConvexHullComputer_compute__SWIG_0(swigCPtr, this, coords, stride, count, shrink, shrinkClamp);
}
}
public float compute(java.nio.DoubleBuffer coords, int stride, int count, float shrink, float shrinkClamp) {
assert coords.isDirect() : "Buffer must be allocated direct.";
{
return LinearMathJNI.btConvexHullComputer_compute__SWIG_1(swigCPtr, this, coords, stride, count, shrink, shrinkClamp);
}
}
public btConvexHullComputer() {
this(LinearMathJNI.new_btConvexHullComputer(), true);
}
}
| saqsun/libgdx | extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/btConvexHullComputer.java | Java | apache-2.0 | 5,913 |
/**
* 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.zookeeper.operations;
import java.util.List;
import static java.lang.String.format;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
* <code>CreateOperation</code> is a basic Zookeeper operation used to create
* and set the data contained in a given node
*/
public class CreateOperation extends ZooKeeperOperation<String> {
private static final List<ACL> DEFAULT_PERMISSIONS = Ids.OPEN_ACL_UNSAFE;
private static final CreateMode DEFAULT_MODE = CreateMode.EPHEMERAL;
private byte[] data;
private List<ACL> permissions = DEFAULT_PERMISSIONS;
private CreateMode createMode = DEFAULT_MODE;
public CreateOperation(ZooKeeper connection, String node) {
super(connection, node);
}
@Override
public OperationResult<String> getResult() {
try {
String created = connection.create(node, data, permissions, createMode);
if (LOG.isDebugEnabled()) {
LOG.debug(format("Created node '%s' using mode '%s'", created, createMode));
}
// for consistency with other operations return an empty stats set.
return new OperationResult<String>(created, new Stat());
} catch (Exception e) {
return new OperationResult<String>(e);
}
}
public void setData(byte[] data) {
this.data = data;
}
public void setPermissions(List<ACL> permissions) {
this.permissions = permissions;
}
public void setCreateMode(CreateMode createMode) {
this.createMode = createMode;
}
}
| YMartsynkevych/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/operations/CreateOperation.java | Java | apache-2.0 | 2,550 |
/*
* Copyright 2005 Sascha Weinreuter
*
* 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 org.intellij.lang.xpath;
import com.intellij.lang.Commenter;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import org.jetbrains.annotations.NotNull;
public final class XPath2Language extends Language {
public static final String ID = "XPath2";
XPath2Language() {
super(Language.findLanguageByID(XPathLanguage.ID), ID);
}
@Override
public XPathFileType getAssociatedFileType() {
return XPathFileType.XPATH2;
}
public static class XPathSyntaxHighlighterFactory extends SingleLazyInstanceSyntaxHighlighterFactory {
@NotNull
protected SyntaxHighlighter createHighlighter() {
return new XPathHighlighter(true);
}
}
public static class XPath2Commenter implements Commenter {
@Override
public String getLineCommentPrefix() {
return null;
}
@Override
public String getBlockCommentPrefix() {
return "(:";
}
@Override
public String getBlockCommentSuffix() {
return ":)";
}
@Override
public String getCommentedBlockCommentPrefix() {
return getBlockCommentPrefix();
}
@Override
public String getCommentedBlockCommentSuffix() {
return getBlockCommentSuffix();
}
}
}
| clumsy/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPath2Language.java | Java | apache-2.0 | 1,943 |
// 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.
#include "tools/json_schema_compiler/test/simple_api.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace test::api::simple_api;
namespace {
static scoped_ptr<base::DictionaryValue> CreateTestTypeDictionary() {
scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
value->SetWithoutPathExpansion("number", new base::FundamentalValue(1.1));
value->SetWithoutPathExpansion("integer", new base::FundamentalValue(4));
value->SetWithoutPathExpansion("string", new base::StringValue("bling"));
value->SetWithoutPathExpansion("boolean", new base::FundamentalValue(true));
return value.Pass();
}
} // namespace
TEST(JsonSchemaCompilerSimpleTest, IncrementIntegerResultCreate) {
scoped_ptr<base::ListValue> results = IncrementInteger::Results::Create(5);
base::ListValue expected;
expected.Append(new base::FundamentalValue(5));
EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerSimpleTest, IncrementIntegerParamsCreate) {
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::FundamentalValue(6));
scoped_ptr<IncrementInteger::Params> params(
IncrementInteger::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_EQ(6, params->num);
}
TEST(JsonSchemaCompilerSimpleTest, NumberOfParams) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::StringValue("text"));
params_value->Append(new base::StringValue("text"));
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_FALSE(params.get());
}
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
scoped_ptr<IncrementInteger::Params> params(
IncrementInteger::Params::Create(*params_value));
EXPECT_FALSE(params.get());
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalStringParamsCreate) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_FALSE(params->str.get());
}
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::StringValue("asdf"));
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_TRUE(params->str.get());
EXPECT_EQ("asdf", *params->str);
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalParamsTakingNull) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(base::Value::CreateNullValue());
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_FALSE(params->str.get());
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalStringParamsWrongType) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::FundamentalValue(5));
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_FALSE(params.get());
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalBeforeRequired) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(base::Value::CreateNullValue());
params_value->Append(new base::StringValue("asdf"));
scoped_ptr<OptionalBeforeRequired::Params> params(
OptionalBeforeRequired::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_FALSE(params->first.get());
EXPECT_EQ("asdf", params->second);
}
}
TEST(JsonSchemaCompilerSimpleTest, NoParamsResultCreate) {
scoped_ptr<base::ListValue> results = OptionalString::Results::Create();
base::ListValue expected;
EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerSimpleTest, TestTypePopulate) {
{
scoped_ptr<TestType> test_type(new TestType());
scoped_ptr<base::DictionaryValue> value = CreateTestTypeDictionary();
EXPECT_TRUE(TestType::Populate(*value, test_type.get()));
EXPECT_EQ("bling", test_type->string);
EXPECT_EQ(1.1, test_type->number);
EXPECT_EQ(4, test_type->integer);
EXPECT_EQ(true, test_type->boolean);
EXPECT_TRUE(value->Equals(test_type->ToValue().get()));
}
{
scoped_ptr<TestType> test_type(new TestType());
scoped_ptr<base::DictionaryValue> value = CreateTestTypeDictionary();
value->Remove("number", NULL);
EXPECT_FALSE(TestType::Populate(*value, test_type.get()));
}
}
TEST(JsonSchemaCompilerSimpleTest, GetTestType) {
{
scoped_ptr<base::DictionaryValue> value = CreateTestTypeDictionary();
scoped_ptr<TestType> test_type(new TestType());
EXPECT_TRUE(TestType::Populate(*value, test_type.get()));
scoped_ptr<base::ListValue> results =
GetTestType::Results::Create(*test_type);
base::DictionaryValue* result = NULL;
results->GetDictionary(0, &result);
EXPECT_TRUE(result->Equals(value.get()));
}
}
TEST(JsonSchemaCompilerSimpleTest, OnIntegerFiredCreate) {
{
scoped_ptr<base::ListValue> results(OnIntegerFired::Create(5));
base::ListValue expected;
expected.Append(new base::FundamentalValue(5));
EXPECT_TRUE(results->Equals(&expected));
}
}
TEST(JsonSchemaCompilerSimpleTest, OnStringFiredCreate) {
{
scoped_ptr<base::ListValue> results(OnStringFired::Create("yo dawg"));
base::ListValue expected;
expected.Append(new base::StringValue("yo dawg"));
EXPECT_TRUE(results->Equals(&expected));
}
}
TEST(JsonSchemaCompilerSimpleTest, OnTestTypeFiredCreate) {
{
TestType some_test_type;
scoped_ptr<base::DictionaryValue> expected = CreateTestTypeDictionary();
ASSERT_TRUE(expected->GetDouble("number", &some_test_type.number));
ASSERT_TRUE(expected->GetString("string", &some_test_type.string));
ASSERT_TRUE(expected->GetInteger("integer", &some_test_type.integer));
ASSERT_TRUE(expected->GetBoolean("boolean", &some_test_type.boolean));
scoped_ptr<base::ListValue> results(
OnTestTypeFired::Create(some_test_type));
base::DictionaryValue* result = NULL;
results->GetDictionary(0, &result);
EXPECT_TRUE(result->Equals(expected.get()));
}
}
| CTSRD-SOAAP/chromium-42.0.2311.135 | tools/json_schema_compiler/test/simple_api_unittest.cc | C++ | bsd-3-clause | 6,511 |
// Copyright 2014 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package internal
// This file implements a network dialer that limits the number of concurrent connections.
// It is only used for API calls.
import (
"log"
"net"
"runtime"
"sync"
"time"
)
var limitSem = make(chan int, 100) // TODO(dsymonds): Use environment variable.
func limitRelease() {
// non-blocking
select {
case <-limitSem:
default:
// This should not normally happen.
log.Print("appengine: unbalanced limitSem release!")
}
}
func limitDial(network, addr string) (net.Conn, error) {
limitSem <- 1
// Dial with a timeout in case the API host is MIA.
// The connection should normally be very fast.
conn, err := net.DialTimeout(network, addr, 500*time.Millisecond)
if err != nil {
limitRelease()
return nil, err
}
lc := &limitConn{Conn: conn}
runtime.SetFinalizer(lc, (*limitConn).Close) // shouldn't usually be required
return lc, nil
}
type limitConn struct {
close sync.Once
net.Conn
}
func (lc *limitConn) Close() error {
defer lc.close.Do(func() {
limitRelease()
runtime.SetFinalizer(lc, nil)
})
return lc.Conn.Close()
}
| ae6rt/decap | web/vendor/google.golang.org/appengine/internal/net.go | GO | mit | 1,236 |
/// <reference path="denodeify.d.ts" />
/// <reference path="../node/node.d.ts" />
import denodeify = require("denodeify");
import fs = require('fs');
import cp = require('child_process');
const readFile = denodeify<string,string,string>(fs.readFile);
const exec = denodeify<string,string>(cp.exec, (err, stdout, stderr) => [err, stdout]);
| Pro/DefinitelyTyped | denodeify/denodeify-tests.ts | TypeScript | mit | 342 |
/* { dg-do compile } */
/* { dg-require-effective-target ia32 } */
/* { dg-require-effective-target fpic } */
/* { dg-skip-if "" { *-*-* } { "-march=*" } { "-march=atom" } } */
/* { dg-skip-if "No Windows PIC" { *-*-mingw* *-*-cygwin } { "*" } { "" } } */
/* { dg-options "-O2 -fomit-frame-pointer -march=atom -fPIC" } */
/* { dg-final { scan-assembler-times "nop" 8 } } */
/* { dg-final { scan-assembler-not "rep" } } */
extern int bar;
int
foo ()
{
asm volatile ("");
return bar;
}
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/gcc.target/i386/pad-4.c | C | gpl-3.0 | 490 |
package graph
import (
"strings"
"github.com/docker/docker/engine"
"github.com/docker/docker/image"
)
func (s *TagStore) CmdViz(job *engine.Job) engine.Status {
images, _ := s.graph.Map()
if images == nil {
return engine.StatusOK
}
job.Stdout.Write([]byte("digraph docker {\n"))
var (
parentImage *image.Image
err error
)
for _, image := range images {
parentImage, err = image.GetParent()
if err != nil {
return job.Errorf("Error while getting parent image: %v", err)
}
if parentImage != nil {
job.Stdout.Write([]byte(" \"" + parentImage.ID + "\" -> \"" + image.ID + "\"\n"))
} else {
job.Stdout.Write([]byte(" base -> \"" + image.ID + "\" [style=invis]\n"))
}
}
for id, repos := range s.GetRepoRefs() {
job.Stdout.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
}
job.Stdout.Write([]byte(" base [style=invisible]\n}\n"))
return engine.StatusOK
}
| openshift/dockerexec | vendor/src/github.com/docker/docker/graph/viz.go | GO | apache-2.0 | 1,016 |
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "PathOpsExtendedTest.h"
#include "PathOpsThreadedCommon.h"
static void testOpCubicsMain(PathOpsThreadState* data) {
#if DEBUG_SHOW_TEST_NAME
strncpy(DEBUG_FILENAME_STRING, "", DEBUG_FILENAME_STRING_LENGTH);
#endif
SkASSERT(data);
PathOpsThreadState& state = *data;
char pathStr[1024]; // gdb: set print elements 400
bool progress = state.fReporter->verbose(); // FIXME: break out into its own parameter?
if (progress) {
sk_bzero(pathStr, sizeof(pathStr));
}
for (int a = 0 ; a < 6; ++a) {
for (int b = a + 1 ; b < 7; ++b) {
for (int c = 0 ; c < 6; ++c) {
for (int d = c + 1 ; d < 7; ++d) {
for (int e = SkPath::kWinding_FillType ; e <= SkPath::kEvenOdd_FillType; ++e) {
for (int f = SkPath::kWinding_FillType ; f <= SkPath::kEvenOdd_FillType; ++f) {
SkPath pathA, pathB;
if (progress) {
char* str = pathStr;
str += sprintf(str, " path.setFillType(SkPath::k%s_FillType);\n",
e == SkPath::kWinding_FillType ? "Winding" : e == SkPath::kEvenOdd_FillType
? "EvenOdd" : "?UNDEFINED");
str += sprintf(str, " path.moveTo(%d,%d);\n", state.fA, state.fB);
str += sprintf(str, " path.cubicTo(%d,%d, %d,%d, %d,%d);\n", state.fC, state.fD,
b, a, d, c);
str += sprintf(str, " path.close();\n");
str += sprintf(str, " pathB.setFillType(SkPath::k%s_FillType);\n",
f == SkPath::kWinding_FillType ? "Winding" : f == SkPath::kEvenOdd_FillType
? "EvenOdd" : "?UNDEFINED");
str += sprintf(str, " pathB.moveTo(%d,%d);\n", a, b);
str += sprintf(str, " pathB.cubicTo(%d,%d, %d,%d, %d,%d);\n", c, d,
state.fB, state.fA, state.fD, state.fC);
str += sprintf(str, " pathB.close();\n");
}
pathA.setFillType((SkPath::FillType) e);
pathA.moveTo(SkIntToScalar(state.fA), SkIntToScalar(state.fB));
pathA.cubicTo(SkIntToScalar(state.fC), SkIntToScalar(state.fD), SkIntToScalar(b),
SkIntToScalar(a), SkIntToScalar(d), SkIntToScalar(c));
pathA.close();
pathB.setFillType((SkPath::FillType) f);
pathB.moveTo(SkIntToScalar(a), SkIntToScalar(b));
pathB.cubicTo(SkIntToScalar(c), SkIntToScalar(d), SkIntToScalar(state.fB),
SkIntToScalar(state.fA), SkIntToScalar(state.fD), SkIntToScalar(state.fC));
pathB.close();
for (int op = 0 ; op <= kXOR_PathOp; ++op) {
if (progress) {
outputProgress(state.fPathStr, pathStr, (SkPathOp) op);
}
testThreadedPathOp(state.fReporter, pathA, pathB, (SkPathOp) op, "cubics");
}
}
}
}
}
}
}
}
DEF_TEST(PathOpsOpCubicsThreaded, reporter) {
int threadCount = initializeTests(reporter, "cubicOp");
PathOpsThreadedTestRunner testRunner(reporter, threadCount);
for (int a = 0; a < 6; ++a) { // outermost
for (int b = a + 1; b < 7; ++b) {
for (int c = 0 ; c < 6; ++c) {
for (int d = c + 1; d < 7; ++d) {
*testRunner.fRunnables.append() = SkNEW_ARGS(PathOpsThreadedRunnable,
(&testOpCubicsMain, a, b, c, d, &testRunner));
}
}
if (!reporter->allowExtendedTest()) goto finish;
}
}
finish:
testRunner.render();
ShowTestArray();
}
| ench0/external_skia | tests/PathOpsOpCubicThreadedTest.cpp | C++ | bsd-3-clause | 3,732 |
.foo > .bar, .foo > .bip + .baz {
a: b; }
| studiochakra/teamlinkmuaythai.com | wp-content/themes/symetrio-theme/node_modules/gulp-sass/node_modules/node-sass/test/fixtures/spec/spec/extend-tests/125_test_nested_extender_with_early_child_selector/expected_output.css | CSS | gpl-2.0 | 44 |
import * as angular from 'angular';
angular
.module('app', ['ngDesktopNotification'])
.config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => {
desktopNotificationProvider.config({
autoClose: true,
duration: 5,
showOnPageHidden: false,
});
}])
.controller('AppController', ['desktopNotification', (desktopNotification: angular.desktopNotification.IDesktopNotificationService) => {
// Check support and permission
const isNotificationSupported = desktopNotification.isSupported();
const currentNotificationPermission = desktopNotification.currentPermission();
if (currentNotificationPermission === desktopNotification.permissions.granted) {
// Permission granted
}
// Request permission
desktopNotification.requestPermission().then(
// Permission granted
(permission) => {
// Show notification
desktopNotification.show(
"Notification title",
{
tag: "tag",
body: "Notification body",
icon: "https://www.iconurl.com/icon-name.icon-extension",
onClick: () => {
// Notification clicked
}
});
},
() => {
// No permission granted
});
}]);
| borisyankov/DefinitelyTyped | types/angular-desktop-notification/angular-desktop-notification-tests.ts | TypeScript | mit | 1,560 |
/* SPDX-License-Identifier: GPL-2.0 */
/******************************************************************************
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#ifndef __STA_INFO_H_
#define __STA_INFO_H_
#include "osdep_service.h"
#include "drv_types.h"
#include "wifi.h"
#define NUM_STA 32
#define NUM_ACL 64
/* if mode ==0, then the sta is allowed once the addr is hit.
* if mode ==1, then the sta is rejected once the addr is non-hit.
*/
struct wlan_acl_node {
struct list_head list;
u8 addr[ETH_ALEN];
u8 mode;
};
struct wlan_acl_pool {
struct wlan_acl_node aclnode[NUM_ACL];
};
struct stainfo_stats {
uint rx_pkts;
uint rx_bytes;
u64 tx_pkts;
uint tx_bytes;
};
struct sta_info {
spinlock_t lock;
struct list_head list; /*free_sta_queue*/
struct list_head hash_list; /*sta_hash*/
struct sta_xmit_priv sta_xmitpriv;
struct sta_recv_priv sta_recvpriv;
uint state;
uint aid;
uint mac_id;
uint qos_option;
u8 hwaddr[ETH_ALEN];
uint ieee8021x_blocked; /*0: allowed, 1:blocked */
uint XPrivacy; /*aes, tkip...*/
union Keytype tkiptxmickey;
union Keytype tkiprxmickey;
union Keytype x_UncstKey;
union pn48 txpn; /* PN48 used for Unicast xmit.*/
union pn48 rxpn; /* PN48 used for Unicast recv.*/
u8 bssrateset[16];
uint bssratelen;
s32 rssi;
s32 signal_quality;
struct stainfo_stats sta_stats;
/*for A-MPDU Rx reordering buffer control */
struct recv_reorder_ctrl recvreorder_ctrl[16];
struct ht_priv htpriv;
/* Notes:
* STA_Mode:
* curr_network(mlme_priv/security_priv/qos/ht)
* + sta_info: (STA & AP) CAP/INFO
* scan_q: AP CAP/INFO
* AP_Mode:
* curr_network(mlme_priv/security_priv/qos/ht) : AP CAP/INFO
* sta_info: (AP & STA) CAP/INFO
*/
struct list_head asoc_list;
struct list_head auth_list;
unsigned int expire_to;
unsigned int auth_seq;
unsigned int authalg;
unsigned char chg_txt[128];
unsigned int tx_ra_bitmap;
};
struct sta_priv {
u8 *pallocated_stainfo_buf;
u8 *pstainfo_buf;
struct __queue free_sta_queue;
spinlock_t sta_hash_lock;
struct list_head sta_hash[NUM_STA];
int asoc_sta_count;
struct __queue sleep_q;
struct __queue wakeup_q;
struct _adapter *padapter;
struct list_head asoc_list;
struct list_head auth_list;
unsigned int auth_to; /* sec, time to expire in authenticating. */
unsigned int assoc_to; /* sec, time to expire before associating. */
unsigned int expire_to; /* sec , time to expire after associated. */
};
static inline u32 wifi_mac_hash(u8 *mac)
{
u32 x;
x = mac[0];
x = (x << 2) ^ mac[1];
x = (x << 2) ^ mac[2];
x = (x << 2) ^ mac[3];
x = (x << 2) ^ mac[4];
x = (x << 2) ^ mac[5];
x ^= x >> 8;
x = x & (NUM_STA - 1);
return x;
}
int _r8712_init_sta_priv(struct sta_priv *pstapriv);
void _r8712_free_sta_priv(struct sta_priv *pstapriv);
struct sta_info *r8712_alloc_stainfo(struct sta_priv *pstapriv,
u8 *hwaddr);
void r8712_free_stainfo(struct _adapter *padapter, struct sta_info *psta);
void r8712_free_all_stainfo(struct _adapter *padapter);
struct sta_info *r8712_get_stainfo(struct sta_priv *pstapriv, u8 *hwaddr);
void r8712_init_bcmc_stainfo(struct _adapter *padapter);
struct sta_info *r8712_get_bcmc_stainfo(struct _adapter *padapter);
u8 r8712_access_ctrl(struct wlan_acl_pool *pacl_list, u8 *mac_addr);
#endif /* _STA_INFO_H_ */
| cminyard/linux-live-app-coredump | drivers/staging/rtl8712/sta_info.h | C | gpl-2.0 | 3,642 |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: petar@google.com (Petar Petrov)
#include <Python.h>
#include <string>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#define C(str) const_cast<char*>(str)
#if PY_MAJOR_VERSION >= 3
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
#define PyInt_FromLong PyLong_FromLong
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#else
#define PyString_AsString(ob) \
(PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AS_STRING(ob))
#endif
#endif
namespace google {
namespace protobuf {
namespace python {
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
#endif
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
static google::protobuf::DescriptorPool* g_descriptor_pool = NULL;
namespace cfield_descriptor {
static void Dealloc(CFieldDescriptor* self) {
Py_CLEAR(self->descriptor_field);
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
static PyObject* GetFullName(CFieldDescriptor* self, void *closure) {
return PyString_FromStringAndSize(
self->descriptor->full_name().c_str(),
self->descriptor->full_name().size());
}
static PyObject* GetName(CFieldDescriptor *self, void *closure) {
return PyString_FromStringAndSize(
self->descriptor->name().c_str(),
self->descriptor->name().size());
}
static PyObject* GetCppType(CFieldDescriptor *self, void *closure) {
return PyInt_FromLong(self->descriptor->cpp_type());
}
static PyObject* GetLabel(CFieldDescriptor *self, void *closure) {
return PyInt_FromLong(self->descriptor->label());
}
static PyObject* GetID(CFieldDescriptor *self, void *closure) {
return PyLong_FromVoidPtr(self);
}
static PyGetSetDef Getters[] = {
{ C("full_name"), (getter)GetFullName, NULL, "Full name", NULL},
{ C("name"), (getter)GetName, NULL, "last name", NULL},
{ C("cpp_type"), (getter)GetCppType, NULL, "C++ Type", NULL},
{ C("label"), (getter)GetLabel, NULL, "Label", NULL},
{ C("id"), (getter)GetID, NULL, "ID", NULL},
{NULL}
};
} // namespace cfield_descriptor
PyTypeObject CFieldDescriptor_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
C("google.protobuf.internal."
"_net_proto2___python."
"CFieldDescriptor"), // tp_name
sizeof(CFieldDescriptor), // tp_basicsize
0, // tp_itemsize
(destructor)cfield_descriptor::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
C("A Field Descriptor"), // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
cfield_descriptor::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyType_GenericAlloc, // tp_alloc
PyType_GenericNew, // tp_new
PyObject_Del, // tp_free
};
namespace cdescriptor_pool {
static void Dealloc(CDescriptorPool* self) {
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
static PyObject* NewCDescriptor(
const google::protobuf::FieldDescriptor* field_descriptor) {
CFieldDescriptor* cfield_descriptor = PyObject_New(
CFieldDescriptor, &CFieldDescriptor_Type);
if (cfield_descriptor == NULL) {
return NULL;
}
cfield_descriptor->descriptor = field_descriptor;
cfield_descriptor->descriptor_field = NULL;
return reinterpret_cast<PyObject*>(cfield_descriptor);
}
PyObject* FindFieldByName(CDescriptorPool* self, PyObject* name) {
const char* full_field_name = PyString_AsString(name);
if (full_field_name == NULL) {
return NULL;
}
const google::protobuf::FieldDescriptor* field_descriptor = NULL;
field_descriptor = self->pool->FindFieldByName(full_field_name);
if (field_descriptor == NULL) {
PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s",
full_field_name);
return NULL;
}
return NewCDescriptor(field_descriptor);
}
PyObject* FindExtensionByName(CDescriptorPool* self, PyObject* arg) {
const char* full_field_name = PyString_AsString(arg);
if (full_field_name == NULL) {
return NULL;
}
const google::protobuf::FieldDescriptor* field_descriptor =
self->pool->FindExtensionByName(full_field_name);
if (field_descriptor == NULL) {
PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s",
full_field_name);
return NULL;
}
return NewCDescriptor(field_descriptor);
}
static PyMethodDef Methods[] = {
{ C("FindFieldByName"),
(PyCFunction)FindFieldByName,
METH_O,
C("Searches for a field descriptor by full name.") },
{ C("FindExtensionByName"),
(PyCFunction)FindExtensionByName,
METH_O,
C("Searches for extension descriptor by full name.") },
{NULL}
};
} // namespace cdescriptor_pool
PyTypeObject CDescriptorPool_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
C("google.protobuf.internal."
"_net_proto2___python."
"CFieldDescriptor"), // tp_name
sizeof(CDescriptorPool), // tp_basicsize
0, // tp_itemsize
(destructor)cdescriptor_pool::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
C("A Descriptor Pool"), // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
cdescriptor_pool::Methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyType_GenericAlloc, // tp_alloc
PyType_GenericNew, // tp_new
PyObject_Del, // tp_free
};
google::protobuf::DescriptorPool* GetDescriptorPool() {
if (g_descriptor_pool == NULL) {
g_descriptor_pool = new google::protobuf::DescriptorPool(
google::protobuf::DescriptorPool::generated_pool());
}
return g_descriptor_pool;
}
PyObject* Python_NewCDescriptorPool(PyObject* ignored, PyObject* args) {
CDescriptorPool* cdescriptor_pool = PyObject_New(
CDescriptorPool, &CDescriptorPool_Type);
if (cdescriptor_pool == NULL) {
return NULL;
}
cdescriptor_pool->pool = GetDescriptorPool();
return reinterpret_cast<PyObject*>(cdescriptor_pool);
}
// Collects errors that occur during proto file building to allow them to be
// propagated in the python exception instead of only living in ERROR logs.
class BuildFileErrorCollector : public google::protobuf::DescriptorPool::ErrorCollector {
public:
BuildFileErrorCollector() : error_message(""), had_errors(false) {}
void AddError(const string& filename, const string& element_name,
const Message* descriptor, ErrorLocation location,
const string& message) {
// Replicates the logging behavior that happens in the C++ implementation
// when an error collector is not passed in.
if (!had_errors) {
error_message +=
("Invalid proto descriptor for file \"" + filename + "\":\n");
}
// As this only happens on failure and will result in the program not
// running at all, no effort is made to optimize this string manipulation.
error_message += (" " + element_name + ": " + message + "\n");
}
string error_message;
bool had_errors;
};
PyObject* Python_BuildFile(PyObject* ignored, PyObject* arg) {
char* message_type;
Py_ssize_t message_len;
if (PyBytes_AsStringAndSize(arg, &message_type, &message_len) < 0) {
return NULL;
}
google::protobuf::FileDescriptorProto file_proto;
if (!file_proto.ParseFromArray(message_type, message_len)) {
PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!");
return NULL;
}
if (google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
file_proto.name()) != NULL) {
Py_RETURN_NONE;
}
BuildFileErrorCollector error_collector;
const google::protobuf::FileDescriptor* descriptor =
GetDescriptorPool()->BuildFileCollectingErrors(file_proto,
&error_collector);
if (descriptor == NULL) {
PyErr_Format(PyExc_TypeError,
"Couldn't build proto file into descriptor pool!\n%s",
error_collector.error_message.c_str());
return NULL;
}
Py_RETURN_NONE;
}
bool InitDescriptor() {
CFieldDescriptor_Type.tp_new = PyType_GenericNew;
if (PyType_Ready(&CFieldDescriptor_Type) < 0)
return false;
CDescriptorPool_Type.tp_new = PyType_GenericNew;
if (PyType_Ready(&CDescriptorPool_Type) < 0)
return false;
return true;
}
} // namespace python
} // namespace protobuf
} // namespace google
| cherrishes/weilai | xingxing/protobuf/python/lib/Python3.4/google/protobuf/pyext/descriptor.cc | C++ | apache-2.0 | 13,106 |
/**
* 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.hadoop.mapred;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* This class tests reliability of the framework in the face of failures of
* both tasks and tasktrackers. Steps:
* 1) Get the cluster status
* 2) Get the number of slots in the cluster
* 3) Spawn a sleepjob that occupies the entire cluster (with two waves of maps)
* 4) Get the list of running attempts for the job
* 5) Fail a few of them
* 6) Now fail a few trackers (ssh)
* 7) Job should run to completion
* 8) The above is repeated for the Sort suite of job (randomwriter, sort,
* validator). All jobs must complete, and finally, the sort validation
* should succeed.
* To run the test:
* ./bin/hadoop --config <config> jar
* build/hadoop-<version>-test.jar MRReliabilityTest -libjars
* build/hadoop-<version>-examples.jar [-scratchdir <dir>]"
*
* The scratchdir is optional and by default the current directory on the client
* will be used as the scratch space. Note that password-less SSH must be set up
* between the client machine from where the test is submitted, and the cluster
* nodes where the test runs.
*
* The test should be run on a <b>free</b> cluster where there is no other parallel
* job submission going on. Submission of other jobs while the test runs can cause
* the tests/jobs submitted to fail.
*/
public class ReliabilityTest extends Configured implements Tool {
private String dir;
private static final Log LOG = LogFactory.getLog(ReliabilityTest.class);
private void displayUsage() {
LOG.info("This must be run in only the distributed mode " +
"(LocalJobRunner not supported).\n\tUsage: MRReliabilityTest " +
"-libjars <path to hadoop-examples.jar> [-scratchdir <dir>]" +
"\n[-scratchdir] points to a scratch space on this host where temp" +
" files for this test will be created. Defaults to current working" +
" dir. \nPasswordless SSH must be set up between this host and the" +
" nodes which the test is going to use.\n"+
"The test should be run on a free cluster with no parallel job submission" +
" going on, as the test requires to restart TaskTrackers and kill tasks" +
" any job submission while the tests are running can cause jobs/tests to fail");
System.exit(-1);
}
public int run(String[] args) throws Exception {
Configuration conf = getConf();
if ("local".equals(conf.get("mapred.job.tracker", "local"))) {
displayUsage();
}
String[] otherArgs =
new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length == 2) {
if (otherArgs[0].equals("-scratchdir")) {
dir = otherArgs[1];
} else {
displayUsage();
}
}
else if (otherArgs.length == 0) {
dir = System.getProperty("user.dir");
} else {
displayUsage();
}
//to protect against the case of jobs failing even when multiple attempts
//fail, set some high values for the max attempts
conf.setInt("mapred.map.max.attempts", 10);
conf.setInt("mapred.reduce.max.attempts", 10);
runSleepJobTest(new JobClient(new JobConf(conf)), conf);
runSortJobTests(new JobClient(new JobConf(conf)), conf);
return 0;
}
private void runSleepJobTest(final JobClient jc, final Configuration conf)
throws Exception {
ClusterStatus c = jc.getClusterStatus();
int maxMaps = c.getMaxMapTasks() * 2;
int maxReduces = maxMaps;
int mapSleepTime = (int)c.getTTExpiryInterval();
int reduceSleepTime = mapSleepTime;
String[] sleepJobArgs = new String[] {
"-m", Integer.toString(maxMaps),
"-r", Integer.toString(maxReduces),
"-mt", Integer.toString(mapSleepTime),
"-rt", Integer.toString(reduceSleepTime)};
runTest(jc, conf, "org.apache.hadoop.examples.SleepJob", sleepJobArgs,
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.4f, false, 1));
LOG.info("SleepJob done");
}
private void runSortJobTests(final JobClient jc, final Configuration conf)
throws Exception {
String inputPath = "my_reliability_test_input";
String outputPath = "my_reliability_test_output";
FileSystem fs = jc.getFs();
fs.delete(new Path(inputPath), true);
fs.delete(new Path(outputPath), true);
runRandomWriterTest(jc, conf, inputPath);
runSortTest(jc, conf, inputPath, outputPath);
runSortValidatorTest(jc, conf, inputPath, outputPath);
}
private void runRandomWriterTest(final JobClient jc,
final Configuration conf, final String inputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.RandomWriter",
new String[]{inputPath},
null, new KillTrackerThread(jc, 0, 0.4f, false, 1));
LOG.info("RandomWriter job done");
}
private void runSortTest(final JobClient jc, final Configuration conf,
final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.Sort",
new String[]{inputPath, outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("Sort job done");
}
private void runSortValidatorTest(final JobClient jc,
final Configuration conf, final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.mapred.SortValidator", new String[] {
"-sortInput", inputPath, "-sortOutput", outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 1),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("SortValidator job done");
}
private String normalizeCommandPath(String command) {
final String hadoopHome;
if ((hadoopHome = System.getenv("HADOOP_HOME")) != null) {
command = hadoopHome + "/" + command;
}
return command;
}
private void checkJobExitStatus(int status, String jobName) {
if (status != 0) {
LOG.info(jobName + " job failed with status: " + status);
System.exit(status);
} else {
LOG.info(jobName + " done.");
}
}
//Starts the job in a thread. It also starts the taskKill/tasktrackerKill
//threads.
private void runTest(final JobClient jc, final Configuration conf,
final String jobClass, final String[] args, KillTaskThread killTaskThread,
KillTrackerThread killTrackerThread) throws Exception {
Thread t = new Thread("Job Test") {
public void run() {
try {
Class<?> jobClassObj = conf.getClassByName(jobClass);
int status = ToolRunner.run(conf, (Tool)(jobClassObj.newInstance()),
args);
checkJobExitStatus(status, jobClass);
} catch (Exception e) {
LOG.fatal("JOB " + jobClass + " failed to run");
System.exit(-1);
}
}
};
t.setDaemon(true);
t.start();
JobStatus[] jobs;
//get the job ID. This is the job that we just submitted
while ((jobs = jc.jobsToComplete()).length == 0) {
LOG.info("Waiting for the job " + jobClass +" to start");
Thread.sleep(1000);
}
JobID jobId = jobs[jobs.length - 1].getJobID();
RunningJob rJob = jc.getJob(jobId);
if(rJob.isComplete()) {
LOG.error("The last job returned by the querying JobTracker is complete :" +
rJob.getJobID() + " .Exiting the test");
System.exit(-1);
}
while (rJob.getJobState() == JobStatus.PREP) {
LOG.info("JobID : " + jobId + " not started RUNNING yet");
Thread.sleep(1000);
rJob = jc.getJob(jobId);
}
if (killTaskThread != null) {
killTaskThread.setRunningJob(rJob);
killTaskThread.start();
killTaskThread.join();
LOG.info("DONE WITH THE TASK KILL/FAIL TESTS");
}
if (killTrackerThread != null) {
killTrackerThread.setRunningJob(rJob);
killTrackerThread.start();
killTrackerThread.join();
LOG.info("DONE WITH THE TESTS TO DO WITH LOST TASKTRACKERS");
}
t.join();
}
private class KillTrackerThread extends Thread {
private volatile boolean killed = false;
private JobClient jc;
private RunningJob rJob;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
final private String slavesFile = dir + "/_reliability_test_slaves_file_";
final String shellCommand = normalizeCommandPath("bin/slaves.sh");
final private String STOP_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s STOP";
final private String RESUME_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s CONT";
//Only one instance must be active at any point
public KillTrackerThread(JobClient jc, int threshaldMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = threshaldMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
stopStartTrackers(true);
if (!onlyMapsProgress) {
stopStartTrackers(false);
}
}
private void stopStartTrackers(boolean considerMaps) {
if (considerMaps) {
LOG.info("Will STOP/RESUME tasktrackers based on Maps'" +
" progress");
} else {
LOG.info("Will STOP/RESUME tasktrackers based on " +
"Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
ClusterStatus c;
stopTaskTrackers((c = jc.getClusterStatus(true)));
Thread.sleep((int)Math.ceil(1.5 * c.getTTExpiryInterval()));
startTaskTrackers();
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
return;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
private void stopTaskTrackers(ClusterStatus c) throws Exception {
Collection <String> trackerNames = c.getActiveTrackerNames();
ArrayList<String> trackerNamesList = new ArrayList<String>(trackerNames);
Collections.shuffle(trackerNamesList);
int count = 0;
FileOutputStream fos = new FileOutputStream(new File(slavesFile));
LOG.info(new Date() + " Stopping a few trackers");
for (String tracker : trackerNamesList) {
String host = convertTrackerNameToHostName(tracker);
LOG.info(new Date() + " Marking tracker on host: " + host);
fos.write((host + "\n").getBytes());
if (count++ >= trackerNamesList.size()/2) {
break;
}
}
fos.close();
runOperationOnTT("suspend");
}
private void startTaskTrackers() throws Exception {
LOG.info(new Date() + " Resuming the stopped trackers");
runOperationOnTT("resume");
new File(slavesFile).delete();
}
private void runOperationOnTT(String operation) throws IOException {
Map<String,String> hMap = new HashMap<String,String>();
hMap.put("HADOOP_SLAVES", slavesFile);
StringTokenizer strToken;
if (operation.equals("suspend")) {
strToken = new StringTokenizer(STOP_COMMAND, " ");
} else {
strToken = new StringTokenizer(RESUME_COMMAND, " ");
}
String commandArgs[] = new String[strToken.countTokens() + 1];
int i = 0;
commandArgs[i++] = shellCommand;
while (strToken.hasMoreTokens()) {
commandArgs[i++] = strToken.nextToken();
}
String output = Shell.execCommand(hMap, commandArgs);
if (output != null && !output.equals("")) {
LOG.info(output);
}
}
private String convertTrackerNameToHostName(String trackerName) {
// Convert the trackerName to it's host name
int indexOfColon = trackerName.indexOf(":");
String trackerHostName = (indexOfColon == -1) ?
trackerName :
trackerName.substring(0, indexOfColon);
return trackerHostName.substring("tracker_".length());
}
}
private class KillTaskThread extends Thread {
private volatile boolean killed = false;
private RunningJob rJob;
private JobClient jc;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
public KillTaskThread(JobClient jc, int thresholdMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = thresholdMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
killBasedOnProgress(true);
if (!onlyMapsProgress) {
killBasedOnProgress(false);
}
}
private void killBasedOnProgress(boolean considerMaps) {
boolean fail = false;
if (considerMaps) {
LOG.info("Will kill tasks based on Maps' progress");
} else {
LOG.info("Will kill tasks based on Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
if (numIterationsDone > 0 && numIterationsDone % 2 == 0) {
fail = true; //fail tasks instead of kill
}
ClusterStatus c = jc.getClusterStatus();
LOG.info(new Date() + " Killing a few tasks");
Collection<TaskAttemptID> runningTasks =
new ArrayList<TaskAttemptID>();
TaskReport mapReports[] = jc.getMapTaskReports(rJob.getID());
for (TaskReport mapReport : mapReports) {
if (mapReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(mapReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
runningTasks.clear();
TaskReport reduceReports[] = jc.getReduceTaskReports(rJob.getID());
for (TaskReport reduceReport : reduceReports) {
if (reduceReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(reduceReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
}
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new Configuration(), new ReliabilityTest(), args);
System.exit(res);
}
} | shakamunyi/hadoop-20 | src/test/org/apache/hadoop/mapred/ReliabilityTest.java | Java | apache-2.0 | 18,910 |
a enum; | Jazzling/jazzle-parser | test/test-esprima/fixtures/invalid-syntax/migrated_0115.js | JavaScript | mit | 7 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using SortedDictionaryTests.SortedDictionary_SortedDictionary_KeyCollection;
using SortedDictionary_SortedDictionaryUtils;
namespace SortedDictionaryTests
{
public class SortedDictionary_KeyCollectionTests
{
public class IntGenerator
{
private int _index;
public IntGenerator()
{
_index = 0;
}
public int NextValue()
{
return _index++;
}
public Object NextValueObject()
{
return (Object)NextValue();
}
}
public class StringGenerator
{
private int _index;
public StringGenerator()
{
_index = 0;
}
public String NextValue()
{
return (_index++).ToString();
}
public Object NextValueObject()
{
return (Object)NextValue();
}
}
[Fact]
public static void SortedDictionary_KeyCollectionTest1()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
//Scenario 1: Vanilla - fill in an SortedDictionary with 10 keys and check this property
Driver<int, int> IntDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
int count = 1000;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
for (int i = 0; i < count; i++)
ints[i] = i;
IntDriver.TestVanilla(ints, ints);
simpleRef.TestVanilla(simpleStrings, simpleStrings);
simpleVal.TestVanilla(simpleInts, simpleInts);
IntDriver.NonGenericIDictionaryTestVanilla(ints, ints);
simpleRef.NonGenericIDictionaryTestVanilla(simpleStrings, simpleStrings);
simpleVal.NonGenericIDictionaryTestVanilla(simpleInts, simpleInts);
//Scenario 2: Check for an empty SortedDictionary
IntDriver.TestVanilla(new int[0], new int[0]);
simpleRef.TestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.TestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]);
IntDriver.NonGenericIDictionaryTestVanilla(new int[0], new int[0]);
simpleRef.NonGenericIDictionaryTestVanilla(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.NonGenericIDictionaryTestVanilla(new SimpleRef<int>[0], new SimpleRef<int>[0]);
//Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the
//change is reflected
int half = count / 2;
SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half];
SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half];
int[] ints_1 = new int[half];
int[] ints_2 = new int[half];
for (int i = 0; i < half; i++)
{
simpleInts_1[i] = simpleInts[i];
simpleStrings_1[i] = simpleStrings[i];
ints_1[i] = ints[i];
simpleInts_2[i] = simpleInts[i + half];
simpleStrings_2[i] = simpleStrings[i + half];
ints_2[i] = ints[i + half];
}
IntDriver.TestModify(ints_1, ints_1, ints_2);
simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2);
IntDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2);
simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2);
}
[Fact]
public static void SortedDictionary_KeyCollectionTest_Negative()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
//Scenario 1: Vanilla - fill in SortedDictionary with 10 keys and check this property
Driver<int, int> IntDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
int count = 1000;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
for (int i = 0; i < count; i++)
ints[i] = i;
IntDriver.TestVanilla_Negative(ints, ints);
simpleRef.TestVanilla_Negative(simpleStrings, simpleStrings);
simpleVal.TestVanilla_Negative(simpleInts, simpleInts);
IntDriver.NonGenericIDictionaryTestVanilla_Negative(ints, ints);
simpleRef.NonGenericIDictionaryTestVanilla_Negative(simpleStrings, simpleStrings);
simpleVal.NonGenericIDictionaryTestVanilla_Negative(simpleInts, simpleInts);
//Scenario 2: Check for an empty SortedDictionary
IntDriver.TestVanilla_Negative(new int[0], new int[0]);
simpleRef.TestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.TestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]);
IntDriver.NonGenericIDictionaryTestVanilla_Negative(new int[0], new int[0]);
simpleRef.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<String>[0], new SimpleRef<String>[0]);
simpleVal.NonGenericIDictionaryTestVanilla_Negative(new SimpleRef<int>[0], new SimpleRef<int>[0]);
}
[Fact]
public static void SortedDictionary_KeyCollectionTest2()
{
IntGenerator intGenerator = new IntGenerator();
StringGenerator stringGenerator = new StringGenerator();
intGenerator.NextValue();
stringGenerator.NextValue();
Driver<int, int> intDriver = new Driver<int, int>();
Driver<SimpleRef<String>, SimpleRef<String>> simpleRef = new Driver<SimpleRef<String>, SimpleRef<String>>();
Driver<SimpleRef<int>, SimpleRef<int>> simpleVal = new Driver<SimpleRef<int>, SimpleRef<int>>();
//Scenario 3: Check the underlying reference. Change the SortedDictionary afterwards and examine ICollection keys and make sure that the
//change is reflected
int count = 1000;
SimpleRef<int>[] simpleInts = SortedDictionaryUtils.GetSimpleInts(count);
SimpleRef<String>[] simpleStrings = SortedDictionaryUtils.GetSimpleStrings(count);
int[] ints = new int[count];
int half = count / 2;
SimpleRef<int>[] simpleInts_1 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_1 = new SimpleRef<String>[half];
SimpleRef<int>[] simpleInts_2 = new SimpleRef<int>[half];
SimpleRef<String>[] simpleStrings_2 = new SimpleRef<String>[half];
for (int i = 0; i < count; i++)
ints[i] = i;
int[] ints_1 = new int[half];
int[] ints_2 = new int[half];
for (int i = 0; i < half; i++)
{
simpleInts_1[i] = simpleInts[i];
simpleStrings_1[i] = simpleStrings[i];
ints_1[i] = ints[i];
simpleInts_2[i] = simpleInts[i + half];
simpleStrings_2[i] = simpleStrings[i + half];
ints_2[i] = ints[i + half];
}
intDriver.TestModify(ints_1, ints_1, ints_2);
simpleRef.TestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.TestModify(simpleInts_1, simpleInts_1, simpleInts_2);
intDriver.NonGenericIDictionaryTestModify(ints_1, ints_1, ints_2);
simpleRef.NonGenericIDictionaryTestModify(simpleStrings_1, simpleStrings_1, simpleStrings_2);
simpleVal.NonGenericIDictionaryTestModify(simpleInts_1, simpleInts_1, simpleInts_2);
}
}
namespace SortedDictionary_SortedDictionary_KeyCollection
{
public class Driver<KeyType, ValueType>
{
public void TestVanilla(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
Assert.Equal(_col.Count, _dic.Count); //"Err_1! Count not equal"
IEnumerator<KeyType> _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey(_enum.Current)); //"Err_2! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_3! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_4! Expected key to be present"
count = 0;
foreach (KeyType currKey in _dic.Keys)
{
Assert.True(_dic.ContainsKey(currKey)); //"Err_5! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_6! Count not equal"
try
{
//The behavior here is undefined as long as we don't AV we're fine
KeyType item = _enum.Current;
}
catch (Exception) { }
}
// verify we get InvalidOperationException when we call MoveNext() after adding a key
public void TestVanilla_Negative(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
IEnumerator<KeyType> _enum = _col.GetEnumerator();
if (keys.Length > 0)
{
_dic.Add(keys[keys.Length - 1], values[values.Length - 1]);
Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_7! Expected InvalidOperationException."
}
}
public void TestModify(KeyType[] keys, ValueType[] values, KeyType[] newKeys)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
{
_dic.Add(keys[i], values[i]);
}
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
for (int i = 0; i < keys.Length; i++)
_dic.Remove(keys[i]);
Assert.Equal(_col.Count, 0); //"Err_8! Expected count to be zero"
IEnumerator<KeyType> _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey(_enum.Current)); //"Err_9! Expected key to be present"
count++;
}
Assert.Equal(count, 0); //"Err_10! Expected count to be zero"
for (int i = 0; i < keys.Length; i++)
_dic.Add(newKeys[i], values[i]);
Assert.Equal(_col.Count, _dic.Count); //"Err_11! Count not equal"
_enum = _col.GetEnumerator();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey(_enum.Current)); //"Err_12! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_13! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_14! Expected key to be present"
}
public void NonGenericIDictionaryTestVanilla(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
Assert.Equal(_col.Count, _dic.Count); //"Err_15! Count not equal"
IEnumerator _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_16! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_17! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_18! Expected key to be present"
_enum.Reset();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_19! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_20! Count not equal"
_keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length - 1; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_21! Expected key to be present"
}
public void NonGenericIDictionaryTestVanilla_Negative(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length - 1; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
IEnumerator _enum = _col.GetEnumerator();
// get to the end
while (_enum.MoveNext()) { }
Assert.Throws<InvalidOperationException>((() => _dic.ContainsKey((KeyType)_enum.Current))); //"Err_22! Expected InvalidOperationException."
if (keys.Length > 0)
{
_dic.Add(keys[keys.Length - 1], values[values.Length - 1]);
Assert.Throws<InvalidOperationException>((() => _enum.MoveNext())); //"Err_23! Expected InvalidOperationException."
Assert.Throws<InvalidOperationException>((() => _enum.Reset())); //"Err_24! Expected InvalidOperationException."
}
}
public void NonGenericIDictionaryTestModify(KeyType[] keys, ValueType[] values, KeyType[] newKeys)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
IDictionary _idic = _dic;
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
SortedDictionary<KeyType, ValueType>.KeyCollection _col = new SortedDictionary<KeyType, ValueType>.KeyCollection(_dic);
for (int i = 0; i < keys.Length; i++)
_dic.Remove(keys[i]);
Assert.Equal(_col.Count, 0); //"Err_25! Expected count to be zero"
IEnumerator _enum = _col.GetEnumerator();
int count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_26! Expected key to be present"
count++;
}
Assert.Equal(count, 0); //"Err_27! Expected count to be zero"
for (int i = 0; i < keys.Length; i++)
_dic.Add(newKeys[i], values[i]);
Assert.Equal(_col.Count, _dic.Count); //"Err_28! Count not equal"
_enum = _col.GetEnumerator();
count = 0;
while (_enum.MoveNext())
{
Assert.True(_dic.ContainsKey((KeyType)_enum.Current)); //"Err_29! Expected key to be present"
count++;
}
Assert.Equal(count, _dic.Count); //"Err_30! Count not equal"
KeyType[] _keys = new KeyType[_dic.Count];
_col.CopyTo(_keys, 0);
for (int i = 0; i < keys.Length; i++)
Assert.True(_dic.ContainsKey(_keys[i])); //"Err_31! Expected key to be present"
}
}
}
}
| Frank125/corefx | src/System.Collections/tests/Generic/SortedDictionary/SortedDictionary_KeyCollection.cs | C# | mit | 18,964 |
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Automatically generated strings for Moodle installer
*
* Do not edit this file manually! It contains just a subset of strings
* needed during the very first steps of installation. This file was
* generated automatically by export-installer.php (which is part of AMOS
* {@link http://docs.moodle.org/dev/Languages/AMOS}) using the
* list of strings defined in /install/stringnames.txt.
*
* @package installer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['cannotcreatelangdir'] = 'Hindi makalikha ng lang bgsk.';
$string['cannotcreatetempdir'] = 'Hindi makalikha ng temp bgsk.';
$string['cannotdownloadcomponents'] = 'Hindi mai-download ang mga sangkap';
$string['cannotdownloadzipfile'] = 'Hindi mai-download ang ZIP file.';
$string['cannotfindcomponent'] = 'Hindi makita ang component.';
$string['cannotsavemd5file'] = 'Hindi mai-save ang file na md5.';
$string['cannotsavezipfile'] = 'Hindi mai-save ang file na ZIP.';
$string['cannotunzipfile'] = 'Hindi mai-unzip ang file.';
$string['componentisuptodate'] = 'Up-to-date ang component.';
$string['downloadedfilecheckfailed'] = 'Bigo ang pagsusuri sa idinownload na file.';
$string['invalidmd5'] = 'Mali ang check variable - paki-ulit';
$string['missingrequiredfield'] = 'May ilang nawawalang field na kailangan';
$string['wrongdestpath'] = 'Mali ang patutunguhang landas';
$string['wrongsourcebase'] = 'Mali ang URL base ng source.';
$string['wrongzipfilename'] = 'Mali ang pangalan ng ZIP file';
| michael-milette/moodle | install/lang/tl/error.php | PHP | gpl-3.0 | 2,237 |
/* PR target/8340 */
/* { dg-do compile } */
/* { dg-require-effective-target ia32 } */
/* { dg-require-effective-target fpic } */
/* { dg-skip-if "No Windows PIC" { *-*-mingw* *-*-cygwin } { "*" } { "" } } */
/* { dg-options "-fPIC" } */
/* Test verifies that %ebx is no longer fixed when generating PIC code on i686. */
int foo ()
{
static int a;
__asm__ __volatile__ (
"xorl %%ebx, %%ebx\n"
"movl %%ebx, %0\n"
: "=m" (a)
:
: "%ebx"
);
return a;
}
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/gcc.target/i386/pic-1.c | C | gpl-3.0 | 483 |
<!doctype html>
<html>
<head>
<title>Analytics sample app</title>
</head>
<body>
<div>
<button id="chocolate">Chocolate</button>
<button id="vanilla">Vanilla</button>
<div id=out></div>
</div>
<div id="settings">
<h1>Settings</h1>
<div id="settings-loading">
Loading settings...
</div>
<div id="settings-loaded" hidden>
<label>
<input id="analytics" type="checkbox" />
Send anonymous usage data.
</label>
</div>
</div>
<script src="google-analytics-bundle.js"></script>
<script src="main.js"></script>
</body>
</html>
| Jabqooo/chrome-app-samples | samples/analytics/main.html | HTML | apache-2.0 | 647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.