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
# -*- coding: utf-8 -*- from qiniu import config from qiniu import http class PersistentFop(object): """持久化处理类 该类用于主动触发异步持久化操作,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/fop/pfop/pfop.html Attributes: auth: 账号管理密钥对,Auth对象 bucket: 操作资源所在空间 pipeline: 多媒体处理队列,详见 https://portal.qiniu.com/mps/pipeline notify_url: 持久化处理结果通知URL """ def __init__(self, auth, bucket, pipeline=None, notify_url=None): """初始化持久化处理类""" self.auth = auth self.bucket = bucket self.pipeline = pipeline self.notify_url = notify_url def execute(self, key, fops, force=None): """执行持久化处理: Args: key: 待处理的源文件 fops: 处理详细操作,规格详见 http://developer.qiniu.com/docs/v6/api/reference/fop/ force: 强制执行持久化处理开关 Returns: 一个dict变量,返回持久化处理的persistentId,类似{"persistentId": 5476bedf7823de4068253bae}; 一个ResponseInfo对象 """ ops = ';'.join(fops) data = {'bucket': self.bucket, 'key': key, 'fops': ops} if self.pipeline: data['pipeline'] = self.pipeline if self.notify_url: data['notifyURL'] = self.notify_url if force == 1: data['force'] = 1 url = 'http://{0}/pfop'.format(config.get_default('default_api_host')) return http._post_with_auth(url, data, self.auth)
hotpoor-for-Liwei/hj_hackathon_201607
vendor/qiniu/services/processing/pfop.py
Python
mit
1,697
--- layout: post date: 2005-12-27 time: "09:00:00" authors: ["Greg Wilson"] title: "New Year's Schedule for Software Carpentry" category: ["Content"] --- <p>I'm teaching a cut-down version of Software Carpentry at the IASSE in two and a half weeks. I'll have students half days for the weeks of January 16 and 23, and full days for the week of February 6. That's only 20 lectures (rather than 26), so the question is, what to cut? The answer has wider implications, since this will be the version of the course I take to the <a href="http://www.aaas.org/meetings/Annual_Meeting/02_PE/PE_06_Career_Workshops.shtml#EssentialSoftware">AAAS workshop</a>.</p> <p>My plan is:</p> <table> <tr> <td valign="top">Jan</td> <td valign="top">16</td> <td valign="top">Introduction</td> <td valign="top">Revised to be a forward summary of the whole course.</td> </tr> <tr> <td></td> <td valign="top">17</td> <td valign="top">Shell 1</td> <td></td> </tr> <tr> <td></td> <td valign="top">18</td> <td valign="top">Shell 2</td> <td></td> </tr> <tr> <td></td> <td valign="top">19</td> <td valign="top">Version Control</td> <td></td> </tr> <tr> <td></td> <td valign="top">20</td> <td valign="top">Make</td> <td valign="top">Revised so that it doesn't depend on Python.</td> </tr> <tr> <td valign="top">Jan</td> <td valign="top">23</td> <td valign="top">Python 1</td> <td valign="top">Basic features.</td> </tr> <tr> <td></td> <td valign="top">24</td> <td valign="top">Python 2</td> <td valign="top">Strings and lists.</td> </tr> <tr> <td></td> <td valign="top">25</td> <td valign="top">Python 3</td> <td valign="top">Functions and Libraries.</td> </tr> <tr> <td></td> <td valign="top">26</td> <td valign="top">Testing</td> <td valign="top">Basic concepts.</td> </tr> <tr> <td></td> <td valign="top">27</td> <td valign="top">Mini-Project 1</td> <td valign="top">Build something useful with Python.</td> </tr> <tr> <td valign="top">Feb</td> <td valign="top">06</td> <td valign="top">Python 4</td> <td valign="top">Dictionaries and exceptions.</td> </tr> <tr> <td></td> <td></td> <td valign="top">Debugging</td> <td valign="top">Deepened to include material from <a href="http://pyre.third-bit.com/blog/archives/000335.html">Zeller</a>.</td> </tr> <tr> <td></td> <td valign="top">07</td> <td valign="top">Python 5</td> <td valign="top">Object-oriented programming.</td> </tr> <tr> <td></td> <td></td> <td valign="top">Unit Testing</td> <td valign="top">Use the unit test framework to show what good OO design looks like.</td> </tr> <tr> <td></td> <td valign="top">08</td> <td valign="top">Coding Style</td> <td valign="top">Update to include an actual Python style guide.</td> </tr> <tr> <td></td> <td></td> <td valign="top">Reflection</td> <td valign="top">Complete rewrite: exec, eval, sub-processes, etc.</td> </tr> <tr> <td></td> <td valign="top">09</td> <td valign="top">Regular Expressions</td> <td></td> </tr> <tr> <td></td> <td></td> <td valign="top">XML and DOM</td> <td></td> </tr> <tr> <td></td> <td valign="top">10</td> <td valign="top">Development Process</td> <td valign="top">Describe how a good shop actually works (with nods to XP and RUP).</td> </tr> <tr> <td></td> <td></td> <td valign="top">Teamware</td> <td valign="top">Based on <a href="http://projects.edgewall.com/trac">Trac</a>.</td> </tr> </table> <p>Client-side and CGI web programming, security, and databases have disappeared completely; the three lectures on process have been folded into one; and there's no end-of-course summary. I'm comfortable with those changes; what I don't like is the amount of time spent teaching Python-the-language. I'd rather spend those hours showing them how to use Python to automate development activities, but you can't cut trees 'til you have an ax.</p> <p>Second, there's no place in this new scheme for a lecture based on Paul Dubois's CiSE article on maintaining correctness. There really ought to be: it shows the jigsaw puzzle of which many good practices are pieces.</p> <p>Third, I'd like a second project lecture, showing students part of the build system for the course notes. This would let them see regular expressions and DOM in action, and would tie together many of the earlier ideas on automation. It's this or teamware, though, and I think the latter is more important. Having made that decision, I'm wavering on whether to pull out the material on regular expressions and DOM.</p> <p>Finally, everything I have to say about the development process is now squeezed into a single hour. It makes sense in this case, since IASSE students will get several more courses on the subject, but it's definitely under weight for the <a href="http://www.aaas.org/meetings/Annual_Meeting/02_PE/PE_06_Career_Workshops.shtml#EssentialSoftware">AAAS workshop</a>.</p> <p>So: in order to pull this off, I'm going to have to revise one lecture per day from January 2 onward (including diagrams). I'll post the new materials here until they're polished, at which point I'll swap them into the standard location. I'll blog each time a lecture goes up: timely feedback would be greatly appreciated.</p>
gvwilson/website
_posts/2005/12/2005-12-27-new-years-schedule-for-software-carpentry.html
HTML
mit
5,102
const helpers = require("./global-setup"); const path = require("path"); const request = require("request"); const expect = require("chai").expect; const describe = global.describe; const it = global.it; const beforeEach = global.beforeEach; const afterEach = global.afterEach; describe("Position of modules", function () { helpers.setupTimeout(this); var app = null; describe("Using helloworld", function () { after(function () { return helpers.stopApplication(app); }); before(function () { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/positions.js"; return helpers.startApplication({ args: ["js/electron.js"] }).then(function (startedApp) { app = startedApp; }) }); var positions = ["top_bar", "top_left", "top_center", "top_right", "upper_third", "middle_center", "lower_third", "bottom_left", "bottom_center", "bottom_right", "bottom_bar", "fullscreen_above", "fullscreen_below"]; var position; var className; for (idx in positions) { position = positions[idx]; className = position.replace("_", "."); it("show text in " + position, function () { return app.client.waitUntilWindowLoaded() .getText("." + className).should.eventually.equal("Text in " + position); }); } }); });
morozgrafix/MagicMirror
tests/e2e/modules_position_spec.js
JavaScript
mit
1,305
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe(`Pursuit`, function () { afterEach(() => battle.destroy()); it(`should execute before the target switches out and after the user mega evolves`, function () { battle = common.createBattle(); battle.join('p1', 'Guest 1', 1, [{species: "Beedrill", ability: 'swarm', item: 'beedrillite', moves: ['pursuit']}]); battle.join('p2', 'Guest 2', 1, [{species: "Alakazam", ability: 'magicguard', moves: ['psyshock']}, {species: "Clefable", ability: 'unaware', moves: ['calmmind']}]); battle.p1.chooseMove('pursuit', null, true); battle.p2.chooseSwitch(2); assert.species(battle.p1.active[0], "Beedrill-Mega"); assert.fainted(battle.p2.active[0]); }); });
KewlStatics/Alliance
test/simulator/moves/pursuit.js
JavaScript
mit
784
using System; using System.Collections.Generic; using System.IO; using System.Windows.Media; namespace Wox.Plugin { public class Result { private string _pluginDirectory; private string _icoPath; public string Title { get; set; } public string SubTitle { get; set; } public string IcoPath { get { return _icoPath; } set { if (!string.IsNullOrEmpty(PluginDirectory) && !Path.IsPathRooted(value)) { _icoPath = Path.Combine(value, IcoPath); } else { _icoPath = value; } } } public delegate ImageSource IconDelegate(); public IconDelegate Icon; /// <summary> /// return true to hide wox after select result /// </summary> public Func<ActionContext, bool> Action { get; set; } public int Score { get; set; } /// <summary> /// Only resulsts that originQuery match with curren query will be displayed in the panel /// </summary> internal Query OriginQuery { get; set; } /// <summary> /// Plugin directory /// </summary> public string PluginDirectory { get { return _pluginDirectory; } set { _pluginDirectory = value; if (!string.IsNullOrEmpty(IcoPath) && !Path.IsPathRooted(IcoPath)) { IcoPath = Path.Combine(value, IcoPath); } } } public override bool Equals(object obj) { Result r = obj as Result; if (r != null) { var equality = string.Equals(r.Title, Title) && string.Equals(r.SubTitle, SubTitle); return equality; } else { return false; } } public override int GetHashCode() { var hashcode = (Title?.GetHashCode() ?? 0) ^ (SubTitle?.GetHashCode() ?? 0); return hashcode; } public override string ToString() { return Title + SubTitle; } [Obsolete("Use IContextMenu instead")] /// <summary> /// Context menus associate with this result /// </summary> public List<Result> ContextMenu { get; set; } [Obsolete("Use Object initializers instead")] public Result(string Title, string IcoPath, string SubTitle = null) { this.Title = Title; this.IcoPath = IcoPath; this.SubTitle = SubTitle; } public Result() { } /// <summary> /// Additional data associate with this result /// </summary> public object ContextData { get; set; } /// <summary> /// Plugin ID that generate this result /// </summary> public string PluginID { get; set; } } }
danisein/Wox
Wox.Plugin/Result.cs
C#
mit
3,146
namespace FakeItEasy.Core { /// <summary> /// Provides access to a call matcher. /// </summary> internal interface ICallMatcherAccessor { /// <summary> /// Gets a call predicate that can be used to check if a fake object call matches /// the specified constraint. /// </summary> ICallMatcher Matcher { get; } } }
khellang/FakeItEasy
Source/FakeItEasy/Core/ICallMatcherAccessor.cs
C#
mit
389
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - one_vs_one_decision_function.h</title></head><body bgcolor='white'><pre> <font color='#009900'>// Copyright (C) 2010 Davis E. King (davis@dlib.net) </font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license. </font><font color='#0000FF'>#ifndef</font> DLIB_ONE_VS_ONE_DECISION_FUnCTION_H__ <font color='#0000FF'>#define</font> DLIB_ONE_VS_ONE_DECISION_FUnCTION_H__ <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='one_vs_one_decision_function_abstract.h.html'>one_vs_one_decision_function_abstract.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../serialize.h.html'>../serialize.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../type_safe_union.h.html'>../type_safe_union.h</a>" <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>iostream<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>sstream<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>set<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>map<font color='#5555FF'>&gt;</font> <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../any.h.html'>../any.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../unordered_pair.h.html'>../unordered_pair.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='null_df.h.html'>null_df.h</a>" <font color='#0000FF'>namespace</font> dlib <b>{</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> one_vs_one_trainer, <font color='#0000FF'>typename</font> DF1 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF2 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF3 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF4 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF5 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF6 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF7 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF8 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF9 <font color='#5555FF'>=</font> null_df, <font color='#0000FF'>typename</font> DF10 <font color='#5555FF'>=</font> null_df <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='one_vs_one_decision_function'></a>one_vs_one_decision_function</b> <b>{</b> <font color='#0000FF'>public</font>: <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> one_vs_one_trainer::label_type result_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> one_vs_one_trainer::sample_type sample_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> one_vs_one_trainer::scalar_type scalar_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> one_vs_one_trainer::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> std::map<font color='#5555FF'>&lt;</font>unordered_pair<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font>, any_decision_function<font color='#5555FF'>&lt;</font>sample_type, scalar_type<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> binary_function_table; <b><a name='one_vs_one_decision_function'></a>one_vs_one_decision_function</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> :num_classes<font face='Lucida Console'>(</font><font color='#979000'>0</font><font face='Lucida Console'>)</font> <b>{</b><b>}</b> <font color='#0000FF'>explicit</font> <b><a name='one_vs_one_decision_function'></a>one_vs_one_decision_function</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> binary_function_table<font color='#5555FF'>&amp;</font> dfs_ <font face='Lucida Console'>)</font> : dfs<font face='Lucida Console'>(</font>dfs_<font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>#ifdef</font> ENABLE_ASSERTS <b>{</b> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>unordered_pair<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> missing_pairs <font color='#5555FF'>=</font> <font color='#BB00BB'>find_missing_pairs</font><font face='Lucida Console'>(</font>dfs_<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>missing_pairs.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>!</font><font color='#5555FF'>=</font> <font color='#979000'>0</font><font face='Lucida Console'>)</font> <b>{</b> std::ostringstream sout; <font color='#0000FF'>for</font> <font face='Lucida Console'>(</font><font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> i <font color='#5555FF'>=</font> <font color='#979000'>0</font>; i <font color='#5555FF'>&lt;</font> missing_pairs.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> sout <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>\t (</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> missing_pairs[i].first <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>, </font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> missing_pairs[i].second <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>)\n</font>"; <b>}</b> <font color='#BB00BB'>DLIB_ASSERT</font><font face='Lucida Console'>(</font>missing_pairs.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>0</font>, "<font color='#CC0000'>\t void one_vs_one_decision_function::one_vs_one_decision_function()</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>\n\t The supplied set of binary decision functions is incomplete.</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>\n\t this: </font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#0000FF'>this</font> <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>\n\t Classifiers are missing for the following label pairs: \n</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> sout.<font color='#BB00BB'>str</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>)</font>; <b>}</b> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// figure out how many labels are covered by this set of binary decision functions </font> std::set<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font> labels; <font color='#0000FF'>for</font> <font face='Lucida Console'>(</font><font color='#0000FF'>typename</font> binary_function_table::const_iterator i <font color='#5555FF'>=</font> dfs.<font color='#BB00BB'>begin</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; i <font color='#5555FF'>!</font><font color='#5555FF'>=</font> dfs.<font color='#BB00BB'>end</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> labels.<font color='#BB00BB'>insert</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first.first<font face='Lucida Console'>)</font>; labels.<font color='#BB00BB'>insert</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first.second<font face='Lucida Console'>)</font>; <b>}</b> num_classes <font color='#5555FF'>=</font> labels.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>const</font> binary_function_table<font color='#5555FF'>&amp;</font> <b><a name='get_binary_decision_functions'></a>get_binary_decision_functions</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> dfs; <b>}</b> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font> <b><a name='get_labels'></a>get_labels</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> std::set<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font> labels; <font color='#0000FF'>for</font> <font face='Lucida Console'>(</font><font color='#0000FF'>typename</font> binary_function_table::const_iterator i <font color='#5555FF'>=</font> dfs.<font color='#BB00BB'>begin</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; i <font color='#5555FF'>!</font><font color='#5555FF'>=</font> dfs.<font color='#BB00BB'>end</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> labels.<font color='#BB00BB'>insert</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first.first<font face='Lucida Console'>)</font>; labels.<font color='#BB00BB'>insert</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first.second<font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>return</font> std::vector<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>labels.<font color='#BB00BB'>begin</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>, labels.<font color='#BB00BB'>end</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> df1, <font color='#0000FF'>typename</font> df2, <font color='#0000FF'>typename</font> df3, <font color='#0000FF'>typename</font> df4, <font color='#0000FF'>typename</font> df5, <font color='#0000FF'>typename</font> df6, <font color='#0000FF'>typename</font> df7, <font color='#0000FF'>typename</font> df8, <font color='#0000FF'>typename</font> df9, <font color='#0000FF'>typename</font> df10 <font color='#5555FF'>&gt;</font> <b><a name='one_vs_one_decision_function'></a>one_vs_one_decision_function</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> one_vs_one_decision_function<font color='#5555FF'>&lt;</font>one_vs_one_trainer, df1, df2, df3, df4, df5, df6, df7, df8, df9, df10<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item <font face='Lucida Console'>)</font> : dfs<font face='Lucida Console'>(</font>item.get_binary_decision_functions<font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>, num_classes<font face='Lucida Console'>(</font>item.number_of_classes<font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <b>{</b><b>}</b> <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> <b><a name='number_of_classes'></a>number_of_classes</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>return</font> num_classes; <b>}</b> result_type <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> sample_type<font color='#5555FF'>&amp;</font> sample <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#BB00BB'>DLIB_ASSERT</font><font face='Lucida Console'>(</font><font color='#BB00BB'>number_of_classes</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>!</font><font color='#5555FF'>=</font> <font color='#979000'>0</font>, "<font color='#CC0000'>\t void one_vs_one_decision_function::operator()</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>\n\t You can't make predictions with an empty decision function.</font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> "<font color='#CC0000'>\n\t this: </font>" <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font> <font color='#0000FF'>this</font> <font face='Lucida Console'>)</font>; std::map<font color='#5555FF'>&lt;</font>result_type,<font color='#0000FF'><u>int</u></font><font color='#5555FF'>&gt;</font> votes; <font color='#009900'>// run all the classifiers over the sample </font> <font color='#0000FF'>for</font><font face='Lucida Console'>(</font><font color='#0000FF'>typename</font> binary_function_table::const_iterator i <font color='#5555FF'>=</font> dfs.<font color='#BB00BB'>begin</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; i <font color='#5555FF'>!</font><font color='#5555FF'>=</font> dfs.<font color='#BB00BB'>end</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>const</font> scalar_type score <font color='#5555FF'>=</font> i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font><font color='#BB00BB'>second</font><font face='Lucida Console'>(</font>sample<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>score <font color='#5555FF'>&gt;</font> <font color='#979000'>0</font><font face='Lucida Console'>)</font> votes[i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first.first] <font color='#5555FF'>+</font><font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#0000FF'>else</font> votes[i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first.second] <font color='#5555FF'>+</font><font color='#5555FF'>=</font> <font color='#979000'>1</font>; <b>}</b> <font color='#009900'>// now figure out who had the most votes </font> result_type best_label <font color='#5555FF'>=</font> <font color='#BB00BB'>result_type</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#0000FF'><u>int</u></font> best_votes <font color='#5555FF'>=</font> <font color='#979000'>0</font>; <font color='#0000FF'>for</font> <font face='Lucida Console'>(</font><font color='#0000FF'>typename</font> std::map<font color='#5555FF'>&lt;</font>result_type,<font color='#0000FF'><u>int</u></font><font color='#5555FF'>&gt;</font>::iterator i <font color='#5555FF'>=</font> votes.<font color='#BB00BB'>begin</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; i <font color='#5555FF'>!</font><font color='#5555FF'>=</font> votes.<font color='#BB00BB'>end</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second <font color='#5555FF'>&gt;</font> best_votes<font face='Lucida Console'>)</font> <b>{</b> best_votes <font color='#5555FF'>=</font> i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second; best_label <font color='#5555FF'>=</font> i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first; <b>}</b> <b>}</b> <font color='#0000FF'>return</font> best_label; <b>}</b> <font color='#0000FF'>private</font>: binary_function_table dfs; <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> num_classes; <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> DF1, <font color='#0000FF'>typename</font> DF2, <font color='#0000FF'>typename</font> DF3, <font color='#0000FF'>typename</font> DF4, <font color='#0000FF'>typename</font> DF5, <font color='#0000FF'>typename</font> DF6, <font color='#0000FF'>typename</font> DF7, <font color='#0000FF'>typename</font> DF8, <font color='#0000FF'>typename</font> DF9, <font color='#0000FF'>typename</font> DF10 <font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>void</u></font> <b><a name='serialize'></a>serialize</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> one_vs_one_decision_function<font color='#5555FF'>&lt;</font>T,DF1,DF2,DF3,DF4,DF5,DF6,DF7,DF8,DF9,DF10<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item, std::ostream<font color='#5555FF'>&amp;</font> out <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>try</font> <b>{</b> type_safe_union<font color='#5555FF'>&lt;</font>DF1,DF2,DF3,DF4,DF5,DF6,DF7,DF8,DF9,DF10<font color='#5555FF'>&gt;</font> temp; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> T::label_type result_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> T::sample_type sample_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> T::scalar_type scalar_type; <font color='#0000FF'>typedef</font> std::map<font color='#5555FF'>&lt;</font>unordered_pair<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font>, any_decision_function<font color='#5555FF'>&lt;</font>sample_type, scalar_type<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> binary_function_table; <font color='#0000FF'>const</font> <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> version <font color='#5555FF'>=</font> <font color='#979000'>1</font>; <font color='#BB00BB'>serialize</font><font face='Lucida Console'>(</font>version, out<font face='Lucida Console'>)</font>; <font color='#0000FF'>const</font> <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> size <font color='#5555FF'>=</font> item.<font color='#BB00BB'>get_binary_decision_functions</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#BB00BB'>serialize</font><font face='Lucida Console'>(</font>size, out<font face='Lucida Console'>)</font>; <font color='#0000FF'>for</font><font face='Lucida Console'>(</font><font color='#0000FF'>typename</font> binary_function_table::const_iterator i <font color='#5555FF'>=</font> item.<font color='#BB00BB'>get_binary_decision_functions</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>.<font color='#BB00BB'>begin</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; i <font color='#5555FF'>!</font><font color='#5555FF'>=</font> item.<font color='#BB00BB'>get_binary_decision_functions</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>.<font color='#BB00BB'>end</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> <font color='#BB00BB'>serialize</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>first, out<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF1<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF1<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF1<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF2<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF2<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF2<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF3<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF3<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF3<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF4<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF4<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF4<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF5<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF5<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF5<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF6<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF6<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF6<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF7<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF7<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF7<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF8<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF8<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF8<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF9<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF9<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF9<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>DF10<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> temp.<font color='#0000FF'>template</font> get<font color='#5555FF'>&lt;</font>DF10<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font> any_cast<font color='#5555FF'>&lt;</font>DF10<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>i<font color='#5555FF'>-</font><font color='#5555FF'>&gt;</font>second<font face='Lucida Console'>)</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>serialization_error</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Can't serialize one_vs_one_decision_function. Not all decision functions defined.</font>"<font face='Lucida Console'>)</font>; <font color='#BB00BB'>serialize</font><font face='Lucida Console'>(</font>temp,out<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b> <font color='#0000FF'>catch</font> <font face='Lucida Console'>(</font>serialization_error<font color='#5555FF'>&amp;</font> e<font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>throw</font> <font color='#BB00BB'>serialization_error</font><font face='Lucida Console'>(</font>e.info <font color='#5555FF'>+</font> "<font color='#CC0000'>\n while serializing an object of type one_vs_one_decision_function</font>"<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>namespace</font> impl <b>{</b> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> sample_type, <font color='#0000FF'>typename</font> scalar_type<font color='#5555FF'>&gt;</font> <font color='#0000FF'>struct</font> <b><a name='copy_to_df_helper'></a>copy_to_df_helper</b> <b>{</b> <b><a name='copy_to_df_helper'></a>copy_to_df_helper</b><font face='Lucida Console'>(</font>any_decision_function<font color='#5555FF'>&lt;</font>sample_type, scalar_type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> target_<font face='Lucida Console'>)</font> : target<font face='Lucida Console'>(</font>target_<font face='Lucida Console'>)</font> <b>{</b><b>}</b> any_decision_function<font color='#5555FF'>&lt;</font>sample_type, scalar_type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> target; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T<font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>void</u></font> <b><a name='operator'></a>operator</b><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> T<font color='#5555FF'>&amp;</font> item <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> target <font color='#5555FF'>=</font> item; <b>}</b> <b>}</b>; <b>}</b> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> DF1, <font color='#0000FF'>typename</font> DF2, <font color='#0000FF'>typename</font> DF3, <font color='#0000FF'>typename</font> DF4, <font color='#0000FF'>typename</font> DF5, <font color='#0000FF'>typename</font> DF6, <font color='#0000FF'>typename</font> DF7, <font color='#0000FF'>typename</font> DF8, <font color='#0000FF'>typename</font> DF9, <font color='#0000FF'>typename</font> DF10 <font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>void</u></font> <b><a name='deserialize'></a>deserialize</b><font face='Lucida Console'>(</font> one_vs_one_decision_function<font color='#5555FF'>&lt;</font>T,DF1,DF2,DF3,DF4,DF5,DF6,DF7,DF8,DF9,DF10<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> item, std::istream<font color='#5555FF'>&amp;</font> in <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>try</font> <b>{</b> type_safe_union<font color='#5555FF'>&lt;</font>DF1,DF2,DF3,DF4,DF5,DF6,DF7,DF8,DF9,DF10<font color='#5555FF'>&gt;</font> temp; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> T::label_type result_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> T::sample_type sample_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> T::scalar_type scalar_type; <font color='#0000FF'>typedef</font> impl::copy_to_df_helper<font color='#5555FF'>&lt;</font>sample_type, scalar_type<font color='#5555FF'>&gt;</font> copy_to; <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> version; <font color='#BB00BB'>deserialize</font><font face='Lucida Console'>(</font>version, in<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>version <font color='#5555FF'>!</font><font color='#5555FF'>=</font> <font color='#979000'>1</font><font face='Lucida Console'>)</font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>serialization_error</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Can't deserialize one_vs_one_decision_function. Wrong version.</font>"<font face='Lucida Console'>)</font>; <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> size; <font color='#BB00BB'>deserialize</font><font face='Lucida Console'>(</font>size, in<font face='Lucida Console'>)</font>; <font color='#0000FF'>typedef</font> std::map<font color='#5555FF'>&lt;</font>unordered_pair<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font>, any_decision_function<font color='#5555FF'>&lt;</font>sample_type, scalar_type<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font> binary_function_table; binary_function_table dfs; unordered_pair<font color='#5555FF'>&lt;</font>result_type<font color='#5555FF'>&gt;</font> p; <font color='#0000FF'>for</font> <font face='Lucida Console'>(</font><font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> i <font color='#5555FF'>=</font> <font color='#979000'>0</font>; i <font color='#5555FF'>&lt;</font> size; <font color='#5555FF'>+</font><font color='#5555FF'>+</font>i<font face='Lucida Console'>)</font> <b>{</b> <font color='#BB00BB'>deserialize</font><font face='Lucida Console'>(</font>p, in<font face='Lucida Console'>)</font>; <font color='#BB00BB'>deserialize</font><font face='Lucida Console'>(</font>temp, in<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>temp.<font color='#0000FF'>template</font> contains<font color='#5555FF'>&lt;</font>null_df<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>serialization_error</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>A sub decision function of unknown type was encountered.</font>"<font face='Lucida Console'>)</font>; temp.<font color='#BB00BB'>apply_to_contents</font><font face='Lucida Console'>(</font><font color='#BB00BB'>copy_to</font><font face='Lucida Console'>(</font>dfs[p]<font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <b>}</b> item <font color='#5555FF'>=</font> one_vs_one_decision_function<font color='#5555FF'>&lt;</font>T,DF1,DF2,DF3,DF4,DF5,DF6,DF7,DF8,DF9,DF10<font color='#5555FF'>&gt;</font><font face='Lucida Console'>(</font>dfs<font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>catch</font> <font face='Lucida Console'>(</font>serialization_error<font color='#5555FF'>&amp;</font> e<font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>throw</font> <font color='#BB00BB'>serialization_error</font><font face='Lucida Console'>(</font>e.info <font color='#5555FF'>+</font> "<font color='#CC0000'>\n while deserializing an object of type one_vs_one_decision_function</font>"<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_ONE_VS_ONE_DECISION_FUnCTION_H__ </font> </pre></body></html>
eldilibra/mudsling
include/dlib-18.9/docs/dlib/svm/one_vs_one_decision_function.h.html
HTML
mit
39,691
survey 'LB', :full_title => 'Lebanon', :default_mandatory => 'false', :status => 'alpha', :description => '<p><strong>This has been generated based on a default and needs to be localised for Lebanon. Please help us! Contact <a href="mailto:certificate@theodi.org">certificate@theodi.org</a></strong></p><p>This self-assessment questionnaire generates an open data certificate and badge you can publish to tell people all about this open data. We also use your answers to learn how organisations publish open data.</p><p>When you answer these questions it demonstrates your efforts to comply with relevant legislation. You should also check which other laws and policies apply to your sector.</p><p><strong>You do not need to answer all the questions to get a certificate.</strong> Just answer those you can.</p>' do translations :en => :default section_general 'General Information', :description => '', :display_header => false do q_dataTitle 'What\'s this data called?', :discussion_topic => :dataTitle, :help_text => 'People see the name of your open data in a list of similar ones so make this as unambiguous and descriptive as you can in this tiny box so they quickly identify what\'s unique about it.', :required => :required a_1 'Data Title', :string, :placeholder => 'Data Title', :required => :required q_documentationUrl 'Where is it described?', :discussion_topic => :documentationUrl, :display_on_certificate => true, :text_as_statement => 'This data is described at', :help_text => 'Give a URL for people to read about the contents of your open data and find more detail. It can be a page within a bigger catalog like data.gov.uk.' a_1 'Documentation URL', :string, :input_type => :url, :placeholder => 'Documentation URL', :requirement => ['pilot_1', 'basic_1'] label_pilot_1 'You should have a <strong>web page that offers documentation</strong> about the open data you publish so that people can understand its context, content and utility.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_1' dependency :rule => 'A and B' condition_A :q_releaseType, '!=', :a_collection condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} label_basic_1 'You must have a <strong>web page that gives documentation</strong> and access to the open data you publish so that people can use it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_1' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_collection condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} q_publisher 'Who publishes this data?', :discussion_topic => :publisher, :display_on_certificate => true, :text_as_statement => 'This data is published by', :help_text => 'Give the name of the organisation who publishes this data. It’s probably who you work for unless you’re doing this on behalf of someone else.', :required => :required a_1 'Data Publisher', :string, :placeholder => 'Data Publisher', :required => :required q_publisherUrl 'What website is the data published on?', :discussion_topic => :publisherUrl, :display_on_certificate => true, :text_as_statement => 'The data is published on', :help_text => 'Give a URL to a website, this helps us to group data from the same organisation even if people give different names.' a_1 'Publisher URL', :string, :input_type => :url, :placeholder => 'Publisher URL' q_releaseType 'What kind of release is this?', :discussion_topic => :releaseType, :pick => :one, :required => :required a_oneoff 'a one-off release of a single dataset', :help_text => 'This is a single file and you don’t currently plan to publish similar files in the future.' a_collection 'a one-off release of a set of related datasets', :help_text => 'This is a collection of related files about the same data and you don’t currently plan to publish similar collections in the future.' a_series 'ongoing release of a series of related datasets', :help_text => 'This is a sequence of datasets with planned periodic updates in the future.' a_service 'a service or API for accessing open data', :help_text => 'This is a live web service that exposes your data to programmers through an interface they can query.' end section_legal 'Legal Information', :description => 'Rights, licensing and privacy' do label_group_2 'Rights', :help_text => 'your right to share this data with people', :customer_renderer => '/partials/fieldset' q_publisherRights 'Do you have the rights to publish this data as open data?', :discussion_topic => :lb_publisherRights, :help_text => 'If your organisation didn\'t originally create or gather this data then you might not have the right to publish it. If you’re not sure, check with the data owner because you will need their permission to publish it.', :requirement => ['basic_2'], :pick => :one, :required => :required a_yes 'yes, you have the rights to publish this data as open data', :requirement => ['standard_1'] a_no 'no, you don\'t have the rights to publish this data as open data' a_unsure 'you\'re not sure if you have the rights to publish this data as open data' a_complicated 'the rights in this data are complicated or unclear' label_standard_1 'You should have a <strong>clear legal right to publish this data</strong>.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_1' dependency :rule => 'A' condition_A :q_publisherRights, '!=', :a_yes label_basic_2 'You must have the <strong>right to publish this data</strong>.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_2' dependency :rule => 'A' condition_A :q_publisherRights, '==', :a_no q_rightsRiskAssessment 'Where do you detail the risks people might encounter if they use this data?', :discussion_topic => :lb_rightsRiskAssessment, :display_on_certificate => true, :text_as_statement => 'Risks in using this data are described at', :help_text => 'It can be risky for people to use data without a clear legal right to do so. For example, the data might be taken down in response to a legal challenge. Give a URL for a page that describes the risk of using this data.' dependency :rule => 'A' condition_A :q_publisherRights, '==', :a_complicated a_1 'Risk Documentation URL', :string, :input_type => :url, :placeholder => 'Risk Documentation URL', :requirement => ['pilot_2'] label_pilot_2 'You should document <strong>risks associated with using this data</strong>, so people can work out how they want to use it.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_2' dependency :rule => 'A and B' condition_A :q_publisherRights, '==', :a_complicated condition_B :q_rightsRiskAssessment, '==', {:string_value => '', :answer_reference => '1'} q_publisherOrigin 'Was <em>all</em> this data originally created or gathered by you?', :discussion_topic => :lb_publisherOrigin, :display_on_certificate => true, :text_as_statement => 'This data was', :help_text => 'If any part of this data was sourced outside your organisation by other individuals or organisations then you need to give extra information about your right to publish it.', :pick => :one, :required => :required dependency :rule => '(A or B)' condition_A :q_publisherRights, '==', :a_yes condition_B :q_publisherRights, '==', :a_unsure a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'originally created or generated by its curator' q_thirdPartyOrigin 'Was some of this data extracted or calculated from other data?', :discussion_topic => :lb_thirdPartyOrigin, :help_text => 'An extract or smaller part of someone else\'s data still means your rights to use it might be affected. There might also be legal issues if you analysed their data to produce new results from it.', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false a_false 'no' a_true 'yes', :requirement => ['basic_3'] label_basic_3 'You indicated that this data wasn\'t originally created or gathered by you, and wasn\'t crowdsourced, so it must have been extracted or calculated from other data sources.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_3' dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_false condition_D :q_thirdPartyOrigin, '!=', :a_true q_thirdPartyOpen 'Are <em>all</em> sources of this data already published as open data?', :discussion_topic => :lb_thirdPartyOpen, :display_on_certificate => true, :text_as_statement => 'This data is created from', :help_text => 'You\'re allowed to republish someone else\'s data if it\'s already under an open data licence or if their rights have expired or been waived. If any part of this data is not like this then you\'ll need legal advice before you can publish it.', :pick => :one, :required => :required dependency :rule => 'A and B and C' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_thirdPartyOrigin, '==', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'open data sources', :requirement => ['basic_4'] label_basic_4 'You should get <strong>legal advice to make sure you have the right to publish this data</strong>.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_4' dependency :rule => 'A and B and C and D and E' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_thirdPartyOrigin, '==', :a_true condition_D :q_thirdPartyOpen, '==', :a_false condition_E :q_thirdPartyOpen, '==', :a_false q_crowdsourced 'Was some of this data crowdsourced?', :discussion_topic => :lb_crowdsourced, :display_on_certificate => true, :text_as_statement => 'Some of this data is', :help_text => 'If the data includes information contributed by people outside your organisation, you need their permission to publish their contributions as open data.', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'crowdsourced', :requirement => ['basic_5'] label_basic_5 'You indicated that the data wasn\'t originally created or gathered by you, and wasn\'t extracted or calculated from other data, so it must have been crowdsourced.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_5' dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_thirdPartyOrigin, '==', :a_false condition_D :q_crowdsourced, '!=', :a_true q_crowdsourcedContent 'Did contributors to this data use their judgement?', :discussion_topic => :lb_crowdsourcedContent, :help_text => 'If people used their creativity or judgement to contribute data then they have copyright over their work. For example, writing a description or deciding whether or not to include some data in a dataset would require judgement. So contributors must transfer or waive their rights, or license the data to you before you can publish it.', :pick => :one, :required => :required dependency :rule => 'A and B and C' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true a_false 'no' a_true 'yes' q_claUrl 'Where is the Contributor Licence Agreement (CLA)?', :discussion_topic => :lb_claUrl, :display_on_certificate => true, :text_as_statement => 'The Contributor Licence Agreement is at', :help_text => 'Give a link to an agreement that shows contributors allow you to reuse their data. A CLA will either transfer contributor\'s rights to you, waive their rights, or license the data to you so you can publish it.', :help_text_more_url => 'http://en.wikipedia.org/wiki/Contributor_License_Agreement', :required => :required dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true condition_D :q_crowdsourcedContent, '==', :a_true a_1 'Contributor Licence Agreement URL', :string, :input_type => :url, :placeholder => 'Contributor Licence Agreement URL', :required => :required q_cldsRecorded 'Have all contributors agreed to the Contributor Licence Agreement (CLA)?', :discussion_topic => :lb_cldsRecorded, :help_text => 'Check all contributors agree to a CLA before you reuse or republish their contributions. You should keep a record of who gave contributions and whether or not they agree to the CLA.', :pick => :one, :required => :required dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true condition_D :q_crowdsourcedContent, '==', :a_true a_false 'no' a_true 'yes', :requirement => ['basic_6'] label_basic_6 'You must get <strong>contributors to agree to a Contributor Licence Agreement</strong> (CLA) that gives you the right to publish their work as open data.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_6' dependency :rule => 'A and B and C and D and E' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true condition_D :q_crowdsourcedContent, '==', :a_true condition_E :q_cldsRecorded, '==', :a_false q_sourceDocumentationUrl 'Where do you describe sources of this data?', :discussion_topic => :lb_sourceDocumentationUrl, :display_on_certificate => true, :text_as_statement => 'The sources of this data are described at', :help_text => 'Give a URL that documents where the data was sourced from (its provenance) and the rights under which you publish the data. This helps people understand where the data comes from.' dependency :rule => 'A' condition_A :q_publisherOrigin, '==', :a_false a_1 'Data Sources Documentation URL', :string, :input_type => :url, :placeholder => 'Data Sources Documentation URL', :requirement => ['pilot_3'] label_pilot_3 'You should document <strong>where the data came from and the rights under which you publish it</strong>, so people are assured they can use parts which came from third parties.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_3' dependency :rule => 'A and B' condition_A :q_publisherOrigin, '==', :a_false condition_B :q_sourceDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'} q_sourceDocumentationMetadata 'Is documentation about the sources of this data also in machine-readable format?', :discussion_topic => :lb_sourceDocumentationMetadata, :display_on_certificate => true, :text_as_statement => 'The curator has published', :help_text => 'Information about data sources should be human-readable so people can understand it, as well as in a metadata format that computers can process. When everyone does this it helps other people find out how the same open data is being used and justify its ongoing publication.', :pick => :one dependency :rule => 'A and B' condition_A :q_publisherOrigin, '==', :a_false condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'} a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'machine-readable data about the sources of this data', :requirement => ['standard_2'] label_standard_2 'You should <strong>include machine-readable data about the sources of this data</strong>.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_2' dependency :rule => 'A and B and C' condition_A :q_publisherOrigin, '==', :a_false condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_C :q_sourceDocumentationMetadata, '==', :a_false label_group_3 'Licensing', :help_text => 'how you give people permission to use this data', :customer_renderer => '/partials/fieldset' q_copyrightURL 'Where have you published the rights statement for this dataset?', :discussion_topic => :lb_copyrightURL, :display_on_certificate => true, :text_as_statement => 'The rights statement is at', :help_text => 'Give the URL to a page that describes the right to re-use this dataset. This should include a reference to its license, attribution requirements, and a statement about relevant copyright. A rights statement helps people understand what they can and can\'t do with the data.' a_1 'Rights Statement URL', :string, :input_type => :url, :placeholder => 'Rights Statement URL', :requirement => ['pilot_4'] label_pilot_4 'You should <strong>publish a rights statement</strong> that details copyright, licensing and how people should give attribution to the data.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_4' dependency :rule => 'A' condition_A :q_copyrightURL, '==', {:string_value => '', :answer_reference => '1'} q_dataLicence 'Under which licence can people reuse this data?', :discussion_topic => :lb_dataLicence, :display_on_certificate => true, :text_as_statement => 'This data is available under', :help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it. Creative content includes the organisation and selection of items within data, but does not include facts. So people need a waiver or a licence which proves that they can use the data and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the data, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.', :pick => :one, :required => :required, :display_type => 'dropdown' a_cc_by 'Creative Commons Attribution', :text_as_statement => 'Creative Commons Attribution' a_cc_by_sa 'Creative Commons Attribution Share-Alike', :text_as_statement => 'Creative Commons Attribution Share-Alike' a_cc_zero 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_odc_by 'Open Data Commons Attribution License', :text_as_statement => 'Open Data Commons Attribution License' a_odc_odbl 'Open Data Commons Open Database License (ODbL)', :text_as_statement => 'Open Data Commons Open Database License (ODbL)' a_odc_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)', :text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)' a_na 'Not applicable', :text_as_statement => '' a_other 'Other...', :text_as_statement => '' q_dataNotApplicable 'Why doesn\'t a licence apply to this data?', :discussion_topic => :lb_dataNotApplicable, :display_on_certificate => true, :text_as_statement => 'This data is not licensed because', :pick => :one, :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_na a_norights 'there is no copyright in this data', :text_as_statement => 'there is no copyright in it', :help_text => 'Copyright only applies to data if you spent intellectual effort creating what\'s in it, for example, by writing text that\'s within the data, or deciding whether particular data is included. There\'s no copyright if the data only contains facts where no judgements were made about whether to include them or not.' a_expired 'copyright has expired', :text_as_statement => 'copyright has expired', :help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.' a_waived 'copyright has been waived', :text_as_statement => '', :help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.' q_dataWaiver 'Which waiver do you use to waive copyright in the data?', :discussion_topic => :lb_dataWaiver, :display_on_certificate => true, :text_as_statement => 'Rights in the data have been waived with', :help_text => 'You need a statement to show people copyright has been waived, so they understand that they can do whatever they like with this data. Standard waivers already exist like PDDL and CCZero but you can write your own with legal advice.', :pick => :one, :required => :required, :display_type => 'dropdown' dependency :rule => 'A and B' condition_A :q_dataLicence, '==', :a_na condition_B :q_dataNotApplicable, '==', :a_waived a_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)', :text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)' a_cc0 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_other 'Other...', :text_as_statement => '' q_dataOtherWaiver 'Where is the waiver for the copyright in the data?', :discussion_topic => :lb_dataOtherWaiver, :display_on_certificate => true, :text_as_statement => 'Rights in the data have been waived with', :help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive copyright in the data.', :required => :required dependency :rule => 'A and B and C' condition_A :q_dataLicence, '==', :a_na condition_B :q_dataNotApplicable, '==', :a_waived condition_C :q_dataWaiver, '==', :a_other a_1 'Waiver URL', :string, :input_type => :url, :required => :required, :placeholder => 'Waiver URL' q_otherDataLicenceName 'What is the name of the licence?', :discussion_topic => :lb_otherDataLicenceName, :display_on_certificate => true, :text_as_statement => 'This data is available under', :help_text => 'If you use a different licence, we need the name so people can see it on your Open Data Certificate.', :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_other a_1 'Other Licence Name', :string, :required => :required, :placeholder => 'Other Licence Name' q_otherDataLicenceURL 'Where is the licence?', :discussion_topic => :lb_otherDataLicenceURL, :display_on_certificate => true, :text_as_statement => 'This licence is at', :help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.', :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_other a_1 'Other Licence URL', :string, :input_type => :url, :required => :required, :placeholder => 'Other Licence URL' q_otherDataLicenceOpen 'Is the licence an open licence?', :discussion_topic => :lb_otherDataLicenceOpen, :help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.', :help_text_more_url => 'http://opendefinition.org/', :pick => :one, :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_other a_false 'no' a_true 'yes', :requirement => ['basic_7'] label_basic_7 'You must <strong>publish open data under an open licence</strong> so that people can use it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_7' dependency :rule => 'A and B' condition_A :q_dataLicence, '==', :a_other condition_B :q_otherDataLicenceOpen, '==', :a_false q_contentRights 'Is there any copyright in the content of this data?', :discussion_topic => :lb_contentRights, :display_on_certificate => true, :text_as_statement => 'There are', :pick => :one, :required => :required a_norights 'no, the data only contains facts and numbers', :text_as_statement => 'no rights in the content of the data', :help_text => 'There is no copyright in factual information. If the data does not contain any content that was created through intellectual effort, there are no rights in the content.' a_samerights 'yes, and the rights are all held by the same person or organisation', :text_as_statement => '', :help_text => 'Choose this option if the content in the data was all created by or transferred to the same person or organisation.' a_mixedrights 'yes, and the rights are held by different people or organisations', :text_as_statement => '', :help_text => 'In some data, the rights in different records are held by different people or organisations. Information about rights needs to be kept in the data too.' q_explicitWaiver 'Is the content of the data marked as public domain?', :discussion_topic => :lb_explicitWaiver, :display_on_certificate => true, :text_as_statement => 'The content has been', :help_text => 'Content can be marked as public domain using the <a href="http://creativecommons.org/publicdomain/">Creative Commons Public Domain Mark</a>. This helps people know that it can be freely reused.', :pick => :one dependency :rule => 'A' condition_A :q_contentRights, '==', :a_norights a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'marked as public domain', :requirement => ['standard_3'] label_standard_3 'You should <strong>mark public domain content as public domain</strong> so that people know they can reuse it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_3' dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_norights condition_B :q_explicitWaiver, '==', :a_false q_contentLicence 'Under which licence can others reuse content?', :discussion_topic => :lb_contentLicence, :display_on_certificate => true, :text_as_statement => 'The content is available under', :help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it but creative content does not include facts. So people need a waiver or a licence which proves that they can use the content and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the content, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.', :pick => :one, :required => :required, :display_type => 'dropdown' dependency :rule => 'A' condition_A :q_contentRights, '==', :a_samerights a_cc_by 'Creative Commons Attribution', :text_as_statement => 'Creative Commons Attribution' a_cc_by_sa 'Creative Commons Attribution Share-Alike', :text_as_statement => 'Creative Commons Attribution Share-Alike' a_cc_zero 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_na 'Not applicable', :text_as_statement => '' a_other 'Other...', :text_as_statement => '' q_contentNotApplicable 'Why doesn\'t a licence apply to the content of the data?', :discussion_topic => :lb_contentNotApplicable, :display_on_certificate => true, :text_as_statement => 'The content in this data is not licensed because', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_na a_norights 'there is no copyright in the content of this data', :text_as_statement => 'there is no copyright', :help_text => 'Copyright only applies to content if you spent intellectual effort creating it, for example, by writing text that\'s within the data. There\'s no copyright if the content only contains facts.' a_expired 'copyright has expired', :text_as_statement => 'copyright has expired', :help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.' a_waived 'copyright has been waived', :text_as_statement => '', :help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.' q_contentWaiver 'Which waiver do you use to waive copyright?', :discussion_topic => :lb_contentWaiver, :display_on_certificate => true, :text_as_statement => 'Copyright has been waived with', :help_text => 'You need a statement to show people you\'ve done this, so they understand that they can do whatever they like with this data. Standard waivers already exist like CCZero but you can write your own with legal advice.', :pick => :one, :required => :required, :display_type => 'dropdown' dependency :rule => 'A and B and C' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_na condition_C :q_contentNotApplicable, '==', :a_waived a_cc0 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_other 'Other...', :text_as_statement => 'Other...' q_contentOtherWaiver 'Where is the waiver for the copyright?', :discussion_topic => :lb_contentOtherWaiver, :display_on_certificate => true, :text_as_statement => 'Copyright has been waived with', :help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive your copyright.', :required => :required dependency :rule => 'A and B and C and D' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_na condition_C :q_contentNotApplicable, '==', :a_waived condition_D :q_contentWaiver, '==', :a_other a_1 'Waiver URL', :string, :input_type => :url, :required => :required, :placeholder => 'Waiver URL' q_otherContentLicenceName 'What\'s the name of the licence?', :discussion_topic => :lb_otherContentLicenceName, :display_on_certificate => true, :text_as_statement => 'The content is available under', :help_text => 'If you use a different licence, we need its name so people can see it on your Open Data Certificate.', :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other a_1 'Licence Name', :string, :required => :required, :placeholder => 'Licence Name' q_otherContentLicenceURL 'Where is the licence?', :discussion_topic => :lb_otherContentLicenceURL, :display_on_certificate => true, :text_as_statement => 'The content licence is at', :help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.', :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other a_1 'Licence URL', :string, :input_type => :url, :required => :required, :placeholder => 'Licence URL' q_otherContentLicenceOpen 'Is the licence an open licence?', :discussion_topic => :lb_otherContentLicenceOpen, :help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.', :help_text_more_url => 'http://opendefinition.org/', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other a_false 'no' a_true 'yes', :requirement => ['basic_8'] label_basic_8 'You must <strong>publish open data under an open licence</strong> so that people can use it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_8' dependency :rule => 'A and B and C' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other condition_C :q_otherContentLicenceOpen, '==', :a_false q_contentRightsURL 'Where are the rights and licensing of the content explained?', :discussion_topic => :lb_contentRightsURL, :display_on_certificate => true, :text_as_statement => 'The rights and licensing of the content are explained at', :help_text => 'Give the URL for a page where you describe how someone can find out the rights and licensing of a piece of content from the data.', :required => :required dependency :rule => 'A' condition_A :q_contentRights, '==', :a_mixedrights a_1 'Content Rights Description URL', :string, :input_type => :url, :required => :required, :placeholder => 'Content Rights Description URL' q_copyrightStatementMetadata 'Does your rights statement include machine-readable versions of', :discussion_topic => :lb_copyrightStatementMetadata, :display_on_certificate => true, :text_as_statement => 'The rights statement includes data about', :help_text => 'It\'s good practice to embed information about rights in machine-readable formats so people can automatically attribute this data back to you when they use it.', :help_text_more_url => 'https://github.com/theodi/open-data-licensing/blob/master/guides/publisher-guide.md', :pick => :any dependency :rule => 'A' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} a_dataLicense 'data licence', :text_as_statement => 'its data licence', :requirement => ['standard_4'] a_contentLicense 'content licence', :text_as_statement => 'its content licence', :requirement => ['standard_5'] a_attribution 'attribution text', :text_as_statement => 'what attribution text to use', :requirement => ['standard_6'] a_attributionURL 'attribution URL', :text_as_statement => 'what attribution link to give', :requirement => ['standard_7'] a_copyrightNotice 'copyright notice or statement', :text_as_statement => 'a copyright notice or statement', :requirement => ['exemplar_1'] a_copyrightYear 'copyright year', :text_as_statement => 'the copyright year', :requirement => ['exemplar_2'] a_copyrightHolder 'copyright holder', :text_as_statement => 'the copyright holder', :requirement => ['exemplar_3'] label_standard_4 'You should provide <strong>machine-readable data in your rights statement about the licence</strong> for this data, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_4' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_dataLicense label_standard_5 'You should provide <strong>machine-readable data in your rights statement about the licence for the content</strong> of this data, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_5' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_contentLicense label_standard_6 'You should provide <strong>machine-readable data in your rights statement about the text to use when citing the data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_6' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_attribution label_standard_7 'You should provide <strong>machine-readable data in your rights statement about the URL to link to when citing this data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_7' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_attributionURL label_exemplar_1 'You should provide <strong>machine-readable data in your rights statement about the copyright statement or notice of this data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_1' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightNotice label_exemplar_2 'You should provide <strong>machine-readable data in your rights statement about the copyright year for the data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_2' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightYear label_exemplar_3 'You should provide <strong>machine-readable data in your rights statement about the copyright holder for the data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_3' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightHolder label_group_4 'Privacy', :help_text => 'how you protect people\'s privacy', :customer_renderer => '/partials/fieldset' q_dataPersonal 'Can individuals be identified from this data?', :discussion_topic => :lb_dataPersonal, :display_on_certificate => true, :text_as_statement => 'This data contains', :pick => :one, :required => :pilot a_not_personal 'no, the data is not about people or their activities', :text_as_statement => 'no data about individuals', :help_text => 'Remember that individuals can still be identified even if data isn\'t directly about them. For example, road traffic flow data combined with an individual\'s commuting patterns could reveal information about that person.' a_summarised 'no, the data has been anonymised by aggregating individuals into groups, so they can\'t be distinguished from other people in the group', :text_as_statement => 'aggregated data', :help_text => 'Statistical disclosure controls can help to make sure that individuals are not identifiable within aggregate data.' a_individual 'yes, there is a risk that individuals be identified, for example by third parties with access to extra information', :text_as_statement => 'information that could identify individuals', :help_text => 'Some data is legitimately about individuals like civil service pay or public expenses for example.' q_statisticalAnonAudited 'Has your anonymisation process been independently audited?', :discussion_topic => :lb_statisticalAnonAudited, :display_on_certificate => true, :text_as_statement => 'The anonymisation process has been', :pick => :one dependency :rule => 'A' condition_A :q_dataPersonal, '==', :a_summarised a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'independently audited', :requirement => ['standard_8'] label_standard_8 'You should <strong>have your anonymisation process audited independently</strong> to ensure it reduces the risk of individuals being reidentified.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_8' dependency :rule => 'A and B' condition_A :q_dataPersonal, '==', :a_summarised condition_B :q_statisticalAnonAudited, '==', :a_false q_appliedAnon 'Have you attempted to reduce or remove the possibility of individuals being identified?', :discussion_topic => :lb_appliedAnon, :display_on_certificate => true, :text_as_statement => 'This data about individuals has been', :help_text => 'Anonymisation reduces the risk of individuals being identified from the data you publish. The best technique to use depends on the kind of data you have.', :pick => :one, :required => :pilot dependency :rule => 'A' condition_A :q_dataPersonal, '==', :a_individual a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'anonymised' q_lawfulDisclosure 'Are you required or permitted by law to publish this data about individuals?', :discussion_topic => :lb_lawfulDisclosure, :display_on_certificate => true, :text_as_statement => 'By law, this data about individuals', :help_text => 'The law might require you to publish data about people, such as the names of company directors. Or you might have permission from the affected individuals to publish information about them.', :pick => :one dependency :rule => 'A and B' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'can be published', :requirement => ['pilot_5'] label_pilot_5 'You should <strong>only publish personal data without anonymisation if you are required or permitted to do so by law</strong>.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_5' dependency :rule => 'A and B and C' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false condition_C :q_lawfulDisclosure, '==', :a_false q_lawfulDisclosureURL 'Where do you document your right to publish data about individuals?', :discussion_topic => :lb_lawfulDisclosureURL, :display_on_certificate => true, :text_as_statement => 'The right to publish this data about individuals is documented at' dependency :rule => 'A and B and C' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false condition_C :q_lawfulDisclosure, '==', :a_true a_1 'Disclosure Rationale URL', :string, :input_type => :url, :placeholder => 'Disclosure Rationale URL', :requirement => ['standard_9'] label_standard_9 'You should <strong>document your right to publish data about individuals</strong> for people who use your data and for those affected by disclosure.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_9' dependency :rule => 'A and B and C and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_lawfulDisclosureURL, '==', {:string_value => '', :answer_reference => '1'} q_riskAssessmentExists 'Have you assessed the risks of disclosing personal data?', :discussion_topic => :lb_riskAssessmentExists, :display_on_certificate => true, :text_as_statement => 'The curator has', :help_text => 'A risk assessment measures risks to the privacy of individuals in your data as well as the use and disclosure of that information.', :pick => :one dependency :rule => 'A and (B or C)' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true a_false 'no', :text_as_statement => 'not carried out a privacy risk assessment' a_true 'yes', :text_as_statement => 'carried out a privacy risk assessment', :requirement => ['pilot_6'] label_pilot_6 'You should <strong>assess the risks of disclosing personal data</strong> if you publish data about individuals.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_6' dependency :rule => 'A and (B or C) and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_false q_riskAssessmentUrl 'Where is your risk assessment published?', :discussion_topic => :lb_riskAssessmentUrl, :display_on_certificate => true, :text_as_statement => 'The risk assessment is published at', :help_text => 'Give a URL to where people can check how you have assessed the privacy risks to individuals. This may be redacted or summarised if it contains sensitive information.' dependency :rule => 'A and (B or C) and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true a_1 'Risk Assessment URL', :string, :input_type => :url, :placeholder => 'Risk Assessment URL', :requirement => ['standard_10'] label_standard_10 'You should <strong>publish your privacy risk assessment</strong> so people can understand how you have assessed the risks of disclosing data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_10' dependency :rule => 'A and (B or C) and D and E' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_riskAssessmentUrl, '==', {:string_value => '', :answer_reference => '1'} q_riskAssessmentAudited 'Has your risk assessment been independently audited?', :discussion_topic => :lb_riskAssessmentAudited, :display_on_certificate => true, :text_as_statement => 'The risk assessment has been', :help_text => 'It\'s good practice to check your risk assessment was done correctly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.', :pick => :one dependency :rule => 'A and (B or C) and D and E' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'} a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'independently audited', :requirement => ['standard_11'] label_standard_11 'You should <strong>have your risk assessment audited independently</strong> to ensure it has been carried out correctly.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_11' dependency :rule => 'A and (B or C) and D and E and F' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_F :q_riskAssessmentAudited, '==', :a_false q_anonymisationAudited 'Has your anonymisation approach been independently audited?', :discussion_topic => :lb_anonymisationAudited, :display_on_certificate => true, :text_as_statement => 'The anonymisation of the data has been', :help_text => 'It is good practice to make sure your process to remove personal identifiable data works properly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.', :pick => :one dependency :rule => 'A and (B or C) and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'independently audited', :requirement => ['standard_12'] label_standard_12 'You should <strong>have your anonymisation process audited independently</strong> by an expert to ensure it is appropriate for your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_12' dependency :rule => 'A and (B or C) and D and E' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_anonymisationAudited, '==', :a_false end section_practical 'Practical Information', :description => 'Findability, accuracy, quality and guarantees' do label_group_6 'Findability', :help_text => 'how you help people find your data', :customer_renderer => '/partials/fieldset' q_onWebsite 'Is there a link to your data from your main website?', :discussion_topic => :onWebsite, :help_text => 'Data can be found more easily if it is linked to from your main website.', :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_13'] label_standard_13 'You should <strong>ensure that people can find the data from your main website</strong> so that people can find it more easily.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_13' dependency :rule => 'A' condition_A :q_onWebsite, '==', :a_false repeater 'Web Page' do dependency :rule => 'A' condition_A :q_onWebsite, '==', :a_true q_webpage 'Which page on your website links to the data?', :discussion_topic => :webpage, :display_on_certificate => true, :text_as_statement => 'The website links to the data from', :help_text => 'Give a URL on your main website that includes a link to this data.', :required => :required dependency :rule => 'A' condition_A :q_onWebsite, '==', :a_true a_1 'Web page URL', :string, :input_type => :url, :required => :required, :placeholder => 'Web page URL' end q_listed 'Is your data listed within a collection?', :discussion_topic => :listed, :help_text => 'Data is easier for people to find when it\'s in relevant data catalogs like academic, public sector or health for example, or when it turns up in relevant search results.', :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_14'] label_standard_14 'You should <strong>ensure that people can find your data when they search for it</strong> in locations that list data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_14' dependency :rule => 'A' condition_A :q_listed, '==', :a_false repeater 'Listing' do dependency :rule => 'A' condition_A :q_listed, '==', :a_true q_listing 'Where is it listed?', :discussion_topic => :listing, :display_on_certificate => true, :text_as_statement => 'The data appears in this collection', :help_text => 'Give a URL where this data is listed within a relevant collection. For example, data.gov.uk (if it\'s UK public sector data), hub.data.ac.uk (if it\'s UK academia data) or a URL for search engine results.', :required => :required dependency :rule => 'A' condition_A :q_listed, '==', :a_true a_1 'Listing URL', :string, :input_type => :url, :required => :required, :placeholder => 'Listing URL' end q_referenced 'Is this data referenced from your own publications?', :discussion_topic => :referenced, :help_text => 'When you reference your data within your own publications, such as reports, presentations or blog posts, you give it more context and help people find and understand it better.', :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_15'] label_standard_15 'You should <strong>reference data from your own publications</strong> so that people are aware of its availability and context.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_15' dependency :rule => 'A' condition_A :q_referenced, '==', :a_false repeater 'Reference' do dependency :rule => 'A' condition_A :q_referenced, '==', :a_true q_reference 'Where is your data referenced?', :discussion_topic => :reference, :display_on_certificate => true, :text_as_statement => 'This data is referenced from', :help_text => 'Give a URL to a document that cites or references this data.', :required => :required dependency :rule => 'A' condition_A :q_referenced, '==', :a_true a_1 'Reference URL', :string, :input_type => :url, :required => :required, :placeholder => 'Reference URL' end label_group_7 'Accuracy', :help_text => 'how you keep your data up-to-date', :customer_renderer => '/partials/fieldset' q_serviceType 'Does the data behind your API change?', :discussion_topic => :serviceType, :display_on_certificate => true, :text_as_statement => 'The data behind the API', :pick => :one, :required => :pilot dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_static 'no, the API gives access to unchanging data', :text_as_statement => 'will not change', :help_text => 'Some APIs just make accessing an unchanging dataset easier, particularly when there\'s lots of it.' a_changing 'yes, the API gives access to changing data', :text_as_statement => 'will change', :help_text => 'Some APIs give instant access to more up-to-date and ever-changing data' q_timeSensitive 'Will your data go out of date?', :discussion_topic => :timeSensitive, :display_on_certificate => true, :text_as_statement => 'The accuracy or relevance of this data will', :pick => :one dependency :rule => '(A or B or (C and D))' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_releaseType, '==', :a_collection condition_C :q_releaseType, '==', :a_service condition_D :q_serviceType, '==', :a_static a_true 'yes, this data will go out of date', :text_as_statement => 'go out of date', :help_text => 'For example, a dataset of bus stop locations will go out of date over time as some are moved or new ones created.' a_timestamped 'yes, this data will go out of date over time but it’s time stamped', :text_as_statement => 'go out of date but it is timestamped', :help_text => 'For example, population statistics usually include a fixed timestamp to indicate when the statistics were relevant.', :requirement => ['pilot_7'] a_false 'no, this data does not contain any time-sensitive information', :text_as_statement => 'not go out of date', :help_text => 'For example, the results of an experiment will not go out of date because the data accurately reports observed outcomes.', :requirement => ['standard_16'] label_pilot_7 'You should <strong>put timestamps in your data when you release it</strong> so people know the period it relates to and when it will expire.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_7' dependency :rule => '(A or B or (C and D)) and (E and F)' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_releaseType, '==', :a_collection condition_C :q_releaseType, '==', :a_service condition_D :q_serviceType, '==', :a_static condition_E :q_timeSensitive, '!=', :a_timestamped condition_F :q_timeSensitive, '!=', :a_false label_standard_16 'You should <strong>publish updates to time-sensitive data</strong> so that it does not go stale.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_16' dependency :rule => '(A or B or (C and D)) and (E)' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_releaseType, '==', :a_collection condition_C :q_releaseType, '==', :a_service condition_D :q_serviceType, '==', :a_static condition_E :q_timeSensitive, '!=', :a_false q_frequentChanges 'Does this data change at least daily?', :discussion_topic => :frequentChanges, :display_on_certificate => true, :text_as_statement => 'This data changes', :help_text => 'Tell people if the underlying data changes on most days. When data changes frequently it also goes out of date quickly, so people need to know if you also update it frequently and quickly too.', :pick => :one, :required => :pilot dependency :rule => 'A' condition_A :q_releaseType, '==', :a_series a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'at least daily' q_seriesType 'What type of dataset series is this?', :discussion_topic => :seriesType, :display_on_certificate => true, :text_as_statement => 'This data is a series of', :pick => :one, :required => :exemplar dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true a_dumps 'regular copies of a complete database', :text_as_statement => 'copies of a database', :help_text => 'Choose if you publish new and updated copies of your full database regularly. When you create database dumps, it\'s useful for people to have access to a feed of the changes so they can keep their copies up to date.' a_aggregate 'regular aggregates of changing data', :text_as_statement => 'aggregates of changing data', :help_text => 'Choose if you create new datasets regularly. You might do this if the underlying data can\'t be released as open data or if you only publish data that\'s new since the last publication.' q_changeFeed 'Is a feed of changes available?', :discussion_topic => :changeFeed, :display_on_certificate => true, :text_as_statement => 'A feed of changes to this data', :help_text => 'Tell people if you provide a stream of changes that affect this data, like new entries or amendments to existing entries. Feeds might be in RSS, Atom or custom formats.', :pick => :one dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_seriesType, '==', :a_dumps a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'is available', :requirement => ['exemplar_4'] label_exemplar_4 'You should <strong>provide a feed of changes to your data</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_4' dependency :rule => 'A and B and C and D' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_seriesType, '==', :a_dumps condition_D :q_changeFeed, '==', :a_false q_frequentSeriesPublication 'How often do you create a new release?', :discussion_topic => :frequentSeriesPublication, :display_on_certificate => true, :text_as_statement => 'New releases of this data are made', :help_text => 'This determines how out of date this data becomes before people can get an update.', :pick => :one dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true a_rarely 'less than once a month', :text_as_statement => 'less than once a month' a_monthly 'at least every month', :text_as_statement => 'at least every month', :requirement => ['pilot_8'] a_weekly 'at least every week', :text_as_statement => 'at least every week', :requirement => ['standard_17'] a_daily 'at least every day', :text_as_statement => 'at least every day', :requirement => ['exemplar_5'] label_pilot_8 'You should <strong>create a new dataset release every month</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_8' dependency :rule => 'A and B and (C and D and E)' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_frequentSeriesPublication, '!=', :a_monthly condition_D :q_frequentSeriesPublication, '!=', :a_weekly condition_E :q_frequentSeriesPublication, '!=', :a_daily label_standard_17 'You should <strong>create a new dataset release every week</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_17' dependency :rule => 'A and B and (C and D)' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_frequentSeriesPublication, '!=', :a_weekly condition_D :q_frequentSeriesPublication, '!=', :a_daily label_exemplar_5 'You should <strong>create a new dataset release every day</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_5' dependency :rule => 'A and B and (C)' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_frequentSeriesPublication, '!=', :a_daily q_seriesPublicationDelay 'How long is the delay between when you create a dataset and when you publish it?', :discussion_topic => :seriesPublicationDelay, :display_on_certificate => true, :text_as_statement => 'The lag between creation and publication of this data is', :pick => :one dependency :rule => 'A' condition_A :q_releaseType, '==', :a_series a_extreme 'longer than the gap between releases', :text_as_statement => 'longer than the gap between releases', :help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes more than a day for it to be published.' a_reasonable 'about the same as the gap between releases', :text_as_statement => 'about the same as the gap between releases', :help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes about a day for it to be published.', :requirement => ['pilot_9'] a_good 'less than half the gap between releases', :text_as_statement => 'less than half the gap between releases', :help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes less than twelve hours for it to be published.', :requirement => ['standard_18'] a_minimal 'there is minimal or no delay', :text_as_statement => 'minimal', :help_text => 'Choose this if you publish within a few seconds or a few minutes.', :requirement => ['exemplar_6'] label_pilot_9 'You should <strong>have a reasonable delay between when you create and publish a dataset</strong> that is less than the gap between releases so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_9' dependency :rule => 'A and (B and C and D)' condition_A :q_releaseType, '==', :a_series condition_B :q_seriesPublicationDelay, '!=', :a_reasonable condition_C :q_seriesPublicationDelay, '!=', :a_good condition_D :q_seriesPublicationDelay, '!=', :a_minimal label_standard_18 'You should <strong>have a short delay between when you create and publish a dataset</strong> that is less than half the gap between releases so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_18' dependency :rule => 'A and (B and C)' condition_A :q_releaseType, '==', :a_series condition_B :q_seriesPublicationDelay, '!=', :a_good condition_C :q_seriesPublicationDelay, '!=', :a_minimal label_exemplar_6 'You should <strong>have minimal or no delay between when you create and publish a dataset</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_6' dependency :rule => 'A and (B)' condition_A :q_releaseType, '==', :a_series condition_B :q_seriesPublicationDelay, '!=', :a_minimal q_provideDumps 'Do you also publish dumps of this dataset?', :discussion_topic => :provideDumps, :display_on_certificate => true, :text_as_statement => 'The curator publishes', :help_text => 'A dump is an extract of the whole dataset into a file that people can download. This lets people do analysis that\'s different to analysis with API access.', :pick => :one dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'dumps of the data', :requirement => ['standard_19'] label_standard_19 'You should <strong>let people download your entire dataset</strong> so that they can do more complete and accurate analysis with all the data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_19' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_false q_dumpFrequency 'How frequently do you create a new database dump?', :discussion_topic => :dumpFrequency, :display_on_certificate => true, :text_as_statement => 'Database dumps are created', :help_text => 'Faster access to more frequent extracts of the whole dataset means people can get started quicker with the most up-to-date data.', :pick => :one dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true a_rarely 'less frequently than once a month', :text_as_statement => 'less frequently than once a month' a_monthly 'at least every month', :text_as_statement => 'at least every month', :requirement => ['pilot_10'] a_weekly 'within a week of any change', :text_as_statement => 'within a week of any change', :requirement => ['standard_20'] a_daily 'within a day of any change', :text_as_statement => 'within a day of any change', :requirement => ['exemplar_7'] label_pilot_10 'You should <strong>create a new database dump every month</strong> so that people have the latest data.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_10' dependency :rule => 'A and B and C and (D and E and F)' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true condition_D :q_dumpFrequency, '!=', :a_monthly condition_E :q_dumpFrequency, '!=', :a_weekly condition_F :q_dumpFrequency, '!=', :a_daily label_standard_20 'You should <strong>create a new database dump within a week of any change</strong> so that people have less time to wait for the latest data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_20' dependency :rule => 'A and B and C and (D and E)' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true condition_D :q_dumpFrequency, '!=', :a_weekly condition_E :q_dumpFrequency, '!=', :a_daily label_exemplar_7 'You should <strong>create a new database dump within a day of any change</strong> so that people find it easier to get the latest data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_7' dependency :rule => 'A and B and C and (D)' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true condition_D :q_dumpFrequency, '!=', :a_daily q_corrected 'Will your data be corrected if it has errors?', :discussion_topic => :corrected, :display_on_certificate => true, :text_as_statement => 'Any errors in this data are', :help_text => 'It\'s good practice to fix errors in your data especially if you use it yourself. When you make corrections, people need to be told about them.', :pick => :one dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_timeSensitive, '!=', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'corrected', :requirement => ['standard_21'] label_standard_21 'You should <strong>correct data when people report errors</strong> so everyone benefits from improvements in accuracy.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_21' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_timeSensitive, '!=', :a_true condition_C :q_corrected, '==', :a_false label_group_8 'Quality', :help_text => 'how much people can rely on your data', :customer_renderer => '/partials/fieldset' q_qualityUrl 'Where do you document issues with the quality of this data?', :discussion_topic => :qualityUrl, :display_on_certificate => true, :text_as_statement => 'Data quality is documented at', :help_text => 'Give a URL where people can find out about the quality of your data. People accept that errors are inevitable, from equipment malfunctions or mistakes that happen in system migrations. You should be open about quality so people can judge how much to rely on this data.' a_1 'Data Quality Documentation URL', :string, :input_type => :url, :placeholder => 'Data Quality Documentation URL', :requirement => ['standard_22'] label_standard_22 'You should <strong>document any known issues with your data quality</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_22' dependency :rule => 'A' condition_A :q_qualityUrl, '==', {:string_value => '', :answer_reference => '1'} q_qualityControlUrl 'Where is your quality control process described?', :discussion_topic => :qualityControlUrl, :display_on_certificate => true, :text_as_statement => 'Quality control processes are described at', :help_text => 'Give a URL for people to learn about ongoing checks on your data, either automatic or manual. This reassures them that you take quality seriously and encourages improvements that benefit everyone.' a_1 'Quality Control Process Description URL', :string, :input_type => :url, :placeholder => 'Quality Control Process Description URL', :requirement => ['exemplar_8'] label_exemplar_8 'You should <strong>document your quality control process</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_8' dependency :rule => 'A' condition_A :q_qualityControlUrl, '==', {:string_value => '', :answer_reference => '1'} label_group_9 'Guarantees', :help_text => 'how much people can depend on your data’s availability', :customer_renderer => '/partials/fieldset' q_backups 'Do you take offsite backups?', :discussion_topic => :backups, :display_on_certificate => true, :text_as_statement => 'The data is', :help_text => 'Taking a regular offsite backup helps ensure that the data won\'t be lost in the case of accident.', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'backed up offsite', :requirement => ['standard_23'] label_standard_23 'You should <strong>take a result offsite backup</strong> so that the data won\'t be lost if an accident happens.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_23' dependency :rule => 'A' condition_A :q_backups, '==', :a_false q_slaUrl 'Where do you describe any guarantees about service availability?', :discussion_topic => :slaUrl, :display_on_certificate => true, :text_as_statement => 'Service availability is described at', :help_text => 'Give a URL for a page that describes what guarantees you have about your service being available for people to use. For example you might have a guaranteed uptime of 99.5%, or you might provide no guarantees.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_1 'Service Availability Documentation URL', :string, :input_type => :url, :placeholder => 'Service Availability Documentation URL', :requirement => ['standard_24'] label_standard_24 'You should <strong>describe what guarantees you have around service availability</strong> so that people know how much they can rely on it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_24' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_slaUrl, '==', {:string_value => '', :answer_reference => '1'} q_statusUrl 'Where do you give information about the current status of the service?', :discussion_topic => :statusUrl, :display_on_certificate => true, :text_as_statement => 'Service status is given at', :help_text => 'Give a URL for a page that tells people about the current status of your service, including any faults you are aware of.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_1 'Service Status URL', :string, :input_type => :url, :placeholder => 'Service Status URL', :requirement => ['exemplar_9'] label_exemplar_9 'You should <strong>have a service status page</strong> that tells people about the current status of your service.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_9' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_statusUrl, '==', {:string_value => '', :answer_reference => '1'} q_onGoingAvailability 'How long will this data be available for?', :discussion_topic => :onGoingAvailability, :display_on_certificate => true, :text_as_statement => 'The data is available', :pick => :one a_experimental 'it might disappear at any time', :text_as_statement => 'experimentally and might disappear at any time' a_short 'it\'s available experimentally but should be around for another year or so', :text_as_statement => 'experimentally for another year or so', :requirement => ['pilot_11'] a_medium 'it\'s in your medium-term plans so should be around for a couple of years', :text_as_statement => 'for at least a couple of years', :requirement => ['standard_25'] a_long 'it\'s part of your day-to-day operations so will stay published for a long time', :text_as_statement => 'for a long time', :requirement => ['exemplar_10'] label_pilot_11 'You should <strong>guarantee that your data will be available in this form for at least a year</strong> so that people can decide how much to rely on your data.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_11' dependency :rule => 'A and B and C' condition_A :q_onGoingAvailability, '!=', :a_short condition_B :q_onGoingAvailability, '!=', :a_medium condition_C :q_onGoingAvailability, '!=', :a_long label_standard_25 'You should <strong>guarantee that your data will be available in this form in the medium-term</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_25' dependency :rule => 'A and B' condition_A :q_onGoingAvailability, '!=', :a_medium condition_B :q_onGoingAvailability, '!=', :a_long label_exemplar_10 'You should <strong>guarantee that your data will be available in this form in the long-term</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_10' dependency :rule => 'A' condition_A :q_onGoingAvailability, '!=', :a_long end section_technical 'Technical Information', :description => 'Locations, formats and trust' do label_group_11 'Locations', :help_text => 'how people can access your data', :customer_renderer => '/partials/fieldset' q_datasetUrl 'Where is your dataset?', :discussion_topic => :datasetUrl, :display_on_certificate => true, :text_as_statement => 'This data is published at', :help_text => 'Give a URL to the dataset itself. Open data should be linked to directly on the web so people can easily find and reuse it.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_oneoff a_1 'Dataset URL', :string, :input_type => :url, :placeholder => 'Dataset URL', :requirement => ['basic_9', 'pilot_12'] label_basic_9 'You must <strong>provide either a URL to your data or a URL to documentation</strong> about it so that people can find it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_9' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'} label_pilot_12 'You should <strong>have a URL that is a direct link to the data itself</strong> so that people can access it easily.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_12' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'} q_versionManagement 'How do you publish a series of the same dataset?', :discussion_topic => :versionManagement, :requirement => ['basic_10'], :pick => :any dependency :rule => 'A' condition_A :q_releaseType, '==', :a_series a_current 'as a single URL that\'s regularly updated', :help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current dataset.', :requirement => ['standard_26'] a_template 'as consistent URLs for each release', :help_text => 'Choose this if your dataset URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['pilot_13'] a_list 'as a list of releases', :help_text => 'Choose this if you have a list of datasets on a web page or a feed (like Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['standard_27'] label_standard_26 'You should <strong>have a single persistent URL to download the current version of your data</strong> so that people can access it easily.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_26' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '!=', :a_current label_pilot_13 'You should <strong>use a consistent pattern for different release URLs</strong> so that people can download each one automatically.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_13' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '!=', :a_template label_standard_27 'You should <strong>have a document or feed with a list of available releases</strong> so people can create scripts to download them all.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_27' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '!=', :a_list label_basic_10 'You must <strong>provide access to releases of your data through a URL</strong> that gives the current version, a discoverable series of URLs or through a documentation page so that people can find it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_10' dependency :rule => 'A and (B and C and D and E)' condition_A :q_releaseType, '==', :a_series condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} condition_C :q_versionManagement, '!=', :a_current condition_D :q_versionManagement, '!=', :a_template condition_E :q_versionManagement, '!=', :a_list q_currentDatasetUrl 'Where is your current dataset?', :discussion_topic => :currentDatasetUrl, :display_on_certificate => true, :text_as_statement => 'The current dataset is available at', :help_text => 'Give a single URL to the most recent version of the dataset. The content at this URL should change each time a new version is released.', :required => :required dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '==', :a_current a_1 'Current Dataset URL', :string, :input_type => :url, :placeholder => 'Current Dataset URL', :required => :required q_versionsTemplateUrl 'What format do dataset release URLs follow?', :discussion_topic => :versionsTemplateUrl, :display_on_certificate => true, :text_as_statement => 'Releases follow this consistent URL pattern', :help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`', :required => :required dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '==', :a_template a_1 'Version Template URL', :string, :input_type => :text, :placeholder => 'Version Template URL', :required => :required q_versionsUrl 'Where is your list of dataset releases?', :discussion_topic => :versionsUrl, :display_on_certificate => true, :text_as_statement => 'Releases of this data are listed at', :help_text => 'Give a URL to a page or feed with a machine-readable list of datasets. Use the URL of the first page which should link to the rest of the pages.', :required => :required dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '==', :a_list a_1 'Version List URL', :string, :input_type => :url, :placeholder => 'Version List URL', :required => :required q_endpointUrl 'Where is the endpoint for your API?', :discussion_topic => :endpointUrl, :display_on_certificate => true, :text_as_statement => 'The API service endpoint is', :help_text => 'Give a URL that\'s a starting point for people\'s scripts to access your API. This should be a service description document that helps the script to work out which services exist.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_1 'Endpoint URL', :string, :input_type => :url, :placeholder => 'Endpoint URL', :requirement => ['basic_11', 'standard_28'] label_basic_11 'You must <strong>provide either an API endpoint URL or a URL to its documentation</strong> so that people can find it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_11' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'} label_standard_28 'You should <strong>have a service description document or single entry point for your API</strong> so that people can access it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_28' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'} q_dumpManagement 'How do you publish database dumps?', :discussion_topic => :dumpManagement, :pick => :any dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true a_current 'as a single URL that\'s regularly updated', :help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current database dump.', :requirement => ['standard_29'] a_template 'as consistent URLs for each release', :help_text => 'Choose this if your database dump URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['exemplar_11'] a_list 'as a list of releases', :help_text => 'Choose this if you have a list of database dumps on a web page or a feed (such as Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['exemplar_12'] label_standard_29 'You should <strong>have a single persistent URL to download the current dump of your database</strong> so that people can find it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_29' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '!=', :a_current label_exemplar_11 'You should <strong>use a consistent pattern for database dump URLs</strong> so that people can can download each one automatically.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_11' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '!=', :a_template label_exemplar_12 'You should <strong>have a document or feed with a list of available database dumps</strong> so people can create scripts to download them all', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_12' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '!=', :a_list q_currentDumpUrl 'Where is the current database dump?', :discussion_topic => :currentDumpUrl, :display_on_certificate => true, :text_as_statement => 'The most recent database dump is always available at', :help_text => 'Give a URL to the most recent dump of the database. The content at this URL should change each time a new database dump is created.', :required => :required dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '==', :a_current a_1 'Current Dump URL', :string, :input_type => :url, :placeholder => 'Current Dump URL', :required => :required q_dumpsTemplateUrl 'What format do database dump URLs follow?', :discussion_topic => :dumpsTemplateUrl, :display_on_certificate => true, :text_as_statement => 'Database dumps follow the consistent URL pattern', :help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`', :required => :required dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '==', :a_template a_1 'Dump Template URL', :string, :input_type => :text, :placeholder => 'Dump Template URL', :required => :required q_dumpsUrl 'Where is your list of available database dumps?', :discussion_topic => :dumpsUrl, :display_on_certificate => true, :text_as_statement => 'A list of database dumps is at', :help_text => 'Give a URL to a page or feed with a machine-readable list of database dumps. Use the URL of the first page which should link to the rest of the pages.', :required => :required dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '==', :a_list a_1 'Dump List URL', :string, :input_type => :url, :placeholder => 'Dump List URL', :required => :required q_changeFeedUrl 'Where is your feed of changes?', :discussion_topic => :changeFeedUrl, :display_on_certificate => true, :text_as_statement => 'A feed of changes to this data is at', :help_text => 'Give a URL to a page or feed that provides a machine-readable list of the previous versions of the database dumps. Use the URL of the first page which should link to the rest of the pages.', :required => :required dependency :rule => 'A' condition_A :q_changeFeed, '==', :a_true a_1 'Change Feed URL', :string, :input_type => :url, :placeholder => 'Change Feed URL', :required => :required label_group_12 'Formats', :help_text => 'how people can work with your data', :customer_renderer => '/partials/fieldset' q_machineReadable 'Is this data machine-readable?', :discussion_topic => :machineReadable, :display_on_certificate => true, :text_as_statement => 'This data is', :help_text => 'People prefer data formats which are easily processed by a computer, for speed and accuracy. For example, a scanned photocopy of a spreadsheet would not be machine-readable but a CSV file would be.', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'machine-readable', :requirement => ['pilot_14'] label_pilot_14 'You should <strong>provide your data in a machine-readable format</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_14' dependency :rule => 'A' condition_A :q_machineReadable, '==', :a_false q_openStandard 'Is this data in a standard open format?', :discussion_topic => :openStandard, :display_on_certificate => true, :text_as_statement => 'The format of this data is', :help_text => 'Open standards are created through a fair, transparent and collaborative process. Anyone can implement them and there’s lots of support so it’s easier for you to share data with more people. For example, XML, CSV and JSON are open standards.', :help_text_more_url => 'https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/183962/Open-Standards-Principles-FINAL.pdf', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'a standard open format', :requirement => ['standard_30'] label_standard_30 'You should <strong>provide your data in an open standard format</strong> so that people can use widely available tools to process it more easily.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_30' dependency :rule => 'A' condition_A :q_openStandard, '==', :a_false q_dataType 'What kind of data do you publish?', :discussion_topic => :dataType, :pick => :any a_documents 'human-readable documents', :help_text => 'Choose this if your data is meant for human consumption. For example; policy documents, white papers, reports and meeting minutes. These usually have some structure to them but are mostly text.' a_statistical 'statistical data like counts, averages and percentages', :help_text => 'Choose this if your data is statistical or numeric data like counts, averages or percentages. Like census results, traffic flow information or crime statistics for example.' a_geographic 'geographic information, such as points and boundaries', :help_text => 'Choose this if your data can be plotted on a map as points, boundaries or lines.' a_structured 'other kinds of structured data', :help_text => 'Choose this if your data is structured in other ways. Like event details, railway timetables, contact information or anything that can be interpreted as data, and analysed and presented in multiple ways.' q_documentFormat 'Do your human-readable documents include formats that', :discussion_topic => :documentFormat, :display_on_certificate => true, :text_as_statement => 'Documents are published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_documents a_semantic 'describe semantic structure like HTML, Docbook or Markdown', :text_as_statement => 'in a semantic format', :help_text => 'These formats label structures like chapters, headings and tables that make it easy to automatically create summaries like tables of contents and glossaries. They also make it easy to apply different styles to the document so its appearance changes.', :requirement => ['standard_31'] a_format 'describe information on formatting like OOXML or PDF', :text_as_statement => 'in a display format', :help_text => 'These formats emphasise appearance like fonts, colours and positioning of different elements within the page. These are good for human consumption, but aren\'t as easy for people to process automatically and change style.', :requirement => ['pilot_15'] a_unsuitable 'aren\'t meant for documents like Excel, JSON or CSV', :text_as_statement => 'in a format unsuitable for documents', :help_text => 'These formats better suit tabular or structured data.' label_standard_31 'You should <strong>publish documents in a format that exposes semantic structure</strong> so that people can display them in different styles.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_31' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_documents condition_B :q_documentFormat, '!=', :a_semantic label_pilot_15 'You should <strong>publish documents in a format designed specifically for them</strong> so that they\'re easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_15' dependency :rule => 'A and (B and C)' condition_A :q_dataType, '==', :a_documents condition_B :q_documentFormat, '!=', :a_semantic condition_C :q_documentFormat, '!=', :a_format q_statisticalFormat 'Does your statistical data include formats that', :discussion_topic => :statisticalFormat, :display_on_certificate => true, :text_as_statement => 'Statistical data is published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_statistical a_statistical 'expose the structure of statistical hypercube data like <a href="http://sdmx.org/">SDMX</a> or <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a>', :text_as_statement => 'in a statistical data format', :help_text => 'Individual observations in hypercubes relate to a particular measure and a set of dimensions. Each observation may also be related to annotations that give extra context. Formats like <a href="http://sdmx.org/">SDMX</a> and <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a> are designed to express this underlying structure.', :requirement => ['exemplar_13'] a_tabular 'treat statistical data as a table like CSV', :text_as_statement => 'in a tabular data format', :help_text => 'These formats arrange statistical data within a table of rows and columns. This lacks extra context about the underlying hypercube but is easy to process.', :requirement => ['standard_32'] a_format 'focus on the format of tabular data like Excel', :text_as_statement => 'in a presentation format', :help_text => 'Spreadsheets use formatting like italic or bold text, and indentation within fields to describe its appearance and underlying structure. This styling helps people to understand the meaning of your data but makes it less suitable for computers to process.', :requirement => ['pilot_16'] a_unsuitable 'aren\'t meant for statistical or tabular data like Word or PDF', :text_as_statement => 'in a format unsuitable for statistical data', :help_text => 'These formats don\'t suit statistical data because they obscure the underlying structure of the data.' label_exemplar_13 'You should <strong>publish statistical data in a format that exposes dimensions and measures</strong> so that it\'s easy to analyse.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_13' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_statistical condition_B :q_statisticalFormat, '!=', :a_statistical label_standard_32 'You should <strong>publish tabular data in a format that exposes tables of data</strong> so that it\'s easy to analyse.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_32' dependency :rule => 'A and (B and C)' condition_A :q_dataType, '==', :a_statistical condition_B :q_statisticalFormat, '!=', :a_statistical condition_C :q_statisticalFormat, '!=', :a_tabular label_pilot_16 'You should <strong>publish tabular data in a format designed for that purpose</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_16' dependency :rule => 'A and (B and C and D)' condition_A :q_dataType, '==', :a_statistical condition_B :q_statisticalFormat, '!=', :a_statistical condition_C :q_statisticalFormat, '!=', :a_tabular condition_D :q_statisticalFormat, '!=', :a_format q_geographicFormat 'Does your geographic data include formats that', :discussion_topic => :geographicFormat, :display_on_certificate => true, :text_as_statement => 'Geographic data is published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_geographic a_specific 'are designed for geographic data like <a href="http://www.opengeospatial.org/standards/kml/">KML</a> or <a href="http://www.geojson.org/">GeoJSON</a>', :text_as_statement => 'in a geographic data format', :help_text => 'These formats describe points, lines and boundaries, and expose structures in the data which make it easier to process automatically.', :requirement => ['exemplar_14'] a_generic 'keeps data structured like JSON, XML or CSV', :text_as_statement => 'in a generic data format', :help_text => 'Any format that stores normal structured data can express geographic data too, particularly if it only holds data about points.', :requirement => ['pilot_17'] a_unsuitable 'aren\'t designed for geographic data like Word or PDF', :text_as_statement => 'in a format unsuitable for geographic data', :help_text => 'These formats don\'t suit geographic data because they obscure the underlying structure of the data.' label_exemplar_14 'You should <strong>publish geographic data in a format designed that purpose</strong> so that people can use widely available tools to process it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_14' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_geographic condition_B :q_geographicFormat, '!=', :a_specific label_pilot_17 'You should <strong>publish geographic data as structured data</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_17' dependency :rule => 'A and (B and C)' condition_A :q_dataType, '==', :a_geographic condition_B :q_geographicFormat, '!=', :a_specific condition_C :q_geographicFormat, '!=', :a_generic q_structuredFormat 'Does your structured data include formats that', :discussion_topic => :structuredFormat, :display_on_certificate => true, :text_as_statement => 'Structured data is published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_structured a_suitable 'are designed for structured data like JSON, XML, Turtle or CSV', :text_as_statement => 'in a structured data format', :help_text => 'These formats organise data into a basic structure of things which have values for a known set of properties. These formats are easy for computers to process automatically.', :requirement => ['pilot_18'] a_unsuitable 'aren\'t designed for structured data like Word or PDF', :text_as_statement => 'in a format unsuitable for structured data', :help_text => 'These formats don\'t suit this kind of data because they obscure its underlying structure.' label_pilot_18 'You should <strong>publish structured data in a format designed that purpose</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_18' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_structured condition_B :q_structuredFormat, '!=', :a_suitable q_identifiers 'Does your data use persistent identifiers?', :discussion_topic => :identifiers, :display_on_certificate => true, :text_as_statement => 'The data includes', :help_text => 'Data is usually about real things like schools or roads or uses a coding scheme. If data from different sources use the same persistent and unique identifier to refer to the same things, people can combine sources easily to create more useful data. Identifiers might be GUIDs, DOIs or URLs.', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'persistent identifiers', :requirement => ['standard_33'] label_standard_33 'You should <strong>use identifiers for things in your data</strong> so that they can be easily related with other data about those things.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_33' dependency :rule => 'A' condition_A :q_identifiers, '==', :a_false q_resolvingIds 'Can the identifiers in your data be used to find extra information?', :discussion_topic => :resolvingIds, :display_on_certificate => true, :text_as_statement => 'The persistent identifiers', :pick => :one dependency :rule => 'A' condition_A :q_identifiers, '==', :a_true a_false 'no, the identifiers can\'t be used to find extra information', :text_as_statement => '' a_service 'yes, there is a service that people can use to resolve the identifiers', :text_as_statement => 'resolve using a service', :help_text => 'Online services can be used to give people information about identifiers such as GUIDs or DOIs which can\'t be directly accessed in the way that URLs are.', :requirement => ['standard_34'] a_resolvable 'yes, the identifiers are URLs that resolve to give information', :text_as_statement => 'resolve because they are URLs', :help_text => 'URLs are useful for both people and computers. People can put a URL into their browser and read more information, like <a href="http://opencorporates.com/companies/gb/08030289">companies</a> and <a href="http://data.ordnancesurvey.co.uk/doc/postcodeunit/EC2A4JE">postcodes</a>. Computers can also process this extra information using scripts to access the underlying data.', :requirement => ['exemplar_15'] label_standard_34 'You should <strong>provide a service to resolve the identifiers you use</strong> so that people can find extra information about them.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_34' dependency :rule => 'A and (B and C)' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '!=', :a_service condition_C :q_resolvingIds, '!=', :a_resolvable label_exemplar_15 'You should <strong>link to a web page of information about each of the things in your data</strong> so that people can easily find and share that information.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_15' dependency :rule => 'A and (B)' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '!=', :a_resolvable q_resolutionServiceURL 'Where is the service that is used to resolve the identifiers?', :discussion_topic => :resolutionServiceURL, :display_on_certificate => true, :text_as_statement => 'The identifier resolution service is at', :help_text => 'The resolution service should take an identifier as a query parameter and give back some information about the thing it identifies.' dependency :rule => 'A and B' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '==', :a_service a_1 'Identifier Resolution Service URL', :string, :input_type => :url, :placeholder => 'Identifier Resolution Service URL', :requirement => ['standard_35'] label_standard_35 'You should <strong>have a URL through which identifiers can be resolved</strong> so that more information about them can be found by a computer.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_35' dependency :rule => 'A and B and C' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '==', :a_service condition_C :q_resolutionServiceURL, '==', {:string_value => '', :answer_reference => '1'} q_existingExternalUrls 'Is there third-party information about things in your data on the web?', :discussion_topic => :existingExternalUrls, :help_text => 'Sometimes other people outside your control provide URLs to the things your data is about. For example, your data might have postcodes in it that link to the Ordnance Survey website.', :pick => :one, :required => :exemplar dependency :rule => 'A' condition_A :q_identifiers, '==', :a_true a_false 'no' a_true 'yes' q_reliableExternalUrls 'Is that third-party information reliable?', :discussion_topic => :reliableExternalUrls, :help_text => 'If a third-party provides public URLs about things in your data, they probably take steps to ensure data quality and reliability. This is a measure of how much you trust their processes to do that. Look for their open data certificate or similar hallmarks to help make your decision.', :pick => :one, :required => :exemplar dependency :rule => 'A and B' condition_A :q_identifiers, '==', :a_true condition_B :q_existingExternalUrls, '==', :a_true a_false 'no' a_true 'yes' q_externalUrls 'Does your data use those third-party URLs?', :discussion_topic => :externalUrls, :display_on_certificate => true, :text_as_statement => 'Third-party URLs are', :help_text => 'You should use third-party URLs that resolve to information about the things your data describes. This reduces duplication and helps people combine data from different sources to make it more useful.', :pick => :one dependency :rule => 'A and B and C' condition_A :q_identifiers, '==', :a_true condition_B :q_existingExternalUrls, '==', :a_true condition_C :q_reliableExternalUrls, '==', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'referenced in this data', :requirement => ['exemplar_16'] label_exemplar_16 'You should <strong>use URLs to third-party information in your data</strong> so that it\'s easy to combine with other data that uses those URLs.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_16' dependency :rule => 'A and B and C and D' condition_A :q_identifiers, '==', :a_true condition_B :q_existingExternalUrls, '==', :a_true condition_C :q_reliableExternalUrls, '==', :a_true condition_D :q_externalUrls, '==', :a_false label_group_13 'Trust', :help_text => 'how much trust people can put in your data', :customer_renderer => '/partials/fieldset' q_provenance 'Do you provide machine-readable provenance for your data?', :discussion_topic => :provenance, :display_on_certificate => true, :text_as_statement => 'The provenance of this data is', :help_text => 'This about the origins of how your data was created and processed before it was published. It builds trust in the data you publish because people can trace back how it has been handled.', :help_text_more_url => 'http://www.w3.org/TR/prov-primer/', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'machine-readable', :requirement => ['exemplar_17'] label_exemplar_17 'You should <strong>provide a machine-readable provenance trail</strong> about your data so that people can trace how it was processed.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_17' dependency :rule => 'A' condition_A :q_provenance, '==', :a_false q_digitalCertificate 'Where do you describe how people can verify that data they receive comes from you?', :discussion_topic => :digitalCertificate, :display_on_certificate => true, :text_as_statement => 'This data can be verified using', :help_text => 'If you deliver important data to people they should be able to check that what they receive is the same as what you published. For example, you can digitally sign the data you publish, so people can tell if it has been tampered with.' a_1 'Verification Process URL', :string, :input_type => :url, :placeholder => 'Verification Process URL', :requirement => ['exemplar_18'] label_exemplar_18 'You should <strong>describe how people can check that the data they receive is the same as what you published</strong> so that they can trust it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_18' dependency :rule => 'A' condition_A :q_digitalCertificate, '==', {:string_value => '', :answer_reference => '1'} end section_social 'Social Information', :description => 'Documentation, support and services' do label_group_15 'Documentation', :help_text => 'how you help people understand the context and content of your data', :customer_renderer => '/partials/fieldset' q_documentationMetadata 'Does your data documentation include machine-readable data for:', :discussion_topic => :documentationMetadata, :display_on_certificate => true, :text_as_statement => 'The documentation includes machine-readable data for', :pick => :any dependency :rule => 'A' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} a_title 'title', :text_as_statement => 'title', :requirement => ['standard_36'] a_description 'description', :text_as_statement => 'description', :requirement => ['standard_37'] a_issued 'release date', :text_as_statement => 'release date', :requirement => ['standard_38'] a_modified 'modification date', :text_as_statement => 'modification date', :requirement => ['standard_39'] a_accrualPeriodicity 'frequency of releases', :text_as_statement => 'release frequency', :requirement => ['standard_40'] a_identifier 'identifier', :text_as_statement => 'identifier', :requirement => ['standard_41'] a_landingPage 'landing page', :text_as_statement => 'landing page', :requirement => ['standard_42'] a_language 'language', :text_as_statement => 'language', :requirement => ['standard_43'] a_publisher 'publisher', :text_as_statement => 'publisher', :requirement => ['standard_44'] a_spatial 'spatial/geographical coverage', :text_as_statement => 'spatial/geographical coverage', :requirement => ['standard_45'] a_temporal 'temporal coverage', :text_as_statement => 'temporal coverage', :requirement => ['standard_46'] a_theme 'theme(s)', :text_as_statement => 'theme(s)', :requirement => ['standard_47'] a_keyword 'keyword(s) or tag(s)', :text_as_statement => 'keyword(s) or tag(s)', :requirement => ['standard_48'] a_distribution 'distribution(s)', :text_as_statement => 'distribution(s)' label_standard_36 'You should <strong>include a machine-readable data title in your documentation</strong> so that people know how to refer to it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_36' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_title label_standard_37 'You should <strong>include a machine-readable data description in your documentation</strong> so that people know what it contains.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_37' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_description label_standard_38 'You should <strong>include a machine-readable data release date in your documentation</strong> so that people know how timely it is.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_38' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_issued label_standard_39 'You should <strong>include a machine-readable last modification date in your documentation</strong> so that people know they have the latest data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_39' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_modified label_standard_40 'You should <strong>provide machine-readable metadata about how frequently you release new versions of your data</strong> so people know how often you update it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_40' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_accrualPeriodicity label_standard_41 'You should <strong>include a canonical URL for the data in your machine-readable documentation</strong> so that people know how to access it consistently.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_41' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_identifier label_standard_42 'You should <strong>include a canonical URL to the machine-readable documentation itself</strong> so that people know how to access to it consistently.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_42' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_landingPage label_standard_43 'You should <strong>include the data language in your machine-readable documentation</strong> so that people who search for it will know whether they can understand it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_43' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_language label_standard_44 'You should <strong>indicate the data publisher in your machine-readable documentation</strong> so people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_44' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_publisher label_standard_45 'You should <strong>include the geographic coverage in your machine-readable documentation</strong> so that people understand where your data applies to.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_45' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_spatial label_standard_46 'You should <strong>include the time period in your machine-readable documentation</strong> so that people understand when your data applies to.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_46' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_temporal label_standard_47 'You should <strong>include the subject in your machine-readable documentation</strong> so that people know roughly what your data is about.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_47' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_theme label_standard_48 'You should <strong>include machine-readable keywords or tags in your documentation</strong> to help people search within the data effectively.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_48' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_keyword q_distributionMetadata 'Does your documentation include machine-readable metadata for each distribution on:', :discussion_topic => :distributionMetadata, :display_on_certificate => true, :text_as_statement => 'The documentation about each distribution includes machine-readable data for', :pick => :any dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution a_title 'title', :text_as_statement => 'title', :requirement => ['standard_49'] a_description 'description', :text_as_statement => 'description', :requirement => ['standard_50'] a_issued 'release date', :text_as_statement => 'release date', :requirement => ['standard_51'] a_modified 'modification date', :text_as_statement => 'modification date', :requirement => ['standard_52'] a_rights 'rights statement', :text_as_statement => 'rights statement', :requirement => ['standard_53'] a_accessURL 'URL to access the data', :text_as_statement => 'a URL to access the data', :help_text => 'This metadata should be used when your data isn\'t available as a download, like an API for example.' a_downloadURL 'URL to download the dataset', :text_as_statement => 'a URL to download the dataset' a_byteSize 'size in bytes', :text_as_statement => 'size in bytes' a_mediaType 'type of download media', :text_as_statement => 'type of download media' label_standard_49 'You should <strong>include machine-readable titles within your documentation</strong> so people know how to refer to each data distribution.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_49' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_title label_standard_50 'You should <strong>include machine-readable descriptions within your documentation</strong> so people know what each data distribution contains.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_50' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_description label_standard_51 'You should <strong>include machine-readable release dates within your documentation</strong> so people know how current each distribution is.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_51' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_issued label_standard_52 'You should <strong>include machine-readable last modification dates within your documentation</strong> so people know whether their copy of a data distribution is up-to-date.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_52' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_modified label_standard_53 'You should <strong>include a machine-readable link to the applicable rights statement</strong> so people can find out what they can do with a data distribution.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_53' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_rights q_technicalDocumentation 'Where is the technical documentation for the data?', :discussion_topic => :technicalDocumentation, :display_on_certificate => true, :text_as_statement => 'The technical documentation for the data is at' a_1 'Technical Documentation URL', :string, :input_type => :url, :placeholder => 'Technical Documentation URL', :requirement => ['pilot_19'] label_pilot_19 'You should <strong>provide technical documentation for the data</strong> so that people understand how to use it.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_19' dependency :rule => 'A' condition_A :q_technicalDocumentation, '==', {:string_value => '', :answer_reference => '1'} q_vocabulary 'Do the data formats use vocabularies or schemas?', :discussion_topic => :vocabulary, :help_text => 'Formats like CSV, JSON, XML or Turtle use custom vocabularies or schemas which say what columns or properties the data contains.', :pick => :one, :required => :standard a_false 'no' a_true 'yes' q_schemaDocumentationUrl 'Where is documentation about your data vocabularies?', :discussion_topic => :schemaDocumentationUrl, :display_on_certificate => true, :text_as_statement => 'The vocabularies used by this data are documented at' dependency :rule => 'A' condition_A :q_vocabulary, '==', :a_true a_1 'Schema Documentation URL', :string, :input_type => :url, :placeholder => 'Schema Documentation URL', :requirement => ['standard_54'] label_standard_54 'You should <strong>document any vocabulary you use within your data</strong> so that people know how to interpret it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_54' dependency :rule => 'A and B' condition_A :q_vocabulary, '==', :a_true condition_B :q_schemaDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'} q_codelists 'Are there any codes used in this data?', :discussion_topic => :codelists, :help_text => 'If your data uses codes to refer to things like geographical areas, spending categories or diseases for example, these need to be explained to people.', :pick => :one, :required => :standard a_false 'no' a_true 'yes' q_codelistDocumentationUrl 'Where are any codes in your data documented?', :discussion_topic => :codelistDocumentationUrl, :display_on_certificate => true, :text_as_statement => 'The codes in this data are documented at' dependency :rule => 'A' condition_A :q_codelists, '==', :a_true a_1 'Codelist Documentation URL', :string, :input_type => :url, :placeholder => 'Codelist Documentation URL', :requirement => ['standard_55'] label_standard_55 'You should <strong>document the codes used within your data</strong> so that people know how to interpret them.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_55' dependency :rule => 'A and B' condition_A :q_codelists, '==', :a_true condition_B :q_codelistDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'} label_group_16 'Support', :help_text => 'how you communicate with people who use your data', :customer_renderer => '/partials/fieldset' q_contactUrl 'Where can people find out how to contact someone with questions about this data?', :discussion_topic => :contactUrl, :display_on_certificate => true, :text_as_statement => 'Find out how to contact someone about this data at', :help_text => 'Give a URL for a page that describes how people can contact someone if they have questions about the data.' a_1 'Contact Documentation', :string, :input_type => :url, :placeholder => 'Contact Documentation', :requirement => ['pilot_20'] label_pilot_20 'You should <strong>provide contact information for people to send questions</strong> about your data to.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_20' dependency :rule => 'A' condition_A :q_contactUrl, '==', {:string_value => '', :answer_reference => '1'} q_improvementsContact 'Where can people find out how to improve the way your data is published?', :discussion_topic => :improvementsContact, :display_on_certificate => true, :text_as_statement => 'Find out how to suggest improvements to publication at' a_1 'Improvement Suggestions URL', :string, :input_type => :url, :placeholder => 'Improvement Suggestions URL', :requirement => ['pilot_21'] label_pilot_21 'You should <strong>provide instructions about how suggest improvements</strong> to the way you publish data so you can discover what people need.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_21' dependency :rule => 'A' condition_A :q_improvementsContact, '==', {:string_value => '', :answer_reference => '1'} q_dataProtectionUrl 'Where can people find out how to contact someone with questions about privacy?', :discussion_topic => :dataProtectionUrl, :display_on_certificate => true, :text_as_statement => 'Find out where to send questions about privacy at' a_1 'Confidentiality Contact Documentation', :string, :input_type => :url, :placeholder => 'Confidentiality Contact Documentation', :requirement => ['pilot_22'] label_pilot_22 'You should <strong>provide contact information for people to send questions about privacy</strong> and disclosure of personal details to.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_22' dependency :rule => 'A' condition_A :q_dataProtectionUrl, '==', {:string_value => '', :answer_reference => '1'} q_socialMedia 'Do you use social media to connect with people who use your data?', :discussion_topic => :socialMedia, :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_56'] label_standard_56 'You should <strong>use social media to reach people who use your data</strong> and discover how your data is being used', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_56' dependency :rule => 'A' condition_A :q_socialMedia, '==', :a_false repeater 'Account' do dependency :rule => 'A' condition_A :q_socialMedia, '==', :a_true q_account 'Which social media accounts can people reach you on?', :discussion_topic => :account, :display_on_certificate => true, :text_as_statement => 'Contact the curator through these social media accounts', :help_text => 'Give URLs to your social media accounts, like your Twitter or Facebook profile page.', :required => :required dependency :rule => 'A' condition_A :q_socialMedia, '==', :a_true a_1 'Social Media URL', :string, :input_type => :url, :required => :required, :placeholder => 'Social Media URL' end q_forum 'Where should people discuss this dataset?', :discussion_topic => :forum, :display_on_certificate => true, :text_as_statement => 'Discuss this data at', :help_text => 'Give a URL to your forum or mailing list where people can talk about your data.' a_1 'Forum or Mailing List URL', :string, :input_type => :url, :placeholder => 'Forum or Mailing List URL', :requirement => ['standard_57'] label_standard_57 'You should <strong>tell people where they can discuss your data</strong> and support one another.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_57' dependency :rule => 'A' condition_A :q_forum, '==', {:string_value => '', :answer_reference => '1'} q_correctionReporting 'Where can people find out how to request corrections to your data?', :discussion_topic => :correctionReporting, :display_on_certificate => true, :text_as_statement => 'Find out how to request data corrections at', :help_text => 'Give a URL where people can report errors they spot in your data.' dependency :rule => 'A' condition_A :q_corrected, '==', :a_true a_1 'Correction Instructions URL', :string, :input_type => :url, :placeholder => 'Correction Instructions URL', :requirement => ['standard_58'] label_standard_58 'You should <strong>provide instructions about how people can report errors</strong> in your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_58' dependency :rule => 'A and B' condition_A :q_corrected, '==', :a_true condition_B :q_correctionReporting, '==', {:string_value => '', :answer_reference => '1'} q_correctionDiscovery 'Where can people find out how to get notifications of corrections to your data?', :discussion_topic => :correctionDiscovery, :display_on_certificate => true, :text_as_statement => 'Find out how to get notifications about data corrections at', :help_text => 'Give a URL where you describe how notifications about corrections are shared with people.' dependency :rule => 'A' condition_A :q_corrected, '==', :a_true a_1 'Correction Notification URL', :string, :input_type => :url, :placeholder => 'Correction Notification URL', :requirement => ['standard_59'] label_standard_59 'You should <strong>provide a mailing list or feed with updates</strong> that people can use to keep their copies of your data up-to-date.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_59' dependency :rule => 'A and B' condition_A :q_corrected, '==', :a_true condition_B :q_correctionDiscovery, '==', {:string_value => '', :answer_reference => '1'} q_engagementTeam 'Do you have anyone who actively builds a community around this data?', :discussion_topic => :engagementTeam, :help_text => 'A community engagement team will engage through social media, blogging, and arrange hackdays or competitions to encourage people to use the data.', :help_text_more_url => 'http://theodi.org/guide/engaging-reusers', :pick => :one a_false 'no' a_true 'yes', :requirement => ['exemplar_19'] label_exemplar_19 'You should <strong>build a community of people around your data</strong> to encourage wider use of your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_19' dependency :rule => 'A' condition_A :q_engagementTeam, '==', :a_false q_engagementTeamUrl 'Where is their home page?', :discussion_topic => :engagementTeamUrl, :display_on_certificate => true, :text_as_statement => 'Community engagement is done by', :required => :required dependency :rule => 'A' condition_A :q_engagementTeam, '==', :a_true a_1 'Community Engagement Team Home Page URL', :string, :input_type => :url, :placeholder => 'Community Engagement Team Home Page URL', :required => :required label_group_17 'Services', :help_text => 'how you give people access to tools they need to work with your data', :customer_renderer => '/partials/fieldset' q_libraries 'Where do you list tools to work with your data?', :discussion_topic => :libraries, :display_on_certificate => true, :text_as_statement => 'Tools to help use this data are listed at', :help_text => 'Give a URL that lists the tools you know or recommend people can use when they work with your data.' a_1 'Tool URL', :string, :input_type => :url, :placeholder => 'Tool URL', :requirement => ['exemplar_20'] label_exemplar_20 'You should <strong>provide a list of software libraries and other readily-available tools</strong> so that people can quickly get to work with your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_20' dependency :rule => 'A' condition_A :q_libraries, '==', {:string_value => '', :answer_reference => '1'} end end
istvan-antal/open-data-certificate
surveys/odc_questionnaire.LB.rb
Ruby
mit
140,400
#!/bin/bash FN="BSgenome.Sscrofa.UCSC.susScr3_1.4.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.9/data/annotation/src/contrib/BSgenome.Sscrofa.UCSC.susScr3_1.4.0.tar.gz" "https://bioarchive.galaxyproject.org/BSgenome.Sscrofa.UCSC.susScr3_1.4.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-bsgenome.sscrofa.ucsc.susscr3/bioconductor-bsgenome.sscrofa.ucsc.susscr3_1.4.0_src_all.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-bsgenome.sscrofa.ucsc.susscr3/bioconductor-bsgenome.sscrofa.ucsc.susscr3_1.4.0_src_all.tar.gz" ) MD5="0457ca52a81c9d7ceadad5830169e6cf" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
jerowe/bioconda-recipes
recipes/bioconductor-bsgenome.sscrofa.ucsc.susscr3/post-link.sh
Shell
mit
1,544
/*********************************** This is a our graphics core library, for all our displays. We'll be adapting all the existing libaries to use this core to make updating, support and upgrading easier! Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, check license.txt for more information All text above must be included in any redistribution ****************************************/ #include "Adafruit_GFX.h" #include "glcdfont.c" #include <avr/pgmspace.h> void Adafruit_GFX::constructor(int16_t w, int16_t h) { _width = WIDTH = w; _height = HEIGHT = h; rotation = 0; cursor_y = cursor_x = 0; textsize = 1; textcolor = textbgcolor = 0xFFFF; wrap = true; } // draw a circle outline void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, uint32_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; drawPixel(x0, y0+r, color); drawPixel(x0, y0-r, color); drawPixel(x0+r, y0, color); drawPixel(x0-r, y0, color); while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; drawPixel(x0 + x, y0 + y, color); drawPixel(x0 - x, y0 + y, color); drawPixel(x0 + x, y0 - y, color); drawPixel(x0 - x, y0 - y, color); drawPixel(x0 + y, y0 + x, color); drawPixel(x0 - y, y0 + x, color); drawPixel(x0 + y, y0 - x, color); drawPixel(x0 - y, y0 - x, color); } } void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint32_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4) { drawPixel(x0 + x, y0 + y, color); drawPixel(x0 + y, y0 + x, color); } if (cornername & 0x2) { drawPixel(x0 + x, y0 - y, color); drawPixel(x0 + y, y0 - x, color); } if (cornername & 0x8) { drawPixel(x0 - y, y0 + x, color); drawPixel(x0 - x, y0 + y, color); } if (cornername & 0x1) { drawPixel(x0 - y, y0 - x, color); drawPixel(x0 - x, y0 - y, color); } } } void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, uint32_t color) { drawFastVLine(x0, y0-r, 2*r+1, color); fillCircleHelper(x0, y0, r, 3, 0, color); } // used to do circles and roundrects! void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint32_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x1) { drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); } if (cornername & 0x2) { drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); } } } // bresenham's algorithm - thx wikpedia void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint32_t color) { int16_t steep = abs(y1 - y0) > abs(x1 - x0); if (steep) { swap(x0, y0); swap(x1, y1); } if (x0 > x1) { swap(x0, x1); swap(y0, y1); } int16_t dx, dy; dx = x1 - x0; dy = abs(y1 - y0); int16_t err = dx / 2; int16_t ystep; if (y0 < y1) { ystep = 1; } else { ystep = -1; } for (; x0<=x1; x0++) { if (steep) { drawPixel(y0, x0, color); } else { drawPixel(x0, y0, color); } err -= dy; if (err < 0) { y0 += ystep; err += dx; } } } // draw a rectangle void Adafruit_GFX::drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint32_t color) { drawFastHLine(x, y, w, color); drawFastHLine(x, y+h-1, w, color); drawFastVLine(x, y, h, color); drawFastVLine(x+w-1, y, h, color); } void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, int16_t h, uint32_t color) { // stupidest version - update in subclasses if desired! drawLine(x, y, x, y+h-1, color); } void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, int16_t w, uint32_t color) { // stupidest version - update in subclasses if desired! drawLine(x, y, x+w-1, y, color); } void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint32_t color) { // stupidest version - update in subclasses if desired! for (int16_t i=x; i<x+w; i++) { drawFastVLine(i, y, h, color); } } void Adafruit_GFX::fillScreen(uint32_t color) { fillRect(0, 0, _width, _height, color); } // draw a rounded rectangle! void Adafruit_GFX::drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint32_t color) { // smarter version drawFastHLine(x+r , y , w-2*r, color); // Top drawFastHLine(x+r , y+h-1, w-2*r, color); // Bottom drawFastVLine( x , y+r , h-2*r, color); // Left drawFastVLine( x+w-1, y+r , h-2*r, color); // Right // draw four corners drawCircleHelper(x+r , y+r , r, 1, color); drawCircleHelper(x+w-r-1, y+r , r, 2, color); drawCircleHelper(x+w-r-1, y+h-r-1, r, 4, color); drawCircleHelper(x+r , y+h-r-1, r, 8, color); } // fill a rounded rectangle! void Adafruit_GFX::fillRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint32_t color) { // smarter version fillRect(x+r, y, w-2*r, h, color); // draw four corners fillCircleHelper(x+w-r-1, y+r, r, 1, h-2*r-1, color); fillCircleHelper(x+r , y+r, r, 2, h-2*r-1, color); } // draw a triangle! void Adafruit_GFX::drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint32_t color) { drawLine(x0, y0, x1, y1, color); drawLine(x1, y1, x2, y2, color); drawLine(x2, y2, x0, y0, color); } // fill a triangle! void Adafruit_GFX::fillTriangle ( int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint32_t color) { int16_t a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if (y1 > y2) { swap(y2, y1); swap(x2, x1); } if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing a = b = x0; if(x1 < a) a = x1; else if(x1 > b) b = x1; if(x2 < a) a = x2; else if(x2 > b) b = x2; drawFastHLine(a, y0, b-a+1, color); return; } int16_t dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1, sa = 0, sb = 0; // For upper part of triangle, find scanline crossings for segments // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 // is included here (and second loop will be skipped, avoiding a /0 // error there), otherwise scanline y1 is skipped here and handled // in the second loop...which also avoids a /0 error here if y0=y1 // (flat-topped triangle). if(y1 == y2) last = y1; // Include y1 scanline else last = y1-1; // Skip it for(y=y0; y<=last; y++) { a = x0 + sa / dy01; b = x0 + sb / dy02; sa += dx01; sb += dx02; /* longhand: a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } // For lower part of triangle, find scanline crossings for segments // 0-2 and 1-2. This loop is skipped if y1=y2. sa = dx12 * (y - y1); sb = dx02 * (y - y0); for(; y<=y2; y++) { a = x1 + sa / dy12; b = x0 + sb / dy02; sa += dx12; sb += dx02; /* longhand: a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } } void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint32_t color) { for (int16_t j=0; j<h; j++) { for (int16_t i=0; i<w; i++ ) { if (pgm_read_byte(bitmap + i + (j/8)*w) & _BV(j%8)) { drawPixel(x+i, y+j, color); } } } } #if ARDUINO >= 100 size_t Adafruit_GFX::write(uint8_t c) { #else void Adafruit_GFX::write(uint8_t c) { #endif if (c == '\n') { cursor_y += textsize*8; cursor_x = 0; } else if (c == '\r') { // skip em } else { drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); cursor_x += textsize*6; if (wrap && (cursor_x > (_width - textsize*6))) { cursor_y += textsize*8; cursor_x = 0; } } #if ARDUINO >= 100 return 1; #endif } // draw a character void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, uint32_t color, uint32_t bg, uint8_t size) { if((x >= _width) || // Clip right (y >= _height) || // Clip bottom ((x + 5 * size - 1) < 0) || // Clip left ((y + 8 * size - 1) < 0)) // Clip top return; for (int8_t i=0; i<6; i++ ) { uint8_t line; if (i == 5) line = 0x0; else line = pgm_read_byte(font+(c*5)+i); for (int8_t j = 0; j<8; j++) { if (line & 0x1) { if (size == 1) // default size drawPixel(x+i, y+j, color); else { // big size fillRect(x+(i*size), y+(j*size), size, size, color); } } else if (bg != color) { if (size == 1) // default size drawPixel(x+i, y+j, bg); else { // big size fillRect(x+i*size, y+j*size, size, size, bg); } } line >>= 1; } } } void Adafruit_GFX::setCursor(int16_t x, int16_t y) { cursor_x = x; cursor_y = y; } void Adafruit_GFX::setTextSize(uint8_t s) { textsize = (s > 0) ? s : 1; } void Adafruit_GFX::setTextColor(uint32_t c) { textcolor = c; textbgcolor = c; // for 'transparent' background, we'll set the bg // to the same as fg instead of using a flag } void Adafruit_GFX::setTextColor(uint32_t c, uint32_t b) { textcolor = c; textbgcolor = b; } void Adafruit_GFX::setTextWrap(boolean w) { wrap = w; } uint8_t Adafruit_GFX::getRotation(void) { rotation %= 4; return rotation; } void Adafruit_GFX::setRotation(uint8_t x) { x %= 4; // cant be higher than 3 rotation = x; switch (x) { case 0: case 2: _width = WIDTH; _height = HEIGHT; break; case 1: case 3: _width = HEIGHT; _height = WIDTH; break; } } void Adafruit_GFX::invertDisplay(boolean i) { // do nothing, can be subclassed } // return the size of the display which depends on the rotation! int16_t Adafruit_GFX::width(void) { return _width; } int16_t Adafruit_GFX::height(void) { return _height; }
labfab/vitrines-io
src/bin/pixelcontroller-distribution-2.0.0/integration/ArduinoFw/stealthSpi/stealthSpiTeensy/Adafruit_GFX.cpp
C++
cc0-1.0
11,161
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.wemo.internal; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Extension of the default OSGi bundle activator * * @author Hans-Jörg Merk * @since 1.6.0 */ public final class WemoActivator implements BundleActivator { private static Logger logger = LoggerFactory.getLogger(WemoActivator.class); private static BundleContext context; /** * Called whenever the OSGi framework starts our bundle */ @Override public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Wemo binding has been started."); } /** * Called whenever the OSGi framework stops our bundle */ @Override public void stop(BundleContext bc) throws Exception { context = null; logger.debug("Wemo binding has been stopped."); } /** * Returns the bundle context of this bundle * * @return the bundle context */ public static BundleContext getContext() { return context; } }
computergeek1507/openhab
bundles/binding/org.openhab.binding.wemo/src/main/java/org/openhab/binding/wemo/internal/WemoActivator.java
Java
epl-1.0
1,514
/** * Copyright (c) 2010-2019 by the respective copyright holders. * * 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.action.xmpp.internal; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.commons.io.IOUtils; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ChatManager; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smackx.filetransfer.FileTransferManager; import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer; import org.jivesoftware.smackx.muc.MultiUserChat; import org.openhab.core.scriptengine.action.ActionDoc; import org.openhab.core.scriptengine.action.ParamDoc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class contains the methods that are made available in scripts and rules for XMPP. * * @author Kai Kreuzer * @since 1.3.0 */ public class XMPP { private static final Logger logger = LoggerFactory.getLogger(XMPP.class); // provide public static methods here /** * Sends a message to an XMPP user. * * @param to the XMPP address to send the message to * @param message the message to send * * @return <code>true</code>, if sending the message has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text = "Sends a message to an XMPP user.") static public boolean sendXMPP(@ParamDoc(name = "to") String to, @ParamDoc(name = "message") String message) { boolean success = false; try { XMPPConnection conn = XMPPConnect.getConnection(); ChatManager chatmanager = ChatManager.getInstanceFor(conn); Chat newChat = chatmanager.createChat(to, null); try { while (message.length() >= 2000) { newChat.sendMessage(message.substring(0, 2000)); message = message.substring(2000); } newChat.sendMessage(message); logger.debug("Sent message '{}' to '{}'.", message, to); success = true; } catch (XMPPException e) { logger.warn("Error Delivering block", e); } catch (NotConnectedException e) { logger.warn("Error Delivering block", e); } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; } /** * Sends a message with an attachment to an XMPP user. * * @param to the XMPP address to send the message to * @param message the message to send * @param attachmentUrl a URL string of which the content should be send to the user * * @return <code>true</code>, if sending the message has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text = "Sends a message with an attachment to an XMPP user.") static public boolean sendXMPP(@ParamDoc(name = "to") String to, @ParamDoc(name = "message") String message, @ParamDoc(name = "attachmentUrl") String attachmentUrl) { boolean success = false; try { XMPPConnection conn = XMPPConnect.getConnection(); if (attachmentUrl == null) { // send a normal message without an attachment ChatManager chatmanager = ChatManager.getInstanceFor(conn); Chat newChat = chatmanager.createChat(to, new MessageListener() { @Override public void processMessage(Chat chat, Message message) { logger.debug("Received message on XMPP: {}", message.getBody()); } }); try { newChat.sendMessage(message); logger.debug("Sent message '{}' to '{}'.", message, to); success = true; } catch (XMPPException e) { logger.error("Error sending message '{}'", message, e); } catch (NotConnectedException e) { logger.error("Error sending message '{}'", message, e); } } else { // Create the file transfer manager FileTransferManager manager = new FileTransferManager(conn); // Create the outgoing file transfer OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(to); InputStream is = null; try { URL url = new URL(attachmentUrl); // Send the file is = url.openStream(); OutgoingFileTransfer.setResponseTimeout(10000); transfer.sendStream(is, url.getFile(), is.available(), message); logger.debug("Sent message '{}' with attachment '{}' to '{}'.", (Object[]) new String[] { message, attachmentUrl, to }); success = true; } catch (IOException e) { logger.error("Could not open url '{}' for sending it via XMPP", attachmentUrl, e); } finally { IOUtils.closeQuietly(is); } } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; } /** * Sends a message to an XMPP multi user chat. * * @param message the message to send * * @return <code>true</code>, if sending the message has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text = "Sends a message to an XMPP multi user chat.") static public boolean chatXMPP(@ParamDoc(name = "message") String message) { boolean success = false; try { MultiUserChat chat = XMPPConnect.getChat(); try { while (message.length() >= 2000) { chat.sendMessage(message.substring(0, 2000)); message = message.substring(2000); } chat.sendMessage(message); logger.debug("Sent message '{}' to multi user chat.", message); success = true; } catch (XMPPException e) { logger.warn("Error Delivering block", e); } catch (NotConnectedException e) { logger.warn("Error Delivering block", e); } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; } }
idserda/openhab
bundles/action/org.openhab.action.xmpp/src/main/java/org/openhab/action/xmpp/internal/XMPP.java
Java
epl-1.0
7,243
/* * VirtioBus * * Copyright (C) 2012 : GreenSocs Ltd * http://www.greensocs.com/ , email: info@greensocs.com * * Developed by : * Frederic Konrad <fred.konrad@greensocs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. * */ #include "hw/hw.h" #include "qemu/error-report.h" #include "hw/qdev.h" #include "hw/virtio/virtio-bus.h" #include "hw/virtio/virtio.h" /* #define DEBUG_VIRTIO_BUS */ #ifdef DEBUG_VIRTIO_BUS #define DPRINTF(fmt, ...) \ do { printf("virtio_bus: " fmt , ## __VA_ARGS__); } while (0) #else #define DPRINTF(fmt, ...) do { } while (0) #endif /* A VirtIODevice is being plugged */ void virtio_bus_device_plugged(VirtIODevice *vdev, Error **errp) { DeviceState *qdev = DEVICE(vdev); BusState *qbus = BUS(qdev_get_parent_bus(qdev)); VirtioBusState *bus = VIRTIO_BUS(qbus); VirtioBusClass *klass = VIRTIO_BUS_GET_CLASS(bus); VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev); DPRINTF("%s: plug device.\n", qbus->name); if (klass->device_plugged != NULL) { klass->device_plugged(qbus->parent, errp); } /* Get the features of the plugged device. */ assert(vdc->get_features != NULL); vdev->host_features = vdc->get_features(vdev, vdev->host_features, errp); } /* Reset the virtio_bus */ void virtio_bus_reset(VirtioBusState *bus) { VirtIODevice *vdev = virtio_bus_get_device(bus); DPRINTF("%s: reset device.\n", BUS(bus)->name); if (vdev != NULL) { virtio_reset(vdev); } } /* A VirtIODevice is being unplugged */ void virtio_bus_device_unplugged(VirtIODevice *vdev) { DeviceState *qdev = DEVICE(vdev); BusState *qbus = BUS(qdev_get_parent_bus(qdev)); VirtioBusClass *klass = VIRTIO_BUS_GET_CLASS(qbus); DPRINTF("%s: remove device.\n", qbus->name); if (vdev != NULL) { if (klass->device_unplugged != NULL) { klass->device_unplugged(qbus->parent); } } } /* Get the device id of the plugged device. */ uint16_t virtio_bus_get_vdev_id(VirtioBusState *bus) { VirtIODevice *vdev = virtio_bus_get_device(bus); assert(vdev != NULL); return vdev->device_id; } /* Get the config_len field of the plugged device. */ size_t virtio_bus_get_vdev_config_len(VirtioBusState *bus) { VirtIODevice *vdev = virtio_bus_get_device(bus); assert(vdev != NULL); return vdev->config_len; } /* Get bad features of the plugged device. */ uint32_t virtio_bus_get_vdev_bad_features(VirtioBusState *bus) { VirtIODevice *vdev = virtio_bus_get_device(bus); VirtioDeviceClass *k; assert(vdev != NULL); k = VIRTIO_DEVICE_GET_CLASS(vdev); if (k->bad_features != NULL) { return k->bad_features(vdev); } else { return 0; } } /* Get config of the plugged device. */ void virtio_bus_get_vdev_config(VirtioBusState *bus, uint8_t *config) { VirtIODevice *vdev = virtio_bus_get_device(bus); VirtioDeviceClass *k; assert(vdev != NULL); k = VIRTIO_DEVICE_GET_CLASS(vdev); if (k->get_config != NULL) { k->get_config(vdev, config); } } /* Set config of the plugged device. */ void virtio_bus_set_vdev_config(VirtioBusState *bus, uint8_t *config) { VirtIODevice *vdev = virtio_bus_get_device(bus); VirtioDeviceClass *k; assert(vdev != NULL); k = VIRTIO_DEVICE_GET_CLASS(vdev); if (k->set_config != NULL) { k->set_config(vdev, config); } } static char *virtio_bus_get_dev_path(DeviceState *dev) { BusState *bus = qdev_get_parent_bus(dev); DeviceState *proxy = DEVICE(bus->parent); return qdev_get_dev_path(proxy); } static char *virtio_bus_get_fw_dev_path(DeviceState *dev) { return NULL; } static void virtio_bus_class_init(ObjectClass *klass, void *data) { BusClass *bus_class = BUS_CLASS(klass); bus_class->get_dev_path = virtio_bus_get_dev_path; bus_class->get_fw_dev_path = virtio_bus_get_fw_dev_path; } static const TypeInfo virtio_bus_info = { .name = TYPE_VIRTIO_BUS, .parent = TYPE_BUS, .instance_size = sizeof(VirtioBusState), .abstract = true, .class_size = sizeof(VirtioBusClass), .class_init = virtio_bus_class_init }; static void virtio_register_types(void) { type_register_static(&virtio_bus_info); } type_init(virtio_register_types)
BCLinux/qga-bc
qemu-master/hw/virtio/virtio-bus.c
C
gpl-2.0
4,926
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser; import org.gradle.internal.component.model.DefaultIvyArtifactName; import org.gradle.internal.component.model.IvyArtifactName; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; class BuildableIvyArtifact { private final IvyArtifactName ivyArtifactName; private final Set<String> configurations = new LinkedHashSet<String>(); public BuildableIvyArtifact(String name, String type, String ext, Map<String, String> extraAttributes) { this.ivyArtifactName = new DefaultIvyArtifactName(name, type, ext, extraAttributes); } public BuildableIvyArtifact addConfiguration(String confName) { configurations.add(confName); return this; } public IvyArtifactName getArtifact() { return ivyArtifactName; } public Set<String> getConfigurations() { return configurations; } }
cams7/gradle-samples
plugin/dependency-management/src/main/java/org/gradle/api/internal/artifacts/ivyservice/ivyresolve/parser/BuildableIvyArtifact.java
Java
gpl-2.0
1,562
GCC_VERSION := $(shell $(CONFIG_SHELL) $(PWD)/scripts/gcc-version.sh $(CROSS_COMPILE)gcc) ccflags-y += -Idrivers/media/video/msm/io ccflags-y += -Idrivers/media/video/msm/vfe obj-$(CONFIG_MSM_CAMERA) += io/ ifeq ($(CONFIG_MSM_CAMERA_V4L2),y) EXTRA_CFLAGS += -Idrivers/media/video/msm/csi EXTRA_CFLAGS += -Idrivers/media/video/msm/io EXTRA_CFLAGS += -Idrivers/media/video/msm/eeprom EXTRA_CFLAGS += -Idrivers/media/video/msm/sensors EXTRA_CFLAGS += -Idrivers/media/video/msm/actuators obj-$(CONFIG_MSM_CAMERA) += msm_isp.o msm.o msm_mem.o msm_mctl.o msm_mctl_buf.o msm_mctl_pp.o obj-$(CONFIG_MSM_CAMERA) += io/ eeprom/ sensors/ actuators/ csi/ obj-$(CONFIG_MSM_CAMERA) += msm_gesture.o else obj-$(CONFIG_MSM_CAMERA) += msm_camera.o endif obj-$(CONFIG_MSM_CAMERA) += vfe/ obj-$(CONFIG_MSM_CAMERA) += msm_axi_qos.o gemini/ obj-$(CONFIG_MSM_CAMERA_FLASH) += flash.o ifeq ($(CONFIG_MSM_CAMERA_V4L2),y) obj-$(CONFIG_ARCH_MSM8X60) += msm_vpe.o obj-$(CONFIG_ARCH_MSM7X30) += msm_vpe.o msm_axi_qos.o else obj-$(CONFIG_ARCH_MSM8X60) += msm_vpe1.o obj-$(CONFIG_ARCH_MSM7X30) += msm_vpe1.o endif obj-$(CONFIG_ARCH_MSM8960) += msm_vpe.o obj-$(CONFIG_MT9T013) += mt9t013.o mt9t013_reg.o obj-$(CONFIG_SN12M0PZ) += sn12m0pz.o sn12m0pz_reg.o obj-$(CONFIG_MT9P012) += mt9p012_reg.o obj-$(CONFIG_MSM_CAMERA_AF_FOXCONN) += mt9p012_fox.o obj-$(CONFIG_MSM_CAMERA_AF_BAM) += mt9p012_bam.o obj-$(CONFIG_MT9P012_KM) += mt9p012_km.o mt9p012_km_reg.o obj-$(CONFIG_S5K3E2FX) += s5k3e2fx.o #FIXME: Merge the two ifeq causes VX6953 preview not coming up. ifneq ($(CONFIG_MSM_CAMERA_V4L2),y) obj-$(CONFIG_VX6953) += vx6953.o vx6953_reg.o obj-$(CONFIG_IMX074) += imx074.o imx074_reg.o obj-$(CONFIG_MT9E013) += mt9e013.o mt9e013_reg.o obj-$(CONFIG_WEBCAM_OV9726) += ov9726.o ov9726_reg.o obj-$(CONFIG_OV5647) += ov5647.o ov5647_reg.o obj-$(CONFIG_S5K4E1) += s5k4e1.o s5k4e1_reg.o obj-$(CONFIG_WEBCAM_OV7692) += ov7692.o obj-$(CONFIG_WEBCAM_OV7692_QRD) += ov7692_qrd.o endif obj-$(CONFIG_QS_S5K4E1) += qs_s5k4e1.o qs_s5k4e1_reg.o obj-$(CONFIG_VB6801) += vb6801.o obj-$(CONFIG_IMX072) += imx072.o imx072_reg.o obj-$(CONFIG_OV5640) += ov5640.o obj-$(CONFIG_MT9D112) += mt9d112.o mt9d112_reg.o obj-$(CONFIG_MT9D113) += mt9d113.o mt9d113_reg.o obj-$(CONFIG_FB_MSM_WRITEBACK_MSM_PANEL) += wfd/ obj-$(CONFIG_MSM_V4L2_VIDEO_OVERLAY_DEVICE) += msm_v4l2_video.o
Dearms/android_kernel_xiaomi_msm8960
drivers/media/video/msm/Makefile
Makefile
gpl-2.0
2,368
(function($) { Drupal.plupload = Drupal.plupload || {}; /** * Attaches the Plupload behavior to each FileField Sources Plupload form element. */ Drupal.behaviors.filefield_sources_plupload = { attach: function (context, settings) { $(".filefield-source-plupload .plupload-element", context).once('ffs-plupload-init', function () { // Merge the default settings and the element settings to get a full // settings object to pass to the Plupload library for this element. var id = $(this).attr('id'); var defaultSettings = settings.plupload['_default'] ? settings.plupload['_default'] : {}; var elementSettings = (id && settings.plupload[id]) ? settings.plupload[id] : {}; var pluploadSettings = $.extend({}, defaultSettings, elementSettings); // Initialize Plupload for this element. $(this).pluploadQueue(pluploadSettings); // Hide upload button. We will do this using uploader.start() $(this).find('.plupload_start').hide(); // While we are at it, hide the redundant file validation help $(this).closest('.filefield-source-plupload').find('div.description').hide(); // Add button. var add_button = $(this).find('.plupload_button.plupload_add'); // Intercept the submit to start uploading and ensure all files are done // uploading before triggering the ajax form update. var $submit = $(this).closest('.filefield-source-plupload').find('.form-submit'); var uploader_element = $(this).closest('.filefield-source-plupload').find('.plupload-element'); var uploader = uploader_element.pluploadQueue(); // Refresh for IE8 uploader.refresh(); uploader.bind('QueueChanged', function() { // If cardinality is NOT unlimited. if (pluploadSettings.cardinality > 0) { // Remove files exceeding the cardinality setting. if (uploader.files.length >= pluploadSettings.cardinality) { var i = 0; for (i=0;i<uploader.files.length;i++) { if (i >= pluploadSettings.cardinality) { uploader.removeFile(uploader.files[i]); } } add_button.hide(); } else { add_button.show(); } } }); $submit.bind('click', function(e) { e.preventDefault(); uploader.bind('StateChanged', function() { if (uploader.total.uploaded == uploader.files.length) { // Custom ajax trigger $submit.trigger('pud_update'); } }); if (uploader.files.length > 0) { $submit.val(Drupal.t('Uploading...')); uploader.start(); } return false; }); }); } } })(jQuery);
geoffreygevalt/ywp
sites/all/modules/filefield_sources_plupload/js/plupload.js
JavaScript
gpl-2.0
2,845
#!/bin/sh TEST_SCRIPT=./VMake/executableTester.sh until test -r ${TEST_SCRIPT} ; do TEST_SCRIPT=../${TEST_SCRIPT} done . ${TEST_SCRIPT} runAndHandleSystemTestStdLocations "testShape testSuperellipsoid.xml --dim=2" "$0" "$@"
kelchuan/snac_thesis
StGermain/Discretisation/Shape/tests/testSuperellipsoid2D.0of1.sh
Shell
gpl-2.0
234
#ifndef CAMIF_REG_CONFIG_H_ #define CAMIF_REG_CONFIG_H_ /* If you wanna use the reg_val configuration file on board, set this value to 1 */ //#define IS_USE_REGISTER_CONFIGURE_FILE_LSI 0 #if (IS_USE_REGISTER_CONFIGURE_FILE_LSI) #if 0 static int s5ka3dfx_make_table(void); enum { REG_INIT_QCIF_SECTION, REG_INIT_CIF_SECTION, REG_INIT_QVGA_SECTION, REG_INIT_VGA_SECTION, REG_INIT_QCIF_VT_SECTION, REG_INIT_CIF_VT_SECTION, REG_INIT_QVGA_VT_SECTION, REG_INIT_VGA_VT_SECTION, REG_WB_AUTO_SECTION, REG_WB_DAYLIGHT_SECTION, REG_WB_CLOUDY_SECTION, REG_WB_INCANDESCENT_SECTION, REG_WB_FLUORESCENT_SECTION, REG_EV_SECTION, REG_EV_VT_SECTION, REG_CONTRAST_LEVEL_M5_SECTION, REG_CONTRAST_LEVEL_M4_SECTION, REG_CONTRAST_LEVEL_M3_SECTION, REG_CONTRAST_LEVEL_M2_SECTION, REG_CONTRAST_LEVEL_M1_SECTION, REG_CONTRAST_DEFAULT_SECTION, REG_CONTRAST_LEVEL_P1_SECTION, REG_CONTRAST_LEVEL_P2_SECTION, REG_CONTRAST_LEVEL_P3_SECTION, REG_CONTRAST_LEVEL_P4_SECTION, REG_CONTRAST_LEVEL_P5_SECTION, REG_EFFECT_NONE_SECTION, REG_EFFECT_GRAY_SECTION, REG_EFFECT_RED_SECTION, REG_EFFECT_SEPIA_SECTION, REG_EFFECT_GREEN_SECTION, REG_EFFECT_AQUA_SECTION, REG_EFFECT_NEGATIVE_SECTION, REG_FLIP_NONE_SECTION, REG_FLIP_WATER_SECTION, REG_FLIP_MIRROR_SECTION, REG_FLIP_WATER_MIRROR_SECTION, REG_PRETTY_NONE_SECTION, REG_PRETTY_LEVEL1_SECTION, REG_PRETTY_LEVEL2_SECTION, REG_PRETTY_LEVEL3_SECTION, REG_PRETTY_VT_NONE_SECTION, REG_PRETTY_VT_LEVEL1_SECTION, REG_PRETTY_VT_LEVEL2_SECTION, REG_PRETTY_VT_LEVEL3_SECTION, REG_7FPS_SECTION, REG_10FPS_SECTION, REG_15FPS_SECTION, REG_SELF_CAPTURE_SECTION, }; /****************************************************************************/ /* sensor */ /*--------------------------------------------------------------------------*/ #define CAMIF_CONFIGURE_FILE_LSI "/mnt/sdcard/external_sd/reg_val_s5ka3dfx.txt" #define CAMIF_SET_SENSOR_QCIF_INIT "[[CAMIF_INIT_QCIF_INIT]]" #define CAMIF_SET_SENSOR_CIF_INIT "[[CAMIF_INIT_CIF_INIT]]" #define CAMIF_SET_SENSOR_QVGA_INIT "[[CAMIF_INIT_QVGA_INIT]]" #define CAMIF_SET_SENSOR_VGA_INIT "[[CAMIF_INIT_VGA_INIT]]" #define CAMIF_SET_SENSOR_QCIF_VT_INIT "[[CAMIF_INIT_QCIF_VT_INIT]]" #define CAMIF_SET_SENSOR_CIF_VT_INIT "[[CAMIF_INIT_CIF_VT_INIT]]" #define CAMIF_SET_SENSOR_QVGA_VT_INIT "[[CAMIF_INIT_QVGA_VT_INIT]]" #define CAMIF_SET_SENSOR_VGA_VT_INIT "[[CAMIF_INIT_VGA_VT_INIT]]" #define CAMIF_SET_SENSOR_WB_AUTO "[[CAMIF_WB_AUTO]]" #define CAMIF_SET_SENSOR_WB_DAYLIGHT "[[CAMIF_WB_DAYLIGHT]]" #define CAMIF_SET_SENSOR_WB_CLOUDY "[[CAMIF_WB_CLOUDY]]" #define CAMIF_SET_SENSOR_WB_INCANDESCENT "[[CAMIF_WB_INCANDESCENT]]" #define CAMIF_SET_SENSOR_WB_FLUORESCENT "[[CAMIF_WB_FLUORESCENT]]" #define CAMIF_SET_SENSOR_EV "[[CAMIF_EV]]" #define CAMIF_SET_SENSOR_EV_VT "[[CAMIF_EV_VT]]" #define CAMIF_SET_SENSOR_LEVEL_M5_CONTRAST "[[CAMIF_LEVEL_M5_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_M4_CONTRAST "[[CAMIF_LEVEL_M4_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_M3_CONTRAST "[[CAMIF_LEVEL_M3_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_M2_CONTRAST "[[CAMIF_LEVEL_M2_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_M1_CONTRAST "[[CAMIF_LEVEL_M1_CONTRAST]]" #define CAMIF_SET_SENSOR_DEFAULT_CONTRAST "[[CAMIF_DEFAULT_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_P1_CONTRAST "[[CAMIF_LEVEL_P1_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_P2_CONTRAST "[[CAMIF_LEVEL_P2_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_P3_CONTRAST "[[CAMIF_LEVEL_P3_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_P4_CONTRAST "[[CAMIF_LEVEL_P4_CONTRAST]]" #define CAMIF_SET_SENSOR_LEVEL_P5_CONTRAST "[[CAMIF_LEVEL_P5_CONTRAST]]" #define CAMIF_SET_SENSOR_EFFECT_NONE "[[CAMIF_EFFECT_NONE]]" #define CAMIF_SET_SENSOR_EFFECT_GRAY "[[CAMIF_EFFECT_GRAY]]" #define CAMIF_SET_SENSOR_EFFECT_RED "[[CAMIF_EFFECT_RED]]" #define CAMIF_SET_SENSOR_EFFECT_SEPIA "[[CAMIF_EFFECT_SEPIA]]" #define CAMIF_SET_SENSOR_EFFECT_GREEN "[[CAMIF_EFFECT_GREEN]]" #define CAMIF_SET_SENSOR_EFFECT_AQUA "[[CAMIF_EFFECT_AQUA]]" #define CAMIF_SET_SENSOR_EFFECT_NEGATIVE "[[CAMIF_EFFECT_NEGATIVE]]" #define CAMIF_SET_SENSOR_FLIP_NONE "[[CAMIF_FLIP_NONE]]" #define CAMIF_SET_SENSOR_FLIP_WATER "[[CAMIF_FLIP_WATER]]" #define CAMIF_SET_SENSOR_FLIP_MIRROR "[[CAMIF_FLIP_MIRROR]]" #define CAMIF_SET_SENSOR_FLIP_WATER_MIRROR "[[CAMIF_FLIP_WATER_MIRROR]]" #define CAMIF_SET_SENSOR_PRETTY_NONE "[[CAMIF_FLIP_PRETTY_NONE]]" #define CAMIF_SET_SENSOR_PRETTY_LEVEL1 "[[CAMIF_FLIP_PRETTY_LEVEL1]]" #define CAMIF_SET_SENSOR_PRETTY_LEVEL2 "[[CAMIF_FLIP_PRETTY_LEVEL2]]" #define CAMIF_SET_SENSOR_PRETTY_LEVEL3 "[[CAMIF_FLIP_PRETTY_LEVEL3]]" #define CAMIF_SET_SENSOR_PRETTY_VT_NONE "[[CAMIF_FLIP_PRETTY_VT_NONE]]" #define CAMIF_SET_SENSOR_PRETTY_VT_LEVEL1 "[[CAMIF_FLIP_PRETTY_VT_LEVEL1]]" #define CAMIF_SET_SENSOR_PRETTY_VT_LEVEL2 "[[CAMIF_FLIP_PRETTY_VT_LEVEL2]]" #define CAMIF_SET_SENSOR_PRETTY_VT_LEVEL3 "[[CAMIF_FLIP_PRETTY_VT_LEVEL3]]" #define CAMIF_SET_SENSOR_FPS7 "[[CAMIF_INIT_FPS7]]" #define CAMIF_SET_SENSOR_FPS10 "[[CAMIF_INIT_FPS10]]" #define CAMIF_SET_SENSOR_FPS15 "[[CAMIF_INIT_FPS15]]" #define CAMIF_SET_SENSOR_SELF_CAPTURE "[[CAMIF_SELF_CAPTURE]]" /* Section Entry Num */ #define CAMIF_SECTION_INIT_QCIF_MAX 1200 #define CAMIF_SECTION_INIT_CIF_MAX 1200 #define CAMIF_SECTION_INIT_QVGA_MAX 1200 #define CAMIF_SECTION_INIT_VGA_MAX 1200 #define CAMIF_SECTION_INIT_QCIF_VT_MAX 1200 #define CAMIF_SECTION_INIT_CIF_VT_MAX 1200 #define CAMIF_SECTION_INIT_QVGA_VT_MAX 1200 #define CAMIF_SECTION_INIT_VGA_VT_MAX 1200 #define CAMIF_SECTION_WB_AUTO_MAX 50 #define CAMIF_SECTION_WB_DAYLIGHT_MAX 50 #define CAMIF_SECTION_WB_CLOUDY_MAX 50 #define CAMIF_SECTION_WB_INCANDESCENT_MAX 50 #define CAMIF_SECTION_WB_FLUORESCENT_MAX 50 #define CAMIF_SECTION_EV_MAX 50 #define CAMIF_SECTION_EV_VT_MAX 50 #define CAMIF_SECTION_CONTRAST_LEVEL_M5_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_M4_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_M3_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_M2_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_M1_MAX 500 #define CAMIF_SECTION_CONTRAST_DEFAULT_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_P1_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_P2_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_P3_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_P4_MAX 500 #define CAMIF_SECTION_CONTRAST_LEVEL_P5_MAX 500 #define CAMIF_SECTION_EFFECT_NONE_MAX 50 #define CAMIF_SECTION_EFFECT_GRAY_MAX 50 #define CAMIF_SECTION_EFFECT_RED_MAX 50 #define CAMIF_SECTION_EFFECT_SEPIA_MAX 50 #define CAMIF_SECTION_EFFECT_GREEN_MAX 50 #define CAMIF_SECTION_EFFECT_AQUA_MAX 50 #define CAMIF_SECTION_EFFECT_NEGATIVE_MAX 50 #define CAMIF_SECTION_FLIP_NONE_MAX 50 #define CAMIF_SECTION_FLIP_WATER_MAX 50 #define CAMIF_SECTION_FLIP_MIRROR_MAX 50 #define CAMIF_SECTION_FLIP_WATER_MIRROR_MAX 50 #define CAMIF_SECTION_PRETTY_NONE_MAX 500 #define CAMIF_SECTION_PRETTY_LEVEL1_MAX 500 #define CAMIF_SECTION_PRETTY_LEVEL2_MAX 500 #define CAMIF_SECTION_PRETTY_LEVEL3_MAX 500 #define CAMIF_SECTION_PRETTY_VT_NONE_MAX 500 #define CAMIF_SECTION_PRETTY_VT_LEVEL1_MAX 500 #define CAMIF_SECTION_PRETTY_VT_LEVEL2_MAX 500 #define CAMIF_SECTION_PRETTY_VT_LEVEL3_MAX 500 #define CAMIF_SECTION_7FPS_MAX 500 #define CAMIF_SECTION_10FPS_MAX 500 #define CAMIF_SECTION_15FPS_MAX 500 #define CAMIF_SECTION_SELF_CAPTURE_MAX 1200 /* Section Table */ u32 reg_init_qcif_table [CAMIF_SECTION_INIT_QCIF_MAX]; u32 reg_init_cif_table [CAMIF_SECTION_INIT_CIF_MAX]; u32 reg_init_qvga_table [CAMIF_SECTION_INIT_QVGA_MAX]; u32 reg_init_vga_table [CAMIF_SECTION_INIT_VGA_MAX]; u32 reg_init_qcif_vt_table [CAMIF_SECTION_INIT_QCIF_VT_MAX]; u32 reg_init_cif_vt_table [CAMIF_SECTION_INIT_CIF_VT_MAX]; u32 reg_init_qvga_vt_table [CAMIF_SECTION_INIT_QVGA_VT_MAX]; u32 reg_init_vga_vt_table [CAMIF_SECTION_INIT_VGA_VT_MAX]; u32 reg_wb_auto_table [CAMIF_SECTION_WB_AUTO_MAX]; u32 reg_wb_daylight_table [CAMIF_SECTION_WB_DAYLIGHT_MAX]; u32 reg_wb_cloudy_table [CAMIF_SECTION_WB_CLOUDY_MAX]; u32 reg_wb_incandescent_table [CAMIF_SECTION_WB_INCANDESCENT_MAX]; u32 reg_wb_fluorescent_table [CAMIF_SECTION_WB_FLUORESCENT_MAX]; u32 reg_ev_table [CAMIF_SECTION_EV_MAX]; u32 reg_ev_vt_table [CAMIF_SECTION_EV_VT_MAX]; u32 reg_contrast_level_m5_table [CAMIF_SECTION_CONTRAST_LEVEL_M5_MAX]; u32 reg_contrast_level_m4_table [CAMIF_SECTION_CONTRAST_LEVEL_M4_MAX]; u32 reg_contrast_level_m3_table [CAMIF_SECTION_CONTRAST_LEVEL_M3_MAX]; u32 reg_contrast_level_m2_table [CAMIF_SECTION_CONTRAST_LEVEL_M2_MAX]; u32 reg_contrast_level_m1_table [CAMIF_SECTION_CONTRAST_LEVEL_M1_MAX]; u32 reg_contrast_level_default_table [CAMIF_SECTION_CONTRAST_DEFAULT_MAX]; u32 reg_contrast_level_p1_table [CAMIF_SECTION_CONTRAST_LEVEL_P1_MAX]; u32 reg_contrast_level_p2_table [CAMIF_SECTION_CONTRAST_LEVEL_P2_MAX]; u32 reg_contrast_level_p3_table [CAMIF_SECTION_CONTRAST_LEVEL_P3_MAX]; u32 reg_contrast_level_p4_table [CAMIF_SECTION_CONTRAST_LEVEL_P4_MAX]; u32 reg_contrast_level_p5_table [CAMIF_SECTION_CONTRAST_LEVEL_P5_MAX]; u32 reg_effect_none_table [CAMIF_SECTION_EFFECT_NONE_MAX]; u32 reg_effect_gray_table [CAMIF_SECTION_EFFECT_GRAY_MAX]; u32 reg_effect_red_table [CAMIF_SECTION_EFFECT_RED_MAX]; u32 reg_effect_sepia_table [CAMIF_SECTION_EFFECT_SEPIA_MAX]; u32 reg_effect_green_table [CAMIF_SECTION_EFFECT_GREEN_MAX]; u32 reg_effect_aqua_table [CAMIF_SECTION_EFFECT_AQUA_MAX]; u32 reg_effect_negative_table [CAMIF_SECTION_EFFECT_NEGATIVE_MAX]; u32 reg_flip_none_table [CAMIF_SECTION_FLIP_NONE_MAX]; u32 reg_flip_water_table [CAMIF_SECTION_FLIP_WATER_MAX]; u32 reg_flip_mirror_table [CAMIF_SECTION_FLIP_MIRROR_MAX]; u32 reg_flip_water_mirror_table [CAMIF_SECTION_FLIP_WATER_MIRROR_MAX]; u32 reg_pretty_none_table [CAMIF_SECTION_PRETTY_NONE_MAX]; u32 reg_pretty_level1_table [CAMIF_SECTION_PRETTY_LEVEL1_MAX]; u32 reg_pretty_level2_table [CAMIF_SECTION_PRETTY_LEVEL2_MAX]; u32 reg_pretty_level3_table [CAMIF_SECTION_PRETTY_LEVEL3_MAX]; u32 reg_pretty_vt_none_table [CAMIF_SECTION_PRETTY_VT_NONE_MAX]; u32 reg_pretty_vt_level1_table [CAMIF_SECTION_PRETTY_VT_LEVEL1_MAX]; u32 reg_pretty_vt_level2_table [CAMIF_SECTION_PRETTY_VT_LEVEL2_MAX]; u32 reg_pretty_vt_level3_table [CAMIF_SECTION_PRETTY_VT_LEVEL3_MAX]; u32 reg_7fps_table [CAMIF_SECTION_7FPS_MAX]; u32 reg_10fps_table [CAMIF_SECTION_10FPS_MAX]; u32 reg_15fps_table [CAMIF_SECTION_15FPS_MAX]; u32 reg_self_capture_table [CAMIF_SECTION_SELF_CAPTURE_MAX]; #endif #else #if 0 /************** Init Setting ******************/ /* Modified to SEHF Variable */ static const u32 reg_init_qcif_table[] = { 0xef02, //Analog setting 0x13a0, //Analog setting 0x2353, //Analog setting 0x2624, //Analog setting 0x2c05, //Analog setting 0x0500, //Analog setting 0x0350, //Analog setting 0x240a, //Analog setting 0x0b82, //Analog setting 0x1eb7, //Analog setting 0x5605, //Analog setting 0x2896, //Analog setting 0x673c, //Analog setting 0x4b5c, //Analog setting 0xef01, 0x70c3, //Clock delay 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max 0x620c, //PAL shutter Max 0x6301, //NT Vblank 0x64E7, 0x6501, //NT Hblank 0x66e7, 0x6d65, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f5d, //Dgain Max 0x4800, //NT Hblank 0x499E, 0x4c00, //PAL Hblank 0x4d9E, 0xef03, 0x0087, //AEAWB On 50Hz Mode 0x2b41, //Auto e-shutter enable 0x3100, //Brightness NH 0x3210, //Brightness LL 0x3380, //Contrast H 0x3479, //Contrast L 0x3630, //Saturation H 0x3730, //Saturation L 0x6a00, //BPR Start Position 0x7b05, //BPR 0x3805, //BPR 0x3903, //BPR 0x2d08, //NR 0x2e2c, //NR 0x2f30, //NR 0x30ff, //NR 0x7c06, //NR 0x7d2a, //NR 0x7e0c, //NR 0x7f2a, //NR 0x2802, //Sharpness 0x297f, //Sharpness 0x2a00, //Sharpness 0x1300, //AWB Outdoor Cintr limit 0x14a0, 0x1943, 0x1a6a, //Outdoor R gain Max 0x1b5f, //Outdoor R gain Min 0x1c61, //Outdoor B gain Max 0x1d4b, //Outdoor B gain Min 0x1e6a, //Indoor R gain Max 0x1f46, //Indoor R gain Min 0x2080, //7a Indoor B gain Max 0x2150, //Indoor B gain Min 0x3a13, //AWB speed AWB threshold 0x3b3e, //AWB Skip Bright 0x3c00, //AWB Skip Gain 0x3d18, //AWB Skip Avg 0x2380, //AWB Window Select 0x150b, //AWB Cnt 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order 0xdd03, //X shade on 0x2310, //GrGb 0x2410, //GrGb 0x2510, //GrGb 0x2718, //GrGb 0x2960, //GrGb 0x2a22, //GrGb 0x2f01, //Intp Coef Sharpness 0x3601, //Shading on 0x37e1, 0x38c7, 0x39af, 0x3a01, 0x3b04, 0x3c01, 0x3d31, 0xb902, //Sharpness on 0xbbb0, //HPF for sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness core 0xc188, 0xc811, //YC delay 0xeb81, //ECS on 0xed05, //ECS threshold 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, //Hue 0x7810, 0xef00, //AWB map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //Y level for AWB 0xaf10, //Y level for AWB 0xef00, 0x425D, //R gain start 0x4460, //B gain start 0x5700, //AE min skip 0xef03, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x0463, //AGC max Lowlight 0x061c, //AGC mac Highlight 0x0701, //AE window A weight 0x0801, //AE window B weight 0x0b01, //Cintc max high 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed 0x6917, //AE row flag 0xef00, //AE window 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61b1, 0x6201, 0x63be, 0x6400, 0x6581, 0x6601, 0x6761, 0xef00, //flicker setting 0x6a01, 0x6be0, 0x6c05, 0x6d00, 0x6e0e, 0x6f00, 0x7010, 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, //CCM 0x4c80, 0x4dbb, 0x4e84, 0x4f91, 0x5064, 0x5193, 0x5203, 0x53cd, 0x5489, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A31, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A31, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A31, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, 0xef03, //176X144 0x7000, 0xef00, 0xd108, 0x7a03, 0x1200, 0x1100, 0x1502, 0x1690, 0x1301, 0x14f0, 0x3104, 0x3006, 0x3402, 0x3588, 0x3201, 0x33e8, 0x7d02, 0x7e88, 0x7b01, 0x7ce8, 0x8100, 0x82b8, 0x7f00, 0x8098, 0xc304, 0xc204, 0xc600, 0xc7b0, 0xc400, 0xc590, }; static const u32 reg_init_cif_table[] = { 0xef02, //Analog setting 0x13a0, //Analog setting 0x2353, //Analog setting 0x2624, //Analog setting 0x2c05, //Analog setting 0x0500, //Analog setting 0x0350, //Analog setting 0x240a, //Analog setting 0x0b82, //Analog setting 0x1eb7, //Analog setting 0x5605, //Analog setting 0x2896, //Analog setting 0x673c, //Analog setting 0x4b5c, //Analog setting 0xef01, 0x70c3, //Clock delay 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max 0x620c, //PAL shutter Max 0x6301, //NT Vblank 0x64E7, 0x6501, //NT Hblank 0x66e7, 0x6d65, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f5d, //Dgain Max 0x4800, //NT Hblank 0x499E, 0x4c00, //PAL Hblank 0x4d9E, 0xef03, 0x0087, //AEAWB On 50Hz Mode 0x2b41, //Auto e-shutter enable 0x3100, //Brightness NH 0x3210, //Brightness LL 0x3380, //Contrast H 0x3479, //Contrast L 0x3630, //Saturation H 0x3730, //Saturation L 0x6a00, //BPR Start Position 0x7b05, //BPR 0x3805, //BPR 0x3903, //BPR 0x2d08, //NR 0x2e2c, //NR 0x2f30, //NR 0x30ff, //NR 0x7c06, //NR 0x7d2a, //NR 0x7e0c, //NR 0x7f2a, //NR 0x2802, //Sharpness 0x297f, //Sharpness 0x2a00, //Sharpness 0x1300, //AWB Outdoor Cintr limit 0x14a0, 0x1943, 0x1a6a, //Outdoor R gain Max 0x1b5f, //Outdoor R gain Min 0x1c61, //Outdoor B gain Max 0x1d4b, //Outdoor B gain Min 0x1e6a, //Indoor R gain Max 0x1f46, //Indoor R gain Min 0x2080, //7a Indoor B gain Max 0x2150, //Indoor B gain Min 0x3a13, //AWB speed AWB threshold 0x3b3e, //AWB Skip Bright 0x3c00, //AWB Skip Gain 0x3d18, //AWB Skip Avg 0x2380, //AWB Window Select 0x150b, //AWB Cnt 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order 0xdd03, //X shade on 0x2310, //GrGb 0x2410, //GrGb 0x2510, //GrGb 0x2718, //GrGb 0x2960, //GrGb 0x2a22, //GrGb 0x2f01, //Intp Coef Sharpness 0x3601, //Shading on 0x37e1, 0x38c7, 0x39af, 0x3a01, 0x3b04, 0x3c01, 0x3d31, 0xb902, //Sharpness on 0xbbb0, //HPF for sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness core 0xc188, 0xc811, //YC delay 0xeb81, //ECS on 0xed05, //ECS threshold 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, //Hue 0x7810, 0xef00, //AWB map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //Y level for AWB 0xaf10, //Y level for AWB 0xef00, 0x425D, //R gain start 0x4460, //B gain start 0x5700, //AE min skip 0xef03, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x0463, //AGC max Lowlight 0x061c, //AGC mac Highlight 0x0701, //AE window A weight 0x0801, //AE window B weight 0x0b01, //Cintc max high 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed 0x6917, //AE row flag 0xef00, //AE window 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61b1, 0x6201, 0x63be, 0x6400, 0x6581, 0x6601, 0x6761, 0xef00, //flicker setting 0x6a01, 0x6be0, 0x6c05, 0x6d00, 0x6e0e, 0x6f00, 0x7010, 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, //CCM 0x4c80, 0x4dbb, 0x4e84, 0x4f91, 0x5064, 0x5193, 0x5203, 0x53cd, 0x5489, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A31, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A31, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A31, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, 0xef03, //352X288 0x7000, 0xef00, 0xd108, 0x7a03, 0x1200, 0x1100, 0x1502, 0x1690, 0x1301, 0x14f0, 0x3104, 0x3006, 0x3402, 0x3588, 0x3201, 0x33e8, 0x7d02, 0x7e88, 0x7b01, 0x7ce8, 0x8101, 0x8268, 0x7f01, 0x8028, 0xc304, 0xc204, 0xc601, 0xc760, 0xc401, 0xc520, }; static const u32 reg_init_qvga_table[] = { 0xef02, //Analog setting 0x13a0, //Analog setting 0x2353, //Analog setting 0x2624, //Analog setting 0x2c05, //Analog setting 0x0500, //Analog setting 0x0350, //Analog setting 0x240a, //Analog setting 0x0b82, //Analog setting 0x1eb7, //Analog setting 0x5605, //Analog setting 0x2896, //Analog setting 0x673c, //Analog setting 0x4b5c, //Analog setting 0xef01, 0x70c3, //Clock delay 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max 0x620c, //PAL shutter Max 0x6301, //NT Vblank 0x64E7, 0x6501, //NT Hblank 0x66e7, 0x6d65, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f5d, //Dgain Max 0x4800, //NT Hblank 0x499E, 0x4c00, //PAL Hblank 0x4d9E, 0xef03, 0x0087, //AEAWB On 50Hz Mode 0x2b41, //Auto e-shutter enable 0x3100, //Brightness NH 0x3210, //Brightness LL 0x3380, //Contrast H 0x3479, //Contrast L 0x3630, //Saturation H 0x3730, //Saturation L 0x6a00, //BPR Start Position 0x7b05, //BPR 0x3805, //BPR 0x3903, //BPR 0x2d08, //NR 0x2e2c, //NR 0x2f30, //NR 0x30ff, //NR 0x7c06, //NR 0x7d2a, //NR 0x7e0c, //NR 0x7f2a, //NR 0x2802, //Sharpness 0x297f, //Sharpness 0x2a00, //Sharpness 0x1300, //AWB Outdoor Cintr limit 0x14a0, 0x1943, 0x1a6a, //Outdoor R gain Max 0x1b5f, //Outdoor R gain Min 0x1c61, //Outdoor B gain Max 0x1d4b, //Outdoor B gain Min 0x1e6a, //Indoor R gain Max 0x1f46, //Indoor R gain Min 0x2080, //7a Indoor B gain Max 0x2150, //Indoor B gain Min 0x3a13, //AWB speed AWB threshold 0x3b3e, //AWB Skip Bright 0x3c00, //AWB Skip Gain 0x3d18, //AWB Skip Avg 0x2380, //AWB Window Select 0x150b, //AWB Cnt 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order 0xdd03, //X shade on 0x2310, //GrGb 0x2410, //GrGb 0x2510, //GrGb 0x2718, //GrGb 0x2960, //GrGb 0x2a22, //GrGb 0x2f01, //Intp Coef Sharpness 0x3601, //Shading on 0x37e1, 0x38c7, 0x39af, 0x3a01, 0x3b04, 0x3c01, 0x3d31, 0xb902, //Sharpness on 0xbbb0, //HPF for sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness core 0xc188, 0xc811, //YC delay 0xeb81, //ECS on 0xed05, //ECS threshold 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, //Hue 0x7810, 0xef00, //AWB map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //Y level for AWB 0xaf10, //Y level for AWB 0xef00, 0x425D, //R gain start 0x4460, //B gain start 0x5700, //AE min skip 0xef03, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x0463, //AGC max Lowlight 0x061c, //AGC mac Highlight 0x0701, //AE window A weight 0x0801, //AE window B weight 0x0b01, //Cintc max high 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed 0x6917, //AE row flag 0xef00, //AE window 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61b1, 0x6201, 0x63be, 0x6400, 0x6581, 0x6601, 0x6761, 0xef00, //flicker setting 0x6a01, 0x6be0, 0x6c05, 0x6d00, 0x6e0e, 0x6f00, 0x7010, 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, //CCM 0x4c80, 0x4dbb, 0x4e84, 0x4f91, 0x5064, 0x5193, 0x5203, 0x53cd, 0x5489, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A31, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A31, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A31, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, 0xef03, //320X240 0x7000, 0xef00, 0xd108, 0x7a03, 0x1200, 0x1100, 0x1502, 0x1690, 0x1301, 0x14f0, 0x3104, 0x3006, 0x3402, 0x3588, 0x3201, 0x33e8, 0x7d02, 0x7e88, 0x7b01, 0x7ce8, 0x8101, 0x8248, 0x7f00, 0x80f8, 0xc304, 0xc204, 0xc601, 0xc740, 0xc400, 0xc5f0, }; static const u32 reg_init_vga_table[] = { 0xef02, //Analog setting 0x13a0, //Analog setting 0x2353, //Analog setting 0x2624, //Analog setting 0x2c05, //Analog setting 0x0500, //Analog setting 0x0350, //Analog setting 0x240a, //Analog setting 0x0b82, //Analog setting 0x1eb7, //Analog setting 0x5605, //Analog setting 0x2896, //Analog setting 0x673c, //Analog setting 0x4b5c, //Analog setting 0xef01, 0x70c3, //Clock delay 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max 0x620c, //PAL shutter Max 0x6301, //NT Vblank 0x64E7, 0x6501, //NT Hblank 0x66e7, 0x6d65, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f5d, //Dgain Max 0x4800, //NT Hblank 0x499E, 0x4c00, //PAL Hblank 0x4d9E, 0xef03, 0x0087, //AEAWB On 50Hz Mode 0x2b41, //Auto e-shutter enable 0x3100, //Brightness NH 0x3210, //Brightness LL 0x3380, //Contrast H 0x3479, //Contrast L 0x3630, //Saturation H 0x3730, //Saturation L 0x6a00, //BPR Start Position 0x7b05, //BPR 0x3805, //BPR 0x3903, //BPR 0x2d08, //NR 0x2e2c, //NR 0x2f30, //NR 0x30ff, //NR 0x7c06, //NR 0x7d2a, //NR 0x7e0c, //NR 0x7f2a, //NR 0x2802, //Sharpness 0x297f, //Sharpness 0x2a00, //Sharpness 0x1300, //AWB Outdoor Cintr limit 0x14a0, 0x1943, 0x1a6a, //Outdoor R gain Max 0x1b5f, //Outdoor R gain Min 0x1c61, //Outdoor B gain Max 0x1d4b, //Outdoor B gain Min 0x1e6a, //Indoor R gain Max 0x1f46, //Indoor R gain Min 0x2080, //7a Indoor B gain Max 0x2150, //Indoor B gain Min 0x3a13, //AWB speed AWB threshold 0x3b3e, //AWB Skip Bright 0x3c00, //AWB Skip Gain 0x3d18, //AWB Skip Avg 0x2380, //AWB Window Select 0x150b, //AWB Cnt 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order 0xdd03, //X shade on 0x2310, //GrGb 0x2410, //GrGb 0x2510, //GrGb 0x2718, //GrGb 0x2960, //GrGb 0x2a22, //GrGb 0x2f01, //Intp Coef Sharpness 0x3601, //Shading on 0x37e1, 0x38c7, 0x39af, 0x3a01, 0x3b04, 0x3c01, 0x3d31, 0xb902, //Sharpness on 0xbbb0, //HPF for sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness core 0xc188, 0xc811, //YC delay 0xeb81, //ECS on 0xed05, //ECS threshold 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, //Hue 0x7810, 0xef00, //AWB map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //Y level for AWB 0xaf10, //Y level for AWB 0xef00, 0x425D, //R gain start 0x4460, //B gain start 0x5700, //AE min skip 0xef03, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x0463, //AGC max Lowlight 0x061c, //AGC mac Highlight 0x0701, //AE window A weight 0x0801, //AE window B weight 0x0b01, //Cintc max high 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed 0x6917, //AE row flag 0xef00, //AE window 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61b1, 0x6201, 0x63be, 0x6400, 0x6581, 0x6601, 0x6761, 0xef00, //flicker setting 0x6a01, 0x6be0, 0x6c05, 0x6d00, 0x6e0e, 0x6f00, 0x7010, 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, //CCM 0x4c80, 0x4dbb, 0x4e84, 0x4f91, 0x5064, 0x5193, 0x5203, 0x53cd, 0x5489, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A31, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A31, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A31, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, 0xef03, 0x7001, }; static const u32 reg_init_qcif_vt_table[] = { 0xef02, 0x13a0, 0x2353, 0x2624, 0x2c05, 0x0500, 0x0350, //58 0x240a, 0x0b82, 0x1eb7, 0x5605, 0x2896, 0x673c, //reduce HN at low lux 0x4b5c, 0xef01, 0x70c3, 0xef03, 0x50d2, //24MHz //5a //12MHz 0x0f31, 0xef03, 0x5F03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max (Fixed mode) 0x620c, //PAL shutter Max (Fixed mode) 0x6305, //NT Vblank 0x6443, 0x6505, //PAL Vblank 0x6643, 0x6d5a, //indi.B 0x6e40, //Dgain Min 0x6f70, //Dgain Max 0x4c00, 0x4d9e, 0xef03, 0x0087, //AE ON [0], AWB ON [1] //87 : 50Hz Fixed mode, 07 : 60Hz Fixed modeAE target (Temporary. Don't move) 0x0180, //AE target (Temporary. Don't move) 0x027f, //AE th. (Temporary. Don't move) 0x2b41, 0x3107, // N.L. BT(Brightness) 0x3218, //12 L.L. BT(Brightness) 0x3380, //N.L. CT(Contrast) 0x3479, //L.L. CT(Contrast) 0x3636, //N.L ST(Saturation) 0x3727, //L.L. ST(Saturation) 0x6a00, //BPR start point 0x7b05, //H.L. BPR 0x3805, //N.L. BPR 0x3903, //L.L. BPR 0x2d08, //N.L. NR gain 0x2e20, //N.L. NR edge 0x2f30, //L.L. NR gain 0x30ff, //L.L. NR edge 0x7c06, //H.L. NR gain 0x7d20, //H.L. NR edge 0x7e0c, //M.L. NR gain 0x7f20, //M.L. NR edge 0x2802, //Sharpness ON 0x2975, //N.L Sharpness gain 0x2a00, //L.L Sharpness gain 0x1300, //AWB Outdoor Cintr limi 0x14a0, 0x1a6a, //Outdoor Rgain Max 0x1b50, //Outdoor Rgain Min 0x1c63, //Outdoor Bgain Max 0x1d4b, //Outdoor Bgain Min 0x1e6a, //Indoor Rgain Max 0x1f3c, //point Indoor Rgain Min 0x209a, //Indoor Bgain Max 0x214b, //Indoor Bgain Min 0x3a13, 0x3b3e, 0x3c00, 0x3d18, 0x2380, //AWB Window 0x150b, //AWB CNT 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order [3]YC [2]RB 0xdd03, //X shade ON 0x2310, //GrGb 0x2410, 0x2510, 0x2718, 0x2960, 0x2a22, 0x2f01, 0x3601, //Shading ON(R, G, B) 0x37e1, //R Gain 0x38c7, //g gain 0x39b1, //b gain82 0x3a00, //y 0x3bfa, 0x3c01, //x 0x3d31, 0xb902, //Sharpness ON(HW initial) 0xbbb0, //HPF for Sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness Core 0xc188, 0xc811, //YC delay 0xeb81, //ECS ON 0xed05, //ECS th. 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, 0x7810, //hue 0xef00, //AWB Map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //AWB up data 0xaf10, //AWB dn data 0xef00, 0x425f, //64 0x4461, //63 0x5700, //ae min skip 0xef03, 0x0087, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x046c, //73 AGC Max of LowLux 0x061c, //AGC Max of HL 0x0701, //AE win_A weight 0x0801, //AE win_B weight 0x0b01, //cintc max high 0x5110, 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, 0x6917, 0xef00, 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61ae, 0x6201, 0x63bb, 0x6400, 0x657e, 0x6601, 0x678e, 0xef00, //Flicker setting 0x6a01, //080331 Flicker H SIZE High 0x6be0, //080331 Flicker H SIZE low 0x6c05, //04 //080331 Flicker WINDOW VSIZE 0x6d00, //080331 Flicker V SIZE START H 0x6e0e, //080331 Flicker V SIZE START L 0x6f00, //080331 Flicker H SIZE START H 0x7010, //080331 Flicker H SIZE START L 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, 0x4c79, //ccm 0x4dbe, 0x4e08, 0x4f9c, 0x507a, 0x519e, 0x528f, 0x53bb, 0x548a, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A4A, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A4A, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A4A, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, //QCIF 0xef03, 0x7000, 0xef00, 0xd108, 0x7a00, 0x1200, 0x1100, 0x1502, 0x1690, //4c, //40 0x1301, 0x14f0, //e4, //D4 0x3104, 0x3006, 0x3402, 0x3588, //44, //38 0x3201, 0x33e8, //dc, //CC 0x7d02, 0x7e88, //44, //88 0x7b01, 0x7ce8, //dc, //e8 0x8100, 0x82c8, //b8, //D0 0x7f00, 0x8098, //9C 0xc30c, //04, 0xc204, //02 0xc600, 0xc7b0, 0xc400, 0xc590, 0x7a02, 0x7A03, // LPF_SCALE_CTRL 0xef03, 0x7001, }; static const u32 reg_init_cif_vt_table[] = { 0xef02, 0x13a0, 0x2353, 0x2624, 0x2c05, 0x0500, 0x0350, //58 0x240a, 0x0b82, 0x1eb7, 0x5605, 0x2896, 0x673c, //reduce HN at low lux 0x4b5c, 0xef01, 0x70c3, 0xef03, 0x50d2, //24MHz //5a //12MHz 0x0f31, 0xef03, 0x5F03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max (Fixed mode) 0x620c, //PAL shutter Max (Fixed mode) 0x6305, //NT Vblank 0x6443, 0x6505, //PAL Vblank 0x6643, 0x6d5a, //indi.B 0x6e40, //Dgain Min 0x6f70, //Dgain Max 0x4c00, 0x4d9e, 0xef03, 0x0087, //AE ON [0], AWB ON [1] //87 : 50Hz Fixed mode, 07 : 60Hz Fixed modeAE target (Temporary. Don't move) 0x0180, //AE target (Temporary. Don't move) 0x027f, //AE th. (Temporary. Don't move) 0x2b41, 0x3107, // N.L. BT(Brightness) 0x3218, //12 L.L. BT(Brightness) 0x3380, //N.L. CT(Contrast) 0x3479, //L.L. CT(Contrast) 0x3636, //N.L ST(Saturation) 0x3727, //L.L. ST(Saturation) 0x6a00, //BPR start point 0x7b05, //H.L. BPR 0x3805, //N.L. BPR 0x3903, //L.L. BPR 0x2d08, //N.L. NR gain 0x2e20, //N.L. NR edge 0x2f30, //L.L. NR gain 0x30ff, //L.L. NR edge 0x7c06, //H.L. NR gain 0x7d20, //H.L. NR edge 0x7e0c, //M.L. NR gain 0x7f20, //M.L. NR edge 0x2802, //Sharpness ON 0x2975, //N.L Sharpness gain 0x2a00, //L.L Sharpness gain 0x1300, //AWB Outdoor Cintr limi 0x14a0, 0x1a6a, //Outdoor Rgain Max 0x1b50, //Outdoor Rgain Min 0x1c63, //Outdoor Bgain Max 0x1d4b, //Outdoor Bgain Min 0x1e6a, //Indoor Rgain Max 0x1f3c, //point Indoor Rgain Min 0x209a, //Indoor Bgain Max 0x214b, //Indoor Bgain Min 0x3a13, 0x3b3e, 0x3c00, 0x3d18, 0x2380, //AWB Window 0x150b, //AWB CNT 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order [3]YC [2]RB 0xdd03, //X shade ON 0x2310, //GrGb 0x2410, 0x2510, 0x2718, 0x2960, 0x2a22, 0x2f01, 0x3601, //Shading ON(R, G, B) 0x37e1, //R Gain 0x38c7, //g gain 0x39b1, //b gain82 0x3a00, //y 0x3bfa, 0x3c01, //x 0x3d31, 0xb902, //Sharpness ON(HW initial) 0xbbb0, //HPF for Sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness Core 0xc188, 0xc811, //YC delay 0xeb81, //ECS ON 0xed05, //ECS th. 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, 0x7810, //hue 0xef00, //AWB Map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //AWB up data 0xaf10, //AWB dn data 0xef00, 0x425f, //64 0x4461, //63 0x5700, //ae min skip 0xef03, 0x0087, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x046c, //73 AGC Max of LowLux 0x061c, //AGC Max of HL 0x0701, //AE win_A weight 0x0801, //AE win_B weight 0x0b01, //cintc max high 0x5110, 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, 0x6917, 0xef00, 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61ae, 0x6201, 0x63bb, 0x6400, 0x657e, 0x6601, 0x678e, 0xef00, //Flicker setting 0x6a01, //080331 Flicker H SIZE High 0x6be0, //080331 Flicker H SIZE low 0x6c05, //04 //080331 Flicker WINDOW VSIZE 0x6d00, //080331 Flicker V SIZE START H 0x6e0e, //080331 Flicker V SIZE START L 0x6f00, //080331 Flicker H SIZE START H 0x7010, //080331 Flicker H SIZE START L 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, 0x4c79, //ccm 0x4dbe, 0x4e08, 0x4f9c, 0x507a, 0x519e, 0x528f, 0x53bb, 0x548a, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A4A, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A4A, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A4A, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, 0xef03, //352X288 0x7000, 0xef00, 0xd108, 0x7a03, 0x1200, 0x1100, 0x1502, 0x1690, 0x1301, 0x14f0, 0x3104, 0x3006, 0x3402, 0x3588, 0x3201, 0x33e8, 0x7d02, 0x7e88, 0x7b01, 0x7ce8, 0x8101, 0x8268, 0x7f01, 0x8028, 0xc304, 0xc204, 0xc601, 0xc760, 0xc401, 0xc520, }; static const u32 reg_init_qvga_vt_table[] = { 0xef02, 0x13a0, 0x2353, 0x2624, 0x2c05, 0x0500, 0x0350, //58 0x240a, 0x0b82, 0x1eb7, 0x5605, 0x2896, 0x673c, //reduce HN at low lux 0x4b5c, 0xef01, 0x70c3, 0xef03, 0x50d2, //24MHz //5a //12MHz 0x0f31, 0xef03, 0x5F03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max (Fixed mode) 0x620c, //PAL shutter Max (Fixed mode) 0x6305, //NT Vblank 0x6443, 0x6505, //PAL Vblank 0x6643, 0x6d5a, //indi.B 0x6e40, //Dgain Min 0x6f70, //Dgain Max 0x4c00, 0x4d9e, 0xef03, 0x0087, //AE ON [0], AWB ON [1] //87 : 50Hz Fixed mode, 07 : 60Hz Fixed modeAE target (Temporary. Don't move) 0x0180, //AE target (Temporary. Don't move) 0x027f, //AE th. (Temporary. Don't move) 0x2b41, 0x3107, // N.L. BT(Brightness) 0x3218, //12 L.L. BT(Brightness) 0x3380, //N.L. CT(Contrast) 0x3479, //L.L. CT(Contrast) 0x3636, //N.L ST(Saturation) 0x3727, //L.L. ST(Saturation) 0x6a00, //BPR start point 0x7b05, //H.L. BPR 0x3805, //N.L. BPR 0x3903, //L.L. BPR 0x2d08, //N.L. NR gain 0x2e20, //N.L. NR edge 0x2f30, //L.L. NR gain 0x30ff, //L.L. NR edge 0x7c06, //H.L. NR gain 0x7d20, //H.L. NR edge 0x7e0c, //M.L. NR gain 0x7f20, //M.L. NR edge 0x2802, //Sharpness ON 0x2975, //N.L Sharpness gain 0x2a00, //L.L Sharpness gain 0x1300, //AWB Outdoor Cintr limi 0x14a0, 0x1a6a, //Outdoor Rgain Max 0x1b50, //Outdoor Rgain Min 0x1c63, //Outdoor Bgain Max 0x1d4b, //Outdoor Bgain Min 0x1e6a, //Indoor Rgain Max 0x1f3c, //point Indoor Rgain Min 0x209a, //Indoor Bgain Max 0x214b, //Indoor Bgain Min 0x3a13, 0x3b3e, 0x3c00, 0x3d18, 0x2380, //AWB Window 0x150b, //AWB CNT 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order [3]YC [2]RB 0xdd03, //X shade ON 0x2310, //GrGb 0x2410, 0x2510, 0x2718, 0x2960, 0x2a22, 0x2f01, 0x3601, //Shading ON(R, G, B) 0x37e1, //R Gain 0x38c7, //g gain 0x39b1, //b gain82 0x3a00, //y 0x3bfa, 0x3c01, //x 0x3d31, 0xb902, //Sharpness ON(HW initial) 0xbbb0, //HPF for Sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness Core 0xc188, 0xc811, //YC delay 0xeb81, //ECS ON 0xed05, //ECS th. 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, 0x7810, //hue 0xef00, //AWB Map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //AWB up data 0xaf10, //AWB dn data 0xef00, 0x425f, //64 0x4461, //63 0x5700, //ae min skip 0xef03, 0x0087, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x046c, //73 AGC Max of LowLux 0x061c, //AGC Max of HL 0x0701, //AE win_A weight 0x0801, //AE win_B weight 0x0b01, //cintc max high 0x5110, 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, 0x6917, 0xef00, 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61ae, 0x6201, 0x63bb, 0x6400, 0x657e, 0x6601, 0x678e, 0xef00, //Flicker setting 0x6a01, //080331 Flicker H SIZE High 0x6be0, //080331 Flicker H SIZE low 0x6c05, //04 //080331 Flicker WINDOW VSIZE 0x6d00, //080331 Flicker V SIZE START H 0x6e0e, //080331 Flicker V SIZE START L 0x6f00, //080331 Flicker H SIZE START H 0x7010, //080331 Flicker H SIZE START L 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, 0x4c79, //ccm 0x4dbe, 0x4e08, 0x4f9c, 0x507a, 0x519e, 0x528f, 0x53bb, 0x548a, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A4A, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A4A, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A4A, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, 0xef03, //320X240 0x7000, 0xef00, 0xd108, 0x7a03, 0x1200, 0x1100, 0x1502, 0x1690, 0x1301, 0x14f0, 0x3104, 0x3006, 0x3402, 0x3588, 0x3201, 0x33e8, 0x7d02, 0x7e88, 0x7b01, 0x7ce8, 0x8101, 0x8248, 0x7f00, 0x80f8, 0xc304, 0xc204, 0xc601, 0xc740, 0xc400, 0xc5f0, }; static const u32 reg_init_vga_vt_table[] = { 0xef02, 0x13a0, 0x2353, 0x2624, 0x2c05, 0x0500, 0x0350, //58 0x240a, 0x0b82, 0x1eb7, 0x5605, 0x2896, 0x673c, //reduce HN at low lux 0x4b5c, 0xef01, 0x70c3, 0xef03, 0x50d2, //24MHz //5a //12MHz 0x0f31, 0xef03, 0x5F03, //NT Cintr Max 0x6002, //PAL Cintr Max 0x610f, //NT shutter Max (Fixed mode) 0x620c, //PAL shutter Max (Fixed mode) 0x6305, //NT Vblank 0x6443, 0x6505, //PAL Vblank 0x6643, 0x6d5a, //indi.B 0x6e40, //Dgain Min 0x6f70, //Dgain Max 0x4c00, 0x4d9e, 0xef03, 0x0087, //AE ON [0], AWB ON [1] //87 : 50Hz Fixed mode, 07 : 60Hz Fixed modeAE target (Temporary. Don't move) 0x0180, //AE target (Temporary. Don't move) 0x027f, //AE th. (Temporary. Don't move) 0x2b41, 0x3107, // N.L. BT(Brightness) 0x3218, //12 L.L. BT(Brightness) 0x3380, //N.L. CT(Contrast) 0x3479, //L.L. CT(Contrast) 0x3636, //N.L ST(Saturation) 0x3727, //L.L. ST(Saturation) 0x6a00, //BPR start point 0x7b05, //H.L. BPR 0x3805, //N.L. BPR 0x3903, //L.L. BPR 0x2d08, //N.L. NR gain 0x2e20, //N.L. NR edge 0x2f30, //L.L. NR gain 0x30ff, //L.L. NR edge 0x7c06, //H.L. NR gain 0x7d20, //H.L. NR edge 0x7e0c, //M.L. NR gain 0x7f20, //M.L. NR edge 0x2802, //Sharpness ON 0x2975, //N.L Sharpness gain 0x2a00, //L.L Sharpness gain 0x1300, //AWB Outdoor Cintr limi 0x14a0, 0x1a6a, //Outdoor Rgain Max 0x1b50, //Outdoor Rgain Min 0x1c63, //Outdoor Bgain Max 0x1d4b, //Outdoor Bgain Min 0x1e6a, //Indoor Rgain Max 0x1f3c, //point Indoor Rgain Min 0x209a, //Indoor Bgain Max 0x214b, //Indoor Bgain Min 0x3a13, 0x3b3e, 0x3c00, 0x3d18, 0x2380, //AWB Window 0x150b, //AWB CNT 0x16d2, 0x1764, 0x1878, 0xef00, //X shade 0xde00, 0xdf1F, 0xe000, 0xe137, 0xe208, 0xe342, 0xe400, 0xe512, 0xe69E, 0xe900, 0xe700, 0xe8A8, 0xe901, 0xe700, 0xe8B1, 0xe902, 0xe700, 0xe8C4, 0xe903, 0xe700, 0xe8BA, 0xe904, 0xe700, 0xe8C4, 0xe905, 0xe700, 0xe8E5, 0xe906, 0xe701, 0xe813, 0xe907, 0xe700, 0xe84B, 0xe908, 0xe700, 0xe84B, 0xe909, 0xe700, 0xe84E, 0xe90A, 0xe700, 0xe84F, 0xe90B, 0xe700, 0xe842, 0xe90C, 0xe700, 0xe86A, 0xe90D, 0xe700, 0xe889, 0xe90E, 0xe707, 0xe8D9, 0xe90F, 0xe707, 0xe8D8, 0xe910, 0xe707, 0xe8DD, 0xe911, 0xe707, 0xe8D1, 0xe912, 0xe707, 0xe8CA, 0xe913, 0xe707, 0xe8CE, 0xe914, 0xe707, 0xe8FA, 0xe915, 0xe707, 0xe86A, 0xe916, 0xe707, 0xe871, 0xe917, 0xe707, 0xe870, 0xe918, 0xe707, 0xe85E, 0xe919, 0xe707, 0xe850, 0xe91A, 0xe707, 0xe855, 0xe91B, 0xe707, 0xe86D, 0xe91C, 0xe707, 0xe81C, 0xe91D, 0xe707, 0xe812, 0xe91E, 0xe707, 0xe807, 0xe91F, 0xe706, 0xe8FA, 0xe920, 0xe706, 0xe8E5, 0xe921, 0xe706, 0xe8F0, 0xe922, 0xe707, 0xe80A, 0xe940, 0xd108, //YC order [3]YC [2]RB 0xdd03, //X shade ON 0x2310, //GrGb 0x2410, 0x2510, 0x2718, 0x2960, 0x2a22, 0x2f01, 0x3601, //Shading ON(R, G, B) 0x37e1, //R Gain 0x38c7, //g gain 0x39b1, //b gain82 0x3a00, //y 0x3bfa, 0x3c01, //x 0x3d31, 0xb902, //Sharpness ON(HW initial) 0xbbb0, //HPF for Sharpness 0xbc18, 0xbd30, 0xbf38, //Sharpness Core 0xc188, 0xc811, //YC delay 0xeb81, //ECS ON 0xed05, //ECS th. 0xb100, //AWB window 0xb262, 0xb300, 0xb400, 0xb501, 0xb6a3, 0xb702, 0xb880, 0x7700, 0x7810, //hue 0xef00, //AWB Map 0x9340, 0x9480, 0x95c0, 0x96c0, 0x9720, 0x9820, 0x9930, 0xA000, 0xA100, 0xA21c, 0xA316, 0xA403, 0xA507, 0xA600, 0xef00, 0xadd0, //AWB up data 0xaf10, //AWB dn data 0xef00, 0x425f, //64 0x4461, //63 0x5700, //ae min skip 0xef03, 0x0087, 0x013c, //AE target 0x0205, //AE threshold 0x0321, //AE step 0x046c, //73 AGC Max of LowLux 0x061c, //AGC Max of HL 0x0701, //AE win_A weight 0x0801, //AE win_B weight 0x0b01, //cintc max high 0x5110, 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, 0x6917, 0xef00, 0x5800, 0x5900, 0x5a02, 0x5b73, 0x5c00, 0x5d00, 0x5e01, 0x5fe0, 0x6000, 0x61ae, 0x6201, 0x63bb, 0x6400, 0x657e, 0x6601, 0x678e, 0xef00, //Flicker setting 0x6a01, //080331 Flicker H SIZE High 0x6be0, //080331 Flicker H SIZE low 0x6c05, //04 //080331 Flicker WINDOW VSIZE 0x6d00, //080331 Flicker V SIZE START H 0x6e0e, //080331 Flicker V SIZE START L 0x6f00, //080331 Flicker H SIZE START H 0x7010, //080331 Flicker H SIZE START L 0xef03, 0x2224, 0x3e23, 0x3f23, 0x4000, 0x4109, 0x4a09, 0x4b04, 0x5b20, 0x5d35, 0x5e13, 0x780f, 0xef00, 0x4c79, //ccm 0x4dbe, 0x4e08, 0x4f9c, 0x507a, 0x519e, 0x528f, 0x53bb, 0x548a, 0xef00, //RGB Gamma 0x4800, 0x4900, 0x4A03, 0x4801, 0x4900, 0x4A08, 0x4802, 0x4900, 0x4A4A, 0x4803, 0x4900, 0x4A96, 0x4804, 0x4901, 0x4A24, 0x4805, 0x4901, 0x4AB4, 0x4806, 0x4902, 0x4A23, 0x4807, 0x4902, 0x4A72, 0x4808, 0x4902, 0x4ABE, 0x4809, 0x4902, 0x4AFA, 0x480A, 0x4903, 0x4A27, 0x480B, 0x4903, 0x4A55, 0x480C, 0x4903, 0x4A81, 0x480D, 0x4903, 0x4AA2, 0x480E, 0x4903, 0x4ABC, 0x480F, 0x4903, 0x4AD4, 0x4810, 0x4903, 0x4AE8, 0x4811, 0x4903, 0x4AF4, 0x4812, 0x4903, 0x4AFF, 0x4820, 0x4900, 0x4A03, 0x4821, 0x4900, 0x4A08, 0x4822, 0x4900, 0x4A4A, 0x4823, 0x4900, 0x4A96, 0x4824, 0x4901, 0x4A24, 0x4825, 0x4901, 0x4AB4, 0x4826, 0x4902, 0x4A23, 0x4827, 0x4902, 0x4A72, 0x4828, 0x4902, 0x4ABE, 0x4829, 0x4902, 0x4AFA, 0x482A, 0x4903, 0x4A27, 0x482B, 0x4903, 0x4A55, 0x482C, 0x4903, 0x4A81, 0x482D, 0x4903, 0x4AA2, 0x482E, 0x4903, 0x4ABC, 0x482F, 0x4903, 0x4AD4, 0x4830, 0x4903, 0x4AE8, 0x4831, 0x4903, 0x4AF4, 0x4832, 0x4903, 0x4AFF, 0x4840, 0x4900, 0x4A03, 0x4841, 0x4900, 0x4A08, 0x4842, 0x4900, 0x4A4A, 0x4843, 0x4900, 0x4A96, 0x4844, 0x4901, 0x4A24, 0x4845, 0x4901, 0x4AB4, 0x4846, 0x4902, 0x4A23, 0x4847, 0x4902, 0x4A72, 0x4848, 0x4902, 0x4ABE, 0x4849, 0x4902, 0x4AFA, 0x484A, 0x4903, 0x4A27, 0x484B, 0x4903, 0x4A55, 0x484C, 0x4903, 0x4A81, 0x484D, 0x4903, 0x4AA2, 0x484E, 0x4903, 0x4ABC, 0x484F, 0x4903, 0x4AD4, 0x4850, 0x4903, 0x4AE8, 0x4851, 0x4903, 0x4AF4, 0x4852, 0x4903, 0x4AFF, }; /************** White Balance Setting ******************/ /* Modified to SEHF Variable */ static const u32 reg_wb_auto_table[] = { 0xef03, 0x0087, 0xef00, 0x426f, 0x4340, 0x445a, }; static const u32 reg_wb_daylight_table[] = { 0xef03, 0x0085, 0xef00, 0x4267, 0x4340, 0x444c, }; static const u32 reg_wb_incandescent_table[] = { 0xef03, 0x0085, 0xef00, 0x4248, 0x4343, 0x447e, }; static const u32 reg_wb_fluorescent_table[] = { 0xef03, 0x0085, 0xef00, 0x425c, 0x4340, 0x446d, }; static const u32 reg_wb_cloudy_table[] = { 0xef03, 0x0085, 0xef00, 0x426f, 0x433d, 0x4447, }; /************** Exposure Value Setting ****************/ /* Modified to SEHF Variable */ static const u32 reg_ev_table[] = { 0xef03, //Page 03 0x31b0, //EV_-5 0x3298, 0x31a0, //EV_-4 0x3290, 0x3198, //EV_-3 0x3288, 0x3190, //EV_-2 0x3200, 0x3188, //EV_-1 0x3208, 0x3100, //EV_0 0x3210, 0x3108, //EV_+1 0x3220, 0x3110, //EV_+2 0x3230, 0x3120, //EV_+3 0x3238, 0x3128, //EV_+4 0x3240, 0x3130, //EV_+5 0x3248, }; static const u32 reg_ev_vt_table[] = { 0xef03, //Page 03 0x31a9, //EV_-5 0x32a4, 0x3199, //EV_-4 0x329c, 0x3191, //EV_-3 0x3294, 0x3189, //EV_-2 0x3208, 0x3181, //EV_-1 0x3210, 0x3107, //EV_0 0x3218, 0x310e, //EV_+1 0x3228, 0x3117, //EV_+2 0x3238, 0x3127, //EV_+3 0x3240, 0x312a, //EV_+4 0x323e, 0x3132, //EV_+5 0x3246, }; /************** Contrast Value Setting ****************/ /* Modified to SEHF Variable */ static const u32 reg_contrast_level_m5_table[] = { 0xef03, 0x3330, 0x3429, }; static const u32 reg_contrast_level_m4_table[] = { 0xef03, 0x3340, 0x3439, }; static const u32 reg_contrast_level_m3_table[] = { 0xef03, 0x3350, 0x3449, }; static const u32 reg_contrast_level_m2_table[] = { 0xef03, 0x3360, 0x3459, }; static const u32 reg_contrast_level_m1_table[] = { 0xef03, 0x3370, 0x3469, }; static const u32 reg_contrast_level_default_table[] = { 0xef03, 0x3380, 0x3479, }; static const u32 reg_contrast_level_p1_table[] = { 0xef03, 0x3390, 0x3489, }; static const u32 reg_contrast_level_p2_table[] = { 0xef03, 0x33a0, 0x3499, }; static const u32 reg_contrast_level_p3_table[] = { 0xef03, 0x33b0, 0x34a9, }; static const u32 reg_contrast_level_p4_table[] = { 0xef03, 0x33c0, 0x34b9, }; static const u32 reg_contrast_level_p5_table[] = { 0xef03, 0x33d0, 0x34c9, }; /************** Effect Setting ********************/ /* Modified to SEHF Variable */ static const u32 reg_effect_none_table[] = { 0xef00, 0xd300, 0xd400, 0xd501, 0xd6a3, }; static const u32 reg_effect_gray_table[] = { 0xef00, 0xd300, 0xd403, 0xd580, 0xd680, }; static const u32 reg_effect_sepia_table[] = { 0xef00, 0xd300, 0xd403, 0xd560, 0xd68c, }; static const u32 reg_effect_negative_table[] = { 0xef00, 0xd301, 0xd400, 0xd52c, 0xd681, }; static const u32 reg_effect_aqua_table[] = { 0xef00, 0xd300, 0xd403, 0xd5dc, 0xd600, }; static const u32 reg_effect_red_table[] = { 0xef00, 0xd300, 0xd413, 0xd5aa, 0xd681, }; static const u32 reg_effect_green_table[] = { 0xef00, 0xd300, 0xd403, 0xd52c, 0xd641, }; /************** Pretty Setting ********************/ /* Modified to SEHF Variable */ static const u32 reg_pretty_none_table[] = { 0xef03, 0x013c, 0x298f, 0x3479, }; static const u32 reg_pretty_level1_table[] = { 0xef03, 0x014a, 0x294f, 0x3489, }; static const u32 reg_pretty_level2_table[] = { 0xef03, 0x0158, 0x291f, 0x3499, }; static const u32 reg_pretty_level3_table[] = { 0xef03, 0x0166, 0x2900, 0x34a9, }; static const u32 reg_pretty_vt_none_table[] = { 0xef03, 0x013c, 0x2975, 0x3479, }; static const u32 reg_pretty_vt_level1_table[] = { 0xef03, 0x014a, 0x2945, 0x3489, }; static const u32 reg_pretty_vt_level2_table[] = { 0xef03, 0x0158, 0x2915, 0x3499, }; static const u32 reg_pretty_vt_level3_table[] = { 0xef03, 0x0166, 0x2900, 0x34a9, }; /************** Flip Setting ********************/ /* Modified to SEHF Variable */ static const u32 reg_flip_none_table[] = { 0xef03, 0x7000, }; static const u32 reg_flip_mirror_table[] = { 0xef03, 0x7001, }; static const u32 reg_flip_water_table[] = { 0xef03, 0x7002, }; static const u32 reg_flip_water_mirror_table[] = { 0xef03, 0x7003, }; static const u32 reg_7fps_table[] = { 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f11, //NT Cintr Max 0x600e, //PAL Cintr Max 0x6111, //NT shutter Max 0x620e, //PAL shutter Max 0x6306, //NT Vblank 0x644b, 0x6506, //NT Hblank 0x664b, 0x6d6c, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f40, //Dgain Max 0x4c00, //PAL Hblank 0x4d9E, 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed }; static const u32 reg_10fps_table[] = { 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f0c, //NT Cintr Max 0x600a, //PAL Cintr Max 0x610c, //NT shutter Max 0x620a, //PAL shutter Max 0x6303, //NT Vblank 0x64d3, 0x6503, //NT Hblank 0x66d3, 0x6d6C, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f40, //Dgain Max 0x4c00, //PAL Hblank 0x4d9E, 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed }; static const u32 reg_15fps_table[] = { 0xef03, 0x50d2, //Mclk 0x0f31, //Vblank Value 0xef03, 0x5f08, //NT Cintr Max 0x6006, //PAL Cintr Max 0x6108, //NT shutter Max 0x6206, //PAL shutter Max 0x6301, //NT Vblank 0x64E7, 0x6501, //NT Hblank 0x66E7, 0x6d6C, //AGC Min for suppress B 0x6E40, //Dgain Min 0x6f40, //Dgain Max 0x4c00, //PAL Hblank 0x4d9E, 0x5110, //Chip DBG 0x5200, 0x5300, 0x5400, 0x5522, 0x5601, 0x5761, 0x5825, 0x67cf, //AE speed }; static const u32 reg_self_capture_table[] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; static const u32 s5ka3dfx_dataline[] = { 0xef00, 0x0a01, // s/w reset 0x0401, 0xcb01, 0xd108, }; static const u32 s5ka3dfx_dataline_stop[] = { 0xef00, 0xcb00, }; #endif /* * VGA Self shot init setting */ #if 0 //hawk //handong /* * VGA Self shot init setting */ static unsigned short SR030pc30_init_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, //Page0 0x0300, 0x1000, 0x11b0, //On Var Frame - None : 90, X Flip : 91, Y Flip : 0x1224,//PCLK Inversion 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 336 0x4150, 0x4201, //Vblank 300 0x432c, //BLC 0x803e, 0x8196, 0x8290, 0x8300, 0x842c, 0x900f, //BLC_TIME_TH_ON 0x910f, //BLC_TIME_TH_OFF 0x9278, //BLC_AG_TH_ON 0x9370, //BLC_AG_TH_OFF 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, //Page2 0x0302, 0x1000, 0x1300, 0x181C, 0x1900, 0x1a00, 0x1b08, 0x1C00, 0x1D00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343C, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639E, 0x6478, 0x659E, 0x727A, 0x739A, 0x747A, 0x759A, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81D, 0xaa49, 0xb98A, 0xbb8A, 0xbc04, 0xbd10, 0xbe04, 0xbf10, //Page10 0x0310,// 0x1001,//ISPCTL1 0x1230,//Y offet, dy offseet enable 0x4080, 0x4105,// 0x5078,// 0x601f, 0x6180, 0x6280, 0x63f0, 0x6480, //Page11 0x0311, 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, //Page12 0x0312, 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, //Page13 0x0313, 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800D, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, //Page14 0x0314, 0x1001, 0x2080, 0x2178, 0x2253, 0x2340, 0x243e, //Page 15 CmC 0x0315, 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, 0x1001, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, //Page20 AE 0x0320, 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2af0, 0x2bf4, 0x30f8, 0x60d5, 0x6834, 0x696e, 0x6A28, 0x6Bc8, 0x7034,//Y Target 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8300,//ExpTime 30fps 0x84c3, 0x8550, 0x8600,//ExpMin 0x87fa, 0x8802,//ExpMax 8fps(10fps) 0x8949, 0x8af0, 0x8b3a,//Exp100 0x8c98, 0x8d30,//Exp120 0x8ed4, 0x8f04, 0x9093, 0x9102, 0x92d2, 0x93a8, 0x988C, 0x9923, 0x9c05, //EXP Limit 1000.00 fps 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0xb014, 0xb114, 0xb2d0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc870, 0xc980, //Page 22 AWB 0x0322, 0x10e2, 0x1126, 0x2104, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x50d0, 0x51a0, 0x52aa, 0x8045, 0x8120, 0x8248, 0x8354,//54 0x8422,//22 29 27 0x8552,//54 53 50 0x8620,//22 0x874c, 0x8834, 0x8930, 0x8a22, 0x8b00, 0x8d22, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x0300, 0x11b0, //3 Bad frame skip, Fixed disable 0x01f0, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x1194, //Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2263, // 53 0x2350, // 40 0x244e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 30.00 fps 0x84c3, 0x8550, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x01f0, 0xFFFF, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt2_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x1197, //Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2263, // 53 0x2350, // 40 0x244e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 30.00 fps 0x84c3, 0x8550, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x01f0, 0xFFFF, }; /************** Exposure Value Setting ****************/ /* * EV bias */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /* * EV bias for VT */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_vt_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_vt_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_vt_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_vt_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_vt_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_vt_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_vt_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_vt_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_vt_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /************** White Balance Setting ******************/ static unsigned short SR030pc30_wb_auto[] = { 0x0322, 0x10e2, 0x1126, 0x8045, 0x8120, 0x8248, 0x8366, //66 RMAX Default : 50 0x8426, //28 26 RMIN Default : 20 0x8555, //58 5a BMAX Default : 50 0x8620, //20 BMIN Default : 20 0x10fb, }; static unsigned short SR030pc30_wb_tungsten[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_fluorescent[] = { 0x0322, 0x107b, 0x1126, 0x8042, 0x8120, 0x8251, 0x834a, //4c 4e RMAX 0x843a, //40 0x8555, //58 0x8645, //48 4a BMIN 0x10fb, }; static unsigned short SR030pc30_wb_sunny[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_cloudy[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x837f, //7f 7d 0x8470, //7d 7d 7f RMIN 0x851f, //1c 1e 1a 21 BMAX 0x8610, //10 1e 0x10fb, }; /************** Effect Setting ********************/ static unsigned short SR030pc30_effect_none[] = { 0x0310, 0x1103, 0x1230, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_gray[] = { 0x0310, 0x1103, 0x1233, 0x4480, 0x4580, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_sepia[] = { 0x0310, 0x1103, 0x1233, 0x4470, 0x4598, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_negative[] = { 0x0310, 0x1103, 0x1238, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_aqua[] = { 0x0310, 0x1103, 0x1233, 0x44b0, 0x4540, 0x0313, 0x103b, 0x2002, }; /************** Blur Setting ********************/ /*Self shot*/ static unsigned short SR030pc30_blur_none[] = { 0x0316, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, }; static unsigned short SR030pc30_blur_p1[] = { 0x0316, 0x3000, 0x3115, 0x3225, 0x3344, 0x3476, 0x359c, 0x36b8, 0x37cd, 0x38db, 0x39e6, 0x3aed, 0x3bf7, 0x3cfc, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_p2[] = { 0x0316, 0x3000, 0x3118, 0x322e, 0x3357, 0x3495, 0x35bd, 0x36d6, 0x37e5, 0x38ef, 0x39f5, 0x3af9, 0x3bfd, 0x3cfe, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_p3[] = { 0x0316, 0x3000, 0x311b, 0x3238, 0x336c, 0x34b0, 0x35d4, 0x36e8, 0x37f2, 0x38f8, 0x39fb, 0x3afd, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; /*vt call*/ static unsigned short SR030pc30_blur_vt_none[] = { 0x0316, 0x1001, 0x3000, 0x3119, 0x3226, 0x333b, 0x345d, 0x3579, 0x368e, 0x379f, 0x38af, 0x39bd, 0x3aca, 0x3bdd, 0x3cec, 0x3df7, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p1[] = { 0x0316, 0x3000, 0x3119, 0x3226, 0x3341, 0x3472, 0x3597, 0x36b3, 0x37c8, 0x38d7, 0x39e3, 0x3aeb, 0x3bf5, 0x3cfb, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p2[] = { 0x0316, 0x3000, 0x3119, 0x322c, 0x3356, 0x3496, 0x35bf, 0x36d8, 0x37e8, 0x38f1, 0x39f6, 0x3afa, 0x3bfd, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p3[] = { 0x0316, 0x3000, 0x311a, 0x323a, 0x3374, 0x34bd, 0x35e0, 0x36f0, 0x37f8, 0x38fc, 0x39fd, 0x3afe, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_dataline[] = { 0x0300, 0x5005, //Test Pattern 0x0311, 0x1098, 0x0312, 0x4022, 0x701c, 0x0313, 0x103a, 0x800c, 0x0314, 0x1000, 0x0315, 0x1002, 0x0316, 0x1000, 0x0320, 0x100c, 0x0322, 0x107b, }; static unsigned short SR030pc30_dataline_stop[] = { 0x0300, 0x5000, //Test Pattern 0x0311, 0x1099, 0x0312, 0x4023, 0x701d, 0x0313, 0x103b, 0x800d, 0x0314, 0x1001, 0x0315, 0x1003, 0x0316, 0x1001, 0x0320, 0x108c, 0x0322, 0x10fb, }; /************** FPS********************/ static unsigned short SR030pc30_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b0,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b4, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_10[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b0,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05, 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b4, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b0,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b4, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b0,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b4, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_10[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b0,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b4, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b0,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b4, //Fixed enable 0x01f0, //Sleep Off }; #endif // handong #if 0 // org static unsigned short SR030pc30_init_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, //Page0 0x0300, 0x1000, 0x11b1, //On Var Frame - None : 90, X Flip : 91, Y Flip : 0x1224,//PCLK Inversion 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 336 0x4150, 0x4201, //Vblank 300 0x432c, //BLC 0x803e, 0x8196, 0x8290, 0x8300, 0x842c, 0x900f, //BLC_TIME_TH_ON 0x910f, //BLC_TIME_TH_OFF 0x9278, //BLC_AG_TH_ON 0x9370, //BLC_AG_TH_OFF 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, //Page2 0x0302, 0x1000, 0x1300, 0x181C, 0x1900, 0x1a00, 0x1b08, 0x1C00, 0x1D00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343C, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639E, 0x6478, 0x659E, 0x727A, 0x739A, 0x747A, 0x759A, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81D, 0xaa49, 0xb98A, 0xbb8A, 0xbc04, 0xbd10, 0xbe04, 0xbf10, //Page10 0x0310,// 0x1001,//ISPCTL1 0x1230,//Y offet, dy offseet enable 0x4080, 0x4102,// 0x5078,// 0x601f, 0x6182, 0x6282, 0x63f0, 0x6480, //Page11 0x0311, 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, //Page12 0x0312, 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, //Page13 0x0313, 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800D, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, //Page14 0x0314, 0x1001, 0x2080, 0x2178, 0x2253, 0x2340, 0x243e, //Page 15 CmC 0x0315, 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, 0x1001, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, //Page20 AE 0x0320, 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2af0, 0x2bf4, 0x30f8, 0x60d5, 0x6834, 0x696e, 0x6A28, 0x6Bc8, 0x7034,//Y Target 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8300,//ExpTime 30fps 0x84c3, 0x8550, 0x8600,//ExpMin 0x87fa, 0x8802, //EXP Max 8.00 fps 0x89dc, 0x8a6c, 0x8b3a,//Exp100 0x8c98, 0x8d30,//Exp120 0x8ed4, 0x8f04, 0x9093, 0x9102, 0x92d2, 0x93a8, 0x988C, 0x9923, 0x9c05, //EXP Limit 1000.00 fps 0x9ddc, 0x9e00,//4s unit 0x9ffa, 0xb014, 0xb114, 0xb2a0, //d0 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc870, 0xc980, //Page 22 AWB 0x0322, 0x10e2, 0x1126, 0x2104, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x50d0, 0x51a0, 0x52aa, 0x8045, 0x8120, 0x8248, 0x8354,//54 0x8422,//22 29 27 0x8552,//54 53 50 0x8620,//22 0x8752, //4C 0x8834, 0x8934, //30 0x8a22, 0x8b00, 0x8d22, 0x8e71, 0x8f5e, //63 0x9059, //60 0x9156, //5c 0x9251, //59 0x934b, //55 0x9445, //50 0x953a, //48 0x962e, //3e 0x9727, //37 0x9821, //30 0x991e, //29 0x9a19, //26 0x9b09, //09 0xb47b, 0x0322, 0x10fb, 0x0320, 0x108c, 0x0300, 0x11b1, //3 Bad frame skip, Fixed disable 0x01f0, }; //========================================================== // CAMERA INITIAL for VT Preview 7 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt_reg[] = { 0x0300, //this is for VT-call 0x01f1, 0x01f3, 0x01f1, 0x0320, //page 3 0x100c, //ae off 0x0322, //page 4 0x107b, //awb off //Page0 0x0300, 0x1000, 0x1195, //On Fix Frame - None : 94, X Flip : 95, Y Flip : 96, XY : 97 0x1204, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // //BLC 0x803e, 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, //Page2 0x0302, // 0x1000, // 0x1300, // 0x181C, // 0x1900, // 0x1a00, // 0x1b08, // 0x1C00, // 0x1D00, // 0x2033, // 0x21aa, // 0x22a6, // 0x23b0, // 0x3199, // 0x3200, // 0x3300, // 0x343C, // 0x5021, // 0x5430, // 0x56fe, // 0x6278, // 0x639E, // 0x6478, // 0x659E, // 0x727A, // 0x739A, // 0x747A, // 0x759A, // 0x8209, // 0x8409, // 0x8609, // 0xa003, // 0xa81D, // 0xaa49, // 0xb98A, // 0xbb8A, // 0xbc04, // 0xbd10, // 0xbe04, // 0xbf10, // //Page10 0x0310,// 0x1001,//ISPCTL1 0x03 0x1230,//Y offet, dy offseet enable 0x4080, //8e 0x4118, 0x5078, 0x601f, 0x6180,//CB//82 0x6280,//CR//83 0x63f0, 0x6480, //Page 11 0x0311, 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, //Page12 0x0312, 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, //Page13 0x0313, 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800D, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, //Page14 0x0314, 0x1001, 0x2080, 0x2178, 0x2253, 0x2340, 0x2442,//3e //Page15 CMC 0x0315, 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, 0x1001, 0x3000, 0x3114, 0x3223, 0x333b, 0x345d, 0x3579, 0x368e, 0x379f, 0x38af, 0x39bd, 0x3aca, 0x3bdd, 0x3cec, 0x3df7, 0x3eff, //Page 20 AE 0x0320, // 0x100c, // 0x1104, // 0x2001, //AE weight 0x283f, //AE 4Shared speed up Enable 0x29a3, 0x2a93, // Fixed 0x2bf5, // 2/120 Anti banding 0x30f8, // 0xf8->0x78 2/120 Anti banding 0x60c0, // weight 80->6a 0x683c, 0x6964, 0x6A28, 0x6Bc8, 0x7042, //Y LVL 0x7812, //yth1 0x7916, //yth2 0x7A23, //yth3 0x8300, //30fps 0x84c3, 0x8550, 0x8600, // Exp min 0x87fa, 0x8802, // Exp Max 7fps 0x89dc, 0x8a6c, 0x8b3a, //Exp100Hz 0x8c98, 0x8d30, //Exp120Hz 0x8ed4, 0x8f04, // 0x9093, // 0x9103, //Fixed 7 0x923b, // 0x9349, // 0x988C, //outdoor th1 0x9923, //outdoor th2 0x9c06, //4s_limit 0x9dd6, // 0x9e00, //4s_unit 0x9ffa, // 0xb014, // 0xb114, // 08->14 0xb2b0, // a0->e0 0xb314, // 0xb414, // 0xb538, // 0xb626, // 0xb720, // 0xb81d, // 0xb91b, // 0xba1a, // 0xbb19, // 0xbc19, // 0xbd18, // 0xc014, //skygain 0xc8b0, // 0xc980, // //Page22 AWB 0x0322, // 0x10e2, 0x1126, // AD CMC off 0x2140, // 0x3080, // 0x3180, // 0x3811, // 0x3933, 0x40f0, // 0x4133, 0x4233, 0x43f3, // 0x4455, 0x4544, 0x4602, // 0x8040, // 0x8120, // 0x8243, // 0x8366, // RMAX Default : 50 0x841f, // RMIN Default : 20 0x8561, // BMAX Default : 50 0x8620, // BMIN Default : 20 0x8750, // RMAXB Default : 50 0x8845, // RMINB Default : 3e 0x892d, // BMAXB Default : 2e 0x8a22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, //AWB On 0x10fb, 0x0320, //AE On 0x108c, 0x01f0, }; /************** Exposure Value Setting ****************/ /* * EV bias */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /* * EV bias for VT */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_vt_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_vt_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_vt_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_vt_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_vt_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_vt_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_vt_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_vt_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_vt_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /************** White Balance Setting ******************/ static unsigned short SR030pc30_wb_auto[] = { 0x0322, 0x10e2, 0x1126, 0x8045, 0x8120, 0x8248, 0x8366, //66 RMAX Default : 50 0x8426, //28 26 RMIN Default : 20 0x8555, //58 5a BMAX Default : 50 0x8620, //20 BMIN Default : 20 0x10fb, }; static unsigned short SR030pc30_wb_tungsten[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_fluorescent[] = { 0x0322, 0x107b, 0x1126, 0x8042, 0x8120, 0x8251, 0x834a, //4c 4e RMAX 0x843a, //40 0x8555, //58 0x8645, //48 4a BMIN 0x10fb, }; static unsigned short SR030pc30_wb_sunny[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_cloudy[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x837f, //7f 7d 0x8470, //7d 7d 7f RMIN 0x851f, //1c 1e 1a 21 BMAX 0x8610, //10 1e 0x10fb, }; /************** Effect Setting ********************/ static unsigned short SR030pc30_effect_none[] = { 0x0310, 0x1103, 0x1230, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_gray[] = { 0x0310, 0x1103, 0x1233, 0x4480, 0x4580, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_sepia[] = { 0x0310, 0x1103, 0x1233, 0x4470, 0x4598, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_negative[] = { 0x0310, 0x1103, 0x1238, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_aqua[] = { 0x0310, 0x1103, 0x1233, 0x44b0, 0x4540, 0x0313, 0x103b, 0x2002, }; /************** Blur Setting ********************/ /*Self shot*/ static unsigned short SR030pc30_blur_none[] = { 0x0316, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, }; static unsigned short SR030pc30_blur_p1[] = { 0x0316, 0x3000, 0x3115, 0x3225, 0x3344, 0x3476, 0x359c, 0x36b8, 0x37cd, 0x38db, 0x39e6, 0x3aed, 0x3bf7, 0x3cfc, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_p2[] = { 0x0316, 0x3000, 0x3118, 0x322e, 0x3357, 0x3495, 0x35bd, 0x36d6, 0x37e5, 0x38ef, 0x39f5, 0x3af9, 0x3bfd, 0x3cfe, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_p3[] = { 0x0316, 0x3000, 0x311b, 0x3238, 0x336c, 0x34b0, 0x35d4, 0x36e8, 0x37f2, 0x38f8, 0x39fb, 0x3afd, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; /*vt call*/ static unsigned short SR030pc30_blur_vt_none[] = { 0x0316, 0x1001, 0x3000, 0x3119, 0x3226, 0x333b, 0x345d, 0x3579, 0x368e, 0x379f, 0x38af, 0x39bd, 0x3aca, 0x3bdd, 0x3cec, 0x3df7, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p1[] = { 0x0316, 0x3000, 0x3119, 0x3226, 0x3341, 0x3472, 0x3597, 0x36b3, 0x37c8, 0x38d7, 0x39e3, 0x3aeb, 0x3bf5, 0x3cfb, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p2[] = { 0x0316, 0x3000, 0x3119, 0x322c, 0x3356, 0x3496, 0x35bf, 0x36d8, 0x37e8, 0x38f1, 0x39f6, 0x3afa, 0x3bfd, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p3[] = { 0x0316, 0x3000, 0x311a, 0x323a, 0x3374, 0x34bd, 0x35e0, 0x36f0, 0x37f8, 0x38fc, 0x39fd, 0x3afe, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_dataline[] = { 0x0300, 0x5005, //Test Pattern //0x5001, //Test Pattern 0x0311, 0x1098, 0x0312, 0x4022, 0x701c, 0x0313, 0x103a, 0x800c, 0x0314, 0x1000, 0x0315, 0x1002, 0x0316, 0x1000, 0x0320, 0x100c, 0x0322, 0x107b, }; static unsigned short SR030pc30_dataline_stop[] = { 0x0300, 0x5000, //Test Pattern 0x0311, 0x1099, 0x0312, 0x4023, 0x701d, 0x0313, 0x103b, 0x800d, 0x0314, 0x1001, 0x0315, 0x1003, 0x0316, 0x1001, 0x0320, 0x108c, 0x0322, 0x10fb, }; /************** FPS********************/ static unsigned short SR030pc30_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_10[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05, 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_10[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; #endif //org #if 0 // CAMSYS 0524 VGA rotation static unsigned short SR030pc30_init_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, //Page0 0x0300, 0x1000, 0x11b3, //On Var Frame - None : 90, X Flip : 91, Y Flip : 0x1224,//PCLK Inversion 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 336 0x4150, 0x4201, //Vblank 300 0x432c, //BLC 0x803e, 0x8196, 0x8290, 0x8300, 0x842c, 0x900f, //BLC_TIME_TH_ON 0x910f, //BLC_TIME_TH_OFF 0x9278, //BLC_AG_TH_ON 0x9370, //BLC_AG_TH_OFF 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, //Page2 0x0302, 0x1000, 0x1300, 0x181C, 0x1900, 0x1a00, 0x1b08, 0x1C00, 0x1D00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343C, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639E, 0x6478, 0x659E, 0x727A, 0x739A, 0x747A, 0x759A, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81D, 0xaa49, 0xb98A, 0xbb8A, 0xbc04, 0xbd10, 0xbe04, 0xbf10, //Page10 0x0310,// 0x1001,//ISPCTL1 0x1230,//Y offet, dy offseet enable 0x4080, 0x4105,// 0x5078,// 0x601f, 0x6180, 0x6280, 0x63f0, 0x6480, //Page11 0x0311, 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, //Page12 0x0312, 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, //Page13 0x0313, 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800D, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, //Page14 0x0314, 0x1001, 0x2080, 0x2178, 0x2253, 0x2340, 0x243e, //Page 15 CmC 0x0315, 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, 0x1001, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, //Page20 AE 0x0320, 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2af0, 0x2bf4, 0x30f8, 0x60d5, 0x6834, 0x696e, 0x6A28, 0x6Bc8, 0x7034,//Y Target 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8300,//ExpTime 30fps 0x84c3, 0x8550, 0x8600,//ExpMin 0x87fa, 0x8802,//ExpMax 8fps(10fps) 0x8949, 0x8af0, 0x8b3a,//Exp100 0x8c98, 0x8d30,//Exp120 0x8ed4, 0x8f04, 0x9093, 0x9102, 0x92d2, 0x93a8, 0x988C, 0x9923, 0x9c05, //EXP Limit 1000.00 fps 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0xb014, 0xb114, 0xb2d0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc870, 0xc980, //Page 22 AWB 0x0322, 0x10e2, 0x1126, 0x2104, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x50d0, 0x51a0, 0x52aa, 0x8045, 0x8120, 0x8248, 0x8354,//54 0x8422,//22 29 27 0x8552,//54 53 50 0x8620,//22 0x874c, 0x8834, 0x8930, 0x8a22, 0x8b00, 0x8d22, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x0300, 0x11b3, //3 Bad frame skip, Fixed disable 0x01f0, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x11b7, //Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2263, // 53 0x2350, // 40 0x244e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 30.00 fps 0x84c3, 0x8550, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x01f0, 0xFFFF, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt2_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x11b7,//Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2263, // 53 0x2350, // 40 0x244e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 30.00 fps 0x84c3, 0x8550, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x01f0, 0xFFFF, }; /************** Exposure Value Setting ****************/ /* * EV bias */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /* * EV bias for VT */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_vt_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_vt_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_vt_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_vt_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_vt_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_vt_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_vt_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_vt_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_vt_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /************** White Balance Setting ******************/ static unsigned short SR030pc30_wb_auto[] = { 0x0322, 0x10e2, 0x1126, 0x8045, 0x8120, 0x8248, 0x8366, //66 RMAX Default : 50 0x8426, //28 26 RMIN Default : 20 0x8555, //58 5a BMAX Default : 50 0x8620, //20 BMIN Default : 20 0x10fb, }; static unsigned short SR030pc30_wb_tungsten[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_fluorescent[] = { 0x0322, 0x107b, 0x1126, 0x8042, 0x8120, 0x8251, 0x834a, //4c 4e RMAX 0x843a, //40 0x8555, //58 0x8645, //48 4a BMIN 0x10fb, }; static unsigned short SR030pc30_wb_sunny[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_cloudy[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x837f, //7f 7d 0x8470, //7d 7d 7f RMIN 0x851f, //1c 1e 1a 21 BMAX 0x8610, //10 1e 0x10fb, }; /************** Effect Setting ********************/ static unsigned short SR030pc30_effect_none[] = { 0x0310, 0x1103, 0x1230, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_gray[] = { 0x0310, 0x1103, 0x1233, 0x4480, 0x4580, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_sepia[] = { 0x0310, 0x1103, 0x1233, 0x4470, 0x4598, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_negative[] = { 0x0310, 0x1103, 0x1238, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_aqua[] = { 0x0310, 0x1103, 0x1233, 0x44b0, 0x4540, 0x0313, 0x103b, 0x2002, }; /************** Blur Setting ********************/ /*Self shot*/ static unsigned short SR030pc30_blur_none[] = { 0x0316, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, }; static unsigned short SR030pc30_blur_p1[] = { 0x0316, 0x3000, 0x3115, 0x3225, 0x3344, 0x3476, 0x359c, 0x36b8, 0x37cd, 0x38db, 0x39e6, 0x3aed, 0x3bf7, 0x3cfc, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_p2[] = { 0x0316, 0x3000, 0x3118, 0x322e, 0x3357, 0x3495, 0x35bd, 0x36d6, 0x37e5, 0x38ef, 0x39f5, 0x3af9, 0x3bfd, 0x3cfe, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_p3[] = { 0x0316, 0x3000, 0x311b, 0x3238, 0x336c, 0x34b0, 0x35d4, 0x36e8, 0x37f2, 0x38f8, 0x39fb, 0x3afd, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; /*vt call*/ static unsigned short SR030pc30_blur_vt_none[] = { 0x0316, 0x1001, 0x3000, 0x3119, 0x3226, 0x333b, 0x345d, 0x3579, 0x368e, 0x379f, 0x38af, 0x39bd, 0x3aca, 0x3bdd, 0x3cec, 0x3df7, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p1[] = { 0x0316, 0x3000, 0x3119, 0x3226, 0x3341, 0x3472, 0x3597, 0x36b3, 0x37c8, 0x38d7, 0x39e3, 0x3aeb, 0x3bf5, 0x3cfb, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p2[] = { 0x0316, 0x3000, 0x3119, 0x322c, 0x3356, 0x3496, 0x35bf, 0x36d8, 0x37e8, 0x38f1, 0x39f6, 0x3afa, 0x3bfd, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p3[] = { 0x0316, 0x3000, 0x311a, 0x323a, 0x3374, 0x34bd, 0x35e0, 0x36f0, 0x37f8, 0x38fc, 0x39fd, 0x3afe, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_dataline[] = { 0x0300, 0x5005, //Test Pattern 0x0311, 0x1098, 0x0312, 0x4022, 0x701c, 0x0313, 0x103a, 0x800c, 0x0314, 0x1000, 0x0315, 0x1002, 0x0316, 0x1000, 0x0320, 0x100c, 0x0322, 0x107b, }; static unsigned short SR030pc30_dataline_stop[] = { 0x0300, 0x5000, //Test Pattern 0x0311, 0x1099, 0x0312, 0x4023, 0x701d, 0x0313, 0x103b, 0x800d, 0x0314, 0x1001, 0x0315, 0x1003, 0x0316, 0x1001, 0x0320, 0x108c, 0x0322, 0x10fb, }; /************** FPS********************/ static unsigned short SR030pc30_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b3,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b7, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_10[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b3,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05, 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b7, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b3,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b7, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b3,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b7, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_10[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b3,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b7, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b3,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b7, //Fixed enable 0x01f0, //Sleep Off }; #endif #if 1 //LSI 1019 flicker static unsigned short SR030pc30_init_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x101c, 0x0322, 0x107b, //Page0 0x0300, 0x0baa, 0x0caa, 0x0daa, 0x1000, 0x1190, //On Var Frame - None : 90, X Flip : 91, Y Flip : 0x1224, //PCLK Inversion 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 336 0x4150, 0x4201, //Vblank 336 0x4350, //BLC 0x803e, 0x8196, 0x8290, 0x8300, 0x842c, 0x900f, //BLC_TIME_TH_ON 0x910f, //BLC_TIME_TH_OFF 0x9278, //BLC_AG_TH_ON 0x9370, //BLC_AG_TH_OFF 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, //Page2 0x0302, 0x1000, 0x1300, 0x181C, 0x1900, 0x1a00, 0x1b08, 0x1C00, 0x1D00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343C, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639E, 0x6478, 0x659E, 0x727A, 0x739A, 0x747A, 0x759A, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81D, 0xaa49, 0xb98A, 0xbb8A, 0xbc04, 0xbd10, 0xbe04, 0xbf10, //Page10 0x0310,// 0x1001,//ISPCTL1 0x1230,//Y offet, dy offseet enable 0x4080, 0x4105,// 0x5078,// 0x601f, 0x6180, 0x6280, 0x63f0, 0x6480, //Page11 0x0311, 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, //Page12 0x0312, 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, //Page13 0x0313, 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800D, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, //Page14 0x0314, 0x1001, 0x2080, 0x2178, 0x2253, 0x2340, 0x243e, //Page 15 CmC 0x0315, 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, 0x1001, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, //Page20 AE 0x0320, 0x101c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2af0, 0x2bf4, 0x30f8, 0x60d5, 0x6834, 0x696e, 0x6A28, 0x6Bc8, 0x7034,//Y Target 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8300,//ExpTime 30fps 0x84af, 0x85c8, 0x8600,//ExpMin 0x87fa, 0x8802,//ExpMax 8fps(10fps) 0x8949, 0x8af0, 0x8b3a,//Exp100 0x8c98, 0x8d30,//Exp120 0x8ed4, 0x8f04, 0x9093, 0x9102, 0x92d2, 0x93a8, 0x988C, 0x9923, 0x9c05, //EXP Limit 1000.00 fps 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0xb014, 0xb114, 0xb2d0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc870, 0xc980, //Page 22 AWB 0x0322, 0x10e2, 0x1126, 0x2104, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x50d0, 0x51a0, 0x52aa, 0x8045, 0x8120, 0x8248, 0x8354,//54 0x8420,//22 29 27 0x8552,//54 53 50 0x8620,//22 0x874c, 0x8834, 0x8930, 0x8a22, 0x8b00, 0x8d22, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x109c, 0x0300, 0x01f0, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x101c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x1194, //Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2253, // 53 0x2340, // 40 0x243e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x101c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 33.33 fps 0x84af, 0x85c8, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x109c, 0x01f0, 0xFFFF, }; static unsigned short SR030pc30_preview_640x480[] = { 0x0300, 0x01f1, 0x1000, 0x01f0, 0x1190, 0xffff, }; static unsigned short SR030pc30_preview_320x240[] = { 0x0300, 0x01f1, 0x1010, 0x01f0, 0x1190, 0xffff, }; static unsigned short SR030pc30_FLIP_NONE_640x480[] = { 0x0300, 0x1190, //90, //B[1:0] 00: Flip None, 01:X Flip, 02:Y Flip, 03:XY Flip 0xffff, }; static unsigned short SR030pc30_FLIP_MIRROR_640x480[] = { 0x0300, 0x1193, //93, //B[1:0] 00: Flip None, 01:X Flip, 02:Y Flip, 03:XY Flip 0xffff, }; /************** Exposure Value Setting ****************/ /* * EV bias */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /* * EV bias for VT */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_vt_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_vt_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_vt_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_vt_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_vt_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_vt_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_vt_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_vt_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_vt_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /************** White Balance Setting ******************/ static unsigned short SR030pc30_wb_auto[] = { 0x0322, 0x10e2, 0x1126, 0x8045, 0x8120, 0x8248, 0x8354, //66 RMAX Default : 50 0x8420, //28 26 RMIN Default : 20 0x8552, //58 5a BMAX Default : 50 0x8620, //20 BMIN Default : 20 0x10fb, }; static unsigned short SR030pc30_wb_tungsten[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_fluorescent[] = { 0x0322, 0x107b, 0x1126, 0x8042, 0x8120, 0x8251, 0x834a, //4c 4e RMAX 0x843a, //40 0x8555, //58 0x8645, //48 4a BMIN 0x10fb, }; static unsigned short SR030pc30_wb_sunny[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_cloudy[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x837f, //7f 7d 0x8470, //7d 7d 7f RMIN 0x851f, //1c 1e 1a 21 BMAX 0x8610, //10 1e 0x10fb, }; /************** Effect Setting ********************/ static unsigned short SR030pc30_effect_none[] = { 0x0310, 0x1103, 0x1230, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_gray[] = { 0x0310, 0x1103, 0x1233, 0x4480, 0x4580, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_sepia[] = { 0x0310, 0x1103, 0x1233, 0x4470, 0x4598, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_negative[] = { 0x0310, 0x1103, 0x1238, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_aqua[] = { 0x0310, 0x1103, 0x1233, 0x44b0, 0x4540, 0x0313, 0x103b, 0x2002, }; /************** Blur Setting ********************/ /*Self shot*/ static unsigned short SR030pc30_blur_none[] = { 0x0316, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, }; static unsigned short SR030pc30_blur_p1[] = { 0x0316, 0x3000, 0x3115, 0x3225, 0x3344, 0x3476, 0x359c, 0x36b8, 0x37cd, 0x38db, 0x39e6, 0x3aed, 0x3bf7, 0x3cfc, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_p2[] = { 0x0316, 0x3000, 0x3118, 0x322e, 0x3357, 0x3495, 0x35bd, 0x36d6, 0x37e5, 0x38ef, 0x39f5, 0x3af9, 0x3bfd, 0x3cfe, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_p3[] = { 0x0316, 0x3000, 0x311b, 0x3238, 0x336c, 0x34b0, 0x35d4, 0x36e8, 0x37f2, 0x38f8, 0x39fb, 0x3afd, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; /*vt call*/ static unsigned short SR030pc30_blur_vt_none[] = { 0x0316, 0x1001, 0x3000, 0x3119, 0x3226, 0x333b, 0x345d, 0x3579, 0x368e, 0x379f, 0x38af, 0x39bd, 0x3aca, 0x3bdd, 0x3cec, 0x3df7, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p1[] = { 0x0316, 0x3000, 0x3119, 0x3226, 0x3341, 0x3472, 0x3597, 0x36b3, 0x37c8, 0x38d7, 0x39e3, 0x3aeb, 0x3bf5, 0x3cfb, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p2[] = { 0x0316, 0x3000, 0x3119, 0x322c, 0x3356, 0x3496, 0x35bf, 0x36d8, 0x37e8, 0x38f1, 0x39f6, 0x3afa, 0x3bfd, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p3[] = { 0x0316, 0x3000, 0x311a, 0x323a, 0x3374, 0x34bd, 0x35e0, 0x36f0, 0x37f8, 0x38fc, 0x39fd, 0x3afe, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_dataline[] = { 0x0300, 0x5005, //Test Pattern 0x0311, 0x1098, 0x0312, 0x4022, 0x701c, 0x0313, 0x103a, 0x800c, 0x0314, 0x1000, 0x0315, 0x1002, 0x0316, 0x1000, 0x0320, 0x101c, 0x0322, 0x107b, }; static unsigned short SR030pc30_dataline_stop[] = { 0x0300, 0x5000, //Test Pattern 0x0311, 0x1099, 0x0312, 0x4023, 0x701d, 0x0313, 0x103b, 0x800d, 0x0314, 0x1001, 0x0315, 0x1003, 0x0316, 0x1001, 0x0320, 0x109c, 0x0322, 0x10fb, }; /************** FPS********************/ static unsigned short SR030pc30_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x1190,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x101c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x109c, // AE on 0x0300, 0x1000, 0x1197, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_10[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x1190,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x101c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05, 0x9d5f, 0x9e00,//4 0x9ffa, 0x109c, // AE on 0x0300, 0x1197, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x1190,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x101c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x109c, // AE on 0x0300, 0x1197, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x1190,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x101c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x109c, // AE on 0x0300, 0x1000, 0x1197, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_10[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x1190,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x101c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x109c, // AE on 0x0300, 0x1000, 0x1197, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x1190,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x101c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x109c, // AE on 0x0300, 0x1197, //Fixed enable 0x01f0, //Sleep Off }; #endif #if 0 //camsys 0525 static unsigned short SR030pc30_init_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, //Page0 0x0300, 0x1000, 0x11b1, //On Var Frame - None : 90, X Flip : 91, Y Flip : 0x1224,//PCLK Inversion 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 336 0x4150, 0x4201, //Vblank 300 0x432c, //BLC 0x803e, 0x8196, 0x8290, 0x8300, 0x842c, 0x900f, //BLC_TIME_TH_ON 0x910f, //BLC_TIME_TH_OFF 0x9278, //BLC_AG_TH_ON 0x9370, //BLC_AG_TH_OFF 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, //Page2 0x0302, 0x1000, 0x1300, 0x181C, 0x1900, 0x1a00, 0x1b08, 0x1C00, 0x1D00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343C, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639E, 0x6478, 0x659E, 0x727A, 0x739A, 0x747A, 0x759A, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81D, 0xaa49, 0xb98A, 0xbb8A, 0xbc04, 0xbd10, 0xbe04, 0xbf10, //Page10 0x0310,// 0x1001,//ISPCTL1 0x1230,//Y offet, dy offseet enable 0x4080, 0x4105,// 0x5078,// 0x601f, 0x6180, 0x6280, 0x63f0, 0x6480, //Page11 0x0311, 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, //Page12 0x0312, 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, //Page13 0x0313, 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800D, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, //Page14 0x0314, 0x1001, 0x2080, 0x2178, 0x2253, 0x2340, 0x243e, //Page 15 CmC 0x0315, 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, 0x1001, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, //Page20 AE 0x0320, 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2af0, 0x2bf4, 0x30f8, 0x60d5, 0x6834, 0x696e, 0x6A28, 0x6Bc8, 0x7034,//Y Target 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8300,//ExpTime 30fps 0x84c3, 0x8550, 0x8600,//ExpMin 0x87fa, 0x8802,//ExpMax 8fps(10fps) 0x8949, 0x8af0, 0x8b3a,//Exp100 0x8c98, 0x8d30,//Exp120 0x8ed4, 0x8f04, 0x9093, 0x9102, 0x92d2, 0x93a8, 0x988C, 0x9923, 0x9c05, //EXP Limit 1000.00 fps 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0xb014, 0xb114, 0xb2d0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc870, 0xc980, //Page 22 AWB 0x0322, 0x10e2, 0x1126, 0x2104, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x50d0, 0x51a0, 0x52aa, 0x8045, 0x8120, 0x8248, 0x8354,//54 0x8422,//22 29 27 0x8552,//54 53 50 0x8620,//22 0x874c, 0x8834, 0x8930, 0x8a22, 0x8b00, 0x8d22, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x0300, 0x11b1, //3 Bad frame skip, Fixed disable 0x01f0, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x11b5, //Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2263, // 53 0x2350, // 40 0x244e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 30.00 fps 0x84c3, 0x8550, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x01f0, 0xFFFF, }; //========================================================== // CAMERA INITIAL for WIFI CALL (QIK) Preview 15 Fixed Frame (VGA SETTING) //========================================================== static unsigned short SR030pc30_init_vt2_reg[] = { 0x0300, 0x01f1, 0x01f3, 0x01f1, 0x0320, 0x100c, 0x0322, 0x107b, 0x0300, //Page 0 0x1000, //no change(v sync type) 0x11b5, //Fixed On(fixed frame enable : BIT 2) 0x1204, //00, 0x2000, 0x2106, 0x2200, 0x2306, 0x2401, 0x25e0, 0x2602, 0x2780, 0x4001, //Hblank 360 0x4150, // 0x4200, //Vsync 4 0x4304, // 0x803e, //BLC 0x8196, 0x8290, 0x8300, 0x842c, 0x900e, 0x910f, 0x923a, 0x9330, 0x9488, 0x9580, 0x9820, 0xa040, 0xa241, 0xa440, 0xa641, 0xa844, 0xaa43, 0xac44, 0xae43, 0x0302, //Page 2 0x1000, 0x1300, 0x181c, 0x1900, 0x1a00, 0x1b08, 0x1c00, 0x1d00, 0x2033, 0x21aa, 0x22a6, 0x23b0, 0x3199, 0x3200, 0x3300, 0x343c, 0x5021, 0x5430, 0x56fe, 0x6278, 0x639e, 0x6478, 0x659e, 0x727a, 0x739a, 0x747a, 0x759a, 0x8209, 0x8409, 0x8609, 0xa003, 0xa81d, 0xaa49, 0xb98a, 0xbb8a, 0xbc04, 0xbd10, 0xbe04, 0xbf10, 0x0310, //Page 10 0x1001, //ISPCTL1, YUV ORDER(FIX) 0x1230, //Y offet, dy offseet enable 0x4009, //80 0x4138, //00 DYOFS 0x50ee, 0x601f, 0x6190, 0x6280, 0x63f0, 0x6480, 0x0311, //Page 11 0x1099, 0x110e, 0x2129, 0x5005, 0x600f, 0x6243, 0x6363, 0x7408, 0x7508, 0x0312, //Page 12 0x4023, 0x413b, 0x5005, 0x701d, 0x7405, 0x7504, 0x7720, 0x7810, 0x9134, 0xb0c9, 0xd0b1, 0x0313, //Page 13 0x103b, 0x1103, 0x1200, 0x1302, 0x1418, 0x2002, 0x2101, 0x2324, 0x2406, 0x254a, 0x2800, 0x2978, 0x30ff, 0x800d, 0x8113, 0x835d, 0x9003, 0x9102, 0x933d, 0x9403, 0x958f, 0x0314, //Page 14 0x1001, 0x2080, 0x2178, 0x2263, // 53 0x2350, // 40 0x244e, // 3e 0x0315, //Page 15 CMC 0x1003, 0x143c, 0x162c, 0x172f, 0x30cb, 0x3161, 0x3216, 0x3323, 0x34ce, 0x352b, 0x3601, 0x3734, 0x3875, 0x4087, 0x4118, 0x4291, 0x4394, 0x449f, 0x4533, 0x4600, 0x4794, 0x4814, 0x0316, //page 16 gamma 0x1001, 0x3000, 0x3109, // 0b / 0x3217, // 19 / 0x3335, 0x3460, // 5d / 0x3582, // 7a / 0x3696, // 93 / 0x37a7, 0x38b8, 0x39c6, 0x3ad4, 0x3be7, 0x3cf5, 0x3dfc, 0x3eff, 0x0320, //Page 20 AE 0x100c, 0x1104, 0x2001, 0x283f, 0x29a3, 0x2a90, 0x2bf5, 0x30f8, 0x60d5, //d5, 99 0x683c, 0x6964, 0x6a28, 0x6bc8, 0x7034, //30 normal luminance value 42(Y Target) 0x7812, //Yth 1 0x7913, //Yth 2 0x7a23, 0x8300, //EXP Normal 30.00 fps 0x84c3, 0x8550, 0x8600, //EXPMin 6000.00 fps 0x87fa, 0x8800, //EXP Max 24.00 fps 0x89f4, 0x8a24, 0x8b3a, //EXP100 0x8c98, 0x8d30, //EXP120 0x8ed4, 0x8f04, 0x9093, 0x9101, //EXP Fix 15.02 fps 0x9284, 0x932f, 0x988c, 0x9923, 0x9c08, //EXP Limit 666.67 fps 0x9dca, 0x9e00, //EXP Unit 0x9ffa, 0xb014, 0xb114, 0xb2f0, 0xb314, 0xb41c, 0xb548, 0xb632, 0xb72b, 0xb827, 0xb925, 0xba23, 0xbb22, 0xbc22, 0xbd21, 0xc014, 0xc8f0, //digital global gain 80 0xc980, 0x0322, //Page 22 AWB 0x10e2, 0x1126, 0x2140, 0x3080, 0x3180, 0x3811, 0x3933, 0x40f0, 0x4133, 0x4233, 0x43f3, 0x4455, 0x4544, 0x4602, 0x8045, 0x8120, 0x8248, 0x8366, // RMAX Default : 50 0x8420, //1c 20 1E / // RMIN Default : 20 0x855d, //5b 5e 6a, // BMAX Default : 50 0x861f, // BMIN Default : 20 0x8747, //49, //4a, //50, // RMAXB Default : 50 0x8844, //45, //3e, //40, //45, // RMINB Default : 3e 0x892f, //2d, //2e, //2d, //30, //2d, // BMAXB Default : 2e 0x8a26, //28, //22, // BMINB Default : 20 0x8b00, 0x8d21, 0x8e71, 0x8f63, 0x9060, 0x915c, 0x9259, 0x9355, 0x9450, 0x9548, 0x963e, 0x9737, 0x9830, 0x9929, 0x9a26, 0x9b09, 0x0322, 0x10fb, 0x0320, 0x108c, 0x01f0, 0xFFFF, }; /************** Exposure Value Setting ****************/ /* * EV bias */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /* * EV bias for VT */ #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_m5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ static unsigned short SR030pc30_ev_vt_m4[] = { 0x0310, 0x40d0, }; static unsigned short SR030pc30_ev_vt_m3[] = { 0x0310, 0x40B0, }; static unsigned short SR030pc30_ev_vt_m2[] = { 0x0310, 0x40A0, }; static unsigned short SR030pc30_ev_vt_m1[] = { 0x0310, 0x4090, }; static unsigned short SR030pc30_ev_vt_default[] = { 0x0310, 0x4080, }; static unsigned short SR030pc30_ev_vt_p1[] = { 0x0310, 0x4010, }; static unsigned short SR030pc30_ev_vt_p2[] = { 0x0310, 0x4020, }; static unsigned short SR030pc30_ev_vt_p3[] = { 0x0310, 0x4030, }; static unsigned short SR030pc30_ev_vt_p4[] = { 0x0310, 0x4050, }; #if 0 /* unused variables */ static unsigned short SR030pc30_ev_vt_p5[] = { 0x0310, 0x40d0, }; #endif /* unused variables */ /************** White Balance Setting ******************/ static unsigned short SR030pc30_wb_auto[] = { 0x0322, 0x10e2, 0x1126, 0x8045, 0x8120, 0x8248, 0x8366, //66 RMAX Default : 50 0x8426, //28 26 RMIN Default : 20 0x8555, //58 5a BMAX Default : 50 0x8620, //20 BMIN Default : 20 0x10fb, }; static unsigned short SR030pc30_wb_tungsten[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_fluorescent[] = { 0x0322, 0x107b, 0x1126, 0x8042, 0x8120, 0x8251, 0x834a, //4c 4e RMAX 0x843a, //40 0x8555, //58 0x8645, //48 4a BMIN 0x10fb, }; static unsigned short SR030pc30_wb_sunny[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x8353, 0x8448, 0x8535, 0x862b, 0x10fb, 0xffff, }; static unsigned short SR030pc30_wb_cloudy[] = { 0x0322, 0x107b, 0x1126, 0x8052, 0x8120, 0x8230, 0x837f, //7f 7d 0x8470, //7d 7d 7f RMIN 0x851f, //1c 1e 1a 21 BMAX 0x8610, //10 1e 0x10fb, }; /************** Effect Setting ********************/ static unsigned short SR030pc30_effect_none[] = { 0x0310, 0x1103, 0x1230, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_gray[] = { 0x0310, 0x1103, 0x1233, 0x4480, 0x4580, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_sepia[] = { 0x0310, 0x1103, 0x1233, 0x4470, 0x4598, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_negative[] = { 0x0310, 0x1103, 0x1238, 0x0313, 0x103b, 0x2002, }; static unsigned short SR030pc30_effect_aqua[] = { 0x0310, 0x1103, 0x1233, 0x44b0, 0x4540, 0x0313, 0x103b, 0x2002, }; /************** Blur Setting ********************/ /*Self shot*/ static unsigned short SR030pc30_blur_none[] = { 0x0316, 0x3000, 0x3109, 0x321b, 0x3335, 0x345d, 0x357a, 0x3693, 0x37a7, 0x38b8, 0x39c6, 0x3ad2, 0x3be4, 0x3cf1, 0x3df9, 0x3eff, }; static unsigned short SR030pc30_blur_p1[] = { 0x0316, 0x3000, 0x3115, 0x3225, 0x3344, 0x3476, 0x359c, 0x36b8, 0x37cd, 0x38db, 0x39e6, 0x3aed, 0x3bf7, 0x3cfc, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_p2[] = { 0x0316, 0x3000, 0x3118, 0x322e, 0x3357, 0x3495, 0x35bd, 0x36d6, 0x37e5, 0x38ef, 0x39f5, 0x3af9, 0x3bfd, 0x3cfe, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_p3[] = { 0x0316, 0x3000, 0x311b, 0x3238, 0x336c, 0x34b0, 0x35d4, 0x36e8, 0x37f2, 0x38f8, 0x39fb, 0x3afd, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; /*vt call*/ static unsigned short SR030pc30_blur_vt_none[] = { 0x0316, 0x1001, 0x3000, 0x3119, 0x3226, 0x333b, 0x345d, 0x3579, 0x368e, 0x379f, 0x38af, 0x39bd, 0x3aca, 0x3bdd, 0x3cec, 0x3df7, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p1[] = { 0x0316, 0x3000, 0x3119, 0x3226, 0x3341, 0x3472, 0x3597, 0x36b3, 0x37c8, 0x38d7, 0x39e3, 0x3aeb, 0x3bf5, 0x3cfb, 0x3dfe, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p2[] = { 0x0316, 0x3000, 0x3119, 0x322c, 0x3356, 0x3496, 0x35bf, 0x36d8, 0x37e8, 0x38f1, 0x39f6, 0x3afa, 0x3bfd, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_blur_vt_p3[] = { 0x0316, 0x3000, 0x311a, 0x323a, 0x3374, 0x34bd, 0x35e0, 0x36f0, 0x37f8, 0x38fc, 0x39fd, 0x3afe, 0x3bff, 0x3cff, 0x3dff, 0x3eff, }; static unsigned short SR030pc30_dataline[] = { 0x0300, 0x5005, //Test Pattern 0x0311, 0x1098, 0x0312, 0x4022, 0x701c, 0x0313, 0x103a, 0x800c, 0x0314, 0x1000, 0x0315, 0x1002, 0x0316, 0x1000, 0x0320, 0x100c, 0x0322, 0x107b, }; static unsigned short SR030pc30_dataline_stop[] = { 0x0300, 0x5000, //Test Pattern 0x0311, 0x1099, 0x0312, 0x4023, 0x701d, 0x0313, 0x103b, 0x800d, 0x0314, 0x1001, 0x0315, 0x1003, 0x0316, 0x1001, 0x0320, 0x108c, 0x0322, 0x10fb, }; /************** FPS********************/ static unsigned short SR030pc30_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_10[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05, 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_7[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4s limit 0x9d5f, 0x9e00,//4s unit 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_10[] = { 0x0300, //7 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x7034, // Ylvl 34 0x7911, // yth2 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9103,//Fixed 7 FPS frame 0x923b, 0x9349, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x1000, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; static unsigned short SR030pc30_vt_fps_15[] = { 0x0300, //15 Fix 0x1000, 0xffaa, //170ms 0x01f1,//Sleep On 0x11b1,//Fixed Disable 0x4001, //Hblank 336 0x4150, // 0x4200, //Vsync 20 0x4314, // 0x0320, 0x100c, // AE off 0x2a90, 0x2bf5, 0x30f8, 0x7034, // Ylvl 34 0x7812,//Yth 1 0x7911,//Yth 2 0x7A23, 0x8801,//Expmax 20fps 0x8924, 0x8af8, 0x9101,////Fixed 15 FPS frame 0x927c, 0x93dc, 0x9c05,//4 0x9d5f, 0x9e00,//4 0x9ffa, 0x108c, // AE on 0x0300, 0x11b5, //Fixed enable 0x01f0, //Sleep Off }; #endif //camsys 0525 #endif #endif //#ifndef CAMIF_REG_CONFIG_H_
SerkTheTurk/android_kernel_samsung_hugo
drivers/media/video/s5ka3dfx_tune.h
C
gpl-2.0
155,890
/* Copyright (C) 2013 - 2016 Boldizsár Lipka <lipkab@zoho.com> Part of the Battle for Wesnoth Project http://www.wesnoth.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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. See the COPYING file for more details. */ #ifndef MULTIPLAYER_CONFIGURE_HPP_INCLUDED #define MULTIPLAYER_CONFIGURE_HPP_INCLUDED #include "depcheck.hpp" #include "mp_game_settings.hpp" #include "multiplayer_ui.hpp" #include "widgets/slider.hpp" #include "widgets/scrollpane.hpp" #include "widgets/combo.hpp" #include "tooltips.hpp" #include "mp_options.hpp" #include "configure_engine.hpp" #include <boost/scoped_ptr.hpp> class saved_game; namespace mp { class configure : public mp::ui { public: ///gives the user the option to adjust the passed saved_game ///Call get_parameters to finalize; configure(CVideo& v, const config& game_config, chat& c, config& gamelist, saved_game& game, bool local_players_only); ~configure(); void get_parameters(); protected: virtual void layout_children(const SDL_Rect& rect); virtual void process_event(); virtual void hide_children(bool hide=true); private: //Settings that can be changed unledd wml forbids it struct nolock_settings { nolock_settings(CVideo& video); gui::slider turns_slider_; gui::label turns_label_; gui::slider village_gold_slider_; gui::label village_gold_label_; gui::slider village_support_slider_; gui::label village_support_label_; gui::slider xp_modifier_slider_; gui::label xp_modifier_label_; gui::label generic_label_; gui::button use_map_settings_; gui::button random_start_time_; gui::button fog_game_; gui::button shroud_game_; }; bool local_players_only_; tooltips::manager tooltip_manager_; int mp_countdown_init_time_; int mp_countdown_reservoir_time_; gui::button countdown_game_; gui::slider countdown_init_time_slider_; gui::label countdown_init_time_label_; gui::slider countdown_reservoir_time_slider_; gui::label countdown_reservoir_time_label_; gui::label countdown_turn_bonus_label_; gui::slider countdown_turn_bonus_slider_; gui::label countdown_action_bonus_label_; gui::slider countdown_action_bonus_slider_; gui::label name_entry_label_; gui::button observers_game_; gui::button oos_debug_; gui::button shuffle_sides_; gui::label random_faction_mode_label_; gui::combo random_faction_mode_; gui::button cancel_game_; gui::button launch_game_; gui::button password_button_; gui::textbox name_entry_; gui::label entry_points_label_; gui::combo entry_points_combo_; gui::scrollpane options_pane_left_; gui::scrollpane options_pane_right_; std::vector<config const*> entry_points_; bool show_entry_points_; bool force_use_map_settings_check_; saved_game& state_; mp_game_settings& parameters_; ng::configure_engine engine_; options::manager options_manager_; boost::scoped_ptr<nolock_settings> nolock_settings_; struct process_event_data { bool launch, quit; process_event_data() : launch(false), quit(false) {} process_event_data(bool l, bool q) : launch(l), quit(q) {} }; void process_event_impl(const process_event_data &); bool plugin_event_helper(const process_event_data &); }; } // end namespace mp #endif
suxinde2009/wesnoth
src/game_initialization/multiplayer_configure.hpp
C++
gpl-2.0
3,495
# # Copyright (C) 2006-2016 OpenWrt.org # # This is free software, licensed under the GNU General Public License v2. # See /LICENSE for more information. # include $(TOPDIR)/rules.mk PKG_NAME:=gst1-libav PKG_VERSION:=1.12.4 PKG_RELEASE:=1 PKG_MAINTAINER:=W. Michael Petullo <mike@flyn.org> \ Ted Hess <thess@kitschensync.net> PKG_SOURCE:=gst-libav-$(PKG_VERSION).tar.xz PKG_SOURCE_URL:=http://gstreamer.freedesktop.org/src/gst-libav PKG_HASH:=2a56aa5d2d8cd912f2bce17f174713d2c417ca298f1f9c28ee66d4aa1e1d9e62 PKG_LICENSE:=GPL-2.0 LGPL-2.0 PKG_LICENSE_FILES:=COPYING COPYING.LIB PKG_BUILD_DIR:=$(BUILD_DIR)/gst-libav-$(PKG_VERSION) PKG_FIXUP:=autoreconf PKG_INSTALL:=1 PKG_USE_MIPS16:=0 GST_VERSION:=1.0 LIBAV_ENCODERS:= \ ac3 \ jpegls \ mpeg1video \ mpeg2video \ mpeg4 \ pcm_s16be \ pcm_s16le \ png \ vorbis \ zlib \ LIBAV_DECODERS:= \ aac \ ac3 \ atrac3 \ gif \ h264 \ jpegls \ mp2 \ mp3 \ mpeg1video \ mpeg2video \ mpeg4 \ mpegvideo \ pcm_s16be \ pcm_s16le \ png \ vorbis \ wmav1 \ wmav2 \ zlib \ LIBAV_MUXERS:= \ ac3 \ ffm \ h264 \ mp3 \ mp4 \ mpeg1video \ mpeg2video \ mpegts \ ogg \ oss \ rtp \ LIBAV_DEMUXERS:= \ ac3 \ ffm \ h264 \ mp3 \ mpegps \ mpegts \ mpegvideo \ ogg \ rm \ rtsp \ sdp \ v4l2 \ LIBAV_PARSERS:= \ aac \ ac3 \ h264 \ mpegaudio \ mpegvideo \ mpeg4video \ LIBAV_PROTOCOLS:= \ file http pipe rtp tcp udp PKG_CONFIG_DEPENDS:= \ $(patsubst %,CONFIG_GST1_LIBAV_ENCODER_%,$(LIBAV_ENCODERS)) \ $(patsubst %,CONFIG_GST1_LIBAV_DECODER_%,$(LIBAV_DECODERS)) \ $(patsubst %,CONFIG_GST1_LIBAV_MUXER_%,$(LIBAV_DEMUXERS)) \ $(patsubst %,CONFIG_GST1_LIBAV_DEMUXER_%,$(LIBAV_DEMUXERS)) \ $(patsubst %,CONFIG_GST1_LIBAV_PARSER_%,$(LIBAV_PARSERS)) \ $(patsubst %,CONFIG_GST1_LIBAV_PROTOCOL_%,$(LIBAV_PROTOCOLS)) include $(INCLUDE_DIR)/package.mk include $(INCLUDE_DIR)/nls.mk define Package/gst1-libav SECTION:=multimedia CATEGORY:=Multimedia TITLE:=GStreamer Libav plugin URL:=http://www.gstreamer.net/modules/gst-libav.html DEPENDS:= +libgstreamer1 +gstreamer1-plugins-base \ +gst1-mod-alsa +libgst1audio +libgst1pbutils +libgst1video \ +libbz2 +liblzma endef define Package/gst1-libav/description GStreamer with libav bindings using internal Libav endef define Package/gst1-libav/config source "$(SOURCE)/Config.in" endef FILTER_CONFIG= \ $(foreach c, $(3), \ $(if $(CONFIG_GST1_LIBAV_$(1)_$(c)),--enable-$(2)='$(c)') \ ) LIBAV_CONFIGURE_ENCODERS:=$(call FILTER_CONFIG,ENCODER,encoder,$(LIBAV_ENCODERS)) LIBAV_CONFIGURE_DECODERS:=$(call FILTER_CONFIG,DECODER,decoder,$(LIBAV_DECODERS)) LIBAV_CONFIGURE_MUXERS:=$(call FILTER_CONFIG,MUXER,muxer,$(LIBAV_MUXERS)) LIBAV_CONFIGURE_DEMUXERS:=$(call FILTER_CONFIG,DEMUXER,demuxer,$(LIBAV_DEMUXERS)) LIBAV_CONFIGURE_PARSERS:=$(call FILTER_CONFIG,PARSER,parser,$(LIBAV_PARSERS)) LIBAV_CONFIGURE_PROTOCOLS:=$(call FILTER_CONFIG,PROTOCOL,protocol,$(LIBAV_PROTOCOLS)) # Strip off FPU notation REAL_CPU_TYPE:=$(firstword $(subst +, ,$(CONFIG_CPU_TYPE))) CONFIGURE_ARGS += \ --without-system-libav \ --with-libav-extra-configure=" \ $(if $(REAL_CPU_TYPE),--cpu=$(call qstrip,$(REAL_CPU_TYPE)),) \ --disable-bsfs \ --disable-programs \ --disable-devices \ --disable-encoders \ $(LIBAV_CONFIGURE_ENCODERS) \ --disable-decoders \ $(LIBAV_CONFIGURE_DECODERS) \ --disable-muxers \ $(LIBAV_CONFIGURE_MUXERS) \ --disable-demuxers \ $(LIBAV_CONFIGURE_DEMUXERS) \ --disable-parsers \ $(LIBAV_CONFIGURE_PARSERS) \ --disable-protocols \ $(LIBAV_CONFIGURE_PROTOCOLS) \ --disable-asm \ --disable-altivec \ --disable-amd3dnow \ --disable-amd3dnowext \ --disable-mmx \ --disable-mmxext \ --disable-sse \ --disable-sse2 \ --disable-sse3 \ --disable-ssse3 \ --disable-sse4 \ --disable-sse42 \ --disable-avx \ --disable-xop \ --disable-fma3 \ --disable-fma4 \ --disable-avx2 \ --disable-inline-asm \ --disable-yasm" TARGET_CFLAGS += -D_GNU_SOURCE TARGET_LDFLAGS += $(FPIC) define Package/gst1-libav/install $(INSTALL_DIR) $(1)/usr/lib/gstreamer-$(GST_VERSION) ( cd $(PKG_INSTALL_DIR); $(CP) \ ./usr/lib/gstreamer-$(GST_VERSION)/libgstlibav.so* \ $(1)/usr/lib/gstreamer-$(GST_VERSION)/ \ ) endef $(eval $(call BuildPackage,gst1-libav))
Entware-for-kernel-3x/entware-packages-3x
multimedia/gst1-libav/Makefile
Makefile
gpl-2.0
4,262
/* * Copyright (C) 2008 Ole André Vadla Ravnås <ole.andre.ravnas@tandberg.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-wasapisrc * * Provides audio capture from the Windows Audio Session API available with * Vista and newer. * * <refsect2> * <title>Example pipelines</title> * |[ * gst-launch-0.10 -v wasapisrc ! fakesink * ]| Capture from the default audio device and render to fakesink. * </refsect2> */ #include "gstwasapisrc.h" #include <gst/audio/gstaudioclock.h> GST_DEBUG_CATEGORY_STATIC (gst_wasapi_src_debug); #define GST_CAT_DEFAULT gst_wasapi_src_debug static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/x-raw-int, " "width = (int) 16, " "depth = (int) 16, " "rate = (int) 8000, " "channels = (int) 1, " "signed = (boolean) TRUE, " "endianness = (int) " G_STRINGIFY (G_BYTE_ORDER))); static void gst_wasapi_src_dispose (GObject * object); static void gst_wasapi_src_finalize (GObject * object); static GstClock *gst_wasapi_src_provide_clock (GstElement * element); static gboolean gst_wasapi_src_start (GstBaseSrc * src); static gboolean gst_wasapi_src_stop (GstBaseSrc * src); static gboolean gst_wasapi_src_query (GstBaseSrc * src, GstQuery * query); static GstFlowReturn gst_wasapi_src_create (GstPushSrc * src, GstBuffer ** buf); static GstClockTime gst_wasapi_src_get_time (GstClock * clock, gpointer user_data); GST_BOILERPLATE (GstWasapiSrc, gst_wasapi_src, GstPushSrc, GST_TYPE_PUSH_SRC); static void gst_wasapi_src_base_init (gpointer gclass) { GstElementClass *element_class = GST_ELEMENT_CLASS (gclass); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&src_template)); gst_element_class_set_static_metadata (element_class, "WasapiSrc", "Source/Audio", "Stream audio from an audio capture device through WASAPI", "Ole André Vadla Ravnås <ole.andre.ravnas@tandberg.com>"); } static void gst_wasapi_src_class_init (GstWasapiSrcClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); GstBaseSrcClass *gstbasesrc_class = GST_BASE_SRC_CLASS (klass); GstPushSrcClass *gstpushsrc_class = GST_PUSH_SRC_CLASS (klass); gobject_class->dispose = gst_wasapi_src_dispose; gobject_class->finalize = gst_wasapi_src_finalize; gstelement_class->provide_clock = gst_wasapi_src_provide_clock; gstbasesrc_class->start = gst_wasapi_src_start; gstbasesrc_class->stop = gst_wasapi_src_stop; gstbasesrc_class->query = gst_wasapi_src_query; gstpushsrc_class->create = gst_wasapi_src_create; GST_DEBUG_CATEGORY_INIT (gst_wasapi_src_debug, "wasapisrc", 0, "Windows audio session API source"); } static void gst_wasapi_src_init (GstWasapiSrc * self, GstWasapiSrcClass * gclass) { GstBaseSrc *basesrc = GST_BASE_SRC (self); gst_base_src_set_format (basesrc, GST_FORMAT_TIME); gst_base_src_set_live (basesrc, TRUE); self->rate = 8000; self->buffer_time = 20 * GST_MSECOND; self->period_time = 20 * GST_MSECOND; self->latency = GST_CLOCK_TIME_NONE; self->samples_per_buffer = self->rate / (GST_SECOND / self->period_time); self->start_time = GST_CLOCK_TIME_NONE; self->next_time = GST_CLOCK_TIME_NONE; #if GST_CHECK_VERSION(0, 10, 31) || (GST_CHECK_VERSION(0, 10, 30) && GST_VERSION_NANO > 0) self->clock = gst_audio_clock_new_full ("GstWasapiSrcClock", gst_wasapi_src_get_time, gst_object_ref (self), (GDestroyNotify) gst_object_unref); #else self->clock = gst_audio_clock_new ("GstWasapiSrcClock", gst_wasapi_src_get_time, self); #endif CoInitialize (NULL); } static void gst_wasapi_src_dispose (GObject * object) { GstWasapiSrc *self = GST_WASAPI_SRC (object); if (self->clock != NULL) { gst_object_unref (self->clock); self->clock = NULL; } G_OBJECT_CLASS (parent_class)->dispose (object); } static void gst_wasapi_src_finalize (GObject * object) { GstWasapiSrc *self = GST_WASAPI_SRC (object); CoUninitialize (); G_OBJECT_CLASS (parent_class)->finalize (object); } static GstClock * gst_wasapi_src_provide_clock (GstElement * element) { GstWasapiSrc *self = GST_WASAPI_SRC (element); GstClock *clock; GST_OBJECT_LOCK (self); if (self->client_clock == NULL) goto wrong_state; clock = GST_CLOCK (gst_object_ref (self->clock)); GST_OBJECT_UNLOCK (self); return clock; /* ERRORS */ wrong_state: { GST_OBJECT_UNLOCK (self); GST_DEBUG_OBJECT (self, "IAudioClock not acquired"); return NULL; } } static gboolean gst_wasapi_src_start (GstBaseSrc * src) { GstWasapiSrc *self = GST_WASAPI_SRC (src); gboolean res = FALSE; IAudioClient *client = NULL; IAudioClock *client_clock = NULL; guint64 client_clock_freq = 0; IAudioCaptureClient *capture_client = NULL; HRESULT hr; if (!gst_wasapi_util_get_default_device_client (GST_ELEMENT (self), TRUE, self->rate, self->buffer_time, self->period_time, 0, &client, &self->latency)) goto beach; hr = IAudioClient_GetService (client, &IID_IAudioClock, &client_clock); if (hr != S_OK) { GST_ERROR_OBJECT (self, "IAudioClient::GetService (IID_IAudioClock) " "failed"); goto beach; } hr = IAudioClock_GetFrequency (client_clock, &client_clock_freq); if (hr != S_OK) { GST_ERROR_OBJECT (self, "IAudioClock::GetFrequency () failed"); goto beach; } hr = IAudioClient_GetService (client, &IID_IAudioCaptureClient, &capture_client); if (hr != S_OK) { GST_ERROR_OBJECT (self, "IAudioClient::GetService " "(IID_IAudioCaptureClient) failed"); goto beach; } hr = IAudioClient_Start (client); if (hr != S_OK) { GST_ERROR_OBJECT (self, "IAudioClient::Start failed"); goto beach; } self->client = client; self->client_clock = client_clock; self->client_clock_freq = client_clock_freq; self->capture_client = capture_client; res = TRUE; beach: if (!res) { if (capture_client != NULL) IUnknown_Release (capture_client); if (client_clock != NULL) IUnknown_Release (client_clock); if (client != NULL) IUnknown_Release (client); } return res; } static gboolean gst_wasapi_src_stop (GstBaseSrc * src) { GstWasapiSrc *self = GST_WASAPI_SRC (src); if (self->client != NULL) { IAudioClient_Stop (self->client); } if (self->capture_client != NULL) { IUnknown_Release (self->capture_client); self->capture_client = NULL; } if (self->client_clock != NULL) { IUnknown_Release (self->client_clock); self->client_clock = NULL; } if (self->client != NULL) { IUnknown_Release (self->client); self->client = NULL; } return TRUE; } static gboolean gst_wasapi_src_query (GstBaseSrc * src, GstQuery * query) { GstWasapiSrc *self = GST_WASAPI_SRC (src); gboolean ret = FALSE; GST_DEBUG_OBJECT (self, "query for %s", gst_query_type_get_name (GST_QUERY_TYPE (query))); switch (GST_QUERY_TYPE (query)) { case GST_QUERY_LATENCY:{ GstClockTime min_latency, max_latency; min_latency = self->latency + self->period_time; max_latency = min_latency; GST_DEBUG_OBJECT (self, "reporting latency of min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT, GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency)); gst_query_set_latency (query, TRUE, min_latency, max_latency); ret = TRUE; break; } default: ret = GST_BASE_SRC_CLASS (parent_class)->query (src, query); break; } return ret; } static GstFlowReturn gst_wasapi_src_create (GstPushSrc * src, GstBuffer ** buf) { GstWasapiSrc *self = GST_WASAPI_SRC (src); GstFlowReturn ret = GST_FLOW_OK; GstClock *clock; GstClockTime timestamp, duration = self->period_time; HRESULT hr; gint16 *samples = NULL; guint32 nsamples_read = 0, nsamples; DWORD flags = 0; guint64 devpos; GST_OBJECT_LOCK (self); clock = GST_ELEMENT_CLOCK (self); if (clock != NULL) gst_object_ref (clock); GST_OBJECT_UNLOCK (self); if (clock != NULL && GST_CLOCK_TIME_IS_VALID (self->next_time)) { GstClockID id; id = gst_clock_new_single_shot_id (clock, self->next_time); gst_clock_id_wait (id, NULL); gst_clock_id_unref (id); } do { hr = IAudioCaptureClient_GetBuffer (self->capture_client, (BYTE **) & samples, &nsamples_read, &flags, &devpos, NULL); } while (hr == AUDCLNT_S_BUFFER_EMPTY); if (hr != S_OK) { GST_ERROR_OBJECT (self, "IAudioCaptureClient::GetBuffer () failed: %s", gst_wasapi_util_hresult_to_string (hr)); ret = GST_FLOW_ERROR; goto beach; } if (flags != 0) { GST_WARNING_OBJECT (self, "devpos %" G_GUINT64_FORMAT ": flags=0x%08x", devpos, flags); } /* FIXME: Why do we get 1024 sometimes and not a multiple of * samples_per_buffer? Shouldn't WASAPI provide a DISCONT * flag if we read too slow? */ nsamples = nsamples_read; g_assert (nsamples >= self->samples_per_buffer); if (nsamples > self->samples_per_buffer) { GST_WARNING_OBJECT (self, "devpos %" G_GUINT64_FORMAT ": got %d samples, expected %d, clipping!", devpos, nsamples, self->samples_per_buffer); nsamples = self->samples_per_buffer; } if (clock == NULL || clock == self->clock) { timestamp = gst_util_uint64_scale (devpos, GST_SECOND, self->client_clock_freq); } else { GstClockTime base_time; timestamp = gst_clock_get_time (clock); base_time = GST_ELEMENT_CAST (self)->base_time; if (timestamp > base_time) timestamp -= base_time; else timestamp = 0; if (timestamp > duration) timestamp -= duration; else timestamp = 0; } ret = gst_pad_alloc_buffer_and_set_caps (GST_BASE_SRC_PAD (self), devpos, nsamples * sizeof (gint16), GST_PAD_CAPS (GST_BASE_SRC_PAD (self)), buf); if (ret == GST_FLOW_OK) { guint i; gint16 *dst; GST_BUFFER_OFFSET_END (*buf) = devpos + self->samples_per_buffer; GST_BUFFER_TIMESTAMP (*buf) = timestamp; GST_BUFFER_DURATION (*buf) = duration; dst = (gint16 *) GST_BUFFER_DATA (*buf); for (i = 0; i < nsamples; i++) { *dst = *samples; samples += 2; dst++; } } hr = IAudioCaptureClient_ReleaseBuffer (self->capture_client, nsamples_read); if (hr != S_OK) { GST_ERROR_OBJECT (self, "IAudioCaptureClient::ReleaseBuffer () failed: %s", gst_wasapi_util_hresult_to_string (hr)); ret = GST_FLOW_ERROR; goto beach; } beach: if (clock != NULL) gst_object_unref (clock); return ret; } static GstClockTime gst_wasapi_src_get_time (GstClock * clock, gpointer user_data) { GstWasapiSrc *self = GST_WASAPI_SRC (user_data); HRESULT hr; guint64 devpos; GstClockTime result; if (G_UNLIKELY (self->client_clock == NULL)) return GST_CLOCK_TIME_NONE; hr = IAudioClock_GetPosition (self->client_clock, &devpos, NULL); if (G_UNLIKELY (hr != S_OK)) return GST_CLOCK_TIME_NONE; result = gst_util_uint64_scale_int (devpos, GST_SECOND, self->client_clock_freq); /* GST_DEBUG_OBJECT (self, "devpos = %" G_GUINT64_FORMAT " frequency = %" G_GUINT64_FORMAT " result = %" G_GUINT64_FORMAT " ms", devpos, self->client_clock_freq, GST_TIME_AS_MSECONDS (result)); */ return result; }
rawoul/gst-plugins-bad
sys/wasapi/gstwasapisrc.c
C
gpl-2.0
12,204
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> <title>About</title> </head> <body lang="EN-US"> <h2>About This Content</h2> <p>March 21, 2011</p> <h3>License</h3> <p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> <p>If you did not receive this Content directly from the Eclipse Foundation, the Content is being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may apply to your use of any object code in the Content. Check the Redistributor's license that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise indicated below, the terms and conditions of the EPL still apply to any source code in the Content and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p> <h3>Third Party Content</h3> <p>The Content includes items that have been sourced from third parties as set out below. If you did not receive this Content directly from the Eclipse Foundation, the following is provided for informational purposes only, and you should look to the Redistributor's license for terms and conditions of use.</p> <div style="font-style: italic"> <p>The Content includes items that have been sourced from third parties as follows:</p> <h4>JUnit 4.8.2</h4> <p>The plug-in is accompanied by software developed by <a href="http://www.junit.org/">JUnit.org</a>. The JUnit 4.8.2 code included with the plug-in includes no modifications. Your use of JUnit 4.8.2 in both source and binary code form contained in the plug-in is subject to the terms and conditions of the Common Public License Version 1.0 (&quot;CPL&quot;). A copy of the CPL is available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>. The binary code is located in junit.jar and the source code is located in source-bundle or in the org.junit.source bundle. <br/>The original source and binaries are available from <a href="https://github.com/KentBeck/junit/downloads">https://github.com/KentBeck/junit/downloads</a>, namely: <br/><a href="https://github.com/downloads/KentBeck/junit/junit-4.8.2-src.jar">https://github.com/downloads/KentBeck/junit/junit-4.8.2-src.jar</a> <br/><a href="https://github.com/downloads/KentBeck/junit/junit-dep-4.8.2.jar">https://github.com/downloads/KentBeck/junit/junit-dep-4.8.2.jar</a> </p> <h4>Hamcrest Library 1.1</h4> <p>The plug-in is accompanied by software developed by Hamcrest (<a href="http://code.google.com/p/hamcrest/">http://code.google.com/p/hamcrest/</a>). The hamcrest-library 1.1 code included within the JUnit 4.8.1 Jar includes no modifications. Your use of hamcrest-library 1.1 in both source and binary code form contained in the plug-in is subject to the terms and conditions of the New BSD License. The binary code is located in junit.jar/org/junit/internal/matchers and the source code is located in source-bundle/org/junit/internal/matchers.</p> <p>The Hamcrest New BSD License:</p> <pre> BSD License Copyright (c) 2000-2006, www.hamcrest.org All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Hamcrest 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. </pre> </div> </body> </html>
heartsome/translationstudio8
targetPlatform/plugins/org.junit_4.8.2.v4_8_2_v20110321-1705/about.html
HTML
gpl-2.0
5,133
/* 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. */ /** * @file http_core.h * @brief CORE HTTP Daemon * * @defgroup APACHE_CORE_HTTPD Core HTTP Daemon * @ingroup APACHE_CORE * @{ */ #ifndef APACHE_HTTP_CORE_H #define APACHE_HTTP_CORE_H #include "apr.h" #include "apr_hash.h" #include "apr_optional.h" #include "util_filter.h" #if APR_HAVE_STRUCT_RLIMIT #include <sys/time.h> #include <sys/resource.h> #endif #ifdef __cplusplus extern "C" { #endif /* **************************************************************** * * The most basic server code is encapsulated in a single module * known as the core, which is just *barely* functional enough to * serve documents, though not terribly well. * * Largely for NCSA back-compatibility reasons, the core needs to * make pieces of its config structures available to other modules. * The accessors are declared here, along with the interpretation * of one of them (allow_options). */ /** * @defgroup APACHE_CORE_HTTPD_ACESSORS Acessors * * @brief File/Directory Accessor directives * * @{ */ /** No directives */ #define OPT_NONE 0 /** Indexes directive */ #define OPT_INDEXES 1 /** SSI is enabled without exec= permission */ #define OPT_INCLUDES 2 /** FollowSymLinks directive */ #define OPT_SYM_LINKS 4 /** ExecCGI directive */ #define OPT_EXECCGI 8 /** directive unset */ #define OPT_UNSET 16 /** IncludesNOEXEC directive */ #define OPT_INCNOEXEC 32 /** SymLinksIfOwnerMatch directive */ #define OPT_SYM_OWNER 64 /** MultiViews directive */ #define OPT_MULTI 128 /** All directives */ #define OPT_ALL (OPT_INDEXES|OPT_INCLUDES|OPT_INCNOEXEC|OPT_SYM_LINKS|OPT_EXECCGI) /** @} */ #ifdef CORE_PRIVATE /* For internal use only - since 2.2.12, the OPT_INCNOEXEC bit is * internally replaced by OPT_INC_WITH_EXEC. The internal semantics * of the two SSI-related bits are hence: * * OPT_INCLUDES => "enable SSI, without exec= permission" * OPT_INC_WITH_EXEC => "iff OPT_INCLUDES is set, also enable exec=" * * The set of options exposed via ap_allow_options() retains the * semantics of OPT_INCNOEXEC by flipping the bit. */ #define OPT_INC_WITH_EXEC OPT_INCNOEXEC #endif /** * @defgroup get_remote_host Remote Host Resolution * @ingroup APACHE_CORE_HTTPD * @{ */ /** REMOTE_HOST returns the hostname, or NULL if the hostname * lookup fails. It will force a DNS lookup according to the * HostnameLookups setting. */ #define REMOTE_HOST (0) /** REMOTE_NAME returns the hostname, or the dotted quad if the * hostname lookup fails. It will force a DNS lookup according * to the HostnameLookups setting. */ #define REMOTE_NAME (1) /** REMOTE_NOLOOKUP is like REMOTE_NAME except that a DNS lookup is * never forced. */ #define REMOTE_NOLOOKUP (2) /** REMOTE_DOUBLE_REV will always force a DNS lookup, and also force * a double reverse lookup, regardless of the HostnameLookups * setting. The result is the (double reverse checked) hostname, * or NULL if any of the lookups fail. */ #define REMOTE_DOUBLE_REV (3) /** @} // get_remote_host */ /** all of the requirements must be met */ #define SATISFY_ALL 0 /** any of the requirements must be met */ #define SATISFY_ANY 1 /** There are no applicable satisfy lines */ #define SATISFY_NOSPEC 2 /** Make sure we don't write less than 8000 bytes at any one time. */ #define AP_MIN_BYTES_TO_WRITE 8000 /** default maximum of internal redirects */ # define AP_DEFAULT_MAX_INTERNAL_REDIRECTS 10 /** default maximum subrequest nesting level */ # define AP_DEFAULT_MAX_SUBREQ_DEPTH 10 /** * Retrieve the value of Options for this request * @param r The current request * @return the Options bitmask */ AP_DECLARE(int) ap_allow_options(request_rec *r); /** * Retrieve the value of the AllowOverride for this request * @param r The current request * @return the overrides bitmask */ AP_DECLARE(int) ap_allow_overrides(request_rec *r); /** * Retrieve the value of the DefaultType directive, or text/plain if not set * @param r The current request * @return The default type */ AP_DECLARE(const char *) ap_default_type(request_rec *r); /** * Retrieve the document root for this server * @param r The current request * @warning Don't use this! If your request went through a Userdir, or * something like that, it'll screw you. But it's back-compatible... * @return The document root */ AP_DECLARE(const char *) ap_document_root(request_rec *r); /** * Lookup the remote client's DNS name or IP address * @ingroup get_remote_host * @param conn The current connection * @param dir_config The directory config vector from the request * @param type The type of lookup to perform. One of: * <pre> * REMOTE_HOST returns the hostname, or NULL if the hostname * lookup fails. It will force a DNS lookup according to the * HostnameLookups setting. * REMOTE_NAME returns the hostname, or the dotted quad if the * hostname lookup fails. It will force a DNS lookup according * to the HostnameLookups setting. * REMOTE_NOLOOKUP is like REMOTE_NAME except that a DNS lookup is * never forced. * REMOTE_DOUBLE_REV will always force a DNS lookup, and also force * a double reverse lookup, regardless of the HostnameLookups * setting. The result is the (double reverse checked) * hostname, or NULL if any of the lookups fail. * </pre> * @param str_is_ip unless NULL is passed, this will be set to non-zero on output when an IP address * string is returned * @return The remote hostname */ AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config, int type, int *str_is_ip); /** * Retrieve the login name of the remote user. Undef if it could not be * determined * @param r The current request * @return The user logged in to the client machine */ AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r); /* Used for constructing self-referencing URLs, and things like SERVER_PORT, * and SERVER_NAME. */ /** * build a fully qualified URL from the uri and information in the request rec * @param p The pool to allocate the URL from * @param uri The path to the requested file * @param r The current request * @return A fully qualified URL */ AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri, request_rec *r); /** * Get the current server name from the request * @param r The current request * @return the server name */ AP_DECLARE(const char *) ap_get_server_name(request_rec *r); /** * Get the current server port * @param r The current request * @return The server's port */ AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r); /** * Return the limit on bytes in request msg body * @param r The current request * @return the maximum number of bytes in the request msg body */ AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r); /** * Return the limit on bytes in XML request msg body * @param r The current request * @return the maximum number of bytes in XML request msg body */ AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r); /** * Install a custom response handler for a given status * @param r The current request * @param status The status for which the custom response should be used * @param string The custom response. This can be a static string, a file * or a URL */ AP_DECLARE(void) ap_custom_response(request_rec *r, int status, const char *string); /** * Check if the current request is beyond the configured max. number of redirects or subrequests * @param r The current request * @return true (is exceeded) or false */ AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r); /** * Check for a definition from the server command line * @param name The define to check for * @return 1 if defined, 0 otherwise */ AP_DECLARE(int) ap_exists_config_define(const char *name); /* FIXME! See STATUS about how */ AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r); /* Authentication stuff. This is one of the places where compatibility * with the old config files *really* hurts; they don't discriminate at * all between different authentication schemes, meaning that we need * to maintain common state for all of them in the core, and make it * available to the other modules through interfaces. */ /** @see require_line */ typedef struct require_line require_line; /** * @brief A structure to keep track of authorization requirements */ struct require_line { /** Where the require line is in the config file. */ apr_int64_t method_mask; /** The complete string from the command line */ char *requirement; }; /** * Return the type of authorization required for this request * @param r The current request * @return The authorization required */ AP_DECLARE(const char *) ap_auth_type(request_rec *r); /** * Return the current Authorization realm * @param r The current request * @return The current authorization realm */ AP_DECLARE(const char *) ap_auth_name(request_rec *r); /** * How the requires lines must be met. * @param r The current request * @return How the requirements must be met. One of: * <pre> * SATISFY_ANY -- any of the requirements must be met. * SATISFY_ALL -- all of the requirements must be met. * SATISFY_NOSPEC -- There are no applicable satisfy lines * </pre> */ AP_DECLARE(int) ap_satisfies(request_rec *r); /** * Retrieve information about all of the requires directives for this request * @param r The current request * @return An array of all requires directives for this request */ AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r); #ifdef CORE_PRIVATE /** * Core is also unlike other modules in being implemented in more than * one file... so, data structures are declared here, even though most of * the code that cares really is in http_core.c. Also, another accessor. */ AP_DECLARE_DATA extern module core_module; /** * @brief Per-request configuration */ typedef struct { /** bucket brigade used by getline for look-ahead and * ap_get_client_block for holding left-over request body */ struct apr_bucket_brigade *bb; /** an array of per-request working data elements, accessed * by ID using ap_get_request_note() * (Use ap_register_request_note() during initialization * to add elements) */ void **notes; /** There is a script processor installed on the output filter chain, * so it needs the default_handler to deliver a (script) file into * the chain so it can process it. Normally, default_handler only * serves files on a GET request (assuming the file is actual content), * since other methods are not content-retrieval. This flag overrides * that behavior, stating that the "content" is actually a script and * won't actually be delivered as the response for the non-GET method. */ int deliver_script; /** Custom response strings registered via ap_custom_response(), * or NULL; check per-dir config if nothing found here */ char **response_code_strings; /* from ap_custom_response(), not from * ErrorDocument */ /** Should addition of charset= be suppressed for this request? */ int suppress_charset; } core_request_config; /* Standard entries that are guaranteed to be accessible via * ap_get_request_note() for each request (additional entries * can be added with ap_register_request_note()) */ #define AP_NOTE_DIRECTORY_WALK 0 #define AP_NOTE_LOCATION_WALK 1 #define AP_NOTE_FILE_WALK 2 #define AP_NUM_STD_NOTES 3 /** * Reserve an element in the core_request_config->notes array * for some application-specific data * @return An integer key that can be passed to ap_get_request_note() * during request processing to access this element for the * current request. */ AP_DECLARE(apr_size_t) ap_register_request_note(void); /** * Retrieve a pointer to an element in the core_request_config->notes array * @param r The request * @param note_num A key for the element: either a value obtained from * ap_register_request_note() or one of the predefined AP_NOTE_* * values. * @return NULL if the note_num is invalid, otherwise a pointer to the * requested note element. * @remark At the start of a request, each note element is NULL. The * handle provided by ap_get_request_note() is a pointer-to-pointer * so that the caller can point the element to some app-specific * data structure. The caller should guarantee that any such * structure will last as long as the request itself. */ AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num); typedef unsigned char allow_options_t; typedef unsigned char overrides_t; /* * Bits of info that go into making an ETag for a file * document. Why a long? Because char historically * proved too short for Options, and int can be different * sizes on different platforms. */ typedef unsigned long etag_components_t; #define ETAG_UNSET 0 #define ETAG_NONE (1 << 0) #define ETAG_MTIME (1 << 1) #define ETAG_INODE (1 << 2) #define ETAG_SIZE (1 << 3) #define ETAG_BACKWARD (ETAG_MTIME | ETAG_INODE | ETAG_SIZE) #define ETAG_ALL (ETAG_MTIME | ETAG_INODE | ETAG_SIZE) /** * @brief Server Signature Enumeration */ typedef enum { srv_sig_unset, srv_sig_off, srv_sig_on, srv_sig_withmail } server_signature_e; /** * @brief Per-directory configuration */ typedef struct { /** path of the directory/regex/etc. see also d_is_fnmatch/absolute below */ char *d; /** the number of slashes in d */ unsigned d_components; /** If (opts & OPT_UNSET) then no absolute assignment to options has * been made. * invariant: (opts_add & opts_remove) == 0 * Which said another way means that the last relative (options + or -) * assignment made to each bit is recorded in exactly one of opts_add * or opts_remove. */ allow_options_t opts; allow_options_t opts_add; allow_options_t opts_remove; overrides_t override; allow_options_t override_opts; /* MIME typing --- the core doesn't do anything at all with this, * but it does know what to slap on a request for a document which * goes untyped by other mechanisms before it slips out the door... */ char *ap_default_type; /* Authentication stuff. Groan... */ int *satisfy; /* for every method one */ char *ap_auth_type; char *ap_auth_name; apr_array_header_t *ap_requires; /* Custom response config. These can contain text or a URL to redirect to. * if response_code_strings is NULL then there are none in the config, * if it's not null then it's allocated to sizeof(char*)*RESPONSE_CODES. * This lets us do quick merges in merge_core_dir_configs(). */ char **response_code_strings; /* from ErrorDocument, not from * ap_custom_response() */ /* Hostname resolution etc */ #define HOSTNAME_LOOKUP_OFF 0 #define HOSTNAME_LOOKUP_ON 1 #define HOSTNAME_LOOKUP_DOUBLE 2 #define HOSTNAME_LOOKUP_UNSET 3 unsigned int hostname_lookups : 4; signed int content_md5 : 2; /* calculate Content-MD5? */ #define USE_CANONICAL_NAME_OFF (0) #define USE_CANONICAL_NAME_ON (1) #define USE_CANONICAL_NAME_DNS (2) #define USE_CANONICAL_NAME_UNSET (3) unsigned use_canonical_name : 2; /* since is_fnmatch(conf->d) was being called so frequently in * directory_walk() and its relatives, this field was created and * is set to the result of that call. */ unsigned d_is_fnmatch : 1; /* should we force a charset on any outgoing parameterless content-type? * if so, which charset? */ #define ADD_DEFAULT_CHARSET_OFF (0) #define ADD_DEFAULT_CHARSET_ON (1) #define ADD_DEFAULT_CHARSET_UNSET (2) unsigned add_default_charset : 2; const char *add_default_charset_name; /* System Resource Control */ #ifdef RLIMIT_CPU struct rlimit *limit_cpu; #endif #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) struct rlimit *limit_mem; #endif #ifdef RLIMIT_NPROC struct rlimit *limit_nproc; #endif apr_off_t limit_req_body; /* limit on bytes in request msg body */ long limit_xml_body; /* limit on bytes in XML request msg body */ /* logging options */ server_signature_e server_signature; int loglevel; /* Access control */ apr_array_header_t *sec_file; ap_regex_t *r; const char *mime_type; /* forced with ForceType */ const char *handler; /* forced with SetHandler */ const char *output_filters; /* forced with SetOutputFilters */ const char *input_filters; /* forced with SetInputFilters */ int accept_path_info; /* forced with AcceptPathInfo */ apr_hash_t *ct_output_filters; /* added with AddOutputFilterByType */ /* * What attributes/data should be included in ETag generation? */ etag_components_t etag_bits; etag_components_t etag_add; etag_components_t etag_remove; /* * Run-time performance tuning */ #define ENABLE_MMAP_OFF (0) #define ENABLE_MMAP_ON (1) #define ENABLE_MMAP_UNSET (2) unsigned int enable_mmap : 2; /* whether files in this dir can be mmap'ed */ #define ENABLE_SENDFILE_OFF (0) #define ENABLE_SENDFILE_ON (1) #define ENABLE_SENDFILE_UNSET (2) unsigned int enable_sendfile : 2; /* files in this dir can be mmap'ed */ unsigned int allow_encoded_slashes : 1; /* URLs may contain %2f w/o being * pitched indiscriminately */ #define USE_CANONICAL_PHYS_PORT_OFF (0) #define USE_CANONICAL_PHYS_PORT_ON (1) #define USE_CANONICAL_PHYS_PORT_UNSET (2) unsigned use_canonical_phys_port : 2; unsigned int decode_encoded_slashes : 1; /* whether to decode encoded slashes in URLs */ #define AP_MAXRANGES_UNSET -1 #define AP_MAXRANGES_DEFAULT -2 #define AP_MAXRANGES_UNLIMITED -3 #define AP_MAXRANGES_NORANGES 0 /** Number of Ranges before returning HTTP_OK. **/ int max_ranges; } core_dir_config; /* Per-server core configuration */ typedef struct { #ifdef GPROF char *gprof_dir; #endif /* Name translations --- we want the core to be able to do *something* * so it's at least a minimally functional web server on its own (and * can be tested that way). But let's keep it to the bare minimum: */ const char *ap_document_root; /* Access control */ char *access_name; apr_array_header_t *sec_dir; apr_array_header_t *sec_url; /* recursion backstopper */ int redirect_limit; /* maximum number of internal redirects */ int subreq_limit; /* maximum nesting level of subrequests */ const char *protocol; apr_table_t *accf_map; /* TRACE control */ #define AP_TRACE_UNSET -1 #define AP_TRACE_DISABLE 0 #define AP_TRACE_ENABLE 1 #define AP_TRACE_EXTENDED 2 int trace_enable; } core_server_config; /* for AddOutputFiltersByType in core.c */ void ap_add_output_filters_by_type(request_rec *r); /* for http_config.c */ void ap_core_reorder_directories(apr_pool_t *, server_rec *); /* for mod_perl */ AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config); AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config); AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config); AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg); /* Core filters; not exported. */ int ap_core_input_filter(ap_filter_t *f, apr_bucket_brigade *b, ap_input_mode_t mode, apr_read_type_e block, apr_off_t readbytes); apr_status_t ap_core_output_filter(ap_filter_t *f, apr_bucket_brigade *b); #endif /* CORE_PRIVATE */ AP_DECLARE(const char*) ap_get_server_protocol(server_rec* s); AP_DECLARE(void) ap_set_server_protocol(server_rec* s, const char* proto); /* ---------------------------------------------------------------------- * * Runtime status/management */ typedef enum { ap_mgmt_type_string, ap_mgmt_type_long, ap_mgmt_type_hash } ap_mgmt_type_e; typedef union { const char *s_value; long i_value; apr_hash_t *h_value; } ap_mgmt_value; typedef struct { const char *description; const char *name; ap_mgmt_type_e vtype; ap_mgmt_value v; } ap_mgmt_item_t; /* Handles for core filters */ extern AP_DECLARE_DATA ap_filter_rec_t *ap_subreq_core_filter_handle; extern AP_DECLARE_DATA ap_filter_rec_t *ap_core_output_filter_handle; extern AP_DECLARE_DATA ap_filter_rec_t *ap_content_length_filter_handle; extern AP_DECLARE_DATA ap_filter_rec_t *ap_core_input_filter_handle; /** * This hook provdes a way for modules to provide metrics/statistics about * their operational status. * * @param p A pool to use to create entries in the hash table * @param val The name of the parameter(s) that is wanted. This is * tree-structured would be in the form ('*' is all the tree, * 'module.*' all of the module , 'module.foo.*', or * 'module.foo.bar' ) * @param ht The hash table to store the results. Keys are item names, and * the values point to ap_mgmt_item_t structures. * @ingroup hooks */ AP_DECLARE_HOOK(int, get_mgmt_items, (apr_pool_t *p, const char * val, apr_hash_t *ht)) /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- * * I/O logging with mod_logio */ APR_DECLARE_OPTIONAL_FN(void, ap_logio_add_bytes_out, (conn_rec *c, apr_off_t bytes)); APR_DECLARE_OPTIONAL_FN(void, ap_logio_add_bytes_in, (conn_rec *c, apr_off_t bytes)); /* ---------------------------------------------------------------------- * * ident lookups with mod_ident */ APR_DECLARE_OPTIONAL_FN(const char *, ap_ident_lookup, (request_rec *r)); /* ---------------------------------------------------------------------- */ #ifdef __cplusplus } #endif #endif /* !APACHE_HTTP_CORE_H */ /** @} */
apolloolive/apollo
http_core.h
C
gpl-2.0
24,019
/*****************************************************************************/ /* */ /* Copyright (c) 1990-2008 Morgan Stanley All rights reserved.*/ /* See .../src/LICENSE for terms of distribution. */ /* */ /* */ /*****************************************************************************/ #include <stdio.h> #include <sys/time.h> int microsleep(int i) { struct timeval tv; if(i>1000000) { tv.tv_sec = (int) i/1000000; tv.tv_usec = i - tv.tv_sec*1000000; } else { tv.tv_sec = 0; tv.tv_usec = i; } return select(0, NULL, NULL, NULL, &tv); }
rdm/aplus-fsf
src/cxsys/microsleep.c
C
gpl-2.0
833
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'bidi', 'ka', { ltr: 'ტექსტის მიმართულება მარცხნიდან მარჯვნივ', rtl: 'ტექსტის მიმართულება მარჯვნიდან მარცხნივ' } );
jagnoha/website
profiles/varbase/profiles/varbase/modules/contrib/ckeditor_bidi/js/plugins/bidi/lang/ka.js
JavaScript
gpl-2.0
431
<!-- Copyright 2013 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <script type="text/x-red" data-template-name="switch"> <div class="form-row"> <label for="node-input-name"><i class="fa fa-tag"></i> Name</label> <input type="text" id="node-input-name" placeholder="Name"> </div> <div class="form-row"> If msg.<input type="text" id="node-input-property" style="width: 200px;"/> </div> <div class="form-row node-input-rule-container-row" style="margin-bottom: 0px;"> <div id="node-input-rule-container-div" style="box-sizing: border-box; border-radius: 5px; height: 310px; padding: 5px; border: 1px solid #ccc; overflow-y:scroll;"> <ol id="node-input-rule-container" style=" list-style-type:none; margin: 0;"></ol> </div> </div> <div class="form-row"> <a href="#" class="btn btn-mini" id="node-input-add-rule" style="margin-top: 4px;"><i class="fa fa-plus"></i> rule</a> </div> <div class="form-row"> <select id="node-input-checkall" style="width:100%; margin-right:5px;"> <option value="true">checking all rules</option> <option value="false">stopping after first match</option> </select> </div> </script> <script type="text/x-red" data-help-name="switch"> <p>A simple function node to route messages based on its properties.</p> <p>When a message arrives, the selected property is evaluated against each of the defined rules. The message is then sent to the output of <i>all</i> rules that pass.</p> <p>Note: the <i>otherwise</i> rule applies as a "not any of" the rules preceding it.</p> </script> <script type="text/javascript"> RED.nodes.registerType('switch', { color: "#E2D96E", category: 'function', defaults: { name: {value:""}, property: {value:"payload", required:true}, rules: {value:[{t:"eq", v:""}]}, checkall: {value:"true", required:true}, outputs: {value:1} }, inputs: 1, outputs: 1, icon: "switch.png", label: function() { return this.name||"switch"; }, oneditprepare: function() { var operators = [ {v:"eq",t:"=="}, {v:"neq",t:"!="}, {v:"lt",t:"<"}, {v:"lte",t:"<="}, {v:"gt",t:">"}, {v:"gte",t:">="}, {v:"btwn",t:"is between"}, {v:"cont",t:"contains"}, {v:"regex",t:"matches regex"}, {v:"true",t:"is true"}, {v:"false",t:"is false"}, {v:"null",t:"is null"}, {v:"nnull",t:"is not null"}, {v:"else",t:"otherwise"} ]; function generateRule(i,rule) { var container = $('<li/>',{style:"margin:0; padding:8px 0px; border-bottom: 1px solid #ccc;"}); var row = $('<div/>').appendTo(container); var row2 = $('<div/>',{style:"padding-top: 5px; text-align: right;"}).appendTo(container); var selectField = $('<select/>',{style:"width:120px; margin-left: 5px; text-align: center;"}).appendTo(row); for (var d in operators) { selectField.append($("<option></option>").val(operators[d].v).text(operators[d].t)); } var valueField = $('<input/>',{class:"node-input-rule-value",type:"text",style:"margin-left: 5px; width: 145px;"}).appendTo(row); var btwnField = $('<span/>').appendTo(row); var btwnValueField = $('<input/>',{class:"node-input-rule-btwn-value",type:"text",style:"margin-left: 5px; width: 50px;"}).appendTo(btwnField); btwnField.append(" and "); var btwnValue2Field = $('<input/>',{class:"node-input-rule-btwn-value2",type:"text",style:"width: 50px;margin-left:2px;"}).appendTo(btwnField); var finalspan = $('<span/>',{style:"float: right; margin-top: 3px;margin-right: 10px;"}).appendTo(row); finalspan.append(' send to <span class="node-input-rule-index">'+i+'</span> '); selectField.change(function() { var type = selectField.children("option:selected").val(); if (type.length < 4) { selectField.css({"width":"60px"}); } else if (type === "regex") { selectField.css({"width":"147px"}); } else { selectField.css({"width":"120px"}); } if (type === "btwn") { valueField.hide(); btwnField.show(); } else { btwnField.hide(); if (type === "true" || type === "false" || type === "null" || type === "nnull" || type === "else") { valueField.hide(); } else { valueField.show(); } } }); var deleteButton = $('<a/>',{href:"#",class:"btn btn-mini", style:"margin-left: 5px;"}).appendTo(finalspan); $('<i/>',{class:"fa fa-remove"}).appendTo(deleteButton); deleteButton.click(function() { container.css({"background":"#fee"}); container.fadeOut(300, function() { $(this).remove(); $("#node-input-rule-container").children().each(function(i) { $(this).find(".node-input-rule-index").html(i+1); }); }); }); $("#node-input-rule-container").append(container); selectField.find("option").filter(function() {return $(this).val() == rule.t;}).attr('selected',true); if (rule.t == "btwn") { btwnValueField.val(rule.v); btwnValue2Field.val(rule.v2); } else if (typeof rule.v != "undefined") { valueField.val(rule.v); } selectField.change(); } $("#node-input-add-rule").click(function() { generateRule($("#node-input-rule-container").children().length+1,{t:"",v:"",v2:""}); $("#node-input-rule-container-div").scrollTop($("#node-input-rule-container-div").get(0).scrollHeight); }); for (var i=0;i<this.rules.length;i++) { var rule = this.rules[i]; generateRule(i+1,rule); } function switchDialogResize() { var rows = $("#dialog-form>div:not(.node-input-rule-container-row)"); var height = $("#dialog-form").height(); for (var i=0;i<rows.size();i++) { height -= $(rows[i]).outerHeight(true); } var editorRow = $("#dialog-form>div.node-input-rule-container-row"); height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom"))); $("#node-input-rule-container-div").css("height",height+"px"); }; $( "#dialog" ).on("dialogresize", switchDialogResize); $( "#dialog" ).one("dialogopen", function(ev) { var size = $( "#dialog" ).dialog('option','sizeCache-switch'); if (size) { $("#dialog").dialog('option','width',size.width); $("#dialog").dialog('option','height',size.height); switchDialogResize(); } }); $( "#dialog" ).one("dialogclose", function(ev,ui) { $( "#dialog" ).off("dialogresize",switchDialogResize); }); }, oneditsave: function() { var rules = $("#node-input-rule-container").children(); var ruleset; var node = this; node.rules= []; rules.each(function(i) { var rule = $(this); var type = rule.find("select option:selected").val(); var r = {t:type}; if (!(type === "true" || type === "false" || type === "null" || type === "nnull" || type === "else")) { if (type === "btwn") { r.v = rule.find(".node-input-rule-btwn-value").val(); r.v2 = rule.find(".node-input-rule-btwn-value2").val(); } else { r.v = rule.find(".node-input-rule-value").val(); } } node.rules.push(r); }); node.outputs = node.rules.length; } }); </script>
Wyliodrin/streamsitems
red/logic/10-switch.html
HTML
gpl-2.0
9,431
#include "scripting/js-bindings/manual/experimental/jsb_cocos2dx_experimental_webView_manual.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #include "ui/UIWebView.h" #include "scripting/js-bindings/manual/ScriptingCore.h" #include "scripting/js-bindings/manual/cocos2d_specifics.hpp" using namespace cocos2d; static bool jsb_cocos2dx_experimental_webView_setOnShouldStartLoading(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(obj); experimental::ui::WebView* cobj = (experimental::ui::WebView *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if(argc == 1){ std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, obj, args.get(0))); cobj->setOnShouldStartLoading([=](experimental::ui::WebView *sender, const std::string &url)->bool{ JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval arg[2]; JS::RootedObject jsobj(cx, js_get_or_create_jsobject<experimental::ui::WebView>(cx, sender)); arg[0] = OBJECT_TO_JSVAL(jsobj); arg[1] = std_string_to_jsval(cx, url); JS::RootedValue rval(cx); bool ok = func->invoke(2, arg, &rval); if (!ok && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } return rval.toBoolean(); }); return true; } JS_ReportError(cx, "jsb_cocos2dx_experimental_webView_setOnShouldStartLoading : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } static bool jsb_cocos2dx_experimental_webView_setOnDidFinishLoading(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(obj); experimental::ui::WebView* cobj = (experimental::ui::WebView *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if(argc == 1){ std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, obj, args.get(0))); cobj->setOnDidFinishLoading([=](experimental::ui::WebView *sender, const std::string &url)->void{ JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval arg[2]; JS::RootedObject jsobj(cx, js_get_or_create_jsobject<experimental::ui::WebView>(cx, sender)); arg[0] = OBJECT_TO_JSVAL(jsobj); arg[1] = std_string_to_jsval(cx, url); JS::RootedValue rval(cx); bool ok = func->invoke(2, arg, &rval); if (!ok && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } }); return true; } JS_ReportError(cx, "jsb_cocos2dx_experimental_webView_setOnDidFinishLoading : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } static bool jsb_cocos2dx_experimental_webView_setOnDidFailLoading(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(obj); experimental::ui::WebView* cobj = (experimental::ui::WebView *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if(argc == 1){ std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, obj, args.get(0))); cobj->setOnDidFailLoading([=](experimental::ui::WebView *sender, const std::string &url)->void{ JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval arg[2]; JS::RootedObject jsobj(cx, js_get_or_create_jsobject<experimental::ui::WebView>(cx, sender)); arg[0] = OBJECT_TO_JSVAL(jsobj); arg[1] = std_string_to_jsval(cx, url); JS::RootedValue rval(cx); bool ok = func->invoke(2, arg, &rval); if (!ok && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } }); return true; } JS_ReportError(cx, "jsb_cocos2dx_experimental_webView_setOnDidFailLoading : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } static bool jsb_cocos2dx_experimental_webView_setOnJSCallback(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(obj); experimental::ui::WebView* cobj = (experimental::ui::WebView *)(proxy ? proxy->ptr : NULL); JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if(argc == 1){ std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, obj, args.get(0))); cobj->setOnJSCallback([=](experimental::ui::WebView *sender, const std::string &url)->void{ JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval arg[2]; JS::RootedObject jsobj(cx, js_get_or_create_jsobject<experimental::ui::WebView>(cx, sender)); arg[0] = OBJECT_TO_JSVAL(jsobj); arg[1] = std_string_to_jsval(cx, url); JS::RootedValue rval(cx); bool ok = func->invoke(2, arg, &rval); if (!ok && JS_IsExceptionPending(cx)) { JS_ReportPendingException(cx); } }); return true; } JS_ReportError(cx, "jsb_cocos2dx_experimental_webView_setOnJSCallback : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } extern JSObject* jsb_cocos2d_experimental_ui_WebView_prototype; void register_all_cocos2dx_experimental_webView_manual(JSContext* cx, JS::HandleObject global) { JS::RootedObject proto(cx, jsb_cocos2d_experimental_ui_WebView_prototype); JS_DefineFunction(cx, proto, "setOnShouldStartLoading", jsb_cocos2dx_experimental_webView_setOnShouldStartLoading, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, proto, "setOnDidFinishLoading", jsb_cocos2dx_experimental_webView_setOnDidFinishLoading, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, proto, "setOnDidFailLoading", jsb_cocos2dx_experimental_webView_setOnDidFailLoading, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, proto, "setOnJSCallback", jsb_cocos2dx_experimental_webView_setOnJSCallback, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); } #endif
zero5566/super_mahjong
mahjong/super_mahjong/frameworks/cocos2d-x/cocos/scripting/js-bindings/manual/experimental/jsb_cocos2dx_experimental_webView_manual.cpp
C++
gpl-2.0
6,600
#include <linux/types.h> #include <linux/mm.h> #include <linux/blk.h> #include <linux/version.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/bootinfo.h> #include <asm/amigaints.h> #include <asm/amigahw.h> #include <asm/zorro.h> #include <asm/irq.h> #include "scsi.h" #include "hosts.h" #include "wd33c93.h" #include "gvp11.h" #include<linux/stat.h> struct proc_dir_entry proc_scsi_gvp11 = { PROC_SCSI_GVP11, 5, "GVP11", S_IFDIR | S_IRUGO | S_IXUGO, 2 }; #define DMA(ptr) ((gvp11_scsiregs *)((ptr)->base)) #define HDATA(ptr) ((struct WD33C93_hostdata *)((ptr)->hostdata)) static struct Scsi_Host *first_instance = NULL; static Scsi_Host_Template *gvp11_template; static void gvp11_intr (int irq, struct pt_regs *fp, void *dummy) { unsigned int status; struct Scsi_Host *instance; for (instance = first_instance; instance && instance->hostt == gvp11_template; instance = instance->next) { status = DMA(instance)->CNTR; if (!(status & GVP11_DMAC_INT_PENDING)) continue; /* disable PORTS interrupt */ custom.intena = IF_PORTS; wd33c93_intr (instance); /* enable PORTS interrupt */ custom.intena = IF_SETCLR | IF_PORTS; } } /* * DMA transfer mask for GVP Series II SCSI controller. * Some versions can only DMA into the 24 bit address space * (0->16M). Others can DMA into the full 32 bit address * space. The default is to only allow DMA into the 24 bit * address space. The "gvp11=0xFFFFFFFE" setup parameter can * be supplied to force an alternate (32 bit) mask. */ static int gvp11_xfer_mask = GVP11_XFER_MASK; void gvp11_setup (char *str, int *ints) { gvp11_xfer_mask = ints[1]; } static int dma_setup (Scsi_Cmnd *cmd, int dir_in) { unsigned short cntr = GVP11_DMAC_INT_ENABLE; unsigned long addr = VTOP(cmd->SCp.ptr); /* don't allow DMA if the physical address is bad */ if (addr & gvp11_xfer_mask || (!dir_in && mm_end_of_chunk (addr, cmd->SCp.this_residual))) { HDATA(cmd->host)->dma_bounce_len = (cmd->SCp.this_residual + 511) & ~0x1ff; HDATA(cmd->host)->dma_bounce_buffer = scsi_malloc (HDATA(cmd->host)->dma_bounce_len); /* can't allocate memory; use PIO */ if (!HDATA(cmd->host)->dma_bounce_buffer) { HDATA(cmd->host)->dma_bounce_len = 0; return 1; } /* check if the address of the bounce buffer is OK */ addr = VTOP(HDATA(cmd->host)->dma_bounce_buffer); if (addr & gvp11_xfer_mask) { scsi_free (HDATA(cmd->host)->dma_bounce_buffer, HDATA(cmd->host)->dma_bounce_len); HDATA(cmd->host)->dma_bounce_buffer = NULL; HDATA(cmd->host)->dma_bounce_len = 0; return 1; } if (!dir_in) { /* copy to bounce buffer for a write */ if (cmd->use_sg) #if 0 panic ("scsi%ddma: incomplete s/g support", cmd->host->host_no); #else memcpy (HDATA(cmd->host)->dma_bounce_buffer, cmd->SCp.ptr, cmd->SCp.this_residual); #endif else memcpy (HDATA(cmd->host)->dma_bounce_buffer, cmd->request_buffer, cmd->request_bufflen); } } /* setup dma direction */ if (!dir_in) cntr |= GVP11_DMAC_DIR_WRITE; HDATA(cmd->host)->dma_dir = dir_in; DMA(cmd->host)->CNTR = cntr; /* setup DMA *physical* address */ DMA(cmd->host)->ACR = addr; if (dir_in) /* invalidate any cache */ cache_clear (addr, cmd->SCp.this_residual); else /* push any dirty cache */ cache_push (addr, cmd->SCp.this_residual); /* start DMA */ DMA(cmd->host)->ST_DMA = 1; /* return success */ return 0; } static void dma_stop (struct Scsi_Host *instance, Scsi_Cmnd *SCpnt, int status) { /* stop DMA */ DMA(instance)->SP_DMA = 1; /* remove write bit from CONTROL bits */ DMA(instance)->CNTR = GVP11_DMAC_INT_ENABLE; /* copy from a bounce buffer, if necessary */ if (status && HDATA(instance)->dma_bounce_buffer) { if (SCpnt && SCpnt->use_sg) { #if 0 panic ("scsi%d: incomplete s/g support", instance->host_no); #else if( HDATA(instance)->dma_dir ) memcpy (SCpnt->SCp.ptr, HDATA(instance)->dma_bounce_buffer, SCpnt->SCp.this_residual); scsi_free (HDATA(instance)->dma_bounce_buffer, HDATA(instance)->dma_bounce_len); HDATA(instance)->dma_bounce_buffer = NULL; HDATA(instance)->dma_bounce_len = 0; #endif } else { if (HDATA(instance)->dma_dir && SCpnt) memcpy (SCpnt->request_buffer, HDATA(instance)->dma_bounce_buffer, SCpnt->request_bufflen); scsi_free (HDATA(instance)->dma_bounce_buffer, HDATA(instance)->dma_bounce_len); HDATA(instance)->dma_bounce_buffer = NULL; HDATA(instance)->dma_bounce_len = 0; } } } int gvp11_detect(Scsi_Host_Template *tpnt) { static unsigned char called = 0; struct Scsi_Host *instance; int i, manuf, product, num_gvp11 = 0; caddr_t address; enum GVP_ident epc; if (!MACH_IS_AMIGA || called) return 0; called = 1; tpnt->proc_dir = &proc_scsi_gvp11; for (i = 0; i < boot_info.bi_amiga.num_autocon; i++) { manuf = boot_info.bi_amiga.autocon[i].cd_Rom.er_Manufacturer; product = boot_info.bi_amiga.autocon[i].cd_Rom.er_Product; #if 0 /* this seems to catch some non HD boards. GVP is sooooo stupid */ if (manuf == MANUF_GVP && ((product == PROD_GVPIISCSI) || (product == PROD_GVPIISCSI_2))) { #else if (manuf == MANUF_GVP && product == PROD_GVPIISCSI) { #endif /* check extended product code */ address = boot_info.bi_amiga.autocon[i].cd_BoardAddr; epc = *(unsigned short *)(ZTWO_VADDR(address) + 0x8000); epc = epc & GVP_EPCMASK; /* * This should (hopefully) be the correct way to identify * all the different GVP SCSI controllers (except for the * SERIES I though). */ if (!((epc == GVP_A1291_SCSI) || (epc == GVP_GFORCE_040_SCSI) || (epc == GVP_GFORCE_030_SCSI) || (epc == GVP_A530_SCSI) || (epc == GVP_COMBO_R4_SCSI) || (epc == GVP_COMBO_R3_SCSI) || (epc == GVP_SERIESII))) continue; instance = scsi_register (tpnt, sizeof (struct WD33C93_hostdata)); instance->base = (unsigned char *)ZTWO_VADDR(address); DMA(instance)->secret2 = 1; DMA(instance)->secret1 = 0; DMA(instance)->secret3 = 15; while (DMA(instance)->CNTR & GVP11_DMAC_BUSY) ; DMA(instance)->CNTR = 0; wd33c93_init(instance, (wd33c93_regs *)&(DMA(instance)->SASR), dma_setup, dma_stop, WD33C93_FS_8_10); if (num_gvp11++ == 0) { first_instance = instance; gvp11_template = instance->hostt; add_isr(IRQ_AMIGA_PORTS, gvp11_intr, 0, NULL, "GVP11 SCSI"); } DMA(instance)->CNTR = GVP11_DMAC_INT_ENABLE; #if 0 /* The Zorro stuff is not totally integrated yet ! */ boot_info.bi_amiga.autocon_configured |= 1<<i; #endif } } return num_gvp11; }
carlobar/uclinux_leon3_UD
linux-2.0.x/drivers/scsi/gvp11.c
C
gpl-2.0
6,809
@import '../../components/variables.css'; .root { padding-left: 20px; padding-right: 20px; } .container { margin: 0 auto; padding: 0 0 40px; max-width: var(--max-content-width); }
bigearth/www.clone.earth
src/routes/register/Register.css
CSS
gpl-2.0
193
require_dependency 'enum_site_setting' class S3RegionSiteSetting < EnumSiteSetting def self.valid_value?(val) valid_values.include? val end def self.values @values ||= valid_values.sort.map {|x| {name: x, value: x} } end def self.valid_values [ '', 'us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'sa-east-1' ] end end
vasinov/discourse
app/models/s3_region_site_setting.rb
Ruby
gpl-2.0
452
/*=========================================================================== FILE: ProtocolRequest.cpp DESCRIPTION: Generic protocol request/command related structures and affliated methods, these structures are used by clients of the protocol server to specify outgoing requests PUBLIC CLASSES AND METHODS: sProtocolRequest Copyright (c) 2013, The Linux Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of The Linux Foundation 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. ===========================================================================*/ //--------------------------------------------------------------------------- // Include Files //--------------------------------------------------------------------------- #include "StdAfx.h" #include "ProtocolRequest.h" #include "ProtocolNotification.h" #include "ProtocolServer.h" //--------------------------------------------------------------------------- // Definitions //--------------------------------------------------------------------------- // Default protocol request timeout const ULONG DEFAULT_REQ_TIMEOUT = 1000; // Minimum and maximum allowable timeout values (in milliseconds) const ULONG MIN_REQ_TIMEOUT = 100; const ULONG MAX_REQ_TIMEOUT = 300000; // Minimum number of attempts a request can be scheduled for const ULONG MIN_REQ_ATTEMPTS = 1; // Value to indicate that a request is to be sent out indefinately const ULONG INFINITE_REQS = 0xFFFFFFFF; // Minimum/default amount of time between repeated requests (in milliseconds) const ULONG MIN_REQ_FREQUENCY = 10; const ULONG DEFAULT_REQ_FREQUENCY = 100; /*=========================================================================*/ // sProtocolRequest Methods /*=========================================================================*/ /*=========================================================================== METHOD: sProtocolRequest DESCRIPTION: Parameterized constructor PARAMETERS: pBuffer [ I ] - Shareable buffer representing the request (must be valid) schedule [ I ] - When (from now, in milliseconds) to send the first request, this isn't a hard value as the request is only guaranteed to go out after this time elapses timeout [ I ] - Milliseconds to wait for a response to an individual request before declaring a timeout. Regardless of what is passed in the timeout value used will be between MIN/MAX_REQ_TIMEOUT requests [ I ] - Number of request attempts to make, this isn't a retry count rather this value is used to specify repeating requests. Regardless of what is passed in the requests value used will be at least MIN_REQ_ATTEMPTS frequency [ I ] - If the 'requests' value is greater than the MIN_REQ_ATTEMPTS than this represents the amount of time to wait between requests (from the completion of the last request attempt, in milliseconds), again this isn't a hard value. Regardless of what is passed in the frequency value used will be at least MIN_REQ_FREQUENCY pNotifier [ I ] - Status notification mechanism (may be 0) RETURN VALUE: None ===========================================================================*/ sProtocolRequest::sProtocolRequest( sSharedBuffer * pBuffer, ULONG schedule, ULONG timeout, ULONG requests, ULONG frequency, cProtocolNotification * pNotifier ) : sProtocolBuffer( pBuffer ), mSchedule( schedule ), mTimeout( DEFAULT_REQ_TIMEOUT ), mRequests( MIN_REQ_ATTEMPTS ), mFrequency( DEFAULT_REQ_FREQUENCY ), mpNotifier( 0 ), mpAuxData( 0 ), mAuxDataSize( 0 ), mbTXOnly( false ) { // Constrain requested timeout to allowable range if (timeout < MIN_REQ_TIMEOUT) { timeout = MIN_REQ_TIMEOUT; } if (timeout > MAX_REQ_TIMEOUT) { timeout = MAX_REQ_TIMEOUT; } mTimeout = timeout; // Constrain request attempts if (requests >= MIN_REQ_ATTEMPTS) { mRequests = requests; } // Constrain frequency if (frequency >= MIN_REQ_FREQUENCY) { mFrequency = frequency; } // Clone notifier? if (pNotifier != 0) { mpNotifier = pNotifier->Clone(); } } /*=========================================================================== METHOD: sProtocolRequest DESCRIPTION: Parameterized constructor (notification with defaults) PARAMETERS: pBuffer [ I ] - Shareable buffer representing the request (must be valid) pNotifier [ I ] - Status notification mechanism (may be 0) RETURN VALUE: None ===========================================================================*/ sProtocolRequest::sProtocolRequest( sSharedBuffer * pBuffer, cProtocolNotification * pNotifier ) : sProtocolBuffer( pBuffer ), mSchedule( 0 ), mTimeout( DEFAULT_REQ_TIMEOUT ), mRequests( MIN_REQ_ATTEMPTS ), mFrequency( DEFAULT_REQ_FREQUENCY ), mpNotifier( pNotifier ), mpAuxData( 0 ), mAuxDataSize( 0 ), mbTXOnly( false ) { // Clone notifier? if (pNotifier != 0) { mpNotifier = pNotifier->Clone(); } Validate(); } /*=========================================================================== METHOD: sProtocolRequest DESCRIPTION: Copy constructor PARAMETERS: req [ I ] - Request to copy RETURN VALUE: None ===========================================================================*/ sProtocolRequest::sProtocolRequest( const sProtocolRequest & req ) : sProtocolBuffer( req ), mSchedule( req.mSchedule ), mTimeout( req.mTimeout ), mRequests( req.mRequests ), mFrequency( req.mFrequency ), mpNotifier( 0 ), mpAuxData( req.mpAuxData ), mAuxDataSize( req.mAuxDataSize ), mbTXOnly( req.mbTXOnly ) { // Clone notifier? if (req.mpNotifier != 0) { mpNotifier = req.mpNotifier->Clone(); } Validate(); } /*=========================================================================== METHOD: ~sProtocolRequest DESCRIPTION: Destructor RETURN VALUE: None ===========================================================================*/ sProtocolRequest::~sProtocolRequest() { // Delete cloned notifier? if (mpNotifier != 0) { delete mpNotifier; mpNotifier = 0; } }
E3V3A/libqmi
gobi-api/GobiAPI_2013-07-31-1347/Core/ProtocolRequest.cpp
C++
gpl-2.0
8,168
<?php /** * @package Redcore * @subpackage Fields * * @copyright Copyright (C) 2008 - 2016 redCOMPONENT.com. All rights reserved. * @license GNU General Public License version 2 or later, see LICENSE. */ defined('JPATH_REDCORE') or die; /** * Bootstrap timepicker field. * * @package Redcore * @subpackage Fields * @since 1.0 */ class JFormFieldTimePicker extends JFormField { /** * The form field type. * * @var string */ protected $type = 'TimePicker'; /** * Method to get the field input markup. * * @return string The field input markup. */ protected function getInput() { $class = $this->element['class'] ? $this->element['class'] : ''; return RLayoutHelper::render('fields.timepicker', array( 'field' => $this, 'class' => $class, 'id' => $this->id, 'required' => $this->required, 'name' => $this->name, 'value' => $this->value ) ); } /** * Get the field options as a js string. * * @return string The options. */ public function getOptions() { // Prepare the params. $template = $this->element['template'] ? $this->element['template'] : 'dropdown'; $minuteStep = (isset($this->element['minute_step']) && !empty($this->element['minute_step'])) ? (int) $this->element['minute_step'] : 15; $secondStep = (isset($this->element['second_step']) && !empty($this->element['second_step'])) ? (int) $this->element['second_step'] : 15; $showSeconds = RHelperString::toBool($this->element['seconds']) ? 'true' : 'false'; $showMeridian = RHelperString::toBool($this->element['meridian']) ? 'true' : 'false'; $showInputs = RHelperString::toBool($this->element['inputs']) ? 'true' : 'false'; $disableFocus = RHelperString::toBool($this->element['disable_focus']) ? 'true' : 'false'; $modalBackdrop = RHelperString::toBool($this->element['backdrop']) ? 'true' : 'false'; // If we don't have a value. if (empty($this->value)) { $defaultTime = $this->element['default'] ? $this->element['default'] : 'current'; } else { $defaultTime = 'value'; } $options = new JRegistry; $options->loadArray( array( 'template' => $template, 'minuteStep' => $minuteStep, 'showSeconds' => $showSeconds, 'secondStep' => $secondStep, 'defaultTime' => $defaultTime, 'showMeridian' => $showMeridian, 'showInputs' => $showInputs, 'disableFocus' => $disableFocus, 'modalBackdrop' => $modalBackdrop ) ); return $options->toString(); } }
jatitoam/redCORE
extensions/libraries/redcore/form/fields/timepicker.php
PHP
gpl-2.0
2,532
/*************************************************************************** qgsannotation.h --------------- begin : January 2017 copyright : (C) 2017 by Nyall Dawson email : nyall dot dawson at gmail dot 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. * * * ***************************************************************************/ #ifndef QGSANNOTATION_H #define QGSANNOTATION_H #include "qgis_core.h" #include "qgis.h" #include "qgspointxy.h" #include "qgscoordinatereferencesystem.h" #include "qgsrendercontext.h" #include "qgssymbol.h" #include "qgsmargins.h" #include "qgsmaplayer.h" /** * \ingroup core * \class QgsAnnotation * * \brief Abstract base class for annotation items which are drawn over a map. * * QgsAnnotation is an abstract base class for map annotation items. These annotations can be * drawn within a map, and have either a fixed map position (retrieved using mapPosition()) * or are placed relative to the map's frame (retrieved using relativePosition()). * Annotations with a fixed map position also have a corresponding * QgsCoordinateReferenceSystem, which can be determined by calling mapPositionCrs(). * * Derived classes should implement their custom painting routines within * a renderAnnotation() override. * * \since QGIS 3.0 */ class CORE_EXPORT QgsAnnotation : public QObject { #ifdef SIP_RUN SIP_CONVERT_TO_SUBCLASS_CODE if ( dynamic_cast< QgsTextAnnotation * >( sipCpp ) ) sipType = sipType_QgsTextAnnotation; else if ( dynamic_cast< QgsSvgAnnotation * >( sipCpp ) ) sipType = sipType_QgsSvgAnnotation; else if ( dynamic_cast< QgsHtmlAnnotation * >( sipCpp ) ) sipType = sipType_QgsHtmlAnnotation; else sipType = NULL; SIP_END #endif Q_OBJECT Q_PROPERTY( bool visible READ isVisible WRITE setVisible ) Q_PROPERTY( bool hasFixedMapPosition READ hasFixedMapPosition WRITE setHasFixedMapPosition ) Q_PROPERTY( QgsPointXY mapPosition READ mapPosition WRITE setMapPosition ) Q_PROPERTY( QSizeF frameSize READ frameSize WRITE setFrameSize ) public: /** * Constructor for QgsAnnotation. */ QgsAnnotation( QObject *parent SIP_TRANSFERTHIS = nullptr ); /** * Clones the annotation, returning a new copy of the annotation * reflecting the annotation's current state. */ virtual QgsAnnotation *clone() const = 0 SIP_FACTORY; /** * Returns true if the annotation is visible and should be rendered. * \see setVisible() */ bool isVisible() const { return mVisible; } /** * Sets whether the annotation is visible and should be rendered. * \see isVisible() */ void setVisible( bool visible ); /** * Returns true if the annotation is attached to a fixed map position, or * false if the annotation uses a position relative to the current map * extent. * \see setHasFixedMapPosition() * \see mapPosition() * \see relativePosition() */ bool hasFixedMapPosition() const { return mHasFixedMapPosition; } /** * Sets whether the annotation is attached to a fixed map position, or * uses a position relative to the current map extent. * \see hasFixedMapPosition() */ void setHasFixedMapPosition( bool fixed ); /** * Returns the map position of the annotation, if it is attached to a fixed map * position. * \see setMapPosition() * \see hasFixedMapPosition() * \see mapPositionCrs() */ QgsPointXY mapPosition() const { return mMapPosition; } /** * Sets the map position of the annotation, if it is attached to a fixed map * position. * \see mapPosition() */ void setMapPosition( const QgsPointXY &position ); /** * Returns the CRS of the map position, or an invalid CRS if the annotation does * not have a fixed map position. * \see setMapPositionCrs() */ QgsCoordinateReferenceSystem mapPositionCrs() const { return mMapPositionCrs; } /** * Sets the CRS of the map position. * \see mapPositionCrs() */ void setMapPositionCrs( const QgsCoordinateReferenceSystem &crs ); /** * Returns the relative position of the annotation, if it is not attached to a fixed map * position. The coordinates in the return point should be between 0 and 1, and represent * the relative percentage for the position compared to the map width and height. * \see setRelativePosition() */ QPointF relativePosition() const { return mRelativePosition; } /** * Sets the relative position of the annotation, if it is not attached to a fixed map * position. The coordinates in the return point should be between 0 and 1, and represent * the relative percentage for the position compared to the map width and height. * \see relativePosition() */ void setRelativePosition( QPointF position ); /** * Sets the annotation's frame's offset from the mapPosition() reference point. * \see frameOffsetFromReferencePoint() */ void setFrameOffsetFromReferencePoint( QPointF offset ); /** * Returns the annotation's frame's offset from the mapPosition() reference point. * \see setFrameOffsetFromReferencePoint() */ QPointF frameOffsetFromReferencePoint() const { return mOffsetFromReferencePoint; } /** * Sets the size of the annotation's frame (the main area in which * the annotation's content is drawn). * \see frameSize() */ void setFrameSize( QSizeF size ); /** * Returns the size of the annotation's frame (the main area in which * the annotation's content is drawn). * \see setFrameSize() */ QSizeF frameSize() const { return mFrameSize; } /** * Sets the margins (in millimeters) between the outside of the frame and the annotation * content. * \see contentsMargin() */ void setContentsMargin( const QgsMargins &margins ); /** * Returns the margins (in millimeters) between the outside of the frame and the annotation * content. * \see setContentsMargin() */ QgsMargins contentsMargin() const { return mContentsMargins; } /** * Sets the fill symbol used for rendering the annotation frame. Ownership * of the symbol is transferred to the annotation. * \see fillSymbol() */ void setFillSymbol( QgsFillSymbol *symbol SIP_TRANSFER ); /** * Returns the symbol that is used for rendering the annotation frame. * \see setFillSymbol() */ QgsFillSymbol *fillSymbol() const { return mFillSymbol.get(); } /** * Renders the annotation to a target render context. */ void render( QgsRenderContext &context ) const; /** * Writes the annotation state to a DOM element. Derived classes should * call _writeXml() within their implementation of this method. * \see readXml() * \see _writeXml() */ virtual void writeXml( QDomElement &elem, QDomDocument &doc, const QgsReadWriteContext &context ) const = 0; /** * Restores the annotation's state from a DOM element. Derived classes should * call _readXml() within their implementation of this method. * \see writeXml() * \see _readXml() */ virtual void readXml( const QDomElement &itemElem, const QgsReadWriteContext &context ) = 0; /** * Sets the symbol that is drawn at the annotation's map position. Ownership * of the symbol is transferred to the annotation. * \see markerSymbol() */ void setMarkerSymbol( QgsMarkerSymbol *symbol SIP_TRANSFER ); /** * Returns the symbol that is drawn at the annotation's map position. * \see setMarkerSymbol() */ QgsMarkerSymbol *markerSymbol() const { return mMarkerSymbol.get(); } /** * Returns the map layer associated with the annotation. Annotations can be * associated with a map layer if their visibility should be synchronized * with the layer's visibility. * \see setMapLayer() */ QgsMapLayer *mapLayer() const { return mMapLayer.data(); } /** * Sets the map layer associated with the annotation. Annotations can be * associated with a map layer if their visibility should be synchronized * with the layer's visibility. * \see mapLayer() */ void setMapLayer( QgsMapLayer *layer ); /** * Returns the feature associated with the annotation, or an invalid * feature if none has been set. * \see setAssociatedFeature() */ QgsFeature associatedFeature() const { return mFeature; } /** * Sets the feature associated with the annotation. * \see associatedFeature() */ virtual void setAssociatedFeature( const QgsFeature &feature ); signals: //! Emitted whenever the annotation's appearance changes void appearanceChanged(); /** * Emitted when the annotation's position has changed and items need * to be moved to reflect this. */ void moved(); /** * Emitted when the map layer associated with the annotation changes. */ void mapLayerChanged(); protected: /** * Renders the annotation's contents to a target /a context at the specified /a size. * Derived classes should implement their custom annotation drawing logic here. */ virtual void renderAnnotation( QgsRenderContext &context, QSizeF size ) const = 0; /** * Returns the minimum frame size for the annotation. Subclasses should implement this if they * cannot be resized smaller than a certain minimum size. */ virtual QSizeF minimumFrameSize() const; /** * Writes common annotation properties to a DOM element. * This method should be called from subclasses in their writeXml method. * \see writeXml() * \see _readXml() */ void _writeXml( QDomElement &itemElem, QDomDocument &doc, const QgsReadWriteContext &context ) const; /** * Reads common annotation properties from a DOM element. * This method should be called from subclasses in their readXml method. * \see readXml() * \see _writeXml() */ void _readXml( const QDomElement &annotationElem, const QgsReadWriteContext &context ); /** * Copies common annotation properties to the \a targe * annotation. * Can be used within QgsAnnotation::clone() implementations * to assist with creating copies. */ void copyCommonProperties( QgsAnnotation *target ) const; private: //! Check where to attach the balloon connection between frame and map point void updateBalloon(); //! Gets the frame line (0 is the top line, 1 right, 2 bottom, 3 left) QLineF segment( int index ) const; //! Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point QPointF pointOnLineWithDistance( QPointF startPoint, QPointF directionPoint, double distance ) const; //! Draws the annotation frame to a destination painter void drawFrame( QgsRenderContext &context ) const; //! Draws the map position marker symbol to a destination painter void drawMarkerSymbol( QgsRenderContext &context ) const; bool mVisible = true; //! True if the item stays at the same map position, false if the item stays on same screen position bool mHasFixedMapPosition = true; //! Map position (for fixed position items) QgsPointXY mMapPosition; //! CRS of the map position QgsCoordinateReferenceSystem mMapPositionCrs; //! Relative position (for non-fixed items) (0-1) QPointF mRelativePosition; //! Describes the shift of the item content box to the reference point QPointF mOffsetFromReferencePoint = QPointF( 50, -50 ); //! Size of the frame (without balloon) QSizeF mFrameSize; //! Point symbol that is to be drawn at the map reference location std::unique_ptr<QgsMarkerSymbol> mMarkerSymbol; QgsMargins mContentsMargins; //! Fill symbol used for drawing annotation std::unique_ptr<QgsFillSymbol> mFillSymbol; //! Segment number where the connection to the map point is attached. -1 if no balloon needed (e.g. if point is contained in frame) int mBalloonSegment = -1; //! First segment point for drawing the connection (ccw direction) QPointF mBalloonSegmentPoint1; //! Second segment point for drawing the balloon connection (ccw direction) QPointF mBalloonSegmentPoint2; //! Associated layer (or nullptr if not attached to a layer) QgsWeakMapLayerPointer mMapLayer; //! Associated feature, or invalid feature if no feature associated QgsFeature mFeature; }; #endif // QGSANNOTATION_H
dwadler/QGIS
src/core/annotations/qgsannotation.h
C
gpl-2.0
13,452
/* Broadcom NetXtreme-C/E network driver. * * Copyright (c) 2014-2016 Broadcom Corporation * Copyright (c) 2016-2019 Broadcom Limited * * 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. */ #include <linux/module.h> #include <linux/stringify.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/dma-mapping.h> #include <linux/bitops.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/delay.h> #include <asm/byteorder.h> #include <asm/page.h> #include <linux/time.h> #include <linux/mii.h> #include <linux/mdio.h> #include <linux/if.h> #include <linux/if_vlan.h> #include <linux/if_bridge.h> #include <linux/rtc.h> #include <linux/bpf.h> #include <net/ip.h> #include <net/tcp.h> #include <net/udp.h> #include <net/checksum.h> #include <net/ip6_checksum.h> #include <net/udp_tunnel.h> #include <linux/workqueue.h> #include <linux/prefetch.h> #include <linux/cache.h> #include <linux/log2.h> #include <linux/aer.h> #include <linux/bitmap.h> #include <linux/cpu_rmap.h> #include <linux/cpumask.h> #include <net/pkt_cls.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <net/page_pool.h> #include "bnxt_hsi.h" #include "bnxt.h" #include "bnxt_ulp.h" #include "bnxt_sriov.h" #include "bnxt_ethtool.h" #include "bnxt_dcb.h" #include "bnxt_xdp.h" #include "bnxt_vfr.h" #include "bnxt_tc.h" #include "bnxt_devlink.h" #include "bnxt_debugfs.h" #define BNXT_TX_TIMEOUT (5 * HZ) MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Broadcom BCM573xx network driver"); #define BNXT_RX_OFFSET (NET_SKB_PAD + NET_IP_ALIGN) #define BNXT_RX_DMA_OFFSET NET_SKB_PAD #define BNXT_RX_COPY_THRESH 256 #define BNXT_TX_PUSH_THRESH 164 enum board_idx { BCM57301, BCM57302, BCM57304, BCM57417_NPAR, BCM58700, BCM57311, BCM57312, BCM57402, BCM57404, BCM57406, BCM57402_NPAR, BCM57407, BCM57412, BCM57414, BCM57416, BCM57417, BCM57412_NPAR, BCM57314, BCM57417_SFP, BCM57416_SFP, BCM57404_NPAR, BCM57406_NPAR, BCM57407_SFP, BCM57407_NPAR, BCM57414_NPAR, BCM57416_NPAR, BCM57452, BCM57454, BCM5745x_NPAR, BCM57508, BCM57504, BCM57502, BCM57508_NPAR, BCM57504_NPAR, BCM57502_NPAR, BCM58802, BCM58804, BCM58808, NETXTREME_E_VF, NETXTREME_C_VF, NETXTREME_S_VF, NETXTREME_E_P5_VF, }; /* indexed by enum above */ static const struct { char *name; } board_info[] = { [BCM57301] = { "Broadcom BCM57301 NetXtreme-C 10Gb Ethernet" }, [BCM57302] = { "Broadcom BCM57302 NetXtreme-C 10Gb/25Gb Ethernet" }, [BCM57304] = { "Broadcom BCM57304 NetXtreme-C 10Gb/25Gb/40Gb/50Gb Ethernet" }, [BCM57417_NPAR] = { "Broadcom BCM57417 NetXtreme-E Ethernet Partition" }, [BCM58700] = { "Broadcom BCM58700 Nitro 1Gb/2.5Gb/10Gb Ethernet" }, [BCM57311] = { "Broadcom BCM57311 NetXtreme-C 10Gb Ethernet" }, [BCM57312] = { "Broadcom BCM57312 NetXtreme-C 10Gb/25Gb Ethernet" }, [BCM57402] = { "Broadcom BCM57402 NetXtreme-E 10Gb Ethernet" }, [BCM57404] = { "Broadcom BCM57404 NetXtreme-E 10Gb/25Gb Ethernet" }, [BCM57406] = { "Broadcom BCM57406 NetXtreme-E 10GBase-T Ethernet" }, [BCM57402_NPAR] = { "Broadcom BCM57402 NetXtreme-E Ethernet Partition" }, [BCM57407] = { "Broadcom BCM57407 NetXtreme-E 10GBase-T Ethernet" }, [BCM57412] = { "Broadcom BCM57412 NetXtreme-E 10Gb Ethernet" }, [BCM57414] = { "Broadcom BCM57414 NetXtreme-E 10Gb/25Gb Ethernet" }, [BCM57416] = { "Broadcom BCM57416 NetXtreme-E 10GBase-T Ethernet" }, [BCM57417] = { "Broadcom BCM57417 NetXtreme-E 10GBase-T Ethernet" }, [BCM57412_NPAR] = { "Broadcom BCM57412 NetXtreme-E Ethernet Partition" }, [BCM57314] = { "Broadcom BCM57314 NetXtreme-C 10Gb/25Gb/40Gb/50Gb Ethernet" }, [BCM57417_SFP] = { "Broadcom BCM57417 NetXtreme-E 10Gb/25Gb Ethernet" }, [BCM57416_SFP] = { "Broadcom BCM57416 NetXtreme-E 10Gb Ethernet" }, [BCM57404_NPAR] = { "Broadcom BCM57404 NetXtreme-E Ethernet Partition" }, [BCM57406_NPAR] = { "Broadcom BCM57406 NetXtreme-E Ethernet Partition" }, [BCM57407_SFP] = { "Broadcom BCM57407 NetXtreme-E 25Gb Ethernet" }, [BCM57407_NPAR] = { "Broadcom BCM57407 NetXtreme-E Ethernet Partition" }, [BCM57414_NPAR] = { "Broadcom BCM57414 NetXtreme-E Ethernet Partition" }, [BCM57416_NPAR] = { "Broadcom BCM57416 NetXtreme-E Ethernet Partition" }, [BCM57452] = { "Broadcom BCM57452 NetXtreme-E 10Gb/25Gb/40Gb/50Gb Ethernet" }, [BCM57454] = { "Broadcom BCM57454 NetXtreme-E 10Gb/25Gb/40Gb/50Gb/100Gb Ethernet" }, [BCM5745x_NPAR] = { "Broadcom BCM5745x NetXtreme-E Ethernet Partition" }, [BCM57508] = { "Broadcom BCM57508 NetXtreme-E 10Gb/25Gb/50Gb/100Gb/200Gb Ethernet" }, [BCM57504] = { "Broadcom BCM57504 NetXtreme-E 10Gb/25Gb/50Gb/100Gb/200Gb Ethernet" }, [BCM57502] = { "Broadcom BCM57502 NetXtreme-E 10Gb/25Gb/50Gb Ethernet" }, [BCM57508_NPAR] = { "Broadcom BCM57508 NetXtreme-E Ethernet Partition" }, [BCM57504_NPAR] = { "Broadcom BCM57504 NetXtreme-E Ethernet Partition" }, [BCM57502_NPAR] = { "Broadcom BCM57502 NetXtreme-E Ethernet Partition" }, [BCM58802] = { "Broadcom BCM58802 NetXtreme-S 10Gb/25Gb/40Gb/50Gb Ethernet" }, [BCM58804] = { "Broadcom BCM58804 NetXtreme-S 10Gb/25Gb/40Gb/50Gb/100Gb Ethernet" }, [BCM58808] = { "Broadcom BCM58808 NetXtreme-S 10Gb/25Gb/40Gb/50Gb/100Gb Ethernet" }, [NETXTREME_E_VF] = { "Broadcom NetXtreme-E Ethernet Virtual Function" }, [NETXTREME_C_VF] = { "Broadcom NetXtreme-C Ethernet Virtual Function" }, [NETXTREME_S_VF] = { "Broadcom NetXtreme-S Ethernet Virtual Function" }, [NETXTREME_E_P5_VF] = { "Broadcom BCM5750X NetXtreme-E Ethernet Virtual Function" }, }; static const struct pci_device_id bnxt_pci_tbl[] = { { PCI_VDEVICE(BROADCOM, 0x1604), .driver_data = BCM5745x_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1605), .driver_data = BCM5745x_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1614), .driver_data = BCM57454 }, { PCI_VDEVICE(BROADCOM, 0x16c0), .driver_data = BCM57417_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16c8), .driver_data = BCM57301 }, { PCI_VDEVICE(BROADCOM, 0x16c9), .driver_data = BCM57302 }, { PCI_VDEVICE(BROADCOM, 0x16ca), .driver_data = BCM57304 }, { PCI_VDEVICE(BROADCOM, 0x16cc), .driver_data = BCM57417_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16cd), .driver_data = BCM58700 }, { PCI_VDEVICE(BROADCOM, 0x16ce), .driver_data = BCM57311 }, { PCI_VDEVICE(BROADCOM, 0x16cf), .driver_data = BCM57312 }, { PCI_VDEVICE(BROADCOM, 0x16d0), .driver_data = BCM57402 }, { PCI_VDEVICE(BROADCOM, 0x16d1), .driver_data = BCM57404 }, { PCI_VDEVICE(BROADCOM, 0x16d2), .driver_data = BCM57406 }, { PCI_VDEVICE(BROADCOM, 0x16d4), .driver_data = BCM57402_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16d5), .driver_data = BCM57407 }, { PCI_VDEVICE(BROADCOM, 0x16d6), .driver_data = BCM57412 }, { PCI_VDEVICE(BROADCOM, 0x16d7), .driver_data = BCM57414 }, { PCI_VDEVICE(BROADCOM, 0x16d8), .driver_data = BCM57416 }, { PCI_VDEVICE(BROADCOM, 0x16d9), .driver_data = BCM57417 }, { PCI_VDEVICE(BROADCOM, 0x16de), .driver_data = BCM57412_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16df), .driver_data = BCM57314 }, { PCI_VDEVICE(BROADCOM, 0x16e2), .driver_data = BCM57417_SFP }, { PCI_VDEVICE(BROADCOM, 0x16e3), .driver_data = BCM57416_SFP }, { PCI_VDEVICE(BROADCOM, 0x16e7), .driver_data = BCM57404_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16e8), .driver_data = BCM57406_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16e9), .driver_data = BCM57407_SFP }, { PCI_VDEVICE(BROADCOM, 0x16ea), .driver_data = BCM57407_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16eb), .driver_data = BCM57412_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16ec), .driver_data = BCM57414_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16ed), .driver_data = BCM57414_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16ee), .driver_data = BCM57416_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16ef), .driver_data = BCM57416_NPAR }, { PCI_VDEVICE(BROADCOM, 0x16f0), .driver_data = BCM58808 }, { PCI_VDEVICE(BROADCOM, 0x16f1), .driver_data = BCM57452 }, { PCI_VDEVICE(BROADCOM, 0x1750), .driver_data = BCM57508 }, { PCI_VDEVICE(BROADCOM, 0x1751), .driver_data = BCM57504 }, { PCI_VDEVICE(BROADCOM, 0x1752), .driver_data = BCM57502 }, { PCI_VDEVICE(BROADCOM, 0x1800), .driver_data = BCM57508_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1801), .driver_data = BCM57504_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1802), .driver_data = BCM57502_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1803), .driver_data = BCM57508_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1804), .driver_data = BCM57504_NPAR }, { PCI_VDEVICE(BROADCOM, 0x1805), .driver_data = BCM57502_NPAR }, { PCI_VDEVICE(BROADCOM, 0xd802), .driver_data = BCM58802 }, { PCI_VDEVICE(BROADCOM, 0xd804), .driver_data = BCM58804 }, #ifdef CONFIG_BNXT_SRIOV { PCI_VDEVICE(BROADCOM, 0x1606), .driver_data = NETXTREME_E_VF }, { PCI_VDEVICE(BROADCOM, 0x1609), .driver_data = NETXTREME_E_VF }, { PCI_VDEVICE(BROADCOM, 0x16c1), .driver_data = NETXTREME_E_VF }, { PCI_VDEVICE(BROADCOM, 0x16cb), .driver_data = NETXTREME_C_VF }, { PCI_VDEVICE(BROADCOM, 0x16d3), .driver_data = NETXTREME_E_VF }, { PCI_VDEVICE(BROADCOM, 0x16dc), .driver_data = NETXTREME_E_VF }, { PCI_VDEVICE(BROADCOM, 0x16e1), .driver_data = NETXTREME_C_VF }, { PCI_VDEVICE(BROADCOM, 0x16e5), .driver_data = NETXTREME_C_VF }, { PCI_VDEVICE(BROADCOM, 0x1806), .driver_data = NETXTREME_E_P5_VF }, { PCI_VDEVICE(BROADCOM, 0x1807), .driver_data = NETXTREME_E_P5_VF }, { PCI_VDEVICE(BROADCOM, 0xd800), .driver_data = NETXTREME_S_VF }, #endif { 0 } }; MODULE_DEVICE_TABLE(pci, bnxt_pci_tbl); static const u16 bnxt_vf_req_snif[] = { HWRM_FUNC_CFG, HWRM_FUNC_VF_CFG, HWRM_PORT_PHY_QCFG, HWRM_CFA_L2_FILTER_ALLOC, }; static const u16 bnxt_async_events_arr[] = { ASYNC_EVENT_CMPL_EVENT_ID_LINK_STATUS_CHANGE, ASYNC_EVENT_CMPL_EVENT_ID_LINK_SPEED_CHANGE, ASYNC_EVENT_CMPL_EVENT_ID_PF_DRVR_UNLOAD, ASYNC_EVENT_CMPL_EVENT_ID_PORT_CONN_NOT_ALLOWED, ASYNC_EVENT_CMPL_EVENT_ID_VF_CFG_CHANGE, ASYNC_EVENT_CMPL_EVENT_ID_LINK_SPEED_CFG_CHANGE, ASYNC_EVENT_CMPL_EVENT_ID_PORT_PHY_CFG_CHANGE, ASYNC_EVENT_CMPL_EVENT_ID_RESET_NOTIFY, ASYNC_EVENT_CMPL_EVENT_ID_ERROR_RECOVERY, }; static struct workqueue_struct *bnxt_pf_wq; static bool bnxt_vf_pciid(enum board_idx idx) { return (idx == NETXTREME_C_VF || idx == NETXTREME_E_VF || idx == NETXTREME_S_VF || idx == NETXTREME_E_P5_VF); } #define DB_CP_REARM_FLAGS (DB_KEY_CP | DB_IDX_VALID) #define DB_CP_FLAGS (DB_KEY_CP | DB_IDX_VALID | DB_IRQ_DIS) #define DB_CP_IRQ_DIS_FLAGS (DB_KEY_CP | DB_IRQ_DIS) #define BNXT_CP_DB_IRQ_DIS(db) \ writel(DB_CP_IRQ_DIS_FLAGS, db) #define BNXT_DB_CQ(db, idx) \ writel(DB_CP_FLAGS | RING_CMP(idx), (db)->doorbell) #define BNXT_DB_NQ_P5(db, idx) \ writeq((db)->db_key64 | DBR_TYPE_NQ | RING_CMP(idx), (db)->doorbell) #define BNXT_DB_CQ_ARM(db, idx) \ writel(DB_CP_REARM_FLAGS | RING_CMP(idx), (db)->doorbell) #define BNXT_DB_NQ_ARM_P5(db, idx) \ writeq((db)->db_key64 | DBR_TYPE_NQ_ARM | RING_CMP(idx), (db)->doorbell) static void bnxt_db_nq(struct bnxt *bp, struct bnxt_db_info *db, u32 idx) { if (bp->flags & BNXT_FLAG_CHIP_P5) BNXT_DB_NQ_P5(db, idx); else BNXT_DB_CQ(db, idx); } static void bnxt_db_nq_arm(struct bnxt *bp, struct bnxt_db_info *db, u32 idx) { if (bp->flags & BNXT_FLAG_CHIP_P5) BNXT_DB_NQ_ARM_P5(db, idx); else BNXT_DB_CQ_ARM(db, idx); } static void bnxt_db_cq(struct bnxt *bp, struct bnxt_db_info *db, u32 idx) { if (bp->flags & BNXT_FLAG_CHIP_P5) writeq(db->db_key64 | DBR_TYPE_CQ_ARMALL | RING_CMP(idx), db->doorbell); else BNXT_DB_CQ(db, idx); } const u16 bnxt_lhint_arr[] = { TX_BD_FLAGS_LHINT_512_AND_SMALLER, TX_BD_FLAGS_LHINT_512_TO_1023, TX_BD_FLAGS_LHINT_1024_TO_2047, TX_BD_FLAGS_LHINT_1024_TO_2047, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, TX_BD_FLAGS_LHINT_2048_AND_LARGER, }; static u16 bnxt_xmit_get_cfa_action(struct sk_buff *skb) { struct metadata_dst *md_dst = skb_metadata_dst(skb); if (!md_dst || md_dst->type != METADATA_HW_PORT_MUX) return 0; return md_dst->u.port_info.port_id; } static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct bnxt *bp = netdev_priv(dev); struct tx_bd *txbd; struct tx_bd_ext *txbd1; struct netdev_queue *txq; int i; dma_addr_t mapping; unsigned int length, pad = 0; u32 len, free_size, vlan_tag_flags, cfa_action, flags; u16 prod, last_frag; struct pci_dev *pdev = bp->pdev; struct bnxt_tx_ring_info *txr; struct bnxt_sw_tx_bd *tx_buf; i = skb_get_queue_mapping(skb); if (unlikely(i >= bp->tx_nr_rings)) { dev_kfree_skb_any(skb); return NETDEV_TX_OK; } txq = netdev_get_tx_queue(dev, i); txr = &bp->tx_ring[bp->tx_ring_map[i]]; prod = txr->tx_prod; free_size = bnxt_tx_avail(bp, txr); if (unlikely(free_size < skb_shinfo(skb)->nr_frags + 2)) { netif_tx_stop_queue(txq); return NETDEV_TX_BUSY; } length = skb->len; len = skb_headlen(skb); last_frag = skb_shinfo(skb)->nr_frags; txbd = &txr->tx_desc_ring[TX_RING(prod)][TX_IDX(prod)]; txbd->tx_bd_opaque = prod; tx_buf = &txr->tx_buf_ring[prod]; tx_buf->skb = skb; tx_buf->nr_frags = last_frag; vlan_tag_flags = 0; cfa_action = bnxt_xmit_get_cfa_action(skb); if (skb_vlan_tag_present(skb)) { vlan_tag_flags = TX_BD_CFA_META_KEY_VLAN | skb_vlan_tag_get(skb); /* Currently supports 8021Q, 8021AD vlan offloads * QINQ1, QINQ2, QINQ3 vlan headers are deprecated */ if (skb->vlan_proto == htons(ETH_P_8021Q)) vlan_tag_flags |= 1 << TX_BD_CFA_META_TPID_SHIFT; } if (free_size == bp->tx_ring_size && length <= bp->tx_push_thresh) { struct tx_push_buffer *tx_push_buf = txr->tx_push; struct tx_push_bd *tx_push = &tx_push_buf->push_bd; struct tx_bd_ext *tx_push1 = &tx_push->txbd2; void __iomem *db = txr->tx_db.doorbell; void *pdata = tx_push_buf->data; u64 *end; int j, push_len; /* Set COAL_NOW to be ready quickly for the next push */ tx_push->tx_bd_len_flags_type = cpu_to_le32((length << TX_BD_LEN_SHIFT) | TX_BD_TYPE_LONG_TX_BD | TX_BD_FLAGS_LHINT_512_AND_SMALLER | TX_BD_FLAGS_COAL_NOW | TX_BD_FLAGS_PACKET_END | (2 << TX_BD_FLAGS_BD_CNT_SHIFT)); if (skb->ip_summed == CHECKSUM_PARTIAL) tx_push1->tx_bd_hsize_lflags = cpu_to_le32(TX_BD_FLAGS_TCP_UDP_CHKSUM); else tx_push1->tx_bd_hsize_lflags = 0; tx_push1->tx_bd_cfa_meta = cpu_to_le32(vlan_tag_flags); tx_push1->tx_bd_cfa_action = cpu_to_le32(cfa_action << TX_BD_CFA_ACTION_SHIFT); end = pdata + length; end = PTR_ALIGN(end, 8) - 1; *end = 0; skb_copy_from_linear_data(skb, pdata, len); pdata += len; for (j = 0; j < last_frag; j++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[j]; void *fptr; fptr = skb_frag_address_safe(frag); if (!fptr) goto normal_tx; memcpy(pdata, fptr, skb_frag_size(frag)); pdata += skb_frag_size(frag); } txbd->tx_bd_len_flags_type = tx_push->tx_bd_len_flags_type; txbd->tx_bd_haddr = txr->data_mapping; prod = NEXT_TX(prod); txbd = &txr->tx_desc_ring[TX_RING(prod)][TX_IDX(prod)]; memcpy(txbd, tx_push1, sizeof(*txbd)); prod = NEXT_TX(prod); tx_push->doorbell = cpu_to_le32(DB_KEY_TX_PUSH | DB_LONG_TX_PUSH | prod); txr->tx_prod = prod; tx_buf->is_push = 1; netdev_tx_sent_queue(txq, skb->len); wmb(); /* Sync is_push and byte queue before pushing data */ push_len = (length + sizeof(*tx_push) + 7) / 8; if (push_len > 16) { __iowrite64_copy(db, tx_push_buf, 16); __iowrite32_copy(db + 4, tx_push_buf + 1, (push_len - 16) << 1); } else { __iowrite64_copy(db, tx_push_buf, push_len); } goto tx_done; } normal_tx: if (length < BNXT_MIN_PKT_SIZE) { pad = BNXT_MIN_PKT_SIZE - length; if (skb_pad(skb, pad)) { /* SKB already freed. */ tx_buf->skb = NULL; return NETDEV_TX_OK; } length = BNXT_MIN_PKT_SIZE; } mapping = dma_map_single(&pdev->dev, skb->data, len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(&pdev->dev, mapping))) { dev_kfree_skb_any(skb); tx_buf->skb = NULL; return NETDEV_TX_OK; } dma_unmap_addr_set(tx_buf, mapping, mapping); flags = (len << TX_BD_LEN_SHIFT) | TX_BD_TYPE_LONG_TX_BD | ((last_frag + 2) << TX_BD_FLAGS_BD_CNT_SHIFT); txbd->tx_bd_haddr = cpu_to_le64(mapping); prod = NEXT_TX(prod); txbd1 = (struct tx_bd_ext *) &txr->tx_desc_ring[TX_RING(prod)][TX_IDX(prod)]; txbd1->tx_bd_hsize_lflags = 0; if (skb_is_gso(skb)) { u32 hdr_len; if (skb->encapsulation) hdr_len = skb_inner_network_offset(skb) + skb_inner_network_header_len(skb) + inner_tcp_hdrlen(skb); else hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb); txbd1->tx_bd_hsize_lflags = cpu_to_le32(TX_BD_FLAGS_LSO | TX_BD_FLAGS_T_IPID | (hdr_len << (TX_BD_HSIZE_SHIFT - 1))); length = skb_shinfo(skb)->gso_size; txbd1->tx_bd_mss = cpu_to_le32(length); length += hdr_len; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { txbd1->tx_bd_hsize_lflags = cpu_to_le32(TX_BD_FLAGS_TCP_UDP_CHKSUM); txbd1->tx_bd_mss = 0; } length >>= 9; if (unlikely(length >= ARRAY_SIZE(bnxt_lhint_arr))) { dev_warn_ratelimited(&pdev->dev, "Dropped oversize %d bytes TX packet.\n", skb->len); i = 0; goto tx_dma_error; } flags |= bnxt_lhint_arr[length]; txbd->tx_bd_len_flags_type = cpu_to_le32(flags); txbd1->tx_bd_cfa_meta = cpu_to_le32(vlan_tag_flags); txbd1->tx_bd_cfa_action = cpu_to_le32(cfa_action << TX_BD_CFA_ACTION_SHIFT); for (i = 0; i < last_frag; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; prod = NEXT_TX(prod); txbd = &txr->tx_desc_ring[TX_RING(prod)][TX_IDX(prod)]; len = skb_frag_size(frag); mapping = skb_frag_dma_map(&pdev->dev, frag, 0, len, DMA_TO_DEVICE); if (unlikely(dma_mapping_error(&pdev->dev, mapping))) goto tx_dma_error; tx_buf = &txr->tx_buf_ring[prod]; dma_unmap_addr_set(tx_buf, mapping, mapping); txbd->tx_bd_haddr = cpu_to_le64(mapping); flags = len << TX_BD_LEN_SHIFT; txbd->tx_bd_len_flags_type = cpu_to_le32(flags); } flags &= ~TX_BD_LEN; txbd->tx_bd_len_flags_type = cpu_to_le32(((len + pad) << TX_BD_LEN_SHIFT) | flags | TX_BD_FLAGS_PACKET_END); netdev_tx_sent_queue(txq, skb->len); /* Sync BD data before updating doorbell */ wmb(); prod = NEXT_TX(prod); txr->tx_prod = prod; if (!netdev_xmit_more() || netif_xmit_stopped(txq)) bnxt_db_write(bp, &txr->tx_db, prod); tx_done: if (unlikely(bnxt_tx_avail(bp, txr) <= MAX_SKB_FRAGS + 1)) { if (netdev_xmit_more() && !tx_buf->is_push) bnxt_db_write(bp, &txr->tx_db, prod); netif_tx_stop_queue(txq); /* netif_tx_stop_queue() must be done before checking * tx index in bnxt_tx_avail() below, because in * bnxt_tx_int(), we update tx index before checking for * netif_tx_queue_stopped(). */ smp_mb(); if (bnxt_tx_avail(bp, txr) > bp->tx_wake_thresh) netif_tx_wake_queue(txq); } return NETDEV_TX_OK; tx_dma_error: last_frag = i; /* start back at beginning and unmap skb */ prod = txr->tx_prod; tx_buf = &txr->tx_buf_ring[prod]; tx_buf->skb = NULL; dma_unmap_single(&pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); prod = NEXT_TX(prod); /* unmap remaining mapped pages */ for (i = 0; i < last_frag; i++) { prod = NEXT_TX(prod); tx_buf = &txr->tx_buf_ring[prod]; dma_unmap_page(&pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); } dev_kfree_skb_any(skb); return NETDEV_TX_OK; } static void bnxt_tx_int(struct bnxt *bp, struct bnxt_napi *bnapi, int nr_pkts) { struct bnxt_tx_ring_info *txr = bnapi->tx_ring; struct netdev_queue *txq = netdev_get_tx_queue(bp->dev, txr->txq_index); u16 cons = txr->tx_cons; struct pci_dev *pdev = bp->pdev; int i; unsigned int tx_bytes = 0; for (i = 0; i < nr_pkts; i++) { struct bnxt_sw_tx_bd *tx_buf; struct sk_buff *skb; int j, last; tx_buf = &txr->tx_buf_ring[cons]; cons = NEXT_TX(cons); skb = tx_buf->skb; tx_buf->skb = NULL; if (tx_buf->is_push) { tx_buf->is_push = 0; goto next_tx_int; } dma_unmap_single(&pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); last = tx_buf->nr_frags; for (j = 0; j < last; j++) { cons = NEXT_TX(cons); tx_buf = &txr->tx_buf_ring[cons]; dma_unmap_page( &pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_frag_size(&skb_shinfo(skb)->frags[j]), PCI_DMA_TODEVICE); } next_tx_int: cons = NEXT_TX(cons); tx_bytes += skb->len; dev_kfree_skb_any(skb); } netdev_tx_completed_queue(txq, nr_pkts, tx_bytes); txr->tx_cons = cons; /* Need to make the tx_cons update visible to bnxt_start_xmit() * before checking for netif_tx_queue_stopped(). Without the * memory barrier, there is a small possibility that bnxt_start_xmit() * will miss it and cause the queue to be stopped forever. */ smp_mb(); if (unlikely(netif_tx_queue_stopped(txq)) && (bnxt_tx_avail(bp, txr) > bp->tx_wake_thresh)) { __netif_tx_lock(txq, smp_processor_id()); if (netif_tx_queue_stopped(txq) && bnxt_tx_avail(bp, txr) > bp->tx_wake_thresh && txr->dev_state != BNXT_DEV_STATE_CLOSING) netif_tx_wake_queue(txq); __netif_tx_unlock(txq); } } static struct page *__bnxt_alloc_rx_page(struct bnxt *bp, dma_addr_t *mapping, struct bnxt_rx_ring_info *rxr, gfp_t gfp) { struct device *dev = &bp->pdev->dev; struct page *page; page = page_pool_dev_alloc_pages(rxr->page_pool); if (!page) return NULL; *mapping = dma_map_page_attrs(dev, page, 0, PAGE_SIZE, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); if (dma_mapping_error(dev, *mapping)) { page_pool_recycle_direct(rxr->page_pool, page); return NULL; } *mapping += bp->rx_dma_offset; return page; } static inline u8 *__bnxt_alloc_rx_data(struct bnxt *bp, dma_addr_t *mapping, gfp_t gfp) { u8 *data; struct pci_dev *pdev = bp->pdev; data = kmalloc(bp->rx_buf_size, gfp); if (!data) return NULL; *mapping = dma_map_single_attrs(&pdev->dev, data + bp->rx_dma_offset, bp->rx_buf_use_size, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); if (dma_mapping_error(&pdev->dev, *mapping)) { kfree(data); data = NULL; } return data; } int bnxt_alloc_rx_data(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 prod, gfp_t gfp) { struct rx_bd *rxbd = &rxr->rx_desc_ring[RX_RING(prod)][RX_IDX(prod)]; struct bnxt_sw_rx_bd *rx_buf = &rxr->rx_buf_ring[prod]; dma_addr_t mapping; if (BNXT_RX_PAGE_MODE(bp)) { struct page *page = __bnxt_alloc_rx_page(bp, &mapping, rxr, gfp); if (!page) return -ENOMEM; rx_buf->data = page; rx_buf->data_ptr = page_address(page) + bp->rx_offset; } else { u8 *data = __bnxt_alloc_rx_data(bp, &mapping, gfp); if (!data) return -ENOMEM; rx_buf->data = data; rx_buf->data_ptr = data + bp->rx_offset; } rx_buf->mapping = mapping; rxbd->rx_bd_haddr = cpu_to_le64(mapping); return 0; } void bnxt_reuse_rx_data(struct bnxt_rx_ring_info *rxr, u16 cons, void *data) { u16 prod = rxr->rx_prod; struct bnxt_sw_rx_bd *cons_rx_buf, *prod_rx_buf; struct rx_bd *cons_bd, *prod_bd; prod_rx_buf = &rxr->rx_buf_ring[prod]; cons_rx_buf = &rxr->rx_buf_ring[cons]; prod_rx_buf->data = data; prod_rx_buf->data_ptr = cons_rx_buf->data_ptr; prod_rx_buf->mapping = cons_rx_buf->mapping; prod_bd = &rxr->rx_desc_ring[RX_RING(prod)][RX_IDX(prod)]; cons_bd = &rxr->rx_desc_ring[RX_RING(cons)][RX_IDX(cons)]; prod_bd->rx_bd_haddr = cons_bd->rx_bd_haddr; } static inline u16 bnxt_find_next_agg_idx(struct bnxt_rx_ring_info *rxr, u16 idx) { u16 next, max = rxr->rx_agg_bmap_size; next = find_next_zero_bit(rxr->rx_agg_bmap, max, idx); if (next >= max) next = find_first_zero_bit(rxr->rx_agg_bmap, max); return next; } static inline int bnxt_alloc_rx_page(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 prod, gfp_t gfp) { struct rx_bd *rxbd = &rxr->rx_agg_desc_ring[RX_RING(prod)][RX_IDX(prod)]; struct bnxt_sw_rx_agg_bd *rx_agg_buf; struct pci_dev *pdev = bp->pdev; struct page *page; dma_addr_t mapping; u16 sw_prod = rxr->rx_sw_agg_prod; unsigned int offset = 0; if (PAGE_SIZE > BNXT_RX_PAGE_SIZE) { page = rxr->rx_page; if (!page) { page = alloc_page(gfp); if (!page) return -ENOMEM; rxr->rx_page = page; rxr->rx_page_offset = 0; } offset = rxr->rx_page_offset; rxr->rx_page_offset += BNXT_RX_PAGE_SIZE; if (rxr->rx_page_offset == PAGE_SIZE) rxr->rx_page = NULL; else get_page(page); } else { page = alloc_page(gfp); if (!page) return -ENOMEM; } mapping = dma_map_page_attrs(&pdev->dev, page, offset, BNXT_RX_PAGE_SIZE, PCI_DMA_FROMDEVICE, DMA_ATTR_WEAK_ORDERING); if (dma_mapping_error(&pdev->dev, mapping)) { __free_page(page); return -EIO; } if (unlikely(test_bit(sw_prod, rxr->rx_agg_bmap))) sw_prod = bnxt_find_next_agg_idx(rxr, sw_prod); __set_bit(sw_prod, rxr->rx_agg_bmap); rx_agg_buf = &rxr->rx_agg_ring[sw_prod]; rxr->rx_sw_agg_prod = NEXT_RX_AGG(sw_prod); rx_agg_buf->page = page; rx_agg_buf->offset = offset; rx_agg_buf->mapping = mapping; rxbd->rx_bd_haddr = cpu_to_le64(mapping); rxbd->rx_bd_opaque = sw_prod; return 0; } static struct rx_agg_cmp *bnxt_get_agg(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, u16 cp_cons, u16 curr) { struct rx_agg_cmp *agg; cp_cons = RING_CMP(ADV_RAW_CMP(cp_cons, curr)); agg = (struct rx_agg_cmp *) &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; return agg; } static struct rx_agg_cmp *bnxt_get_tpa_agg_p5(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 agg_id, u16 curr) { struct bnxt_tpa_info *tpa_info = &rxr->rx_tpa[agg_id]; return &tpa_info->agg_arr[curr]; } static void bnxt_reuse_rx_agg_bufs(struct bnxt_cp_ring_info *cpr, u16 idx, u16 start, u32 agg_bufs, bool tpa) { struct bnxt_napi *bnapi = cpr->bnapi; struct bnxt *bp = bnapi->bp; struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; u16 prod = rxr->rx_agg_prod; u16 sw_prod = rxr->rx_sw_agg_prod; bool p5_tpa = false; u32 i; if ((bp->flags & BNXT_FLAG_CHIP_P5) && tpa) p5_tpa = true; for (i = 0; i < agg_bufs; i++) { u16 cons; struct rx_agg_cmp *agg; struct bnxt_sw_rx_agg_bd *cons_rx_buf, *prod_rx_buf; struct rx_bd *prod_bd; struct page *page; if (p5_tpa) agg = bnxt_get_tpa_agg_p5(bp, rxr, idx, start + i); else agg = bnxt_get_agg(bp, cpr, idx, start + i); cons = agg->rx_agg_cmp_opaque; __clear_bit(cons, rxr->rx_agg_bmap); if (unlikely(test_bit(sw_prod, rxr->rx_agg_bmap))) sw_prod = bnxt_find_next_agg_idx(rxr, sw_prod); __set_bit(sw_prod, rxr->rx_agg_bmap); prod_rx_buf = &rxr->rx_agg_ring[sw_prod]; cons_rx_buf = &rxr->rx_agg_ring[cons]; /* It is possible for sw_prod to be equal to cons, so * set cons_rx_buf->page to NULL first. */ page = cons_rx_buf->page; cons_rx_buf->page = NULL; prod_rx_buf->page = page; prod_rx_buf->offset = cons_rx_buf->offset; prod_rx_buf->mapping = cons_rx_buf->mapping; prod_bd = &rxr->rx_agg_desc_ring[RX_RING(prod)][RX_IDX(prod)]; prod_bd->rx_bd_haddr = cpu_to_le64(cons_rx_buf->mapping); prod_bd->rx_bd_opaque = sw_prod; prod = NEXT_RX_AGG(prod); sw_prod = NEXT_RX_AGG(sw_prod); } rxr->rx_agg_prod = prod; rxr->rx_sw_agg_prod = sw_prod; } static struct sk_buff *bnxt_rx_page_skb(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons, void *data, u8 *data_ptr, dma_addr_t dma_addr, unsigned int offset_and_len) { unsigned int payload = offset_and_len >> 16; unsigned int len = offset_and_len & 0xffff; skb_frag_t *frag; struct page *page = data; u16 prod = rxr->rx_prod; struct sk_buff *skb; int off, err; err = bnxt_alloc_rx_data(bp, rxr, prod, GFP_ATOMIC); if (unlikely(err)) { bnxt_reuse_rx_data(rxr, cons, data); return NULL; } dma_addr -= bp->rx_dma_offset; dma_unmap_page_attrs(&bp->pdev->dev, dma_addr, PAGE_SIZE, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); page_pool_release_page(rxr->page_pool, page); if (unlikely(!payload)) payload = eth_get_headlen(bp->dev, data_ptr, len); skb = napi_alloc_skb(&rxr->bnapi->napi, payload); if (!skb) { __free_page(page); return NULL; } off = (void *)data_ptr - page_address(page); skb_add_rx_frag(skb, 0, page, off, len, PAGE_SIZE); memcpy(skb->data - NET_IP_ALIGN, data_ptr - NET_IP_ALIGN, payload + NET_IP_ALIGN); frag = &skb_shinfo(skb)->frags[0]; skb_frag_size_sub(frag, payload); skb_frag_off_add(frag, payload); skb->data_len -= payload; skb->tail += payload; return skb; } static struct sk_buff *bnxt_rx_skb(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons, void *data, u8 *data_ptr, dma_addr_t dma_addr, unsigned int offset_and_len) { u16 prod = rxr->rx_prod; struct sk_buff *skb; int err; err = bnxt_alloc_rx_data(bp, rxr, prod, GFP_ATOMIC); if (unlikely(err)) { bnxt_reuse_rx_data(rxr, cons, data); return NULL; } skb = build_skb(data, 0); dma_unmap_single_attrs(&bp->pdev->dev, dma_addr, bp->rx_buf_use_size, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); if (!skb) { kfree(data); return NULL; } skb_reserve(skb, bp->rx_offset); skb_put(skb, offset_and_len & 0xffff); return skb; } static struct sk_buff *bnxt_rx_pages(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, struct sk_buff *skb, u16 idx, u32 agg_bufs, bool tpa) { struct bnxt_napi *bnapi = cpr->bnapi; struct pci_dev *pdev = bp->pdev; struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; u16 prod = rxr->rx_agg_prod; bool p5_tpa = false; u32 i; if ((bp->flags & BNXT_FLAG_CHIP_P5) && tpa) p5_tpa = true; for (i = 0; i < agg_bufs; i++) { u16 cons, frag_len; struct rx_agg_cmp *agg; struct bnxt_sw_rx_agg_bd *cons_rx_buf; struct page *page; dma_addr_t mapping; if (p5_tpa) agg = bnxt_get_tpa_agg_p5(bp, rxr, idx, i); else agg = bnxt_get_agg(bp, cpr, idx, i); cons = agg->rx_agg_cmp_opaque; frag_len = (le32_to_cpu(agg->rx_agg_cmp_len_flags_type) & RX_AGG_CMP_LEN) >> RX_AGG_CMP_LEN_SHIFT; cons_rx_buf = &rxr->rx_agg_ring[cons]; skb_fill_page_desc(skb, i, cons_rx_buf->page, cons_rx_buf->offset, frag_len); __clear_bit(cons, rxr->rx_agg_bmap); /* It is possible for bnxt_alloc_rx_page() to allocate * a sw_prod index that equals the cons index, so we * need to clear the cons entry now. */ mapping = cons_rx_buf->mapping; page = cons_rx_buf->page; cons_rx_buf->page = NULL; if (bnxt_alloc_rx_page(bp, rxr, prod, GFP_ATOMIC) != 0) { struct skb_shared_info *shinfo; unsigned int nr_frags; shinfo = skb_shinfo(skb); nr_frags = --shinfo->nr_frags; __skb_frag_set_page(&shinfo->frags[nr_frags], NULL); dev_kfree_skb(skb); cons_rx_buf->page = page; /* Update prod since possibly some pages have been * allocated already. */ rxr->rx_agg_prod = prod; bnxt_reuse_rx_agg_bufs(cpr, idx, i, agg_bufs - i, tpa); return NULL; } dma_unmap_page_attrs(&pdev->dev, mapping, BNXT_RX_PAGE_SIZE, PCI_DMA_FROMDEVICE, DMA_ATTR_WEAK_ORDERING); skb->data_len += frag_len; skb->len += frag_len; skb->truesize += PAGE_SIZE; prod = NEXT_RX_AGG(prod); } rxr->rx_agg_prod = prod; return skb; } static int bnxt_agg_bufs_valid(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, u8 agg_bufs, u32 *raw_cons) { u16 last; struct rx_agg_cmp *agg; *raw_cons = ADV_RAW_CMP(*raw_cons, agg_bufs); last = RING_CMP(*raw_cons); agg = (struct rx_agg_cmp *) &cpr->cp_desc_ring[CP_RING(last)][CP_IDX(last)]; return RX_AGG_CMP_VALID(agg, *raw_cons); } static inline struct sk_buff *bnxt_copy_skb(struct bnxt_napi *bnapi, u8 *data, unsigned int len, dma_addr_t mapping) { struct bnxt *bp = bnapi->bp; struct pci_dev *pdev = bp->pdev; struct sk_buff *skb; skb = napi_alloc_skb(&bnapi->napi, len); if (!skb) return NULL; dma_sync_single_for_cpu(&pdev->dev, mapping, bp->rx_copy_thresh, bp->rx_dir); memcpy(skb->data - NET_IP_ALIGN, data - NET_IP_ALIGN, len + NET_IP_ALIGN); dma_sync_single_for_device(&pdev->dev, mapping, bp->rx_copy_thresh, bp->rx_dir); skb_put(skb, len); return skb; } static int bnxt_discard_rx(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, u32 *raw_cons, void *cmp) { struct rx_cmp *rxcmp = cmp; u32 tmp_raw_cons = *raw_cons; u8 cmp_type, agg_bufs = 0; cmp_type = RX_CMP_TYPE(rxcmp); if (cmp_type == CMP_TYPE_RX_L2_CMP) { agg_bufs = (le32_to_cpu(rxcmp->rx_cmp_misc_v1) & RX_CMP_AGG_BUFS) >> RX_CMP_AGG_BUFS_SHIFT; } else if (cmp_type == CMP_TYPE_RX_L2_TPA_END_CMP) { struct rx_tpa_end_cmp *tpa_end = cmp; if (bp->flags & BNXT_FLAG_CHIP_P5) return 0; agg_bufs = TPA_END_AGG_BUFS(tpa_end); } if (agg_bufs) { if (!bnxt_agg_bufs_valid(bp, cpr, agg_bufs, &tmp_raw_cons)) return -EBUSY; } *raw_cons = tmp_raw_cons; return 0; } static void bnxt_queue_fw_reset_work(struct bnxt *bp, unsigned long delay) { if (BNXT_PF(bp)) queue_delayed_work(bnxt_pf_wq, &bp->fw_reset_task, delay); else schedule_delayed_work(&bp->fw_reset_task, delay); } static void bnxt_queue_sp_work(struct bnxt *bp) { if (BNXT_PF(bp)) queue_work(bnxt_pf_wq, &bp->sp_task); else schedule_work(&bp->sp_task); } static void bnxt_cancel_sp_work(struct bnxt *bp) { if (BNXT_PF(bp)) flush_workqueue(bnxt_pf_wq); else cancel_work_sync(&bp->sp_task); } static void bnxt_sched_reset(struct bnxt *bp, struct bnxt_rx_ring_info *rxr) { if (!rxr->bnapi->in_reset) { rxr->bnapi->in_reset = true; set_bit(BNXT_RESET_TASK_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } rxr->rx_next_cons = 0xffff; } static u16 bnxt_alloc_agg_idx(struct bnxt_rx_ring_info *rxr, u16 agg_id) { struct bnxt_tpa_idx_map *map = rxr->rx_tpa_idx_map; u16 idx = agg_id & MAX_TPA_P5_MASK; if (test_bit(idx, map->agg_idx_bmap)) idx = find_first_zero_bit(map->agg_idx_bmap, BNXT_AGG_IDX_BMAP_SIZE); __set_bit(idx, map->agg_idx_bmap); map->agg_id_tbl[agg_id] = idx; return idx; } static void bnxt_free_agg_idx(struct bnxt_rx_ring_info *rxr, u16 idx) { struct bnxt_tpa_idx_map *map = rxr->rx_tpa_idx_map; __clear_bit(idx, map->agg_idx_bmap); } static u16 bnxt_lookup_agg_idx(struct bnxt_rx_ring_info *rxr, u16 agg_id) { struct bnxt_tpa_idx_map *map = rxr->rx_tpa_idx_map; return map->agg_id_tbl[agg_id]; } static void bnxt_tpa_start(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, struct rx_tpa_start_cmp *tpa_start, struct rx_tpa_start_cmp_ext *tpa_start1) { struct bnxt_sw_rx_bd *cons_rx_buf, *prod_rx_buf; struct bnxt_tpa_info *tpa_info; u16 cons, prod, agg_id; struct rx_bd *prod_bd; dma_addr_t mapping; if (bp->flags & BNXT_FLAG_CHIP_P5) { agg_id = TPA_START_AGG_ID_P5(tpa_start); agg_id = bnxt_alloc_agg_idx(rxr, agg_id); } else { agg_id = TPA_START_AGG_ID(tpa_start); } cons = tpa_start->rx_tpa_start_cmp_opaque; prod = rxr->rx_prod; cons_rx_buf = &rxr->rx_buf_ring[cons]; prod_rx_buf = &rxr->rx_buf_ring[prod]; tpa_info = &rxr->rx_tpa[agg_id]; if (unlikely(cons != rxr->rx_next_cons || TPA_START_ERROR(tpa_start))) { netdev_warn(bp->dev, "TPA cons %x, expected cons %x, error code %x\n", cons, rxr->rx_next_cons, TPA_START_ERROR_CODE(tpa_start1)); bnxt_sched_reset(bp, rxr); return; } /* Store cfa_code in tpa_info to use in tpa_end * completion processing. */ tpa_info->cfa_code = TPA_START_CFA_CODE(tpa_start1); prod_rx_buf->data = tpa_info->data; prod_rx_buf->data_ptr = tpa_info->data_ptr; mapping = tpa_info->mapping; prod_rx_buf->mapping = mapping; prod_bd = &rxr->rx_desc_ring[RX_RING(prod)][RX_IDX(prod)]; prod_bd->rx_bd_haddr = cpu_to_le64(mapping); tpa_info->data = cons_rx_buf->data; tpa_info->data_ptr = cons_rx_buf->data_ptr; cons_rx_buf->data = NULL; tpa_info->mapping = cons_rx_buf->mapping; tpa_info->len = le32_to_cpu(tpa_start->rx_tpa_start_cmp_len_flags_type) >> RX_TPA_START_CMP_LEN_SHIFT; if (likely(TPA_START_HASH_VALID(tpa_start))) { u32 hash_type = TPA_START_HASH_TYPE(tpa_start); tpa_info->hash_type = PKT_HASH_TYPE_L4; tpa_info->gso_type = SKB_GSO_TCPV4; /* RSS profiles 1 and 3 with extract code 0 for inner 4-tuple */ if (hash_type == 3 || TPA_START_IS_IPV6(tpa_start1)) tpa_info->gso_type = SKB_GSO_TCPV6; tpa_info->rss_hash = le32_to_cpu(tpa_start->rx_tpa_start_cmp_rss_hash); } else { tpa_info->hash_type = PKT_HASH_TYPE_NONE; tpa_info->gso_type = 0; if (netif_msg_rx_err(bp)) netdev_warn(bp->dev, "TPA packet without valid hash\n"); } tpa_info->flags2 = le32_to_cpu(tpa_start1->rx_tpa_start_cmp_flags2); tpa_info->metadata = le32_to_cpu(tpa_start1->rx_tpa_start_cmp_metadata); tpa_info->hdr_info = le32_to_cpu(tpa_start1->rx_tpa_start_cmp_hdr_info); tpa_info->agg_count = 0; rxr->rx_prod = NEXT_RX(prod); cons = NEXT_RX(cons); rxr->rx_next_cons = NEXT_RX(cons); cons_rx_buf = &rxr->rx_buf_ring[cons]; bnxt_reuse_rx_data(rxr, cons, cons_rx_buf->data); rxr->rx_prod = NEXT_RX(rxr->rx_prod); cons_rx_buf->data = NULL; } static void bnxt_abort_tpa(struct bnxt_cp_ring_info *cpr, u16 idx, u32 agg_bufs) { if (agg_bufs) bnxt_reuse_rx_agg_bufs(cpr, idx, 0, agg_bufs, true); } #ifdef CONFIG_INET static void bnxt_gro_tunnel(struct sk_buff *skb, __be16 ip_proto) { struct udphdr *uh = NULL; if (ip_proto == htons(ETH_P_IP)) { struct iphdr *iph = (struct iphdr *)skb->data; if (iph->protocol == IPPROTO_UDP) uh = (struct udphdr *)(iph + 1); } else { struct ipv6hdr *iph = (struct ipv6hdr *)skb->data; if (iph->nexthdr == IPPROTO_UDP) uh = (struct udphdr *)(iph + 1); } if (uh) { if (uh->check) skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL_CSUM; else skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL; } } #endif static struct sk_buff *bnxt_gro_func_5731x(struct bnxt_tpa_info *tpa_info, int payload_off, int tcp_ts, struct sk_buff *skb) { #ifdef CONFIG_INET struct tcphdr *th; int len, nw_off; u16 outer_ip_off, inner_ip_off, inner_mac_off; u32 hdr_info = tpa_info->hdr_info; bool loopback = false; inner_ip_off = BNXT_TPA_INNER_L3_OFF(hdr_info); inner_mac_off = BNXT_TPA_INNER_L2_OFF(hdr_info); outer_ip_off = BNXT_TPA_OUTER_L3_OFF(hdr_info); /* If the packet is an internal loopback packet, the offsets will * have an extra 4 bytes. */ if (inner_mac_off == 4) { loopback = true; } else if (inner_mac_off > 4) { __be16 proto = *((__be16 *)(skb->data + inner_ip_off - ETH_HLEN - 2)); /* We only support inner iPv4/ipv6. If we don't see the * correct protocol ID, it must be a loopback packet where * the offsets are off by 4. */ if (proto != htons(ETH_P_IP) && proto != htons(ETH_P_IPV6)) loopback = true; } if (loopback) { /* internal loopback packet, subtract all offsets by 4 */ inner_ip_off -= 4; inner_mac_off -= 4; outer_ip_off -= 4; } nw_off = inner_ip_off - ETH_HLEN; skb_set_network_header(skb, nw_off); if (tpa_info->flags2 & RX_TPA_START_CMP_FLAGS2_IP_TYPE) { struct ipv6hdr *iph = ipv6_hdr(skb); skb_set_transport_header(skb, nw_off + sizeof(struct ipv6hdr)); len = skb->len - skb_transport_offset(skb); th = tcp_hdr(skb); th->check = ~tcp_v6_check(len, &iph->saddr, &iph->daddr, 0); } else { struct iphdr *iph = ip_hdr(skb); skb_set_transport_header(skb, nw_off + sizeof(struct iphdr)); len = skb->len - skb_transport_offset(skb); th = tcp_hdr(skb); th->check = ~tcp_v4_check(len, iph->saddr, iph->daddr, 0); } if (inner_mac_off) { /* tunnel */ __be16 proto = *((__be16 *)(skb->data + outer_ip_off - ETH_HLEN - 2)); bnxt_gro_tunnel(skb, proto); } #endif return skb; } static struct sk_buff *bnxt_gro_func_5750x(struct bnxt_tpa_info *tpa_info, int payload_off, int tcp_ts, struct sk_buff *skb) { #ifdef CONFIG_INET u16 outer_ip_off, inner_ip_off, inner_mac_off; u32 hdr_info = tpa_info->hdr_info; int iphdr_len, nw_off; inner_ip_off = BNXT_TPA_INNER_L3_OFF(hdr_info); inner_mac_off = BNXT_TPA_INNER_L2_OFF(hdr_info); outer_ip_off = BNXT_TPA_OUTER_L3_OFF(hdr_info); nw_off = inner_ip_off - ETH_HLEN; skb_set_network_header(skb, nw_off); iphdr_len = (tpa_info->flags2 & RX_TPA_START_CMP_FLAGS2_IP_TYPE) ? sizeof(struct ipv6hdr) : sizeof(struct iphdr); skb_set_transport_header(skb, nw_off + iphdr_len); if (inner_mac_off) { /* tunnel */ __be16 proto = *((__be16 *)(skb->data + outer_ip_off - ETH_HLEN - 2)); bnxt_gro_tunnel(skb, proto); } #endif return skb; } #define BNXT_IPV4_HDR_SIZE (sizeof(struct iphdr) + sizeof(struct tcphdr)) #define BNXT_IPV6_HDR_SIZE (sizeof(struct ipv6hdr) + sizeof(struct tcphdr)) static struct sk_buff *bnxt_gro_func_5730x(struct bnxt_tpa_info *tpa_info, int payload_off, int tcp_ts, struct sk_buff *skb) { #ifdef CONFIG_INET struct tcphdr *th; int len, nw_off, tcp_opt_len = 0; if (tcp_ts) tcp_opt_len = 12; if (tpa_info->gso_type == SKB_GSO_TCPV4) { struct iphdr *iph; nw_off = payload_off - BNXT_IPV4_HDR_SIZE - tcp_opt_len - ETH_HLEN; skb_set_network_header(skb, nw_off); iph = ip_hdr(skb); skb_set_transport_header(skb, nw_off + sizeof(struct iphdr)); len = skb->len - skb_transport_offset(skb); th = tcp_hdr(skb); th->check = ~tcp_v4_check(len, iph->saddr, iph->daddr, 0); } else if (tpa_info->gso_type == SKB_GSO_TCPV6) { struct ipv6hdr *iph; nw_off = payload_off - BNXT_IPV6_HDR_SIZE - tcp_opt_len - ETH_HLEN; skb_set_network_header(skb, nw_off); iph = ipv6_hdr(skb); skb_set_transport_header(skb, nw_off + sizeof(struct ipv6hdr)); len = skb->len - skb_transport_offset(skb); th = tcp_hdr(skb); th->check = ~tcp_v6_check(len, &iph->saddr, &iph->daddr, 0); } else { dev_kfree_skb_any(skb); return NULL; } if (nw_off) /* tunnel */ bnxt_gro_tunnel(skb, skb->protocol); #endif return skb; } static inline struct sk_buff *bnxt_gro_skb(struct bnxt *bp, struct bnxt_tpa_info *tpa_info, struct rx_tpa_end_cmp *tpa_end, struct rx_tpa_end_cmp_ext *tpa_end1, struct sk_buff *skb) { #ifdef CONFIG_INET int payload_off; u16 segs; segs = TPA_END_TPA_SEGS(tpa_end); if (segs == 1) return skb; NAPI_GRO_CB(skb)->count = segs; skb_shinfo(skb)->gso_size = le32_to_cpu(tpa_end1->rx_tpa_end_cmp_seg_len); skb_shinfo(skb)->gso_type = tpa_info->gso_type; if (bp->flags & BNXT_FLAG_CHIP_P5) payload_off = TPA_END_PAYLOAD_OFF_P5(tpa_end1); else payload_off = TPA_END_PAYLOAD_OFF(tpa_end); skb = bp->gro_func(tpa_info, payload_off, TPA_END_GRO_TS(tpa_end), skb); if (likely(skb)) tcp_gro_complete(skb); #endif return skb; } /* Given the cfa_code of a received packet determine which * netdev (vf-rep or PF) the packet is destined to. */ static struct net_device *bnxt_get_pkt_dev(struct bnxt *bp, u16 cfa_code) { struct net_device *dev = bnxt_get_vf_rep(bp, cfa_code); /* if vf-rep dev is NULL, the must belongs to the PF */ return dev ? dev : bp->dev; } static inline struct sk_buff *bnxt_tpa_end(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, u32 *raw_cons, struct rx_tpa_end_cmp *tpa_end, struct rx_tpa_end_cmp_ext *tpa_end1, u8 *event) { struct bnxt_napi *bnapi = cpr->bnapi; struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; u8 *data_ptr, agg_bufs; unsigned int len; struct bnxt_tpa_info *tpa_info; dma_addr_t mapping; struct sk_buff *skb; u16 idx = 0, agg_id; void *data; bool gro; if (unlikely(bnapi->in_reset)) { int rc = bnxt_discard_rx(bp, cpr, raw_cons, tpa_end); if (rc < 0) return ERR_PTR(-EBUSY); return NULL; } if (bp->flags & BNXT_FLAG_CHIP_P5) { agg_id = TPA_END_AGG_ID_P5(tpa_end); agg_id = bnxt_lookup_agg_idx(rxr, agg_id); agg_bufs = TPA_END_AGG_BUFS_P5(tpa_end1); tpa_info = &rxr->rx_tpa[agg_id]; if (unlikely(agg_bufs != tpa_info->agg_count)) { netdev_warn(bp->dev, "TPA end agg_buf %d != expected agg_bufs %d\n", agg_bufs, tpa_info->agg_count); agg_bufs = tpa_info->agg_count; } tpa_info->agg_count = 0; *event |= BNXT_AGG_EVENT; bnxt_free_agg_idx(rxr, agg_id); idx = agg_id; gro = !!(bp->flags & BNXT_FLAG_GRO); } else { agg_id = TPA_END_AGG_ID(tpa_end); agg_bufs = TPA_END_AGG_BUFS(tpa_end); tpa_info = &rxr->rx_tpa[agg_id]; idx = RING_CMP(*raw_cons); if (agg_bufs) { if (!bnxt_agg_bufs_valid(bp, cpr, agg_bufs, raw_cons)) return ERR_PTR(-EBUSY); *event |= BNXT_AGG_EVENT; idx = NEXT_CMP(idx); } gro = !!TPA_END_GRO(tpa_end); } data = tpa_info->data; data_ptr = tpa_info->data_ptr; prefetch(data_ptr); len = tpa_info->len; mapping = tpa_info->mapping; if (unlikely(agg_bufs > MAX_SKB_FRAGS || TPA_END_ERRORS(tpa_end1))) { bnxt_abort_tpa(cpr, idx, agg_bufs); if (agg_bufs > MAX_SKB_FRAGS) netdev_warn(bp->dev, "TPA frags %d exceeded MAX_SKB_FRAGS %d\n", agg_bufs, (int)MAX_SKB_FRAGS); return NULL; } if (len <= bp->rx_copy_thresh) { skb = bnxt_copy_skb(bnapi, data_ptr, len, mapping); if (!skb) { bnxt_abort_tpa(cpr, idx, agg_bufs); return NULL; } } else { u8 *new_data; dma_addr_t new_mapping; new_data = __bnxt_alloc_rx_data(bp, &new_mapping, GFP_ATOMIC); if (!new_data) { bnxt_abort_tpa(cpr, idx, agg_bufs); return NULL; } tpa_info->data = new_data; tpa_info->data_ptr = new_data + bp->rx_offset; tpa_info->mapping = new_mapping; skb = build_skb(data, 0); dma_unmap_single_attrs(&bp->pdev->dev, mapping, bp->rx_buf_use_size, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); if (!skb) { kfree(data); bnxt_abort_tpa(cpr, idx, agg_bufs); return NULL; } skb_reserve(skb, bp->rx_offset); skb_put(skb, len); } if (agg_bufs) { skb = bnxt_rx_pages(bp, cpr, skb, idx, agg_bufs, true); if (!skb) { /* Page reuse already handled by bnxt_rx_pages(). */ return NULL; } } skb->protocol = eth_type_trans(skb, bnxt_get_pkt_dev(bp, tpa_info->cfa_code)); if (tpa_info->hash_type != PKT_HASH_TYPE_NONE) skb_set_hash(skb, tpa_info->rss_hash, tpa_info->hash_type); if ((tpa_info->flags2 & RX_CMP_FLAGS2_META_FORMAT_VLAN) && (skb->dev->features & NETIF_F_HW_VLAN_CTAG_RX)) { u16 vlan_proto = tpa_info->metadata >> RX_CMP_FLAGS2_METADATA_TPID_SFT; u16 vtag = tpa_info->metadata & RX_CMP_FLAGS2_METADATA_TCI_MASK; __vlan_hwaccel_put_tag(skb, htons(vlan_proto), vtag); } skb_checksum_none_assert(skb); if (likely(tpa_info->flags2 & RX_TPA_START_CMP_FLAGS2_L4_CS_CALC)) { skb->ip_summed = CHECKSUM_UNNECESSARY; skb->csum_level = (tpa_info->flags2 & RX_CMP_FLAGS2_T_L4_CS_CALC) >> 3; } if (gro) skb = bnxt_gro_skb(bp, tpa_info, tpa_end, tpa_end1, skb); return skb; } static void bnxt_tpa_agg(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, struct rx_agg_cmp *rx_agg) { u16 agg_id = TPA_AGG_AGG_ID(rx_agg); struct bnxt_tpa_info *tpa_info; agg_id = bnxt_lookup_agg_idx(rxr, agg_id); tpa_info = &rxr->rx_tpa[agg_id]; BUG_ON(tpa_info->agg_count >= MAX_SKB_FRAGS); tpa_info->agg_arr[tpa_info->agg_count++] = *rx_agg; } static void bnxt_deliver_skb(struct bnxt *bp, struct bnxt_napi *bnapi, struct sk_buff *skb) { if (skb->dev != bp->dev) { /* this packet belongs to a vf-rep */ bnxt_vf_rep_rx(bp, skb); return; } skb_record_rx_queue(skb, bnapi->index); napi_gro_receive(&bnapi->napi, skb); } /* returns the following: * 1 - 1 packet successfully received * 0 - successful TPA_START, packet not completed yet * -EBUSY - completion ring does not have all the agg buffers yet * -ENOMEM - packet aborted due to out of memory * -EIO - packet aborted due to hw error indicated in BD */ static int bnxt_rx_pkt(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, u32 *raw_cons, u8 *event) { struct bnxt_napi *bnapi = cpr->bnapi; struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; struct net_device *dev = bp->dev; struct rx_cmp *rxcmp; struct rx_cmp_ext *rxcmp1; u32 tmp_raw_cons = *raw_cons; u16 cfa_code, cons, prod, cp_cons = RING_CMP(tmp_raw_cons); struct bnxt_sw_rx_bd *rx_buf; unsigned int len; u8 *data_ptr, agg_bufs, cmp_type; dma_addr_t dma_addr; struct sk_buff *skb; void *data; int rc = 0; u32 misc; rxcmp = (struct rx_cmp *) &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; cmp_type = RX_CMP_TYPE(rxcmp); if (cmp_type == CMP_TYPE_RX_TPA_AGG_CMP) { bnxt_tpa_agg(bp, rxr, (struct rx_agg_cmp *)rxcmp); goto next_rx_no_prod_no_len; } tmp_raw_cons = NEXT_RAW_CMP(tmp_raw_cons); cp_cons = RING_CMP(tmp_raw_cons); rxcmp1 = (struct rx_cmp_ext *) &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; if (!RX_CMP_VALID(rxcmp1, tmp_raw_cons)) return -EBUSY; prod = rxr->rx_prod; if (cmp_type == CMP_TYPE_RX_L2_TPA_START_CMP) { bnxt_tpa_start(bp, rxr, (struct rx_tpa_start_cmp *)rxcmp, (struct rx_tpa_start_cmp_ext *)rxcmp1); *event |= BNXT_RX_EVENT; goto next_rx_no_prod_no_len; } else if (cmp_type == CMP_TYPE_RX_L2_TPA_END_CMP) { skb = bnxt_tpa_end(bp, cpr, &tmp_raw_cons, (struct rx_tpa_end_cmp *)rxcmp, (struct rx_tpa_end_cmp_ext *)rxcmp1, event); if (IS_ERR(skb)) return -EBUSY; rc = -ENOMEM; if (likely(skb)) { bnxt_deliver_skb(bp, bnapi, skb); rc = 1; } *event |= BNXT_RX_EVENT; goto next_rx_no_prod_no_len; } cons = rxcmp->rx_cmp_opaque; if (unlikely(cons != rxr->rx_next_cons)) { int rc1 = bnxt_discard_rx(bp, cpr, raw_cons, rxcmp); netdev_warn(bp->dev, "RX cons %x != expected cons %x\n", cons, rxr->rx_next_cons); bnxt_sched_reset(bp, rxr); return rc1; } rx_buf = &rxr->rx_buf_ring[cons]; data = rx_buf->data; data_ptr = rx_buf->data_ptr; prefetch(data_ptr); misc = le32_to_cpu(rxcmp->rx_cmp_misc_v1); agg_bufs = (misc & RX_CMP_AGG_BUFS) >> RX_CMP_AGG_BUFS_SHIFT; if (agg_bufs) { if (!bnxt_agg_bufs_valid(bp, cpr, agg_bufs, &tmp_raw_cons)) return -EBUSY; cp_cons = NEXT_CMP(cp_cons); *event |= BNXT_AGG_EVENT; } *event |= BNXT_RX_EVENT; rx_buf->data = NULL; if (rxcmp1->rx_cmp_cfa_code_errors_v2 & RX_CMP_L2_ERRORS) { u32 rx_err = le32_to_cpu(rxcmp1->rx_cmp_cfa_code_errors_v2); bnxt_reuse_rx_data(rxr, cons, data); if (agg_bufs) bnxt_reuse_rx_agg_bufs(cpr, cp_cons, 0, agg_bufs, false); rc = -EIO; if (rx_err & RX_CMPL_ERRORS_BUFFER_ERROR_MASK) { bnapi->cp_ring.sw_stats.rx.rx_buf_errors++; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) { netdev_warn(bp->dev, "RX buffer error %x\n", rx_err); bnxt_sched_reset(bp, rxr); } } goto next_rx_no_len; } len = le32_to_cpu(rxcmp->rx_cmp_len_flags_type) >> RX_CMP_LEN_SHIFT; dma_addr = rx_buf->mapping; if (bnxt_rx_xdp(bp, rxr, cons, data, &data_ptr, &len, event)) { rc = 1; goto next_rx; } if (len <= bp->rx_copy_thresh) { skb = bnxt_copy_skb(bnapi, data_ptr, len, dma_addr); bnxt_reuse_rx_data(rxr, cons, data); if (!skb) { if (agg_bufs) bnxt_reuse_rx_agg_bufs(cpr, cp_cons, 0, agg_bufs, false); rc = -ENOMEM; goto next_rx; } } else { u32 payload; if (rx_buf->data_ptr == data_ptr) payload = misc & RX_CMP_PAYLOAD_OFFSET; else payload = 0; skb = bp->rx_skb_func(bp, rxr, cons, data, data_ptr, dma_addr, payload | len); if (!skb) { rc = -ENOMEM; goto next_rx; } } if (agg_bufs) { skb = bnxt_rx_pages(bp, cpr, skb, cp_cons, agg_bufs, false); if (!skb) { rc = -ENOMEM; goto next_rx; } } if (RX_CMP_HASH_VALID(rxcmp)) { u32 hash_type = RX_CMP_HASH_TYPE(rxcmp); enum pkt_hash_types type = PKT_HASH_TYPE_L4; /* RSS profiles 1 and 3 with extract code 0 for inner 4-tuple */ if (hash_type != 1 && hash_type != 3) type = PKT_HASH_TYPE_L3; skb_set_hash(skb, le32_to_cpu(rxcmp->rx_cmp_rss_hash), type); } cfa_code = RX_CMP_CFA_CODE(rxcmp1); skb->protocol = eth_type_trans(skb, bnxt_get_pkt_dev(bp, cfa_code)); if ((rxcmp1->rx_cmp_flags2 & cpu_to_le32(RX_CMP_FLAGS2_META_FORMAT_VLAN)) && (skb->dev->features & NETIF_F_HW_VLAN_CTAG_RX)) { u32 meta_data = le32_to_cpu(rxcmp1->rx_cmp_meta_data); u16 vtag = meta_data & RX_CMP_FLAGS2_METADATA_TCI_MASK; u16 vlan_proto = meta_data >> RX_CMP_FLAGS2_METADATA_TPID_SFT; __vlan_hwaccel_put_tag(skb, htons(vlan_proto), vtag); } skb_checksum_none_assert(skb); if (RX_CMP_L4_CS_OK(rxcmp1)) { if (dev->features & NETIF_F_RXCSUM) { skb->ip_summed = CHECKSUM_UNNECESSARY; skb->csum_level = RX_CMP_ENCAP(rxcmp1); } } else { if (rxcmp1->rx_cmp_cfa_code_errors_v2 & RX_CMP_L4_CS_ERR_BITS) { if (dev->features & NETIF_F_RXCSUM) bnapi->cp_ring.sw_stats.rx.rx_l4_csum_errors++; } } bnxt_deliver_skb(bp, bnapi, skb); rc = 1; next_rx: cpr->rx_packets += 1; cpr->rx_bytes += len; next_rx_no_len: rxr->rx_prod = NEXT_RX(prod); rxr->rx_next_cons = NEXT_RX(cons); next_rx_no_prod_no_len: *raw_cons = tmp_raw_cons; return rc; } /* In netpoll mode, if we are using a combined completion ring, we need to * discard the rx packets and recycle the buffers. */ static int bnxt_force_rx_discard(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, u32 *raw_cons, u8 *event) { u32 tmp_raw_cons = *raw_cons; struct rx_cmp_ext *rxcmp1; struct rx_cmp *rxcmp; u16 cp_cons; u8 cmp_type; cp_cons = RING_CMP(tmp_raw_cons); rxcmp = (struct rx_cmp *) &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; tmp_raw_cons = NEXT_RAW_CMP(tmp_raw_cons); cp_cons = RING_CMP(tmp_raw_cons); rxcmp1 = (struct rx_cmp_ext *) &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; if (!RX_CMP_VALID(rxcmp1, tmp_raw_cons)) return -EBUSY; cmp_type = RX_CMP_TYPE(rxcmp); if (cmp_type == CMP_TYPE_RX_L2_CMP) { rxcmp1->rx_cmp_cfa_code_errors_v2 |= cpu_to_le32(RX_CMPL_ERRORS_CRC_ERROR); } else if (cmp_type == CMP_TYPE_RX_L2_TPA_END_CMP) { struct rx_tpa_end_cmp_ext *tpa_end1; tpa_end1 = (struct rx_tpa_end_cmp_ext *)rxcmp1; tpa_end1->rx_tpa_end_cmp_errors_v2 |= cpu_to_le32(RX_TPA_END_CMP_ERRORS); } return bnxt_rx_pkt(bp, cpr, raw_cons, event); } u32 bnxt_fw_health_readl(struct bnxt *bp, int reg_idx) { struct bnxt_fw_health *fw_health = bp->fw_health; u32 reg = fw_health->regs[reg_idx]; u32 reg_type, reg_off, val = 0; reg_type = BNXT_FW_HEALTH_REG_TYPE(reg); reg_off = BNXT_FW_HEALTH_REG_OFF(reg); switch (reg_type) { case BNXT_FW_HEALTH_REG_TYPE_CFG: pci_read_config_dword(bp->pdev, reg_off, &val); break; case BNXT_FW_HEALTH_REG_TYPE_GRC: reg_off = fw_health->mapped_regs[reg_idx]; /* fall through */ case BNXT_FW_HEALTH_REG_TYPE_BAR0: val = readl(bp->bar0 + reg_off); break; case BNXT_FW_HEALTH_REG_TYPE_BAR1: val = readl(bp->bar1 + reg_off); break; } if (reg_idx == BNXT_FW_RESET_INPROG_REG) val &= fw_health->fw_reset_inprog_reg_mask; return val; } #define BNXT_GET_EVENT_PORT(data) \ ((data) & \ ASYNC_EVENT_CMPL_PORT_CONN_NOT_ALLOWED_EVENT_DATA1_PORT_ID_MASK) static int bnxt_async_event_process(struct bnxt *bp, struct hwrm_async_event_cmpl *cmpl) { u16 event_id = le16_to_cpu(cmpl->event_id); /* TODO CHIMP_FW: Define event id's for link change, error etc */ switch (event_id) { case ASYNC_EVENT_CMPL_EVENT_ID_LINK_SPEED_CFG_CHANGE: { u32 data1 = le32_to_cpu(cmpl->event_data1); struct bnxt_link_info *link_info = &bp->link_info; if (BNXT_VF(bp)) goto async_event_process_exit; /* print unsupported speed warning in forced speed mode only */ if (!(link_info->autoneg & BNXT_AUTONEG_SPEED) && (data1 & 0x20000)) { u16 fw_speed = link_info->force_link_speed; u32 speed = bnxt_fw_to_ethtool_speed(fw_speed); if (speed != SPEED_UNKNOWN) netdev_warn(bp->dev, "Link speed %d no longer supported\n", speed); } set_bit(BNXT_LINK_SPEED_CHNG_SP_EVENT, &bp->sp_event); } /* fall through */ case ASYNC_EVENT_CMPL_EVENT_ID_LINK_SPEED_CHANGE: case ASYNC_EVENT_CMPL_EVENT_ID_PORT_PHY_CFG_CHANGE: set_bit(BNXT_LINK_CFG_CHANGE_SP_EVENT, &bp->sp_event); /* fall through */ case ASYNC_EVENT_CMPL_EVENT_ID_LINK_STATUS_CHANGE: set_bit(BNXT_LINK_CHNG_SP_EVENT, &bp->sp_event); break; case ASYNC_EVENT_CMPL_EVENT_ID_PF_DRVR_UNLOAD: set_bit(BNXT_HWRM_PF_UNLOAD_SP_EVENT, &bp->sp_event); break; case ASYNC_EVENT_CMPL_EVENT_ID_PORT_CONN_NOT_ALLOWED: { u32 data1 = le32_to_cpu(cmpl->event_data1); u16 port_id = BNXT_GET_EVENT_PORT(data1); if (BNXT_VF(bp)) break; if (bp->pf.port_id != port_id) break; set_bit(BNXT_HWRM_PORT_MODULE_SP_EVENT, &bp->sp_event); break; } case ASYNC_EVENT_CMPL_EVENT_ID_VF_CFG_CHANGE: if (BNXT_PF(bp)) goto async_event_process_exit; set_bit(BNXT_RESET_TASK_SILENT_SP_EVENT, &bp->sp_event); break; case ASYNC_EVENT_CMPL_EVENT_ID_RESET_NOTIFY: { u32 data1 = le32_to_cpu(cmpl->event_data1); if (!bp->fw_health) goto async_event_process_exit; bp->fw_reset_timestamp = jiffies; bp->fw_reset_min_dsecs = cmpl->timestamp_lo; if (!bp->fw_reset_min_dsecs) bp->fw_reset_min_dsecs = BNXT_DFLT_FW_RST_MIN_DSECS; bp->fw_reset_max_dsecs = le16_to_cpu(cmpl->timestamp_hi); if (!bp->fw_reset_max_dsecs) bp->fw_reset_max_dsecs = BNXT_DFLT_FW_RST_MAX_DSECS; if (EVENT_DATA1_RESET_NOTIFY_FATAL(data1)) { netdev_warn(bp->dev, "Firmware fatal reset event received\n"); set_bit(BNXT_STATE_FW_FATAL_COND, &bp->state); } else { netdev_warn(bp->dev, "Firmware non-fatal reset event received, max wait time %d msec\n", bp->fw_reset_max_dsecs * 100); } set_bit(BNXT_FW_RESET_NOTIFY_SP_EVENT, &bp->sp_event); break; } case ASYNC_EVENT_CMPL_EVENT_ID_ERROR_RECOVERY: { struct bnxt_fw_health *fw_health = bp->fw_health; u32 data1 = le32_to_cpu(cmpl->event_data1); if (!fw_health) goto async_event_process_exit; fw_health->enabled = EVENT_DATA1_RECOVERY_ENABLED(data1); fw_health->master = EVENT_DATA1_RECOVERY_MASTER_FUNC(data1); if (!fw_health->enabled) break; if (netif_msg_drv(bp)) netdev_info(bp->dev, "Error recovery info: error recovery[%d], master[%d], reset count[0x%x], health status: 0x%x\n", fw_health->enabled, fw_health->master, bnxt_fw_health_readl(bp, BNXT_FW_RESET_CNT_REG), bnxt_fw_health_readl(bp, BNXT_FW_HEALTH_REG)); fw_health->tmr_multiplier = DIV_ROUND_UP(fw_health->polling_dsecs * HZ, bp->current_interval * 10); fw_health->tmr_counter = fw_health->tmr_multiplier; fw_health->last_fw_heartbeat = bnxt_fw_health_readl(bp, BNXT_FW_HEARTBEAT_REG); fw_health->last_fw_reset_cnt = bnxt_fw_health_readl(bp, BNXT_FW_RESET_CNT_REG); goto async_event_process_exit; } default: goto async_event_process_exit; } bnxt_queue_sp_work(bp); async_event_process_exit: bnxt_ulp_async_events(bp, cmpl); return 0; } static int bnxt_hwrm_handler(struct bnxt *bp, struct tx_cmp *txcmp) { u16 cmpl_type = TX_CMP_TYPE(txcmp), vf_id, seq_id; struct hwrm_cmpl *h_cmpl = (struct hwrm_cmpl *)txcmp; struct hwrm_fwd_req_cmpl *fwd_req_cmpl = (struct hwrm_fwd_req_cmpl *)txcmp; switch (cmpl_type) { case CMPL_BASE_TYPE_HWRM_DONE: seq_id = le16_to_cpu(h_cmpl->sequence_id); if (seq_id == bp->hwrm_intr_seq_id) bp->hwrm_intr_seq_id = (u16)~bp->hwrm_intr_seq_id; else netdev_err(bp->dev, "Invalid hwrm seq id %d\n", seq_id); break; case CMPL_BASE_TYPE_HWRM_FWD_REQ: vf_id = le16_to_cpu(fwd_req_cmpl->source_id); if ((vf_id < bp->pf.first_vf_id) || (vf_id >= bp->pf.first_vf_id + bp->pf.active_vfs)) { netdev_err(bp->dev, "Msg contains invalid VF id %x\n", vf_id); return -EINVAL; } set_bit(vf_id - bp->pf.first_vf_id, bp->pf.vf_event_bmap); set_bit(BNXT_HWRM_EXEC_FWD_REQ_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); break; case CMPL_BASE_TYPE_HWRM_ASYNC_EVENT: bnxt_async_event_process(bp, (struct hwrm_async_event_cmpl *)txcmp); default: break; } return 0; } static irqreturn_t bnxt_msix(int irq, void *dev_instance) { struct bnxt_napi *bnapi = dev_instance; struct bnxt *bp = bnapi->bp; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; u32 cons = RING_CMP(cpr->cp_raw_cons); cpr->event_ctr++; prefetch(&cpr->cp_desc_ring[CP_RING(cons)][CP_IDX(cons)]); napi_schedule(&bnapi->napi); return IRQ_HANDLED; } static inline int bnxt_has_work(struct bnxt *bp, struct bnxt_cp_ring_info *cpr) { u32 raw_cons = cpr->cp_raw_cons; u16 cons = RING_CMP(raw_cons); struct tx_cmp *txcmp; txcmp = &cpr->cp_desc_ring[CP_RING(cons)][CP_IDX(cons)]; return TX_CMP_VALID(txcmp, raw_cons); } static irqreturn_t bnxt_inta(int irq, void *dev_instance) { struct bnxt_napi *bnapi = dev_instance; struct bnxt *bp = bnapi->bp; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; u32 cons = RING_CMP(cpr->cp_raw_cons); u32 int_status; prefetch(&cpr->cp_desc_ring[CP_RING(cons)][CP_IDX(cons)]); if (!bnxt_has_work(bp, cpr)) { int_status = readl(bp->bar0 + BNXT_CAG_REG_LEGACY_INT_STATUS); /* return if erroneous interrupt */ if (!(int_status & (0x10000 << cpr->cp_ring_struct.fw_ring_id))) return IRQ_NONE; } /* disable ring IRQ */ BNXT_CP_DB_IRQ_DIS(cpr->cp_db.doorbell); /* Return here if interrupt is shared and is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; napi_schedule(&bnapi->napi); return IRQ_HANDLED; } static int __bnxt_poll_work(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, int budget) { struct bnxt_napi *bnapi = cpr->bnapi; u32 raw_cons = cpr->cp_raw_cons; u32 cons; int tx_pkts = 0; int rx_pkts = 0; u8 event = 0; struct tx_cmp *txcmp; cpr->has_more_work = 0; cpr->had_work_done = 1; while (1) { int rc; cons = RING_CMP(raw_cons); txcmp = &cpr->cp_desc_ring[CP_RING(cons)][CP_IDX(cons)]; if (!TX_CMP_VALID(txcmp, raw_cons)) break; /* The valid test of the entry must be done first before * reading any further. */ dma_rmb(); if (TX_CMP_TYPE(txcmp) == CMP_TYPE_TX_L2_CMP) { tx_pkts++; /* return full budget so NAPI will complete. */ if (unlikely(tx_pkts > bp->tx_wake_thresh)) { rx_pkts = budget; raw_cons = NEXT_RAW_CMP(raw_cons); if (budget) cpr->has_more_work = 1; break; } } else if ((TX_CMP_TYPE(txcmp) & 0x30) == 0x10) { if (likely(budget)) rc = bnxt_rx_pkt(bp, cpr, &raw_cons, &event); else rc = bnxt_force_rx_discard(bp, cpr, &raw_cons, &event); if (likely(rc >= 0)) rx_pkts += rc; /* Increment rx_pkts when rc is -ENOMEM to count towards * the NAPI budget. Otherwise, we may potentially loop * here forever if we consistently cannot allocate * buffers. */ else if (rc == -ENOMEM && budget) rx_pkts++; else if (rc == -EBUSY) /* partial completion */ break; } else if (unlikely((TX_CMP_TYPE(txcmp) == CMPL_BASE_TYPE_HWRM_DONE) || (TX_CMP_TYPE(txcmp) == CMPL_BASE_TYPE_HWRM_FWD_REQ) || (TX_CMP_TYPE(txcmp) == CMPL_BASE_TYPE_HWRM_ASYNC_EVENT))) { bnxt_hwrm_handler(bp, txcmp); } raw_cons = NEXT_RAW_CMP(raw_cons); if (rx_pkts && rx_pkts == budget) { cpr->has_more_work = 1; break; } } if (event & BNXT_REDIRECT_EVENT) xdp_do_flush_map(); if (event & BNXT_TX_EVENT) { struct bnxt_tx_ring_info *txr = bnapi->tx_ring; u16 prod = txr->tx_prod; /* Sync BD data before updating doorbell */ wmb(); bnxt_db_write_relaxed(bp, &txr->tx_db, prod); } cpr->cp_raw_cons = raw_cons; bnapi->tx_pkts += tx_pkts; bnapi->events |= event; return rx_pkts; } static void __bnxt_poll_work_done(struct bnxt *bp, struct bnxt_napi *bnapi) { if (bnapi->tx_pkts) { bnapi->tx_int(bp, bnapi, bnapi->tx_pkts); bnapi->tx_pkts = 0; } if (bnapi->events & BNXT_RX_EVENT) { struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; if (bnapi->events & BNXT_AGG_EVENT) bnxt_db_write(bp, &rxr->rx_agg_db, rxr->rx_agg_prod); bnxt_db_write(bp, &rxr->rx_db, rxr->rx_prod); } bnapi->events = 0; } static int bnxt_poll_work(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, int budget) { struct bnxt_napi *bnapi = cpr->bnapi; int rx_pkts; rx_pkts = __bnxt_poll_work(bp, cpr, budget); /* ACK completion ring before freeing tx ring and producing new * buffers in rx/agg rings to prevent overflowing the completion * ring. */ bnxt_db_cq(bp, &cpr->cp_db, cpr->cp_raw_cons); __bnxt_poll_work_done(bp, bnapi); return rx_pkts; } static int bnxt_poll_nitroa0(struct napi_struct *napi, int budget) { struct bnxt_napi *bnapi = container_of(napi, struct bnxt_napi, napi); struct bnxt *bp = bnapi->bp; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; struct tx_cmp *txcmp; struct rx_cmp_ext *rxcmp1; u32 cp_cons, tmp_raw_cons; u32 raw_cons = cpr->cp_raw_cons; u32 rx_pkts = 0; u8 event = 0; while (1) { int rc; cp_cons = RING_CMP(raw_cons); txcmp = &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; if (!TX_CMP_VALID(txcmp, raw_cons)) break; if ((TX_CMP_TYPE(txcmp) & 0x30) == 0x10) { tmp_raw_cons = NEXT_RAW_CMP(raw_cons); cp_cons = RING_CMP(tmp_raw_cons); rxcmp1 = (struct rx_cmp_ext *) &cpr->cp_desc_ring[CP_RING(cp_cons)][CP_IDX(cp_cons)]; if (!RX_CMP_VALID(rxcmp1, tmp_raw_cons)) break; /* force an error to recycle the buffer */ rxcmp1->rx_cmp_cfa_code_errors_v2 |= cpu_to_le32(RX_CMPL_ERRORS_CRC_ERROR); rc = bnxt_rx_pkt(bp, cpr, &raw_cons, &event); if (likely(rc == -EIO) && budget) rx_pkts++; else if (rc == -EBUSY) /* partial completion */ break; } else if (unlikely(TX_CMP_TYPE(txcmp) == CMPL_BASE_TYPE_HWRM_DONE)) { bnxt_hwrm_handler(bp, txcmp); } else { netdev_err(bp->dev, "Invalid completion received on special ring\n"); } raw_cons = NEXT_RAW_CMP(raw_cons); if (rx_pkts == budget) break; } cpr->cp_raw_cons = raw_cons; BNXT_DB_CQ(&cpr->cp_db, cpr->cp_raw_cons); bnxt_db_write(bp, &rxr->rx_db, rxr->rx_prod); if (event & BNXT_AGG_EVENT) bnxt_db_write(bp, &rxr->rx_agg_db, rxr->rx_agg_prod); if (!bnxt_has_work(bp, cpr) && rx_pkts < budget) { napi_complete_done(napi, rx_pkts); BNXT_DB_CQ_ARM(&cpr->cp_db, cpr->cp_raw_cons); } return rx_pkts; } static int bnxt_poll(struct napi_struct *napi, int budget) { struct bnxt_napi *bnapi = container_of(napi, struct bnxt_napi, napi); struct bnxt *bp = bnapi->bp; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; int work_done = 0; while (1) { work_done += bnxt_poll_work(bp, cpr, budget - work_done); if (work_done >= budget) { if (!budget) BNXT_DB_CQ_ARM(&cpr->cp_db, cpr->cp_raw_cons); break; } if (!bnxt_has_work(bp, cpr)) { if (napi_complete_done(napi, work_done)) BNXT_DB_CQ_ARM(&cpr->cp_db, cpr->cp_raw_cons); break; } } if (bp->flags & BNXT_FLAG_DIM) { struct dim_sample dim_sample = {}; dim_update_sample(cpr->event_ctr, cpr->rx_packets, cpr->rx_bytes, &dim_sample); net_dim(&cpr->dim, dim_sample); } return work_done; } static int __bnxt_poll_cqs(struct bnxt *bp, struct bnxt_napi *bnapi, int budget) { struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; int i, work_done = 0; for (i = 0; i < 2; i++) { struct bnxt_cp_ring_info *cpr2 = cpr->cp_ring_arr[i]; if (cpr2) { work_done += __bnxt_poll_work(bp, cpr2, budget - work_done); cpr->has_more_work |= cpr2->has_more_work; } } return work_done; } static void __bnxt_poll_cqs_done(struct bnxt *bp, struct bnxt_napi *bnapi, u64 dbr_type) { struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; int i; for (i = 0; i < 2; i++) { struct bnxt_cp_ring_info *cpr2 = cpr->cp_ring_arr[i]; struct bnxt_db_info *db; if (cpr2 && cpr2->had_work_done) { db = &cpr2->cp_db; writeq(db->db_key64 | dbr_type | RING_CMP(cpr2->cp_raw_cons), db->doorbell); cpr2->had_work_done = 0; } } __bnxt_poll_work_done(bp, bnapi); } static int bnxt_poll_p5(struct napi_struct *napi, int budget) { struct bnxt_napi *bnapi = container_of(napi, struct bnxt_napi, napi); struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; u32 raw_cons = cpr->cp_raw_cons; struct bnxt *bp = bnapi->bp; struct nqe_cn *nqcmp; int work_done = 0; u32 cons; if (cpr->has_more_work) { cpr->has_more_work = 0; work_done = __bnxt_poll_cqs(bp, bnapi, budget); } while (1) { cons = RING_CMP(raw_cons); nqcmp = &cpr->nq_desc_ring[CP_RING(cons)][CP_IDX(cons)]; if (!NQ_CMP_VALID(nqcmp, raw_cons)) { if (cpr->has_more_work) break; __bnxt_poll_cqs_done(bp, bnapi, DBR_TYPE_CQ_ARMALL); cpr->cp_raw_cons = raw_cons; if (napi_complete_done(napi, work_done)) BNXT_DB_NQ_ARM_P5(&cpr->cp_db, cpr->cp_raw_cons); return work_done; } /* The valid test of the entry must be done first before * reading any further. */ dma_rmb(); if (nqcmp->type == cpu_to_le16(NQ_CN_TYPE_CQ_NOTIFICATION)) { u32 idx = le32_to_cpu(nqcmp->cq_handle_low); struct bnxt_cp_ring_info *cpr2; cpr2 = cpr->cp_ring_arr[idx]; work_done += __bnxt_poll_work(bp, cpr2, budget - work_done); cpr->has_more_work |= cpr2->has_more_work; } else { bnxt_hwrm_handler(bp, (struct tx_cmp *)nqcmp); } raw_cons = NEXT_RAW_CMP(raw_cons); } __bnxt_poll_cqs_done(bp, bnapi, DBR_TYPE_CQ); if (raw_cons != cpr->cp_raw_cons) { cpr->cp_raw_cons = raw_cons; BNXT_DB_NQ_P5(&cpr->cp_db, raw_cons); } return work_done; } static void bnxt_free_tx_skbs(struct bnxt *bp) { int i, max_idx; struct pci_dev *pdev = bp->pdev; if (!bp->tx_ring) return; max_idx = bp->tx_nr_pages * TX_DESC_CNT; for (i = 0; i < bp->tx_nr_rings; i++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; int j; for (j = 0; j < max_idx;) { struct bnxt_sw_tx_bd *tx_buf = &txr->tx_buf_ring[j]; struct sk_buff *skb; int k, last; if (i < bp->tx_nr_rings_xdp && tx_buf->action == XDP_REDIRECT) { dma_unmap_single(&pdev->dev, dma_unmap_addr(tx_buf, mapping), dma_unmap_len(tx_buf, len), PCI_DMA_TODEVICE); xdp_return_frame(tx_buf->xdpf); tx_buf->action = 0; tx_buf->xdpf = NULL; j++; continue; } skb = tx_buf->skb; if (!skb) { j++; continue; } tx_buf->skb = NULL; if (tx_buf->is_push) { dev_kfree_skb(skb); j += 2; continue; } dma_unmap_single(&pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); last = tx_buf->nr_frags; j += 2; for (k = 0; k < last; k++, j++) { int ring_idx = j & bp->tx_ring_mask; skb_frag_t *frag = &skb_shinfo(skb)->frags[k]; tx_buf = &txr->tx_buf_ring[ring_idx]; dma_unmap_page( &pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_frag_size(frag), PCI_DMA_TODEVICE); } dev_kfree_skb(skb); } netdev_tx_reset_queue(netdev_get_tx_queue(bp->dev, i)); } } static void bnxt_free_rx_skbs(struct bnxt *bp) { int i, max_idx, max_agg_idx; struct pci_dev *pdev = bp->pdev; if (!bp->rx_ring) return; max_idx = bp->rx_nr_pages * RX_DESC_CNT; max_agg_idx = bp->rx_agg_nr_pages * RX_DESC_CNT; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_tpa_idx_map *map; int j; if (rxr->rx_tpa) { for (j = 0; j < bp->max_tpa; j++) { struct bnxt_tpa_info *tpa_info = &rxr->rx_tpa[j]; u8 *data = tpa_info->data; if (!data) continue; dma_unmap_single_attrs(&pdev->dev, tpa_info->mapping, bp->rx_buf_use_size, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); tpa_info->data = NULL; kfree(data); } } for (j = 0; j < max_idx; j++) { struct bnxt_sw_rx_bd *rx_buf = &rxr->rx_buf_ring[j]; dma_addr_t mapping = rx_buf->mapping; void *data = rx_buf->data; if (!data) continue; rx_buf->data = NULL; if (BNXT_RX_PAGE_MODE(bp)) { mapping -= bp->rx_dma_offset; dma_unmap_page_attrs(&pdev->dev, mapping, PAGE_SIZE, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); page_pool_recycle_direct(rxr->page_pool, data); } else { dma_unmap_single_attrs(&pdev->dev, mapping, bp->rx_buf_use_size, bp->rx_dir, DMA_ATTR_WEAK_ORDERING); kfree(data); } } for (j = 0; j < max_agg_idx; j++) { struct bnxt_sw_rx_agg_bd *rx_agg_buf = &rxr->rx_agg_ring[j]; struct page *page = rx_agg_buf->page; if (!page) continue; dma_unmap_page_attrs(&pdev->dev, rx_agg_buf->mapping, BNXT_RX_PAGE_SIZE, PCI_DMA_FROMDEVICE, DMA_ATTR_WEAK_ORDERING); rx_agg_buf->page = NULL; __clear_bit(j, rxr->rx_agg_bmap); __free_page(page); } if (rxr->rx_page) { __free_page(rxr->rx_page); rxr->rx_page = NULL; } map = rxr->rx_tpa_idx_map; if (map) memset(map->agg_idx_bmap, 0, sizeof(map->agg_idx_bmap)); } } static void bnxt_free_skbs(struct bnxt *bp) { bnxt_free_tx_skbs(bp); bnxt_free_rx_skbs(bp); } static void bnxt_free_ring(struct bnxt *bp, struct bnxt_ring_mem_info *rmem) { struct pci_dev *pdev = bp->pdev; int i; for (i = 0; i < rmem->nr_pages; i++) { if (!rmem->pg_arr[i]) continue; dma_free_coherent(&pdev->dev, rmem->page_size, rmem->pg_arr[i], rmem->dma_arr[i]); rmem->pg_arr[i] = NULL; } if (rmem->pg_tbl) { size_t pg_tbl_size = rmem->nr_pages * 8; if (rmem->flags & BNXT_RMEM_USE_FULL_PAGE_FLAG) pg_tbl_size = rmem->page_size; dma_free_coherent(&pdev->dev, pg_tbl_size, rmem->pg_tbl, rmem->pg_tbl_map); rmem->pg_tbl = NULL; } if (rmem->vmem_size && *rmem->vmem) { vfree(*rmem->vmem); *rmem->vmem = NULL; } } static int bnxt_alloc_ring(struct bnxt *bp, struct bnxt_ring_mem_info *rmem) { struct pci_dev *pdev = bp->pdev; u64 valid_bit = 0; int i; if (rmem->flags & (BNXT_RMEM_VALID_PTE_FLAG | BNXT_RMEM_RING_PTE_FLAG)) valid_bit = PTU_PTE_VALID; if ((rmem->nr_pages > 1 || rmem->depth > 0) && !rmem->pg_tbl) { size_t pg_tbl_size = rmem->nr_pages * 8; if (rmem->flags & BNXT_RMEM_USE_FULL_PAGE_FLAG) pg_tbl_size = rmem->page_size; rmem->pg_tbl = dma_alloc_coherent(&pdev->dev, pg_tbl_size, &rmem->pg_tbl_map, GFP_KERNEL); if (!rmem->pg_tbl) return -ENOMEM; } for (i = 0; i < rmem->nr_pages; i++) { u64 extra_bits = valid_bit; rmem->pg_arr[i] = dma_alloc_coherent(&pdev->dev, rmem->page_size, &rmem->dma_arr[i], GFP_KERNEL); if (!rmem->pg_arr[i]) return -ENOMEM; if (rmem->init_val) memset(rmem->pg_arr[i], rmem->init_val, rmem->page_size); if (rmem->nr_pages > 1 || rmem->depth > 0) { if (i == rmem->nr_pages - 2 && (rmem->flags & BNXT_RMEM_RING_PTE_FLAG)) extra_bits |= PTU_PTE_NEXT_TO_LAST; else if (i == rmem->nr_pages - 1 && (rmem->flags & BNXT_RMEM_RING_PTE_FLAG)) extra_bits |= PTU_PTE_LAST; rmem->pg_tbl[i] = cpu_to_le64(rmem->dma_arr[i] | extra_bits); } } if (rmem->vmem_size) { *rmem->vmem = vzalloc(rmem->vmem_size); if (!(*rmem->vmem)) return -ENOMEM; } return 0; } static void bnxt_free_tpa_info(struct bnxt *bp) { int i; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; kfree(rxr->rx_tpa_idx_map); rxr->rx_tpa_idx_map = NULL; if (rxr->rx_tpa) { kfree(rxr->rx_tpa[0].agg_arr); rxr->rx_tpa[0].agg_arr = NULL; } kfree(rxr->rx_tpa); rxr->rx_tpa = NULL; } } static int bnxt_alloc_tpa_info(struct bnxt *bp) { int i, j, total_aggs = 0; bp->max_tpa = MAX_TPA; if (bp->flags & BNXT_FLAG_CHIP_P5) { if (!bp->max_tpa_v2) return 0; bp->max_tpa = max_t(u16, bp->max_tpa_v2, MAX_TPA_P5); total_aggs = bp->max_tpa * MAX_SKB_FRAGS; } for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct rx_agg_cmp *agg; rxr->rx_tpa = kcalloc(bp->max_tpa, sizeof(struct bnxt_tpa_info), GFP_KERNEL); if (!rxr->rx_tpa) return -ENOMEM; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) continue; agg = kcalloc(total_aggs, sizeof(*agg), GFP_KERNEL); rxr->rx_tpa[0].agg_arr = agg; if (!agg) return -ENOMEM; for (j = 1; j < bp->max_tpa; j++) rxr->rx_tpa[j].agg_arr = agg + j * MAX_SKB_FRAGS; rxr->rx_tpa_idx_map = kzalloc(sizeof(*rxr->rx_tpa_idx_map), GFP_KERNEL); if (!rxr->rx_tpa_idx_map) return -ENOMEM; } return 0; } static void bnxt_free_rx_rings(struct bnxt *bp) { int i; if (!bp->rx_ring) return; bnxt_free_tpa_info(bp); for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_ring_struct *ring; if (rxr->xdp_prog) bpf_prog_put(rxr->xdp_prog); if (xdp_rxq_info_is_reg(&rxr->xdp_rxq)) xdp_rxq_info_unreg(&rxr->xdp_rxq); page_pool_destroy(rxr->page_pool); rxr->page_pool = NULL; kfree(rxr->rx_agg_bmap); rxr->rx_agg_bmap = NULL; ring = &rxr->rx_ring_struct; bnxt_free_ring(bp, &ring->ring_mem); ring = &rxr->rx_agg_ring_struct; bnxt_free_ring(bp, &ring->ring_mem); } } static int bnxt_alloc_rx_page_pool(struct bnxt *bp, struct bnxt_rx_ring_info *rxr) { struct page_pool_params pp = { 0 }; pp.pool_size = bp->rx_ring_size; pp.nid = dev_to_node(&bp->pdev->dev); pp.dev = &bp->pdev->dev; pp.dma_dir = DMA_BIDIRECTIONAL; rxr->page_pool = page_pool_create(&pp); if (IS_ERR(rxr->page_pool)) { int err = PTR_ERR(rxr->page_pool); rxr->page_pool = NULL; return err; } return 0; } static int bnxt_alloc_rx_rings(struct bnxt *bp) { int i, rc = 0, agg_rings = 0; if (!bp->rx_ring) return -ENOMEM; if (bp->flags & BNXT_FLAG_AGG_RINGS) agg_rings = 1; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_ring_struct *ring; ring = &rxr->rx_ring_struct; rc = bnxt_alloc_rx_page_pool(bp, rxr); if (rc) return rc; rc = xdp_rxq_info_reg(&rxr->xdp_rxq, bp->dev, i); if (rc < 0) return rc; rc = xdp_rxq_info_reg_mem_model(&rxr->xdp_rxq, MEM_TYPE_PAGE_POOL, rxr->page_pool); if (rc) { xdp_rxq_info_unreg(&rxr->xdp_rxq); return rc; } rc = bnxt_alloc_ring(bp, &ring->ring_mem); if (rc) return rc; ring->grp_idx = i; if (agg_rings) { u16 mem_size; ring = &rxr->rx_agg_ring_struct; rc = bnxt_alloc_ring(bp, &ring->ring_mem); if (rc) return rc; ring->grp_idx = i; rxr->rx_agg_bmap_size = bp->rx_agg_ring_mask + 1; mem_size = rxr->rx_agg_bmap_size / 8; rxr->rx_agg_bmap = kzalloc(mem_size, GFP_KERNEL); if (!rxr->rx_agg_bmap) return -ENOMEM; } } if (bp->flags & BNXT_FLAG_TPA) rc = bnxt_alloc_tpa_info(bp); return rc; } static void bnxt_free_tx_rings(struct bnxt *bp) { int i; struct pci_dev *pdev = bp->pdev; if (!bp->tx_ring) return; for (i = 0; i < bp->tx_nr_rings; i++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; struct bnxt_ring_struct *ring; if (txr->tx_push) { dma_free_coherent(&pdev->dev, bp->tx_push_size, txr->tx_push, txr->tx_push_mapping); txr->tx_push = NULL; } ring = &txr->tx_ring_struct; bnxt_free_ring(bp, &ring->ring_mem); } } static int bnxt_alloc_tx_rings(struct bnxt *bp) { int i, j, rc; struct pci_dev *pdev = bp->pdev; bp->tx_push_size = 0; if (bp->tx_push_thresh) { int push_size; push_size = L1_CACHE_ALIGN(sizeof(struct tx_push_bd) + bp->tx_push_thresh); if (push_size > 256) { push_size = 0; bp->tx_push_thresh = 0; } bp->tx_push_size = push_size; } for (i = 0, j = 0; i < bp->tx_nr_rings; i++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; struct bnxt_ring_struct *ring; u8 qidx; ring = &txr->tx_ring_struct; rc = bnxt_alloc_ring(bp, &ring->ring_mem); if (rc) return rc; ring->grp_idx = txr->bnapi->index; if (bp->tx_push_size) { dma_addr_t mapping; /* One pre-allocated DMA buffer to backup * TX push operation */ txr->tx_push = dma_alloc_coherent(&pdev->dev, bp->tx_push_size, &txr->tx_push_mapping, GFP_KERNEL); if (!txr->tx_push) return -ENOMEM; mapping = txr->tx_push_mapping + sizeof(struct tx_push_bd); txr->data_mapping = cpu_to_le64(mapping); } qidx = bp->tc_to_qidx[j]; ring->queue_id = bp->q_info[qidx].queue_id; if (i < bp->tx_nr_rings_xdp) continue; if (i % bp->tx_nr_rings_per_tc == (bp->tx_nr_rings_per_tc - 1)) j++; } return 0; } static void bnxt_free_cp_rings(struct bnxt *bp) { int i; if (!bp->bnapi) return; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr; struct bnxt_ring_struct *ring; int j; if (!bnapi) continue; cpr = &bnapi->cp_ring; ring = &cpr->cp_ring_struct; bnxt_free_ring(bp, &ring->ring_mem); for (j = 0; j < 2; j++) { struct bnxt_cp_ring_info *cpr2 = cpr->cp_ring_arr[j]; if (cpr2) { ring = &cpr2->cp_ring_struct; bnxt_free_ring(bp, &ring->ring_mem); kfree(cpr2); cpr->cp_ring_arr[j] = NULL; } } } } static struct bnxt_cp_ring_info *bnxt_alloc_cp_sub_ring(struct bnxt *bp) { struct bnxt_ring_mem_info *rmem; struct bnxt_ring_struct *ring; struct bnxt_cp_ring_info *cpr; int rc; cpr = kzalloc(sizeof(*cpr), GFP_KERNEL); if (!cpr) return NULL; ring = &cpr->cp_ring_struct; rmem = &ring->ring_mem; rmem->nr_pages = bp->cp_nr_pages; rmem->page_size = HW_CMPD_RING_SIZE; rmem->pg_arr = (void **)cpr->cp_desc_ring; rmem->dma_arr = cpr->cp_desc_mapping; rmem->flags = BNXT_RMEM_RING_PTE_FLAG; rc = bnxt_alloc_ring(bp, rmem); if (rc) { bnxt_free_ring(bp, rmem); kfree(cpr); cpr = NULL; } return cpr; } static int bnxt_alloc_cp_rings(struct bnxt *bp) { bool sh = !!(bp->flags & BNXT_FLAG_SHARED_RINGS); int i, rc, ulp_base_vec, ulp_msix; ulp_msix = bnxt_get_ulp_msix_num(bp); ulp_base_vec = bnxt_get_ulp_msix_base(bp); for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr; struct bnxt_ring_struct *ring; if (!bnapi) continue; cpr = &bnapi->cp_ring; cpr->bnapi = bnapi; ring = &cpr->cp_ring_struct; rc = bnxt_alloc_ring(bp, &ring->ring_mem); if (rc) return rc; if (ulp_msix && i >= ulp_base_vec) ring->map_idx = i + ulp_msix; else ring->map_idx = i; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) continue; if (i < bp->rx_nr_rings) { struct bnxt_cp_ring_info *cpr2 = bnxt_alloc_cp_sub_ring(bp); cpr->cp_ring_arr[BNXT_RX_HDL] = cpr2; if (!cpr2) return -ENOMEM; cpr2->bnapi = bnapi; } if ((sh && i < bp->tx_nr_rings) || (!sh && i >= bp->rx_nr_rings)) { struct bnxt_cp_ring_info *cpr2 = bnxt_alloc_cp_sub_ring(bp); cpr->cp_ring_arr[BNXT_TX_HDL] = cpr2; if (!cpr2) return -ENOMEM; cpr2->bnapi = bnapi; } } return 0; } static void bnxt_init_ring_struct(struct bnxt *bp) { int i; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_ring_mem_info *rmem; struct bnxt_cp_ring_info *cpr; struct bnxt_rx_ring_info *rxr; struct bnxt_tx_ring_info *txr; struct bnxt_ring_struct *ring; if (!bnapi) continue; cpr = &bnapi->cp_ring; ring = &cpr->cp_ring_struct; rmem = &ring->ring_mem; rmem->nr_pages = bp->cp_nr_pages; rmem->page_size = HW_CMPD_RING_SIZE; rmem->pg_arr = (void **)cpr->cp_desc_ring; rmem->dma_arr = cpr->cp_desc_mapping; rmem->vmem_size = 0; rxr = bnapi->rx_ring; if (!rxr) goto skip_rx; ring = &rxr->rx_ring_struct; rmem = &ring->ring_mem; rmem->nr_pages = bp->rx_nr_pages; rmem->page_size = HW_RXBD_RING_SIZE; rmem->pg_arr = (void **)rxr->rx_desc_ring; rmem->dma_arr = rxr->rx_desc_mapping; rmem->vmem_size = SW_RXBD_RING_SIZE * bp->rx_nr_pages; rmem->vmem = (void **)&rxr->rx_buf_ring; ring = &rxr->rx_agg_ring_struct; rmem = &ring->ring_mem; rmem->nr_pages = bp->rx_agg_nr_pages; rmem->page_size = HW_RXBD_RING_SIZE; rmem->pg_arr = (void **)rxr->rx_agg_desc_ring; rmem->dma_arr = rxr->rx_agg_desc_mapping; rmem->vmem_size = SW_RXBD_AGG_RING_SIZE * bp->rx_agg_nr_pages; rmem->vmem = (void **)&rxr->rx_agg_ring; skip_rx: txr = bnapi->tx_ring; if (!txr) continue; ring = &txr->tx_ring_struct; rmem = &ring->ring_mem; rmem->nr_pages = bp->tx_nr_pages; rmem->page_size = HW_RXBD_RING_SIZE; rmem->pg_arr = (void **)txr->tx_desc_ring; rmem->dma_arr = txr->tx_desc_mapping; rmem->vmem_size = SW_TXBD_RING_SIZE * bp->tx_nr_pages; rmem->vmem = (void **)&txr->tx_buf_ring; } } static void bnxt_init_rxbd_pages(struct bnxt_ring_struct *ring, u32 type) { int i; u32 prod; struct rx_bd **rx_buf_ring; rx_buf_ring = (struct rx_bd **)ring->ring_mem.pg_arr; for (i = 0, prod = 0; i < ring->ring_mem.nr_pages; i++) { int j; struct rx_bd *rxbd; rxbd = rx_buf_ring[i]; if (!rxbd) continue; for (j = 0; j < RX_DESC_CNT; j++, rxbd++, prod++) { rxbd->rx_bd_len_flags_type = cpu_to_le32(type); rxbd->rx_bd_opaque = prod; } } } static int bnxt_init_one_rx_ring(struct bnxt *bp, int ring_nr) { struct net_device *dev = bp->dev; struct bnxt_rx_ring_info *rxr; struct bnxt_ring_struct *ring; u32 prod, type; int i; type = (bp->rx_buf_use_size << RX_BD_LEN_SHIFT) | RX_BD_TYPE_RX_PACKET_BD | RX_BD_FLAGS_EOP; if (NET_IP_ALIGN == 2) type |= RX_BD_FLAGS_SOP; rxr = &bp->rx_ring[ring_nr]; ring = &rxr->rx_ring_struct; bnxt_init_rxbd_pages(ring, type); if (BNXT_RX_PAGE_MODE(bp) && bp->xdp_prog) { bpf_prog_add(bp->xdp_prog, 1); rxr->xdp_prog = bp->xdp_prog; } prod = rxr->rx_prod; for (i = 0; i < bp->rx_ring_size; i++) { if (bnxt_alloc_rx_data(bp, rxr, prod, GFP_KERNEL) != 0) { netdev_warn(dev, "init'ed rx ring %d with %d/%d skbs only\n", ring_nr, i, bp->rx_ring_size); break; } prod = NEXT_RX(prod); } rxr->rx_prod = prod; ring->fw_ring_id = INVALID_HW_RING_ID; ring = &rxr->rx_agg_ring_struct; ring->fw_ring_id = INVALID_HW_RING_ID; if (!(bp->flags & BNXT_FLAG_AGG_RINGS)) return 0; type = ((u32)BNXT_RX_PAGE_SIZE << RX_BD_LEN_SHIFT) | RX_BD_TYPE_RX_AGG_BD | RX_BD_FLAGS_SOP; bnxt_init_rxbd_pages(ring, type); prod = rxr->rx_agg_prod; for (i = 0; i < bp->rx_agg_ring_size; i++) { if (bnxt_alloc_rx_page(bp, rxr, prod, GFP_KERNEL) != 0) { netdev_warn(dev, "init'ed rx ring %d with %d/%d pages only\n", ring_nr, i, bp->rx_ring_size); break; } prod = NEXT_RX_AGG(prod); } rxr->rx_agg_prod = prod; if (bp->flags & BNXT_FLAG_TPA) { if (rxr->rx_tpa) { u8 *data; dma_addr_t mapping; for (i = 0; i < bp->max_tpa; i++) { data = __bnxt_alloc_rx_data(bp, &mapping, GFP_KERNEL); if (!data) return -ENOMEM; rxr->rx_tpa[i].data = data; rxr->rx_tpa[i].data_ptr = data + bp->rx_offset; rxr->rx_tpa[i].mapping = mapping; } } else { netdev_err(bp->dev, "No resource allocated for LRO/GRO\n"); return -ENOMEM; } } return 0; } static void bnxt_init_cp_rings(struct bnxt *bp) { int i, j; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_cp_ring_info *cpr = &bp->bnapi[i]->cp_ring; struct bnxt_ring_struct *ring = &cpr->cp_ring_struct; ring->fw_ring_id = INVALID_HW_RING_ID; cpr->rx_ring_coal.coal_ticks = bp->rx_coal.coal_ticks; cpr->rx_ring_coal.coal_bufs = bp->rx_coal.coal_bufs; for (j = 0; j < 2; j++) { struct bnxt_cp_ring_info *cpr2 = cpr->cp_ring_arr[j]; if (!cpr2) continue; ring = &cpr2->cp_ring_struct; ring->fw_ring_id = INVALID_HW_RING_ID; cpr2->rx_ring_coal.coal_ticks = bp->rx_coal.coal_ticks; cpr2->rx_ring_coal.coal_bufs = bp->rx_coal.coal_bufs; } } } static int bnxt_init_rx_rings(struct bnxt *bp) { int i, rc = 0; if (BNXT_RX_PAGE_MODE(bp)) { bp->rx_offset = NET_IP_ALIGN + XDP_PACKET_HEADROOM; bp->rx_dma_offset = XDP_PACKET_HEADROOM; } else { bp->rx_offset = BNXT_RX_OFFSET; bp->rx_dma_offset = BNXT_RX_DMA_OFFSET; } for (i = 0; i < bp->rx_nr_rings; i++) { rc = bnxt_init_one_rx_ring(bp, i); if (rc) break; } return rc; } static int bnxt_init_tx_rings(struct bnxt *bp) { u16 i; bp->tx_wake_thresh = max_t(int, bp->tx_ring_size / 2, MAX_SKB_FRAGS + 1); for (i = 0; i < bp->tx_nr_rings; i++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; struct bnxt_ring_struct *ring = &txr->tx_ring_struct; ring->fw_ring_id = INVALID_HW_RING_ID; } return 0; } static void bnxt_free_ring_grps(struct bnxt *bp) { kfree(bp->grp_info); bp->grp_info = NULL; } static int bnxt_init_ring_grps(struct bnxt *bp, bool irq_re_init) { int i; if (irq_re_init) { bp->grp_info = kcalloc(bp->cp_nr_rings, sizeof(struct bnxt_ring_grp_info), GFP_KERNEL); if (!bp->grp_info) return -ENOMEM; } for (i = 0; i < bp->cp_nr_rings; i++) { if (irq_re_init) bp->grp_info[i].fw_stats_ctx = INVALID_HW_RING_ID; bp->grp_info[i].fw_grp_id = INVALID_HW_RING_ID; bp->grp_info[i].rx_fw_ring_id = INVALID_HW_RING_ID; bp->grp_info[i].agg_fw_ring_id = INVALID_HW_RING_ID; bp->grp_info[i].cp_fw_ring_id = INVALID_HW_RING_ID; } return 0; } static void bnxt_free_vnics(struct bnxt *bp) { kfree(bp->vnic_info); bp->vnic_info = NULL; bp->nr_vnics = 0; } static int bnxt_alloc_vnics(struct bnxt *bp) { int num_vnics = 1; #ifdef CONFIG_RFS_ACCEL if ((bp->flags & (BNXT_FLAG_RFS | BNXT_FLAG_CHIP_P5)) == BNXT_FLAG_RFS) num_vnics += bp->rx_nr_rings; #endif if (BNXT_CHIP_TYPE_NITRO_A0(bp)) num_vnics++; bp->vnic_info = kcalloc(num_vnics, sizeof(struct bnxt_vnic_info), GFP_KERNEL); if (!bp->vnic_info) return -ENOMEM; bp->nr_vnics = num_vnics; return 0; } static void bnxt_init_vnics(struct bnxt *bp) { int i; for (i = 0; i < bp->nr_vnics; i++) { struct bnxt_vnic_info *vnic = &bp->vnic_info[i]; int j; vnic->fw_vnic_id = INVALID_HW_RING_ID; for (j = 0; j < BNXT_MAX_CTX_PER_VNIC; j++) vnic->fw_rss_cos_lb_ctx[j] = INVALID_HW_RING_ID; vnic->fw_l2_ctx_id = INVALID_HW_RING_ID; if (bp->vnic_info[i].rss_hash_key) { if (i == 0) prandom_bytes(vnic->rss_hash_key, HW_HASH_KEY_SIZE); else memcpy(vnic->rss_hash_key, bp->vnic_info[0].rss_hash_key, HW_HASH_KEY_SIZE); } } } static int bnxt_calc_nr_ring_pages(u32 ring_size, int desc_per_pg) { int pages; pages = ring_size / desc_per_pg; if (!pages) return 1; pages++; while (pages & (pages - 1)) pages++; return pages; } void bnxt_set_tpa_flags(struct bnxt *bp) { bp->flags &= ~BNXT_FLAG_TPA; if (bp->flags & BNXT_FLAG_NO_AGG_RINGS) return; if (bp->dev->features & NETIF_F_LRO) bp->flags |= BNXT_FLAG_LRO; else if (bp->dev->features & NETIF_F_GRO_HW) bp->flags |= BNXT_FLAG_GRO; } /* bp->rx_ring_size, bp->tx_ring_size, dev->mtu, BNXT_FLAG_{G|L}RO flags must * be set on entry. */ void bnxt_set_ring_params(struct bnxt *bp) { u32 ring_size, rx_size, rx_space; u32 agg_factor = 0, agg_ring_size = 0; /* 8 for CRC and VLAN */ rx_size = SKB_DATA_ALIGN(bp->dev->mtu + ETH_HLEN + NET_IP_ALIGN + 8); rx_space = rx_size + NET_SKB_PAD + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); bp->rx_copy_thresh = BNXT_RX_COPY_THRESH; ring_size = bp->rx_ring_size; bp->rx_agg_ring_size = 0; bp->rx_agg_nr_pages = 0; if (bp->flags & BNXT_FLAG_TPA) agg_factor = min_t(u32, 4, 65536 / BNXT_RX_PAGE_SIZE); bp->flags &= ~BNXT_FLAG_JUMBO; if (rx_space > PAGE_SIZE && !(bp->flags & BNXT_FLAG_NO_AGG_RINGS)) { u32 jumbo_factor; bp->flags |= BNXT_FLAG_JUMBO; jumbo_factor = PAGE_ALIGN(bp->dev->mtu - 40) >> PAGE_SHIFT; if (jumbo_factor > agg_factor) agg_factor = jumbo_factor; } agg_ring_size = ring_size * agg_factor; if (agg_ring_size) { bp->rx_agg_nr_pages = bnxt_calc_nr_ring_pages(agg_ring_size, RX_DESC_CNT); if (bp->rx_agg_nr_pages > MAX_RX_AGG_PAGES) { u32 tmp = agg_ring_size; bp->rx_agg_nr_pages = MAX_RX_AGG_PAGES; agg_ring_size = MAX_RX_AGG_PAGES * RX_DESC_CNT - 1; netdev_warn(bp->dev, "rx agg ring size %d reduced to %d.\n", tmp, agg_ring_size); } bp->rx_agg_ring_size = agg_ring_size; bp->rx_agg_ring_mask = (bp->rx_agg_nr_pages * RX_DESC_CNT) - 1; rx_size = SKB_DATA_ALIGN(BNXT_RX_COPY_THRESH + NET_IP_ALIGN); rx_space = rx_size + NET_SKB_PAD + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); } bp->rx_buf_use_size = rx_size; bp->rx_buf_size = rx_space; bp->rx_nr_pages = bnxt_calc_nr_ring_pages(ring_size, RX_DESC_CNT); bp->rx_ring_mask = (bp->rx_nr_pages * RX_DESC_CNT) - 1; ring_size = bp->tx_ring_size; bp->tx_nr_pages = bnxt_calc_nr_ring_pages(ring_size, TX_DESC_CNT); bp->tx_ring_mask = (bp->tx_nr_pages * TX_DESC_CNT) - 1; ring_size = bp->rx_ring_size * (2 + agg_factor) + bp->tx_ring_size; bp->cp_ring_size = ring_size; bp->cp_nr_pages = bnxt_calc_nr_ring_pages(ring_size, CP_DESC_CNT); if (bp->cp_nr_pages > MAX_CP_PAGES) { bp->cp_nr_pages = MAX_CP_PAGES; bp->cp_ring_size = MAX_CP_PAGES * CP_DESC_CNT - 1; netdev_warn(bp->dev, "completion ring size %d reduced to %d.\n", ring_size, bp->cp_ring_size); } bp->cp_bit = bp->cp_nr_pages * CP_DESC_CNT; bp->cp_ring_mask = bp->cp_bit - 1; } /* Changing allocation mode of RX rings. * TODO: Update when extending xdp_rxq_info to support allocation modes. */ int bnxt_set_rx_skb_mode(struct bnxt *bp, bool page_mode) { if (page_mode) { if (bp->dev->mtu > BNXT_MAX_PAGE_MODE_MTU) return -EOPNOTSUPP; bp->dev->max_mtu = min_t(u16, bp->max_mtu, BNXT_MAX_PAGE_MODE_MTU); bp->flags &= ~BNXT_FLAG_AGG_RINGS; bp->flags |= BNXT_FLAG_NO_AGG_RINGS | BNXT_FLAG_RX_PAGE_MODE; bp->rx_dir = DMA_BIDIRECTIONAL; bp->rx_skb_func = bnxt_rx_page_skb; /* Disable LRO or GRO_HW */ netdev_update_features(bp->dev); } else { bp->dev->max_mtu = bp->max_mtu; bp->flags &= ~BNXT_FLAG_RX_PAGE_MODE; bp->rx_dir = DMA_FROM_DEVICE; bp->rx_skb_func = bnxt_rx_skb; } return 0; } static void bnxt_free_vnic_attributes(struct bnxt *bp) { int i; struct bnxt_vnic_info *vnic; struct pci_dev *pdev = bp->pdev; if (!bp->vnic_info) return; for (i = 0; i < bp->nr_vnics; i++) { vnic = &bp->vnic_info[i]; kfree(vnic->fw_grp_ids); vnic->fw_grp_ids = NULL; kfree(vnic->uc_list); vnic->uc_list = NULL; if (vnic->mc_list) { dma_free_coherent(&pdev->dev, vnic->mc_list_size, vnic->mc_list, vnic->mc_list_mapping); vnic->mc_list = NULL; } if (vnic->rss_table) { dma_free_coherent(&pdev->dev, PAGE_SIZE, vnic->rss_table, vnic->rss_table_dma_addr); vnic->rss_table = NULL; } vnic->rss_hash_key = NULL; vnic->flags = 0; } } static int bnxt_alloc_vnic_attributes(struct bnxt *bp) { int i, rc = 0, size; struct bnxt_vnic_info *vnic; struct pci_dev *pdev = bp->pdev; int max_rings; for (i = 0; i < bp->nr_vnics; i++) { vnic = &bp->vnic_info[i]; if (vnic->flags & BNXT_VNIC_UCAST_FLAG) { int mem_size = (BNXT_MAX_UC_ADDRS - 1) * ETH_ALEN; if (mem_size > 0) { vnic->uc_list = kmalloc(mem_size, GFP_KERNEL); if (!vnic->uc_list) { rc = -ENOMEM; goto out; } } } if (vnic->flags & BNXT_VNIC_MCAST_FLAG) { vnic->mc_list_size = BNXT_MAX_MC_ADDRS * ETH_ALEN; vnic->mc_list = dma_alloc_coherent(&pdev->dev, vnic->mc_list_size, &vnic->mc_list_mapping, GFP_KERNEL); if (!vnic->mc_list) { rc = -ENOMEM; goto out; } } if (bp->flags & BNXT_FLAG_CHIP_P5) goto vnic_skip_grps; if (vnic->flags & BNXT_VNIC_RSS_FLAG) max_rings = bp->rx_nr_rings; else max_rings = 1; vnic->fw_grp_ids = kcalloc(max_rings, sizeof(u16), GFP_KERNEL); if (!vnic->fw_grp_ids) { rc = -ENOMEM; goto out; } vnic_skip_grps: if ((bp->flags & BNXT_FLAG_NEW_RSS_CAP) && !(vnic->flags & BNXT_VNIC_RSS_FLAG)) continue; /* Allocate rss table and hash key */ vnic->rss_table = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &vnic->rss_table_dma_addr, GFP_KERNEL); if (!vnic->rss_table) { rc = -ENOMEM; goto out; } size = L1_CACHE_ALIGN(HW_HASH_INDEX_SIZE * sizeof(u16)); vnic->rss_hash_key = ((void *)vnic->rss_table) + size; vnic->rss_hash_key_dma_addr = vnic->rss_table_dma_addr + size; } return 0; out: return rc; } static void bnxt_free_hwrm_resources(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; if (bp->hwrm_cmd_resp_addr) { dma_free_coherent(&pdev->dev, PAGE_SIZE, bp->hwrm_cmd_resp_addr, bp->hwrm_cmd_resp_dma_addr); bp->hwrm_cmd_resp_addr = NULL; } if (bp->hwrm_cmd_kong_resp_addr) { dma_free_coherent(&pdev->dev, PAGE_SIZE, bp->hwrm_cmd_kong_resp_addr, bp->hwrm_cmd_kong_resp_dma_addr); bp->hwrm_cmd_kong_resp_addr = NULL; } } static int bnxt_alloc_kong_hwrm_resources(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; if (bp->hwrm_cmd_kong_resp_addr) return 0; bp->hwrm_cmd_kong_resp_addr = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &bp->hwrm_cmd_kong_resp_dma_addr, GFP_KERNEL); if (!bp->hwrm_cmd_kong_resp_addr) return -ENOMEM; return 0; } static int bnxt_alloc_hwrm_resources(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; bp->hwrm_cmd_resp_addr = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &bp->hwrm_cmd_resp_dma_addr, GFP_KERNEL); if (!bp->hwrm_cmd_resp_addr) return -ENOMEM; return 0; } static void bnxt_free_hwrm_short_cmd_req(struct bnxt *bp) { if (bp->hwrm_short_cmd_req_addr) { struct pci_dev *pdev = bp->pdev; dma_free_coherent(&pdev->dev, bp->hwrm_max_ext_req_len, bp->hwrm_short_cmd_req_addr, bp->hwrm_short_cmd_req_dma_addr); bp->hwrm_short_cmd_req_addr = NULL; } } static int bnxt_alloc_hwrm_short_cmd_req(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; if (bp->hwrm_short_cmd_req_addr) return 0; bp->hwrm_short_cmd_req_addr = dma_alloc_coherent(&pdev->dev, bp->hwrm_max_ext_req_len, &bp->hwrm_short_cmd_req_dma_addr, GFP_KERNEL); if (!bp->hwrm_short_cmd_req_addr) return -ENOMEM; return 0; } static void bnxt_free_port_stats(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; bp->flags &= ~BNXT_FLAG_PORT_STATS; bp->flags &= ~BNXT_FLAG_PORT_STATS_EXT; if (bp->hw_rx_port_stats) { dma_free_coherent(&pdev->dev, bp->hw_port_stats_size, bp->hw_rx_port_stats, bp->hw_rx_port_stats_map); bp->hw_rx_port_stats = NULL; } if (bp->hw_tx_port_stats_ext) { dma_free_coherent(&pdev->dev, sizeof(struct tx_port_stats_ext), bp->hw_tx_port_stats_ext, bp->hw_tx_port_stats_ext_map); bp->hw_tx_port_stats_ext = NULL; } if (bp->hw_rx_port_stats_ext) { dma_free_coherent(&pdev->dev, sizeof(struct rx_port_stats_ext), bp->hw_rx_port_stats_ext, bp->hw_rx_port_stats_ext_map); bp->hw_rx_port_stats_ext = NULL; } if (bp->hw_pcie_stats) { dma_free_coherent(&pdev->dev, sizeof(struct pcie_ctx_hw_stats), bp->hw_pcie_stats, bp->hw_pcie_stats_map); bp->hw_pcie_stats = NULL; } } static void bnxt_free_ring_stats(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; int size, i; if (!bp->bnapi) return; size = bp->hw_ring_stats_size; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; if (cpr->hw_stats) { dma_free_coherent(&pdev->dev, size, cpr->hw_stats, cpr->hw_stats_map); cpr->hw_stats = NULL; } } } static int bnxt_alloc_stats(struct bnxt *bp) { u32 size, i; struct pci_dev *pdev = bp->pdev; size = bp->hw_ring_stats_size; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; cpr->hw_stats = dma_alloc_coherent(&pdev->dev, size, &cpr->hw_stats_map, GFP_KERNEL); if (!cpr->hw_stats) return -ENOMEM; cpr->hw_stats_ctx_id = INVALID_STATS_CTX_ID; } if (BNXT_VF(bp) || bp->chip_num == CHIP_NUM_58700) return 0; if (bp->hw_rx_port_stats) goto alloc_ext_stats; bp->hw_port_stats_size = sizeof(struct rx_port_stats) + sizeof(struct tx_port_stats) + 1024; bp->hw_rx_port_stats = dma_alloc_coherent(&pdev->dev, bp->hw_port_stats_size, &bp->hw_rx_port_stats_map, GFP_KERNEL); if (!bp->hw_rx_port_stats) return -ENOMEM; bp->hw_tx_port_stats = (void *)(bp->hw_rx_port_stats + 1) + 512; bp->hw_tx_port_stats_map = bp->hw_rx_port_stats_map + sizeof(struct rx_port_stats) + 512; bp->flags |= BNXT_FLAG_PORT_STATS; alloc_ext_stats: /* Display extended statistics only if FW supports it */ if (bp->hwrm_spec_code < 0x10804 || bp->hwrm_spec_code == 0x10900) if (!(bp->fw_cap & BNXT_FW_CAP_EXT_STATS_SUPPORTED)) return 0; if (bp->hw_rx_port_stats_ext) goto alloc_tx_ext_stats; bp->hw_rx_port_stats_ext = dma_alloc_coherent(&pdev->dev, sizeof(struct rx_port_stats_ext), &bp->hw_rx_port_stats_ext_map, GFP_KERNEL); if (!bp->hw_rx_port_stats_ext) return 0; alloc_tx_ext_stats: if (bp->hw_tx_port_stats_ext) goto alloc_pcie_stats; if (bp->hwrm_spec_code >= 0x10902 || (bp->fw_cap & BNXT_FW_CAP_EXT_STATS_SUPPORTED)) { bp->hw_tx_port_stats_ext = dma_alloc_coherent(&pdev->dev, sizeof(struct tx_port_stats_ext), &bp->hw_tx_port_stats_ext_map, GFP_KERNEL); } bp->flags |= BNXT_FLAG_PORT_STATS_EXT; alloc_pcie_stats: if (bp->hw_pcie_stats || !(bp->fw_cap & BNXT_FW_CAP_PCIE_STATS_SUPPORTED)) return 0; bp->hw_pcie_stats = dma_alloc_coherent(&pdev->dev, sizeof(struct pcie_ctx_hw_stats), &bp->hw_pcie_stats_map, GFP_KERNEL); if (!bp->hw_pcie_stats) return 0; bp->flags |= BNXT_FLAG_PCIE_STATS; return 0; } static void bnxt_clear_ring_indices(struct bnxt *bp) { int i; if (!bp->bnapi) return; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr; struct bnxt_rx_ring_info *rxr; struct bnxt_tx_ring_info *txr; if (!bnapi) continue; cpr = &bnapi->cp_ring; cpr->cp_raw_cons = 0; txr = bnapi->tx_ring; if (txr) { txr->tx_prod = 0; txr->tx_cons = 0; } rxr = bnapi->rx_ring; if (rxr) { rxr->rx_prod = 0; rxr->rx_agg_prod = 0; rxr->rx_sw_agg_prod = 0; rxr->rx_next_cons = 0; } } } static void bnxt_free_ntp_fltrs(struct bnxt *bp, bool irq_reinit) { #ifdef CONFIG_RFS_ACCEL int i; /* Under rtnl_lock and all our NAPIs have been disabled. It's * safe to delete the hash table. */ for (i = 0; i < BNXT_NTP_FLTR_HASH_SIZE; i++) { struct hlist_head *head; struct hlist_node *tmp; struct bnxt_ntuple_filter *fltr; head = &bp->ntp_fltr_hash_tbl[i]; hlist_for_each_entry_safe(fltr, tmp, head, hash) { hlist_del(&fltr->hash); kfree(fltr); } } if (irq_reinit) { kfree(bp->ntp_fltr_bmap); bp->ntp_fltr_bmap = NULL; } bp->ntp_fltr_count = 0; #endif } static int bnxt_alloc_ntp_fltrs(struct bnxt *bp) { #ifdef CONFIG_RFS_ACCEL int i, rc = 0; if (!(bp->flags & BNXT_FLAG_RFS)) return 0; for (i = 0; i < BNXT_NTP_FLTR_HASH_SIZE; i++) INIT_HLIST_HEAD(&bp->ntp_fltr_hash_tbl[i]); bp->ntp_fltr_count = 0; bp->ntp_fltr_bmap = kcalloc(BITS_TO_LONGS(BNXT_NTP_FLTR_MAX_FLTR), sizeof(long), GFP_KERNEL); if (!bp->ntp_fltr_bmap) rc = -ENOMEM; return rc; #else return 0; #endif } static void bnxt_free_mem(struct bnxt *bp, bool irq_re_init) { bnxt_free_vnic_attributes(bp); bnxt_free_tx_rings(bp); bnxt_free_rx_rings(bp); bnxt_free_cp_rings(bp); bnxt_free_ntp_fltrs(bp, irq_re_init); if (irq_re_init) { bnxt_free_ring_stats(bp); bnxt_free_ring_grps(bp); bnxt_free_vnics(bp); kfree(bp->tx_ring_map); bp->tx_ring_map = NULL; kfree(bp->tx_ring); bp->tx_ring = NULL; kfree(bp->rx_ring); bp->rx_ring = NULL; kfree(bp->bnapi); bp->bnapi = NULL; } else { bnxt_clear_ring_indices(bp); } } static int bnxt_alloc_mem(struct bnxt *bp, bool irq_re_init) { int i, j, rc, size, arr_size; void *bnapi; if (irq_re_init) { /* Allocate bnapi mem pointer array and mem block for * all queues */ arr_size = L1_CACHE_ALIGN(sizeof(struct bnxt_napi *) * bp->cp_nr_rings); size = L1_CACHE_ALIGN(sizeof(struct bnxt_napi)); bnapi = kzalloc(arr_size + size * bp->cp_nr_rings, GFP_KERNEL); if (!bnapi) return -ENOMEM; bp->bnapi = bnapi; bnapi += arr_size; for (i = 0; i < bp->cp_nr_rings; i++, bnapi += size) { bp->bnapi[i] = bnapi; bp->bnapi[i]->index = i; bp->bnapi[i]->bp = bp; if (bp->flags & BNXT_FLAG_CHIP_P5) { struct bnxt_cp_ring_info *cpr = &bp->bnapi[i]->cp_ring; cpr->cp_ring_struct.ring_mem.flags = BNXT_RMEM_RING_PTE_FLAG; } } bp->rx_ring = kcalloc(bp->rx_nr_rings, sizeof(struct bnxt_rx_ring_info), GFP_KERNEL); if (!bp->rx_ring) return -ENOMEM; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; if (bp->flags & BNXT_FLAG_CHIP_P5) { rxr->rx_ring_struct.ring_mem.flags = BNXT_RMEM_RING_PTE_FLAG; rxr->rx_agg_ring_struct.ring_mem.flags = BNXT_RMEM_RING_PTE_FLAG; } rxr->bnapi = bp->bnapi[i]; bp->bnapi[i]->rx_ring = &bp->rx_ring[i]; } bp->tx_ring = kcalloc(bp->tx_nr_rings, sizeof(struct bnxt_tx_ring_info), GFP_KERNEL); if (!bp->tx_ring) return -ENOMEM; bp->tx_ring_map = kcalloc(bp->tx_nr_rings, sizeof(u16), GFP_KERNEL); if (!bp->tx_ring_map) return -ENOMEM; if (bp->flags & BNXT_FLAG_SHARED_RINGS) j = 0; else j = bp->rx_nr_rings; for (i = 0; i < bp->tx_nr_rings; i++, j++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; if (bp->flags & BNXT_FLAG_CHIP_P5) txr->tx_ring_struct.ring_mem.flags = BNXT_RMEM_RING_PTE_FLAG; txr->bnapi = bp->bnapi[j]; bp->bnapi[j]->tx_ring = txr; bp->tx_ring_map[i] = bp->tx_nr_rings_xdp + i; if (i >= bp->tx_nr_rings_xdp) { txr->txq_index = i - bp->tx_nr_rings_xdp; bp->bnapi[j]->tx_int = bnxt_tx_int; } else { bp->bnapi[j]->flags |= BNXT_NAPI_FLAG_XDP; bp->bnapi[j]->tx_int = bnxt_tx_int_xdp; } } rc = bnxt_alloc_stats(bp); if (rc) goto alloc_mem_err; rc = bnxt_alloc_ntp_fltrs(bp); if (rc) goto alloc_mem_err; rc = bnxt_alloc_vnics(bp); if (rc) goto alloc_mem_err; } bnxt_init_ring_struct(bp); rc = bnxt_alloc_rx_rings(bp); if (rc) goto alloc_mem_err; rc = bnxt_alloc_tx_rings(bp); if (rc) goto alloc_mem_err; rc = bnxt_alloc_cp_rings(bp); if (rc) goto alloc_mem_err; bp->vnic_info[0].flags |= BNXT_VNIC_RSS_FLAG | BNXT_VNIC_MCAST_FLAG | BNXT_VNIC_UCAST_FLAG; rc = bnxt_alloc_vnic_attributes(bp); if (rc) goto alloc_mem_err; return 0; alloc_mem_err: bnxt_free_mem(bp, true); return rc; } static void bnxt_disable_int(struct bnxt *bp) { int i; if (!bp->bnapi) return; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct bnxt_ring_struct *ring = &cpr->cp_ring_struct; if (ring->fw_ring_id != INVALID_HW_RING_ID) bnxt_db_nq(bp, &cpr->cp_db, cpr->cp_raw_cons); } } static int bnxt_cp_num_to_irq_num(struct bnxt *bp, int n) { struct bnxt_napi *bnapi = bp->bnapi[n]; struct bnxt_cp_ring_info *cpr; cpr = &bnapi->cp_ring; return cpr->cp_ring_struct.map_idx; } static void bnxt_disable_int_sync(struct bnxt *bp) { int i; atomic_inc(&bp->intr_sem); bnxt_disable_int(bp); for (i = 0; i < bp->cp_nr_rings; i++) { int map_idx = bnxt_cp_num_to_irq_num(bp, i); synchronize_irq(bp->irq_tbl[map_idx].vector); } } static void bnxt_enable_int(struct bnxt *bp) { int i; atomic_set(&bp->intr_sem, 0); for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; bnxt_db_nq_arm(bp, &cpr->cp_db, cpr->cp_raw_cons); } } void bnxt_hwrm_cmd_hdr_init(struct bnxt *bp, void *request, u16 req_type, u16 cmpl_ring, u16 target_id) { struct input *req = request; req->req_type = cpu_to_le16(req_type); req->cmpl_ring = cpu_to_le16(cmpl_ring); req->target_id = cpu_to_le16(target_id); if (bnxt_kong_hwrm_message(bp, req)) req->resp_addr = cpu_to_le64(bp->hwrm_cmd_kong_resp_dma_addr); else req->resp_addr = cpu_to_le64(bp->hwrm_cmd_resp_dma_addr); } static int bnxt_hwrm_to_stderr(u32 hwrm_err) { switch (hwrm_err) { case HWRM_ERR_CODE_SUCCESS: return 0; case HWRM_ERR_CODE_RESOURCE_ACCESS_DENIED: return -EACCES; case HWRM_ERR_CODE_RESOURCE_ALLOC_ERROR: return -ENOSPC; case HWRM_ERR_CODE_INVALID_PARAMS: case HWRM_ERR_CODE_INVALID_FLAGS: case HWRM_ERR_CODE_INVALID_ENABLES: case HWRM_ERR_CODE_UNSUPPORTED_TLV: case HWRM_ERR_CODE_UNSUPPORTED_OPTION_ERR: return -EINVAL; case HWRM_ERR_CODE_NO_BUFFER: return -ENOMEM; case HWRM_ERR_CODE_HOT_RESET_PROGRESS: case HWRM_ERR_CODE_BUSY: return -EAGAIN; case HWRM_ERR_CODE_CMD_NOT_SUPPORTED: return -EOPNOTSUPP; default: return -EIO; } } static int bnxt_hwrm_do_send_msg(struct bnxt *bp, void *msg, u32 msg_len, int timeout, bool silent) { int i, intr_process, rc, tmo_count; struct input *req = msg; u32 *data = msg; u8 *valid; u16 cp_ring_id, len = 0; struct hwrm_err_output *resp = bp->hwrm_cmd_resp_addr; u16 max_req_len = BNXT_HWRM_MAX_REQ_LEN; struct hwrm_short_input short_input = {0}; u32 doorbell_offset = BNXT_GRCPF_REG_CHIMP_COMM_TRIGGER; u32 bar_offset = BNXT_GRCPF_REG_CHIMP_COMM; u16 dst = BNXT_HWRM_CHNL_CHIMP; if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) return -EBUSY; if (msg_len > BNXT_HWRM_MAX_REQ_LEN) { if (msg_len > bp->hwrm_max_ext_req_len || !bp->hwrm_short_cmd_req_addr) return -EINVAL; } if (bnxt_hwrm_kong_chnl(bp, req)) { dst = BNXT_HWRM_CHNL_KONG; bar_offset = BNXT_GRCPF_REG_KONG_COMM; doorbell_offset = BNXT_GRCPF_REG_KONG_COMM_TRIGGER; resp = bp->hwrm_cmd_kong_resp_addr; } memset(resp, 0, PAGE_SIZE); cp_ring_id = le16_to_cpu(req->cmpl_ring); intr_process = (cp_ring_id == INVALID_HW_RING_ID) ? 0 : 1; req->seq_id = cpu_to_le16(bnxt_get_hwrm_seq_id(bp, dst)); /* currently supports only one outstanding message */ if (intr_process) bp->hwrm_intr_seq_id = le16_to_cpu(req->seq_id); if ((bp->fw_cap & BNXT_FW_CAP_SHORT_CMD) || msg_len > BNXT_HWRM_MAX_REQ_LEN) { void *short_cmd_req = bp->hwrm_short_cmd_req_addr; u16 max_msg_len; /* Set boundary for maximum extended request length for short * cmd format. If passed up from device use the max supported * internal req length. */ max_msg_len = bp->hwrm_max_ext_req_len; memcpy(short_cmd_req, req, msg_len); if (msg_len < max_msg_len) memset(short_cmd_req + msg_len, 0, max_msg_len - msg_len); short_input.req_type = req->req_type; short_input.signature = cpu_to_le16(SHORT_REQ_SIGNATURE_SHORT_CMD); short_input.size = cpu_to_le16(msg_len); short_input.req_addr = cpu_to_le64(bp->hwrm_short_cmd_req_dma_addr); data = (u32 *)&short_input; msg_len = sizeof(short_input); /* Sync memory write before updating doorbell */ wmb(); max_req_len = BNXT_HWRM_SHORT_REQ_LEN; } /* Write request msg to hwrm channel */ __iowrite32_copy(bp->bar0 + bar_offset, data, msg_len / 4); for (i = msg_len; i < max_req_len; i += 4) writel(0, bp->bar0 + bar_offset + i); /* Ring channel doorbell */ writel(1, bp->bar0 + doorbell_offset); if (!pci_is_enabled(bp->pdev)) return 0; if (!timeout) timeout = DFLT_HWRM_CMD_TIMEOUT; /* convert timeout to usec */ timeout *= 1000; i = 0; /* Short timeout for the first few iterations: * number of loops = number of loops for short timeout + * number of loops for standard timeout. */ tmo_count = HWRM_SHORT_TIMEOUT_COUNTER; timeout = timeout - HWRM_SHORT_MIN_TIMEOUT * HWRM_SHORT_TIMEOUT_COUNTER; tmo_count += DIV_ROUND_UP(timeout, HWRM_MIN_TIMEOUT); if (intr_process) { u16 seq_id = bp->hwrm_intr_seq_id; /* Wait until hwrm response cmpl interrupt is processed */ while (bp->hwrm_intr_seq_id != (u16)~seq_id && i++ < tmo_count) { /* Abort the wait for completion if the FW health * check has failed. */ if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) return -EBUSY; /* on first few passes, just barely sleep */ if (i < HWRM_SHORT_TIMEOUT_COUNTER) usleep_range(HWRM_SHORT_MIN_TIMEOUT, HWRM_SHORT_MAX_TIMEOUT); else usleep_range(HWRM_MIN_TIMEOUT, HWRM_MAX_TIMEOUT); } if (bp->hwrm_intr_seq_id != (u16)~seq_id) { if (!silent) netdev_err(bp->dev, "Resp cmpl intr err msg: 0x%x\n", le16_to_cpu(req->req_type)); return -EBUSY; } len = le16_to_cpu(resp->resp_len); valid = ((u8 *)resp) + len - 1; } else { int j; /* Check if response len is updated */ for (i = 0; i < tmo_count; i++) { /* Abort the wait for completion if the FW health * check has failed. */ if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) return -EBUSY; len = le16_to_cpu(resp->resp_len); if (len) break; /* on first few passes, just barely sleep */ if (i < HWRM_SHORT_TIMEOUT_COUNTER) usleep_range(HWRM_SHORT_MIN_TIMEOUT, HWRM_SHORT_MAX_TIMEOUT); else usleep_range(HWRM_MIN_TIMEOUT, HWRM_MAX_TIMEOUT); } if (i >= tmo_count) { if (!silent) netdev_err(bp->dev, "Error (timeout: %d) msg {0x%x 0x%x} len:%d\n", HWRM_TOTAL_TIMEOUT(i), le16_to_cpu(req->req_type), le16_to_cpu(req->seq_id), len); return -EBUSY; } /* Last byte of resp contains valid bit */ valid = ((u8 *)resp) + len - 1; for (j = 0; j < HWRM_VALID_BIT_DELAY_USEC; j++) { /* make sure we read from updated DMA memory */ dma_rmb(); if (*valid) break; usleep_range(1, 5); } if (j >= HWRM_VALID_BIT_DELAY_USEC) { if (!silent) netdev_err(bp->dev, "Error (timeout: %d) msg {0x%x 0x%x} len:%d v:%d\n", HWRM_TOTAL_TIMEOUT(i), le16_to_cpu(req->req_type), le16_to_cpu(req->seq_id), len, *valid); return -EBUSY; } } /* Zero valid bit for compatibility. Valid bit in an older spec * may become a new field in a newer spec. We must make sure that * a new field not implemented by old spec will read zero. */ *valid = 0; rc = le16_to_cpu(resp->error_code); if (rc && !silent) netdev_err(bp->dev, "hwrm req_type 0x%x seq id 0x%x error 0x%x\n", le16_to_cpu(resp->req_type), le16_to_cpu(resp->seq_id), rc); return bnxt_hwrm_to_stderr(rc); } int _hwrm_send_message(struct bnxt *bp, void *msg, u32 msg_len, int timeout) { return bnxt_hwrm_do_send_msg(bp, msg, msg_len, timeout, false); } int _hwrm_send_message_silent(struct bnxt *bp, void *msg, u32 msg_len, int timeout) { return bnxt_hwrm_do_send_msg(bp, msg, msg_len, timeout, true); } int hwrm_send_message(struct bnxt *bp, void *msg, u32 msg_len, int timeout) { int rc; mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, msg, msg_len, timeout); mutex_unlock(&bp->hwrm_cmd_lock); return rc; } int hwrm_send_message_silent(struct bnxt *bp, void *msg, u32 msg_len, int timeout) { int rc; mutex_lock(&bp->hwrm_cmd_lock); rc = bnxt_hwrm_do_send_msg(bp, msg, msg_len, timeout, true); mutex_unlock(&bp->hwrm_cmd_lock); return rc; } int bnxt_hwrm_func_drv_rgtr(struct bnxt *bp, unsigned long *bmap, int bmap_size, bool async_only) { struct hwrm_func_drv_rgtr_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_func_drv_rgtr_input req = {0}; DECLARE_BITMAP(async_events_bmap, 256); u32 *events = (u32 *)async_events_bmap; u32 flags; int rc, i; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_DRV_RGTR, -1, -1); req.enables = cpu_to_le32(FUNC_DRV_RGTR_REQ_ENABLES_OS_TYPE | FUNC_DRV_RGTR_REQ_ENABLES_VER | FUNC_DRV_RGTR_REQ_ENABLES_ASYNC_EVENT_FWD); req.os_type = cpu_to_le16(FUNC_DRV_RGTR_REQ_OS_TYPE_LINUX); flags = FUNC_DRV_RGTR_REQ_FLAGS_16BIT_VER_MODE; if (bp->fw_cap & BNXT_FW_CAP_HOT_RESET) flags |= FUNC_DRV_RGTR_REQ_FLAGS_HOT_RESET_SUPPORT; if (bp->fw_cap & BNXT_FW_CAP_ERROR_RECOVERY) flags |= FUNC_DRV_RGTR_REQ_FLAGS_ERROR_RECOVERY_SUPPORT | FUNC_DRV_RGTR_REQ_FLAGS_MASTER_SUPPORT; req.flags = cpu_to_le32(flags); req.ver_maj_8b = DRV_VER_MAJ; req.ver_min_8b = DRV_VER_MIN; req.ver_upd_8b = DRV_VER_UPD; req.ver_maj = cpu_to_le16(DRV_VER_MAJ); req.ver_min = cpu_to_le16(DRV_VER_MIN); req.ver_upd = cpu_to_le16(DRV_VER_UPD); if (BNXT_PF(bp)) { u32 data[8]; int i; memset(data, 0, sizeof(data)); for (i = 0; i < ARRAY_SIZE(bnxt_vf_req_snif); i++) { u16 cmd = bnxt_vf_req_snif[i]; unsigned int bit, idx; idx = cmd / 32; bit = cmd % 32; data[idx] |= 1 << bit; } for (i = 0; i < 8; i++) req.vf_req_fwd[i] = cpu_to_le32(data[i]); req.enables |= cpu_to_le32(FUNC_DRV_RGTR_REQ_ENABLES_VF_REQ_FWD); } if (bp->fw_cap & BNXT_FW_CAP_OVS_64BIT_HANDLE) req.flags |= cpu_to_le32( FUNC_DRV_RGTR_REQ_FLAGS_FLOW_HANDLE_64BIT_MODE); memset(async_events_bmap, 0, sizeof(async_events_bmap)); for (i = 0; i < ARRAY_SIZE(bnxt_async_events_arr); i++) { u16 event_id = bnxt_async_events_arr[i]; if (event_id == ASYNC_EVENT_CMPL_EVENT_ID_ERROR_RECOVERY && !(bp->fw_cap & BNXT_FW_CAP_ERROR_RECOVERY)) continue; __set_bit(bnxt_async_events_arr[i], async_events_bmap); } if (bmap && bmap_size) { for (i = 0; i < bmap_size; i++) { if (test_bit(i, bmap)) __set_bit(i, async_events_bmap); } } for (i = 0; i < 8; i++) req.async_event_fwd[i] |= cpu_to_le32(events[i]); if (async_only) req.enables = cpu_to_le32(FUNC_DRV_RGTR_REQ_ENABLES_ASYNC_EVENT_FWD); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { set_bit(BNXT_STATE_DRV_REGISTERED, &bp->state); if (resp->flags & cpu_to_le32(FUNC_DRV_RGTR_RESP_FLAGS_IF_CHANGE_SUPPORTED)) bp->fw_cap |= BNXT_FW_CAP_IF_CHANGE; } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_func_drv_unrgtr(struct bnxt *bp) { struct hwrm_func_drv_unrgtr_input req = {0}; if (!test_and_clear_bit(BNXT_STATE_DRV_REGISTERED, &bp->state)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_DRV_UNRGTR, -1, -1); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_tunnel_dst_port_free(struct bnxt *bp, u8 tunnel_type) { u32 rc = 0; struct hwrm_tunnel_dst_port_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_TUNNEL_DST_PORT_FREE, -1, -1); req.tunnel_type = tunnel_type; switch (tunnel_type) { case TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_VXLAN: req.tunnel_dst_port_id = bp->vxlan_fw_dst_port_id; break; case TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_GENEVE: req.tunnel_dst_port_id = bp->nge_fw_dst_port_id; break; default: break; } rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) netdev_err(bp->dev, "hwrm_tunnel_dst_port_free failed. rc:%d\n", rc); return rc; } static int bnxt_hwrm_tunnel_dst_port_alloc(struct bnxt *bp, __be16 port, u8 tunnel_type) { u32 rc = 0; struct hwrm_tunnel_dst_port_alloc_input req = {0}; struct hwrm_tunnel_dst_port_alloc_output *resp = bp->hwrm_cmd_resp_addr; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_TUNNEL_DST_PORT_ALLOC, -1, -1); req.tunnel_type = tunnel_type; req.tunnel_dst_port_val = port; mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) { netdev_err(bp->dev, "hwrm_tunnel_dst_port_alloc failed. rc:%d\n", rc); goto err_out; } switch (tunnel_type) { case TUNNEL_DST_PORT_ALLOC_REQ_TUNNEL_TYPE_VXLAN: bp->vxlan_fw_dst_port_id = resp->tunnel_dst_port_id; break; case TUNNEL_DST_PORT_ALLOC_REQ_TUNNEL_TYPE_GENEVE: bp->nge_fw_dst_port_id = resp->tunnel_dst_port_id; break; default: break; } err_out: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_cfa_l2_set_rx_mask(struct bnxt *bp, u16 vnic_id) { struct hwrm_cfa_l2_set_rx_mask_input req = {0}; struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_L2_SET_RX_MASK, -1, -1); req.vnic_id = cpu_to_le32(vnic->fw_vnic_id); req.num_mc_entries = cpu_to_le32(vnic->mc_list_count); req.mc_tbl_addr = cpu_to_le64(vnic->mc_list_mapping); req.mask = cpu_to_le32(vnic->rx_mask); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } #ifdef CONFIG_RFS_ACCEL static int bnxt_hwrm_cfa_ntuple_filter_free(struct bnxt *bp, struct bnxt_ntuple_filter *fltr) { struct hwrm_cfa_ntuple_filter_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_NTUPLE_FILTER_FREE, -1, -1); req.ntuple_filter_id = fltr->filter_id; return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } #define BNXT_NTP_FLTR_FLAGS \ (CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_L2_FILTER_ID | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_ETHERTYPE | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_SRC_MACADDR | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_IPADDR_TYPE | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_SRC_IPADDR | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_SRC_IPADDR_MASK | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_DST_IPADDR | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_DST_IPADDR_MASK | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_IP_PROTOCOL | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_SRC_PORT | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_SRC_PORT_MASK | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_DST_PORT | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_DST_PORT_MASK | \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_DST_ID) #define BNXT_NTP_TUNNEL_FLTR_FLAG \ CFA_NTUPLE_FILTER_ALLOC_REQ_ENABLES_TUNNEL_TYPE static int bnxt_hwrm_cfa_ntuple_filter_alloc(struct bnxt *bp, struct bnxt_ntuple_filter *fltr) { struct hwrm_cfa_ntuple_filter_alloc_input req = {0}; struct hwrm_cfa_ntuple_filter_alloc_output *resp; struct flow_keys *keys = &fltr->fkeys; struct bnxt_vnic_info *vnic; u32 flags = 0; int rc = 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_NTUPLE_FILTER_ALLOC, -1, -1); req.l2_filter_id = bp->vnic_info[0].fw_l2_filter_id[fltr->l2_fltr_idx]; if (bp->fw_cap & BNXT_FW_CAP_CFA_RFS_RING_TBL_IDX_V2) { flags = CFA_NTUPLE_FILTER_ALLOC_REQ_FLAGS_DEST_RFS_RING_IDX; req.dst_id = cpu_to_le16(fltr->rxq); } else { vnic = &bp->vnic_info[fltr->rxq + 1]; req.dst_id = cpu_to_le16(vnic->fw_vnic_id); } req.flags = cpu_to_le32(flags); req.enables = cpu_to_le32(BNXT_NTP_FLTR_FLAGS); req.ethertype = htons(ETH_P_IP); memcpy(req.src_macaddr, fltr->src_mac_addr, ETH_ALEN); req.ip_addr_type = CFA_NTUPLE_FILTER_ALLOC_REQ_IP_ADDR_TYPE_IPV4; req.ip_protocol = keys->basic.ip_proto; if (keys->basic.n_proto == htons(ETH_P_IPV6)) { int i; req.ethertype = htons(ETH_P_IPV6); req.ip_addr_type = CFA_NTUPLE_FILTER_ALLOC_REQ_IP_ADDR_TYPE_IPV6; *(struct in6_addr *)&req.src_ipaddr[0] = keys->addrs.v6addrs.src; *(struct in6_addr *)&req.dst_ipaddr[0] = keys->addrs.v6addrs.dst; for (i = 0; i < 4; i++) { req.src_ipaddr_mask[i] = cpu_to_be32(0xffffffff); req.dst_ipaddr_mask[i] = cpu_to_be32(0xffffffff); } } else { req.src_ipaddr[0] = keys->addrs.v4addrs.src; req.src_ipaddr_mask[0] = cpu_to_be32(0xffffffff); req.dst_ipaddr[0] = keys->addrs.v4addrs.dst; req.dst_ipaddr_mask[0] = cpu_to_be32(0xffffffff); } if (keys->control.flags & FLOW_DIS_ENCAPSULATION) { req.enables |= cpu_to_le32(BNXT_NTP_TUNNEL_FLTR_FLAG); req.tunnel_type = CFA_NTUPLE_FILTER_ALLOC_REQ_TUNNEL_TYPE_ANYTUNNEL; } req.src_port = keys->ports.src; req.src_port_mask = cpu_to_be16(0xffff); req.dst_port = keys->ports.dst; req.dst_port_mask = cpu_to_be16(0xffff); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { resp = bnxt_get_hwrm_resp_addr(bp, &req); fltr->filter_id = resp->ntuple_filter_id; } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } #endif static int bnxt_hwrm_set_vnic_filter(struct bnxt *bp, u16 vnic_id, u16 idx, u8 *mac_addr) { u32 rc = 0; struct hwrm_cfa_l2_filter_alloc_input req = {0}; struct hwrm_cfa_l2_filter_alloc_output *resp = bp->hwrm_cmd_resp_addr; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_L2_FILTER_ALLOC, -1, -1); req.flags = cpu_to_le32(CFA_L2_FILTER_ALLOC_REQ_FLAGS_PATH_RX); if (!BNXT_CHIP_TYPE_NITRO_A0(bp)) req.flags |= cpu_to_le32(CFA_L2_FILTER_ALLOC_REQ_FLAGS_OUTERMOST); req.dst_id = cpu_to_le16(bp->vnic_info[vnic_id].fw_vnic_id); req.enables = cpu_to_le32(CFA_L2_FILTER_ALLOC_REQ_ENABLES_L2_ADDR | CFA_L2_FILTER_ALLOC_REQ_ENABLES_DST_ID | CFA_L2_FILTER_ALLOC_REQ_ENABLES_L2_ADDR_MASK); memcpy(req.l2_addr, mac_addr, ETH_ALEN); req.l2_addr_mask[0] = 0xff; req.l2_addr_mask[1] = 0xff; req.l2_addr_mask[2] = 0xff; req.l2_addr_mask[3] = 0xff; req.l2_addr_mask[4] = 0xff; req.l2_addr_mask[5] = 0xff; mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) bp->vnic_info[vnic_id].fw_l2_filter_id[idx] = resp->l2_filter_id; mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_clear_vnic_filter(struct bnxt *bp) { u16 i, j, num_of_vnics = 1; /* only vnic 0 supported */ int rc = 0; /* Any associated ntuple filters will also be cleared by firmware. */ mutex_lock(&bp->hwrm_cmd_lock); for (i = 0; i < num_of_vnics; i++) { struct bnxt_vnic_info *vnic = &bp->vnic_info[i]; for (j = 0; j < vnic->uc_filter_count; j++) { struct hwrm_cfa_l2_filter_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_L2_FILTER_FREE, -1, -1); req.l2_filter_id = vnic->fw_l2_filter_id[j]; rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } vnic->uc_filter_count = 0; } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_vnic_set_tpa(struct bnxt *bp, u16 vnic_id, u32 tpa_flags) { struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; u16 max_aggs = VNIC_TPA_CFG_REQ_MAX_AGGS_MAX; struct hwrm_vnic_tpa_cfg_input req = {0}; if (vnic->fw_vnic_id == INVALID_HW_RING_ID) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_TPA_CFG, -1, -1); if (tpa_flags) { u16 mss = bp->dev->mtu - 40; u32 nsegs, n, segs = 0, flags; flags = VNIC_TPA_CFG_REQ_FLAGS_TPA | VNIC_TPA_CFG_REQ_FLAGS_ENCAP_TPA | VNIC_TPA_CFG_REQ_FLAGS_RSC_WND_UPDATE | VNIC_TPA_CFG_REQ_FLAGS_AGG_WITH_ECN | VNIC_TPA_CFG_REQ_FLAGS_AGG_WITH_SAME_GRE_SEQ; if (tpa_flags & BNXT_FLAG_GRO) flags |= VNIC_TPA_CFG_REQ_FLAGS_GRO; req.flags = cpu_to_le32(flags); req.enables = cpu_to_le32(VNIC_TPA_CFG_REQ_ENABLES_MAX_AGG_SEGS | VNIC_TPA_CFG_REQ_ENABLES_MAX_AGGS | VNIC_TPA_CFG_REQ_ENABLES_MIN_AGG_LEN); /* Number of segs are log2 units, and first packet is not * included as part of this units. */ if (mss <= BNXT_RX_PAGE_SIZE) { n = BNXT_RX_PAGE_SIZE / mss; nsegs = (MAX_SKB_FRAGS - 1) * n; } else { n = mss / BNXT_RX_PAGE_SIZE; if (mss & (BNXT_RX_PAGE_SIZE - 1)) n++; nsegs = (MAX_SKB_FRAGS - n) / n; } if (bp->flags & BNXT_FLAG_CHIP_P5) { segs = MAX_TPA_SEGS_P5; max_aggs = bp->max_tpa; } else { segs = ilog2(nsegs); } req.max_agg_segs = cpu_to_le16(segs); req.max_aggs = cpu_to_le16(max_aggs); req.min_agg_len = cpu_to_le32(512); } req.vnic_id = cpu_to_le16(vnic->fw_vnic_id); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static u16 bnxt_cp_ring_from_grp(struct bnxt *bp, struct bnxt_ring_struct *ring) { struct bnxt_ring_grp_info *grp_info; grp_info = &bp->grp_info[ring->grp_idx]; return grp_info->cp_fw_ring_id; } static u16 bnxt_cp_ring_for_rx(struct bnxt *bp, struct bnxt_rx_ring_info *rxr) { if (bp->flags & BNXT_FLAG_CHIP_P5) { struct bnxt_napi *bnapi = rxr->bnapi; struct bnxt_cp_ring_info *cpr; cpr = bnapi->cp_ring.cp_ring_arr[BNXT_RX_HDL]; return cpr->cp_ring_struct.fw_ring_id; } else { return bnxt_cp_ring_from_grp(bp, &rxr->rx_ring_struct); } } static u16 bnxt_cp_ring_for_tx(struct bnxt *bp, struct bnxt_tx_ring_info *txr) { if (bp->flags & BNXT_FLAG_CHIP_P5) { struct bnxt_napi *bnapi = txr->bnapi; struct bnxt_cp_ring_info *cpr; cpr = bnapi->cp_ring.cp_ring_arr[BNXT_TX_HDL]; return cpr->cp_ring_struct.fw_ring_id; } else { return bnxt_cp_ring_from_grp(bp, &txr->tx_ring_struct); } } static int bnxt_hwrm_vnic_set_rss(struct bnxt *bp, u16 vnic_id, bool set_rss) { u32 i, j, max_rings; struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; struct hwrm_vnic_rss_cfg_input req = {0}; if ((bp->flags & BNXT_FLAG_CHIP_P5) || vnic->fw_rss_cos_lb_ctx[0] == INVALID_HW_RING_ID) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_RSS_CFG, -1, -1); if (set_rss) { req.hash_type = cpu_to_le32(bp->rss_hash_cfg); req.hash_mode_flags = VNIC_RSS_CFG_REQ_HASH_MODE_FLAGS_DEFAULT; if (vnic->flags & BNXT_VNIC_RSS_FLAG) { if (BNXT_CHIP_TYPE_NITRO_A0(bp)) max_rings = bp->rx_nr_rings - 1; else max_rings = bp->rx_nr_rings; } else { max_rings = 1; } /* Fill the RSS indirection table with ring group ids */ for (i = 0, j = 0; i < HW_HASH_INDEX_SIZE; i++, j++) { if (j == max_rings) j = 0; vnic->rss_table[i] = cpu_to_le16(vnic->fw_grp_ids[j]); } req.ring_grp_tbl_addr = cpu_to_le64(vnic->rss_table_dma_addr); req.hash_key_tbl_addr = cpu_to_le64(vnic->rss_hash_key_dma_addr); } req.rss_ctx_idx = cpu_to_le16(vnic->fw_rss_cos_lb_ctx[0]); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_vnic_set_rss_p5(struct bnxt *bp, u16 vnic_id, bool set_rss) { struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; u32 i, j, k, nr_ctxs, max_rings = bp->rx_nr_rings; struct bnxt_rx_ring_info *rxr = &bp->rx_ring[0]; struct hwrm_vnic_rss_cfg_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_RSS_CFG, -1, -1); req.vnic_id = cpu_to_le16(vnic->fw_vnic_id); if (!set_rss) { hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); return 0; } req.hash_type = cpu_to_le32(bp->rss_hash_cfg); req.hash_mode_flags = VNIC_RSS_CFG_REQ_HASH_MODE_FLAGS_DEFAULT; req.ring_grp_tbl_addr = cpu_to_le64(vnic->rss_table_dma_addr); req.hash_key_tbl_addr = cpu_to_le64(vnic->rss_hash_key_dma_addr); nr_ctxs = DIV_ROUND_UP(bp->rx_nr_rings, 64); for (i = 0, k = 0; i < nr_ctxs; i++) { __le16 *ring_tbl = vnic->rss_table; int rc; req.ring_table_pair_index = i; req.rss_ctx_idx = cpu_to_le16(vnic->fw_rss_cos_lb_ctx[i]); for (j = 0; j < 64; j++) { u16 ring_id; ring_id = rxr->rx_ring_struct.fw_ring_id; *ring_tbl++ = cpu_to_le16(ring_id); ring_id = bnxt_cp_ring_for_rx(bp, rxr); *ring_tbl++ = cpu_to_le16(ring_id); rxr++; k++; if (k == max_rings) { k = 0; rxr = &bp->rx_ring[0]; } } rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) return rc; } return 0; } static int bnxt_hwrm_vnic_set_hds(struct bnxt *bp, u16 vnic_id) { struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; struct hwrm_vnic_plcmodes_cfg_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_PLCMODES_CFG, -1, -1); req.flags = cpu_to_le32(VNIC_PLCMODES_CFG_REQ_FLAGS_JUMBO_PLACEMENT | VNIC_PLCMODES_CFG_REQ_FLAGS_HDS_IPV4 | VNIC_PLCMODES_CFG_REQ_FLAGS_HDS_IPV6); req.enables = cpu_to_le32(VNIC_PLCMODES_CFG_REQ_ENABLES_JUMBO_THRESH_VALID | VNIC_PLCMODES_CFG_REQ_ENABLES_HDS_THRESHOLD_VALID); /* thresholds not implemented in firmware yet */ req.jumbo_thresh = cpu_to_le16(bp->rx_copy_thresh); req.hds_threshold = cpu_to_le16(bp->rx_copy_thresh); req.vnic_id = cpu_to_le32(vnic->fw_vnic_id); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static void bnxt_hwrm_vnic_ctx_free_one(struct bnxt *bp, u16 vnic_id, u16 ctx_idx) { struct hwrm_vnic_rss_cos_lb_ctx_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_RSS_COS_LB_CTX_FREE, -1, -1); req.rss_cos_lb_ctx_id = cpu_to_le16(bp->vnic_info[vnic_id].fw_rss_cos_lb_ctx[ctx_idx]); hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); bp->vnic_info[vnic_id].fw_rss_cos_lb_ctx[ctx_idx] = INVALID_HW_RING_ID; } static void bnxt_hwrm_vnic_ctx_free(struct bnxt *bp) { int i, j; for (i = 0; i < bp->nr_vnics; i++) { struct bnxt_vnic_info *vnic = &bp->vnic_info[i]; for (j = 0; j < BNXT_MAX_CTX_PER_VNIC; j++) { if (vnic->fw_rss_cos_lb_ctx[j] != INVALID_HW_RING_ID) bnxt_hwrm_vnic_ctx_free_one(bp, i, j); } } bp->rsscos_nr_ctxs = 0; } static int bnxt_hwrm_vnic_ctx_alloc(struct bnxt *bp, u16 vnic_id, u16 ctx_idx) { int rc; struct hwrm_vnic_rss_cos_lb_ctx_alloc_input req = {0}; struct hwrm_vnic_rss_cos_lb_ctx_alloc_output *resp = bp->hwrm_cmd_resp_addr; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_RSS_COS_LB_CTX_ALLOC, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) bp->vnic_info[vnic_id].fw_rss_cos_lb_ctx[ctx_idx] = le16_to_cpu(resp->rss_cos_lb_ctx_id); mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static u32 bnxt_get_roce_vnic_mode(struct bnxt *bp) { if (bp->flags & BNXT_FLAG_ROCE_MIRROR_CAP) return VNIC_CFG_REQ_FLAGS_ROCE_MIRRORING_CAPABLE_VNIC_MODE; return VNIC_CFG_REQ_FLAGS_ROCE_DUAL_VNIC_MODE; } int bnxt_hwrm_vnic_cfg(struct bnxt *bp, u16 vnic_id) { unsigned int ring = 0, grp_idx; struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; struct hwrm_vnic_cfg_input req = {0}; u16 def_vlan = 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_CFG, -1, -1); if (bp->flags & BNXT_FLAG_CHIP_P5) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[0]; req.default_rx_ring_id = cpu_to_le16(rxr->rx_ring_struct.fw_ring_id); req.default_cmpl_ring_id = cpu_to_le16(bnxt_cp_ring_for_rx(bp, rxr)); req.enables = cpu_to_le32(VNIC_CFG_REQ_ENABLES_DEFAULT_RX_RING_ID | VNIC_CFG_REQ_ENABLES_DEFAULT_CMPL_RING_ID); goto vnic_mru; } req.enables = cpu_to_le32(VNIC_CFG_REQ_ENABLES_DFLT_RING_GRP); /* Only RSS support for now TBD: COS & LB */ if (vnic->fw_rss_cos_lb_ctx[0] != INVALID_HW_RING_ID) { req.rss_rule = cpu_to_le16(vnic->fw_rss_cos_lb_ctx[0]); req.enables |= cpu_to_le32(VNIC_CFG_REQ_ENABLES_RSS_RULE | VNIC_CFG_REQ_ENABLES_MRU); } else if (vnic->flags & BNXT_VNIC_RFS_NEW_RSS_FLAG) { req.rss_rule = cpu_to_le16(bp->vnic_info[0].fw_rss_cos_lb_ctx[0]); req.enables |= cpu_to_le32(VNIC_CFG_REQ_ENABLES_RSS_RULE | VNIC_CFG_REQ_ENABLES_MRU); req.flags |= cpu_to_le32(VNIC_CFG_REQ_FLAGS_RSS_DFLT_CR_MODE); } else { req.rss_rule = cpu_to_le16(0xffff); } if (BNXT_CHIP_TYPE_NITRO_A0(bp) && (vnic->fw_rss_cos_lb_ctx[0] != INVALID_HW_RING_ID)) { req.cos_rule = cpu_to_le16(vnic->fw_rss_cos_lb_ctx[1]); req.enables |= cpu_to_le32(VNIC_CFG_REQ_ENABLES_COS_RULE); } else { req.cos_rule = cpu_to_le16(0xffff); } if (vnic->flags & BNXT_VNIC_RSS_FLAG) ring = 0; else if (vnic->flags & BNXT_VNIC_RFS_FLAG) ring = vnic_id - 1; else if ((vnic_id == 1) && BNXT_CHIP_TYPE_NITRO_A0(bp)) ring = bp->rx_nr_rings - 1; grp_idx = bp->rx_ring[ring].bnapi->index; req.dflt_ring_grp = cpu_to_le16(bp->grp_info[grp_idx].fw_grp_id); req.lb_rule = cpu_to_le16(0xffff); vnic_mru: req.mru = cpu_to_le16(bp->dev->mtu + ETH_HLEN + VLAN_HLEN); req.vnic_id = cpu_to_le16(vnic->fw_vnic_id); #ifdef CONFIG_BNXT_SRIOV if (BNXT_VF(bp)) def_vlan = bp->vf.vlan; #endif if ((bp->flags & BNXT_FLAG_STRIP_VLAN) || def_vlan) req.flags |= cpu_to_le32(VNIC_CFG_REQ_FLAGS_VLAN_STRIP_MODE); if (!vnic_id && bnxt_ulp_registered(bp->edev, BNXT_ROCE_ULP)) req.flags |= cpu_to_le32(bnxt_get_roce_vnic_mode(bp)); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static void bnxt_hwrm_vnic_free_one(struct bnxt *bp, u16 vnic_id) { if (bp->vnic_info[vnic_id].fw_vnic_id != INVALID_HW_RING_ID) { struct hwrm_vnic_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_FREE, -1, -1); req.vnic_id = cpu_to_le32(bp->vnic_info[vnic_id].fw_vnic_id); hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); bp->vnic_info[vnic_id].fw_vnic_id = INVALID_HW_RING_ID; } } static void bnxt_hwrm_vnic_free(struct bnxt *bp) { u16 i; for (i = 0; i < bp->nr_vnics; i++) bnxt_hwrm_vnic_free_one(bp, i); } static int bnxt_hwrm_vnic_alloc(struct bnxt *bp, u16 vnic_id, unsigned int start_rx_ring_idx, unsigned int nr_rings) { int rc = 0; unsigned int i, j, grp_idx, end_idx = start_rx_ring_idx + nr_rings; struct hwrm_vnic_alloc_input req = {0}; struct hwrm_vnic_alloc_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; if (bp->flags & BNXT_FLAG_CHIP_P5) goto vnic_no_ring_grps; /* map ring groups to this vnic */ for (i = start_rx_ring_idx, j = 0; i < end_idx; i++, j++) { grp_idx = bp->rx_ring[i].bnapi->index; if (bp->grp_info[grp_idx].fw_grp_id == INVALID_HW_RING_ID) { netdev_err(bp->dev, "Not enough ring groups avail:%x req:%x\n", j, nr_rings); break; } vnic->fw_grp_ids[j] = bp->grp_info[grp_idx].fw_grp_id; } vnic_no_ring_grps: for (i = 0; i < BNXT_MAX_CTX_PER_VNIC; i++) vnic->fw_rss_cos_lb_ctx[i] = INVALID_HW_RING_ID; if (vnic_id == 0) req.flags = cpu_to_le32(VNIC_ALLOC_REQ_FLAGS_DEFAULT); bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_ALLOC, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) vnic->fw_vnic_id = le32_to_cpu(resp->vnic_id); mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_vnic_qcaps(struct bnxt *bp) { struct hwrm_vnic_qcaps_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_vnic_qcaps_input req = {0}; int rc; bp->hw_ring_stats_size = sizeof(struct ctx_hw_stats); bp->flags &= ~(BNXT_FLAG_NEW_RSS_CAP | BNXT_FLAG_ROCE_MIRROR_CAP); if (bp->hwrm_spec_code < 0x10600) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VNIC_QCAPS, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { u32 flags = le32_to_cpu(resp->flags); if (!(bp->flags & BNXT_FLAG_CHIP_P5) && (flags & VNIC_QCAPS_RESP_FLAGS_RSS_DFLT_CR_CAP)) bp->flags |= BNXT_FLAG_NEW_RSS_CAP; if (flags & VNIC_QCAPS_RESP_FLAGS_ROCE_MIRRORING_CAPABLE_VNIC_CAP) bp->flags |= BNXT_FLAG_ROCE_MIRROR_CAP; bp->max_tpa_v2 = le16_to_cpu(resp->max_aggs_supported); if (bp->max_tpa_v2) bp->hw_ring_stats_size = sizeof(struct ctx_hw_stats_ext); } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_ring_grp_alloc(struct bnxt *bp) { u16 i; u32 rc = 0; if (bp->flags & BNXT_FLAG_CHIP_P5) return 0; mutex_lock(&bp->hwrm_cmd_lock); for (i = 0; i < bp->rx_nr_rings; i++) { struct hwrm_ring_grp_alloc_input req = {0}; struct hwrm_ring_grp_alloc_output *resp = bp->hwrm_cmd_resp_addr; unsigned int grp_idx = bp->rx_ring[i].bnapi->index; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_RING_GRP_ALLOC, -1, -1); req.cr = cpu_to_le16(bp->grp_info[grp_idx].cp_fw_ring_id); req.rr = cpu_to_le16(bp->grp_info[grp_idx].rx_fw_ring_id); req.ar = cpu_to_le16(bp->grp_info[grp_idx].agg_fw_ring_id); req.sc = cpu_to_le16(bp->grp_info[grp_idx].fw_stats_ctx); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) break; bp->grp_info[grp_idx].fw_grp_id = le32_to_cpu(resp->ring_group_id); } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static void bnxt_hwrm_ring_grp_free(struct bnxt *bp) { u16 i; struct hwrm_ring_grp_free_input req = {0}; if (!bp->grp_info || (bp->flags & BNXT_FLAG_CHIP_P5)) return; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_RING_GRP_FREE, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); for (i = 0; i < bp->cp_nr_rings; i++) { if (bp->grp_info[i].fw_grp_id == INVALID_HW_RING_ID) continue; req.ring_group_id = cpu_to_le32(bp->grp_info[i].fw_grp_id); _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); bp->grp_info[i].fw_grp_id = INVALID_HW_RING_ID; } mutex_unlock(&bp->hwrm_cmd_lock); } static int hwrm_ring_alloc_send_msg(struct bnxt *bp, struct bnxt_ring_struct *ring, u32 ring_type, u32 map_index) { int rc = 0, err = 0; struct hwrm_ring_alloc_input req = {0}; struct hwrm_ring_alloc_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_ring_mem_info *rmem = &ring->ring_mem; struct bnxt_ring_grp_info *grp_info; u16 ring_id; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_RING_ALLOC, -1, -1); req.enables = 0; if (rmem->nr_pages > 1) { req.page_tbl_addr = cpu_to_le64(rmem->pg_tbl_map); /* Page size is in log2 units */ req.page_size = BNXT_PAGE_SHIFT; req.page_tbl_depth = 1; } else { req.page_tbl_addr = cpu_to_le64(rmem->dma_arr[0]); } req.fbo = 0; /* Association of ring index with doorbell index and MSIX number */ req.logical_id = cpu_to_le16(map_index); switch (ring_type) { case HWRM_RING_ALLOC_TX: { struct bnxt_tx_ring_info *txr; txr = container_of(ring, struct bnxt_tx_ring_info, tx_ring_struct); req.ring_type = RING_ALLOC_REQ_RING_TYPE_TX; /* Association of transmit ring with completion ring */ grp_info = &bp->grp_info[ring->grp_idx]; req.cmpl_ring_id = cpu_to_le16(bnxt_cp_ring_for_tx(bp, txr)); req.length = cpu_to_le32(bp->tx_ring_mask + 1); req.stat_ctx_id = cpu_to_le32(grp_info->fw_stats_ctx); req.queue_id = cpu_to_le16(ring->queue_id); break; } case HWRM_RING_ALLOC_RX: req.ring_type = RING_ALLOC_REQ_RING_TYPE_RX; req.length = cpu_to_le32(bp->rx_ring_mask + 1); if (bp->flags & BNXT_FLAG_CHIP_P5) { u16 flags = 0; /* Association of rx ring with stats context */ grp_info = &bp->grp_info[ring->grp_idx]; req.rx_buf_size = cpu_to_le16(bp->rx_buf_use_size); req.stat_ctx_id = cpu_to_le32(grp_info->fw_stats_ctx); req.enables |= cpu_to_le32( RING_ALLOC_REQ_ENABLES_RX_BUF_SIZE_VALID); if (NET_IP_ALIGN == 2) flags = RING_ALLOC_REQ_FLAGS_RX_SOP_PAD; req.flags = cpu_to_le16(flags); } break; case HWRM_RING_ALLOC_AGG: if (bp->flags & BNXT_FLAG_CHIP_P5) { req.ring_type = RING_ALLOC_REQ_RING_TYPE_RX_AGG; /* Association of agg ring with rx ring */ grp_info = &bp->grp_info[ring->grp_idx]; req.rx_ring_id = cpu_to_le16(grp_info->rx_fw_ring_id); req.rx_buf_size = cpu_to_le16(BNXT_RX_PAGE_SIZE); req.stat_ctx_id = cpu_to_le32(grp_info->fw_stats_ctx); req.enables |= cpu_to_le32( RING_ALLOC_REQ_ENABLES_RX_RING_ID_VALID | RING_ALLOC_REQ_ENABLES_RX_BUF_SIZE_VALID); } else { req.ring_type = RING_ALLOC_REQ_RING_TYPE_RX; } req.length = cpu_to_le32(bp->rx_agg_ring_mask + 1); break; case HWRM_RING_ALLOC_CMPL: req.ring_type = RING_ALLOC_REQ_RING_TYPE_L2_CMPL; req.length = cpu_to_le32(bp->cp_ring_mask + 1); if (bp->flags & BNXT_FLAG_CHIP_P5) { /* Association of cp ring with nq */ grp_info = &bp->grp_info[map_index]; req.nq_ring_id = cpu_to_le16(grp_info->cp_fw_ring_id); req.cq_handle = cpu_to_le64(ring->handle); req.enables |= cpu_to_le32( RING_ALLOC_REQ_ENABLES_NQ_RING_ID_VALID); } else if (bp->flags & BNXT_FLAG_USING_MSIX) { req.int_mode = RING_ALLOC_REQ_INT_MODE_MSIX; } break; case HWRM_RING_ALLOC_NQ: req.ring_type = RING_ALLOC_REQ_RING_TYPE_NQ; req.length = cpu_to_le32(bp->cp_ring_mask + 1); if (bp->flags & BNXT_FLAG_USING_MSIX) req.int_mode = RING_ALLOC_REQ_INT_MODE_MSIX; break; default: netdev_err(bp->dev, "hwrm alloc invalid ring type %d\n", ring_type); return -1; } mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); err = le16_to_cpu(resp->error_code); ring_id = le16_to_cpu(resp->ring_id); mutex_unlock(&bp->hwrm_cmd_lock); if (rc || err) { netdev_err(bp->dev, "hwrm_ring_alloc type %d failed. rc:%x err:%x\n", ring_type, rc, err); return -EIO; } ring->fw_ring_id = ring_id; return rc; } static int bnxt_hwrm_set_async_event_cr(struct bnxt *bp, int idx) { int rc; if (BNXT_PF(bp)) { struct hwrm_func_cfg_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_CFG, -1, -1); req.fid = cpu_to_le16(0xffff); req.enables = cpu_to_le32(FUNC_CFG_REQ_ENABLES_ASYNC_EVENT_CR); req.async_event_cr = cpu_to_le16(idx); rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } else { struct hwrm_func_vf_cfg_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_VF_CFG, -1, -1); req.enables = cpu_to_le32(FUNC_VF_CFG_REQ_ENABLES_ASYNC_EVENT_CR); req.async_event_cr = cpu_to_le16(idx); rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } return rc; } static void bnxt_set_db(struct bnxt *bp, struct bnxt_db_info *db, u32 ring_type, u32 map_idx, u32 xid) { if (bp->flags & BNXT_FLAG_CHIP_P5) { if (BNXT_PF(bp)) db->doorbell = bp->bar1 + DB_PF_OFFSET_P5; else db->doorbell = bp->bar1 + DB_VF_OFFSET_P5; switch (ring_type) { case HWRM_RING_ALLOC_TX: db->db_key64 = DBR_PATH_L2 | DBR_TYPE_SQ; break; case HWRM_RING_ALLOC_RX: case HWRM_RING_ALLOC_AGG: db->db_key64 = DBR_PATH_L2 | DBR_TYPE_SRQ; break; case HWRM_RING_ALLOC_CMPL: db->db_key64 = DBR_PATH_L2; break; case HWRM_RING_ALLOC_NQ: db->db_key64 = DBR_PATH_L2; break; } db->db_key64 |= (u64)xid << DBR_XID_SFT; } else { db->doorbell = bp->bar1 + map_idx * 0x80; switch (ring_type) { case HWRM_RING_ALLOC_TX: db->db_key32 = DB_KEY_TX; break; case HWRM_RING_ALLOC_RX: case HWRM_RING_ALLOC_AGG: db->db_key32 = DB_KEY_RX; break; case HWRM_RING_ALLOC_CMPL: db->db_key32 = DB_KEY_CP; break; } } } static int bnxt_hwrm_ring_alloc(struct bnxt *bp) { bool agg_rings = !!(bp->flags & BNXT_FLAG_AGG_RINGS); int i, rc = 0; u32 type; if (bp->flags & BNXT_FLAG_CHIP_P5) type = HWRM_RING_ALLOC_NQ; else type = HWRM_RING_ALLOC_CMPL; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct bnxt_ring_struct *ring = &cpr->cp_ring_struct; u32 map_idx = ring->map_idx; unsigned int vector; vector = bp->irq_tbl[map_idx].vector; disable_irq_nosync(vector); rc = hwrm_ring_alloc_send_msg(bp, ring, type, map_idx); if (rc) { enable_irq(vector); goto err_out; } bnxt_set_db(bp, &cpr->cp_db, type, map_idx, ring->fw_ring_id); bnxt_db_nq(bp, &cpr->cp_db, cpr->cp_raw_cons); enable_irq(vector); bp->grp_info[i].cp_fw_ring_id = ring->fw_ring_id; if (!i) { rc = bnxt_hwrm_set_async_event_cr(bp, ring->fw_ring_id); if (rc) netdev_warn(bp->dev, "Failed to set async event completion ring.\n"); } } type = HWRM_RING_ALLOC_TX; for (i = 0; i < bp->tx_nr_rings; i++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; struct bnxt_ring_struct *ring; u32 map_idx; if (bp->flags & BNXT_FLAG_CHIP_P5) { struct bnxt_napi *bnapi = txr->bnapi; struct bnxt_cp_ring_info *cpr, *cpr2; u32 type2 = HWRM_RING_ALLOC_CMPL; cpr = &bnapi->cp_ring; cpr2 = cpr->cp_ring_arr[BNXT_TX_HDL]; ring = &cpr2->cp_ring_struct; ring->handle = BNXT_TX_HDL; map_idx = bnapi->index; rc = hwrm_ring_alloc_send_msg(bp, ring, type2, map_idx); if (rc) goto err_out; bnxt_set_db(bp, &cpr2->cp_db, type2, map_idx, ring->fw_ring_id); bnxt_db_cq(bp, &cpr2->cp_db, cpr2->cp_raw_cons); } ring = &txr->tx_ring_struct; map_idx = i; rc = hwrm_ring_alloc_send_msg(bp, ring, type, map_idx); if (rc) goto err_out; bnxt_set_db(bp, &txr->tx_db, type, map_idx, ring->fw_ring_id); } type = HWRM_RING_ALLOC_RX; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_ring_struct *ring = &rxr->rx_ring_struct; struct bnxt_napi *bnapi = rxr->bnapi; u32 map_idx = bnapi->index; rc = hwrm_ring_alloc_send_msg(bp, ring, type, map_idx); if (rc) goto err_out; bnxt_set_db(bp, &rxr->rx_db, type, map_idx, ring->fw_ring_id); /* If we have agg rings, post agg buffers first. */ if (!agg_rings) bnxt_db_write(bp, &rxr->rx_db, rxr->rx_prod); bp->grp_info[map_idx].rx_fw_ring_id = ring->fw_ring_id; if (bp->flags & BNXT_FLAG_CHIP_P5) { struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; u32 type2 = HWRM_RING_ALLOC_CMPL; struct bnxt_cp_ring_info *cpr2; cpr2 = cpr->cp_ring_arr[BNXT_RX_HDL]; ring = &cpr2->cp_ring_struct; ring->handle = BNXT_RX_HDL; rc = hwrm_ring_alloc_send_msg(bp, ring, type2, map_idx); if (rc) goto err_out; bnxt_set_db(bp, &cpr2->cp_db, type2, map_idx, ring->fw_ring_id); bnxt_db_cq(bp, &cpr2->cp_db, cpr2->cp_raw_cons); } } if (agg_rings) { type = HWRM_RING_ALLOC_AGG; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_ring_struct *ring = &rxr->rx_agg_ring_struct; u32 grp_idx = ring->grp_idx; u32 map_idx = grp_idx + bp->rx_nr_rings; rc = hwrm_ring_alloc_send_msg(bp, ring, type, map_idx); if (rc) goto err_out; bnxt_set_db(bp, &rxr->rx_agg_db, type, map_idx, ring->fw_ring_id); bnxt_db_write(bp, &rxr->rx_agg_db, rxr->rx_agg_prod); bnxt_db_write(bp, &rxr->rx_db, rxr->rx_prod); bp->grp_info[grp_idx].agg_fw_ring_id = ring->fw_ring_id; } } err_out: return rc; } static int hwrm_ring_free_send_msg(struct bnxt *bp, struct bnxt_ring_struct *ring, u32 ring_type, int cmpl_ring_id) { int rc; struct hwrm_ring_free_input req = {0}; struct hwrm_ring_free_output *resp = bp->hwrm_cmd_resp_addr; u16 error_code; if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_RING_FREE, cmpl_ring_id, -1); req.ring_type = ring_type; req.ring_id = cpu_to_le16(ring->fw_ring_id); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); error_code = le16_to_cpu(resp->error_code); mutex_unlock(&bp->hwrm_cmd_lock); if (rc || error_code) { netdev_err(bp->dev, "hwrm_ring_free type %d failed. rc:%x err:%x\n", ring_type, rc, error_code); return -EIO; } return 0; } static void bnxt_hwrm_ring_free(struct bnxt *bp, bool close_path) { u32 type; int i; if (!bp->bnapi) return; for (i = 0; i < bp->tx_nr_rings; i++) { struct bnxt_tx_ring_info *txr = &bp->tx_ring[i]; struct bnxt_ring_struct *ring = &txr->tx_ring_struct; if (ring->fw_ring_id != INVALID_HW_RING_ID) { u32 cmpl_ring_id = bnxt_cp_ring_for_tx(bp, txr); hwrm_ring_free_send_msg(bp, ring, RING_FREE_REQ_RING_TYPE_TX, close_path ? cmpl_ring_id : INVALID_HW_RING_ID); ring->fw_ring_id = INVALID_HW_RING_ID; } } for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_ring_struct *ring = &rxr->rx_ring_struct; u32 grp_idx = rxr->bnapi->index; if (ring->fw_ring_id != INVALID_HW_RING_ID) { u32 cmpl_ring_id = bnxt_cp_ring_for_rx(bp, rxr); hwrm_ring_free_send_msg(bp, ring, RING_FREE_REQ_RING_TYPE_RX, close_path ? cmpl_ring_id : INVALID_HW_RING_ID); ring->fw_ring_id = INVALID_HW_RING_ID; bp->grp_info[grp_idx].rx_fw_ring_id = INVALID_HW_RING_ID; } } if (bp->flags & BNXT_FLAG_CHIP_P5) type = RING_FREE_REQ_RING_TYPE_RX_AGG; else type = RING_FREE_REQ_RING_TYPE_RX; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_rx_ring_info *rxr = &bp->rx_ring[i]; struct bnxt_ring_struct *ring = &rxr->rx_agg_ring_struct; u32 grp_idx = rxr->bnapi->index; if (ring->fw_ring_id != INVALID_HW_RING_ID) { u32 cmpl_ring_id = bnxt_cp_ring_for_rx(bp, rxr); hwrm_ring_free_send_msg(bp, ring, type, close_path ? cmpl_ring_id : INVALID_HW_RING_ID); ring->fw_ring_id = INVALID_HW_RING_ID; bp->grp_info[grp_idx].agg_fw_ring_id = INVALID_HW_RING_ID; } } /* The completion rings are about to be freed. After that the * IRQ doorbell will not work anymore. So we need to disable * IRQ here. */ bnxt_disable_int_sync(bp); if (bp->flags & BNXT_FLAG_CHIP_P5) type = RING_FREE_REQ_RING_TYPE_NQ; else type = RING_FREE_REQ_RING_TYPE_L2_CMPL; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct bnxt_ring_struct *ring; int j; for (j = 0; j < 2; j++) { struct bnxt_cp_ring_info *cpr2 = cpr->cp_ring_arr[j]; if (cpr2) { ring = &cpr2->cp_ring_struct; if (ring->fw_ring_id == INVALID_HW_RING_ID) continue; hwrm_ring_free_send_msg(bp, ring, RING_FREE_REQ_RING_TYPE_L2_CMPL, INVALID_HW_RING_ID); ring->fw_ring_id = INVALID_HW_RING_ID; } } ring = &cpr->cp_ring_struct; if (ring->fw_ring_id != INVALID_HW_RING_ID) { hwrm_ring_free_send_msg(bp, ring, type, INVALID_HW_RING_ID); ring->fw_ring_id = INVALID_HW_RING_ID; bp->grp_info[i].cp_fw_ring_id = INVALID_HW_RING_ID; } } } static int bnxt_trim_rings(struct bnxt *bp, int *rx, int *tx, int max, bool shared); static int bnxt_hwrm_get_rings(struct bnxt *bp) { struct hwrm_func_qcfg_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_hw_resc *hw_resc = &bp->hw_resc; struct hwrm_func_qcfg_input req = {0}; int rc; if (bp->hwrm_spec_code < 0x10601) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_QCFG, -1, -1); req.fid = cpu_to_le16(0xffff); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) { mutex_unlock(&bp->hwrm_cmd_lock); return rc; } hw_resc->resv_tx_rings = le16_to_cpu(resp->alloc_tx_rings); if (BNXT_NEW_RM(bp)) { u16 cp, stats; hw_resc->resv_rx_rings = le16_to_cpu(resp->alloc_rx_rings); hw_resc->resv_hw_ring_grps = le32_to_cpu(resp->alloc_hw_ring_grps); hw_resc->resv_vnics = le16_to_cpu(resp->alloc_vnics); cp = le16_to_cpu(resp->alloc_cmpl_rings); stats = le16_to_cpu(resp->alloc_stat_ctx); hw_resc->resv_irqs = cp; if (bp->flags & BNXT_FLAG_CHIP_P5) { int rx = hw_resc->resv_rx_rings; int tx = hw_resc->resv_tx_rings; if (bp->flags & BNXT_FLAG_AGG_RINGS) rx >>= 1; if (cp < (rx + tx)) { bnxt_trim_rings(bp, &rx, &tx, cp, false); if (bp->flags & BNXT_FLAG_AGG_RINGS) rx <<= 1; hw_resc->resv_rx_rings = rx; hw_resc->resv_tx_rings = tx; } hw_resc->resv_irqs = le16_to_cpu(resp->alloc_msix); hw_resc->resv_hw_ring_grps = rx; } hw_resc->resv_cp_rings = cp; hw_resc->resv_stat_ctxs = stats; } mutex_unlock(&bp->hwrm_cmd_lock); return 0; } /* Caller must hold bp->hwrm_cmd_lock */ int __bnxt_hwrm_get_tx_rings(struct bnxt *bp, u16 fid, int *tx_rings) { struct hwrm_func_qcfg_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_func_qcfg_input req = {0}; int rc; if (bp->hwrm_spec_code < 0x10601) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_QCFG, -1, -1); req.fid = cpu_to_le16(fid); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) *tx_rings = le16_to_cpu(resp->alloc_tx_rings); return rc; } static bool bnxt_rfs_supported(struct bnxt *bp); static void __bnxt_hwrm_reserve_pf_rings(struct bnxt *bp, struct hwrm_func_cfg_input *req, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { u32 enables = 0; bnxt_hwrm_cmd_hdr_init(bp, req, HWRM_FUNC_CFG, -1, -1); req->fid = cpu_to_le16(0xffff); enables |= tx_rings ? FUNC_CFG_REQ_ENABLES_NUM_TX_RINGS : 0; req->num_tx_rings = cpu_to_le16(tx_rings); if (BNXT_NEW_RM(bp)) { enables |= rx_rings ? FUNC_CFG_REQ_ENABLES_NUM_RX_RINGS : 0; enables |= stats ? FUNC_CFG_REQ_ENABLES_NUM_STAT_CTXS : 0; if (bp->flags & BNXT_FLAG_CHIP_P5) { enables |= cp_rings ? FUNC_CFG_REQ_ENABLES_NUM_MSIX : 0; enables |= tx_rings + ring_grps ? FUNC_CFG_REQ_ENABLES_NUM_CMPL_RINGS : 0; enables |= rx_rings ? FUNC_CFG_REQ_ENABLES_NUM_RSSCOS_CTXS : 0; } else { enables |= cp_rings ? FUNC_CFG_REQ_ENABLES_NUM_CMPL_RINGS : 0; enables |= ring_grps ? FUNC_CFG_REQ_ENABLES_NUM_HW_RING_GRPS | FUNC_CFG_REQ_ENABLES_NUM_RSSCOS_CTXS : 0; } enables |= vnics ? FUNC_CFG_REQ_ENABLES_NUM_VNICS : 0; req->num_rx_rings = cpu_to_le16(rx_rings); if (bp->flags & BNXT_FLAG_CHIP_P5) { req->num_cmpl_rings = cpu_to_le16(tx_rings + ring_grps); req->num_msix = cpu_to_le16(cp_rings); req->num_rsscos_ctxs = cpu_to_le16(DIV_ROUND_UP(ring_grps, 64)); } else { req->num_cmpl_rings = cpu_to_le16(cp_rings); req->num_hw_ring_grps = cpu_to_le16(ring_grps); req->num_rsscos_ctxs = cpu_to_le16(1); if (!(bp->flags & BNXT_FLAG_NEW_RSS_CAP) && bnxt_rfs_supported(bp)) req->num_rsscos_ctxs = cpu_to_le16(ring_grps + 1); } req->num_stat_ctxs = cpu_to_le16(stats); req->num_vnics = cpu_to_le16(vnics); } req->enables = cpu_to_le32(enables); } static void __bnxt_hwrm_reserve_vf_rings(struct bnxt *bp, struct hwrm_func_vf_cfg_input *req, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { u32 enables = 0; bnxt_hwrm_cmd_hdr_init(bp, req, HWRM_FUNC_VF_CFG, -1, -1); enables |= tx_rings ? FUNC_VF_CFG_REQ_ENABLES_NUM_TX_RINGS : 0; enables |= rx_rings ? FUNC_VF_CFG_REQ_ENABLES_NUM_RX_RINGS | FUNC_VF_CFG_REQ_ENABLES_NUM_RSSCOS_CTXS : 0; enables |= stats ? FUNC_VF_CFG_REQ_ENABLES_NUM_STAT_CTXS : 0; if (bp->flags & BNXT_FLAG_CHIP_P5) { enables |= tx_rings + ring_grps ? FUNC_VF_CFG_REQ_ENABLES_NUM_CMPL_RINGS : 0; } else { enables |= cp_rings ? FUNC_VF_CFG_REQ_ENABLES_NUM_CMPL_RINGS : 0; enables |= ring_grps ? FUNC_VF_CFG_REQ_ENABLES_NUM_HW_RING_GRPS : 0; } enables |= vnics ? FUNC_VF_CFG_REQ_ENABLES_NUM_VNICS : 0; enables |= FUNC_VF_CFG_REQ_ENABLES_NUM_L2_CTXS; req->num_l2_ctxs = cpu_to_le16(BNXT_VF_MAX_L2_CTX); req->num_tx_rings = cpu_to_le16(tx_rings); req->num_rx_rings = cpu_to_le16(rx_rings); if (bp->flags & BNXT_FLAG_CHIP_P5) { req->num_cmpl_rings = cpu_to_le16(tx_rings + ring_grps); req->num_rsscos_ctxs = cpu_to_le16(DIV_ROUND_UP(ring_grps, 64)); } else { req->num_cmpl_rings = cpu_to_le16(cp_rings); req->num_hw_ring_grps = cpu_to_le16(ring_grps); req->num_rsscos_ctxs = cpu_to_le16(BNXT_VF_MAX_RSS_CTX); } req->num_stat_ctxs = cpu_to_le16(stats); req->num_vnics = cpu_to_le16(vnics); req->enables = cpu_to_le32(enables); } static int bnxt_hwrm_reserve_pf_rings(struct bnxt *bp, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { struct hwrm_func_cfg_input req = {0}; int rc; __bnxt_hwrm_reserve_pf_rings(bp, &req, tx_rings, rx_rings, ring_grps, cp_rings, stats, vnics); if (!req.enables) return 0; rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) return rc; if (bp->hwrm_spec_code < 0x10601) bp->hw_resc.resv_tx_rings = tx_rings; return bnxt_hwrm_get_rings(bp); } static int bnxt_hwrm_reserve_vf_rings(struct bnxt *bp, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { struct hwrm_func_vf_cfg_input req = {0}; int rc; if (!BNXT_NEW_RM(bp)) { bp->hw_resc.resv_tx_rings = tx_rings; return 0; } __bnxt_hwrm_reserve_vf_rings(bp, &req, tx_rings, rx_rings, ring_grps, cp_rings, stats, vnics); rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) return rc; return bnxt_hwrm_get_rings(bp); } static int bnxt_hwrm_reserve_rings(struct bnxt *bp, int tx, int rx, int grp, int cp, int stat, int vnic) { if (BNXT_PF(bp)) return bnxt_hwrm_reserve_pf_rings(bp, tx, rx, grp, cp, stat, vnic); else return bnxt_hwrm_reserve_vf_rings(bp, tx, rx, grp, cp, stat, vnic); } int bnxt_nq_rings_in_use(struct bnxt *bp) { int cp = bp->cp_nr_rings; int ulp_msix, ulp_base; ulp_msix = bnxt_get_ulp_msix_num(bp); if (ulp_msix) { ulp_base = bnxt_get_ulp_msix_base(bp); cp += ulp_msix; if ((ulp_base + ulp_msix) > cp) cp = ulp_base + ulp_msix; } return cp; } static int bnxt_cp_rings_in_use(struct bnxt *bp) { int cp; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) return bnxt_nq_rings_in_use(bp); cp = bp->tx_nr_rings + bp->rx_nr_rings; return cp; } static int bnxt_get_func_stat_ctxs(struct bnxt *bp) { int ulp_stat = bnxt_get_ulp_stat_ctxs(bp); int cp = bp->cp_nr_rings; if (!ulp_stat) return cp; if (bnxt_nq_rings_in_use(bp) > cp + bnxt_get_ulp_msix_num(bp)) return bnxt_get_ulp_msix_base(bp) + ulp_stat; return cp + ulp_stat; } static bool bnxt_need_reserve_rings(struct bnxt *bp) { struct bnxt_hw_resc *hw_resc = &bp->hw_resc; int cp = bnxt_cp_rings_in_use(bp); int nq = bnxt_nq_rings_in_use(bp); int rx = bp->rx_nr_rings, stat; int vnic = 1, grp = rx; if (bp->hwrm_spec_code < 0x10601) return false; if (hw_resc->resv_tx_rings != bp->tx_nr_rings) return true; if ((bp->flags & BNXT_FLAG_RFS) && !(bp->flags & BNXT_FLAG_CHIP_P5)) vnic = rx + 1; if (bp->flags & BNXT_FLAG_AGG_RINGS) rx <<= 1; stat = bnxt_get_func_stat_ctxs(bp); if (BNXT_NEW_RM(bp) && (hw_resc->resv_rx_rings != rx || hw_resc->resv_cp_rings != cp || hw_resc->resv_vnics != vnic || hw_resc->resv_stat_ctxs != stat || (hw_resc->resv_hw_ring_grps != grp && !(bp->flags & BNXT_FLAG_CHIP_P5)))) return true; if ((bp->flags & BNXT_FLAG_CHIP_P5) && BNXT_PF(bp) && hw_resc->resv_irqs != nq) return true; return false; } static int __bnxt_reserve_rings(struct bnxt *bp) { struct bnxt_hw_resc *hw_resc = &bp->hw_resc; int cp = bnxt_nq_rings_in_use(bp); int tx = bp->tx_nr_rings; int rx = bp->rx_nr_rings; int grp, rx_rings, rc; int vnic = 1, stat; bool sh = false; if (!bnxt_need_reserve_rings(bp)) return 0; if (bp->flags & BNXT_FLAG_SHARED_RINGS) sh = true; if ((bp->flags & BNXT_FLAG_RFS) && !(bp->flags & BNXT_FLAG_CHIP_P5)) vnic = rx + 1; if (bp->flags & BNXT_FLAG_AGG_RINGS) rx <<= 1; grp = bp->rx_nr_rings; stat = bnxt_get_func_stat_ctxs(bp); rc = bnxt_hwrm_reserve_rings(bp, tx, rx, grp, cp, stat, vnic); if (rc) return rc; tx = hw_resc->resv_tx_rings; if (BNXT_NEW_RM(bp)) { rx = hw_resc->resv_rx_rings; cp = hw_resc->resv_irqs; grp = hw_resc->resv_hw_ring_grps; vnic = hw_resc->resv_vnics; stat = hw_resc->resv_stat_ctxs; } rx_rings = rx; if (bp->flags & BNXT_FLAG_AGG_RINGS) { if (rx >= 2) { rx_rings = rx >> 1; } else { if (netif_running(bp->dev)) return -ENOMEM; bp->flags &= ~BNXT_FLAG_AGG_RINGS; bp->flags |= BNXT_FLAG_NO_AGG_RINGS; bp->dev->hw_features &= ~NETIF_F_LRO; bp->dev->features &= ~NETIF_F_LRO; bnxt_set_ring_params(bp); } } rx_rings = min_t(int, rx_rings, grp); cp = min_t(int, cp, bp->cp_nr_rings); if (stat > bnxt_get_ulp_stat_ctxs(bp)) stat -= bnxt_get_ulp_stat_ctxs(bp); cp = min_t(int, cp, stat); rc = bnxt_trim_rings(bp, &rx_rings, &tx, cp, sh); if (bp->flags & BNXT_FLAG_AGG_RINGS) rx = rx_rings << 1; cp = sh ? max_t(int, tx, rx_rings) : tx + rx_rings; bp->tx_nr_rings = tx; bp->rx_nr_rings = rx_rings; bp->cp_nr_rings = cp; if (!tx || !rx || !cp || !grp || !vnic || !stat) return -ENOMEM; return rc; } static int bnxt_hwrm_check_vf_rings(struct bnxt *bp, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { struct hwrm_func_vf_cfg_input req = {0}; u32 flags; if (!BNXT_NEW_RM(bp)) return 0; __bnxt_hwrm_reserve_vf_rings(bp, &req, tx_rings, rx_rings, ring_grps, cp_rings, stats, vnics); flags = FUNC_VF_CFG_REQ_FLAGS_TX_ASSETS_TEST | FUNC_VF_CFG_REQ_FLAGS_RX_ASSETS_TEST | FUNC_VF_CFG_REQ_FLAGS_CMPL_ASSETS_TEST | FUNC_VF_CFG_REQ_FLAGS_STAT_CTX_ASSETS_TEST | FUNC_VF_CFG_REQ_FLAGS_VNIC_ASSETS_TEST | FUNC_VF_CFG_REQ_FLAGS_RSSCOS_CTX_ASSETS_TEST; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) flags |= FUNC_VF_CFG_REQ_FLAGS_RING_GRP_ASSETS_TEST; req.flags = cpu_to_le32(flags); return hwrm_send_message_silent(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_check_pf_rings(struct bnxt *bp, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { struct hwrm_func_cfg_input req = {0}; u32 flags; __bnxt_hwrm_reserve_pf_rings(bp, &req, tx_rings, rx_rings, ring_grps, cp_rings, stats, vnics); flags = FUNC_CFG_REQ_FLAGS_TX_ASSETS_TEST; if (BNXT_NEW_RM(bp)) { flags |= FUNC_CFG_REQ_FLAGS_RX_ASSETS_TEST | FUNC_CFG_REQ_FLAGS_CMPL_ASSETS_TEST | FUNC_CFG_REQ_FLAGS_STAT_CTX_ASSETS_TEST | FUNC_CFG_REQ_FLAGS_VNIC_ASSETS_TEST; if (bp->flags & BNXT_FLAG_CHIP_P5) flags |= FUNC_CFG_REQ_FLAGS_RSSCOS_CTX_ASSETS_TEST | FUNC_CFG_REQ_FLAGS_NQ_ASSETS_TEST; else flags |= FUNC_CFG_REQ_FLAGS_RING_GRP_ASSETS_TEST; } req.flags = cpu_to_le32(flags); return hwrm_send_message_silent(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_check_rings(struct bnxt *bp, int tx_rings, int rx_rings, int ring_grps, int cp_rings, int stats, int vnics) { if (bp->hwrm_spec_code < 0x10801) return 0; if (BNXT_PF(bp)) return bnxt_hwrm_check_pf_rings(bp, tx_rings, rx_rings, ring_grps, cp_rings, stats, vnics); return bnxt_hwrm_check_vf_rings(bp, tx_rings, rx_rings, ring_grps, cp_rings, stats, vnics); } static void bnxt_hwrm_coal_params_qcaps(struct bnxt *bp) { struct hwrm_ring_aggint_qcaps_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_coal_cap *coal_cap = &bp->coal_cap; struct hwrm_ring_aggint_qcaps_input req = {0}; int rc; coal_cap->cmpl_params = BNXT_LEGACY_COAL_CMPL_PARAMS; coal_cap->num_cmpl_dma_aggr_max = 63; coal_cap->num_cmpl_dma_aggr_during_int_max = 63; coal_cap->cmpl_aggr_dma_tmr_max = 65535; coal_cap->cmpl_aggr_dma_tmr_during_int_max = 65535; coal_cap->int_lat_tmr_min_max = 65535; coal_cap->int_lat_tmr_max_max = 65535; coal_cap->num_cmpl_aggr_int_max = 65535; coal_cap->timer_units = 80; if (bp->hwrm_spec_code < 0x10902) return; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_RING_AGGINT_QCAPS, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message_silent(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { coal_cap->cmpl_params = le32_to_cpu(resp->cmpl_params); coal_cap->nq_params = le32_to_cpu(resp->nq_params); coal_cap->num_cmpl_dma_aggr_max = le16_to_cpu(resp->num_cmpl_dma_aggr_max); coal_cap->num_cmpl_dma_aggr_during_int_max = le16_to_cpu(resp->num_cmpl_dma_aggr_during_int_max); coal_cap->cmpl_aggr_dma_tmr_max = le16_to_cpu(resp->cmpl_aggr_dma_tmr_max); coal_cap->cmpl_aggr_dma_tmr_during_int_max = le16_to_cpu(resp->cmpl_aggr_dma_tmr_during_int_max); coal_cap->int_lat_tmr_min_max = le16_to_cpu(resp->int_lat_tmr_min_max); coal_cap->int_lat_tmr_max_max = le16_to_cpu(resp->int_lat_tmr_max_max); coal_cap->num_cmpl_aggr_int_max = le16_to_cpu(resp->num_cmpl_aggr_int_max); coal_cap->timer_units = le16_to_cpu(resp->timer_units); } mutex_unlock(&bp->hwrm_cmd_lock); } static u16 bnxt_usec_to_coal_tmr(struct bnxt *bp, u16 usec) { struct bnxt_coal_cap *coal_cap = &bp->coal_cap; return usec * 1000 / coal_cap->timer_units; } static void bnxt_hwrm_set_coal_params(struct bnxt *bp, struct bnxt_coal *hw_coal, struct hwrm_ring_cmpl_ring_cfg_aggint_params_input *req) { struct bnxt_coal_cap *coal_cap = &bp->coal_cap; u32 cmpl_params = coal_cap->cmpl_params; u16 val, tmr, max, flags = 0; max = hw_coal->bufs_per_record * 128; if (hw_coal->budget) max = hw_coal->bufs_per_record * hw_coal->budget; max = min_t(u16, max, coal_cap->num_cmpl_aggr_int_max); val = clamp_t(u16, hw_coal->coal_bufs, 1, max); req->num_cmpl_aggr_int = cpu_to_le16(val); val = min_t(u16, val, coal_cap->num_cmpl_dma_aggr_max); req->num_cmpl_dma_aggr = cpu_to_le16(val); val = clamp_t(u16, hw_coal->coal_bufs_irq, 1, coal_cap->num_cmpl_dma_aggr_during_int_max); req->num_cmpl_dma_aggr_during_int = cpu_to_le16(val); tmr = bnxt_usec_to_coal_tmr(bp, hw_coal->coal_ticks); tmr = clamp_t(u16, tmr, 1, coal_cap->int_lat_tmr_max_max); req->int_lat_tmr_max = cpu_to_le16(tmr); /* min timer set to 1/2 of interrupt timer */ if (cmpl_params & RING_AGGINT_QCAPS_RESP_CMPL_PARAMS_INT_LAT_TMR_MIN) { val = tmr / 2; val = clamp_t(u16, val, 1, coal_cap->int_lat_tmr_min_max); req->int_lat_tmr_min = cpu_to_le16(val); req->enables |= cpu_to_le16(BNXT_COAL_CMPL_MIN_TMR_ENABLE); } /* buf timer set to 1/4 of interrupt timer */ val = clamp_t(u16, tmr / 4, 1, coal_cap->cmpl_aggr_dma_tmr_max); req->cmpl_aggr_dma_tmr = cpu_to_le16(val); if (cmpl_params & RING_AGGINT_QCAPS_RESP_CMPL_PARAMS_NUM_CMPL_DMA_AGGR_DURING_INT) { tmr = bnxt_usec_to_coal_tmr(bp, hw_coal->coal_ticks_irq); val = clamp_t(u16, tmr, 1, coal_cap->cmpl_aggr_dma_tmr_during_int_max); req->cmpl_aggr_dma_tmr_during_int = cpu_to_le16(val); req->enables |= cpu_to_le16(BNXT_COAL_CMPL_AGGR_TMR_DURING_INT_ENABLE); } if (cmpl_params & RING_AGGINT_QCAPS_RESP_CMPL_PARAMS_TIMER_RESET) flags |= RING_CMPL_RING_CFG_AGGINT_PARAMS_REQ_FLAGS_TIMER_RESET; if ((cmpl_params & RING_AGGINT_QCAPS_RESP_CMPL_PARAMS_RING_IDLE) && hw_coal->idle_thresh && hw_coal->coal_ticks < hw_coal->idle_thresh) flags |= RING_CMPL_RING_CFG_AGGINT_PARAMS_REQ_FLAGS_RING_IDLE; req->flags = cpu_to_le16(flags); req->enables |= cpu_to_le16(BNXT_COAL_CMPL_ENABLES); } /* Caller holds bp->hwrm_cmd_lock */ static int __bnxt_hwrm_set_coal_nq(struct bnxt *bp, struct bnxt_napi *bnapi, struct bnxt_coal *hw_coal) { struct hwrm_ring_cmpl_ring_cfg_aggint_params_input req = {0}; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct bnxt_coal_cap *coal_cap = &bp->coal_cap; u32 nq_params = coal_cap->nq_params; u16 tmr; if (!(nq_params & RING_AGGINT_QCAPS_RESP_NQ_PARAMS_INT_LAT_TMR_MIN)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS, -1, -1); req.ring_id = cpu_to_le16(cpr->cp_ring_struct.fw_ring_id); req.flags = cpu_to_le16(RING_CMPL_RING_CFG_AGGINT_PARAMS_REQ_FLAGS_IS_NQ); tmr = bnxt_usec_to_coal_tmr(bp, hw_coal->coal_ticks) / 2; tmr = clamp_t(u16, tmr, 1, coal_cap->int_lat_tmr_min_max); req.int_lat_tmr_min = cpu_to_le16(tmr); req.enables |= cpu_to_le16(BNXT_COAL_CMPL_MIN_TMR_ENABLE); return _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } int bnxt_hwrm_set_ring_coal(struct bnxt *bp, struct bnxt_napi *bnapi) { struct hwrm_ring_cmpl_ring_cfg_aggint_params_input req_rx = {0}; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct bnxt_coal coal; /* Tick values in micro seconds. * 1 coal_buf x bufs_per_record = 1 completion record. */ memcpy(&coal, &bp->rx_coal, sizeof(struct bnxt_coal)); coal.coal_ticks = cpr->rx_ring_coal.coal_ticks; coal.coal_bufs = cpr->rx_ring_coal.coal_bufs; if (!bnapi->rx_ring) return -ENODEV; bnxt_hwrm_cmd_hdr_init(bp, &req_rx, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS, -1, -1); bnxt_hwrm_set_coal_params(bp, &coal, &req_rx); req_rx.ring_id = cpu_to_le16(bnxt_cp_ring_for_rx(bp, bnapi->rx_ring)); return hwrm_send_message(bp, &req_rx, sizeof(req_rx), HWRM_CMD_TIMEOUT); } int bnxt_hwrm_set_coal(struct bnxt *bp) { int i, rc = 0; struct hwrm_ring_cmpl_ring_cfg_aggint_params_input req_rx = {0}, req_tx = {0}, *req; bnxt_hwrm_cmd_hdr_init(bp, &req_rx, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS, -1, -1); bnxt_hwrm_cmd_hdr_init(bp, &req_tx, HWRM_RING_CMPL_RING_CFG_AGGINT_PARAMS, -1, -1); bnxt_hwrm_set_coal_params(bp, &bp->rx_coal, &req_rx); bnxt_hwrm_set_coal_params(bp, &bp->tx_coal, &req_tx); mutex_lock(&bp->hwrm_cmd_lock); for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_coal *hw_coal; u16 ring_id; req = &req_rx; if (!bnapi->rx_ring) { ring_id = bnxt_cp_ring_for_tx(bp, bnapi->tx_ring); req = &req_tx; } else { ring_id = bnxt_cp_ring_for_rx(bp, bnapi->rx_ring); } req->ring_id = cpu_to_le16(ring_id); rc = _hwrm_send_message(bp, req, sizeof(*req), HWRM_CMD_TIMEOUT); if (rc) break; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) continue; if (bnapi->rx_ring && bnapi->tx_ring) { req = &req_tx; ring_id = bnxt_cp_ring_for_tx(bp, bnapi->tx_ring); req->ring_id = cpu_to_le16(ring_id); rc = _hwrm_send_message(bp, req, sizeof(*req), HWRM_CMD_TIMEOUT); if (rc) break; } if (bnapi->rx_ring) hw_coal = &bp->rx_coal; else hw_coal = &bp->tx_coal; __bnxt_hwrm_set_coal_nq(bp, bnapi, hw_coal); } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static void bnxt_hwrm_stat_ctx_free(struct bnxt *bp) { struct hwrm_stat_ctx_free_input req = {0}; int i; if (!bp->bnapi) return; if (BNXT_CHIP_TYPE_NITRO_A0(bp)) return; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_STAT_CTX_FREE, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; if (cpr->hw_stats_ctx_id != INVALID_STATS_CTX_ID) { req.stat_ctx_id = cpu_to_le32(cpr->hw_stats_ctx_id); _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); cpr->hw_stats_ctx_id = INVALID_STATS_CTX_ID; } } mutex_unlock(&bp->hwrm_cmd_lock); } static int bnxt_hwrm_stat_ctx_alloc(struct bnxt *bp) { int rc = 0, i; struct hwrm_stat_ctx_alloc_input req = {0}; struct hwrm_stat_ctx_alloc_output *resp = bp->hwrm_cmd_resp_addr; if (BNXT_CHIP_TYPE_NITRO_A0(bp)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_STAT_CTX_ALLOC, -1, -1); req.stats_dma_length = cpu_to_le16(bp->hw_ring_stats_size); req.update_period_ms = cpu_to_le32(bp->stats_coal_ticks / 1000); mutex_lock(&bp->hwrm_cmd_lock); for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; req.stats_dma_addr = cpu_to_le64(cpr->hw_stats_map); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) break; cpr->hw_stats_ctx_id = le32_to_cpu(resp->stat_ctx_id); bp->grp_info[i].fw_stats_ctx = cpr->hw_stats_ctx_id; } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_func_qcfg(struct bnxt *bp) { struct hwrm_func_qcfg_input req = {0}; struct hwrm_func_qcfg_output *resp = bp->hwrm_cmd_resp_addr; u32 min_db_offset = 0; u16 flags; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_QCFG, -1, -1); req.fid = cpu_to_le16(0xffff); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto func_qcfg_exit; #ifdef CONFIG_BNXT_SRIOV if (BNXT_VF(bp)) { struct bnxt_vf_info *vf = &bp->vf; vf->vlan = le16_to_cpu(resp->vlan) & VLAN_VID_MASK; } else { bp->pf.registered_vfs = le16_to_cpu(resp->registered_vfs); } #endif flags = le16_to_cpu(resp->flags); if (flags & (FUNC_QCFG_RESP_FLAGS_FW_DCBX_AGENT_ENABLED | FUNC_QCFG_RESP_FLAGS_FW_LLDP_AGENT_ENABLED)) { bp->fw_cap |= BNXT_FW_CAP_LLDP_AGENT; if (flags & FUNC_QCFG_RESP_FLAGS_FW_DCBX_AGENT_ENABLED) bp->fw_cap |= BNXT_FW_CAP_DCBX_AGENT; } if (BNXT_PF(bp) && (flags & FUNC_QCFG_RESP_FLAGS_MULTI_HOST)) bp->flags |= BNXT_FLAG_MULTI_HOST; switch (resp->port_partition_type) { case FUNC_QCFG_RESP_PORT_PARTITION_TYPE_NPAR1_0: case FUNC_QCFG_RESP_PORT_PARTITION_TYPE_NPAR1_5: case FUNC_QCFG_RESP_PORT_PARTITION_TYPE_NPAR2_0: bp->port_partition_type = resp->port_partition_type; break; } if (bp->hwrm_spec_code < 0x10707 || resp->evb_mode == FUNC_QCFG_RESP_EVB_MODE_VEB) bp->br_mode = BRIDGE_MODE_VEB; else if (resp->evb_mode == FUNC_QCFG_RESP_EVB_MODE_VEPA) bp->br_mode = BRIDGE_MODE_VEPA; else bp->br_mode = BRIDGE_MODE_UNDEF; bp->max_mtu = le16_to_cpu(resp->max_mtu_configured); if (!bp->max_mtu) bp->max_mtu = BNXT_MAX_MTU; if (bp->db_size) goto func_qcfg_exit; if (bp->flags & BNXT_FLAG_CHIP_P5) { if (BNXT_PF(bp)) min_db_offset = DB_PF_OFFSET_P5; else min_db_offset = DB_VF_OFFSET_P5; } bp->db_size = PAGE_ALIGN(le16_to_cpu(resp->l2_doorbell_bar_size_kb) * 1024); if (!bp->db_size || bp->db_size > pci_resource_len(bp->pdev, 2) || bp->db_size <= min_db_offset) bp->db_size = pci_resource_len(bp->pdev, 2); func_qcfg_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_func_backing_store_qcaps(struct bnxt *bp) { struct hwrm_func_backing_store_qcaps_input req = {0}; struct hwrm_func_backing_store_qcaps_output *resp = bp->hwrm_cmd_resp_addr; int rc; if (bp->hwrm_spec_code < 0x10902 || BNXT_VF(bp) || bp->ctx) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_BACKING_STORE_QCAPS, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message_silent(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { struct bnxt_ctx_pg_info *ctx_pg; struct bnxt_ctx_mem_info *ctx; int i, tqm_rings; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) { rc = -ENOMEM; goto ctx_err; } ctx->qp_max_entries = le32_to_cpu(resp->qp_max_entries); ctx->qp_min_qp1_entries = le16_to_cpu(resp->qp_min_qp1_entries); ctx->qp_max_l2_entries = le16_to_cpu(resp->qp_max_l2_entries); ctx->qp_entry_size = le16_to_cpu(resp->qp_entry_size); ctx->srq_max_l2_entries = le16_to_cpu(resp->srq_max_l2_entries); ctx->srq_max_entries = le32_to_cpu(resp->srq_max_entries); ctx->srq_entry_size = le16_to_cpu(resp->srq_entry_size); ctx->cq_max_l2_entries = le16_to_cpu(resp->cq_max_l2_entries); ctx->cq_max_entries = le32_to_cpu(resp->cq_max_entries); ctx->cq_entry_size = le16_to_cpu(resp->cq_entry_size); ctx->vnic_max_vnic_entries = le16_to_cpu(resp->vnic_max_vnic_entries); ctx->vnic_max_ring_table_entries = le16_to_cpu(resp->vnic_max_ring_table_entries); ctx->vnic_entry_size = le16_to_cpu(resp->vnic_entry_size); ctx->stat_max_entries = le32_to_cpu(resp->stat_max_entries); ctx->stat_entry_size = le16_to_cpu(resp->stat_entry_size); ctx->tqm_entry_size = le16_to_cpu(resp->tqm_entry_size); ctx->tqm_min_entries_per_ring = le32_to_cpu(resp->tqm_min_entries_per_ring); ctx->tqm_max_entries_per_ring = le32_to_cpu(resp->tqm_max_entries_per_ring); ctx->tqm_entries_multiple = resp->tqm_entries_multiple; if (!ctx->tqm_entries_multiple) ctx->tqm_entries_multiple = 1; ctx->mrav_max_entries = le32_to_cpu(resp->mrav_max_entries); ctx->mrav_entry_size = le16_to_cpu(resp->mrav_entry_size); ctx->mrav_num_entries_units = le16_to_cpu(resp->mrav_num_entries_units); ctx->tim_entry_size = le16_to_cpu(resp->tim_entry_size); ctx->tim_max_entries = le32_to_cpu(resp->tim_max_entries); ctx->ctx_kind_initializer = resp->ctx_kind_initializer; ctx->tqm_fp_rings_count = resp->tqm_fp_rings_count; if (!ctx->tqm_fp_rings_count) ctx->tqm_fp_rings_count = bp->max_q; tqm_rings = ctx->tqm_fp_rings_count + 1; ctx_pg = kcalloc(tqm_rings, sizeof(*ctx_pg), GFP_KERNEL); if (!ctx_pg) { kfree(ctx); rc = -ENOMEM; goto ctx_err; } for (i = 0; i < tqm_rings; i++, ctx_pg++) ctx->tqm_mem[i] = ctx_pg; bp->ctx = ctx; } else { rc = 0; } ctx_err: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static void bnxt_hwrm_set_pg_attr(struct bnxt_ring_mem_info *rmem, u8 *pg_attr, __le64 *pg_dir) { u8 pg_size = 0; if (BNXT_PAGE_SHIFT == 13) pg_size = 1 << 4; else if (BNXT_PAGE_SIZE == 16) pg_size = 2 << 4; *pg_attr = pg_size; if (rmem->depth >= 1) { if (rmem->depth == 2) *pg_attr |= 2; else *pg_attr |= 1; *pg_dir = cpu_to_le64(rmem->pg_tbl_map); } else { *pg_dir = cpu_to_le64(rmem->dma_arr[0]); } } #define FUNC_BACKING_STORE_CFG_REQ_DFLT_ENABLES \ (FUNC_BACKING_STORE_CFG_REQ_ENABLES_QP | \ FUNC_BACKING_STORE_CFG_REQ_ENABLES_SRQ | \ FUNC_BACKING_STORE_CFG_REQ_ENABLES_CQ | \ FUNC_BACKING_STORE_CFG_REQ_ENABLES_VNIC | \ FUNC_BACKING_STORE_CFG_REQ_ENABLES_STAT) static int bnxt_hwrm_func_backing_store_cfg(struct bnxt *bp, u32 enables) { struct hwrm_func_backing_store_cfg_input req = {0}; struct bnxt_ctx_mem_info *ctx = bp->ctx; struct bnxt_ctx_pg_info *ctx_pg; __le32 *num_entries; __le64 *pg_dir; u32 flags = 0; u8 *pg_attr; u32 ena; int i; if (!ctx) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_BACKING_STORE_CFG, -1, -1); req.enables = cpu_to_le32(enables); if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_QP) { ctx_pg = &ctx->qp_mem; req.qp_num_entries = cpu_to_le32(ctx_pg->entries); req.qp_num_qp1_entries = cpu_to_le16(ctx->qp_min_qp1_entries); req.qp_num_l2_entries = cpu_to_le16(ctx->qp_max_l2_entries); req.qp_entry_size = cpu_to_le16(ctx->qp_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.qpc_pg_size_qpc_lvl, &req.qpc_page_dir); } if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_SRQ) { ctx_pg = &ctx->srq_mem; req.srq_num_entries = cpu_to_le32(ctx_pg->entries); req.srq_num_l2_entries = cpu_to_le16(ctx->srq_max_l2_entries); req.srq_entry_size = cpu_to_le16(ctx->srq_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.srq_pg_size_srq_lvl, &req.srq_page_dir); } if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_CQ) { ctx_pg = &ctx->cq_mem; req.cq_num_entries = cpu_to_le32(ctx_pg->entries); req.cq_num_l2_entries = cpu_to_le16(ctx->cq_max_l2_entries); req.cq_entry_size = cpu_to_le16(ctx->cq_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.cq_pg_size_cq_lvl, &req.cq_page_dir); } if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_VNIC) { ctx_pg = &ctx->vnic_mem; req.vnic_num_vnic_entries = cpu_to_le16(ctx->vnic_max_vnic_entries); req.vnic_num_ring_table_entries = cpu_to_le16(ctx->vnic_max_ring_table_entries); req.vnic_entry_size = cpu_to_le16(ctx->vnic_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.vnic_pg_size_vnic_lvl, &req.vnic_page_dir); } if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_STAT) { ctx_pg = &ctx->stat_mem; req.stat_num_entries = cpu_to_le32(ctx->stat_max_entries); req.stat_entry_size = cpu_to_le16(ctx->stat_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.stat_pg_size_stat_lvl, &req.stat_page_dir); } if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_MRAV) { ctx_pg = &ctx->mrav_mem; req.mrav_num_entries = cpu_to_le32(ctx_pg->entries); if (ctx->mrav_num_entries_units) flags |= FUNC_BACKING_STORE_CFG_REQ_FLAGS_MRAV_RESERVATION_SPLIT; req.mrav_entry_size = cpu_to_le16(ctx->mrav_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.mrav_pg_size_mrav_lvl, &req.mrav_page_dir); } if (enables & FUNC_BACKING_STORE_CFG_REQ_ENABLES_TIM) { ctx_pg = &ctx->tim_mem; req.tim_num_entries = cpu_to_le32(ctx_pg->entries); req.tim_entry_size = cpu_to_le16(ctx->tim_entry_size); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, &req.tim_pg_size_tim_lvl, &req.tim_page_dir); } for (i = 0, num_entries = &req.tqm_sp_num_entries, pg_attr = &req.tqm_sp_pg_size_tqm_sp_lvl, pg_dir = &req.tqm_sp_page_dir, ena = FUNC_BACKING_STORE_CFG_REQ_ENABLES_TQM_SP; i < 9; i++, num_entries++, pg_attr++, pg_dir++, ena <<= 1) { if (!(enables & ena)) continue; req.tqm_entry_size = cpu_to_le16(ctx->tqm_entry_size); ctx_pg = ctx->tqm_mem[i]; *num_entries = cpu_to_le32(ctx_pg->entries); bnxt_hwrm_set_pg_attr(&ctx_pg->ring_mem, pg_attr, pg_dir); } req.flags = cpu_to_le32(flags); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_alloc_ctx_mem_blk(struct bnxt *bp, struct bnxt_ctx_pg_info *ctx_pg) { struct bnxt_ring_mem_info *rmem = &ctx_pg->ring_mem; rmem->page_size = BNXT_PAGE_SIZE; rmem->pg_arr = ctx_pg->ctx_pg_arr; rmem->dma_arr = ctx_pg->ctx_dma_arr; rmem->flags = BNXT_RMEM_VALID_PTE_FLAG; if (rmem->depth >= 1) rmem->flags |= BNXT_RMEM_USE_FULL_PAGE_FLAG; return bnxt_alloc_ring(bp, rmem); } static int bnxt_alloc_ctx_pg_tbls(struct bnxt *bp, struct bnxt_ctx_pg_info *ctx_pg, u32 mem_size, u8 depth, bool use_init_val) { struct bnxt_ring_mem_info *rmem = &ctx_pg->ring_mem; int rc; if (!mem_size) return -EINVAL; ctx_pg->nr_pages = DIV_ROUND_UP(mem_size, BNXT_PAGE_SIZE); if (ctx_pg->nr_pages > MAX_CTX_TOTAL_PAGES) { ctx_pg->nr_pages = 0; return -EINVAL; } if (ctx_pg->nr_pages > MAX_CTX_PAGES || depth > 1) { int nr_tbls, i; rmem->depth = 2; ctx_pg->ctx_pg_tbl = kcalloc(MAX_CTX_PAGES, sizeof(ctx_pg), GFP_KERNEL); if (!ctx_pg->ctx_pg_tbl) return -ENOMEM; nr_tbls = DIV_ROUND_UP(ctx_pg->nr_pages, MAX_CTX_PAGES); rmem->nr_pages = nr_tbls; rc = bnxt_alloc_ctx_mem_blk(bp, ctx_pg); if (rc) return rc; for (i = 0; i < nr_tbls; i++) { struct bnxt_ctx_pg_info *pg_tbl; pg_tbl = kzalloc(sizeof(*pg_tbl), GFP_KERNEL); if (!pg_tbl) return -ENOMEM; ctx_pg->ctx_pg_tbl[i] = pg_tbl; rmem = &pg_tbl->ring_mem; rmem->pg_tbl = ctx_pg->ctx_pg_arr[i]; rmem->pg_tbl_map = ctx_pg->ctx_dma_arr[i]; rmem->depth = 1; rmem->nr_pages = MAX_CTX_PAGES; if (use_init_val) rmem->init_val = bp->ctx->ctx_kind_initializer; if (i == (nr_tbls - 1)) { int rem = ctx_pg->nr_pages % MAX_CTX_PAGES; if (rem) rmem->nr_pages = rem; } rc = bnxt_alloc_ctx_mem_blk(bp, pg_tbl); if (rc) break; } } else { rmem->nr_pages = DIV_ROUND_UP(mem_size, BNXT_PAGE_SIZE); if (rmem->nr_pages > 1 || depth) rmem->depth = 1; if (use_init_val) rmem->init_val = bp->ctx->ctx_kind_initializer; rc = bnxt_alloc_ctx_mem_blk(bp, ctx_pg); } return rc; } static void bnxt_free_ctx_pg_tbls(struct bnxt *bp, struct bnxt_ctx_pg_info *ctx_pg) { struct bnxt_ring_mem_info *rmem = &ctx_pg->ring_mem; if (rmem->depth > 1 || ctx_pg->nr_pages > MAX_CTX_PAGES || ctx_pg->ctx_pg_tbl) { int i, nr_tbls = rmem->nr_pages; for (i = 0; i < nr_tbls; i++) { struct bnxt_ctx_pg_info *pg_tbl; struct bnxt_ring_mem_info *rmem2; pg_tbl = ctx_pg->ctx_pg_tbl[i]; if (!pg_tbl) continue; rmem2 = &pg_tbl->ring_mem; bnxt_free_ring(bp, rmem2); ctx_pg->ctx_pg_arr[i] = NULL; kfree(pg_tbl); ctx_pg->ctx_pg_tbl[i] = NULL; } kfree(ctx_pg->ctx_pg_tbl); ctx_pg->ctx_pg_tbl = NULL; } bnxt_free_ring(bp, rmem); ctx_pg->nr_pages = 0; } static void bnxt_free_ctx_mem(struct bnxt *bp) { struct bnxt_ctx_mem_info *ctx = bp->ctx; int i; if (!ctx) return; if (ctx->tqm_mem[0]) { for (i = 0; i < ctx->tqm_fp_rings_count + 1; i++) bnxt_free_ctx_pg_tbls(bp, ctx->tqm_mem[i]); kfree(ctx->tqm_mem[0]); ctx->tqm_mem[0] = NULL; } bnxt_free_ctx_pg_tbls(bp, &ctx->tim_mem); bnxt_free_ctx_pg_tbls(bp, &ctx->mrav_mem); bnxt_free_ctx_pg_tbls(bp, &ctx->stat_mem); bnxt_free_ctx_pg_tbls(bp, &ctx->vnic_mem); bnxt_free_ctx_pg_tbls(bp, &ctx->cq_mem); bnxt_free_ctx_pg_tbls(bp, &ctx->srq_mem); bnxt_free_ctx_pg_tbls(bp, &ctx->qp_mem); ctx->flags &= ~BNXT_CTX_FLAG_INITED; } static int bnxt_alloc_ctx_mem(struct bnxt *bp) { struct bnxt_ctx_pg_info *ctx_pg; struct bnxt_ctx_mem_info *ctx; u32 mem_size, ena, entries; u32 entries_sp, min; u32 num_mr, num_ah; u32 extra_srqs = 0; u32 extra_qps = 0; u8 pg_lvl = 1; int i, rc; rc = bnxt_hwrm_func_backing_store_qcaps(bp); if (rc) { netdev_err(bp->dev, "Failed querying context mem capability, rc = %d.\n", rc); return rc; } ctx = bp->ctx; if (!ctx || (ctx->flags & BNXT_CTX_FLAG_INITED)) return 0; if ((bp->flags & BNXT_FLAG_ROCE_CAP) && !is_kdump_kernel()) { pg_lvl = 2; extra_qps = 65536; extra_srqs = 8192; } ctx_pg = &ctx->qp_mem; ctx_pg->entries = ctx->qp_min_qp1_entries + ctx->qp_max_l2_entries + extra_qps; mem_size = ctx->qp_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, pg_lvl, true); if (rc) return rc; ctx_pg = &ctx->srq_mem; ctx_pg->entries = ctx->srq_max_l2_entries + extra_srqs; mem_size = ctx->srq_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, pg_lvl, true); if (rc) return rc; ctx_pg = &ctx->cq_mem; ctx_pg->entries = ctx->cq_max_l2_entries + extra_qps * 2; mem_size = ctx->cq_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, pg_lvl, true); if (rc) return rc; ctx_pg = &ctx->vnic_mem; ctx_pg->entries = ctx->vnic_max_vnic_entries + ctx->vnic_max_ring_table_entries; mem_size = ctx->vnic_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, 1, true); if (rc) return rc; ctx_pg = &ctx->stat_mem; ctx_pg->entries = ctx->stat_max_entries; mem_size = ctx->stat_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, 1, true); if (rc) return rc; ena = 0; if (!(bp->flags & BNXT_FLAG_ROCE_CAP)) goto skip_rdma; ctx_pg = &ctx->mrav_mem; /* 128K extra is needed to accommodate static AH context * allocation by f/w. */ num_mr = 1024 * 256; num_ah = 1024 * 128; ctx_pg->entries = num_mr + num_ah; mem_size = ctx->mrav_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, 2, true); if (rc) return rc; ena = FUNC_BACKING_STORE_CFG_REQ_ENABLES_MRAV; if (ctx->mrav_num_entries_units) ctx_pg->entries = ((num_mr / ctx->mrav_num_entries_units) << 16) | (num_ah / ctx->mrav_num_entries_units); ctx_pg = &ctx->tim_mem; ctx_pg->entries = ctx->qp_mem.entries; mem_size = ctx->tim_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, 1, false); if (rc) return rc; ena |= FUNC_BACKING_STORE_CFG_REQ_ENABLES_TIM; skip_rdma: min = ctx->tqm_min_entries_per_ring; entries_sp = ctx->vnic_max_vnic_entries + ctx->qp_max_l2_entries + 2 * (extra_qps + ctx->qp_min_qp1_entries) + min; entries_sp = roundup(entries_sp, ctx->tqm_entries_multiple); entries = ctx->qp_max_l2_entries + extra_qps + ctx->qp_min_qp1_entries; entries = roundup(entries, ctx->tqm_entries_multiple); entries = clamp_t(u32, entries, min, ctx->tqm_max_entries_per_ring); for (i = 0; i < ctx->tqm_fp_rings_count + 1; i++) { ctx_pg = ctx->tqm_mem[i]; ctx_pg->entries = i ? entries : entries_sp; mem_size = ctx->tqm_entry_size * ctx_pg->entries; rc = bnxt_alloc_ctx_pg_tbls(bp, ctx_pg, mem_size, 1, false); if (rc) return rc; ena |= FUNC_BACKING_STORE_CFG_REQ_ENABLES_TQM_SP << i; } ena |= FUNC_BACKING_STORE_CFG_REQ_DFLT_ENABLES; rc = bnxt_hwrm_func_backing_store_cfg(bp, ena); if (rc) { netdev_err(bp->dev, "Failed configuring context mem, rc = %d.\n", rc); return rc; } ctx->flags |= BNXT_CTX_FLAG_INITED; return 0; } int bnxt_hwrm_func_resc_qcaps(struct bnxt *bp, bool all) { struct hwrm_func_resource_qcaps_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_func_resource_qcaps_input req = {0}; struct bnxt_hw_resc *hw_resc = &bp->hw_resc; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_RESOURCE_QCAPS, -1, -1); req.fid = cpu_to_le16(0xffff); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message_silent(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto hwrm_func_resc_qcaps_exit; hw_resc->max_tx_sch_inputs = le16_to_cpu(resp->max_tx_scheduler_inputs); if (!all) goto hwrm_func_resc_qcaps_exit; hw_resc->min_rsscos_ctxs = le16_to_cpu(resp->min_rsscos_ctx); hw_resc->max_rsscos_ctxs = le16_to_cpu(resp->max_rsscos_ctx); hw_resc->min_cp_rings = le16_to_cpu(resp->min_cmpl_rings); hw_resc->max_cp_rings = le16_to_cpu(resp->max_cmpl_rings); hw_resc->min_tx_rings = le16_to_cpu(resp->min_tx_rings); hw_resc->max_tx_rings = le16_to_cpu(resp->max_tx_rings); hw_resc->min_rx_rings = le16_to_cpu(resp->min_rx_rings); hw_resc->max_rx_rings = le16_to_cpu(resp->max_rx_rings); hw_resc->min_hw_ring_grps = le16_to_cpu(resp->min_hw_ring_grps); hw_resc->max_hw_ring_grps = le16_to_cpu(resp->max_hw_ring_grps); hw_resc->min_l2_ctxs = le16_to_cpu(resp->min_l2_ctxs); hw_resc->max_l2_ctxs = le16_to_cpu(resp->max_l2_ctxs); hw_resc->min_vnics = le16_to_cpu(resp->min_vnics); hw_resc->max_vnics = le16_to_cpu(resp->max_vnics); hw_resc->min_stat_ctxs = le16_to_cpu(resp->min_stat_ctx); hw_resc->max_stat_ctxs = le16_to_cpu(resp->max_stat_ctx); if (bp->flags & BNXT_FLAG_CHIP_P5) { u16 max_msix = le16_to_cpu(resp->max_msix); hw_resc->max_nqs = max_msix; hw_resc->max_hw_ring_grps = hw_resc->max_rx_rings; } if (BNXT_PF(bp)) { struct bnxt_pf_info *pf = &bp->pf; pf->vf_resv_strategy = le16_to_cpu(resp->vf_reservation_strategy); if (pf->vf_resv_strategy > BNXT_VF_RESV_STRATEGY_MINIMAL_STATIC) pf->vf_resv_strategy = BNXT_VF_RESV_STRATEGY_MAXIMAL; } hwrm_func_resc_qcaps_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int __bnxt_hwrm_func_qcaps(struct bnxt *bp) { int rc = 0; struct hwrm_func_qcaps_input req = {0}; struct hwrm_func_qcaps_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_hw_resc *hw_resc = &bp->hw_resc; u32 flags; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_QCAPS, -1, -1); req.fid = cpu_to_le16(0xffff); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto hwrm_func_qcaps_exit; flags = le32_to_cpu(resp->flags); if (flags & FUNC_QCAPS_RESP_FLAGS_ROCE_V1_SUPPORTED) bp->flags |= BNXT_FLAG_ROCEV1_CAP; if (flags & FUNC_QCAPS_RESP_FLAGS_ROCE_V2_SUPPORTED) bp->flags |= BNXT_FLAG_ROCEV2_CAP; if (flags & FUNC_QCAPS_RESP_FLAGS_PCIE_STATS_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_PCIE_STATS_SUPPORTED; if (flags & FUNC_QCAPS_RESP_FLAGS_HOT_RESET_CAPABLE) bp->fw_cap |= BNXT_FW_CAP_HOT_RESET; if (flags & FUNC_QCAPS_RESP_FLAGS_EXT_STATS_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_EXT_STATS_SUPPORTED; if (flags & FUNC_QCAPS_RESP_FLAGS_ERROR_RECOVERY_CAPABLE) bp->fw_cap |= BNXT_FW_CAP_ERROR_RECOVERY; if (flags & FUNC_QCAPS_RESP_FLAGS_ERR_RECOVER_RELOAD) bp->fw_cap |= BNXT_FW_CAP_ERR_RECOVER_RELOAD; bp->tx_push_thresh = 0; if (flags & FUNC_QCAPS_RESP_FLAGS_PUSH_MODE_SUPPORTED) bp->tx_push_thresh = BNXT_TX_PUSH_THRESH; hw_resc->max_rsscos_ctxs = le16_to_cpu(resp->max_rsscos_ctx); hw_resc->max_cp_rings = le16_to_cpu(resp->max_cmpl_rings); hw_resc->max_tx_rings = le16_to_cpu(resp->max_tx_rings); hw_resc->max_rx_rings = le16_to_cpu(resp->max_rx_rings); hw_resc->max_hw_ring_grps = le32_to_cpu(resp->max_hw_ring_grps); if (!hw_resc->max_hw_ring_grps) hw_resc->max_hw_ring_grps = hw_resc->max_tx_rings; hw_resc->max_l2_ctxs = le16_to_cpu(resp->max_l2_ctxs); hw_resc->max_vnics = le16_to_cpu(resp->max_vnics); hw_resc->max_stat_ctxs = le16_to_cpu(resp->max_stat_ctx); if (BNXT_PF(bp)) { struct bnxt_pf_info *pf = &bp->pf; pf->fw_fid = le16_to_cpu(resp->fid); pf->port_id = le16_to_cpu(resp->port_id); memcpy(pf->mac_addr, resp->mac_address, ETH_ALEN); pf->first_vf_id = le16_to_cpu(resp->first_vf_id); pf->max_vfs = le16_to_cpu(resp->max_vfs); pf->max_encap_records = le32_to_cpu(resp->max_encap_records); pf->max_decap_records = le32_to_cpu(resp->max_decap_records); pf->max_tx_em_flows = le32_to_cpu(resp->max_tx_em_flows); pf->max_tx_wm_flows = le32_to_cpu(resp->max_tx_wm_flows); pf->max_rx_em_flows = le32_to_cpu(resp->max_rx_em_flows); pf->max_rx_wm_flows = le32_to_cpu(resp->max_rx_wm_flows); bp->flags &= ~BNXT_FLAG_WOL_CAP; if (flags & FUNC_QCAPS_RESP_FLAGS_WOL_MAGICPKT_SUPPORTED) bp->flags |= BNXT_FLAG_WOL_CAP; } else { #ifdef CONFIG_BNXT_SRIOV struct bnxt_vf_info *vf = &bp->vf; vf->fw_fid = le16_to_cpu(resp->fid); memcpy(vf->mac_addr, resp->mac_address, ETH_ALEN); #endif } hwrm_func_qcaps_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_queue_qportcfg(struct bnxt *bp); static int bnxt_hwrm_func_qcaps(struct bnxt *bp) { int rc; rc = __bnxt_hwrm_func_qcaps(bp); if (rc) return rc; rc = bnxt_hwrm_queue_qportcfg(bp); if (rc) { netdev_err(bp->dev, "hwrm query qportcfg failure rc: %d\n", rc); return rc; } if (bp->hwrm_spec_code >= 0x10803) { rc = bnxt_alloc_ctx_mem(bp); if (rc) return rc; rc = bnxt_hwrm_func_resc_qcaps(bp, true); if (!rc) bp->fw_cap |= BNXT_FW_CAP_NEW_RM; } return 0; } static int bnxt_hwrm_cfa_adv_flow_mgnt_qcaps(struct bnxt *bp) { struct hwrm_cfa_adv_flow_mgnt_qcaps_input req = {0}; struct hwrm_cfa_adv_flow_mgnt_qcaps_output *resp; int rc = 0; u32 flags; if (!(bp->fw_cap & BNXT_FW_CAP_CFA_ADV_FLOW)) return 0; resp = bp->hwrm_cmd_resp_addr; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_ADV_FLOW_MGNT_QCAPS, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto hwrm_cfa_adv_qcaps_exit; flags = le32_to_cpu(resp->flags); if (flags & CFA_ADV_FLOW_MGNT_QCAPS_RESP_FLAGS_RFS_RING_TBL_IDX_V2_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_CFA_RFS_RING_TBL_IDX_V2; hwrm_cfa_adv_qcaps_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_map_fw_health_regs(struct bnxt *bp) { struct bnxt_fw_health *fw_health = bp->fw_health; u32 reg_base = 0xffffffff; int i; /* Only pre-map the monitoring GRC registers using window 3 */ for (i = 0; i < 4; i++) { u32 reg = fw_health->regs[i]; if (BNXT_FW_HEALTH_REG_TYPE(reg) != BNXT_FW_HEALTH_REG_TYPE_GRC) continue; if (reg_base == 0xffffffff) reg_base = reg & BNXT_GRC_BASE_MASK; if ((reg & BNXT_GRC_BASE_MASK) != reg_base) return -ERANGE; fw_health->mapped_regs[i] = BNXT_FW_HEALTH_WIN_BASE + (reg & BNXT_GRC_OFFSET_MASK); } if (reg_base == 0xffffffff) return 0; writel(reg_base, bp->bar0 + BNXT_GRCPF_REG_WINDOW_BASE_OUT + BNXT_FW_HEALTH_WIN_MAP_OFF); return 0; } static int bnxt_hwrm_error_recovery_qcfg(struct bnxt *bp) { struct hwrm_error_recovery_qcfg_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_fw_health *fw_health = bp->fw_health; struct hwrm_error_recovery_qcfg_input req = {0}; int rc, i; if (!(bp->fw_cap & BNXT_FW_CAP_ERROR_RECOVERY)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_ERROR_RECOVERY_QCFG, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto err_recovery_out; fw_health->flags = le32_to_cpu(resp->flags); if ((fw_health->flags & ERROR_RECOVERY_QCFG_RESP_FLAGS_CO_CPU) && !(bp->fw_cap & BNXT_FW_CAP_KONG_MB_CHNL)) { rc = -EINVAL; goto err_recovery_out; } fw_health->polling_dsecs = le32_to_cpu(resp->driver_polling_freq); fw_health->master_func_wait_dsecs = le32_to_cpu(resp->master_func_wait_period); fw_health->normal_func_wait_dsecs = le32_to_cpu(resp->normal_func_wait_period); fw_health->post_reset_wait_dsecs = le32_to_cpu(resp->master_func_wait_period_after_reset); fw_health->post_reset_max_wait_dsecs = le32_to_cpu(resp->max_bailout_time_after_reset); fw_health->regs[BNXT_FW_HEALTH_REG] = le32_to_cpu(resp->fw_health_status_reg); fw_health->regs[BNXT_FW_HEARTBEAT_REG] = le32_to_cpu(resp->fw_heartbeat_reg); fw_health->regs[BNXT_FW_RESET_CNT_REG] = le32_to_cpu(resp->fw_reset_cnt_reg); fw_health->regs[BNXT_FW_RESET_INPROG_REG] = le32_to_cpu(resp->reset_inprogress_reg); fw_health->fw_reset_inprog_reg_mask = le32_to_cpu(resp->reset_inprogress_reg_mask); fw_health->fw_reset_seq_cnt = resp->reg_array_cnt; if (fw_health->fw_reset_seq_cnt >= 16) { rc = -EINVAL; goto err_recovery_out; } for (i = 0; i < fw_health->fw_reset_seq_cnt; i++) { fw_health->fw_reset_seq_regs[i] = le32_to_cpu(resp->reset_reg[i]); fw_health->fw_reset_seq_vals[i] = le32_to_cpu(resp->reset_reg_val[i]); fw_health->fw_reset_seq_delay_msec[i] = resp->delay_after_reset[i]; } err_recovery_out: mutex_unlock(&bp->hwrm_cmd_lock); if (!rc) rc = bnxt_map_fw_health_regs(bp); if (rc) bp->fw_cap &= ~BNXT_FW_CAP_ERROR_RECOVERY; return rc; } static int bnxt_hwrm_func_reset(struct bnxt *bp) { struct hwrm_func_reset_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_RESET, -1, -1); req.enables = 0; return hwrm_send_message(bp, &req, sizeof(req), HWRM_RESET_TIMEOUT); } static int bnxt_hwrm_queue_qportcfg(struct bnxt *bp) { int rc = 0; struct hwrm_queue_qportcfg_input req = {0}; struct hwrm_queue_qportcfg_output *resp = bp->hwrm_cmd_resp_addr; u8 i, j, *qptr; bool no_rdma; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_QUEUE_QPORTCFG, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto qportcfg_exit; if (!resp->max_configurable_queues) { rc = -EINVAL; goto qportcfg_exit; } bp->max_tc = resp->max_configurable_queues; bp->max_lltc = resp->max_configurable_lossless_queues; if (bp->max_tc > BNXT_MAX_QUEUE) bp->max_tc = BNXT_MAX_QUEUE; no_rdma = !(bp->flags & BNXT_FLAG_ROCE_CAP); qptr = &resp->queue_id0; for (i = 0, j = 0; i < bp->max_tc; i++) { bp->q_info[j].queue_id = *qptr; bp->q_ids[i] = *qptr++; bp->q_info[j].queue_profile = *qptr++; bp->tc_to_qidx[j] = j; if (!BNXT_CNPQ(bp->q_info[j].queue_profile) || (no_rdma && BNXT_PF(bp))) j++; } bp->max_q = bp->max_tc; bp->max_tc = max_t(u8, j, 1); if (resp->queue_cfg_info & QUEUE_QPORTCFG_RESP_QUEUE_CFG_INFO_ASYM_CFG) bp->max_tc = 1; if (bp->max_lltc > bp->max_tc) bp->max_lltc = bp->max_tc; qportcfg_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int __bnxt_hwrm_ver_get(struct bnxt *bp, bool silent) { struct hwrm_ver_get_input req = {0}; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_VER_GET, -1, -1); req.hwrm_intf_maj = HWRM_VERSION_MAJOR; req.hwrm_intf_min = HWRM_VERSION_MINOR; req.hwrm_intf_upd = HWRM_VERSION_UPDATE; rc = bnxt_hwrm_do_send_msg(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT, silent); return rc; } static int bnxt_hwrm_ver_get(struct bnxt *bp) { struct hwrm_ver_get_output *resp = bp->hwrm_cmd_resp_addr; u32 dev_caps_cfg, hwrm_ver; int rc; bp->hwrm_max_req_len = HWRM_MAX_REQ_LEN; mutex_lock(&bp->hwrm_cmd_lock); rc = __bnxt_hwrm_ver_get(bp, false); if (rc) goto hwrm_ver_get_exit; memcpy(&bp->ver_resp, resp, sizeof(struct hwrm_ver_get_output)); bp->hwrm_spec_code = resp->hwrm_intf_maj_8b << 16 | resp->hwrm_intf_min_8b << 8 | resp->hwrm_intf_upd_8b; if (resp->hwrm_intf_maj_8b < 1) { netdev_warn(bp->dev, "HWRM interface %d.%d.%d is older than 1.0.0.\n", resp->hwrm_intf_maj_8b, resp->hwrm_intf_min_8b, resp->hwrm_intf_upd_8b); netdev_warn(bp->dev, "Please update firmware with HWRM interface 1.0.0 or newer.\n"); } hwrm_ver = HWRM_VERSION_MAJOR << 16 | HWRM_VERSION_MINOR << 8 | HWRM_VERSION_UPDATE; if (bp->hwrm_spec_code > hwrm_ver) snprintf(bp->hwrm_ver_supp, FW_VER_STR_LEN, "%d.%d.%d", HWRM_VERSION_MAJOR, HWRM_VERSION_MINOR, HWRM_VERSION_UPDATE); else snprintf(bp->hwrm_ver_supp, FW_VER_STR_LEN, "%d.%d.%d", resp->hwrm_intf_maj_8b, resp->hwrm_intf_min_8b, resp->hwrm_intf_upd_8b); snprintf(bp->fw_ver_str, BC_HWRM_STR_LEN, "%d.%d.%d.%d", resp->hwrm_fw_maj_8b, resp->hwrm_fw_min_8b, resp->hwrm_fw_bld_8b, resp->hwrm_fw_rsvd_8b); if (strlen(resp->active_pkg_name)) { int fw_ver_len = strlen(bp->fw_ver_str); snprintf(bp->fw_ver_str + fw_ver_len, FW_VER_STR_LEN - fw_ver_len - 1, "/pkg %s", resp->active_pkg_name); bp->fw_cap |= BNXT_FW_CAP_PKG_VER; } bp->hwrm_cmd_timeout = le16_to_cpu(resp->def_req_timeout); if (!bp->hwrm_cmd_timeout) bp->hwrm_cmd_timeout = DFLT_HWRM_CMD_TIMEOUT; if (resp->hwrm_intf_maj_8b >= 1) { bp->hwrm_max_req_len = le16_to_cpu(resp->max_req_win_len); bp->hwrm_max_ext_req_len = le16_to_cpu(resp->max_ext_req_len); } if (bp->hwrm_max_ext_req_len < HWRM_MAX_REQ_LEN) bp->hwrm_max_ext_req_len = HWRM_MAX_REQ_LEN; bp->chip_num = le16_to_cpu(resp->chip_num); bp->chip_rev = resp->chip_rev; if (bp->chip_num == CHIP_NUM_58700 && !resp->chip_rev && !resp->chip_metal) bp->flags |= BNXT_FLAG_CHIP_NITRO_A0; dev_caps_cfg = le32_to_cpu(resp->dev_caps_cfg); if ((dev_caps_cfg & VER_GET_RESP_DEV_CAPS_CFG_SHORT_CMD_SUPPORTED) && (dev_caps_cfg & VER_GET_RESP_DEV_CAPS_CFG_SHORT_CMD_REQUIRED)) bp->fw_cap |= BNXT_FW_CAP_SHORT_CMD; if (dev_caps_cfg & VER_GET_RESP_DEV_CAPS_CFG_KONG_MB_CHNL_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_KONG_MB_CHNL; if (dev_caps_cfg & VER_GET_RESP_DEV_CAPS_CFG_FLOW_HANDLE_64BIT_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_OVS_64BIT_HANDLE; if (dev_caps_cfg & VER_GET_RESP_DEV_CAPS_CFG_TRUSTED_VF_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_TRUSTED_VF; if (dev_caps_cfg & VER_GET_RESP_DEV_CAPS_CFG_CFA_ADV_FLOW_MGNT_SUPPORTED) bp->fw_cap |= BNXT_FW_CAP_CFA_ADV_FLOW; hwrm_ver_get_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } int bnxt_hwrm_fw_set_time(struct bnxt *bp) { struct hwrm_fw_set_time_input req = {0}; struct tm tm; time64_t now = ktime_get_real_seconds(); if ((BNXT_VF(bp) && bp->hwrm_spec_code < 0x10901) || bp->hwrm_spec_code < 0x10400) return -EOPNOTSUPP; time64_to_tm(now, 0, &tm); bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FW_SET_TIME, -1, -1); req.year = cpu_to_le16(1900 + tm.tm_year); req.month = 1 + tm.tm_mon; req.day = tm.tm_mday; req.hour = tm.tm_hour; req.minute = tm.tm_min; req.second = tm.tm_sec; return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_port_qstats(struct bnxt *bp) { struct bnxt_pf_info *pf = &bp->pf; struct hwrm_port_qstats_input req = {0}; if (!(bp->flags & BNXT_FLAG_PORT_STATS)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_QSTATS, -1, -1); req.port_id = cpu_to_le16(pf->port_id); req.tx_stat_host_addr = cpu_to_le64(bp->hw_tx_port_stats_map); req.rx_stat_host_addr = cpu_to_le64(bp->hw_rx_port_stats_map); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_port_qstats_ext(struct bnxt *bp) { struct hwrm_port_qstats_ext_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_queue_pri2cos_qcfg_input req2 = {0}; struct hwrm_port_qstats_ext_input req = {0}; struct bnxt_pf_info *pf = &bp->pf; u32 tx_stat_size; int rc; if (!(bp->flags & BNXT_FLAG_PORT_STATS_EXT)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_QSTATS_EXT, -1, -1); req.port_id = cpu_to_le16(pf->port_id); req.rx_stat_size = cpu_to_le16(sizeof(struct rx_port_stats_ext)); req.rx_stat_host_addr = cpu_to_le64(bp->hw_rx_port_stats_ext_map); tx_stat_size = bp->hw_tx_port_stats_ext ? sizeof(*bp->hw_tx_port_stats_ext) : 0; req.tx_stat_size = cpu_to_le16(tx_stat_size); req.tx_stat_host_addr = cpu_to_le64(bp->hw_tx_port_stats_ext_map); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { bp->fw_rx_stats_ext_size = le16_to_cpu(resp->rx_stat_size) / 8; bp->fw_tx_stats_ext_size = tx_stat_size ? le16_to_cpu(resp->tx_stat_size) / 8 : 0; } else { bp->fw_rx_stats_ext_size = 0; bp->fw_tx_stats_ext_size = 0; } if (bp->fw_tx_stats_ext_size <= offsetof(struct tx_port_stats_ext, pfc_pri0_tx_duration_us) / 8) { mutex_unlock(&bp->hwrm_cmd_lock); bp->pri2cos_valid = 0; return rc; } bnxt_hwrm_cmd_hdr_init(bp, &req2, HWRM_QUEUE_PRI2COS_QCFG, -1, -1); req2.flags = cpu_to_le32(QUEUE_PRI2COS_QCFG_REQ_FLAGS_IVLAN); rc = _hwrm_send_message(bp, &req2, sizeof(req2), HWRM_CMD_TIMEOUT); if (!rc) { struct hwrm_queue_pri2cos_qcfg_output *resp2; u8 *pri2cos; int i, j; resp2 = bp->hwrm_cmd_resp_addr; pri2cos = &resp2->pri0_cos_queue_id; for (i = 0; i < 8; i++) { u8 queue_id = pri2cos[i]; u8 queue_idx; /* Per port queue IDs start from 0, 10, 20, etc */ queue_idx = queue_id % 10; if (queue_idx > BNXT_MAX_QUEUE) { bp->pri2cos_valid = false; goto qstats_done; } for (j = 0; j < bp->max_q; j++) { if (bp->q_ids[j] == queue_id) bp->pri2cos_idx[i] = queue_idx; } } bp->pri2cos_valid = 1; } qstats_done: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_pcie_qstats(struct bnxt *bp) { struct hwrm_pcie_qstats_input req = {0}; if (!(bp->flags & BNXT_FLAG_PCIE_STATS)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PCIE_QSTATS, -1, -1); req.pcie_stat_size = cpu_to_le16(sizeof(struct pcie_ctx_hw_stats)); req.pcie_stat_host_addr = cpu_to_le64(bp->hw_pcie_stats_map); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static void bnxt_hwrm_free_tunnel_ports(struct bnxt *bp) { if (bp->vxlan_port_cnt) { bnxt_hwrm_tunnel_dst_port_free( bp, TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_VXLAN); } bp->vxlan_port_cnt = 0; if (bp->nge_port_cnt) { bnxt_hwrm_tunnel_dst_port_free( bp, TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_GENEVE); } bp->nge_port_cnt = 0; } static int bnxt_set_tpa(struct bnxt *bp, bool set_tpa) { int rc, i; u32 tpa_flags = 0; if (set_tpa) tpa_flags = bp->flags & BNXT_FLAG_TPA; else if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) return 0; for (i = 0; i < bp->nr_vnics; i++) { rc = bnxt_hwrm_vnic_set_tpa(bp, i, tpa_flags); if (rc) { netdev_err(bp->dev, "hwrm vnic set tpa failure rc for vnic %d: %x\n", i, rc); return rc; } } return 0; } static void bnxt_hwrm_clear_vnic_rss(struct bnxt *bp) { int i; for (i = 0; i < bp->nr_vnics; i++) bnxt_hwrm_vnic_set_rss(bp, i, false); } static void bnxt_clear_vnic(struct bnxt *bp) { if (!bp->vnic_info) return; bnxt_hwrm_clear_vnic_filter(bp); if (!(bp->flags & BNXT_FLAG_CHIP_P5)) { /* clear all RSS setting before free vnic ctx */ bnxt_hwrm_clear_vnic_rss(bp); bnxt_hwrm_vnic_ctx_free(bp); } /* before free the vnic, undo the vnic tpa settings */ if (bp->flags & BNXT_FLAG_TPA) bnxt_set_tpa(bp, false); bnxt_hwrm_vnic_free(bp); if (bp->flags & BNXT_FLAG_CHIP_P5) bnxt_hwrm_vnic_ctx_free(bp); } static void bnxt_hwrm_resource_free(struct bnxt *bp, bool close_path, bool irq_re_init) { bnxt_clear_vnic(bp); bnxt_hwrm_ring_free(bp, close_path); bnxt_hwrm_ring_grp_free(bp); if (irq_re_init) { bnxt_hwrm_stat_ctx_free(bp); bnxt_hwrm_free_tunnel_ports(bp); } } static int bnxt_hwrm_set_br_mode(struct bnxt *bp, u16 br_mode) { struct hwrm_func_cfg_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_CFG, -1, -1); req.fid = cpu_to_le16(0xffff); req.enables = cpu_to_le32(FUNC_CFG_REQ_ENABLES_EVB_MODE); if (br_mode == BRIDGE_MODE_VEB) req.evb_mode = FUNC_CFG_REQ_EVB_MODE_VEB; else if (br_mode == BRIDGE_MODE_VEPA) req.evb_mode = FUNC_CFG_REQ_EVB_MODE_VEPA; else return -EINVAL; return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_set_cache_line_size(struct bnxt *bp, int size) { struct hwrm_func_cfg_input req = {0}; if (BNXT_VF(bp) || bp->hwrm_spec_code < 0x10803) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_CFG, -1, -1); req.fid = cpu_to_le16(0xffff); req.enables = cpu_to_le32(FUNC_CFG_REQ_ENABLES_CACHE_LINESIZE); req.options = FUNC_CFG_REQ_OPTIONS_CACHE_LINESIZE_SIZE_64; if (size == 128) req.options = FUNC_CFG_REQ_OPTIONS_CACHE_LINESIZE_SIZE_128; return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int __bnxt_setup_vnic(struct bnxt *bp, u16 vnic_id) { struct bnxt_vnic_info *vnic = &bp->vnic_info[vnic_id]; int rc; if (vnic->flags & BNXT_VNIC_RFS_NEW_RSS_FLAG) goto skip_rss_ctx; /* allocate context for vnic */ rc = bnxt_hwrm_vnic_ctx_alloc(bp, vnic_id, 0); if (rc) { netdev_err(bp->dev, "hwrm vnic %d alloc failure rc: %x\n", vnic_id, rc); goto vnic_setup_err; } bp->rsscos_nr_ctxs++; if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { rc = bnxt_hwrm_vnic_ctx_alloc(bp, vnic_id, 1); if (rc) { netdev_err(bp->dev, "hwrm vnic %d cos ctx alloc failure rc: %x\n", vnic_id, rc); goto vnic_setup_err; } bp->rsscos_nr_ctxs++; } skip_rss_ctx: /* configure default vnic, ring grp */ rc = bnxt_hwrm_vnic_cfg(bp, vnic_id); if (rc) { netdev_err(bp->dev, "hwrm vnic %d cfg failure rc: %x\n", vnic_id, rc); goto vnic_setup_err; } /* Enable RSS hashing on vnic */ rc = bnxt_hwrm_vnic_set_rss(bp, vnic_id, true); if (rc) { netdev_err(bp->dev, "hwrm vnic %d set rss failure rc: %x\n", vnic_id, rc); goto vnic_setup_err; } if (bp->flags & BNXT_FLAG_AGG_RINGS) { rc = bnxt_hwrm_vnic_set_hds(bp, vnic_id); if (rc) { netdev_err(bp->dev, "hwrm vnic %d set hds failure rc: %x\n", vnic_id, rc); } } vnic_setup_err: return rc; } static int __bnxt_setup_vnic_p5(struct bnxt *bp, u16 vnic_id) { int rc, i, nr_ctxs; nr_ctxs = DIV_ROUND_UP(bp->rx_nr_rings, 64); for (i = 0; i < nr_ctxs; i++) { rc = bnxt_hwrm_vnic_ctx_alloc(bp, vnic_id, i); if (rc) { netdev_err(bp->dev, "hwrm vnic %d ctx %d alloc failure rc: %x\n", vnic_id, i, rc); break; } bp->rsscos_nr_ctxs++; } if (i < nr_ctxs) return -ENOMEM; rc = bnxt_hwrm_vnic_set_rss_p5(bp, vnic_id, true); if (rc) { netdev_err(bp->dev, "hwrm vnic %d set rss failure rc: %d\n", vnic_id, rc); return rc; } rc = bnxt_hwrm_vnic_cfg(bp, vnic_id); if (rc) { netdev_err(bp->dev, "hwrm vnic %d cfg failure rc: %x\n", vnic_id, rc); return rc; } if (bp->flags & BNXT_FLAG_AGG_RINGS) { rc = bnxt_hwrm_vnic_set_hds(bp, vnic_id); if (rc) { netdev_err(bp->dev, "hwrm vnic %d set hds failure rc: %x\n", vnic_id, rc); } } return rc; } static int bnxt_setup_vnic(struct bnxt *bp, u16 vnic_id) { if (bp->flags & BNXT_FLAG_CHIP_P5) return __bnxt_setup_vnic_p5(bp, vnic_id); else return __bnxt_setup_vnic(bp, vnic_id); } static int bnxt_alloc_rfs_vnics(struct bnxt *bp) { #ifdef CONFIG_RFS_ACCEL int i, rc = 0; if (bp->flags & BNXT_FLAG_CHIP_P5) return 0; for (i = 0; i < bp->rx_nr_rings; i++) { struct bnxt_vnic_info *vnic; u16 vnic_id = i + 1; u16 ring_id = i; if (vnic_id >= bp->nr_vnics) break; vnic = &bp->vnic_info[vnic_id]; vnic->flags |= BNXT_VNIC_RFS_FLAG; if (bp->flags & BNXT_FLAG_NEW_RSS_CAP) vnic->flags |= BNXT_VNIC_RFS_NEW_RSS_FLAG; rc = bnxt_hwrm_vnic_alloc(bp, vnic_id, ring_id, 1); if (rc) { netdev_err(bp->dev, "hwrm vnic %d alloc failure rc: %x\n", vnic_id, rc); break; } rc = bnxt_setup_vnic(bp, vnic_id); if (rc) break; } return rc; #else return 0; #endif } /* Allow PF and VF with default VLAN to be in promiscuous mode */ static bool bnxt_promisc_ok(struct bnxt *bp) { #ifdef CONFIG_BNXT_SRIOV if (BNXT_VF(bp) && !bp->vf.vlan) return false; #endif return true; } static int bnxt_setup_nitroa0_vnic(struct bnxt *bp) { unsigned int rc = 0; rc = bnxt_hwrm_vnic_alloc(bp, 1, bp->rx_nr_rings - 1, 1); if (rc) { netdev_err(bp->dev, "Cannot allocate special vnic for NS2 A0: %x\n", rc); return rc; } rc = bnxt_hwrm_vnic_cfg(bp, 1); if (rc) { netdev_err(bp->dev, "Cannot allocate special vnic for NS2 A0: %x\n", rc); return rc; } return rc; } static int bnxt_cfg_rx_mode(struct bnxt *); static bool bnxt_mc_list_updated(struct bnxt *, u32 *); static int bnxt_init_chip(struct bnxt *bp, bool irq_re_init) { struct bnxt_vnic_info *vnic = &bp->vnic_info[0]; int rc = 0; unsigned int rx_nr_rings = bp->rx_nr_rings; if (irq_re_init) { rc = bnxt_hwrm_stat_ctx_alloc(bp); if (rc) { netdev_err(bp->dev, "hwrm stat ctx alloc failure rc: %x\n", rc); goto err_out; } } rc = bnxt_hwrm_ring_alloc(bp); if (rc) { netdev_err(bp->dev, "hwrm ring alloc failure rc: %x\n", rc); goto err_out; } rc = bnxt_hwrm_ring_grp_alloc(bp); if (rc) { netdev_err(bp->dev, "hwrm_ring_grp alloc failure: %x\n", rc); goto err_out; } if (BNXT_CHIP_TYPE_NITRO_A0(bp)) rx_nr_rings--; /* default vnic 0 */ rc = bnxt_hwrm_vnic_alloc(bp, 0, 0, rx_nr_rings); if (rc) { netdev_err(bp->dev, "hwrm vnic alloc failure rc: %x\n", rc); goto err_out; } rc = bnxt_setup_vnic(bp, 0); if (rc) goto err_out; if (bp->flags & BNXT_FLAG_RFS) { rc = bnxt_alloc_rfs_vnics(bp); if (rc) goto err_out; } if (bp->flags & BNXT_FLAG_TPA) { rc = bnxt_set_tpa(bp, true); if (rc) goto err_out; } if (BNXT_VF(bp)) bnxt_update_vf_mac(bp); /* Filter for default vnic 0 */ rc = bnxt_hwrm_set_vnic_filter(bp, 0, 0, bp->dev->dev_addr); if (rc) { netdev_err(bp->dev, "HWRM vnic filter failure rc: %x\n", rc); goto err_out; } vnic->uc_filter_count = 1; vnic->rx_mask = 0; if (bp->dev->flags & IFF_BROADCAST) vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_BCAST; if ((bp->dev->flags & IFF_PROMISC) && bnxt_promisc_ok(bp)) vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_PROMISCUOUS; if (bp->dev->flags & IFF_ALLMULTI) { vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_ALL_MCAST; vnic->mc_list_count = 0; } else { u32 mask = 0; bnxt_mc_list_updated(bp, &mask); vnic->rx_mask |= mask; } rc = bnxt_cfg_rx_mode(bp); if (rc) goto err_out; rc = bnxt_hwrm_set_coal(bp); if (rc) netdev_warn(bp->dev, "HWRM set coalescing failure rc: %x\n", rc); if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { rc = bnxt_setup_nitroa0_vnic(bp); if (rc) netdev_err(bp->dev, "Special vnic setup failure for NS2 A0 rc: %x\n", rc); } if (BNXT_VF(bp)) { bnxt_hwrm_func_qcfg(bp); netdev_update_features(bp->dev); } return 0; err_out: bnxt_hwrm_resource_free(bp, 0, true); return rc; } static int bnxt_shutdown_nic(struct bnxt *bp, bool irq_re_init) { bnxt_hwrm_resource_free(bp, 1, irq_re_init); return 0; } static int bnxt_init_nic(struct bnxt *bp, bool irq_re_init) { bnxt_init_cp_rings(bp); bnxt_init_rx_rings(bp); bnxt_init_tx_rings(bp); bnxt_init_ring_grps(bp, irq_re_init); bnxt_init_vnics(bp); return bnxt_init_chip(bp, irq_re_init); } static int bnxt_set_real_num_queues(struct bnxt *bp) { int rc; struct net_device *dev = bp->dev; rc = netif_set_real_num_tx_queues(dev, bp->tx_nr_rings - bp->tx_nr_rings_xdp); if (rc) return rc; rc = netif_set_real_num_rx_queues(dev, bp->rx_nr_rings); if (rc) return rc; #ifdef CONFIG_RFS_ACCEL if (bp->flags & BNXT_FLAG_RFS) dev->rx_cpu_rmap = alloc_irq_cpu_rmap(bp->rx_nr_rings); #endif return rc; } static int bnxt_trim_rings(struct bnxt *bp, int *rx, int *tx, int max, bool shared) { int _rx = *rx, _tx = *tx; if (shared) { *rx = min_t(int, _rx, max); *tx = min_t(int, _tx, max); } else { if (max < 2) return -ENOMEM; while (_rx + _tx > max) { if (_rx > _tx && _rx > 1) _rx--; else if (_tx > 1) _tx--; } *rx = _rx; *tx = _tx; } return 0; } static void bnxt_setup_msix(struct bnxt *bp) { const int len = sizeof(bp->irq_tbl[0].name); struct net_device *dev = bp->dev; int tcs, i; tcs = netdev_get_num_tc(dev); if (tcs) { int i, off, count; for (i = 0; i < tcs; i++) { count = bp->tx_nr_rings_per_tc; off = i * count; netdev_set_tc_queue(dev, i, count, off); } } for (i = 0; i < bp->cp_nr_rings; i++) { int map_idx = bnxt_cp_num_to_irq_num(bp, i); char *attr; if (bp->flags & BNXT_FLAG_SHARED_RINGS) attr = "TxRx"; else if (i < bp->rx_nr_rings) attr = "rx"; else attr = "tx"; snprintf(bp->irq_tbl[map_idx].name, len, "%s-%s-%d", dev->name, attr, i); bp->irq_tbl[map_idx].handler = bnxt_msix; } } static void bnxt_setup_inta(struct bnxt *bp) { const int len = sizeof(bp->irq_tbl[0].name); if (netdev_get_num_tc(bp->dev)) netdev_reset_tc(bp->dev); snprintf(bp->irq_tbl[0].name, len, "%s-%s-%d", bp->dev->name, "TxRx", 0); bp->irq_tbl[0].handler = bnxt_inta; } static int bnxt_setup_int_mode(struct bnxt *bp) { int rc; if (bp->flags & BNXT_FLAG_USING_MSIX) bnxt_setup_msix(bp); else bnxt_setup_inta(bp); rc = bnxt_set_real_num_queues(bp); return rc; } #ifdef CONFIG_RFS_ACCEL static unsigned int bnxt_get_max_func_rss_ctxs(struct bnxt *bp) { return bp->hw_resc.max_rsscos_ctxs; } static unsigned int bnxt_get_max_func_vnics(struct bnxt *bp) { return bp->hw_resc.max_vnics; } #endif unsigned int bnxt_get_max_func_stat_ctxs(struct bnxt *bp) { return bp->hw_resc.max_stat_ctxs; } unsigned int bnxt_get_max_func_cp_rings(struct bnxt *bp) { return bp->hw_resc.max_cp_rings; } static unsigned int bnxt_get_max_func_cp_rings_for_en(struct bnxt *bp) { unsigned int cp = bp->hw_resc.max_cp_rings; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) cp -= bnxt_get_ulp_msix_num(bp); return cp; } static unsigned int bnxt_get_max_func_irqs(struct bnxt *bp) { struct bnxt_hw_resc *hw_resc = &bp->hw_resc; if (bp->flags & BNXT_FLAG_CHIP_P5) return min_t(unsigned int, hw_resc->max_irqs, hw_resc->max_nqs); return min_t(unsigned int, hw_resc->max_irqs, hw_resc->max_cp_rings); } static void bnxt_set_max_func_irqs(struct bnxt *bp, unsigned int max_irqs) { bp->hw_resc.max_irqs = max_irqs; } unsigned int bnxt_get_avail_cp_rings_for_en(struct bnxt *bp) { unsigned int cp; cp = bnxt_get_max_func_cp_rings_for_en(bp); if (bp->flags & BNXT_FLAG_CHIP_P5) return cp - bp->rx_nr_rings - bp->tx_nr_rings; else return cp - bp->cp_nr_rings; } unsigned int bnxt_get_avail_stat_ctxs_for_en(struct bnxt *bp) { return bnxt_get_max_func_stat_ctxs(bp) - bnxt_get_func_stat_ctxs(bp); } int bnxt_get_avail_msix(struct bnxt *bp, int num) { int max_cp = bnxt_get_max_func_cp_rings(bp); int max_irq = bnxt_get_max_func_irqs(bp); int total_req = bp->cp_nr_rings + num; int max_idx, avail_msix; max_idx = bp->total_irqs; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) max_idx = min_t(int, bp->total_irqs, max_cp); avail_msix = max_idx - bp->cp_nr_rings; if (!BNXT_NEW_RM(bp) || avail_msix >= num) return avail_msix; if (max_irq < total_req) { num = max_irq - bp->cp_nr_rings; if (num <= 0) return 0; } return num; } static int bnxt_get_num_msix(struct bnxt *bp) { if (!BNXT_NEW_RM(bp)) return bnxt_get_max_func_irqs(bp); return bnxt_nq_rings_in_use(bp); } static int bnxt_init_msix(struct bnxt *bp) { int i, total_vecs, max, rc = 0, min = 1, ulp_msix; struct msix_entry *msix_ent; total_vecs = bnxt_get_num_msix(bp); max = bnxt_get_max_func_irqs(bp); if (total_vecs > max) total_vecs = max; if (!total_vecs) return 0; msix_ent = kcalloc(total_vecs, sizeof(struct msix_entry), GFP_KERNEL); if (!msix_ent) return -ENOMEM; for (i = 0; i < total_vecs; i++) { msix_ent[i].entry = i; msix_ent[i].vector = 0; } if (!(bp->flags & BNXT_FLAG_SHARED_RINGS)) min = 2; total_vecs = pci_enable_msix_range(bp->pdev, msix_ent, min, total_vecs); ulp_msix = bnxt_get_ulp_msix_num(bp); if (total_vecs < 0 || total_vecs < ulp_msix) { rc = -ENODEV; goto msix_setup_exit; } bp->irq_tbl = kcalloc(total_vecs, sizeof(struct bnxt_irq), GFP_KERNEL); if (bp->irq_tbl) { for (i = 0; i < total_vecs; i++) bp->irq_tbl[i].vector = msix_ent[i].vector; bp->total_irqs = total_vecs; /* Trim rings based upon num of vectors allocated */ rc = bnxt_trim_rings(bp, &bp->rx_nr_rings, &bp->tx_nr_rings, total_vecs - ulp_msix, min == 1); if (rc) goto msix_setup_exit; bp->cp_nr_rings = (min == 1) ? max_t(int, bp->tx_nr_rings, bp->rx_nr_rings) : bp->tx_nr_rings + bp->rx_nr_rings; } else { rc = -ENOMEM; goto msix_setup_exit; } bp->flags |= BNXT_FLAG_USING_MSIX; kfree(msix_ent); return 0; msix_setup_exit: netdev_err(bp->dev, "bnxt_init_msix err: %x\n", rc); kfree(bp->irq_tbl); bp->irq_tbl = NULL; pci_disable_msix(bp->pdev); kfree(msix_ent); return rc; } static int bnxt_init_inta(struct bnxt *bp) { bp->irq_tbl = kcalloc(1, sizeof(struct bnxt_irq), GFP_KERNEL); if (!bp->irq_tbl) return -ENOMEM; bp->total_irqs = 1; bp->rx_nr_rings = 1; bp->tx_nr_rings = 1; bp->cp_nr_rings = 1; bp->flags |= BNXT_FLAG_SHARED_RINGS; bp->irq_tbl[0].vector = bp->pdev->irq; return 0; } static int bnxt_init_int_mode(struct bnxt *bp) { int rc = 0; if (bp->flags & BNXT_FLAG_MSIX_CAP) rc = bnxt_init_msix(bp); if (!(bp->flags & BNXT_FLAG_USING_MSIX) && BNXT_PF(bp)) { /* fallback to INTA */ rc = bnxt_init_inta(bp); } return rc; } static void bnxt_clear_int_mode(struct bnxt *bp) { if (bp->flags & BNXT_FLAG_USING_MSIX) pci_disable_msix(bp->pdev); kfree(bp->irq_tbl); bp->irq_tbl = NULL; bp->flags &= ~BNXT_FLAG_USING_MSIX; } int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init) { int tcs = netdev_get_num_tc(bp->dev); bool irq_cleared = false; int rc; if (!bnxt_need_reserve_rings(bp)) return 0; if (irq_re_init && BNXT_NEW_RM(bp) && bnxt_get_num_msix(bp) != bp->total_irqs) { bnxt_ulp_irq_stop(bp); bnxt_clear_int_mode(bp); irq_cleared = true; } rc = __bnxt_reserve_rings(bp); if (irq_cleared) { if (!rc) rc = bnxt_init_int_mode(bp); bnxt_ulp_irq_restart(bp, rc); } if (rc) { netdev_err(bp->dev, "ring reservation/IRQ init failure rc: %d\n", rc); return rc; } if (tcs && (bp->tx_nr_rings_per_tc * tcs != bp->tx_nr_rings)) { netdev_err(bp->dev, "tx ring reservation failure\n"); netdev_reset_tc(bp->dev); bp->tx_nr_rings_per_tc = bp->tx_nr_rings; return -ENOMEM; } return 0; } static void bnxt_free_irq(struct bnxt *bp) { struct bnxt_irq *irq; int i; #ifdef CONFIG_RFS_ACCEL free_irq_cpu_rmap(bp->dev->rx_cpu_rmap); bp->dev->rx_cpu_rmap = NULL; #endif if (!bp->irq_tbl || !bp->bnapi) return; for (i = 0; i < bp->cp_nr_rings; i++) { int map_idx = bnxt_cp_num_to_irq_num(bp, i); irq = &bp->irq_tbl[map_idx]; if (irq->requested) { if (irq->have_cpumask) { irq_set_affinity_hint(irq->vector, NULL); free_cpumask_var(irq->cpu_mask); irq->have_cpumask = 0; } free_irq(irq->vector, bp->bnapi[i]); } irq->requested = 0; } } static int bnxt_request_irq(struct bnxt *bp) { int i, j, rc = 0; unsigned long flags = 0; #ifdef CONFIG_RFS_ACCEL struct cpu_rmap *rmap; #endif rc = bnxt_setup_int_mode(bp); if (rc) { netdev_err(bp->dev, "bnxt_setup_int_mode err: %x\n", rc); return rc; } #ifdef CONFIG_RFS_ACCEL rmap = bp->dev->rx_cpu_rmap; #endif if (!(bp->flags & BNXT_FLAG_USING_MSIX)) flags = IRQF_SHARED; for (i = 0, j = 0; i < bp->cp_nr_rings; i++) { int map_idx = bnxt_cp_num_to_irq_num(bp, i); struct bnxt_irq *irq = &bp->irq_tbl[map_idx]; #ifdef CONFIG_RFS_ACCEL if (rmap && bp->bnapi[i]->rx_ring) { rc = irq_cpu_rmap_add(rmap, irq->vector); if (rc) netdev_warn(bp->dev, "failed adding irq rmap for ring %d\n", j); j++; } #endif rc = request_irq(irq->vector, irq->handler, flags, irq->name, bp->bnapi[i]); if (rc) break; irq->requested = 1; if (zalloc_cpumask_var(&irq->cpu_mask, GFP_KERNEL)) { int numa_node = dev_to_node(&bp->pdev->dev); irq->have_cpumask = 1; cpumask_set_cpu(cpumask_local_spread(i, numa_node), irq->cpu_mask); rc = irq_set_affinity_hint(irq->vector, irq->cpu_mask); if (rc) { netdev_warn(bp->dev, "Set affinity failed, IRQ = %d\n", irq->vector); break; } } } return rc; } static void bnxt_del_napi(struct bnxt *bp) { int i; if (!bp->bnapi) return; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; napi_hash_del(&bnapi->napi); netif_napi_del(&bnapi->napi); } /* We called napi_hash_del() before netif_napi_del(), we need * to respect an RCU grace period before freeing napi structures. */ synchronize_net(); } static void bnxt_init_napi(struct bnxt *bp) { int i; unsigned int cp_nr_rings = bp->cp_nr_rings; struct bnxt_napi *bnapi; if (bp->flags & BNXT_FLAG_USING_MSIX) { int (*poll_fn)(struct napi_struct *, int) = bnxt_poll; if (bp->flags & BNXT_FLAG_CHIP_P5) poll_fn = bnxt_poll_p5; else if (BNXT_CHIP_TYPE_NITRO_A0(bp)) cp_nr_rings--; for (i = 0; i < cp_nr_rings; i++) { bnapi = bp->bnapi[i]; netif_napi_add(bp->dev, &bnapi->napi, poll_fn, 64); } if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { bnapi = bp->bnapi[cp_nr_rings]; netif_napi_add(bp->dev, &bnapi->napi, bnxt_poll_nitroa0, 64); } } else { bnapi = bp->bnapi[0]; netif_napi_add(bp->dev, &bnapi->napi, bnxt_poll, 64); } } static void bnxt_disable_napi(struct bnxt *bp) { int i; if (!bp->bnapi) return; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_cp_ring_info *cpr = &bp->bnapi[i]->cp_ring; if (bp->bnapi[i]->rx_ring) cancel_work_sync(&cpr->dim.work); napi_disable(&bp->bnapi[i]->napi); } } static void bnxt_enable_napi(struct bnxt *bp) { int i; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_cp_ring_info *cpr = &bp->bnapi[i]->cp_ring; bp->bnapi[i]->in_reset = false; if (bp->bnapi[i]->rx_ring) { INIT_WORK(&cpr->dim.work, bnxt_dim_work); cpr->dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE; } napi_enable(&bp->bnapi[i]->napi); } } void bnxt_tx_disable(struct bnxt *bp) { int i; struct bnxt_tx_ring_info *txr; if (bp->tx_ring) { for (i = 0; i < bp->tx_nr_rings; i++) { txr = &bp->tx_ring[i]; txr->dev_state = BNXT_DEV_STATE_CLOSING; } } /* Stop all TX queues */ netif_tx_disable(bp->dev); netif_carrier_off(bp->dev); } void bnxt_tx_enable(struct bnxt *bp) { int i; struct bnxt_tx_ring_info *txr; for (i = 0; i < bp->tx_nr_rings; i++) { txr = &bp->tx_ring[i]; txr->dev_state = 0; } netif_tx_wake_all_queues(bp->dev); if (bp->link_info.link_up) netif_carrier_on(bp->dev); } static void bnxt_report_link(struct bnxt *bp) { if (bp->link_info.link_up) { const char *duplex; const char *flow_ctrl; u32 speed; u16 fec; netif_carrier_on(bp->dev); if (bp->link_info.duplex == BNXT_LINK_DUPLEX_FULL) duplex = "full"; else duplex = "half"; if (bp->link_info.pause == BNXT_LINK_PAUSE_BOTH) flow_ctrl = "ON - receive & transmit"; else if (bp->link_info.pause == BNXT_LINK_PAUSE_TX) flow_ctrl = "ON - transmit"; else if (bp->link_info.pause == BNXT_LINK_PAUSE_RX) flow_ctrl = "ON - receive"; else flow_ctrl = "none"; speed = bnxt_fw_to_ethtool_speed(bp->link_info.link_speed); netdev_info(bp->dev, "NIC Link is Up, %u Mbps %s duplex, Flow control: %s\n", speed, duplex, flow_ctrl); if (bp->flags & BNXT_FLAG_EEE_CAP) netdev_info(bp->dev, "EEE is %s\n", bp->eee.eee_active ? "active" : "not active"); fec = bp->link_info.fec_cfg; if (!(fec & PORT_PHY_QCFG_RESP_FEC_CFG_FEC_NONE_SUPPORTED)) netdev_info(bp->dev, "FEC autoneg %s encodings: %s\n", (fec & BNXT_FEC_AUTONEG) ? "on" : "off", (fec & BNXT_FEC_ENC_BASE_R) ? "BaseR" : (fec & BNXT_FEC_ENC_RS) ? "RS" : "None"); } else { netif_carrier_off(bp->dev); netdev_err(bp->dev, "NIC Link is Down\n"); } } static int bnxt_hwrm_phy_qcaps(struct bnxt *bp) { int rc = 0; struct hwrm_port_phy_qcaps_input req = {0}; struct hwrm_port_phy_qcaps_output *resp = bp->hwrm_cmd_resp_addr; struct bnxt_link_info *link_info = &bp->link_info; bp->flags &= ~BNXT_FLAG_EEE_CAP; if (bp->test_info) bp->test_info->flags &= ~(BNXT_TEST_FL_EXT_LPBK | BNXT_TEST_FL_AN_PHY_LPBK); if (bp->hwrm_spec_code < 0x10201) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_QCAPS, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) goto hwrm_phy_qcaps_exit; if (resp->flags & PORT_PHY_QCAPS_RESP_FLAGS_EEE_SUPPORTED) { struct ethtool_eee *eee = &bp->eee; u16 fw_speeds = le16_to_cpu(resp->supported_speeds_eee_mode); bp->flags |= BNXT_FLAG_EEE_CAP; eee->supported = _bnxt_fw_to_ethtool_adv_spds(fw_speeds, 0); bp->lpi_tmr_lo = le32_to_cpu(resp->tx_lpi_timer_low) & PORT_PHY_QCAPS_RESP_TX_LPI_TIMER_LOW_MASK; bp->lpi_tmr_hi = le32_to_cpu(resp->valid_tx_lpi_timer_high) & PORT_PHY_QCAPS_RESP_TX_LPI_TIMER_HIGH_MASK; } if (resp->flags & PORT_PHY_QCAPS_RESP_FLAGS_EXTERNAL_LPBK_SUPPORTED) { if (bp->test_info) bp->test_info->flags |= BNXT_TEST_FL_EXT_LPBK; } if (resp->flags & PORT_PHY_QCAPS_RESP_FLAGS_AUTONEG_LPBK_SUPPORTED) { if (bp->test_info) bp->test_info->flags |= BNXT_TEST_FL_AN_PHY_LPBK; } if (resp->flags & PORT_PHY_QCAPS_RESP_FLAGS_SHARED_PHY_CFG_SUPPORTED) { if (BNXT_PF(bp)) bp->fw_cap |= BNXT_FW_CAP_SHARED_PORT_CFG; } if (resp->supported_speeds_auto_mode) link_info->support_auto_speeds = le16_to_cpu(resp->supported_speeds_auto_mode); bp->port_count = resp->port_cnt; hwrm_phy_qcaps_exit: mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_update_link(struct bnxt *bp, bool chng_link_state) { int rc = 0; struct bnxt_link_info *link_info = &bp->link_info; struct hwrm_port_phy_qcfg_input req = {0}; struct hwrm_port_phy_qcfg_output *resp = bp->hwrm_cmd_resp_addr; u8 link_up = link_info->link_up; u16 diff; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_QCFG, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) { mutex_unlock(&bp->hwrm_cmd_lock); return rc; } memcpy(&link_info->phy_qcfg_resp, resp, sizeof(*resp)); link_info->phy_link_status = resp->link; link_info->duplex = resp->duplex_cfg; if (bp->hwrm_spec_code >= 0x10800) link_info->duplex = resp->duplex_state; link_info->pause = resp->pause; link_info->auto_mode = resp->auto_mode; link_info->auto_pause_setting = resp->auto_pause; link_info->lp_pause = resp->link_partner_adv_pause; link_info->force_pause_setting = resp->force_pause; link_info->duplex_setting = resp->duplex_cfg; if (link_info->phy_link_status == BNXT_LINK_LINK) link_info->link_speed = le16_to_cpu(resp->link_speed); else link_info->link_speed = 0; link_info->force_link_speed = le16_to_cpu(resp->force_link_speed); link_info->support_speeds = le16_to_cpu(resp->support_speeds); link_info->auto_link_speeds = le16_to_cpu(resp->auto_link_speed_mask); link_info->lp_auto_link_speeds = le16_to_cpu(resp->link_partner_adv_speeds); link_info->preemphasis = le32_to_cpu(resp->preemphasis); link_info->phy_ver[0] = resp->phy_maj; link_info->phy_ver[1] = resp->phy_min; link_info->phy_ver[2] = resp->phy_bld; link_info->media_type = resp->media_type; link_info->phy_type = resp->phy_type; link_info->transceiver = resp->xcvr_pkg_type; link_info->phy_addr = resp->eee_config_phy_addr & PORT_PHY_QCFG_RESP_PHY_ADDR_MASK; link_info->module_status = resp->module_status; if (bp->flags & BNXT_FLAG_EEE_CAP) { struct ethtool_eee *eee = &bp->eee; u16 fw_speeds; eee->eee_active = 0; if (resp->eee_config_phy_addr & PORT_PHY_QCFG_RESP_EEE_CONFIG_EEE_ACTIVE) { eee->eee_active = 1; fw_speeds = le16_to_cpu( resp->link_partner_adv_eee_link_speed_mask); eee->lp_advertised = _bnxt_fw_to_ethtool_adv_spds(fw_speeds, 0); } /* Pull initial EEE config */ if (!chng_link_state) { if (resp->eee_config_phy_addr & PORT_PHY_QCFG_RESP_EEE_CONFIG_EEE_ENABLED) eee->eee_enabled = 1; fw_speeds = le16_to_cpu(resp->adv_eee_link_speed_mask); eee->advertised = _bnxt_fw_to_ethtool_adv_spds(fw_speeds, 0); if (resp->eee_config_phy_addr & PORT_PHY_QCFG_RESP_EEE_CONFIG_EEE_TX_LPI) { __le32 tmr; eee->tx_lpi_enabled = 1; tmr = resp->xcvr_identifier_type_tx_lpi_timer; eee->tx_lpi_timer = le32_to_cpu(tmr) & PORT_PHY_QCFG_RESP_TX_LPI_TIMER_MASK; } } } link_info->fec_cfg = PORT_PHY_QCFG_RESP_FEC_CFG_FEC_NONE_SUPPORTED; if (bp->hwrm_spec_code >= 0x10504) link_info->fec_cfg = le16_to_cpu(resp->fec_cfg); /* TODO: need to add more logic to report VF link */ if (chng_link_state) { if (link_info->phy_link_status == BNXT_LINK_LINK) link_info->link_up = 1; else link_info->link_up = 0; if (link_up != link_info->link_up) bnxt_report_link(bp); } else { /* alwasy link down if not require to update link state */ link_info->link_up = 0; } mutex_unlock(&bp->hwrm_cmd_lock); if (!BNXT_PHY_CFG_ABLE(bp)) return 0; diff = link_info->support_auto_speeds ^ link_info->advertising; if ((link_info->support_auto_speeds | diff) != link_info->support_auto_speeds) { /* An advertised speed is no longer supported, so we need to * update the advertisement settings. Caller holds RTNL * so we can modify link settings. */ link_info->advertising = link_info->support_auto_speeds; if (link_info->autoneg & BNXT_AUTONEG_SPEED) bnxt_hwrm_set_link_setting(bp, true, false); } return 0; } static void bnxt_get_port_module_status(struct bnxt *bp) { struct bnxt_link_info *link_info = &bp->link_info; struct hwrm_port_phy_qcfg_output *resp = &link_info->phy_qcfg_resp; u8 module_status; if (bnxt_update_link(bp, true)) return; module_status = link_info->module_status; switch (module_status) { case PORT_PHY_QCFG_RESP_MODULE_STATUS_DISABLETX: case PORT_PHY_QCFG_RESP_MODULE_STATUS_PWRDOWN: case PORT_PHY_QCFG_RESP_MODULE_STATUS_WARNINGMSG: netdev_warn(bp->dev, "Unqualified SFP+ module detected on port %d\n", bp->pf.port_id); if (bp->hwrm_spec_code >= 0x10201) { netdev_warn(bp->dev, "Module part number %s\n", resp->phy_vendor_partnumber); } if (module_status == PORT_PHY_QCFG_RESP_MODULE_STATUS_DISABLETX) netdev_warn(bp->dev, "TX is disabled\n"); if (module_status == PORT_PHY_QCFG_RESP_MODULE_STATUS_PWRDOWN) netdev_warn(bp->dev, "SFP+ module is shutdown\n"); } } static void bnxt_hwrm_set_pause_common(struct bnxt *bp, struct hwrm_port_phy_cfg_input *req) { if (bp->link_info.autoneg & BNXT_AUTONEG_FLOW_CTRL) { if (bp->hwrm_spec_code >= 0x10201) req->auto_pause = PORT_PHY_CFG_REQ_AUTO_PAUSE_AUTONEG_PAUSE; if (bp->link_info.req_flow_ctrl & BNXT_LINK_PAUSE_RX) req->auto_pause |= PORT_PHY_CFG_REQ_AUTO_PAUSE_RX; if (bp->link_info.req_flow_ctrl & BNXT_LINK_PAUSE_TX) req->auto_pause |= PORT_PHY_CFG_REQ_AUTO_PAUSE_TX; req->enables |= cpu_to_le32(PORT_PHY_CFG_REQ_ENABLES_AUTO_PAUSE); } else { if (bp->link_info.req_flow_ctrl & BNXT_LINK_PAUSE_RX) req->force_pause |= PORT_PHY_CFG_REQ_FORCE_PAUSE_RX; if (bp->link_info.req_flow_ctrl & BNXT_LINK_PAUSE_TX) req->force_pause |= PORT_PHY_CFG_REQ_FORCE_PAUSE_TX; req->enables |= cpu_to_le32(PORT_PHY_CFG_REQ_ENABLES_FORCE_PAUSE); if (bp->hwrm_spec_code >= 0x10201) { req->auto_pause = req->force_pause; req->enables |= cpu_to_le32( PORT_PHY_CFG_REQ_ENABLES_AUTO_PAUSE); } } } static void bnxt_hwrm_set_link_common(struct bnxt *bp, struct hwrm_port_phy_cfg_input *req) { u8 autoneg = bp->link_info.autoneg; u16 fw_link_speed = bp->link_info.req_link_speed; u16 advertising = bp->link_info.advertising; if (autoneg & BNXT_AUTONEG_SPEED) { req->auto_mode |= PORT_PHY_CFG_REQ_AUTO_MODE_SPEED_MASK; req->enables |= cpu_to_le32( PORT_PHY_CFG_REQ_ENABLES_AUTO_LINK_SPEED_MASK); req->auto_link_speed_mask = cpu_to_le16(advertising); req->enables |= cpu_to_le32(PORT_PHY_CFG_REQ_ENABLES_AUTO_MODE); req->flags |= cpu_to_le32(PORT_PHY_CFG_REQ_FLAGS_RESTART_AUTONEG); } else { req->force_link_speed = cpu_to_le16(fw_link_speed); req->flags |= cpu_to_le32(PORT_PHY_CFG_REQ_FLAGS_FORCE); } /* tell chimp that the setting takes effect immediately */ req->flags |= cpu_to_le32(PORT_PHY_CFG_REQ_FLAGS_RESET_PHY); } int bnxt_hwrm_set_pause(struct bnxt *bp) { struct hwrm_port_phy_cfg_input req = {0}; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_CFG, -1, -1); bnxt_hwrm_set_pause_common(bp, &req); if ((bp->link_info.autoneg & BNXT_AUTONEG_FLOW_CTRL) || bp->link_info.force_link_chng) bnxt_hwrm_set_link_common(bp, &req); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc && !(bp->link_info.autoneg & BNXT_AUTONEG_FLOW_CTRL)) { /* since changing of pause setting doesn't trigger any link * change event, the driver needs to update the current pause * result upon successfully return of the phy_cfg command */ bp->link_info.pause = bp->link_info.force_pause_setting = bp->link_info.req_flow_ctrl; bp->link_info.auto_pause_setting = 0; if (!bp->link_info.force_link_chng) bnxt_report_link(bp); } bp->link_info.force_link_chng = false; mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static void bnxt_hwrm_set_eee(struct bnxt *bp, struct hwrm_port_phy_cfg_input *req) { struct ethtool_eee *eee = &bp->eee; if (eee->eee_enabled) { u16 eee_speeds; u32 flags = PORT_PHY_CFG_REQ_FLAGS_EEE_ENABLE; if (eee->tx_lpi_enabled) flags |= PORT_PHY_CFG_REQ_FLAGS_EEE_TX_LPI_ENABLE; else flags |= PORT_PHY_CFG_REQ_FLAGS_EEE_TX_LPI_DISABLE; req->flags |= cpu_to_le32(flags); eee_speeds = bnxt_get_fw_auto_link_speeds(eee->advertised); req->eee_link_speed_mask = cpu_to_le16(eee_speeds); req->tx_lpi_timer = cpu_to_le32(eee->tx_lpi_timer); } else { req->flags |= cpu_to_le32(PORT_PHY_CFG_REQ_FLAGS_EEE_DISABLE); } } int bnxt_hwrm_set_link_setting(struct bnxt *bp, bool set_pause, bool set_eee) { struct hwrm_port_phy_cfg_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_CFG, -1, -1); if (set_pause) bnxt_hwrm_set_pause_common(bp, &req); bnxt_hwrm_set_link_common(bp, &req); if (set_eee) bnxt_hwrm_set_eee(bp, &req); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_hwrm_shutdown_link(struct bnxt *bp) { struct hwrm_port_phy_cfg_input req = {0}; if (!BNXT_SINGLE_PF(bp)) return 0; if (pci_num_vf(bp->pdev)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_CFG, -1, -1); req.flags = cpu_to_le32(PORT_PHY_CFG_REQ_FLAGS_FORCE_LINK_DWN); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static int bnxt_fw_init_one(struct bnxt *bp); static int bnxt_hwrm_if_change(struct bnxt *bp, bool up) { struct hwrm_func_drv_if_change_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_func_drv_if_change_input req = {0}; bool resc_reinit = false, fw_reset = false; u32 flags = 0; int rc; if (!(bp->fw_cap & BNXT_FW_CAP_IF_CHANGE)) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FUNC_DRV_IF_CHANGE, -1, -1); if (up) req.flags = cpu_to_le32(FUNC_DRV_IF_CHANGE_REQ_FLAGS_UP); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) flags = le32_to_cpu(resp->flags); mutex_unlock(&bp->hwrm_cmd_lock); if (rc) return rc; if (!up) return 0; if (flags & FUNC_DRV_IF_CHANGE_RESP_FLAGS_RESC_CHANGE) resc_reinit = true; if (flags & FUNC_DRV_IF_CHANGE_RESP_FLAGS_HOT_FW_RESET_DONE) fw_reset = true; if (test_bit(BNXT_STATE_IN_FW_RESET, &bp->state) && !fw_reset) { netdev_err(bp->dev, "RESET_DONE not set during FW reset.\n"); return -ENODEV; } if (resc_reinit || fw_reset) { if (fw_reset) { if (!test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) bnxt_ulp_stop(bp); bnxt_free_ctx_mem(bp); kfree(bp->ctx); bp->ctx = NULL; bnxt_dcb_free(bp); rc = bnxt_fw_init_one(bp); if (rc) { set_bit(BNXT_STATE_ABORT_ERR, &bp->state); return rc; } bnxt_clear_int_mode(bp); rc = bnxt_init_int_mode(bp); if (rc) { netdev_err(bp->dev, "init int mode failed\n"); return rc; } set_bit(BNXT_STATE_FW_RESET_DET, &bp->state); } if (BNXT_NEW_RM(bp)) { struct bnxt_hw_resc *hw_resc = &bp->hw_resc; rc = bnxt_hwrm_func_resc_qcaps(bp, true); hw_resc->resv_cp_rings = 0; hw_resc->resv_stat_ctxs = 0; hw_resc->resv_irqs = 0; hw_resc->resv_tx_rings = 0; hw_resc->resv_rx_rings = 0; hw_resc->resv_hw_ring_grps = 0; hw_resc->resv_vnics = 0; if (!fw_reset) { bp->tx_nr_rings = 0; bp->rx_nr_rings = 0; } } } return 0; } static int bnxt_hwrm_port_led_qcaps(struct bnxt *bp) { struct hwrm_port_led_qcaps_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_port_led_qcaps_input req = {0}; struct bnxt_pf_info *pf = &bp->pf; int rc; bp->num_leds = 0; if (BNXT_VF(bp) || bp->hwrm_spec_code < 0x10601) return 0; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_LED_QCAPS, -1, -1); req.port_id = cpu_to_le16(pf->port_id); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) { mutex_unlock(&bp->hwrm_cmd_lock); return rc; } if (resp->num_leds > 0 && resp->num_leds < BNXT_MAX_LED) { int i; bp->num_leds = resp->num_leds; memcpy(bp->leds, &resp->led0_id, sizeof(bp->leds[0]) * bp->num_leds); for (i = 0; i < bp->num_leds; i++) { struct bnxt_led_info *led = &bp->leds[i]; __le16 caps = led->led_state_caps; if (!led->led_group_id || !BNXT_LED_ALT_BLINK_CAP(caps)) { bp->num_leds = 0; break; } } } mutex_unlock(&bp->hwrm_cmd_lock); return 0; } int bnxt_hwrm_alloc_wol_fltr(struct bnxt *bp) { struct hwrm_wol_filter_alloc_input req = {0}; struct hwrm_wol_filter_alloc_output *resp = bp->hwrm_cmd_resp_addr; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_WOL_FILTER_ALLOC, -1, -1); req.port_id = cpu_to_le16(bp->pf.port_id); req.wol_type = WOL_FILTER_ALLOC_REQ_WOL_TYPE_MAGICPKT; req.enables = cpu_to_le32(WOL_FILTER_ALLOC_REQ_ENABLES_MAC_ADDRESS); memcpy(req.mac_address, bp->dev->dev_addr, ETH_ALEN); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) bp->wol_filter_id = resp->wol_filter_id; mutex_unlock(&bp->hwrm_cmd_lock); return rc; } int bnxt_hwrm_free_wol_fltr(struct bnxt *bp) { struct hwrm_wol_filter_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_WOL_FILTER_FREE, -1, -1); req.port_id = cpu_to_le16(bp->pf.port_id); req.enables = cpu_to_le32(WOL_FILTER_FREE_REQ_ENABLES_WOL_FILTER_ID); req.wol_filter_id = bp->wol_filter_id; return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } static u16 bnxt_hwrm_get_wol_fltrs(struct bnxt *bp, u16 handle) { struct hwrm_wol_filter_qcfg_input req = {0}; struct hwrm_wol_filter_qcfg_output *resp = bp->hwrm_cmd_resp_addr; u16 next_handle = 0; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_WOL_FILTER_QCFG, -1, -1); req.port_id = cpu_to_le16(bp->pf.port_id); req.handle = cpu_to_le16(handle); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { next_handle = le16_to_cpu(resp->next_handle); if (next_handle != 0) { if (resp->wol_type == WOL_FILTER_ALLOC_REQ_WOL_TYPE_MAGICPKT) { bp->wol = 1; bp->wol_filter_id = resp->wol_filter_id; } } } mutex_unlock(&bp->hwrm_cmd_lock); return next_handle; } static void bnxt_get_wol_settings(struct bnxt *bp) { u16 handle = 0; bp->wol = 0; if (!BNXT_PF(bp) || !(bp->flags & BNXT_FLAG_WOL_CAP)) return; do { handle = bnxt_hwrm_get_wol_fltrs(bp, handle); } while (handle && handle != 0xffff); } #ifdef CONFIG_BNXT_HWMON static ssize_t bnxt_show_temp(struct device *dev, struct device_attribute *devattr, char *buf) { struct hwrm_temp_monitor_query_input req = {0}; struct hwrm_temp_monitor_query_output *resp; struct bnxt *bp = dev_get_drvdata(dev); u32 temp = 0; resp = bp->hwrm_cmd_resp_addr; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_TEMP_MONITOR_QUERY, -1, -1); mutex_lock(&bp->hwrm_cmd_lock); if (!_hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT)) temp = resp->temp * 1000; /* display millidegree */ mutex_unlock(&bp->hwrm_cmd_lock); return sprintf(buf, "%u\n", temp); } static SENSOR_DEVICE_ATTR(temp1_input, 0444, bnxt_show_temp, NULL, 0); static struct attribute *bnxt_attrs[] = { &sensor_dev_attr_temp1_input.dev_attr.attr, NULL }; ATTRIBUTE_GROUPS(bnxt); static void bnxt_hwmon_close(struct bnxt *bp) { if (bp->hwmon_dev) { hwmon_device_unregister(bp->hwmon_dev); bp->hwmon_dev = NULL; } } static void bnxt_hwmon_open(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; if (bp->hwmon_dev) return; bp->hwmon_dev = hwmon_device_register_with_groups(&pdev->dev, DRV_MODULE_NAME, bp, bnxt_groups); if (IS_ERR(bp->hwmon_dev)) { bp->hwmon_dev = NULL; dev_warn(&pdev->dev, "Cannot register hwmon device\n"); } } #else static void bnxt_hwmon_close(struct bnxt *bp) { } static void bnxt_hwmon_open(struct bnxt *bp) { } #endif static bool bnxt_eee_config_ok(struct bnxt *bp) { struct ethtool_eee *eee = &bp->eee; struct bnxt_link_info *link_info = &bp->link_info; if (!(bp->flags & BNXT_FLAG_EEE_CAP)) return true; if (eee->eee_enabled) { u32 advertising = _bnxt_fw_to_ethtool_adv_spds(link_info->advertising, 0); if (!(link_info->autoneg & BNXT_AUTONEG_SPEED)) { eee->eee_enabled = 0; return false; } if (eee->advertised & ~advertising) { eee->advertised = advertising & eee->supported; return false; } } return true; } static int bnxt_update_phy_setting(struct bnxt *bp) { int rc; bool update_link = false; bool update_pause = false; bool update_eee = false; struct bnxt_link_info *link_info = &bp->link_info; rc = bnxt_update_link(bp, true); if (rc) { netdev_err(bp->dev, "failed to update link (rc: %x)\n", rc); return rc; } if (!BNXT_SINGLE_PF(bp)) return 0; if ((link_info->autoneg & BNXT_AUTONEG_FLOW_CTRL) && (link_info->auto_pause_setting & BNXT_LINK_PAUSE_BOTH) != link_info->req_flow_ctrl) update_pause = true; if (!(link_info->autoneg & BNXT_AUTONEG_FLOW_CTRL) && link_info->force_pause_setting != link_info->req_flow_ctrl) update_pause = true; if (!(link_info->autoneg & BNXT_AUTONEG_SPEED)) { if (BNXT_AUTO_MODE(link_info->auto_mode)) update_link = true; if (link_info->req_link_speed != link_info->force_link_speed) update_link = true; if (link_info->req_duplex != link_info->duplex_setting) update_link = true; } else { if (link_info->auto_mode == BNXT_LINK_AUTO_NONE) update_link = true; if (link_info->advertising != link_info->auto_link_speeds) update_link = true; } /* The last close may have shutdown the link, so need to call * PHY_CFG to bring it back up. */ if (!bp->link_info.link_up) update_link = true; if (!bnxt_eee_config_ok(bp)) update_eee = true; if (update_link) rc = bnxt_hwrm_set_link_setting(bp, update_pause, update_eee); else if (update_pause) rc = bnxt_hwrm_set_pause(bp); if (rc) { netdev_err(bp->dev, "failed to update phy setting (rc: %x)\n", rc); return rc; } return rc; } /* Common routine to pre-map certain register block to different GRC window. * A PF has 16 4K windows and a VF has 4 4K windows. However, only 15 windows * in PF and 3 windows in VF that can be customized to map in different * register blocks. */ static void bnxt_preset_reg_win(struct bnxt *bp) { if (BNXT_PF(bp)) { /* CAG registers map to GRC window #4 */ writel(BNXT_CAG_REG_BASE, bp->bar0 + BNXT_GRCPF_REG_WINDOW_BASE_OUT + 12); } } static int bnxt_init_dflt_ring_mode(struct bnxt *bp); static int __bnxt_open_nic(struct bnxt *bp, bool irq_re_init, bool link_re_init) { int rc = 0; bnxt_preset_reg_win(bp); netif_carrier_off(bp->dev); if (irq_re_init) { /* Reserve rings now if none were reserved at driver probe. */ rc = bnxt_init_dflt_ring_mode(bp); if (rc) { netdev_err(bp->dev, "Failed to reserve default rings at open\n"); return rc; } } rc = bnxt_reserve_rings(bp, irq_re_init); if (rc) return rc; if ((bp->flags & BNXT_FLAG_RFS) && !(bp->flags & BNXT_FLAG_USING_MSIX)) { /* disable RFS if falling back to INTA */ bp->dev->hw_features &= ~NETIF_F_NTUPLE; bp->flags &= ~BNXT_FLAG_RFS; } rc = bnxt_alloc_mem(bp, irq_re_init); if (rc) { netdev_err(bp->dev, "bnxt_alloc_mem err: %x\n", rc); goto open_err_free_mem; } if (irq_re_init) { bnxt_init_napi(bp); rc = bnxt_request_irq(bp); if (rc) { netdev_err(bp->dev, "bnxt_request_irq err: %x\n", rc); goto open_err_irq; } } bnxt_enable_napi(bp); bnxt_debug_dev_init(bp); rc = bnxt_init_nic(bp, irq_re_init); if (rc) { netdev_err(bp->dev, "bnxt_init_nic err: %x\n", rc); goto open_err; } if (link_re_init) { mutex_lock(&bp->link_lock); rc = bnxt_update_phy_setting(bp); mutex_unlock(&bp->link_lock); if (rc) { netdev_warn(bp->dev, "failed to update phy settings\n"); if (BNXT_SINGLE_PF(bp)) { bp->link_info.phy_retry = true; bp->link_info.phy_retry_expires = jiffies + 5 * HZ; } } } if (irq_re_init) udp_tunnel_get_rx_info(bp->dev); set_bit(BNXT_STATE_OPEN, &bp->state); bnxt_enable_int(bp); /* Enable TX queues */ bnxt_tx_enable(bp); mod_timer(&bp->timer, jiffies + bp->current_interval); /* Poll link status and check for SFP+ module status */ bnxt_get_port_module_status(bp); /* VF-reps may need to be re-opened after the PF is re-opened */ if (BNXT_PF(bp)) bnxt_vf_reps_open(bp); return 0; open_err: bnxt_debug_dev_exit(bp); bnxt_disable_napi(bp); open_err_irq: bnxt_del_napi(bp); open_err_free_mem: bnxt_free_skbs(bp); bnxt_free_irq(bp); bnxt_free_mem(bp, true); return rc; } /* rtnl_lock held */ int bnxt_open_nic(struct bnxt *bp, bool irq_re_init, bool link_re_init) { int rc = 0; rc = __bnxt_open_nic(bp, irq_re_init, link_re_init); if (rc) { netdev_err(bp->dev, "nic open fail (rc: %x)\n", rc); dev_close(bp->dev); } return rc; } /* rtnl_lock held, open the NIC half way by allocating all resources, but * NAPI, IRQ, and TX are not enabled. This is mainly used for offline * self tests. */ int bnxt_half_open_nic(struct bnxt *bp) { int rc = 0; rc = bnxt_alloc_mem(bp, false); if (rc) { netdev_err(bp->dev, "bnxt_alloc_mem err: %x\n", rc); goto half_open_err; } rc = bnxt_init_nic(bp, false); if (rc) { netdev_err(bp->dev, "bnxt_init_nic err: %x\n", rc); goto half_open_err; } return 0; half_open_err: bnxt_free_skbs(bp); bnxt_free_mem(bp, false); dev_close(bp->dev); return rc; } /* rtnl_lock held, this call can only be made after a previous successful * call to bnxt_half_open_nic(). */ void bnxt_half_close_nic(struct bnxt *bp) { bnxt_hwrm_resource_free(bp, false, false); bnxt_free_skbs(bp); bnxt_free_mem(bp, false); } static void bnxt_reenable_sriov(struct bnxt *bp) { if (BNXT_PF(bp)) { struct bnxt_pf_info *pf = &bp->pf; int n = pf->active_vfs; if (n) bnxt_cfg_hw_sriov(bp, &n, true); } } static int bnxt_open(struct net_device *dev) { struct bnxt *bp = netdev_priv(dev); int rc; if (test_bit(BNXT_STATE_ABORT_ERR, &bp->state)) { netdev_err(bp->dev, "A previous firmware reset did not complete, aborting\n"); return -ENODEV; } rc = bnxt_hwrm_if_change(bp, true); if (rc) return rc; rc = __bnxt_open_nic(bp, true, true); if (rc) { bnxt_hwrm_if_change(bp, false); } else { if (test_and_clear_bit(BNXT_STATE_FW_RESET_DET, &bp->state)) { if (!test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) { bnxt_ulp_start(bp, 0); bnxt_reenable_sriov(bp); } } bnxt_hwmon_open(bp); } return rc; } static bool bnxt_drv_busy(struct bnxt *bp) { return (test_bit(BNXT_STATE_IN_SP_TASK, &bp->state) || test_bit(BNXT_STATE_READ_STATS, &bp->state)); } static void bnxt_get_ring_stats(struct bnxt *bp, struct rtnl_link_stats64 *stats); static void __bnxt_close_nic(struct bnxt *bp, bool irq_re_init, bool link_re_init) { /* Close the VF-reps before closing PF */ if (BNXT_PF(bp)) bnxt_vf_reps_close(bp); /* Change device state to avoid TX queue wake up's */ bnxt_tx_disable(bp); clear_bit(BNXT_STATE_OPEN, &bp->state); smp_mb__after_atomic(); while (bnxt_drv_busy(bp)) msleep(20); /* Flush rings and and disable interrupts */ bnxt_shutdown_nic(bp, irq_re_init); /* TODO CHIMP_FW: Link/PHY related cleanup if (link_re_init) */ bnxt_debug_dev_exit(bp); bnxt_disable_napi(bp); del_timer_sync(&bp->timer); bnxt_free_skbs(bp); /* Save ring stats before shutdown */ if (bp->bnapi && irq_re_init) bnxt_get_ring_stats(bp, &bp->net_stats_prev); if (irq_re_init) { bnxt_free_irq(bp); bnxt_del_napi(bp); } bnxt_free_mem(bp, irq_re_init); } int bnxt_close_nic(struct bnxt *bp, bool irq_re_init, bool link_re_init) { int rc = 0; if (test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) { /* If we get here, it means firmware reset is in progress * while we are trying to close. We can safely proceed with * the close because we are holding rtnl_lock(). Some firmware * messages may fail as we proceed to close. We set the * ABORT_ERR flag here so that the FW reset thread will later * abort when it gets the rtnl_lock() and sees the flag. */ netdev_warn(bp->dev, "FW reset in progress during close, FW reset will be aborted\n"); set_bit(BNXT_STATE_ABORT_ERR, &bp->state); } #ifdef CONFIG_BNXT_SRIOV if (bp->sriov_cfg) { rc = wait_event_interruptible_timeout(bp->sriov_cfg_wait, !bp->sriov_cfg, BNXT_SRIOV_CFG_WAIT_TMO); if (rc) netdev_warn(bp->dev, "timeout waiting for SRIOV config operation to complete!\n"); } #endif __bnxt_close_nic(bp, irq_re_init, link_re_init); return rc; } static int bnxt_close(struct net_device *dev) { struct bnxt *bp = netdev_priv(dev); bnxt_hwmon_close(bp); bnxt_close_nic(bp, true, true); bnxt_hwrm_shutdown_link(bp); bnxt_hwrm_if_change(bp, false); return 0; } static int bnxt_hwrm_port_phy_read(struct bnxt *bp, u16 phy_addr, u16 reg, u16 *val) { struct hwrm_port_phy_mdio_read_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_port_phy_mdio_read_input req = {0}; int rc; if (bp->hwrm_spec_code < 0x10a00) return -EOPNOTSUPP; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_MDIO_READ, -1, -1); req.port_id = cpu_to_le16(bp->pf.port_id); req.phy_addr = phy_addr; req.reg_addr = cpu_to_le16(reg & 0x1f); if (mdio_phy_id_is_c45(phy_addr)) { req.cl45_mdio = 1; req.phy_addr = mdio_phy_id_prtad(phy_addr); req.dev_addr = mdio_phy_id_devad(phy_addr); req.reg_addr = cpu_to_le16(reg); } mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) *val = le16_to_cpu(resp->reg_data); mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static int bnxt_hwrm_port_phy_write(struct bnxt *bp, u16 phy_addr, u16 reg, u16 val) { struct hwrm_port_phy_mdio_write_input req = {0}; if (bp->hwrm_spec_code < 0x10a00) return -EOPNOTSUPP; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_PORT_PHY_MDIO_WRITE, -1, -1); req.port_id = cpu_to_le16(bp->pf.port_id); req.phy_addr = phy_addr; req.reg_addr = cpu_to_le16(reg & 0x1f); if (mdio_phy_id_is_c45(phy_addr)) { req.cl45_mdio = 1; req.phy_addr = mdio_phy_id_prtad(phy_addr); req.dev_addr = mdio_phy_id_devad(phy_addr); req.reg_addr = cpu_to_le16(reg); } req.reg_data = cpu_to_le16(val); return hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } /* rtnl_lock held */ static int bnxt_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct mii_ioctl_data *mdio = if_mii(ifr); struct bnxt *bp = netdev_priv(dev); int rc; switch (cmd) { case SIOCGMIIPHY: mdio->phy_id = bp->link_info.phy_addr; /* fallthru */ case SIOCGMIIREG: { u16 mii_regval = 0; if (!netif_running(dev)) return -EAGAIN; rc = bnxt_hwrm_port_phy_read(bp, mdio->phy_id, mdio->reg_num, &mii_regval); mdio->val_out = mii_regval; return rc; } case SIOCSMIIREG: if (!netif_running(dev)) return -EAGAIN; return bnxt_hwrm_port_phy_write(bp, mdio->phy_id, mdio->reg_num, mdio->val_in); default: /* do nothing */ break; } return -EOPNOTSUPP; } static void bnxt_get_ring_stats(struct bnxt *bp, struct rtnl_link_stats64 *stats) { int i; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; struct ctx_hw_stats *hw_stats = cpr->hw_stats; stats->rx_packets += le64_to_cpu(hw_stats->rx_ucast_pkts); stats->rx_packets += le64_to_cpu(hw_stats->rx_mcast_pkts); stats->rx_packets += le64_to_cpu(hw_stats->rx_bcast_pkts); stats->tx_packets += le64_to_cpu(hw_stats->tx_ucast_pkts); stats->tx_packets += le64_to_cpu(hw_stats->tx_mcast_pkts); stats->tx_packets += le64_to_cpu(hw_stats->tx_bcast_pkts); stats->rx_bytes += le64_to_cpu(hw_stats->rx_ucast_bytes); stats->rx_bytes += le64_to_cpu(hw_stats->rx_mcast_bytes); stats->rx_bytes += le64_to_cpu(hw_stats->rx_bcast_bytes); stats->tx_bytes += le64_to_cpu(hw_stats->tx_ucast_bytes); stats->tx_bytes += le64_to_cpu(hw_stats->tx_mcast_bytes); stats->tx_bytes += le64_to_cpu(hw_stats->tx_bcast_bytes); stats->rx_missed_errors += le64_to_cpu(hw_stats->rx_discard_pkts); stats->multicast += le64_to_cpu(hw_stats->rx_mcast_pkts); stats->tx_dropped += le64_to_cpu(hw_stats->tx_drop_pkts); } } static void bnxt_add_prev_stats(struct bnxt *bp, struct rtnl_link_stats64 *stats) { struct rtnl_link_stats64 *prev_stats = &bp->net_stats_prev; stats->rx_packets += prev_stats->rx_packets; stats->tx_packets += prev_stats->tx_packets; stats->rx_bytes += prev_stats->rx_bytes; stats->tx_bytes += prev_stats->tx_bytes; stats->rx_missed_errors += prev_stats->rx_missed_errors; stats->multicast += prev_stats->multicast; stats->tx_dropped += prev_stats->tx_dropped; } static void bnxt_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct bnxt *bp = netdev_priv(dev); set_bit(BNXT_STATE_READ_STATS, &bp->state); /* Make sure bnxt_close_nic() sees that we are reading stats before * we check the BNXT_STATE_OPEN flag. */ smp_mb__after_atomic(); if (!test_bit(BNXT_STATE_OPEN, &bp->state)) { clear_bit(BNXT_STATE_READ_STATS, &bp->state); *stats = bp->net_stats_prev; return; } bnxt_get_ring_stats(bp, stats); bnxt_add_prev_stats(bp, stats); if (bp->flags & BNXT_FLAG_PORT_STATS) { struct rx_port_stats *rx = bp->hw_rx_port_stats; struct tx_port_stats *tx = bp->hw_tx_port_stats; stats->rx_crc_errors = le64_to_cpu(rx->rx_fcs_err_frames); stats->rx_frame_errors = le64_to_cpu(rx->rx_align_err_frames); stats->rx_length_errors = le64_to_cpu(rx->rx_undrsz_frames) + le64_to_cpu(rx->rx_ovrsz_frames) + le64_to_cpu(rx->rx_runt_frames); stats->rx_errors = le64_to_cpu(rx->rx_false_carrier_frames) + le64_to_cpu(rx->rx_jbr_frames); stats->collisions = le64_to_cpu(tx->tx_total_collisions); stats->tx_fifo_errors = le64_to_cpu(tx->tx_fifo_underruns); stats->tx_errors = le64_to_cpu(tx->tx_err); } clear_bit(BNXT_STATE_READ_STATS, &bp->state); } static bool bnxt_mc_list_updated(struct bnxt *bp, u32 *rx_mask) { struct net_device *dev = bp->dev; struct bnxt_vnic_info *vnic = &bp->vnic_info[0]; struct netdev_hw_addr *ha; u8 *haddr; int mc_count = 0; bool update = false; int off = 0; netdev_for_each_mc_addr(ha, dev) { if (mc_count >= BNXT_MAX_MC_ADDRS) { *rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_ALL_MCAST; vnic->mc_list_count = 0; return false; } haddr = ha->addr; if (!ether_addr_equal(haddr, vnic->mc_list + off)) { memcpy(vnic->mc_list + off, haddr, ETH_ALEN); update = true; } off += ETH_ALEN; mc_count++; } if (mc_count) *rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_MCAST; if (mc_count != vnic->mc_list_count) { vnic->mc_list_count = mc_count; update = true; } return update; } static bool bnxt_uc_list_updated(struct bnxt *bp) { struct net_device *dev = bp->dev; struct bnxt_vnic_info *vnic = &bp->vnic_info[0]; struct netdev_hw_addr *ha; int off = 0; if (netdev_uc_count(dev) != (vnic->uc_filter_count - 1)) return true; netdev_for_each_uc_addr(ha, dev) { if (!ether_addr_equal(ha->addr, vnic->uc_list + off)) return true; off += ETH_ALEN; } return false; } static void bnxt_set_rx_mode(struct net_device *dev) { struct bnxt *bp = netdev_priv(dev); struct bnxt_vnic_info *vnic; bool mc_update = false; bool uc_update; u32 mask; if (!test_bit(BNXT_STATE_OPEN, &bp->state)) return; vnic = &bp->vnic_info[0]; mask = vnic->rx_mask; mask &= ~(CFA_L2_SET_RX_MASK_REQ_MASK_PROMISCUOUS | CFA_L2_SET_RX_MASK_REQ_MASK_MCAST | CFA_L2_SET_RX_MASK_REQ_MASK_ALL_MCAST | CFA_L2_SET_RX_MASK_REQ_MASK_BCAST); if ((dev->flags & IFF_PROMISC) && bnxt_promisc_ok(bp)) mask |= CFA_L2_SET_RX_MASK_REQ_MASK_PROMISCUOUS; uc_update = bnxt_uc_list_updated(bp); if (dev->flags & IFF_BROADCAST) mask |= CFA_L2_SET_RX_MASK_REQ_MASK_BCAST; if (dev->flags & IFF_ALLMULTI) { mask |= CFA_L2_SET_RX_MASK_REQ_MASK_ALL_MCAST; vnic->mc_list_count = 0; } else { mc_update = bnxt_mc_list_updated(bp, &mask); } if (mask != vnic->rx_mask || uc_update || mc_update) { vnic->rx_mask = mask; set_bit(BNXT_RX_MASK_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } } static int bnxt_cfg_rx_mode(struct bnxt *bp) { struct net_device *dev = bp->dev; struct bnxt_vnic_info *vnic = &bp->vnic_info[0]; struct netdev_hw_addr *ha; int i, off = 0, rc; bool uc_update; netif_addr_lock_bh(dev); uc_update = bnxt_uc_list_updated(bp); netif_addr_unlock_bh(dev); if (!uc_update) goto skip_uc; mutex_lock(&bp->hwrm_cmd_lock); for (i = 1; i < vnic->uc_filter_count; i++) { struct hwrm_cfa_l2_filter_free_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_CFA_L2_FILTER_FREE, -1, -1); req.l2_filter_id = vnic->fw_l2_filter_id[i]; rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); } mutex_unlock(&bp->hwrm_cmd_lock); vnic->uc_filter_count = 1; netif_addr_lock_bh(dev); if (netdev_uc_count(dev) > (BNXT_MAX_UC_ADDRS - 1)) { vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_PROMISCUOUS; } else { netdev_for_each_uc_addr(ha, dev) { memcpy(vnic->uc_list + off, ha->addr, ETH_ALEN); off += ETH_ALEN; vnic->uc_filter_count++; } } netif_addr_unlock_bh(dev); for (i = 1, off = 0; i < vnic->uc_filter_count; i++, off += ETH_ALEN) { rc = bnxt_hwrm_set_vnic_filter(bp, 0, i, vnic->uc_list + off); if (rc) { netdev_err(bp->dev, "HWRM vnic filter failure rc: %x\n", rc); vnic->uc_filter_count = i; return rc; } } skip_uc: rc = bnxt_hwrm_cfa_l2_set_rx_mask(bp, 0); if (rc && vnic->mc_list_count) { netdev_info(bp->dev, "Failed setting MC filters rc: %d, turning on ALL_MCAST mode\n", rc); vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_ALL_MCAST; vnic->mc_list_count = 0; rc = bnxt_hwrm_cfa_l2_set_rx_mask(bp, 0); } if (rc) netdev_err(bp->dev, "HWRM cfa l2 rx mask failure rc: %d\n", rc); return rc; } static bool bnxt_can_reserve_rings(struct bnxt *bp) { #ifdef CONFIG_BNXT_SRIOV if (BNXT_NEW_RM(bp) && BNXT_VF(bp)) { struct bnxt_hw_resc *hw_resc = &bp->hw_resc; /* No minimum rings were provisioned by the PF. Don't * reserve rings by default when device is down. */ if (hw_resc->min_tx_rings || hw_resc->resv_tx_rings) return true; if (!netif_running(bp->dev)) return false; } #endif return true; } /* If the chip and firmware supports RFS */ static bool bnxt_rfs_supported(struct bnxt *bp) { if (bp->flags & BNXT_FLAG_CHIP_P5) { if (bp->fw_cap & BNXT_FW_CAP_CFA_RFS_RING_TBL_IDX_V2) return true; return false; } if (BNXT_PF(bp) && !BNXT_CHIP_TYPE_NITRO_A0(bp)) return true; if (bp->flags & BNXT_FLAG_NEW_RSS_CAP) return true; return false; } /* If runtime conditions support RFS */ static bool bnxt_rfs_capable(struct bnxt *bp) { #ifdef CONFIG_RFS_ACCEL int vnics, max_vnics, max_rss_ctxs; if (bp->flags & BNXT_FLAG_CHIP_P5) return bnxt_rfs_supported(bp); if (!(bp->flags & BNXT_FLAG_MSIX_CAP) || !bnxt_can_reserve_rings(bp)) return false; vnics = 1 + bp->rx_nr_rings; max_vnics = bnxt_get_max_func_vnics(bp); max_rss_ctxs = bnxt_get_max_func_rss_ctxs(bp); /* RSS contexts not a limiting factor */ if (bp->flags & BNXT_FLAG_NEW_RSS_CAP) max_rss_ctxs = max_vnics; if (vnics > max_vnics || vnics > max_rss_ctxs) { if (bp->rx_nr_rings > 1) netdev_warn(bp->dev, "Not enough resources to support NTUPLE filters, enough resources for up to %d rx rings\n", min(max_rss_ctxs - 1, max_vnics - 1)); return false; } if (!BNXT_NEW_RM(bp)) return true; if (vnics == bp->hw_resc.resv_vnics) return true; bnxt_hwrm_reserve_rings(bp, 0, 0, 0, 0, 0, vnics); if (vnics <= bp->hw_resc.resv_vnics) return true; netdev_warn(bp->dev, "Unable to reserve resources to support NTUPLE filters.\n"); bnxt_hwrm_reserve_rings(bp, 0, 0, 0, 0, 0, 1); return false; #else return false; #endif } static netdev_features_t bnxt_fix_features(struct net_device *dev, netdev_features_t features) { struct bnxt *bp = netdev_priv(dev); netdev_features_t vlan_features; if ((features & NETIF_F_NTUPLE) && !bnxt_rfs_capable(bp)) features &= ~NETIF_F_NTUPLE; if (bp->flags & BNXT_FLAG_NO_AGG_RINGS) features &= ~(NETIF_F_LRO | NETIF_F_GRO_HW); if (!(features & NETIF_F_GRO)) features &= ~NETIF_F_GRO_HW; if (features & NETIF_F_GRO_HW) features &= ~NETIF_F_LRO; /* Both CTAG and STAG VLAN accelaration on the RX side have to be * turned on or off together. */ vlan_features = features & (NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX); if (vlan_features != (NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX)) { if (dev->features & NETIF_F_HW_VLAN_CTAG_RX) features &= ~(NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX); else if (vlan_features) features |= NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX; } #ifdef CONFIG_BNXT_SRIOV if (BNXT_VF(bp)) { if (bp->vf.vlan) { features &= ~(NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX); } } #endif return features; } static int bnxt_set_features(struct net_device *dev, netdev_features_t features) { struct bnxt *bp = netdev_priv(dev); u32 flags = bp->flags; u32 changes; int rc = 0; bool re_init = false; bool update_tpa = false; flags &= ~BNXT_FLAG_ALL_CONFIG_FEATS; if (features & NETIF_F_GRO_HW) flags |= BNXT_FLAG_GRO; else if (features & NETIF_F_LRO) flags |= BNXT_FLAG_LRO; if (bp->flags & BNXT_FLAG_NO_AGG_RINGS) flags &= ~BNXT_FLAG_TPA; if (features & NETIF_F_HW_VLAN_CTAG_RX) flags |= BNXT_FLAG_STRIP_VLAN; if (features & NETIF_F_NTUPLE) flags |= BNXT_FLAG_RFS; changes = flags ^ bp->flags; if (changes & BNXT_FLAG_TPA) { update_tpa = true; if ((bp->flags & BNXT_FLAG_TPA) == 0 || (flags & BNXT_FLAG_TPA) == 0 || (bp->flags & BNXT_FLAG_CHIP_P5)) re_init = true; } if (changes & ~BNXT_FLAG_TPA) re_init = true; if (flags != bp->flags) { u32 old_flags = bp->flags; if (!test_bit(BNXT_STATE_OPEN, &bp->state)) { bp->flags = flags; if (update_tpa) bnxt_set_ring_params(bp); return rc; } if (re_init) { bnxt_close_nic(bp, false, false); bp->flags = flags; if (update_tpa) bnxt_set_ring_params(bp); return bnxt_open_nic(bp, false, false); } if (update_tpa) { bp->flags = flags; rc = bnxt_set_tpa(bp, (flags & BNXT_FLAG_TPA) ? true : false); if (rc) bp->flags = old_flags; } } return rc; } static int bnxt_dbg_hwrm_ring_info_get(struct bnxt *bp, u8 ring_type, u32 ring_id, u32 *prod, u32 *cons) { struct hwrm_dbg_ring_info_get_output *resp = bp->hwrm_cmd_resp_addr; struct hwrm_dbg_ring_info_get_input req = {0}; int rc; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_DBG_RING_INFO_GET, -1, -1); req.ring_type = ring_type; req.fw_ring_id = cpu_to_le32(ring_id); mutex_lock(&bp->hwrm_cmd_lock); rc = _hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (!rc) { *prod = le32_to_cpu(resp->producer_index); *cons = le32_to_cpu(resp->consumer_index); } mutex_unlock(&bp->hwrm_cmd_lock); return rc; } static void bnxt_dump_tx_sw_state(struct bnxt_napi *bnapi) { struct bnxt_tx_ring_info *txr = bnapi->tx_ring; int i = bnapi->index; if (!txr) return; netdev_info(bnapi->bp->dev, "[%d]: tx{fw_ring: %d prod: %x cons: %x}\n", i, txr->tx_ring_struct.fw_ring_id, txr->tx_prod, txr->tx_cons); } static void bnxt_dump_rx_sw_state(struct bnxt_napi *bnapi) { struct bnxt_rx_ring_info *rxr = bnapi->rx_ring; int i = bnapi->index; if (!rxr) return; netdev_info(bnapi->bp->dev, "[%d]: rx{fw_ring: %d prod: %x} rx_agg{fw_ring: %d agg_prod: %x sw_agg_prod: %x}\n", i, rxr->rx_ring_struct.fw_ring_id, rxr->rx_prod, rxr->rx_agg_ring_struct.fw_ring_id, rxr->rx_agg_prod, rxr->rx_sw_agg_prod); } static void bnxt_dump_cp_sw_state(struct bnxt_napi *bnapi) { struct bnxt_cp_ring_info *cpr = &bnapi->cp_ring; int i = bnapi->index; netdev_info(bnapi->bp->dev, "[%d]: cp{fw_ring: %d raw_cons: %x}\n", i, cpr->cp_ring_struct.fw_ring_id, cpr->cp_raw_cons); } static void bnxt_dbg_dump_states(struct bnxt *bp) { int i; struct bnxt_napi *bnapi; for (i = 0; i < bp->cp_nr_rings; i++) { bnapi = bp->bnapi[i]; if (netif_msg_drv(bp)) { bnxt_dump_tx_sw_state(bnapi); bnxt_dump_rx_sw_state(bnapi); bnxt_dump_cp_sw_state(bnapi); } } } static void bnxt_reset_task(struct bnxt *bp, bool silent) { if (!silent) bnxt_dbg_dump_states(bp); if (netif_running(bp->dev)) { int rc; if (silent) { bnxt_close_nic(bp, false, false); bnxt_open_nic(bp, false, false); } else { bnxt_ulp_stop(bp); bnxt_close_nic(bp, true, false); rc = bnxt_open_nic(bp, true, false); bnxt_ulp_start(bp, rc); } } } static void bnxt_tx_timeout(struct net_device *dev, unsigned int txqueue) { struct bnxt *bp = netdev_priv(dev); netdev_err(bp->dev, "TX timeout detected, starting reset task!\n"); set_bit(BNXT_RESET_TASK_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } static void bnxt_fw_health_check(struct bnxt *bp) { struct bnxt_fw_health *fw_health = bp->fw_health; u32 val; if (!fw_health->enabled || test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) return; if (fw_health->tmr_counter) { fw_health->tmr_counter--; return; } val = bnxt_fw_health_readl(bp, BNXT_FW_HEARTBEAT_REG); if (val == fw_health->last_fw_heartbeat) goto fw_reset; fw_health->last_fw_heartbeat = val; val = bnxt_fw_health_readl(bp, BNXT_FW_RESET_CNT_REG); if (val != fw_health->last_fw_reset_cnt) goto fw_reset; fw_health->tmr_counter = fw_health->tmr_multiplier; return; fw_reset: set_bit(BNXT_FW_EXCEPTION_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } static void bnxt_timer(struct timer_list *t) { struct bnxt *bp = from_timer(bp, t, timer); struct net_device *dev = bp->dev; if (!netif_running(dev) || !test_bit(BNXT_STATE_OPEN, &bp->state)) return; if (atomic_read(&bp->intr_sem) != 0) goto bnxt_restart_timer; if (bp->fw_cap & BNXT_FW_CAP_ERROR_RECOVERY) bnxt_fw_health_check(bp); if (bp->link_info.link_up && (bp->flags & BNXT_FLAG_PORT_STATS) && bp->stats_coal_ticks) { set_bit(BNXT_PERIODIC_STATS_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } if (bnxt_tc_flower_enabled(bp)) { set_bit(BNXT_FLOW_STATS_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } #ifdef CONFIG_RFS_ACCEL if ((bp->flags & BNXT_FLAG_RFS) && bp->ntp_fltr_count) { set_bit(BNXT_RX_NTP_FLTR_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } #endif /*CONFIG_RFS_ACCEL*/ if (bp->link_info.phy_retry) { if (time_after(jiffies, bp->link_info.phy_retry_expires)) { bp->link_info.phy_retry = false; netdev_warn(bp->dev, "failed to update phy settings after maximum retries.\n"); } else { set_bit(BNXT_UPDATE_PHY_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } } if ((bp->flags & BNXT_FLAG_CHIP_P5) && !bp->chip_rev && netif_carrier_ok(dev)) { set_bit(BNXT_RING_COAL_NOW_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } bnxt_restart_timer: mod_timer(&bp->timer, jiffies + bp->current_interval); } static void bnxt_rtnl_lock_sp(struct bnxt *bp) { /* We are called from bnxt_sp_task which has BNXT_STATE_IN_SP_TASK * set. If the device is being closed, bnxt_close() may be holding * rtnl() and waiting for BNXT_STATE_IN_SP_TASK to clear. So we * must clear BNXT_STATE_IN_SP_TASK before holding rtnl(). */ clear_bit(BNXT_STATE_IN_SP_TASK, &bp->state); rtnl_lock(); } static void bnxt_rtnl_unlock_sp(struct bnxt *bp) { set_bit(BNXT_STATE_IN_SP_TASK, &bp->state); rtnl_unlock(); } /* Only called from bnxt_sp_task() */ static void bnxt_reset(struct bnxt *bp, bool silent) { bnxt_rtnl_lock_sp(bp); if (test_bit(BNXT_STATE_OPEN, &bp->state)) bnxt_reset_task(bp, silent); bnxt_rtnl_unlock_sp(bp); } static void bnxt_fw_reset_close(struct bnxt *bp) { bnxt_ulp_stop(bp); /* When firmware is fatal state, disable PCI device to prevent * any potential bad DMAs before freeing kernel memory. */ if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) pci_disable_device(bp->pdev); __bnxt_close_nic(bp, true, false); bnxt_clear_int_mode(bp); bnxt_hwrm_func_drv_unrgtr(bp); if (pci_is_enabled(bp->pdev)) pci_disable_device(bp->pdev); bnxt_free_ctx_mem(bp); kfree(bp->ctx); bp->ctx = NULL; } static bool is_bnxt_fw_ok(struct bnxt *bp) { struct bnxt_fw_health *fw_health = bp->fw_health; bool no_heartbeat = false, has_reset = false; u32 val; val = bnxt_fw_health_readl(bp, BNXT_FW_HEARTBEAT_REG); if (val == fw_health->last_fw_heartbeat) no_heartbeat = true; val = bnxt_fw_health_readl(bp, BNXT_FW_RESET_CNT_REG); if (val != fw_health->last_fw_reset_cnt) has_reset = true; if (!no_heartbeat && has_reset) return true; return false; } /* rtnl_lock is acquired before calling this function */ static void bnxt_force_fw_reset(struct bnxt *bp) { struct bnxt_fw_health *fw_health = bp->fw_health; u32 wait_dsecs; if (!test_bit(BNXT_STATE_OPEN, &bp->state) || test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) return; set_bit(BNXT_STATE_IN_FW_RESET, &bp->state); bnxt_fw_reset_close(bp); wait_dsecs = fw_health->master_func_wait_dsecs; if (fw_health->master) { if (fw_health->flags & ERROR_RECOVERY_QCFG_RESP_FLAGS_CO_CPU) wait_dsecs = 0; bp->fw_reset_state = BNXT_FW_RESET_STATE_RESET_FW; } else { bp->fw_reset_timestamp = jiffies + wait_dsecs * HZ / 10; wait_dsecs = fw_health->normal_func_wait_dsecs; bp->fw_reset_state = BNXT_FW_RESET_STATE_ENABLE_DEV; } bp->fw_reset_min_dsecs = fw_health->post_reset_wait_dsecs; bp->fw_reset_max_dsecs = fw_health->post_reset_max_wait_dsecs; bnxt_queue_fw_reset_work(bp, wait_dsecs * HZ / 10); } void bnxt_fw_exception(struct bnxt *bp) { netdev_warn(bp->dev, "Detected firmware fatal condition, initiating reset\n"); set_bit(BNXT_STATE_FW_FATAL_COND, &bp->state); bnxt_rtnl_lock_sp(bp); bnxt_force_fw_reset(bp); bnxt_rtnl_unlock_sp(bp); } /* Returns the number of registered VFs, or 1 if VF configuration is pending, or * < 0 on error. */ static int bnxt_get_registered_vfs(struct bnxt *bp) { #ifdef CONFIG_BNXT_SRIOV int rc; if (!BNXT_PF(bp)) return 0; rc = bnxt_hwrm_func_qcfg(bp); if (rc) { netdev_err(bp->dev, "func_qcfg cmd failed, rc = %d\n", rc); return rc; } if (bp->pf.registered_vfs) return bp->pf.registered_vfs; if (bp->sriov_cfg) return 1; #endif return 0; } void bnxt_fw_reset(struct bnxt *bp) { bnxt_rtnl_lock_sp(bp); if (test_bit(BNXT_STATE_OPEN, &bp->state) && !test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) { int n = 0, tmo; set_bit(BNXT_STATE_IN_FW_RESET, &bp->state); if (bp->pf.active_vfs && !test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) n = bnxt_get_registered_vfs(bp); if (n < 0) { netdev_err(bp->dev, "Firmware reset aborted, rc = %d\n", n); clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state); dev_close(bp->dev); goto fw_reset_exit; } else if (n > 0) { u16 vf_tmo_dsecs = n * 10; if (bp->fw_reset_max_dsecs < vf_tmo_dsecs) bp->fw_reset_max_dsecs = vf_tmo_dsecs; bp->fw_reset_state = BNXT_FW_RESET_STATE_POLL_VF; bnxt_queue_fw_reset_work(bp, HZ / 10); goto fw_reset_exit; } bnxt_fw_reset_close(bp); if (bp->fw_cap & BNXT_FW_CAP_ERR_RECOVER_RELOAD) { bp->fw_reset_state = BNXT_FW_RESET_STATE_POLL_FW_DOWN; tmo = HZ / 10; } else { bp->fw_reset_state = BNXT_FW_RESET_STATE_ENABLE_DEV; tmo = bp->fw_reset_min_dsecs * HZ / 10; } bnxt_queue_fw_reset_work(bp, tmo); } fw_reset_exit: bnxt_rtnl_unlock_sp(bp); } static void bnxt_chk_missed_irq(struct bnxt *bp) { int i; if (!(bp->flags & BNXT_FLAG_CHIP_P5)) return; for (i = 0; i < bp->cp_nr_rings; i++) { struct bnxt_napi *bnapi = bp->bnapi[i]; struct bnxt_cp_ring_info *cpr; u32 fw_ring_id; int j; if (!bnapi) continue; cpr = &bnapi->cp_ring; for (j = 0; j < 2; j++) { struct bnxt_cp_ring_info *cpr2 = cpr->cp_ring_arr[j]; u32 val[2]; if (!cpr2 || cpr2->has_more_work || !bnxt_has_work(bp, cpr2)) continue; if (cpr2->cp_raw_cons != cpr2->last_cp_raw_cons) { cpr2->last_cp_raw_cons = cpr2->cp_raw_cons; continue; } fw_ring_id = cpr2->cp_ring_struct.fw_ring_id; bnxt_dbg_hwrm_ring_info_get(bp, DBG_RING_INFO_GET_REQ_RING_TYPE_L2_CMPL, fw_ring_id, &val[0], &val[1]); cpr->sw_stats.cmn.missed_irqs++; } } } static void bnxt_cfg_ntp_filters(struct bnxt *); static void bnxt_init_ethtool_link_settings(struct bnxt *bp) { struct bnxt_link_info *link_info = &bp->link_info; if (BNXT_AUTO_MODE(link_info->auto_mode)) { link_info->autoneg = BNXT_AUTONEG_SPEED; if (bp->hwrm_spec_code >= 0x10201) { if (link_info->auto_pause_setting & PORT_PHY_CFG_REQ_AUTO_PAUSE_AUTONEG_PAUSE) link_info->autoneg |= BNXT_AUTONEG_FLOW_CTRL; } else { link_info->autoneg |= BNXT_AUTONEG_FLOW_CTRL; } link_info->advertising = link_info->auto_link_speeds; } else { link_info->req_link_speed = link_info->force_link_speed; link_info->req_duplex = link_info->duplex_setting; } if (link_info->autoneg & BNXT_AUTONEG_FLOW_CTRL) link_info->req_flow_ctrl = link_info->auto_pause_setting & BNXT_LINK_PAUSE_BOTH; else link_info->req_flow_ctrl = link_info->force_pause_setting; } static void bnxt_sp_task(struct work_struct *work) { struct bnxt *bp = container_of(work, struct bnxt, sp_task); set_bit(BNXT_STATE_IN_SP_TASK, &bp->state); smp_mb__after_atomic(); if (!test_bit(BNXT_STATE_OPEN, &bp->state)) { clear_bit(BNXT_STATE_IN_SP_TASK, &bp->state); return; } if (test_and_clear_bit(BNXT_RX_MASK_SP_EVENT, &bp->sp_event)) bnxt_cfg_rx_mode(bp); if (test_and_clear_bit(BNXT_RX_NTP_FLTR_SP_EVENT, &bp->sp_event)) bnxt_cfg_ntp_filters(bp); if (test_and_clear_bit(BNXT_HWRM_EXEC_FWD_REQ_SP_EVENT, &bp->sp_event)) bnxt_hwrm_exec_fwd_req(bp); if (test_and_clear_bit(BNXT_VXLAN_ADD_PORT_SP_EVENT, &bp->sp_event)) { bnxt_hwrm_tunnel_dst_port_alloc( bp, bp->vxlan_port, TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_VXLAN); } if (test_and_clear_bit(BNXT_VXLAN_DEL_PORT_SP_EVENT, &bp->sp_event)) { bnxt_hwrm_tunnel_dst_port_free( bp, TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_VXLAN); } if (test_and_clear_bit(BNXT_GENEVE_ADD_PORT_SP_EVENT, &bp->sp_event)) { bnxt_hwrm_tunnel_dst_port_alloc( bp, bp->nge_port, TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_GENEVE); } if (test_and_clear_bit(BNXT_GENEVE_DEL_PORT_SP_EVENT, &bp->sp_event)) { bnxt_hwrm_tunnel_dst_port_free( bp, TUNNEL_DST_PORT_FREE_REQ_TUNNEL_TYPE_GENEVE); } if (test_and_clear_bit(BNXT_PERIODIC_STATS_SP_EVENT, &bp->sp_event)) { bnxt_hwrm_port_qstats(bp); bnxt_hwrm_port_qstats_ext(bp); bnxt_hwrm_pcie_qstats(bp); } if (test_and_clear_bit(BNXT_LINK_CHNG_SP_EVENT, &bp->sp_event)) { int rc; mutex_lock(&bp->link_lock); if (test_and_clear_bit(BNXT_LINK_SPEED_CHNG_SP_EVENT, &bp->sp_event)) bnxt_hwrm_phy_qcaps(bp); if (test_and_clear_bit(BNXT_LINK_CFG_CHANGE_SP_EVENT, &bp->sp_event)) bnxt_init_ethtool_link_settings(bp); rc = bnxt_update_link(bp, true); mutex_unlock(&bp->link_lock); if (rc) netdev_err(bp->dev, "SP task can't update link (rc: %x)\n", rc); } if (test_and_clear_bit(BNXT_UPDATE_PHY_SP_EVENT, &bp->sp_event)) { int rc; mutex_lock(&bp->link_lock); rc = bnxt_update_phy_setting(bp); mutex_unlock(&bp->link_lock); if (rc) { netdev_warn(bp->dev, "update phy settings retry failed\n"); } else { bp->link_info.phy_retry = false; netdev_info(bp->dev, "update phy settings retry succeeded\n"); } } if (test_and_clear_bit(BNXT_HWRM_PORT_MODULE_SP_EVENT, &bp->sp_event)) { mutex_lock(&bp->link_lock); bnxt_get_port_module_status(bp); mutex_unlock(&bp->link_lock); } if (test_and_clear_bit(BNXT_FLOW_STATS_SP_EVENT, &bp->sp_event)) bnxt_tc_flow_stats_work(bp); if (test_and_clear_bit(BNXT_RING_COAL_NOW_SP_EVENT, &bp->sp_event)) bnxt_chk_missed_irq(bp); /* These functions below will clear BNXT_STATE_IN_SP_TASK. They * must be the last functions to be called before exiting. */ if (test_and_clear_bit(BNXT_RESET_TASK_SP_EVENT, &bp->sp_event)) bnxt_reset(bp, false); if (test_and_clear_bit(BNXT_RESET_TASK_SILENT_SP_EVENT, &bp->sp_event)) bnxt_reset(bp, true); if (test_and_clear_bit(BNXT_FW_RESET_NOTIFY_SP_EVENT, &bp->sp_event)) bnxt_devlink_health_report(bp, BNXT_FW_RESET_NOTIFY_SP_EVENT); if (test_and_clear_bit(BNXT_FW_EXCEPTION_SP_EVENT, &bp->sp_event)) { if (!is_bnxt_fw_ok(bp)) bnxt_devlink_health_report(bp, BNXT_FW_EXCEPTION_SP_EVENT); } smp_mb__before_atomic(); clear_bit(BNXT_STATE_IN_SP_TASK, &bp->state); } /* Under rtnl_lock */ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, int tx_xdp) { int max_rx, max_tx, tx_sets = 1; int tx_rings_needed, stats; int rx_rings = rx; int cp, vnics, rc; if (tcs) tx_sets = tcs; rc = bnxt_get_max_rings(bp, &max_rx, &max_tx, sh); if (rc) return rc; if (max_rx < rx) return -ENOMEM; tx_rings_needed = tx * tx_sets + tx_xdp; if (max_tx < tx_rings_needed) return -ENOMEM; vnics = 1; if ((bp->flags & (BNXT_FLAG_RFS | BNXT_FLAG_CHIP_P5)) == BNXT_FLAG_RFS) vnics += rx_rings; if (bp->flags & BNXT_FLAG_AGG_RINGS) rx_rings <<= 1; cp = sh ? max_t(int, tx_rings_needed, rx) : tx_rings_needed + rx; stats = cp; if (BNXT_NEW_RM(bp)) { cp += bnxt_get_ulp_msix_num(bp); stats += bnxt_get_ulp_stat_ctxs(bp); } return bnxt_hwrm_check_rings(bp, tx_rings_needed, rx_rings, rx, cp, stats, vnics); } static void bnxt_unmap_bars(struct bnxt *bp, struct pci_dev *pdev) { if (bp->bar2) { pci_iounmap(pdev, bp->bar2); bp->bar2 = NULL; } if (bp->bar1) { pci_iounmap(pdev, bp->bar1); bp->bar1 = NULL; } if (bp->bar0) { pci_iounmap(pdev, bp->bar0); bp->bar0 = NULL; } } static void bnxt_cleanup_pci(struct bnxt *bp) { bnxt_unmap_bars(bp, bp->pdev); pci_release_regions(bp->pdev); if (pci_is_enabled(bp->pdev)) pci_disable_device(bp->pdev); } static void bnxt_init_dflt_coal(struct bnxt *bp) { struct bnxt_coal *coal; /* Tick values in micro seconds. * 1 coal_buf x bufs_per_record = 1 completion record. */ coal = &bp->rx_coal; coal->coal_ticks = 10; coal->coal_bufs = 30; coal->coal_ticks_irq = 1; coal->coal_bufs_irq = 2; coal->idle_thresh = 50; coal->bufs_per_record = 2; coal->budget = 64; /* NAPI budget */ coal = &bp->tx_coal; coal->coal_ticks = 28; coal->coal_bufs = 30; coal->coal_ticks_irq = 2; coal->coal_bufs_irq = 2; coal->bufs_per_record = 1; bp->stats_coal_ticks = BNXT_DEF_STATS_COAL_TICKS; } static void bnxt_alloc_fw_health(struct bnxt *bp) { if (bp->fw_health) return; if (!(bp->fw_cap & BNXT_FW_CAP_HOT_RESET) && !(bp->fw_cap & BNXT_FW_CAP_ERROR_RECOVERY)) return; bp->fw_health = kzalloc(sizeof(*bp->fw_health), GFP_KERNEL); if (!bp->fw_health) { netdev_warn(bp->dev, "Failed to allocate fw_health\n"); bp->fw_cap &= ~BNXT_FW_CAP_HOT_RESET; bp->fw_cap &= ~BNXT_FW_CAP_ERROR_RECOVERY; } } static int bnxt_fw_init_one_p1(struct bnxt *bp) { int rc; bp->fw_cap = 0; rc = bnxt_hwrm_ver_get(bp); if (rc) return rc; if (bp->fw_cap & BNXT_FW_CAP_KONG_MB_CHNL) { rc = bnxt_alloc_kong_hwrm_resources(bp); if (rc) bp->fw_cap &= ~BNXT_FW_CAP_KONG_MB_CHNL; } if ((bp->fw_cap & BNXT_FW_CAP_SHORT_CMD) || bp->hwrm_max_ext_req_len > BNXT_HWRM_MAX_REQ_LEN) { rc = bnxt_alloc_hwrm_short_cmd_req(bp); if (rc) return rc; } rc = bnxt_hwrm_func_reset(bp); if (rc) return -ENODEV; bnxt_hwrm_fw_set_time(bp); return 0; } static int bnxt_fw_init_one_p2(struct bnxt *bp) { int rc; /* Get the MAX capabilities for this function */ rc = bnxt_hwrm_func_qcaps(bp); if (rc) { netdev_err(bp->dev, "hwrm query capability failure rc: %x\n", rc); return -ENODEV; } rc = bnxt_hwrm_cfa_adv_flow_mgnt_qcaps(bp); if (rc) netdev_warn(bp->dev, "hwrm query adv flow mgnt failure rc: %d\n", rc); bnxt_alloc_fw_health(bp); rc = bnxt_hwrm_error_recovery_qcfg(bp); if (rc) netdev_warn(bp->dev, "hwrm query error recovery failure rc: %d\n", rc); rc = bnxt_hwrm_func_drv_rgtr(bp, NULL, 0, false); if (rc) return -ENODEV; bnxt_hwrm_func_qcfg(bp); bnxt_hwrm_vnic_qcaps(bp); bnxt_hwrm_port_led_qcaps(bp); bnxt_ethtool_init(bp); bnxt_dcb_init(bp); return 0; } static void bnxt_set_dflt_rss_hash_type(struct bnxt *bp) { bp->flags &= ~BNXT_FLAG_UDP_RSS_CAP; bp->rss_hash_cfg = VNIC_RSS_CFG_REQ_HASH_TYPE_IPV4 | VNIC_RSS_CFG_REQ_HASH_TYPE_TCP_IPV4 | VNIC_RSS_CFG_REQ_HASH_TYPE_IPV6 | VNIC_RSS_CFG_REQ_HASH_TYPE_TCP_IPV6; if (BNXT_CHIP_P4_PLUS(bp) && bp->hwrm_spec_code >= 0x10501) { bp->flags |= BNXT_FLAG_UDP_RSS_CAP; bp->rss_hash_cfg |= VNIC_RSS_CFG_REQ_HASH_TYPE_UDP_IPV4 | VNIC_RSS_CFG_REQ_HASH_TYPE_UDP_IPV6; } } static void bnxt_set_dflt_rfs(struct bnxt *bp) { struct net_device *dev = bp->dev; dev->hw_features &= ~NETIF_F_NTUPLE; dev->features &= ~NETIF_F_NTUPLE; bp->flags &= ~BNXT_FLAG_RFS; if (bnxt_rfs_supported(bp)) { dev->hw_features |= NETIF_F_NTUPLE; if (bnxt_rfs_capable(bp)) { bp->flags |= BNXT_FLAG_RFS; dev->features |= NETIF_F_NTUPLE; } } } static void bnxt_fw_init_one_p3(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; bnxt_set_dflt_rss_hash_type(bp); bnxt_set_dflt_rfs(bp); bnxt_get_wol_settings(bp); if (bp->flags & BNXT_FLAG_WOL_CAP) device_set_wakeup_enable(&pdev->dev, bp->wol); else device_set_wakeup_capable(&pdev->dev, false); bnxt_hwrm_set_cache_line_size(bp, cache_line_size()); bnxt_hwrm_coal_params_qcaps(bp); } static int bnxt_fw_init_one(struct bnxt *bp) { int rc; rc = bnxt_fw_init_one_p1(bp); if (rc) { netdev_err(bp->dev, "Firmware init phase 1 failed\n"); return rc; } rc = bnxt_fw_init_one_p2(bp); if (rc) { netdev_err(bp->dev, "Firmware init phase 2 failed\n"); return rc; } rc = bnxt_approve_mac(bp, bp->dev->dev_addr, false); if (rc) return rc; /* In case fw capabilities have changed, destroy the unneeded * reporters and create newly capable ones. */ bnxt_dl_fw_reporters_destroy(bp, false); bnxt_dl_fw_reporters_create(bp); bnxt_fw_init_one_p3(bp); return 0; } static void bnxt_fw_reset_writel(struct bnxt *bp, int reg_idx) { struct bnxt_fw_health *fw_health = bp->fw_health; u32 reg = fw_health->fw_reset_seq_regs[reg_idx]; u32 val = fw_health->fw_reset_seq_vals[reg_idx]; u32 reg_type, reg_off, delay_msecs; delay_msecs = fw_health->fw_reset_seq_delay_msec[reg_idx]; reg_type = BNXT_FW_HEALTH_REG_TYPE(reg); reg_off = BNXT_FW_HEALTH_REG_OFF(reg); switch (reg_type) { case BNXT_FW_HEALTH_REG_TYPE_CFG: pci_write_config_dword(bp->pdev, reg_off, val); break; case BNXT_FW_HEALTH_REG_TYPE_GRC: writel(reg_off & BNXT_GRC_BASE_MASK, bp->bar0 + BNXT_GRCPF_REG_WINDOW_BASE_OUT + 4); reg_off = (reg_off & BNXT_GRC_OFFSET_MASK) + 0x2000; /* fall through */ case BNXT_FW_HEALTH_REG_TYPE_BAR0: writel(val, bp->bar0 + reg_off); break; case BNXT_FW_HEALTH_REG_TYPE_BAR1: writel(val, bp->bar1 + reg_off); break; } if (delay_msecs) { pci_read_config_dword(bp->pdev, 0, &val); msleep(delay_msecs); } } static void bnxt_reset_all(struct bnxt *bp) { struct bnxt_fw_health *fw_health = bp->fw_health; int i, rc; if (bp->fw_cap & BNXT_FW_CAP_ERR_RECOVER_RELOAD) { #ifdef CONFIG_TEE_BNXT_FW rc = tee_bnxt_fw_load(); if (rc) netdev_err(bp->dev, "Unable to reset FW rc=%d\n", rc); bp->fw_reset_timestamp = jiffies; #endif return; } if (fw_health->flags & ERROR_RECOVERY_QCFG_RESP_FLAGS_HOST) { for (i = 0; i < fw_health->fw_reset_seq_cnt; i++) bnxt_fw_reset_writel(bp, i); } else if (fw_health->flags & ERROR_RECOVERY_QCFG_RESP_FLAGS_CO_CPU) { struct hwrm_fw_reset_input req = {0}; bnxt_hwrm_cmd_hdr_init(bp, &req, HWRM_FW_RESET, -1, -1); req.resp_addr = cpu_to_le64(bp->hwrm_cmd_kong_resp_dma_addr); req.embedded_proc_type = FW_RESET_REQ_EMBEDDED_PROC_TYPE_CHIP; req.selfrst_status = FW_RESET_REQ_SELFRST_STATUS_SELFRSTASAP; req.flags = FW_RESET_REQ_FLAGS_RESET_GRACEFUL; rc = hwrm_send_message(bp, &req, sizeof(req), HWRM_CMD_TIMEOUT); if (rc) netdev_warn(bp->dev, "Unable to reset FW rc=%d\n", rc); } bp->fw_reset_timestamp = jiffies; } static void bnxt_fw_reset_task(struct work_struct *work) { struct bnxt *bp = container_of(work, struct bnxt, fw_reset_task.work); int rc; if (!test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) { netdev_err(bp->dev, "bnxt_fw_reset_task() called when not in fw reset mode!\n"); return; } switch (bp->fw_reset_state) { case BNXT_FW_RESET_STATE_POLL_VF: { int n = bnxt_get_registered_vfs(bp); int tmo; if (n < 0) { netdev_err(bp->dev, "Firmware reset aborted, subsequent func_qcfg cmd failed, rc = %d, %d msecs since reset timestamp\n", n, jiffies_to_msecs(jiffies - bp->fw_reset_timestamp)); goto fw_reset_abort; } else if (n > 0) { if (time_after(jiffies, bp->fw_reset_timestamp + (bp->fw_reset_max_dsecs * HZ / 10))) { clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state); bp->fw_reset_state = 0; netdev_err(bp->dev, "Firmware reset aborted, bnxt_get_registered_vfs() returns %d\n", n); return; } bnxt_queue_fw_reset_work(bp, HZ / 10); return; } bp->fw_reset_timestamp = jiffies; rtnl_lock(); bnxt_fw_reset_close(bp); if (bp->fw_cap & BNXT_FW_CAP_ERR_RECOVER_RELOAD) { bp->fw_reset_state = BNXT_FW_RESET_STATE_POLL_FW_DOWN; tmo = HZ / 10; } else { bp->fw_reset_state = BNXT_FW_RESET_STATE_ENABLE_DEV; tmo = bp->fw_reset_min_dsecs * HZ / 10; } rtnl_unlock(); bnxt_queue_fw_reset_work(bp, tmo); return; } case BNXT_FW_RESET_STATE_POLL_FW_DOWN: { u32 val; val = bnxt_fw_health_readl(bp, BNXT_FW_HEALTH_REG); if (!(val & BNXT_FW_STATUS_SHUTDOWN) && !time_after(jiffies, bp->fw_reset_timestamp + (bp->fw_reset_max_dsecs * HZ / 10))) { bnxt_queue_fw_reset_work(bp, HZ / 5); return; } if (!bp->fw_health->master) { u32 wait_dsecs = bp->fw_health->normal_func_wait_dsecs; bp->fw_reset_state = BNXT_FW_RESET_STATE_ENABLE_DEV; bnxt_queue_fw_reset_work(bp, wait_dsecs * HZ / 10); return; } bp->fw_reset_state = BNXT_FW_RESET_STATE_RESET_FW; } /* fall through */ case BNXT_FW_RESET_STATE_RESET_FW: bnxt_reset_all(bp); bp->fw_reset_state = BNXT_FW_RESET_STATE_ENABLE_DEV; bnxt_queue_fw_reset_work(bp, bp->fw_reset_min_dsecs * HZ / 10); return; case BNXT_FW_RESET_STATE_ENABLE_DEV: if (test_bit(BNXT_STATE_FW_FATAL_COND, &bp->state)) { u32 val; val = bnxt_fw_health_readl(bp, BNXT_FW_RESET_INPROG_REG); if (val) netdev_warn(bp->dev, "FW reset inprog %x after min wait time.\n", val); } clear_bit(BNXT_STATE_FW_FATAL_COND, &bp->state); if (pci_enable_device(bp->pdev)) { netdev_err(bp->dev, "Cannot re-enable PCI device\n"); goto fw_reset_abort; } pci_set_master(bp->pdev); bp->fw_reset_state = BNXT_FW_RESET_STATE_POLL_FW; /* fall through */ case BNXT_FW_RESET_STATE_POLL_FW: bp->hwrm_cmd_timeout = SHORT_HWRM_CMD_TIMEOUT; rc = __bnxt_hwrm_ver_get(bp, true); if (rc) { if (time_after(jiffies, bp->fw_reset_timestamp + (bp->fw_reset_max_dsecs * HZ / 10))) { netdev_err(bp->dev, "Firmware reset aborted\n"); goto fw_reset_abort; } bnxt_queue_fw_reset_work(bp, HZ / 5); return; } bp->hwrm_cmd_timeout = DFLT_HWRM_CMD_TIMEOUT; bp->fw_reset_state = BNXT_FW_RESET_STATE_OPENING; /* fall through */ case BNXT_FW_RESET_STATE_OPENING: while (!rtnl_trylock()) { bnxt_queue_fw_reset_work(bp, HZ / 10); return; } rc = bnxt_open(bp->dev); if (rc) { netdev_err(bp->dev, "bnxt_open_nic() failed\n"); clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state); dev_close(bp->dev); } bp->fw_reset_state = 0; /* Make sure fw_reset_state is 0 before clearing the flag */ smp_mb__before_atomic(); clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state); bnxt_ulp_start(bp, rc); if (!rc) bnxt_reenable_sriov(bp); bnxt_dl_health_recovery_done(bp); bnxt_dl_health_status_update(bp, true); rtnl_unlock(); break; } return; fw_reset_abort: clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state); if (bp->fw_reset_state != BNXT_FW_RESET_STATE_POLL_VF) bnxt_dl_health_status_update(bp, false); bp->fw_reset_state = 0; rtnl_lock(); dev_close(bp->dev); rtnl_unlock(); } static int bnxt_init_board(struct pci_dev *pdev, struct net_device *dev) { int rc; struct bnxt *bp = netdev_priv(dev); SET_NETDEV_DEV(dev, &pdev->dev); /* enable device (incl. PCI PM wakeup), and bus-mastering */ rc = pci_enable_device(pdev); if (rc) { dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n"); goto init_err; } if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { dev_err(&pdev->dev, "Cannot find PCI device base address, aborting\n"); rc = -ENODEV; goto init_err_disable; } rc = pci_request_regions(pdev, DRV_MODULE_NAME); if (rc) { dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n"); goto init_err_disable; } if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) != 0 && dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)) != 0) { dev_err(&pdev->dev, "System does not support DMA, aborting\n"); goto init_err_disable; } pci_set_master(pdev); bp->dev = dev; bp->pdev = pdev; /* Doorbell BAR bp->bar1 is mapped after bnxt_fw_init_one_p2() * determines the BAR size. */ bp->bar0 = pci_ioremap_bar(pdev, 0); if (!bp->bar0) { dev_err(&pdev->dev, "Cannot map device registers, aborting\n"); rc = -ENOMEM; goto init_err_release; } bp->bar2 = pci_ioremap_bar(pdev, 4); if (!bp->bar2) { dev_err(&pdev->dev, "Cannot map bar4 registers, aborting\n"); rc = -ENOMEM; goto init_err_release; } pci_enable_pcie_error_reporting(pdev); INIT_WORK(&bp->sp_task, bnxt_sp_task); INIT_DELAYED_WORK(&bp->fw_reset_task, bnxt_fw_reset_task); spin_lock_init(&bp->ntp_fltr_lock); #if BITS_PER_LONG == 32 spin_lock_init(&bp->db_lock); #endif bp->rx_ring_size = BNXT_DEFAULT_RX_RING_SIZE; bp->tx_ring_size = BNXT_DEFAULT_TX_RING_SIZE; bnxt_init_dflt_coal(bp); timer_setup(&bp->timer, bnxt_timer, 0); bp->current_interval = BNXT_TIMER_INTERVAL; clear_bit(BNXT_STATE_OPEN, &bp->state); return 0; init_err_release: bnxt_unmap_bars(bp, pdev); pci_release_regions(pdev); init_err_disable: pci_disable_device(pdev); init_err: return rc; } /* rtnl_lock held */ static int bnxt_change_mac_addr(struct net_device *dev, void *p) { struct sockaddr *addr = p; struct bnxt *bp = netdev_priv(dev); int rc = 0; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; if (ether_addr_equal(addr->sa_data, dev->dev_addr)) return 0; rc = bnxt_approve_mac(bp, addr->sa_data, true); if (rc) return rc; memcpy(dev->dev_addr, addr->sa_data, dev->addr_len); if (netif_running(dev)) { bnxt_close_nic(bp, false, false); rc = bnxt_open_nic(bp, false, false); } return rc; } /* rtnl_lock held */ static int bnxt_change_mtu(struct net_device *dev, int new_mtu) { struct bnxt *bp = netdev_priv(dev); if (netif_running(dev)) bnxt_close_nic(bp, true, false); dev->mtu = new_mtu; bnxt_set_ring_params(bp); if (netif_running(dev)) return bnxt_open_nic(bp, true, false); return 0; } int bnxt_setup_mq_tc(struct net_device *dev, u8 tc) { struct bnxt *bp = netdev_priv(dev); bool sh = false; int rc; if (tc > bp->max_tc) { netdev_err(dev, "Too many traffic classes requested: %d. Max supported is %d.\n", tc, bp->max_tc); return -EINVAL; } if (netdev_get_num_tc(dev) == tc) return 0; if (bp->flags & BNXT_FLAG_SHARED_RINGS) sh = true; rc = bnxt_check_rings(bp, bp->tx_nr_rings_per_tc, bp->rx_nr_rings, sh, tc, bp->tx_nr_rings_xdp); if (rc) return rc; /* Needs to close the device and do hw resource re-allocations */ if (netif_running(bp->dev)) bnxt_close_nic(bp, true, false); if (tc) { bp->tx_nr_rings = bp->tx_nr_rings_per_tc * tc; netdev_set_num_tc(dev, tc); } else { bp->tx_nr_rings = bp->tx_nr_rings_per_tc; netdev_reset_tc(dev); } bp->tx_nr_rings += bp->tx_nr_rings_xdp; bp->cp_nr_rings = sh ? max_t(int, bp->tx_nr_rings, bp->rx_nr_rings) : bp->tx_nr_rings + bp->rx_nr_rings; if (netif_running(bp->dev)) return bnxt_open_nic(bp, true, false); return 0; } static int bnxt_setup_tc_block_cb(enum tc_setup_type type, void *type_data, void *cb_priv) { struct bnxt *bp = cb_priv; if (!bnxt_tc_flower_enabled(bp) || !tc_cls_can_offload_and_chain0(bp->dev, type_data)) return -EOPNOTSUPP; switch (type) { case TC_SETUP_CLSFLOWER: return bnxt_tc_setup_flower(bp, bp->pf.fw_fid, type_data); default: return -EOPNOTSUPP; } } LIST_HEAD(bnxt_block_cb_list); static int bnxt_setup_tc(struct net_device *dev, enum tc_setup_type type, void *type_data) { struct bnxt *bp = netdev_priv(dev); switch (type) { case TC_SETUP_BLOCK: return flow_block_cb_setup_simple(type_data, &bnxt_block_cb_list, bnxt_setup_tc_block_cb, bp, bp, true); case TC_SETUP_QDISC_MQPRIO: { struct tc_mqprio_qopt *mqprio = type_data; mqprio->hw = TC_MQPRIO_HW_OFFLOAD_TCS; return bnxt_setup_mq_tc(dev, mqprio->num_tc); } default: return -EOPNOTSUPP; } } #ifdef CONFIG_RFS_ACCEL static bool bnxt_fltr_match(struct bnxt_ntuple_filter *f1, struct bnxt_ntuple_filter *f2) { struct flow_keys *keys1 = &f1->fkeys; struct flow_keys *keys2 = &f2->fkeys; if (keys1->basic.n_proto != keys2->basic.n_proto || keys1->basic.ip_proto != keys2->basic.ip_proto) return false; if (keys1->basic.n_proto == htons(ETH_P_IP)) { if (keys1->addrs.v4addrs.src != keys2->addrs.v4addrs.src || keys1->addrs.v4addrs.dst != keys2->addrs.v4addrs.dst) return false; } else { if (memcmp(&keys1->addrs.v6addrs.src, &keys2->addrs.v6addrs.src, sizeof(keys1->addrs.v6addrs.src)) || memcmp(&keys1->addrs.v6addrs.dst, &keys2->addrs.v6addrs.dst, sizeof(keys1->addrs.v6addrs.dst))) return false; } if (keys1->ports.ports == keys2->ports.ports && keys1->control.flags == keys2->control.flags && ether_addr_equal(f1->src_mac_addr, f2->src_mac_addr) && ether_addr_equal(f1->dst_mac_addr, f2->dst_mac_addr)) return true; return false; } static int bnxt_rx_flow_steer(struct net_device *dev, const struct sk_buff *skb, u16 rxq_index, u32 flow_id) { struct bnxt *bp = netdev_priv(dev); struct bnxt_ntuple_filter *fltr, *new_fltr; struct flow_keys *fkeys; struct ethhdr *eth = (struct ethhdr *)skb_mac_header(skb); int rc = 0, idx, bit_id, l2_idx = 0; struct hlist_head *head; u32 flags; if (!ether_addr_equal(dev->dev_addr, eth->h_dest)) { struct bnxt_vnic_info *vnic = &bp->vnic_info[0]; int off = 0, j; netif_addr_lock_bh(dev); for (j = 0; j < vnic->uc_filter_count; j++, off += ETH_ALEN) { if (ether_addr_equal(eth->h_dest, vnic->uc_list + off)) { l2_idx = j + 1; break; } } netif_addr_unlock_bh(dev); if (!l2_idx) return -EINVAL; } new_fltr = kzalloc(sizeof(*new_fltr), GFP_ATOMIC); if (!new_fltr) return -ENOMEM; fkeys = &new_fltr->fkeys; if (!skb_flow_dissect_flow_keys(skb, fkeys, 0)) { rc = -EPROTONOSUPPORT; goto err_free; } if ((fkeys->basic.n_proto != htons(ETH_P_IP) && fkeys->basic.n_proto != htons(ETH_P_IPV6)) || ((fkeys->basic.ip_proto != IPPROTO_TCP) && (fkeys->basic.ip_proto != IPPROTO_UDP))) { rc = -EPROTONOSUPPORT; goto err_free; } if (fkeys->basic.n_proto == htons(ETH_P_IPV6) && bp->hwrm_spec_code < 0x10601) { rc = -EPROTONOSUPPORT; goto err_free; } flags = fkeys->control.flags; if (((flags & FLOW_DIS_ENCAPSULATION) && bp->hwrm_spec_code < 0x10601) || (flags & FLOW_DIS_IS_FRAGMENT)) { rc = -EPROTONOSUPPORT; goto err_free; } memcpy(new_fltr->dst_mac_addr, eth->h_dest, ETH_ALEN); memcpy(new_fltr->src_mac_addr, eth->h_source, ETH_ALEN); idx = skb_get_hash_raw(skb) & BNXT_NTP_FLTR_HASH_MASK; head = &bp->ntp_fltr_hash_tbl[idx]; rcu_read_lock(); hlist_for_each_entry_rcu(fltr, head, hash) { if (bnxt_fltr_match(fltr, new_fltr)) { rcu_read_unlock(); rc = 0; goto err_free; } } rcu_read_unlock(); spin_lock_bh(&bp->ntp_fltr_lock); bit_id = bitmap_find_free_region(bp->ntp_fltr_bmap, BNXT_NTP_FLTR_MAX_FLTR, 0); if (bit_id < 0) { spin_unlock_bh(&bp->ntp_fltr_lock); rc = -ENOMEM; goto err_free; } new_fltr->sw_id = (u16)bit_id; new_fltr->flow_id = flow_id; new_fltr->l2_fltr_idx = l2_idx; new_fltr->rxq = rxq_index; hlist_add_head_rcu(&new_fltr->hash, head); bp->ntp_fltr_count++; spin_unlock_bh(&bp->ntp_fltr_lock); set_bit(BNXT_RX_NTP_FLTR_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); return new_fltr->sw_id; err_free: kfree(new_fltr); return rc; } static void bnxt_cfg_ntp_filters(struct bnxt *bp) { int i; for (i = 0; i < BNXT_NTP_FLTR_HASH_SIZE; i++) { struct hlist_head *head; struct hlist_node *tmp; struct bnxt_ntuple_filter *fltr; int rc; head = &bp->ntp_fltr_hash_tbl[i]; hlist_for_each_entry_safe(fltr, tmp, head, hash) { bool del = false; if (test_bit(BNXT_FLTR_VALID, &fltr->state)) { if (rps_may_expire_flow(bp->dev, fltr->rxq, fltr->flow_id, fltr->sw_id)) { bnxt_hwrm_cfa_ntuple_filter_free(bp, fltr); del = true; } } else { rc = bnxt_hwrm_cfa_ntuple_filter_alloc(bp, fltr); if (rc) del = true; else set_bit(BNXT_FLTR_VALID, &fltr->state); } if (del) { spin_lock_bh(&bp->ntp_fltr_lock); hlist_del_rcu(&fltr->hash); bp->ntp_fltr_count--; spin_unlock_bh(&bp->ntp_fltr_lock); synchronize_rcu(); clear_bit(fltr->sw_id, bp->ntp_fltr_bmap); kfree(fltr); } } } if (test_and_clear_bit(BNXT_HWRM_PF_UNLOAD_SP_EVENT, &bp->sp_event)) netdev_info(bp->dev, "Receive PF driver unload event!\n"); } #else static void bnxt_cfg_ntp_filters(struct bnxt *bp) { } #endif /* CONFIG_RFS_ACCEL */ static void bnxt_udp_tunnel_add(struct net_device *dev, struct udp_tunnel_info *ti) { struct bnxt *bp = netdev_priv(dev); if (ti->sa_family != AF_INET6 && ti->sa_family != AF_INET) return; if (!netif_running(dev)) return; switch (ti->type) { case UDP_TUNNEL_TYPE_VXLAN: if (bp->vxlan_port_cnt && bp->vxlan_port != ti->port) return; bp->vxlan_port_cnt++; if (bp->vxlan_port_cnt == 1) { bp->vxlan_port = ti->port; set_bit(BNXT_VXLAN_ADD_PORT_SP_EVENT, &bp->sp_event); bnxt_queue_sp_work(bp); } break; case UDP_TUNNEL_TYPE_GENEVE: if (bp->nge_port_cnt && bp->nge_port != ti->port) return; bp->nge_port_cnt++; if (bp->nge_port_cnt == 1) { bp->nge_port = ti->port; set_bit(BNXT_GENEVE_ADD_PORT_SP_EVENT, &bp->sp_event); } break; default: return; } bnxt_queue_sp_work(bp); } static void bnxt_udp_tunnel_del(struct net_device *dev, struct udp_tunnel_info *ti) { struct bnxt *bp = netdev_priv(dev); if (ti->sa_family != AF_INET6 && ti->sa_family != AF_INET) return; if (!netif_running(dev)) return; switch (ti->type) { case UDP_TUNNEL_TYPE_VXLAN: if (!bp->vxlan_port_cnt || bp->vxlan_port != ti->port) return; bp->vxlan_port_cnt--; if (bp->vxlan_port_cnt != 0) return; set_bit(BNXT_VXLAN_DEL_PORT_SP_EVENT, &bp->sp_event); break; case UDP_TUNNEL_TYPE_GENEVE: if (!bp->nge_port_cnt || bp->nge_port != ti->port) return; bp->nge_port_cnt--; if (bp->nge_port_cnt != 0) return; set_bit(BNXT_GENEVE_DEL_PORT_SP_EVENT, &bp->sp_event); break; default: return; } bnxt_queue_sp_work(bp); } static int bnxt_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq, struct net_device *dev, u32 filter_mask, int nlflags) { struct bnxt *bp = netdev_priv(dev); return ndo_dflt_bridge_getlink(skb, pid, seq, dev, bp->br_mode, 0, 0, nlflags, filter_mask, NULL); } static int bnxt_bridge_setlink(struct net_device *dev, struct nlmsghdr *nlh, u16 flags, struct netlink_ext_ack *extack) { struct bnxt *bp = netdev_priv(dev); struct nlattr *attr, *br_spec; int rem, rc = 0; if (bp->hwrm_spec_code < 0x10708 || !BNXT_SINGLE_PF(bp)) return -EOPNOTSUPP; br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC); if (!br_spec) return -EINVAL; nla_for_each_nested(attr, br_spec, rem) { u16 mode; if (nla_type(attr) != IFLA_BRIDGE_MODE) continue; if (nla_len(attr) < sizeof(mode)) return -EINVAL; mode = nla_get_u16(attr); if (mode == bp->br_mode) break; rc = bnxt_hwrm_set_br_mode(bp, mode); if (!rc) bp->br_mode = mode; break; } return rc; } int bnxt_get_port_parent_id(struct net_device *dev, struct netdev_phys_item_id *ppid) { struct bnxt *bp = netdev_priv(dev); if (bp->eswitch_mode != DEVLINK_ESWITCH_MODE_SWITCHDEV) return -EOPNOTSUPP; /* The PF and it's VF-reps only support the switchdev framework */ if (!BNXT_PF(bp) || !(bp->flags & BNXT_FLAG_DSN_VALID)) return -EOPNOTSUPP; ppid->id_len = sizeof(bp->dsn); memcpy(ppid->id, bp->dsn, ppid->id_len); return 0; } static struct devlink_port *bnxt_get_devlink_port(struct net_device *dev) { struct bnxt *bp = netdev_priv(dev); return &bp->dl_port; } static const struct net_device_ops bnxt_netdev_ops = { .ndo_open = bnxt_open, .ndo_start_xmit = bnxt_start_xmit, .ndo_stop = bnxt_close, .ndo_get_stats64 = bnxt_get_stats64, .ndo_set_rx_mode = bnxt_set_rx_mode, .ndo_do_ioctl = bnxt_ioctl, .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = bnxt_change_mac_addr, .ndo_change_mtu = bnxt_change_mtu, .ndo_fix_features = bnxt_fix_features, .ndo_set_features = bnxt_set_features, .ndo_tx_timeout = bnxt_tx_timeout, #ifdef CONFIG_BNXT_SRIOV .ndo_get_vf_config = bnxt_get_vf_config, .ndo_set_vf_mac = bnxt_set_vf_mac, .ndo_set_vf_vlan = bnxt_set_vf_vlan, .ndo_set_vf_rate = bnxt_set_vf_bw, .ndo_set_vf_link_state = bnxt_set_vf_link_state, .ndo_set_vf_spoofchk = bnxt_set_vf_spoofchk, .ndo_set_vf_trust = bnxt_set_vf_trust, #endif .ndo_setup_tc = bnxt_setup_tc, #ifdef CONFIG_RFS_ACCEL .ndo_rx_flow_steer = bnxt_rx_flow_steer, #endif .ndo_udp_tunnel_add = bnxt_udp_tunnel_add, .ndo_udp_tunnel_del = bnxt_udp_tunnel_del, .ndo_bpf = bnxt_xdp, .ndo_xdp_xmit = bnxt_xdp_xmit, .ndo_bridge_getlink = bnxt_bridge_getlink, .ndo_bridge_setlink = bnxt_bridge_setlink, .ndo_get_devlink_port = bnxt_get_devlink_port, }; static void bnxt_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnxt *bp = netdev_priv(dev); if (BNXT_PF(bp)) bnxt_sriov_disable(bp); bnxt_dl_fw_reporters_destroy(bp, true); if (BNXT_PF(bp)) devlink_port_type_clear(&bp->dl_port); pci_disable_pcie_error_reporting(pdev); unregister_netdev(dev); bnxt_dl_unregister(bp); bnxt_shutdown_tc(bp); bnxt_cancel_sp_work(bp); bp->sp_event = 0; bnxt_clear_int_mode(bp); bnxt_hwrm_func_drv_unrgtr(bp); bnxt_free_hwrm_resources(bp); bnxt_free_hwrm_short_cmd_req(bp); bnxt_ethtool_free(bp); bnxt_dcb_free(bp); kfree(bp->edev); bp->edev = NULL; kfree(bp->fw_health); bp->fw_health = NULL; bnxt_cleanup_pci(bp); bnxt_free_ctx_mem(bp); kfree(bp->ctx); bp->ctx = NULL; bnxt_free_port_stats(bp); free_netdev(dev); } static int bnxt_probe_phy(struct bnxt *bp, bool fw_dflt) { int rc = 0; struct bnxt_link_info *link_info = &bp->link_info; rc = bnxt_hwrm_phy_qcaps(bp); if (rc) { netdev_err(bp->dev, "Probe phy can't get phy capabilities (rc: %x)\n", rc); return rc; } if (!fw_dflt) return 0; rc = bnxt_update_link(bp, false); if (rc) { netdev_err(bp->dev, "Probe phy can't update link (rc: %x)\n", rc); return rc; } /* Older firmware does not have supported_auto_speeds, so assume * that all supported speeds can be autonegotiated. */ if (link_info->auto_link_speeds && !link_info->support_auto_speeds) link_info->support_auto_speeds = link_info->support_speeds; bnxt_init_ethtool_link_settings(bp); return 0; } static int bnxt_get_max_irq(struct pci_dev *pdev) { u16 ctrl; if (!pdev->msix_cap) return 1; pci_read_config_word(pdev, pdev->msix_cap + PCI_MSIX_FLAGS, &ctrl); return (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1; } static void _bnxt_get_max_rings(struct bnxt *bp, int *max_rx, int *max_tx, int *max_cp) { struct bnxt_hw_resc *hw_resc = &bp->hw_resc; int max_ring_grps = 0, max_irq; *max_tx = hw_resc->max_tx_rings; *max_rx = hw_resc->max_rx_rings; *max_cp = bnxt_get_max_func_cp_rings_for_en(bp); max_irq = min_t(int, bnxt_get_max_func_irqs(bp) - bnxt_get_ulp_msix_num(bp), hw_resc->max_stat_ctxs - bnxt_get_ulp_stat_ctxs(bp)); if (!(bp->flags & BNXT_FLAG_CHIP_P5)) *max_cp = min_t(int, *max_cp, max_irq); max_ring_grps = hw_resc->max_hw_ring_grps; if (BNXT_CHIP_TYPE_NITRO_A0(bp) && BNXT_PF(bp)) { *max_cp -= 1; *max_rx -= 2; } if (bp->flags & BNXT_FLAG_AGG_RINGS) *max_rx >>= 1; if (bp->flags & BNXT_FLAG_CHIP_P5) { bnxt_trim_rings(bp, max_rx, max_tx, *max_cp, false); /* On P5 chips, max_cp output param should be available NQs */ *max_cp = max_irq; } *max_rx = min_t(int, *max_rx, max_ring_grps); } int bnxt_get_max_rings(struct bnxt *bp, int *max_rx, int *max_tx, bool shared) { int rx, tx, cp; _bnxt_get_max_rings(bp, &rx, &tx, &cp); *max_rx = rx; *max_tx = tx; if (!rx || !tx || !cp) return -ENOMEM; return bnxt_trim_rings(bp, max_rx, max_tx, cp, shared); } static int bnxt_get_dflt_rings(struct bnxt *bp, int *max_rx, int *max_tx, bool shared) { int rc; rc = bnxt_get_max_rings(bp, max_rx, max_tx, shared); if (rc && (bp->flags & BNXT_FLAG_AGG_RINGS)) { /* Not enough rings, try disabling agg rings. */ bp->flags &= ~BNXT_FLAG_AGG_RINGS; rc = bnxt_get_max_rings(bp, max_rx, max_tx, shared); if (rc) { /* set BNXT_FLAG_AGG_RINGS back for consistency */ bp->flags |= BNXT_FLAG_AGG_RINGS; return rc; } bp->flags |= BNXT_FLAG_NO_AGG_RINGS; bp->dev->hw_features &= ~(NETIF_F_LRO | NETIF_F_GRO_HW); bp->dev->features &= ~(NETIF_F_LRO | NETIF_F_GRO_HW); bnxt_set_ring_params(bp); } if (bp->flags & BNXT_FLAG_ROCE_CAP) { int max_cp, max_stat, max_irq; /* Reserve minimum resources for RoCE */ max_cp = bnxt_get_max_func_cp_rings(bp); max_stat = bnxt_get_max_func_stat_ctxs(bp); max_irq = bnxt_get_max_func_irqs(bp); if (max_cp <= BNXT_MIN_ROCE_CP_RINGS || max_irq <= BNXT_MIN_ROCE_CP_RINGS || max_stat <= BNXT_MIN_ROCE_STAT_CTXS) return 0; max_cp -= BNXT_MIN_ROCE_CP_RINGS; max_irq -= BNXT_MIN_ROCE_CP_RINGS; max_stat -= BNXT_MIN_ROCE_STAT_CTXS; max_cp = min_t(int, max_cp, max_irq); max_cp = min_t(int, max_cp, max_stat); rc = bnxt_trim_rings(bp, max_rx, max_tx, max_cp, shared); if (rc) rc = 0; } return rc; } /* In initial default shared ring setting, each shared ring must have a * RX/TX ring pair. */ static void bnxt_trim_dflt_sh_rings(struct bnxt *bp) { bp->cp_nr_rings = min_t(int, bp->tx_nr_rings_per_tc, bp->rx_nr_rings); bp->rx_nr_rings = bp->cp_nr_rings; bp->tx_nr_rings_per_tc = bp->cp_nr_rings; bp->tx_nr_rings = bp->tx_nr_rings_per_tc; } static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) { int dflt_rings, max_rx_rings, max_tx_rings, rc; if (!bnxt_can_reserve_rings(bp)) return 0; if (sh) bp->flags |= BNXT_FLAG_SHARED_RINGS; dflt_rings = is_kdump_kernel() ? 1 : netif_get_num_default_rss_queues(); /* Reduce default rings on multi-port cards so that total default * rings do not exceed CPU count. */ if (bp->port_count > 1) { int max_rings = max_t(int, num_online_cpus() / bp->port_count, 1); dflt_rings = min_t(int, dflt_rings, max_rings); } rc = bnxt_get_dflt_rings(bp, &max_rx_rings, &max_tx_rings, sh); if (rc) return rc; bp->rx_nr_rings = min_t(int, dflt_rings, max_rx_rings); bp->tx_nr_rings_per_tc = min_t(int, dflt_rings, max_tx_rings); if (sh) bnxt_trim_dflt_sh_rings(bp); else bp->cp_nr_rings = bp->tx_nr_rings_per_tc + bp->rx_nr_rings; bp->tx_nr_rings = bp->tx_nr_rings_per_tc; rc = __bnxt_reserve_rings(bp); if (rc) netdev_warn(bp->dev, "Unable to reserve tx rings\n"); bp->tx_nr_rings_per_tc = bp->tx_nr_rings; if (sh) bnxt_trim_dflt_sh_rings(bp); /* Rings may have been trimmed, re-reserve the trimmed rings. */ if (bnxt_need_reserve_rings(bp)) { rc = __bnxt_reserve_rings(bp); if (rc) netdev_warn(bp->dev, "2nd rings reservation failed.\n"); bp->tx_nr_rings_per_tc = bp->tx_nr_rings; } if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { bp->rx_nr_rings++; bp->cp_nr_rings++; } if (rc) { bp->tx_nr_rings = 0; bp->rx_nr_rings = 0; } return rc; } static int bnxt_init_dflt_ring_mode(struct bnxt *bp) { int rc; if (bp->tx_nr_rings) return 0; bnxt_ulp_irq_stop(bp); bnxt_clear_int_mode(bp); rc = bnxt_set_dflt_rings(bp, true); if (rc) { netdev_err(bp->dev, "Not enough rings available.\n"); goto init_dflt_ring_err; } rc = bnxt_init_int_mode(bp); if (rc) goto init_dflt_ring_err; bp->tx_nr_rings_per_tc = bp->tx_nr_rings; if (bnxt_rfs_supported(bp) && bnxt_rfs_capable(bp)) { bp->flags |= BNXT_FLAG_RFS; bp->dev->features |= NETIF_F_NTUPLE; } init_dflt_ring_err: bnxt_ulp_irq_restart(bp, rc); return rc; } int bnxt_restore_pf_fw_resources(struct bnxt *bp) { int rc; ASSERT_RTNL(); bnxt_hwrm_func_qcaps(bp); if (netif_running(bp->dev)) __bnxt_close_nic(bp, true, false); bnxt_ulp_irq_stop(bp); bnxt_clear_int_mode(bp); rc = bnxt_init_int_mode(bp); bnxt_ulp_irq_restart(bp, rc); if (netif_running(bp->dev)) { if (rc) dev_close(bp->dev); else rc = bnxt_open_nic(bp, true, false); } return rc; } static int bnxt_init_mac_addr(struct bnxt *bp) { int rc = 0; if (BNXT_PF(bp)) { memcpy(bp->dev->dev_addr, bp->pf.mac_addr, ETH_ALEN); } else { #ifdef CONFIG_BNXT_SRIOV struct bnxt_vf_info *vf = &bp->vf; bool strict_approval = true; if (is_valid_ether_addr(vf->mac_addr)) { /* overwrite netdev dev_addr with admin VF MAC */ memcpy(bp->dev->dev_addr, vf->mac_addr, ETH_ALEN); /* Older PF driver or firmware may not approve this * correctly. */ strict_approval = false; } else { eth_hw_addr_random(bp->dev); } rc = bnxt_approve_mac(bp, bp->dev->dev_addr, strict_approval); #endif } return rc; } #define BNXT_VPD_LEN 512 static void bnxt_vpd_read_info(struct bnxt *bp) { struct pci_dev *pdev = bp->pdev; int i, len, pos, ro_size; ssize_t vpd_size; u8 *vpd_data; vpd_data = kmalloc(BNXT_VPD_LEN, GFP_KERNEL); if (!vpd_data) return; vpd_size = pci_read_vpd(pdev, 0, BNXT_VPD_LEN, vpd_data); if (vpd_size <= 0) { netdev_err(bp->dev, "Unable to read VPD\n"); goto exit; } i = pci_vpd_find_tag(vpd_data, 0, vpd_size, PCI_VPD_LRDT_RO_DATA); if (i < 0) { netdev_err(bp->dev, "VPD READ-Only not found\n"); goto exit; } ro_size = pci_vpd_lrdt_size(&vpd_data[i]); i += PCI_VPD_LRDT_TAG_SIZE; if (i + ro_size > vpd_size) goto exit; pos = pci_vpd_find_info_keyword(vpd_data, i, ro_size, PCI_VPD_RO_KEYWORD_PARTNO); if (pos < 0) goto read_sn; len = pci_vpd_info_field_size(&vpd_data[pos]); pos += PCI_VPD_INFO_FLD_HDR_SIZE; if (len + pos > vpd_size) goto read_sn; strlcpy(bp->board_partno, &vpd_data[pos], min(len, BNXT_VPD_FLD_LEN)); read_sn: pos = pci_vpd_find_info_keyword(vpd_data, i, ro_size, PCI_VPD_RO_KEYWORD_SERIALNO); if (pos < 0) goto exit; len = pci_vpd_info_field_size(&vpd_data[pos]); pos += PCI_VPD_INFO_FLD_HDR_SIZE; if (len + pos > vpd_size) goto exit; strlcpy(bp->board_serialno, &vpd_data[pos], min(len, BNXT_VPD_FLD_LEN)); exit: kfree(vpd_data); } static int bnxt_pcie_dsn_get(struct bnxt *bp, u8 dsn[]) { struct pci_dev *pdev = bp->pdev; u64 qword; qword = pci_get_dsn(pdev); if (!qword) { netdev_info(bp->dev, "Unable to read adapter's DSN\n"); return -EOPNOTSUPP; } put_unaligned_le64(qword, dsn); bp->flags |= BNXT_FLAG_DSN_VALID; return 0; } static int bnxt_map_db_bar(struct bnxt *bp) { if (!bp->db_size) return -ENODEV; bp->bar1 = pci_iomap(bp->pdev, 2, bp->db_size); if (!bp->bar1) return -ENOMEM; return 0; } static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *dev; struct bnxt *bp; int rc, max_irqs; if (pci_is_bridge(pdev)) return -ENODEV; /* Clear any pending DMA transactions from crash kernel * while loading driver in capture kernel. */ if (is_kdump_kernel()) { pci_clear_master(pdev); pcie_flr(pdev); } max_irqs = bnxt_get_max_irq(pdev); dev = alloc_etherdev_mq(sizeof(*bp), max_irqs); if (!dev) return -ENOMEM; bp = netdev_priv(dev); bnxt_set_max_func_irqs(bp, max_irqs); if (bnxt_vf_pciid(ent->driver_data)) bp->flags |= BNXT_FLAG_VF; if (pdev->msix_cap) bp->flags |= BNXT_FLAG_MSIX_CAP; rc = bnxt_init_board(pdev, dev); if (rc < 0) goto init_err_free; dev->netdev_ops = &bnxt_netdev_ops; dev->watchdog_timeo = BNXT_TX_TIMEOUT; dev->ethtool_ops = &bnxt_ethtool_ops; pci_set_drvdata(pdev, dev); bnxt_vpd_read_info(bp); rc = bnxt_alloc_hwrm_resources(bp); if (rc) goto init_err_pci_clean; mutex_init(&bp->hwrm_cmd_lock); mutex_init(&bp->link_lock); rc = bnxt_fw_init_one_p1(bp); if (rc) goto init_err_pci_clean; if (BNXT_CHIP_P5(bp)) bp->flags |= BNXT_FLAG_CHIP_P5; rc = bnxt_fw_init_one_p2(bp); if (rc) goto init_err_pci_clean; rc = bnxt_map_db_bar(bp); if (rc) { dev_err(&pdev->dev, "Cannot map doorbell BAR rc = %d, aborting\n", rc); goto init_err_pci_clean; } dev->hw_features = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM | NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_GSO_UDP_TUNNEL | NETIF_F_GSO_GRE | NETIF_F_GSO_IPXIP4 | NETIF_F_GSO_UDP_TUNNEL_CSUM | NETIF_F_GSO_GRE_CSUM | NETIF_F_GSO_PARTIAL | NETIF_F_RXHASH | NETIF_F_RXCSUM | NETIF_F_GRO; if (BNXT_SUPPORTS_TPA(bp)) dev->hw_features |= NETIF_F_LRO; dev->hw_enc_features = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM | NETIF_F_SG | NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_GSO_UDP_TUNNEL | NETIF_F_GSO_GRE | NETIF_F_GSO_UDP_TUNNEL_CSUM | NETIF_F_GSO_GRE_CSUM | NETIF_F_GSO_IPXIP4 | NETIF_F_GSO_PARTIAL; dev->gso_partial_features = NETIF_F_GSO_UDP_TUNNEL_CSUM | NETIF_F_GSO_GRE_CSUM; dev->vlan_features = dev->hw_features | NETIF_F_HIGHDMA; dev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_RX | NETIF_F_HW_VLAN_STAG_TX; if (BNXT_SUPPORTS_TPA(bp)) dev->hw_features |= NETIF_F_GRO_HW; dev->features |= dev->hw_features | NETIF_F_HIGHDMA; if (dev->features & NETIF_F_GRO_HW) dev->features &= ~NETIF_F_LRO; dev->priv_flags |= IFF_UNICAST_FLT; #ifdef CONFIG_BNXT_SRIOV init_waitqueue_head(&bp->sriov_cfg_wait); mutex_init(&bp->sriov_lock); #endif if (BNXT_SUPPORTS_TPA(bp)) { bp->gro_func = bnxt_gro_func_5730x; if (BNXT_CHIP_P4(bp)) bp->gro_func = bnxt_gro_func_5731x; else if (BNXT_CHIP_P5(bp)) bp->gro_func = bnxt_gro_func_5750x; } if (!BNXT_CHIP_P4_PLUS(bp)) bp->flags |= BNXT_FLAG_DOUBLE_DB; bp->ulp_probe = bnxt_ulp_probe; rc = bnxt_init_mac_addr(bp); if (rc) { dev_err(&pdev->dev, "Unable to initialize mac address.\n"); rc = -EADDRNOTAVAIL; goto init_err_pci_clean; } if (BNXT_PF(bp)) { /* Read the adapter's DSN to use as the eswitch switch_id */ rc = bnxt_pcie_dsn_get(bp, bp->dsn); } /* MTU range: 60 - FW defined max */ dev->min_mtu = ETH_ZLEN; dev->max_mtu = bp->max_mtu; rc = bnxt_probe_phy(bp, true); if (rc) goto init_err_pci_clean; bnxt_set_rx_skb_mode(bp, false); bnxt_set_tpa_flags(bp); bnxt_set_ring_params(bp); rc = bnxt_set_dflt_rings(bp, true); if (rc) { netdev_err(bp->dev, "Not enough rings available.\n"); rc = -ENOMEM; goto init_err_pci_clean; } bnxt_fw_init_one_p3(bp); if (dev->hw_features & NETIF_F_HW_VLAN_CTAG_RX) bp->flags |= BNXT_FLAG_STRIP_VLAN; rc = bnxt_init_int_mode(bp); if (rc) goto init_err_pci_clean; /* No TC has been set yet and rings may have been trimmed due to * limited MSIX, so we re-initialize the TX rings per TC. */ bp->tx_nr_rings_per_tc = bp->tx_nr_rings; if (BNXT_PF(bp)) { if (!bnxt_pf_wq) { bnxt_pf_wq = create_singlethread_workqueue("bnxt_pf_wq"); if (!bnxt_pf_wq) { dev_err(&pdev->dev, "Unable to create workqueue.\n"); goto init_err_pci_clean; } } bnxt_init_tc(bp); } bnxt_dl_register(bp); rc = register_netdev(dev); if (rc) goto init_err_cleanup; if (BNXT_PF(bp)) devlink_port_type_eth_set(&bp->dl_port, bp->dev); bnxt_dl_fw_reporters_create(bp); netdev_info(dev, "%s found at mem %lx, node addr %pM\n", board_info[ent->driver_data].name, (long)pci_resource_start(pdev, 0), dev->dev_addr); pcie_print_link_status(pdev); return 0; init_err_cleanup: bnxt_dl_unregister(bp); bnxt_shutdown_tc(bp); bnxt_clear_int_mode(bp); init_err_pci_clean: bnxt_hwrm_func_drv_unrgtr(bp); bnxt_free_hwrm_short_cmd_req(bp); bnxt_free_hwrm_resources(bp); kfree(bp->fw_health); bp->fw_health = NULL; bnxt_cleanup_pci(bp); bnxt_free_ctx_mem(bp); kfree(bp->ctx); bp->ctx = NULL; init_err_free: free_netdev(dev); return rc; } static void bnxt_shutdown(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnxt *bp; if (!dev) return; rtnl_lock(); bp = netdev_priv(dev); if (!bp) goto shutdown_exit; if (netif_running(dev)) dev_close(dev); bnxt_ulp_shutdown(bp); bnxt_clear_int_mode(bp); pci_disable_device(pdev); if (system_state == SYSTEM_POWER_OFF) { pci_wake_from_d3(pdev, bp->wol); pci_set_power_state(pdev, PCI_D3hot); } shutdown_exit: rtnl_unlock(); } #ifdef CONFIG_PM_SLEEP static int bnxt_suspend(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct bnxt *bp = netdev_priv(dev); int rc = 0; rtnl_lock(); bnxt_ulp_stop(bp); if (netif_running(dev)) { netif_device_detach(dev); rc = bnxt_close(dev); } bnxt_hwrm_func_drv_unrgtr(bp); pci_disable_device(bp->pdev); bnxt_free_ctx_mem(bp); kfree(bp->ctx); bp->ctx = NULL; rtnl_unlock(); return rc; } static int bnxt_resume(struct device *device) { struct net_device *dev = dev_get_drvdata(device); struct bnxt *bp = netdev_priv(dev); int rc = 0; rtnl_lock(); rc = pci_enable_device(bp->pdev); if (rc) { netdev_err(dev, "Cannot re-enable PCI device during resume, err = %d\n", rc); goto resume_exit; } pci_set_master(bp->pdev); if (bnxt_hwrm_ver_get(bp)) { rc = -ENODEV; goto resume_exit; } rc = bnxt_hwrm_func_reset(bp); if (rc) { rc = -EBUSY; goto resume_exit; } rc = bnxt_hwrm_func_qcaps(bp); if (rc) goto resume_exit; if (bnxt_hwrm_func_drv_rgtr(bp, NULL, 0, false)) { rc = -ENODEV; goto resume_exit; } bnxt_get_wol_settings(bp); if (netif_running(dev)) { rc = bnxt_open(dev); if (!rc) netif_device_attach(dev); } resume_exit: bnxt_ulp_start(bp, rc); if (!rc) bnxt_reenable_sriov(bp); rtnl_unlock(); return rc; } static SIMPLE_DEV_PM_OPS(bnxt_pm_ops, bnxt_suspend, bnxt_resume); #define BNXT_PM_OPS (&bnxt_pm_ops) #else #define BNXT_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ /** * bnxt_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t bnxt_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct bnxt *bp = netdev_priv(netdev); netdev_info(netdev, "PCI I/O error detected\n"); rtnl_lock(); netif_device_detach(netdev); bnxt_ulp_stop(bp); if (state == pci_channel_io_perm_failure) { rtnl_unlock(); return PCI_ERS_RESULT_DISCONNECT; } if (netif_running(netdev)) bnxt_close(netdev); pci_disable_device(pdev); bnxt_free_ctx_mem(bp); kfree(bp->ctx); bp->ctx = NULL; rtnl_unlock(); /* Request a slot slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * bnxt_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. * At this point, the card has exprienced a hard reset, * followed by fixups by BIOS, and has its config space * set up identically to what it was at cold boot. */ static pci_ers_result_t bnxt_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct bnxt *bp = netdev_priv(netdev); int err = 0; pci_ers_result_t result = PCI_ERS_RESULT_DISCONNECT; netdev_info(bp->dev, "PCI Slot Reset\n"); rtnl_lock(); if (pci_enable_device(pdev)) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset.\n"); } else { pci_set_master(pdev); err = bnxt_hwrm_func_reset(bp); if (!err) { err = bnxt_hwrm_func_qcaps(bp); if (!err && netif_running(netdev)) err = bnxt_open(netdev); } bnxt_ulp_start(bp, err); if (!err) { bnxt_reenable_sriov(bp); result = PCI_ERS_RESULT_RECOVERED; } } if (result != PCI_ERS_RESULT_RECOVERED) { if (netif_running(netdev)) dev_close(netdev); pci_disable_device(pdev); } rtnl_unlock(); return result; } /** * bnxt_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells * us that its OK to resume normal operation. */ static void bnxt_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); rtnl_lock(); netif_device_attach(netdev); rtnl_unlock(); } static const struct pci_error_handlers bnxt_err_handler = { .error_detected = bnxt_io_error_detected, .slot_reset = bnxt_io_slot_reset, .resume = bnxt_io_resume }; static struct pci_driver bnxt_pci_driver = { .name = DRV_MODULE_NAME, .id_table = bnxt_pci_tbl, .probe = bnxt_init_one, .remove = bnxt_remove_one, .shutdown = bnxt_shutdown, .driver.pm = BNXT_PM_OPS, .err_handler = &bnxt_err_handler, #if defined(CONFIG_BNXT_SRIOV) .sriov_configure = bnxt_sriov_configure, #endif }; static int __init bnxt_init(void) { bnxt_debug_init(); return pci_register_driver(&bnxt_pci_driver); } static void __exit bnxt_exit(void) { pci_unregister_driver(&bnxt_pci_driver); if (bnxt_pf_wq) destroy_workqueue(bnxt_pf_wq); bnxt_debug_exit(); } module_init(bnxt_init); module_exit(bnxt_exit);
skalk/linux
drivers/net/ethernet/broadcom/bnxt/bnxt.c
C
gpl-2.0
329,644
/**************************************************************************** * Copyright (c) 1998-2009,2010 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE 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. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1995,1997 * ****************************************************************************/ #include "form.priv.h" MODULE_ID("$Id: frm_def.c,v 1.25 2010/01/23 21:14:36 tom Exp $") /* this can't be readonly */ static FORM default_form = { 0, /* status */ 0, /* rows */ 0, /* cols */ 0, /* currow */ 0, /* curcol */ 0, /* toprow */ 0, /* begincol */ -1, /* maxfield */ -1, /* maxpage */ -1, /* curpage */ ALL_FORM_OPTS, /* opts */ (WINDOW *)0, /* win */ (WINDOW *)0, /* sub */ (WINDOW *)0, /* w */ (FIELD **)0, /* field */ (FIELD *)0, /* current */ (_PAGE *) 0, /* page */ (char *)0, /* usrptr */ NULL, /* forminit */ NULL, /* formterm */ NULL, /* fieldinit */ NULL /* fieldterm */ }; NCURSES_EXPORT_VAR(FORM *) _nc_Default_Form = &default_form; /*--------------------------------------------------------------------------- | Facility : libnform | Function : static FIELD *Insert_Field_By_Position( | FIELD *new_field, | FIELD *head ) | | Description : Insert new_field into sorted fieldlist with head "head" | and return new head of sorted fieldlist. Sorting | criteria is (row,column). This is a circular list. | | Return Values : New head of sorted fieldlist +--------------------------------------------------------------------------*/ static FIELD * Insert_Field_By_Position(FIELD *newfield, FIELD *head) { FIELD *current, *newhead; assert(newfield); if (!head) { /* empty list is trivial */ newhead = newfield->snext = newfield->sprev = newfield; } else { newhead = current = head; while ((current->frow < newfield->frow) || ((current->frow == newfield->frow) && (current->fcol < newfield->fcol))) { current = current->snext; if (current == head) { /* We cycled through. Reset head to indicate that */ head = (FIELD *)0; break; } } /* we leave the loop with current pointing to the field after newfield */ newfield->snext = current; newfield->sprev = current->sprev; newfield->snext->sprev = newfield; newfield->sprev->snext = newfield; if (current == head) newhead = newfield; } return (newhead); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : static void Disconnect_Fields(FORM *form) | | Description : Break association between form and array of fields. | | Return Values : - +--------------------------------------------------------------------------*/ static void Disconnect_Fields(FORM *form) { if (form->field) { FIELD **fields; for (fields = form->field; *fields; fields++) { if (form == (*fields)->form) (*fields)->form = (FORM *)0; } form->rows = form->cols = 0; form->maxfield = form->maxpage = -1; form->field = (FIELD **)0; if (form->page) free(form->page); form->page = (_PAGE *) 0; } } /*--------------------------------------------------------------------------- | Facility : libnform | Function : static int Connect_Fields(FORM *form, FIELD **fields) | | Description : Set association between form and array of fields. | | Return Values : E_OK - no error | E_CONNECTED - a field is already connected | E_BAD_ARGUMENT - Invalid form pointer or field array | E_SYSTEM_ERROR - not enough memory +--------------------------------------------------------------------------*/ static int Connect_Fields(FORM *form, FIELD **fields) { int field_cnt, j; int page_nr; int maximum_row_in_field, maximum_col_in_field; _PAGE *pg; T((T_CALLED("Connect_Fields(%p,%p)"), (void *)form, (void *)fields)); assert(form); form->field = fields; form->maxfield = 0; form->maxpage = 0; if (!fields) RETURN(E_OK); page_nr = 0; /* store formpointer in fields and count pages */ for (field_cnt = 0; fields[field_cnt]; field_cnt++) { if (fields[field_cnt]->form) RETURN(E_CONNECTED); if (field_cnt == 0 || (fields[field_cnt]->status & _NEWPAGE)) page_nr++; fields[field_cnt]->form = form; } if (field_cnt == 0 || (short)field_cnt < 0) RETURN(E_BAD_ARGUMENT); /* allocate page structures */ if ((pg = typeMalloc(_PAGE, page_nr)) != (_PAGE *) 0) { T((T_CREATE("_PAGE %p"), (void *)pg)); form->page = pg; } else RETURN(E_SYSTEM_ERROR); /* Cycle through fields and calculate page boundaries as well as size of the form */ for (j = 0; j < field_cnt; j++) { if (j == 0) pg->pmin = j; else { if (fields[j]->status & _NEWPAGE) { pg->pmax = j - 1; pg++; pg->pmin = j; } } maximum_row_in_field = fields[j]->frow + fields[j]->rows; maximum_col_in_field = fields[j]->fcol + fields[j]->cols; if (form->rows < maximum_row_in_field) form->rows = maximum_row_in_field; if (form->cols < maximum_col_in_field) form->cols = maximum_col_in_field; } pg->pmax = field_cnt - 1; form->maxfield = field_cnt; form->maxpage = page_nr; /* Sort fields on form pages */ for (page_nr = 0; page_nr < form->maxpage; page_nr++) { FIELD *fld = (FIELD *)0; for (j = form->page[page_nr].pmin; j <= form->page[page_nr].pmax; j++) { fields[j]->index = j; fields[j]->page = page_nr; fld = Insert_Field_By_Position(fields[j], fld); } if (fld) { form->page[page_nr].smin = fld->index; form->page[page_nr].smax = fld->sprev->index; } else { form->page[page_nr].smin = 0; form->page[page_nr].smax = 0; } } RETURN(E_OK); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : static int Associate_Fields(FORM *form, FIELD **fields) | | Description : Set association between form and array of fields. | If there are fields, position to first active field. | | Return Values : E_OK - success | E_BAD_ARGUMENT - Invalid form pointer or field array | E_CONNECTED - a field is already connected | E_SYSTEM_ERROR - not enough memory +--------------------------------------------------------------------------*/ NCURSES_INLINE static int Associate_Fields(FORM *form, FIELD **fields) { int res = Connect_Fields(form, fields); if (res == E_OK) { if (form->maxpage > 0) { form->curpage = 0; form_driver(form, FIRST_ACTIVE_MAGIC); } else { form->curpage = -1; form->current = (FIELD *)0; } } return (res); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : FORM *new_form_sp(SCREEN* sp, FIELD** fields ) | | Description : Create new form with given array of fields. | | Return Values : Pointer to form. NULL if error occurred. ! Set errno: | E_OK - success | E_BAD_ARGUMENT - Invalid form pointer or field array | E_CONNECTED - a field is already connected | E_SYSTEM_ERROR - not enough memory +--------------------------------------------------------------------------*/ NCURSES_EXPORT(FORM *) NCURSES_SP_NAME(new_form) (NCURSES_SP_DCLx FIELD **fields) { int err = E_SYSTEM_ERROR; FORM *form = (FORM *)0; T((T_CALLED("new_form(%p,%p)"), (void *)SP_PARM, (void *)fields)); if (IsValidScreen(SP_PARM)) { form = typeMalloc(FORM, 1); if (form) { T((T_CREATE("form %p"), (void *)form)); *form = *_nc_Default_Form; /* This ensures win and sub are always non-null, so we can derive always the SCREEN that this form is running on. */ form->win = StdScreen(SP_PARM); form->sub = StdScreen(SP_PARM); if ((err = Associate_Fields(form, fields)) != E_OK) { free_form(form); form = (FORM *)0; } } } if (!form) SET_ERROR(err); returnForm(form); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : FORM* new_form(FIELD** fields ) | | Description : Create new form with given array of fields. | | Return Values : Pointer to form. NULL if error occurred. ! Set errno: | E_OK - success | E_BAD_ARGUMENT - Invalid form pointer or field array | E_CONNECTED - a field is already connected | E_SYSTEM_ERROR - not enough memory +--------------------------------------------------------------------------*/ #if NCURSES_SP_FUNCS NCURSES_EXPORT(FORM *) new_form(FIELD **fields) { return NCURSES_SP_NAME(new_form) (CURRENT_SCREEN, fields); } #endif /*--------------------------------------------------------------------------- | Facility : libnform | Function : int free_form( FORM *form ) | | Description : Release internal memory associated with form. | | Return Values : E_OK - no error | E_BAD_ARGUMENT - invalid form pointer | E_POSTED - form is posted +--------------------------------------------------------------------------*/ NCURSES_EXPORT(int) free_form(FORM *form) { T((T_CALLED("free_form(%p)"), (void *)form)); if (!form) RETURN(E_BAD_ARGUMENT); if (form->status & _POSTED) RETURN(E_POSTED); Disconnect_Fields(form); if (form->page) free(form->page); free(form); RETURN(E_OK); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : int set_form_fields( FORM *form, FIELD **fields ) | | Description : Set a new association of an array of fields to a form | | Return Values : E_OK - no error | E_BAD_ARGUMENT - Invalid form pointer or field array | E_CONNECTED - a field is already connected | E_POSTED - form is posted | E_SYSTEM_ERROR - not enough memory +--------------------------------------------------------------------------*/ NCURSES_EXPORT(int) set_form_fields(FORM *form, FIELD **fields) { FIELD **old; int res; T((T_CALLED("set_form_fields(%p,%p)"), (void *)form, (void *)fields)); if (!form) RETURN(E_BAD_ARGUMENT); if (form->status & _POSTED) RETURN(E_POSTED); old = form->field; Disconnect_Fields(form); if ((res = Associate_Fields(form, fields)) != E_OK) Connect_Fields(form, old); RETURN(res); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : FIELD **form_fields( const FORM *form ) | | Description : Retrieve array of fields | | Return Values : Pointer to field array +--------------------------------------------------------------------------*/ NCURSES_EXPORT(FIELD **) form_fields(const FORM *form) { T((T_CALLED("form_field(%p)"), (const void *)form)); returnFieldPtr(Normalize_Form(form)->field); } /*--------------------------------------------------------------------------- | Facility : libnform | Function : int field_count( const FORM *form ) | | Description : Retrieve number of fields | | Return Values : Number of fields, -1 if none are defined +--------------------------------------------------------------------------*/ NCURSES_EXPORT(int) field_count(const FORM *form) { T((T_CALLED("field_count(%p)"), (const void *)form)); returnCode(Normalize_Form(form)->maxfield); } /* frm_def.c ends here */
pcengines/coreboot
payloads/libpayload/curses/form/frm_def.c
C
gpl-2.0
14,274
class AddPayloadToEventSubscriptions < ActiveRecord::Migration[6.0] def change add_column :event_subscriptions, :payload, :text end end
M0ses/open-build-service
src/api/db/migrate/20210428132708_add_payload_to_event_subscriptions.rb
Ruby
gpl-2.0
144
#!/bin/sh # File: iva.sh ############################################################## # Credits: # 2004 Hale, Cohen, with Stockwell modifications 2004. # In su distribution directory: # ~/su/src/demos/Velocity_Analysis/Traditional/Velan # 2005 Seismic Processing with Seismic Un*x # Forel, Benz, Pennington, 2005 # script iva.sh (section 7.6.7.3) and # velanQC.sh (section 8.2.2.2) # 2011 Schleicher, offerred to David Forel for new edition # of "Seismic Processing with Seismic Un*x" ############################################################## # Set messages on #set -x #================================================ # USER AREA -- SUPPLY VALUES #------------------------------------------------ # CMPs for analysis eval $1 echo parm1 is $1 echo cmp1 and numCMPs $cmp1 $numCMPs #------------------------------------------------ # File names indata=$2 outpicks=$3 # ASCII file inpicks=$4 #######################################################3 #######################################################3 #------------------------------------------------ # display choices myperc=98 # perc value for plot SUXWIGB_OR_XIMAGE=suxwigb SUXWIGB_OR_XIMAGE=suximage # size of the display windows HBOX=700 # originally 450 WBOXCVS=300 # originally 300 WBOXCMP=200 # originally 300 WBOXVELAN=500 # originally 300 XBOXVELAN=10 # kls 1350 puts it on second screen # these parameters work nicely to put plots on # my 2nd screen. I turn them on by changing # the next line to: if [ 1 ] if [ 2 -eq 1 ] then echo "******** in if ***" HBOX=1000 # originally 450 WBOXCVS=300 # originally 300 WBOXCMP=200 # originally 300 WBOXVELAN=800 # originally 300 XBOXVELAN=1350 fi XBOXCVS=`expr $XBOXVELAN + $WBOXVELAN` XBOXCMP=`expr $XBOXCVS + $WBOXCVS` XBOXNMOCMP=`expr $XBOXCMP + $WBOXCMP` #------------------------------------------------ # Processing variables # Semblance variables nvs=101 # number of velocities dvs=$6 # velocity interval fvs=$5 # first velocity # Compute last semblance (velan) velocity lvs=`echo "$fvs + (( $nvs - 1 ) * $dvs )" | bc -l` # CVS variables fc=$fvs # first CVS velocity lc=$lvs # last CVS velocity - now same at the last semblance velocity nc=11 # number of CVS velocities (panels) SPAN=11 # ODD number of CMPs to stack into central CVS #================================================ # HOW SEMBLANCE (VELAN) VELOCITIES ARE COMPUTED # Last Vel = fvs + (( nvs-1 ) * dvs ) = lvs # 5000 = 500 + (( 99-1 ) * 45 ) # 3900 = 1200 + (( 100-1 ) * 27 ) #------------------------------------------------ # HOW CVS VELOCITIES ARE COMPUTED # dc = CVS velocity increment # dc = ( last CVS vel - first CVS vel ) / ( # CVS - 1 ) # m = CVS plot trace spacing (m = d2, vel units) # m = ( last CVS vel - first CVS vel ) / ( ( # CVS - 1 ) * SPAN ) # j=1 # while [ j le nc ] # do # vel = fc + { [( lc - fc ) / ( nc-1 )] * ( j-1) } # j = j + 1 # done # EXAMPLE: # vel = 1200 + ( (( 3900 - 1200 ) / ( 10-1 )) * ( 1-1) ) # vel = 1200 + ( (( 3900 - 1200 ) / ( 10-1 )) * ( 2-1) ) # ... # vel = 1200 + ( (( 3900 - 1200 ) / ( 10-1 )) * (11-1) ) #================================================ # FILE DESCRIPTIONS # spanpanel.$picknow.su = binary temp file for input CVS gathers # cvs.$picknow.su = binary temp file for output CVS traces # nmopanel.$picknow.su = binary temp file for NMO (flattened) section # panel.$picknow.su = current CMP windowed from line of CMPs # spanpanel.$picknow.su = span of CMPs windowed to make cvs # picks.$picknow = current CMP picks arranged as "t1 v1" # "t2 v2" # etc. # par.# (# is a sequential index number; 1, 2, etc.) # = current CMP picks arranged as # "tnmo=t1,t2,t3,... # "vnmo=v1,v2,v3,... # par.0 = file "par.cmp" re-arranged as # "cdp=#,#,#,etc." NOTE: # in this line is picked CMP # "#=1,2,3,etc." NOTE: # in this line is "#" # outpicks = concatenation of par.0 and all par.# files. #================================================ echo " *** INTERACTIVE VELOCITY ANALYSIS ***" #------------------------------------------------ #kls Remove old files. Open new files #rm -f panel.*.su picks.* par.* tmp* echo "save the old outpicks file with date in the name:" suffix=`date|sed "s/ /_/g"` echo "cp -p $outpicks $outpicks.$suffix" cp -p $outpicks $outpicks.$suffix #make a set of picks.* files that will be used to plot on the #velan and the cvs plots, and apply nmo to gather plot if [ -s $inpicks ] then tvnmoqc mode=2 prefix=picks par=$inpicks fi #------------------------------------------------ # Get ns, dt, first time from seismic file nt=`sugethw ns < $indata | sed 1q | sed 's/.*ns=//'` dt=`sugethw dt < $indata | sed 1q | sed 's/.*dt=//'` delrt=`sugethw delrt < $indata | sed 1q | sed 's/.*delrt=//'` # Convert dt from header value in microseconds # to seconds for velocity profile plot dt=`echo "scale=6; $dt / 1000000 " | bc -l` # If "delrt", use it; else use zero tstart=`echo "scale=6; ${delrt} / 1000" | bc -l` #------------------------------------------------ # BEGIN IVA LOOP #------------------------------------------------ i=1 while [ $i -le $numCMPs ] do # set variable $picknow to current CMP eval pickprev=\$cmp`expr i - 1` eval picknow=\$cmp$i eval picknext=\$cmp`expr i + 1` # make a file so the while loop will run the first time echo "just some junk" > newpicks.$picknow while [ -s "newpicks.$picknow" ] do # work this location until the user makes no picks # on the velan if [ -s picks.$picknow ] ; then echo "Location CMP $picknow has no picks." fi #------------------------------------------------ # Plot CMP (right) #------------------------------------------------ suwind < $indata \ key=cdp min=$picknow max=$picknow > panel.$picknow.su $SUXWIGB_OR_XIMAGE < panel.$picknow.su \ xbox=$XBOXCMP ybox=0 wbox=$WBOXCMP hbox=$HBOX \ title="CMP gather $picknow" \ label1=" Time (s)" label2="Offset (m)" key=offset \ perc=$myperc verbose=0 & #------------------------------------------------ # Constant Velocity Stacks (CVS) (middle-left) # Make CVS plot for first pick effort. # If re-picking t-v values, do not make this plot. #------------------------------------------------ # truncate SPAN to odd number less then or equal to SPAN HALF_SPAN=`expr $SPAN / 2` SPAN=`expr $HALF_SPAN "*" 2 + 1` # Select CMPs $picknow +/- HALF_SPAN. # Write to spanpanel.$picknow.su CMPMIN=`expr $picknow - $HALF_SPAN` CMPMAX=`expr $picknow + $HALF_SPAN` suwind < $indata key=cdp min=$CMPMIN max=$CMPMAX \ > spanpanel.$picknow.su # Calculate CVS velocity increment # dc = ( last CVS vel - first CVS vel ) / ( # CVS - 1 ) dc=`echo "( $lc - $fc ) / ( $nc - 1 )" | bc -l` # Calculate trace spacing for CVS plot (m = d2, vel units) # m = ( last CVS vel - first CVS vel ) / ( ( # CVS - 1 ) * SPAN ) m=`echo "( $lc - $fc ) / ( ( $nc - 1 ) * $SPAN )" | bc -l` if [ ! -s cvs.$picknow.su ] ; then # CVS ve locity loop rm cvs.$picknow.su j=1 while [ $j -le $nc ] do vel=`echo "$fc + $dc * ( $j - 1 )" | bc -l` # uncomment to print CVS velocities to screen ## echo " vel = $vel" sunmo < spanpanel.$picknow.su vnmo=$vel | sustack >> cvs.$picknow.su j=`expr $j + 1` done fi # Compute lowest velocity for annotating CVS plot # loV = first CVS velocity - HALF_SPAN * vel inc loV=`echo "$fc - $HALF_SPAN * $m" | bc -l` #------------------------------------------------ # Picking instructions #------------------------------------------------ echo " " echo "Preparing CMP $i of $numCMPs for Picking " echo "Location is CMP $picknow. CVS CMPs = $CMPMIN,$CMPMAX" echo " " echo " Use the semblance plot to pick (t,v) pairs." echo " Type \"s\" when the mouse pointer is where you want a pick." echo " Be sure your picks increase in time." echo " To control velocity interpolation, pick a first value" echo " near zero time and a last value near the last time." echo " Type \"q\" in the semblance plot when you finish picking." echo " " echo " If there are no picks (using \"s\") before you quit (using" echo " \"q\" in the semblance plot, picking will continue at the" echo " next CMP." #------------------------------------------------ # Plot semblance (velan) (left) #------------------------------------------------ # if there is a non-zero length picks.$picknow file, plotit # kls add logic for pickprev, picknow, picknext if [ -s picks.$picknow ] then #--- --- --- --- --- --- --- --- --- --- # Get the number of picks (number of lines) in picks.$picknow # Remove blank spaces preceding the line count. # Remove file name that was returned from "wc". # Store line count in "npair" to guide line on velan. npair=`wc -l picks.$picknow \ | sed 's/^ *\(.*\)/\1/' \ | sed 's/picks.$picknow//' ` plotline="curve=picks.$picknow npair=$npair curvecolor=white" else plotline=" " fi # echo plotline=$plotline # plot the cvs # cat picks.$picknow suximage < cvs.$picknow.su \ xbox=$XBOXCVS ybox=0 wbox=$WBOXCVS hbox=$HBOX \ title="CMP $picknow Constant Velocity Stacks" \ label1=" Time (s)" label2="Velocity (m/s)" \ f2=$loV d2=$m verbose=0 \ perc=$myperc n2tic=5 cmap=rgb0 $plotline & # if there is a velocity function, display moved out gather if [ -s picks.$picknow ] then # translate picks.$picknow into tnmo/vnmo for sunmo sort < picks.$picknow -n | mkparfile string1=tnmo string2=vnmo > par.$i # apply nmo and plot the moved out gather sunmo < panel.$picknow.su par=par.$i cdp=$picknow verbose=0 \ | $SUXWIGB_OR_XIMAGE \ xbox=$XBOXNMOCMP ybox=0 wbox=$WBOXCMP hbox=$HBOX \ title="CMP $picknow after NMO" \ label1=" Time (s)" label2="Offset (m)" \ verbose=0 perc=$myperc key=offset & fi # compute and plot the semblance/velan cat picks.$picknow suvelan < panel.$picknow.su nv=$nvs dv=$dvs fv=$fvs \ | suximage \ xbox=$XBOXVELAN ybox=0 wbox=$WBOXVELAN hbox=$HBOX perc=99 \ units="semblance" f2=$fvs d2=$dvs n2tic=5 \ title="Semblance Plot CMP $picknow" cmap=hsv2 \ label1=" Time (s)" label2="Velocity (m/s)" \ legend=1 units=Semblance verbose=0 gridcolor=black \ grid1=solid grid2=solid \ mpicks=newpicks.$picknow $plotline if [ -s "newpicks.$picknow" ] then echo "there is a non-zero length newpicks.$picknow file" cat newpicks.$picknow cp newpicks.$picknow picks.$picknow fi echo " " echo " t-v PICKS CMP $picknow" echo "----------------------" cat picks.$picknow echo "----------------------" # rm spanpanel.$picknow.su zap xwigb > /dev/null zap ximage > /dev/null done i=`expr $i + 1` done #------------------------------------------------ # Create velocity output file #------------------------------------------------ cdplist=$cmp1 i=2 while [ $i -le $numCMPs ] do eval picknow=\$cmp$i cdplist=$cdplist,$picknow i=`expr $i + 1` done echo cdp=$cdplist \\ >$outpicks i=1 while [ $i -le $numCMPs ] do sed < par.$i 's/$/ \\/g' >> $outpicks i=`expr $i + 1` done #------------------------------------------------ # Remove files and exit #------------------------------------------------ echo " " echo " The output file of t-v pairs is "$outpicks: cat $outpicks rm -f panel.*.su spanpanel.*.su picks.* par.* newpicks.* cvs.*.su
zxtstarry/src
book/data/alaska/line31-81/iva.sh
Shell
gpl-2.0
11,801
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML ><HEAD ><TITLE >Data Storage</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK REL="HOME" TITLE="The Cacti Manual" HREF="index.html"><LINK REL="UP" TITLE="Principles of Operation" HREF="operating_principles.html"><LINK REL="PREVIOUS" TITLE="Principles of Operation" HREF="operating_principles.html"><LINK REL="NEXT" TITLE="Data Presentation" HREF="data_presentation.html"><LINK REL="STYLESHEET" TYPE="text/css" HREF="manual.css"></HEAD ><BODY CLASS="SECT1" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#840084" ALINK="#0000FF" ><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="3" ALIGN="center" >The Cacti Manual</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="bottom" ><A HREF="operating_principles.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="80%" ALIGN="center" VALIGN="bottom" >Chapter 5. Principles of Operation</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="bottom" ><A HREF="data_presentation.html" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="DATA_STORAGE" >Data Storage</A ></H1 ><P > There are lots of different approaches for this task. Some may use an (SQL) database, others flat files. Cacti uses <A HREF="http://www.rrdtool.org/" TARGET="_top" ><SPAN CLASS="APPLICATION" >RRDTool</SPAN > </A > to store data. </P ><P > RRD is the acronym for Round Robin Database. RRD is a system to store and display time-series data (i.e. network bandwidth, machine-room temperature, server load average). It stores the data in a very compact way that will not expand over time, and it can create beautiful graphs. This keeps storage requirements at bay. </P ><P > Likewise, rrdtool will perform some specific tasks. It performs consolidation to combine raw data (a primary data point in rrdtool lingo) to consolidated data (a consolidated data point). This way, historical data is compressed to save space. rrdtool knows different consolidation functions: AVERAGE, MAXIMUM, MINIMUM and LAST. </P ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="operating_principles.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.html" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="data_presentation.html" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >Principles of Operation</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="operating_principles.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >Data Presentation</TD ></TR ></TABLE ></DIV ></BODY ></HTML >
londonhackspace/hackti
docs/html/data_storage.html
HTML
gpl-2.0
3,059
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Shazzrah SD%Complete: 75 SDCategory: Molten Core EndScriptData */ #include "AI/ScriptDevAI/include/sc_common.h" #include "molten_core.h" #include "AI/ScriptDevAI/base/CombatAI.h" enum { SPELL_ARCANE_EXPLOSION = 19712, SPELL_SHAZZRAH_CURSE = 19713, SPELL_MAGIC_GROUNDING = 19714, SPELL_COUNTERSPELL = 19715, SPELL_GATE_OF_SHAZZRAH = 23138 // effect spell: 23139 }; enum ShazzrahActions { SHAZZRAH_ARCANE_EXPLOSION, SHAZZRAH_SHAZZRAH_CURSE, SHAZZRAH_COUNTERSPELL, SHAZZRAH_MAGIC_GROUNDING, SHAZZRAH_GATE_OF_SHAZZRAH, SHAZZRAH_ACTION_MAX, }; struct boss_shazzrahAI : public CombatAI { boss_shazzrahAI(Creature* creature) : CombatAI(creature, SHAZZRAH_ACTION_MAX), m_instance(static_cast<ScriptedInstance*>(creature->GetInstanceData())) { AddCombatAction(SHAZZRAH_ARCANE_EXPLOSION, 6000u); AddCombatAction(SHAZZRAH_SHAZZRAH_CURSE, 10000u); AddCombatAction(SHAZZRAH_COUNTERSPELL, 15000u); AddCombatAction(SHAZZRAH_MAGIC_GROUNDING, 24000u); AddCombatAction(SHAZZRAH_GATE_OF_SHAZZRAH, 30000u); Reset(); } ScriptedInstance* m_instance; void Aggro(Unit* /*who*/) override { if (m_instance) m_instance->SetData(TYPE_SHAZZRAH, IN_PROGRESS); } void JustDied(Unit* /*killer*/) override { if (m_instance) m_instance->SetData(TYPE_SHAZZRAH, DONE); } void JustReachedHome() override { if (m_instance) m_instance->SetData(TYPE_SHAZZRAH, NOT_STARTED); } void ReceiveAIEvent(AIEventType eventType, Unit* /*sender*/, Unit* /*invoker*/, uint32 /*miscValue*/) override { if (eventType == AI_EVENT_CUSTOM_A) // succesful teleport { DoResetThreat(); DoCastSpellIfCan(nullptr, SPELL_ARCANE_EXPLOSION); } } void ExecuteAction(uint32 action) override { switch (action) { case SHAZZRAH_ARCANE_EXPLOSION: { if (DoCastSpellIfCan(nullptr, SPELL_ARCANE_EXPLOSION) == CAST_OK) ResetCombatAction(action, urand(5000, 9000)); break; } case SHAZZRAH_SHAZZRAH_CURSE: { if (DoCastSpellIfCan(nullptr, SPELL_SHAZZRAH_CURSE) == CAST_OK) ResetCombatAction(action, 20000); break; } case SHAZZRAH_COUNTERSPELL: { if (DoCastSpellIfCan(nullptr, SPELL_COUNTERSPELL) == CAST_OK) ResetCombatAction(action, urand(16000, 20000)); break; } case SHAZZRAH_MAGIC_GROUNDING: { if (DoCastSpellIfCan(nullptr, SPELL_MAGIC_GROUNDING) == CAST_OK) ResetCombatAction(action, 35000); break; } case SHAZZRAH_GATE_OF_SHAZZRAH: { // Teleporting him to a random target and casting Arcane Explosion after that. if (DoCastSpellIfCan(nullptr, SPELL_GATE_OF_SHAZZRAH) == CAST_OK) ResetCombatAction(action, 45000); break; } } } }; UnitAI* GetAI_boss_shazzrah(Creature* creature) { return new boss_shazzrahAI(creature); } void AddSC_boss_shazzrah() { Script* pNewScript = new Script; pNewScript->Name = "boss_shazzrah"; pNewScript->GetAI = &GetAI_boss_shazzrah; pNewScript->RegisterSelf(); }
spkansas/mangos-wotlk
src/game/AI/ScriptDevAI/scripts/eastern_kingdoms/molten_core/boss_shazzrah.cpp
C++
gpl-2.0
4,409
/* * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "DatabaseEnv.h" #include "GridDefines.h" #include "WaypointManager.h" #include "MapManager.h" void WaypointStore::Free() { for (UNORDERED_MAP<uint32, WaypointPath*>::const_iterator itr = waypoint_map.begin(); itr != waypoint_map.end(); ++itr) { for (WaypointPath::const_iterator it = itr->second->begin(); it != itr->second->end(); ++it) delete *it; itr->second->clear(); delete itr->second; } waypoint_map.clear(); } void WaypointStore::Load() { uint32 oldMSTime = getMSTime(); QueryResult result = WorldDatabase.Query("SELECT id,point,position_x,position_y,position_z,move_flag,delay,action,action_chance FROM waypoint_data ORDER BY id, point"); if (!result) { sLog->outErrorDb(">> Loaded 0 waypoints. DB table `waypoint_data` is empty!"); sLog->outString(); return; } uint32 count = 0; Field *fields; uint32 last_id = 0; WaypointPath* path_data = NULL; do { fields = result->Fetch(); uint32 id = fields[0].GetUInt32(); count++; WaypointData *wp = new WaypointData; if (last_id != id) path_data = new WaypointPath; float x,y,z; x = fields[2].GetFloat(); y = fields[3].GetFloat(); z = fields[4].GetFloat(); Trinity::NormalizeMapCoord(x); Trinity::NormalizeMapCoord(y); wp->id = fields[1].GetUInt32(); wp->x = x; wp->y = y; wp->z = z; wp->run = fields[5].GetBool(); wp->delay = fields[6].GetUInt32(); wp->event_id = fields[7].GetUInt32(); wp->event_chance = fields[8].GetUInt8(); path_data->push_back(wp); if (id != last_id) waypoint_map[id] = path_data; last_id = id; } while (result->NextRow()) ; sLog->outString(">> Loaded %u waypoints in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } void WaypointStore::UpdatePath(uint32 id) { if (waypoint_map.find(id)!= waypoint_map.end()) waypoint_map[id]->clear(); QueryResult result; result = WorldDatabase.PQuery("SELECT point,position_x,position_y,position_z,move_flag,delay,action,action_chance FROM waypoint_data WHERE id = %u ORDER BY point", id); if (!result) return; WaypointPath* path_data; path_data = new WaypointPath; Field *fields; do { fields = result->Fetch(); WaypointData *wp = new WaypointData; float x,y,z; x = fields[1].GetFloat(); y = fields[2].GetFloat(); z = fields[3].GetFloat(); Trinity::NormalizeMapCoord(x); Trinity::NormalizeMapCoord(y); wp->id = fields[0].GetUInt32(); wp->x = x; wp->y = y; wp->z = z; wp->run = fields[4].GetBool(); wp->delay = fields[5].GetUInt32(); wp->event_id = fields[6].GetUInt32(); wp->event_chance = fields[7].GetUInt8(); path_data->push_back(wp); } while (result->NextRow()); waypoint_map[id] = path_data; }
Demonid/lazzalf-trinitycore.copy
src/server/game/Movement/Waypoints/WaypointManager.cpp
C++
gpl-2.0
3,884
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>6. README_DEVELOPERS</title> <link rel="stylesheet" type="text/css" href="vg_basic.css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="Valgrind Documentation"> <link rel="up" href="dist.html" title="Valgrind Distribution Documents"> <link rel="prev" href="dist.readme-missing.html" title="5. README_MISSING_SYSCALL_OR_IOCTL"> <link rel="next" href="dist.readme-packagers.html" title="7. README_PACKAGERS"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <div><table class="nav" width="100%" cellspacing="3" cellpadding="3" border="0" summary="Navigation header"><tr> <td width="22px" align="center" valign="middle"><a accesskey="p" href="dist.readme-missing.html"><img src="images/prev.png" width="18" height="21" border="0" alt="Prev"></a></td> <td width="25px" align="center" valign="middle"><a accesskey="u" href="dist.html"><img src="images/up.png" width="21" height="18" border="0" alt="Up"></a></td> <td width="31px" align="center" valign="middle"><a accesskey="h" href="index.html"><img src="images/home.png" width="27" height="20" border="0" alt="Up"></a></td> <th align="center" valign="middle">Valgrind Distribution Documents</th> <td width="22px" align="center" valign="middle"><a accesskey="n" href="dist.readme-packagers.html"><img src="images/next.png" width="18" height="21" border="0" alt="Next"></a></td> </tr></table></div> <div class="chapter"> <div class="titlepage"><div><div><h1 class="title"> <a name="dist.readme-developers"></a>6. README_DEVELOPERS</h1></div></div></div> <div class="literallayout"><p><br>       <br> Building and not installing it<br> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br> To run Valgrind without having to install it, run coregrind/valgrind<br> with the VALGRIND_LIB environment variable set, where &lt;dir&gt; is the root<br> of the source tree (and must be an absolute path).  Eg:<br> <br>   VALGRIND_LIB=~/grind/head4/.in_place ~/grind/head4/coregrind/valgrind <br> <br> This allows you to compile and run with "make" instead of "make install",<br> saving you time.<br> <br> Or, you can use the 'vg-in-place' script which does that for you.<br> <br> I recommend compiling with "make --quiet" to further reduce the amount of<br> output spewed out during compilation, letting you actually see any errors,<br> warnings, etc.<br> <br> <br> Building a distribution tarball<br> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br> To build a distribution tarball from the valgrind sources:<br> <br>   make dist<br> <br> In addition to compiling, linking and packaging everything up, the command<br> will also attempt to build the documentation.<br> <br> If you only want to test whether the generated tarball is complete and runs<br> regression tests successfully, building documentation is not needed.<br> <br>   make dist BUILD_ALL_DOCS=no<br> <br> If you insist on building documentation some embarrassing instructions<br> can be found in docs/README.<br> <br> <br> Running the regression tests<br> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br> To build and run all the regression tests, run "make [--quiet] regtest".<br> <br> To run a subset of the regression tests, execute:<br> <br>   perl tests/vg_regtest &lt;name&gt;<br> <br> where &lt;name&gt; is a directory (all tests within will be run) or a single<br> .vgtest test file, or the name of a program which has a like-named .vgtest<br> file.  Eg:<br> <br>   perl tests/vg_regtest memcheck<br>   perl tests/vg_regtest memcheck/tests/badfree.vgtest<br>   perl tests/vg_regtest memcheck/tests/badfree<br> <br> <br> Running the performance tests<br> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br> To build and run all the performance tests, run "make [--quiet] perf".<br> <br> To run a subset of the performance suite, execute:<br> <br>   perl perf/vg_perf &lt;name&gt;<br> <br> where &lt;name&gt; is a directory (all tests within will be run) or a single<br> .vgperf test file, or the name of a program which has a like-named .vgperf<br> file.  Eg:<br> <br>   perl perf/vg_perf perf/<br>   perl perf/vg_perf perf/bz2.vgperf<br>   perl perf/vg_perf perf/bz2<br> <br> To compare multiple versions of Valgrind, use the --vg= option multiple<br> times.  For example, if you have two Valgrinds next to each other, one in<br> trunk1/ and one in trunk2/, from within either trunk1/ or trunk2/ do this to<br> compare them on all the performance tests:<br> <br>   perl perf/vg_perf --vg=../trunk1 --vg=../trunk2 perf/<br> <br> <br> Debugging Valgrind with GDB<br> ~~~~~~~~~~~~~~~~~~~~~~~~~~~<br> To debug the valgrind launcher program (&lt;prefix&gt;/bin/valgrind) just<br> run it under gdb in the normal way.<br> <br> Debugging the main body of the valgrind code (and/or the code for<br> a particular tool) requires a bit more trickery but can be achieved<br> without too much problem by following these steps:<br> <br> (1) Set VALGRIND_LAUNCHER to point to the valgrind executable.  Eg:<br> <br>       export VALGRIND_LAUNCHER=/usr/local/bin/valgrind<br> <br>     or for an uninstalled version in a source directory $DIR:<br> <br>       export VALGRIND_LAUNCHER=$DIR/coregrind/valgrind<br> <br> (2) Run gdb on the tool executable.  Eg:<br> <br>       gdb /usr/local/lib/valgrind/ppc32-linux/lackey<br> <br>     or<br> <br>       gdb $DIR/.in_place/x86-linux/memcheck<br> <br> (3) Do "handle SIGSEGV SIGILL nostop noprint" in GDB to prevent GDB from<br>     stopping on a SIGSEGV or SIGILL:<br> <br>     (gdb) handle SIGILL SIGSEGV nostop noprint<br> <br> (4) Set any breakpoints you want and proceed as normal for gdb. The<br>     macro VG_(FUNC) is expanded to vgPlain_FUNC, so If you want to set<br>     a breakpoint VG_(do_exec), you could do like this in GDB:<br> <br>     (gdb) b vgPlain_do_exec<br> <br> (5) Run the tool with required options (the --tool option is required<br>     for correct setup), e.g.<br> <br>     (gdb) run --tool=lackey pwd<br> <br> Steps (1)--(3) can be put in a .gdbinit file, but any directory names must<br> be fully expanded (ie. not an environment variable).<br> <br> A different and possibly easier way is as follows:<br> <br> (1) Run Valgrind as normal, but add the flag --wait-for-gdb=yes.  This<br>     puts the tool executable into a wait loop soon after it gains<br>     control.  This delays startup for a few seconds.<br> <br> (2) In a different shell, do "gdb /proc/&lt;pid&gt;/exe &lt;pid&gt;", where<br>     &lt;pid&gt; you read from the output printed by (1).  This attaches<br>     GDB to the tool executable, which should be in the abovementioned<br>     wait loop.<br> <br> (3) Do "cont" to continue.  After the loop finishes spinning, startup<br>     will continue as normal.  Note that comment (3) above re passing<br>     signals applies here too.<br> <br> <br> Self-hosting<br> ~~~~~~~~~~~~<br> This section explains :<br>   (A) How to configure Valgrind to run under Valgrind.<br>       Such a setup is called self hosting, or outer/inner setup.<br>   (B) How to run Valgrind regression tests in a 'self-hosting' mode,<br>       e.g. to verify Valgrind has no bugs such as memory leaks.<br>   (C) How to run Valgrind performance tests in a 'self-hosting' mode,<br>       to analyse and optimise the performance of Valgrind and its tools.<br> <br> (A) How to configure Valgrind to run under Valgrind:<br> <br> (1) Check out 2 trees, "Inner" and "Outer".  Inner runs the app<br>     directly.  Outer runs Inner.<br> <br> (2) Configure inner with --enable-inner and build/install as usual.<br> <br> (3) Configure Outer normally and build/install as usual.<br> <br> (4) Choose a very simple program (date) and try<br> <br>     outer/.../bin/valgrind --sim-hints=enable-outer --trace-children=yes  \<br>        --smc-check=all-non-file \<br>        --run-libc-freeres=no --tool=cachegrind -v \<br>        inner/.../bin/valgrind --vgdb-prefix=./inner --tool=none -v prog<br> <br> Note: You must use a "make install"-ed valgrind.<br> Do *not* use vg-in-place for the outer valgrind.<br> <br> If you omit the --trace-children=yes, you'll only monitor Inner's launcher<br> program, not its stage2. Outer needs --run-libc-freeres=no, as otherwise<br> it will try to find and run __libc_freeres in the inner, while libc is not<br> used by the inner. Inner needs --vgdb-prefix=./inner to avoid inner<br> gdbserver colliding with outer gdbserver.<br> Currently, inner does *not* use the client request <br> VALGRIND_DISCARD_TRANSLATIONS for the JITted code or the code patched for<br> translation chaining. So the outer needs --smc-check=all-non-file to<br> detect the modified code.<br> <br> Debugging the whole thing might imply to use up to 3 GDB:<br>   * a GDB attached to the Outer valgrind, allowing<br>     to examine the state of Outer.<br>   * a GDB using Outer gdbserver, allowing to<br>     examine the state of Inner.<br>   * a GDB using Inner gdbserver, allowing to<br>     examine the state of prog.<br> <br> The whole thing is fragile, confusing and slow, but it does work well enough<br> for you to get some useful performance data.  Inner has most of<br> its output (ie. those lines beginning with "==&lt;pid&gt;==") prefixed with a '&gt;',<br> which helps a lot. However, when running regression tests in an Outer/Inner<br> setup, this prefix causes the reg test diff to fail. Give <br> --sim-hints=no-inner-prefix to the Inner to disable the production<br> of the prefix in the stdout/stderr output of Inner.<br> <br> The allocator (coregrind/m_mallocfree.c) is annotated with client requests<br> so Memcheck can be used to find leaks and use after free in an Inner<br> Valgrind.<br> <br> The Valgrind "big lock" is annotated with helgrind client requests<br> so helgrind and drd can be used to find race conditions in an Inner<br> Valgrind.<br> <br> All this has not been tested much, so don't be surprised if you hit problems.<br> <br> When using self-hosting with an outer Callgrind tool, use '--pop-on-jump'<br> (on the outer). Otherwise, Callgrind has much higher memory requirements. <br> <br> (B) Regression tests in an outer/inner setup:<br> <br>  To run all the regression tests with an outer memcheck, do :<br>    perl tests/vg_regtest --outer-valgrind=../outer/.../bin/valgrind \<br>                          --all<br> <br>  To run a specific regression tests with an outer memcheck, do:<br>    perl tests/vg_regtest --outer-valgrind=../outer/.../bin/valgrind \<br>                          none/tests/args.vgtest<br> <br>  To run regression tests with another outer tool:<br>    perl tests/vg_regtest --outer-valgrind=../outer/.../bin/valgrind \<br>                          --outer-tool=helgrind --all<br> <br>  --outer-args allows to give specific arguments to the outer tool,<br>  replacing the default one provided by vg_regtest.<br> <br> Note: --outer-valgrind must be a "make install"-ed valgrind.<br> Do *not* use vg-in-place.<br> <br> When an outer valgrind runs an inner valgrind, a regression test<br> produces one additional file &lt;testname&gt;.outer.log which contains the<br> errors detected by the outer valgrind.  E.g. for an outer memcheck, it<br> contains the leaks found in the inner, for an outer helgrind or drd,<br> it contains the detected race conditions.<br> <br> The file tests/outer_inner.supp contains suppressions for <br> the irrelevant or benign errors found in the inner.<br> <br> (C) Performance tests in an outer/inner setup:<br> <br>  To run all the performance tests with an outer cachegrind, do :<br>     perl perf/vg_perf --outer-valgrind=../outer/.../bin/valgrind perf<br> <br>  To run a specific perf test (e.g. bz2) in this setup, do :<br>     perl perf/vg_perf --outer-valgrind=../outer/.../bin/valgrind perf/bz2<br> <br>  To run all the performance tests with an outer callgrind, do :<br>     perl perf/vg_perf --outer-valgrind=../outer/.../bin/valgrind \<br>                       --outer-tool=callgrind perf<br> <br> Note: --outer-valgrind must be a "make install"-ed valgrind.<br> Do *not* use vg-in-place.<br> <br>  To compare the performance of multiple Valgrind versions, do :<br>     perl perf/vg_perf --outer-valgrind=../outer/.../bin/valgrind \<br>       --outer-tool=callgrind \<br>       --vg=../inner_xxxx --vg=../inner_yyyy perf<br>   (where inner_xxxx and inner_yyyy are the toplevel directories of<br>   the versions to compare).<br>   Cachegrind and cg_diff are particularly handy to obtain a delta<br>   between the two versions.<br> <br> When the outer tool is callgrind or cachegrind, the following<br> output files will be created for each test:<br>    &lt;outertoolname&gt;.out.&lt;inner_valgrind_dir&gt;.&lt;tt&gt;.&lt;perftestname&gt;.&lt;pid&gt;<br>    &lt;outertoolname&gt;.outer.log.&lt;inner_valgrind_dir&gt;.&lt;tt&gt;.&lt;perftestname&gt;.&lt;pid&gt;<br>  (where tt is the two letters abbreviation for the inner tool(s) run).<br> <br> For example, the command<br>     perl perf/vg_perf \<br>       --outer-valgrind=../outer_trunk/install/bin/valgrind \<br>       --outer-tool=callgrind \<br>       --vg=../inner_tchain --vg=../inner_trunk perf/many-loss-records<br> <br> produces the files<br>     callgrind.out.inner_tchain.no.many-loss-records.18465<br>     callgrind.outer.log.inner_tchain.no.many-loss-records.18465<br>     callgrind.out.inner_tchain.me.many-loss-records.21899<br>     callgrind.outer.log.inner_tchain.me.many-loss-records.21899<br>     callgrind.out.inner_trunk.no.many-loss-records.21224<br>     callgrind.outer.log.inner_trunk.no.many-loss-records.21224<br>     callgrind.out.inner_trunk.me.many-loss-records.22916<br>     callgrind.outer.log.inner_trunk.me.many-loss-records.22916<br> <br> <br> Printing out problematic blocks<br> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br> If you want to print out a disassembly of a particular block that<br> causes a crash, do the following.<br> <br> Try running with "--vex-guest-chase-thresh=0 --trace-flags=10000000<br> --trace-notbelow=999999".  This should print one line for each block<br> translated, and that includes the address.<br> <br> Then re-run with 999999 changed to the highest bb number shown.<br> This will print the one line per block, and also will print a<br> disassembly of the block in which the fault occurred.<br> <br>     </p></div> </div> <div> <br><table class="nav" width="100%" cellspacing="3" cellpadding="2" border="0" summary="Navigation footer"> <tr> <td rowspan="2" width="40%" align="left"> <a accesskey="p" href="dist.readme-missing.html">&lt;&lt; 5. README_MISSING_SYSCALL_OR_IOCTL</a> </td> <td width="20%" align="center"><a accesskey="u" href="dist.html">Up</a></td> <td rowspan="2" width="40%" align="right"> <a accesskey="n" href="dist.readme-packagers.html">7. README_PACKAGERS &gt;&gt;</a> </td> </tr> <tr><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td></tr> </table> </div> </body> </html>
acarno/slicer
valgrind/docs/html/dist.readme-developers.html
HTML
gpl-2.0
14,912
unitDef = { unitname = [[amphcon]], name = [[Conch]], description = [[Amphibious Construction Bot, Builds at 7.5 m/s]], acceleration = 0.4, activateWhenBuilt = true, brakeRate = 0.25, buildCostMetal = 180, buildDistance = 128, builder = true, buildoptions = { }, buildPic = [[amphcon.png]], canMove = true, canPatrol = true, category = [[LAND UNARMED]], corpse = [[DEAD]], customParams = { amph_regen = 10, amph_submerged_at = 40, }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[builder]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 850, maxSlope = 36, maxVelocity = 1.7, minCloakDistance = 75, movementClass = [[AKBOT2]], objectName = [[amphcon.s3o]], selfDestructAs = [[BIG_UNITEX]], script = [[amphcon.lua]], showNanoSpray = false, sightDistance = 375, sonarDistance = 375, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ChickenTrackPointy]], trackWidth = 22, turnRate = 1000, upright = false, workerTime = 7.5, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[amphcon_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ amphcon = unitDef })
N0U/Zero-K
units/amphcon.lua
Lua
gpl-2.0
1,878
/* Copyright (c) 2009-2014, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef ELEM_CONTROL_IMPL_HPP #define ELEM_CONTROL_IMPL_HPP #include "./Lyapunov.hpp" #include "./Sylvester.hpp" #include "./Ricatti.hpp" #endif // ifndef ELEM_CONTROL_IMPL_HPP
kimjsung/madness-original
src/madness/external/elemental/include/elemental/control/impl.hpp
C++
gpl-2.0
457
package edu.stanford.nlp.ie; import edu.stanford.nlp.ie.regexp.NumberSequenceClassifier; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.tokensregex.Env; import edu.stanford.nlp.ling.tokensregex.TokenSequenceMatcher; import edu.stanford.nlp.ling.tokensregex.TokenSequencePattern; import edu.stanford.nlp.pipeline.ChunkAnnotationUtils; import edu.stanford.nlp.pipeline.CoreMapAggregator; import edu.stanford.nlp.pipeline.CoreMapAttributeAggregator; import edu.stanford.nlp.util.*; import java.math.BigDecimal; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Provides functions for converting words to numbers * Unlike QuantifiableEntityNormalizer that normalizes various * types of quantifiable entities like money and dates, * NumberNormalizer only normalizes numeric expressions * (e.g. one =&gt; 1, two hundred =&gt; 200.0 ) * * <br> * This code is somewhat hacked together, so should be reworked. * * <br> * There is a library in perl for parsing english numbers: * http://blog.cordiner.net/2010/01/02/parsing-english-numbers-with-perl/ * * <p> * TODO: To be merged into QuantifiableEntityNormalizer. * It can be used by QuantifiableEntityNormalizer * to first convert numbers expressed as words * into numeric quantities before figuring * out how to do higher level combos * (like one hundred dollars and five cents) * <br> * TODO: Known to not handle the following: * oh: two oh one * non-integers: one and a half, one point five, three fifth * funky numbers: pi * <br> * TODO: This class is very language dependent * Should really be AmericanEnglishNumberNormalizer * <br> * TODO: Make things not static * * @author Angel Chang */ public class NumberNormalizer { private NumberNormalizer() {} // static class private static final Logger logger = Logger.getLogger(NumberNormalizer.class.getName()); // TODO: make this not static, let different NumberNormalizers use // different loggers public static void setVerbose(boolean verbose) { if (verbose) { logger.setLevel(Level.FINE); } else { logger.setLevel(Level.SEVERE); } } // Need these in order - first must come after 21st //public static final Pattern teOrdinalWords = Pattern.compile("(?i)(tenth|eleventh|twelfth|thirteenth|fourteenth|fifteenth|sixteenth|seventeenth|eighteenth|nineteenth|twentieth|twenty-first|twenty-second|twenty-third|twenty-fourth|twenty-fifth|twenty-sixth|twenty-seventh|twenty-eighth|twenty-ninth|thirtieth|thirty-first|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth)"); //static final Pattern teNumOrds = Pattern.compile("(?i)([23]?1-?st|11-?th|[23]?2-?nd|12-?th|[12]?3-?rd|13-?th|[12]?[4-90]-?th|30-?th)"); //static final Pattern unitNumsPattern = Pattern.compile("(?i)(one|two|three|four|five|six|seven|eight|nine)"); //static final Pattern uniqueNumsPattern = Pattern.compile("(?i)(ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)"); //static final Pattern tensNumsPattern = Pattern.compile("(?i)(twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)"); private static final Pattern numUnitPattern = Pattern.compile("(?i)(hundred|thousand|million|billion|trillion)"); private static final Pattern numEndUnitPattern = Pattern.compile("(?i)(gross|dozen|score)"); /***********************/ private static final Pattern numberTermPattern = Pattern.compile("(?i)(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|billion|trillion|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh|twelfth|thirteenth|fourteenth|fifteenth|sixteenth|seventeenth|eighteenth|nineteenth|twentieth|thirtieth|fortieth|fiftieth|sixtieth|seventieth|eightieth|ninetieth|hundred?th|thousandth|millionth|billionth|trillionth)"); private static final Pattern numberTermPattern2 = Pattern.compile("(?i)(" + numberTermPattern.pattern() + "(-" + numberTermPattern.pattern() + ")?)"); private static final Pattern ordinalUnitPattern = Pattern.compile("(?i)(hundredth|thousandth|millionth)"); // private static final String[] unitWords = {"trillion", "billion", "million", "thousand", "hundred"}; // private static final String[] endUnitWords = {"gross", "dozen", "score"}; // Converts numbers in words to numeric form // works through trillions protected static final Pattern digitsPattern = Pattern.compile("\\d+"); private static final Pattern numPattern = Pattern.compile("[-+]?(?:\\d+(?:,\\d\\d\\d)*(?:\\.\\d*)?|\\.\\d+)"); private static final Pattern numRangePattern = Pattern.compile("(" + numPattern.pattern() + ")-(" + numPattern.pattern() + ")"); // private static final Pattern[] endUnitWordsPattern = new Pattern[endUnitWords.length]; // private static final Pattern[] unitWordsPattern = new Pattern[unitWords.length]; // static { // int i = 0; // for (String uw:endUnitWords) { // endUnitWordsPattern[i] = Pattern.compile("(.*)\\s*" + Pattern.quote(uw) + "\\s*(.*)"); // i++; // } // int ii = 0; // for (String uw:unitWords) { // unitWordsPattern[ii] = Pattern.compile("(.*)\\s*" + Pattern.quote(uw) + "\\s*(.*)"); // ii++; // } // } // TODO: similar to QuantifiableEntityNormalizer.wordsToValues // QuantifiableEntityNormalizer also has bn (for billion) // should consolidate // here we use Number representation instead of double... private static final Map<String,Number> word2NumMap = Generics.newHashMap(); static { // Special words for numbers word2NumMap.put("dozen", 12); word2NumMap.put("score", 20); word2NumMap.put("gross", 144); word2NumMap.put("quarter", 0.25); word2NumMap.put("half", 0.5); word2NumMap.put("oh", 0); word2NumMap.put("a" , 1); word2NumMap.put("an" , 1); // Standard words for numbers word2NumMap.put("zero", 0); word2NumMap.put("one", 1); word2NumMap.put("two", 2); word2NumMap.put("three", 3); word2NumMap.put("four", 4); word2NumMap.put("five", 5); word2NumMap.put("six", 6); word2NumMap.put("seven", 7); word2NumMap.put("eight", 8); word2NumMap.put("nine", 9); word2NumMap.put("ten", 10); word2NumMap.put("eleven", 11); word2NumMap.put("twelve", 12); word2NumMap.put("thirteen", 13); word2NumMap.put("fourteen", 14); word2NumMap.put("fifteen", 15); word2NumMap.put("sixteen", 16); word2NumMap.put("seventeen", 17); word2NumMap.put("eighteen", 18); word2NumMap.put("nineteen", 19); word2NumMap.put("twenty", 20); word2NumMap.put("thirty", 30); word2NumMap.put("forty", 40); word2NumMap.put("fifty", 50); word2NumMap.put("sixty", 60); word2NumMap.put("seventy", 70); word2NumMap.put("eighty", 80); word2NumMap.put("ninety", 90); word2NumMap.put("hundred", 100); word2NumMap.put("thousand", 1000); word2NumMap.put("million", 1000000); word2NumMap.put("billion", 1000000000); word2NumMap.put("trillion", 1000000000000L); } // similar to QuantifiableEntityNormalizer.ordinalsToValues private static final Map<String,Number> ordWord2NumMap = Generics.newHashMap(); static { ordWord2NumMap.put("zeroth", 0); ordWord2NumMap.put("first", 1); ordWord2NumMap.put("second", 2); ordWord2NumMap.put("third", 3); ordWord2NumMap.put("fourth", 4); ordWord2NumMap.put("fifth", 5); ordWord2NumMap.put("sixth", 6); ordWord2NumMap.put("seventh", 7); ordWord2NumMap.put("eighth", 8); ordWord2NumMap.put("ninth", 9); ordWord2NumMap.put("tenth", 10); ordWord2NumMap.put("eleventh", 11); ordWord2NumMap.put("twelfth", 12); ordWord2NumMap.put("thirteenth", 13); ordWord2NumMap.put("fourteenth", 14); ordWord2NumMap.put("fifteenth", 15); ordWord2NumMap.put("sixteenth", 16); ordWord2NumMap.put("seventeenth", 17); ordWord2NumMap.put("eighteenth", 18); ordWord2NumMap.put("nineteenth", 19); ordWord2NumMap.put("twentieth", 20); ordWord2NumMap.put("thirtieth", 30); ordWord2NumMap.put("fortieth", 40); ordWord2NumMap.put("fiftieth", 50); ordWord2NumMap.put("sixtieth", 60); ordWord2NumMap.put("seventieth", 70); ordWord2NumMap.put("eightieth", 80); ordWord2NumMap.put("ninetieth", 90); ordWord2NumMap.put("hundredth", 100); ordWord2NumMap.put("hundreth", 100); // really a spelling error ordWord2NumMap.put("thousandth", 1000); ordWord2NumMap.put("millionth", 1000000); ordWord2NumMap.put("billionth", 1000000000); ordWord2NumMap.put("trillionth", 1000000000000L); } // Seems to work better than quantifiable entity normalizer's numeric conversion private static final Pattern alphaPattern = Pattern.compile("([a-zA-Z]+)"); private static final Pattern wsPattern = Pattern.compile("\\s+"); /** * Fairly generous utility function to convert a string representing * a number (hopefully) to a Number. * Assumes that something else has somehow determined that the string * makes ONE suitable number. * The value of the number is determined by: * 0. Breaking up the string into pieces using whitespace * (stuff like "and", "-", "," is turned into whitespace); * 1. Determining the numeric value of the pieces; * 2. Finding the numeric value of each piece; * 3. Combining the pieces together to form the overall value: * a. Find the largest component and its value (X), * b. Let B = overall value of pieces to the left (recursive), * c. Let C = overall value of pieces to the right recursive), * d. The overall value = B*X + C. * * @param str The String to convert * @return numeric value of string */ public static Number wordToNumber(String str){ if (str.trim().equals("")) { return null; } boolean neg = false; String originalString = str; // Trims and lowercases stuff str = str.trim(); str = str.toLowerCase(); if (str.startsWith("-")) { neg = true; } // eliminate hyphens, commas, and the word "and" str = str.replaceAll("\\band\\b", " "); str = str.replaceAll("-", " "); str = str.replaceAll("(\\d),(\\d)", "$1$2"); // Maybe something like 4,233,000 ?? str = str.replaceAll(",", " "); // str = str.replaceAll("(\\d)(\\w)","$1 $2"); // Trims again (do we need this?) str = str.trim(); // TODO: error checking.... //if string starts with "a ", as in "a hundred", replace it with "one" if (str.startsWith("a ")) { str = str.replace("a", "one"); } // cut off some trailing s if (str.endsWith("sands")) { // thousands str = str.substring(0, str.length() - 1); } else if (str.endsWith("ions")) { // millions, billions, etc str = str.substring(0, str.length() - 1); } // now count words String[] fields = wsPattern.split(str); Number[] numFields = new Number[fields.length]; int numWords = fields.length; // get numeric value of each word piece for (int curIndex = 0; curIndex < numWords; curIndex++) { String curPart = fields[curIndex]; Matcher m = alphaPattern.matcher(curPart); if (m.find()) { // Some part of the word has alpha characters Number curNum; if (word2NumMap.containsKey(curPart)) { curNum = word2NumMap.get(curPart); } else if (ordWord2NumMap.containsKey(curPart)) { if (curIndex == numWords-1){ curNum = ordWord2NumMap.get(curPart); } else { throw new NumberFormatException("Error in wordToNumber function."); } } else if (curIndex > 0 && (curPart.endsWith("ths") || curPart.endsWith("rds"))) { // Fractions? curNum = ordWord2NumMap.get(curPart.substring(0, curPart.length()-1)); if (curNum != null) { curNum = 1/curNum.doubleValue(); } else { throw new NumberFormatException("Bad number put into wordToNumber. Word is: \"" + curPart + "\", originally part of \"" + originalString + "\", piece # " + curIndex); } } else if (Character.isDigit(curPart.charAt(0))) { if (curPart.endsWith("th") || curPart.endsWith("rd") || curPart.endsWith("nd") || curPart.endsWith("st")) { curPart = curPart.substring(0, curPart.length()-2); } if (digitsPattern.matcher(curPart).matches()) { curNum = Long.parseLong(curPart); } else{ throw new NumberFormatException("Bad number put into wordToNumber. Word is: \"" + curPart + "\", originally part of \"" + originalString + "\", piece # " + curIndex); } } else { throw new NumberFormatException("Bad number put into wordToNumber. Word is: \"" + curPart + "\", originally part of \"" + originalString + "\", piece # " + curIndex); } numFields[curIndex] = curNum; } else { // Word is all numeric if (digitsPattern.matcher(curPart).matches()) { numFields[curIndex] = Long.parseLong(curPart); } else if (numPattern.matcher(curPart).matches()) { numFields[curIndex] = new BigDecimal(curPart); } else { // Hmm, strange number throw new NumberFormatException("Bad number put into wordToNumber. Word is: \"" + curPart + "\", originally part of \"" + originalString + "\", piece # " + curIndex); } } } Number n = wordToNumberRecurse(numFields); return (neg)? -n.doubleValue():n; } private static Number wordToNumberRecurse(Number[] numFields) { return wordToNumberRecurse(numFields, 0, numFields.length); } private static Number wordToNumberRecurse(Number[] numFields, int start, int end) { // return solitary number if (end <= start) return 0; if (end - start == 1) { return numFields[start]; } // first, find highest number in string Number highestNum = Double.NEGATIVE_INFINITY; int highestNumIndex = start; for (int i = start; i < end; i++) { Number curNum = numFields[i]; if (curNum != null && curNum.doubleValue() >= highestNum.doubleValue()){ highestNum = curNum; highestNumIndex = i; } } Number beforeNum = 1; if (highestNumIndex > start) { beforeNum = wordToNumberRecurse(numFields, start, highestNumIndex); if (beforeNum == null) beforeNum = 1; } Number afterNum = wordToNumberRecurse(numFields, highestNumIndex+1, end); if (afterNum == null) afterNum = 0; // TODO: Everything is treated as double... losing precision information here // Sufficient for now // Should we usually use BigDecimal to do our calculations? // There are also fractions to consider. Number evaluatedNumber = ((beforeNum.doubleValue() * highestNum.doubleValue()) + afterNum.doubleValue()); return evaluatedNumber; } public static Env getNewEnv() { Env env = TokenSequencePattern.getNewEnv(); // Do case insensitive matching env.setDefaultStringPatternFlags(Pattern.CASE_INSENSITIVE); initEnv(env); return env; } public static void initEnv(Env env) { // Custom binding for numeric values expressions env.bind("numtype", CoreAnnotations.NumericTypeAnnotation.class); env.bind("numvalue", CoreAnnotations.NumericValueAnnotation.class); env.bind("numcomptype", CoreAnnotations.NumericCompositeTypeAnnotation.class); env.bind("numcompvalue", CoreAnnotations.NumericCompositeValueAnnotation.class); env.bind("$NUMCOMPTERM", " [ { numcomptype::EXISTS } & !{ numcomptype:NUMBER_RANGE } ] "); env.bind("$NUMTERM", " [ { numtype::EXISTS } & !{ numtype:NUMBER_RANGE } ] "); env.bind("$NUMRANGE", " [ { numtype:NUMBER_RANGE } ] "); // TODO: Improve code to only recognize integers env.bind("$INTTERM", " [ { numtype::EXISTS } & !{ numtype:NUMBER_RANGE } & !{ word:/.*\\.\\d+.*/} ] "); env.bind("$POSINTTERM", " [ { numvalue>0 } & !{ word:/.*\\.\\d+.*/} ] "); env.bind("$ORDTERM", " [ { numtype:ORDINAL } ] "); env.bind("$BEFORE_WS", " [ { before:/\\s*/ } | !{ before::EXISTS} ]"); env.bind("$AFTER_WS", " [ { after:/\\s*/ } | !{ after::EXISTS} ]"); env.bind("$BEFORE_AFTER_WS", " [ $BEFORE_WS & $AFTER_WS ]"); } private static final Env env = getNewEnv(); private static final TokenSequencePattern numberPattern = TokenSequencePattern.compile( env, "$NUMTERM ( [/,/ & $BEFORE_WS]? [$POSINTTERM & $BEFORE_WS] )* ( [/,/ & $BEFORE_WS]? [/and/ & $BEFORE_WS] [$POSINTTERM & $BEFORE_WS]+ )? "); /** * Find and mark numbers (does not need NumberSequenceClassifier) * Each token is annotated with the numeric value and type * - CoreAnnotations.NumericTypeAnnotation.class: ORDINAL, UNIT (hundred, thousand,..., dozen, gross,...), NUMBER * - CoreAnnotations.NumericValueAnnotation.class: Number representing the numeric value of the token * ( two thousand =&gt; 2 1000 ) * * Tries also to separate individual numbers like four five six, * while keeping numbers like four hundred and seven together * Annotate tokens belonging to each composite number with * - CoreAnnotations.NumericCompositeTypeAnnotation.class: ORDINAL (1st, 2nd), NUMBER (one hundred) * - CoreAnnotations.NumericCompositeValueAnnotation.class: Number representing the composite numeric value * ( two thousand =&gt; 2000 2000 ) * * Also returns list of CoreMap representing the identified numbers * * The function is overly aggressive in marking possible numbers * - should either do more checks or use in conjunction with NumberSequenceClassifier * to avoid marking certain tokens (like second/NN) as numbers... * * @param annotation The annotation structure * @return list of CoreMap representing the identified numbers */ public static List<CoreMap> findNumbers(CoreMap annotation) { List<CoreLabel> tokens = annotation.get(CoreAnnotations.TokensAnnotation.class); for (CoreLabel token:tokens) { String w = token.word(); w = w.trim().toLowerCase(); if (/*("CD".equals(token.get(CoreAnnotations.PartOfSpeechAnnotation.class)) || */ NumberNormalizer.numPattern.matcher(w).matches() || NumberNormalizer.numberTermPattern2.matcher(w).matches() || NumberSequenceClassifier.ORDINAL_PATTERN.matcher(w).matches() || NumberNormalizer.numEndUnitPattern.matcher(w).matches()) { // TODO: first ADVERB and second NN shouldn't be marked as ordinals // But maybe we don't care, this can just mark the potential numbers, something else can disregard those try { token.set(CoreAnnotations.NumericValueAnnotation.class, NumberNormalizer.wordToNumber(w)); if (NumberSequenceClassifier.ORDINAL_PATTERN.matcher(w).find()) { token.set(CoreAnnotations.NumericTypeAnnotation.class, "ORDINAL"); } else if (NumberNormalizer.numUnitPattern.matcher(w).matches()) { token.set(CoreAnnotations.NumericTypeAnnotation.class, "UNIT"); } else if (NumberNormalizer.numEndUnitPattern.matcher(w).matches()) { token.set(CoreAnnotations.NumericTypeAnnotation.class, "UNIT"); } else { token.set(CoreAnnotations.NumericTypeAnnotation.class, "NUMBER"); } } catch (Exception ex) { logger.warning("Error interpreting number " + w + ": " + ex.getMessage()); } } } // TODO: Should we allow "," in written out numbers? // TODO: Handle "-" that is not with token? TokenSequenceMatcher matcher = numberPattern.getMatcher(tokens); List<CoreMap> numbers = new ArrayList<CoreMap>(); while (matcher.find()) { @SuppressWarnings("unused") List<CoreMap> matchedTokens = matcher.groupNodes(); int numStart = matcher.start(); int possibleNumEnd = -1; int lastUnitPos = -1; int possibleNumStart = -1; Number possibleNumEndUnit = null; Number lastUnit = null; // Check if we need to split matched chunk up more for (int i = matcher.start(); i < matcher.end(); i++) { CoreLabel token = tokens.get(i); CoreLabel prev = (i > matcher.start())? tokens.get(i - 1): null; Number num = token.get(CoreAnnotations.NumericValueAnnotation.class); Number prevNum = (prev != null)? prev.get(CoreAnnotations.NumericValueAnnotation.class):null; String w = token.word(); w = w.trim().toLowerCase(); switch (w) { case ",": if (lastUnit != null && lastUnitPos == i - 1) { // OKAY, this may be one big number possibleNumEnd = i; possibleNumEndUnit = lastUnit; } else { // Not one big number if (numStart < i) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, i)); numStart = i + 1; possibleNumEnd = -1; possibleNumEndUnit = null; lastUnit = null; lastUnitPos = -1; } } if (numStart == i) { numStart = i + 1; } break; case "and": // Check if number before and was unit String prevWord = prev.word(); if (lastUnitPos == i - 1 || (lastUnitPos == i - 2 && ",".equals(prevWord))) { // Okay } else { // Two separate numbers if (numStart < possibleNumEnd) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, possibleNumEnd)); if (possibleNumStart >= possibleNumEnd) { numStart = possibleNumStart; } else { numStart = i + 1; } } else if (numStart < i) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, i)); numStart = i + 1; } if (lastUnitPos < numStart) { lastUnit = null; lastUnitPos = -1; } possibleNumEnd = -1; possibleNumEndUnit = null; } break; default: // NUMBER or ORDINAL String numType = token.get(CoreAnnotations.NumericTypeAnnotation.class); if ("UNIT".equals(numType)) { // Compare this unit with previous if (lastUnit == null || lastUnit.longValue() > num.longValue()) { // lastUnit larger than this unit // maybe four thousand two hundred? // OKAY, probably one big number } else { if (numStart < possibleNumEnd) { // Units are increasing - check if this unit is >= unit before "," (if so, need to split into chunks) // Not one big number ( had a comma ) if (num.longValue() >= possibleNumEndUnit.longValue()) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, possibleNumEnd)); if (possibleNumStart >= possibleNumEnd) { numStart = possibleNumStart; } else { numStart = i; } possibleNumEnd = -1; possibleNumEndUnit = null; } } else { // unit is increasing - can be okay, maybe five hundred thousand? // what about four hundred five thousand // unit might also be the same, as in thousand thousand, // which we convert to million } } lastUnit = num; lastUnitPos = i; } else { // Normal number if (num == null) { logger.warning("NO NUMBER: " + token.word()); continue; } if (prevNum != null) { if (num.doubleValue() > 0) { if (num.doubleValue() < 10) { // This number is a digit // Treat following as two separate numbers // \d+ [0-9] // [one to nine] [0-9] if (NumberNormalizer.numPattern.matcher(prev.word()).matches() || prevNum.longValue() < 10 || prevNum.longValue() % 10 != 0) { // two separate numbers if (numStart < i) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, i)); } numStart = i; possibleNumEnd = -1; possibleNumEndUnit = null; lastUnit = null; lastUnitPos = -1; } } else { String prevNumType = prev.get(CoreAnnotations.NumericTypeAnnotation.class); if ("UNIT".equals(prevNumType)) { // OKAY } else if (!ordinalUnitPattern.matcher(w).matches()) { // Start of new number if (numStart < i) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, i)); } numStart = i; possibleNumEnd = -1; possibleNumEndUnit = null; lastUnit = null; lastUnitPos = -1; } } } } if ("ORDINAL".equals(numType)) { if (possibleNumEnd >= 0) { if (numStart < possibleNumEnd) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, possibleNumEnd)); } if (possibleNumStart > possibleNumEnd) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, possibleNumStart, i + 1)); } else { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, possibleNumEnd + 1, i + 1)); } } else { if (numStart < i + 1) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, i + 1)); } } numStart = i + 1; possibleNumEnd = -1; possibleNumEndUnit = null; lastUnit = null; lastUnitPos = -1; } if (possibleNumStart < possibleNumEnd) { possibleNumStart = i; } } break; } } if (numStart < matcher.end()) { numbers.add(ChunkAnnotationUtils.getAnnotatedChunk(annotation, numStart, matcher.end())); } } for (CoreMap n:numbers) { String exp = n.get(CoreAnnotations.TextAnnotation.class); if (exp.trim().equals("")) { continue; } List<CoreLabel> ts = n.get(CoreAnnotations.TokensAnnotation.class); String label = ts.get(ts.size() - 1).get(CoreAnnotations.NumericTypeAnnotation.class); if ("UNIT".equals(label)) { label = "NUMBER"; } try { Number num = NumberNormalizer.wordToNumber(exp); if (num == null) { logger.warning("NO NUMBER FOR: \"" + exp + "\""); } n.set(CoreAnnotations.NumericCompositeValueAnnotation.class, num); n.set(CoreAnnotations.NumericCompositeTypeAnnotation.class, label); for (CoreLabel t:ts) { t.set(CoreAnnotations.NumericCompositeValueAnnotation.class, num); t.set(CoreAnnotations.NumericCompositeTypeAnnotation.class, label); } } catch (NumberFormatException ex) { logger.log(Level.WARNING, "Invalid number for: \"" + exp + "\"", ex); } } return numbers; } /** * Find and mark number ranges * Ranges are NUM1 [-|to] NUM2 where NUM2 > NUM1 * * Each number range is marked with * - CoreAnnotations.NumericTypeAnnotation.class: NUMBER_RANGE * - CoreAnnotations.NumericObjectAnnotation.class: {@code Pair<Number>} representing the start/end of the range * * @param annotation - annotation where numbers have already been identified * @return list of CoreMap representing the identified number ranges */ private static final TokenSequencePattern rangePattern = TokenSequencePattern.compile(env, "(?:$NUMCOMPTERM /-|to/ $NUMCOMPTERM) | $NUMRANGE"); public static List<CoreMap> findNumberRanges(CoreMap annotation) { List<CoreMap> numerizedTokens = annotation.get(CoreAnnotations.NumerizedTokensAnnotation.class); for (CoreMap token:numerizedTokens) { String w = token.get(CoreAnnotations.TextAnnotation.class); w = w.trim().toLowerCase(); Matcher rangeMatcher = NumberNormalizer.numRangePattern.matcher(w); if (rangeMatcher.matches()) { try { String w1 = rangeMatcher.group(1); String w2 = rangeMatcher.group(2); Number v1 = NumberNormalizer.wordToNumber(w1); Number v2 = NumberNormalizer.wordToNumber(w2); if (v2.doubleValue() > v1.doubleValue()) { token.set(CoreAnnotations.NumericTypeAnnotation.class, "NUMBER_RANGE"); token.set(CoreAnnotations.NumericCompositeTypeAnnotation.class, "NUMBER_RANGE"); Pair<Number,Number> range = new Pair<Number,Number>(v1,v2); token.set(CoreAnnotations.NumericCompositeObjectAnnotation.class, range); } } catch (Exception ex) { logger.warning("Error interpreting number range " + w + ": " + ex.getMessage()); } } } List<CoreMap> numberRanges = new ArrayList<CoreMap>(); TokenSequenceMatcher matcher = rangePattern.getMatcher(numerizedTokens); while (matcher.find()) { List<CoreMap> matched = matcher.groupNodes(); if (matched.size() == 1) { numberRanges.add(matched.get(0)); } else { Number v1 = matched.get(0).get(CoreAnnotations.NumericCompositeValueAnnotation.class); Number v2 = matched.get(matched.size()-1).get(CoreAnnotations.NumericCompositeValueAnnotation.class); if (v2.doubleValue() > v1.doubleValue()) { CoreMap newChunk = CoreMapAggregator.getDefaultAggregator().merge(numerizedTokens, matcher.start(), matcher.end()); newChunk.set(CoreAnnotations.NumericCompositeTypeAnnotation.class, "NUMBER_RANGE"); Pair<Number,Number> range = new Pair<Number,Number>(v1,v2); newChunk.set(CoreAnnotations.NumericCompositeObjectAnnotation.class, range); numberRanges.add(newChunk); } } } return numberRanges; } /** * Takes annotation and identifies numbers in the annotation * Returns a list of tokens (as CoreMaps) with numbers merged * As by product, also marks each individual token with the TokenBeginAnnotation and TokenEndAnnotation * - this is mainly to make it easier to the rest of the code to figure out what the token offsets are. * * Note that this copies the annotation, since it modifies token offsets in the original * @param annotationRaw The annotation to find numbers in * @return list of CoreMap representing the identified numbers */ public static List<CoreMap> findAndMergeNumbers(CoreMap annotationRaw){ //copy annotation to preserve its integrity CoreMap annotation = new ArrayCoreMap(annotationRaw); // Find and label numbers List<CoreMap> numbers = NumberNormalizer.findNumbers(annotation); CoreMapAggregator numberAggregator = CoreMapAggregator.getAggregator(CoreMapAttributeAggregator.DEFAULT_NUMERIC_AGGREGATORS, CoreAnnotations.TokensAnnotation.class); // We are going to mark the token begin and token end for each token so we can more easily deal with // ensuring correct token offsets for merging //get sentence offset Integer startTokenOffset = annotation.get(CoreAnnotations.TokenBeginAnnotation.class); if (startTokenOffset == null) { startTokenOffset = 0; } //set token offsets int i = 0; List<Integer> savedTokenBegins = new LinkedList<Integer>(); List<Integer> savedTokenEnds = new LinkedList<Integer>(); for (CoreMap c:annotation.get(CoreAnnotations.TokensAnnotation.class)) { //set token begin if( (i==0 && c.get(CoreAnnotations.TokenBeginAnnotation.class) != null) || (i > 0 && !savedTokenBegins.isEmpty()) ){ savedTokenBegins.add(c.get(CoreAnnotations.TokenBeginAnnotation.class)); } c.set(CoreAnnotations.TokenBeginAnnotation.class, i+startTokenOffset); i++; //set token end if( (i==1 && c.get(CoreAnnotations.TokenEndAnnotation.class) != null) || (i > 1 && !savedTokenEnds.isEmpty()) ){ savedTokenEnds.add(c.get(CoreAnnotations.TokenEndAnnotation.class)); } c.set(CoreAnnotations.TokenEndAnnotation.class, i+startTokenOffset); } //merge numbers final Integer startTokenOffsetFinal = startTokenOffset; List<CoreMap> mergedNumbers = numberAggregator.merge(annotation.get(CoreAnnotations.TokensAnnotation.class), numbers, in -> Interval.toInterval( in.get(CoreAnnotations.TokenBeginAnnotation.class) - startTokenOffsetFinal, in.get(CoreAnnotations.TokenEndAnnotation.class) - startTokenOffsetFinal) ); //restore token offsets if (!savedTokenBegins.isEmpty() && !savedTokenEnds.isEmpty()) { for (CoreMap c : mergedNumbers) { // get new indices int newBegin = c.get(CoreAnnotations.TokenBeginAnnotation.class) - startTokenOffset; int newEnd = c.get(CoreAnnotations.TokenEndAnnotation.class) - startTokenOffset; // get token offsets for those indices c.set(CoreAnnotations.TokenBeginAnnotation.class, savedTokenBegins.get(newBegin)); c.set(CoreAnnotations.TokenEndAnnotation.class, savedTokenEnds.get(newEnd-1)); } } //return return mergedNumbers; } public static List<CoreMap> findAndAnnotateNumericExpressions(CoreMap annotation) { List<CoreMap> mergedNumbers = NumberNormalizer.findAndMergeNumbers(annotation); annotation.set(CoreAnnotations.NumerizedTokensAnnotation.class, mergedNumbers); return mergedNumbers; } public static List<CoreMap> findAndAnnotateNumericExpressionsWithRanges(CoreMap annotation) { Integer startTokenOffset = annotation.get(CoreAnnotations.TokenBeginAnnotation.class); if (startTokenOffset == null) { startTokenOffset = 0; } List<CoreMap> mergedNumbers = NumberNormalizer.findAndMergeNumbers(annotation); annotation.set(CoreAnnotations.NumerizedTokensAnnotation.class, mergedNumbers); // Find and label number ranges List<CoreMap> numberRanges = NumberNormalizer.findNumberRanges(annotation); final Integer startTokenOffsetFinal = startTokenOffset; List<CoreMap> mergedNumbersWithRanges = CollectionUtils.mergeListWithSortedMatchedPreAggregated( annotation.get(CoreAnnotations.NumerizedTokensAnnotation.class), numberRanges, (CoreMap in) -> Interval.toInterval( in.get(CoreAnnotations.TokenBeginAnnotation.class) - startTokenOffsetFinal, in.get(CoreAnnotations.TokenEndAnnotation.class) - startTokenOffsetFinal) ); annotation.set(CoreAnnotations.NumerizedTokensAnnotation.class, mergedNumbersWithRanges); return mergedNumbersWithRanges; } }
matadorhong/CoreNLP
src/edu/stanford/nlp/ie/NumberNormalizer.java
Java
gpl-2.0
36,075
#! /bin/sh # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Test to make sure depcomp is installed and found properly # when required for multiple directories. . test-init.sh cat > configure.ac << END AC_INIT([$me], [1.0]) AM_INIT_AUTOMAKE AC_CONFIG_FILES([subdir/Makefile subdir2/Makefile]) AC_PROG_CC AC_OUTPUT END rm -f depcomp mkdir subdir mkdir subdir2 cat > subdir/Makefile.am << 'END' noinst_PROGRAMS = foo foo_SOURCES = foo.c END cp subdir/Makefile.am subdir2/Makefile.am $ACLOCAL $AUTOMAKE --add-missing # There used to be a bug where this was created in the first subdir with C # sources in it instead of in $top_srcdir or $ac_auxdir. test -f depcomp :
DDTChen/CookieVLC
vlc/extras/tools/automake/t/depcomp.sh
Shell
gpl-2.0
1,303
/* * Ftrace trace backend * * Copyright (C) 2013 Hitachi, Ltd. * Created by Eiichi Tsukata <eiichi.tsukata.xh@hitachi.com> * * This work is licensed under the terms of the GNU GPL, version 2. See * the COPYING file in the top-level directory. * */ #include "qemu/osdep.h" #include "trace.h" #include "trace/control.h" int trace_marker_fd; static int find_debugfs(char *debugfs) { char type[100]; FILE *fp; fp = fopen("/proc/mounts", "r"); if (fp == NULL) { return 0; } while (fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n", debugfs, type) == 2) { if (strcmp(type, "debugfs") == 0) { break; } } fclose(fp); if (strcmp(type, "debugfs") != 0) { return 0; } return 1; } bool ftrace_init(void) { char debugfs[PATH_MAX]; char path[PATH_MAX]; int debugfs_found; int trace_fd = -1; debugfs_found = find_debugfs(debugfs); if (debugfs_found) { snprintf(path, PATH_MAX, "%s/tracing/tracing_on", debugfs); trace_fd = open(path, O_WRONLY); if (trace_fd < 0) { if (errno == EACCES) { trace_marker_fd = open("/dev/null", O_WRONLY); if (trace_marker_fd != -1) { return true; } } perror("Could not open ftrace 'tracing_on' file"); return false; } else { if (write(trace_fd, "1", 1) < 0) { perror("Could not write to 'tracing_on' file"); close(trace_fd); return false; } close(trace_fd); } snprintf(path, PATH_MAX, "%s/tracing/trace_marker", debugfs); trace_marker_fd = open(path, O_WRONLY); if (trace_marker_fd < 0) { perror("Could not open ftrace 'trace_marker' file"); return false; } } else { fprintf(stderr, "debugfs is not mounted\n"); return false; } return true; }
gongleiarei/qemu
trace/ftrace.c
C
gpl-2.0
2,037
<?php /** * @file * Contains \Drupal\taxonomy\Tests\VocabularyUnitTest. */ namespace Drupal\taxonomy\Tests; /** * Tests for taxonomy vocabulary functions. */ class VocabularyUnitTest extends TaxonomyTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('field_test'); public static function getInfo() { return array( 'name' => 'Taxonomy vocabularies', 'description' => 'Test loading, saving and deleting vocabularies.', 'group' => 'Taxonomy', ); } function setUp() { parent::setUp(); $admin_user = $this->drupalCreateUser(array('create article content', 'administer taxonomy')); $this->drupalLogin($admin_user); $this->vocabulary = $this->createVocabulary(); } /** * Test deleting a taxonomy that contains terms. */ function testTaxonomyVocabularyDeleteWithTerms() { // Delete any existing vocabularies. foreach (entity_load_multiple('taxonomy_vocabulary') as $vocabulary) { $vocabulary->delete(); } // Assert that there are no terms left. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField(), 'There are no terms remaining.'); // Create a new vocabulary and add a few terms to it. $vocabulary = $this->createVocabulary(); $terms = array(); for ($i = 0; $i < 5; $i++) { $terms[$i] = $this->createTerm($vocabulary); } // Set up hierarchy. term 2 is a child of 1 and 4 a child of 1 and 2. $terms[2]->parent = array($terms[1]->id()); $terms[2]->save(); $terms[4]->parent = array($terms[1]->id(), $terms[2]->id()); $terms[4]->save(); // Assert that there are now 5 terms. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField(), 'There are 5 terms found.'); $vocabulary->delete(); // Assert that there are no terms left. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField(), 'All terms are deleted.'); } /** * Ensure that the vocabulary static reset works correctly. */ function testTaxonomyVocabularyLoadStaticReset() { $original_vocabulary = entity_load('taxonomy_vocabulary', $this->vocabulary->id()); $this->assertTrue(is_object($original_vocabulary), 'Vocabulary loaded successfully.'); $this->assertEqual($this->vocabulary->name, $original_vocabulary->name, 'Vocabulary loaded successfully.'); // Change the name and description. $vocabulary = $original_vocabulary; $vocabulary->name = $this->randomName(); $vocabulary->description = $this->randomName(); $vocabulary->save(); // Load the vocabulary. $new_vocabulary = entity_load('taxonomy_vocabulary', $original_vocabulary->id()); $this->assertEqual($new_vocabulary->name, $vocabulary->name, 'The vocabulary was loaded.'); // Delete the vocabulary. $this->vocabulary->delete(); $vocabularies = entity_load_multiple('taxonomy_vocabulary'); $this->assertTrue(!isset($vocabularies[$this->vocabulary->id()]), 'The vocabulary was deleted.'); } /** * Tests for loading multiple vocabularies. */ function testTaxonomyVocabularyLoadMultiple() { // Delete any existing vocabularies. foreach (entity_load_multiple('taxonomy_vocabulary') as $vocabulary) { $vocabulary->delete(); } // Create some vocabularies and assign weights. $vocabulary1 = $this->createVocabulary(); $vocabulary1->weight = 0; $vocabulary1->save(); $vocabulary2 = $this->createVocabulary(); $vocabulary2->weight = 1; $vocabulary2->save(); $vocabulary3 = $this->createVocabulary(); $vocabulary3->weight = 2; $vocabulary3->save(); // Fetch the names for all vocabularies, confirm that they are keyed by // machine name. $names = taxonomy_vocabulary_get_names(); $this->assertEqual($names[$vocabulary1->id()], $vocabulary1->id(), 'Vocabulary 1 name found.'); // Fetch the vocabularies with entity_load_multiple(), specifying IDs. // Ensure they are returned in the same order as the original array. $vocabularies = entity_load_multiple('taxonomy_vocabulary', array($vocabulary3->id(), $vocabulary2->id(), $vocabulary1->id())); $loaded_order = array_keys($vocabularies); $expected_order = array($vocabulary3->id(), $vocabulary2->id(), $vocabulary1->id()); $this->assertIdentical($loaded_order, $expected_order); // Test loading vocabularies by their properties. $controller = $this->container->get('entity.manager')->getStorage('taxonomy_vocabulary'); // Fetch vocabulary 1 by name. $vocabulary = current($controller->loadByProperties(array('name' => $vocabulary1->name))); $this->assertEqual($vocabulary->id(), $vocabulary1->id(), 'Vocabulary loaded successfully by name.'); // Fetch vocabulary 2 by name and ID. $vocabulary = current($controller->loadByProperties(array( 'name' => $vocabulary2->name, 'vid' => $vocabulary2->id(), ))); $this->assertEqual($vocabulary->id(), $vocabulary2->id(), 'Vocabulary loaded successfully by name and ID.'); } /** * Tests that machine name changes are properly reflected. */ function testTaxonomyVocabularyChangeMachineName() { // Add a field instance to the vocabulary. entity_create('field_config', array( 'name' => 'field_test', 'entity_type' => 'taxonomy_term', 'type' => 'test_field', ))->save(); entity_create('field_instance_config', array( 'field_name' => 'field_test', 'entity_type' => 'taxonomy_term', 'bundle' => $this->vocabulary->id(), ))->save(); // Change the machine name. $old_name = $this->vocabulary->id(); $new_name = drupal_strtolower($this->randomName()); $this->vocabulary->vid = $new_name; $this->vocabulary->save(); // Check that entity bundles are properly updated. $info = entity_get_bundles('taxonomy_term'); $this->assertFalse(isset($info[$old_name]), 'The old bundle name does not appear in entity_get_bundles().'); $this->assertTrue(isset($info[$new_name]), 'The new bundle name appears in entity_get_bundles().'); // Check that the field instance is still attached to the vocabulary. $this->assertTrue(field_info_instance('taxonomy_term', 'field_test', $new_name), 'The bundle name was updated correctly.'); } /** * Test uninstall and reinstall of the taxonomy module. */ function testUninstallReinstall() { // Fields and field instances attached to taxonomy term bundles should be // removed when the module is uninstalled. $this->field_name = drupal_strtolower($this->randomName() . '_field_name'); $this->field_definition = array( 'name' => $this->field_name, 'entity_type' => 'taxonomy_term', 'type' => 'text', 'cardinality' => 4 ); entity_create('field_config', $this->field_definition)->save(); $this->instance_definition = array( 'field_name' => $this->field_name, 'entity_type' => 'taxonomy_term', 'bundle' => $this->vocabulary->id(), 'label' => $this->randomName() . '_label', ); entity_create('field_instance_config', $this->instance_definition)->save(); require_once DRUPAL_ROOT . '/core/includes/install.inc'; module_uninstall(array('taxonomy')); \Drupal::moduleHandler()->install(array('taxonomy')); // Now create a vocabulary with the same name. All field instances // connected to this vocabulary name should have been removed when the // module was uninstalled. Creating a new field with the same name and // an instance of this field on the same bundle name should be successful. $this->vocabulary->enforceIsNew(); $this->vocabulary->save(); entity_create('field_config', $this->field_definition)->save(); entity_create('field_instance_config', $this->instance_definition)->save(); } }
targoo/mariquecalcus_drupal
core/modules/taxonomy/lib/Drupal/taxonomy/Tests/VocabularyUnitTest.php
PHP
gpl-2.0
7,909
/* * Allofthelights.js * Version: 1.0 * http://www.megaptery.com/allofthelights/ */ (function ($) { $.fn.allofthelights = function (options) { var defaults = { 'color': '#000000', 'opacity': '0.9', 'switch_id': 'switch', 'animation': 'fade', 'delay_turn_on': 400, 'delay_turn_off': 400, 'scrolling': true, 'clickable_bg': false, 'is_responsive': true, 'z_index': '10', 'custom_player': null, }; var options = $.extend(defaults, options); return this.each(function () { var $this = $(this), first_click = true, offset = null, height = null, width = null, width_window = null, height_window = null, button = null, switch_off = '#'+options.switch_id+'_off'; if (options.is_responsive) { var selectors = [ "iframe[src*='player.vimeo.com']", "iframe[src*='www.youtube.com']", "iframe[src*='www.dailymotion.com']", "iframe[src*='www.kickstarter.com']", "object", "embed" ]; if (options.custom_player) { selectors.push(options.custom_player); } var $allVideos = $(this).parent().find(selectors.join(',')); var style = '&shy;<style type="text/css"> \ .fluid_width_video_wrapper { \ width: 100%; \ position: relative; \ padding: 0; \ } \ \ .fluid_width_video_wrapper iframe, \ .ffluid_width_video_wrapper object, \ .fluid_width_video_wrapper embed { \ position: absolute; \ top: 0; \ left: 0; \ width: 100%; \ height: 100%; \ } \ </style>'; $('body').append(style); $allVideos.each(function(){ var $this = $(this); if (this.tagName.toLowerCase() == 'embed' && $this.parent('object').length || $this.parent('.fluid_width_video_wrapper').length) { return; } var height = ( this.tagName.toLowerCase() == 'object' || $this.attr('height') ) ? $this.attr('height') : $this.height(), width = $this.attr('width') ? $this.attr('width') : $this.width(), aspectRatio = height / width; if(!$this.attr('id')){ var videoID = 'fitvid' + Math.floor(Math.random()*999999); $this.attr('id', videoID); } $this.wrap('<div class="fluid_width_video_wrapper"></div>').parent('.fluid_width_video_wrapper').css('padding-top', (aspectRatio * 100)+"%"); $this.removeAttr('height').removeAttr('width'); }); } if (options.animation == 'none') { options.delay_turn_on = 0; options.delay_turn_off = 0; } if (options.clickable_bg) { switch_off += ', div.allofthelights_bg'; } $('body').on('click', switch_off, function() { variables(); update(); $('div.allofthelights_bg').fadeOut(+options.delay_turn_off); $('#'+options.switch_id+'_off').fadeOut(0); if (!options.scrolling) { $('body').css('overflow', 'auto'); } }).on('click', '#'+options.switch_id, function() { variables(); if (first_click) { first_click = false; var html = "<style type='text/css'>.allofthelights_bg {display:none;position:absolute;background:"+options.color+";z-index:"+options.z_index+";}</style>" + "<div id='"+options.switch_id+"_off' style='display:none;position:absolute;top:"+button.top+"px;left:"+button.left+"px;'></div>"; var i = 0; for ( i = 1 ; i <= 4 ; ++i ) { html += "<div id='allofthelights_bg"+i+"' class='allofthelights_bg'></div>" } $('body').append(html); $('.allofthelights_bg').css('opacity',+options.opacity); update(); } $('#'+options.switch_id+'_off').fadeIn(0); $('div.allofthelights_bg').fadeIn(+options.delay_turn_on); if (!options.scrolling) { $('body').css('overflow', 'hidden'); } }); $(window).on('resize', function() { var display = false; if ( $('div.allofthelights_bg').is(':visible') ) { display = true; $('div.allofthelights_bg').hide(); } variables(); update(); if (display) { $('div.allofthelights_bg').show(); } }); function variables() { offset = $this.offset(); height = $this.height(); width = $this.width(); width_window = $(document).width(); height_window = $(document).height(); button = $('#'+options.switch_id).offset(); } function update() { $('#'+options.switch_id+'_off').css({ 'top': button.top, 'left': button.left }); $('#allofthelights_bg1').css({ 'top': '0px', 'height': offset.top, 'left': '0px', 'right': '0px' }); $('#allofthelights_bg2').css({ 'height': height, 'top': offset.top, 'left': '0px', 'right': (width_window - offset.left) }); $('#allofthelights_bg3').css({ 'height': height, 'top': offset.top, 'right': '0px', 'bottom': '0px', 'left': (offset.left+width) }); $('#allofthelights_bg4').css({ 'height': (height_window-(offset.top+height)), 'top': (offset.top+height), 'bottom': '0px', 'left': '0px', 'right': '0px' }); } }); }; })(jQuery);
candidosales/zulk
wp-content/themes/zulk_wp_version_4.3.2/javascripts/jquery.allofthelights.js
JavaScript
gpl-2.0
5,393
<?php namespace Yoast\WP\SEO\Generators; use Yoast\WP\SEO\Context\Meta_Tags_Context; use Yoast\WP\SEO\Helpers\Current_Page_Helper; use Yoast\WP\SEO\Helpers\Options_Helper; use Yoast\WP\SEO\Helpers\Pagination_Helper; use Yoast\WP\SEO\Helpers\Post_Type_Helper; use Yoast\WP\SEO\Helpers\Url_Helper; use Yoast\WP\SEO\Models\Indexable; use Yoast\WP\SEO\Repositories\Indexable_Repository; /** * Represents the generator class for the breadcrumbs. */ class Breadcrumbs_Generator implements Generator_Interface { /** * The indexable repository. * * @var Indexable_Repository */ private $repository; /** * The options helper. * * @var Options_Helper */ private $options; /** * The current page helper. * * @var Current_Page_Helper */ private $current_page_helper; /** * The post type helper. * * @var Post_Type_Helper */ private $post_type_helper; /** * The URL helper. * * @var Url_Helper */ private $url_helper; /** * The pagination helper. * * @var Pagination_Helper */ private $pagination_helper; /** * Breadcrumbs_Generator constructor. * * @param Indexable_Repository $repository The repository. * @param Options_Helper $options The options helper. * @param Current_Page_Helper $current_page_helper The current page helper. * @param Post_Type_Helper $post_type_helper The post type helper. * @param Url_Helper $url_helper The URL helper. * @param Pagination_Helper $pagination_helper The pagination helper. */ public function __construct( Indexable_Repository $repository, Options_Helper $options, Current_Page_Helper $current_page_helper, Post_Type_Helper $post_type_helper, Url_Helper $url_helper, Pagination_Helper $pagination_helper ) { $this->repository = $repository; $this->options = $options; $this->current_page_helper = $current_page_helper; $this->post_type_helper = $post_type_helper; $this->url_helper = $url_helper; $this->pagination_helper = $pagination_helper; } /** * Generates the breadcrumbs. * * @param Meta_Tags_Context $context The meta tags context. * * @return array An array of associative arrays that each have a 'text' and a 'url'. */ public function generate( Meta_Tags_Context $context ) { $static_ancestors = []; $breadcrumbs_home = $this->options->get( 'breadcrumbs-home' ); if ( $breadcrumbs_home !== '' && ! \in_array( $this->current_page_helper->get_page_type(), [ 'Home_Page', 'Static_Home_Page' ], true ) ) { $front_page_id = $this->current_page_helper->get_front_page_id(); if ( $front_page_id === 0 ) { $static_ancestors[] = $this->repository->find_for_home_page(); } else { $static_ancestor = $this->repository->find_by_id_and_type( $front_page_id, 'post' ); if ( $static_ancestor->post_status !== 'unindexed' ) { $static_ancestors[] = $static_ancestor; } } } $page_for_posts = \get_option( 'page_for_posts' ); if ( $this->should_have_blog_crumb( $page_for_posts, $context ) ) { $static_ancestor = $this->repository->find_by_id_and_type( $page_for_posts, 'post' ); if ( $static_ancestor->post_status !== 'unindexed' ) { $static_ancestors[] = $static_ancestor; } } if ( $context->indexable->object_type === 'post' && $context->indexable->object_sub_type !== 'post' && $context->indexable->object_sub_type !== 'page' && $this->post_type_helper->has_archive( $context->indexable->object_sub_type ) ) { $static_ancestors[] = $this->repository->find_for_post_type_archive( $context->indexable->object_sub_type ); } if ( $context->indexable->object_type === 'term' ) { $parent = $this->get_taxonomy_post_type_parent( $context->indexable->object_sub_type ); if ( $parent && $parent !== 'post' && $this->post_type_helper->has_archive( $parent ) ) { $static_ancestors[] = $this->repository->find_for_post_type_archive( $parent ); } } // Get all ancestors of the indexable and append itself to get all indexables in the full crumb. $indexables = $this->repository->get_ancestors( $context->indexable ); $indexables[] = $context->indexable; if ( ! empty( $static_ancestors ) ) { \array_unshift( $indexables, ...$static_ancestors ); } $indexables = \apply_filters( 'wpseo_breadcrumb_indexables', $indexables, $context ); $callback = function ( Indexable $ancestor ) { $crumb = [ 'url' => $ancestor->permalink, 'text' => $ancestor->breadcrumb_title, ]; switch ( $ancestor->object_type ) { case 'post': $crumb = $this->get_post_crumb( $crumb, $ancestor ); break; case 'post-type-archive': $crumb = $this->get_post_type_archive_crumb( $crumb, $ancestor ); break; case 'term': $crumb = $this->get_term_crumb( $crumb, $ancestor ); break; case 'system-page': $crumb = $this->get_system_page_crumb( $crumb, $ancestor ); break; case 'user': $crumb = $this->get_user_crumb( $crumb, $ancestor ); break; case 'date-archive': $crumb = $this->get_date_archive_crumb( $crumb ); break; } return $crumb; }; $crumbs = \array_map( $callback, $indexables ); if ( $breadcrumbs_home !== '' ) { $crumbs[0]['text'] = $breadcrumbs_home; } $crumbs = $this->add_paged_crumb( $crumbs, $context->indexable ); /** * Filter: 'wpseo_breadcrumb_links' - Allow the developer to filter the Yoast SEO breadcrumb links, add to them, change order, etc. * * @api array $crumbs The crumbs array. */ $crumbs = \apply_filters( 'wpseo_breadcrumb_links', $crumbs ); $filter_callback = static function( $link_info, $index ) use ( $crumbs ) { /** * Filter: 'wpseo_breadcrumb_single_link_info' - Allow developers to filter the Yoast SEO Breadcrumb link information. * * @api array $link_info The breadcrumb link information. * * @param int $index The index of the breadcrumb in the list. * @param array $crumbs The complete list of breadcrumbs. */ return \apply_filters( 'wpseo_breadcrumb_single_link_info', $link_info, $index, $crumbs ); }; return \array_map( $filter_callback, $crumbs, \array_keys( $crumbs ) ); } /** * Returns the modified post crumb. * * @param array $crumb The crumb. * @param Indexable $ancestor The indexable. * * @return array The crumb. */ private function get_post_crumb( $crumb, $ancestor ) { $crumb['id'] = $ancestor->object_id; return $crumb; } /** * Returns the modified post type crumb. * * @param array $crumb The crumb. * @param Indexable $ancestor The indexable. * * @return array The crumb. */ private function get_post_type_archive_crumb( $crumb, $ancestor ) { $crumb['ptarchive'] = $ancestor->object_sub_type; return $crumb; } /** * Returns the modified term crumb. * * @param array $crumb The crumb. * @param Indexable $ancestor The indexable. * * @return array The crumb. */ private function get_term_crumb( $crumb, $ancestor ) { $crumb['term_id'] = $ancestor->object_id; return $crumb; } /** * Returns the modified system page crumb. * * @param array $crumb The crumb. * @param Indexable $ancestor The indexable. * * @return array The crumb. */ private function get_system_page_crumb( $crumb, $ancestor ) { if ( $ancestor->object_sub_type === 'search-result' ) { $crumb['text'] = $this->options->get( 'breadcrumbs-searchprefix' ) . ' ' . \esc_html( \get_search_query() ); $crumb['url'] = \get_search_link(); } elseif ( $ancestor->object_sub_type === '404' ) { $crumb['text'] = $this->options->get( 'breadcrumbs-404crumb' ); } return $crumb; } /** * Returns the modified user crumb. * * @param array $crumb The crumb. * @param Indexable $ancestor The indexable. * * @return array The crumb. */ private function get_user_crumb( $crumb, $ancestor ) { $display_name = \get_the_author_meta( 'display_name', $ancestor->object_id ); $crumb['text'] = $this->options->get( 'breadcrumbs-archiveprefix' ) . ' ' . $display_name; return $crumb; } /** * Returns the modified date archive crumb. * * @param array $crumb The crumb. * * @return array The crumb. */ protected function get_date_archive_crumb( $crumb ) { $home_url = $this->url_helper->home(); $prefix = $this->options->get( 'breadcrumbs-archiveprefix' ); if ( \is_day() ) { $day = \esc_html( \get_the_date() ); $crumb['url'] = $home_url . \get_the_date( 'Y/m/d' ) . '/'; $crumb['text'] = $prefix . ' ' . $day; } elseif ( \is_month() ) { $month = \esc_html( \trim( \single_month_title( ' ', false ) ) ); $crumb['url'] = $home_url . \get_the_date( 'Y/m' ) . '/'; $crumb['text'] = $prefix . ' ' . $month; } elseif ( \is_year() ) { $year = \get_the_date( 'Y' ); $crumb['url'] = $home_url . $year . '/'; $crumb['text'] = $prefix . ' ' . $year; } return $crumb; } /** * Returns whether or not a blog crumb should be added. * * @param int $page_for_posts The page for posts ID. * @param Meta_Tags_Context $context The meta tags context. * * @return bool Whether or not a blog crumb should be added. */ protected function should_have_blog_crumb( $page_for_posts, $context ) { // When there is no page configured as blog page. if ( \get_option( 'show_on_front' ) !== 'page' || ! $page_for_posts ) { return false; } if ( $context->indexable->object_type === 'term' ) { $parent = $this->get_taxonomy_post_type_parent( $context->indexable->object_sub_type ); return $parent === 'post'; } if ( $this->options->get( 'breadcrumbs-display-blog-page' ) !== true ) { return false; } // When the current page is the home page, searchpage or isn't a singular post. if ( \is_home() || \is_search() || ! \is_singular( 'post' ) ) { return false; } return true; } /** * Returns the post type parent of a given taxonomy. * * @param string $taxonomy The taxonomy. * * @return string|false The parent if it exists, false otherwise. */ protected function get_taxonomy_post_type_parent( $taxonomy ) { $parent = $this->options->get( 'taxonomy-' . $taxonomy . '-ptparent' ); if ( empty( $parent ) || (string) $parent === '0' ) { return false; } return $parent; } /** * Adds a crumb for the current page, if we're on an archive page or paginated post. * * @param array $crumbs The array of breadcrumbs. * @param Indexable $current_indexable The current indexable. * * @return array The breadcrumbs. */ protected function add_paged_crumb( array $crumbs, $current_indexable ) { $is_simple_page = $this->current_page_helper->is_simple_page(); // If we're not on a paged page do nothing. if ( ! $is_simple_page && ! $this->current_page_helper->is_paged() ) { return $crumbs; } // If we're not on a paginated post do nothing. if ( $is_simple_page && $current_indexable->number_of_pages === null ) { return $crumbs; } $current_page_number = $this->pagination_helper->get_current_page_number(); if ( $current_page_number <= 1 ) { return $crumbs; } $crumbs[] = [ 'text' => \sprintf( /* translators: %s expands to the current page number */ \__( 'Page %s', 'wordpress-seo' ), $current_page_number ), ]; return $crumbs; } }
TheThumbsupguy/Ross-Upholstery-Inc
wp-content/plugins/wordpress-seo/src/generators/breadcrumbs-generator.php
PHP
gpl-2.0
11,448
/** * SDHCI Controller driver for TI's OMAP SoCs * * Copyright (C) 2017 Texas Instruments * Author: Kishon Vijay Abraham I <kishon@ti.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 of * the 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, see <http://www.gnu.org/licenses/>. */ #include <linux/delay.h> #include <linux/mmc/slot-gpio.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> #include <linux/pinctrl/consumer.h> #include <linux/sys_soc.h> #include <linux/thermal.h> #include "sdhci-pltfm.h" #define SDHCI_OMAP_CON 0x12c #define CON_DW8 BIT(5) #define CON_DMA_MASTER BIT(20) #define CON_DDR BIT(19) #define CON_CLKEXTFREE BIT(16) #define CON_PADEN BIT(15) #define CON_CTPL BIT(11) #define CON_INIT BIT(1) #define CON_OD BIT(0) #define SDHCI_OMAP_DLL 0x0134 #define DLL_SWT BIT(20) #define DLL_FORCE_SR_C_SHIFT 13 #define DLL_FORCE_SR_C_MASK (0x7f << DLL_FORCE_SR_C_SHIFT) #define DLL_FORCE_VALUE BIT(12) #define DLL_CALIB BIT(1) #define SDHCI_OMAP_CMD 0x20c #define SDHCI_OMAP_PSTATE 0x0224 #define PSTATE_DLEV_DAT0 BIT(20) #define PSTATE_DATI BIT(1) #define SDHCI_OMAP_HCTL 0x228 #define HCTL_SDBP BIT(8) #define HCTL_SDVS_SHIFT 9 #define HCTL_SDVS_MASK (0x7 << HCTL_SDVS_SHIFT) #define HCTL_SDVS_33 (0x7 << HCTL_SDVS_SHIFT) #define HCTL_SDVS_30 (0x6 << HCTL_SDVS_SHIFT) #define HCTL_SDVS_18 (0x5 << HCTL_SDVS_SHIFT) #define SDHCI_OMAP_SYSCTL 0x22c #define SYSCTL_CEN BIT(2) #define SYSCTL_CLKD_SHIFT 6 #define SYSCTL_CLKD_MASK 0x3ff #define SDHCI_OMAP_STAT 0x230 #define SDHCI_OMAP_IE 0x234 #define INT_CC_EN BIT(0) #define SDHCI_OMAP_AC12 0x23c #define AC12_V1V8_SIGEN BIT(19) #define AC12_SCLK_SEL BIT(23) #define SDHCI_OMAP_CAPA 0x240 #define CAPA_VS33 BIT(24) #define CAPA_VS30 BIT(25) #define CAPA_VS18 BIT(26) #define SDHCI_OMAP_CAPA2 0x0244 #define CAPA2_TSDR50 BIT(13) #define SDHCI_OMAP_TIMEOUT 1 /* 1 msec */ #define SYSCTL_CLKD_MAX 0x3FF #define IOV_1V8 1800000 /* 180000 uV */ #define IOV_3V0 3000000 /* 300000 uV */ #define IOV_3V3 3300000 /* 330000 uV */ #define MAX_PHASE_DELAY 0x7C /* sdhci-omap controller flags */ #define SDHCI_OMAP_REQUIRE_IODELAY BIT(0) struct sdhci_omap_data { u32 offset; u8 flags; }; struct sdhci_omap_host { char *version; void __iomem *base; struct device *dev; struct regulator *pbias; bool pbias_enabled; struct sdhci_host *host; u8 bus_mode; u8 power_mode; u8 timing; u8 flags; struct pinctrl *pinctrl; struct pinctrl_state **pinctrl_state; bool is_tuning; }; static void sdhci_omap_start_clock(struct sdhci_omap_host *omap_host); static void sdhci_omap_stop_clock(struct sdhci_omap_host *omap_host); static inline u32 sdhci_omap_readl(struct sdhci_omap_host *host, unsigned int offset) { return readl(host->base + offset); } static inline void sdhci_omap_writel(struct sdhci_omap_host *host, unsigned int offset, u32 data) { writel(data, host->base + offset); } static int sdhci_omap_set_pbias(struct sdhci_omap_host *omap_host, bool power_on, unsigned int iov) { int ret; struct device *dev = omap_host->dev; if (IS_ERR(omap_host->pbias)) return 0; if (power_on) { ret = regulator_set_voltage(omap_host->pbias, iov, iov); if (ret) { dev_err(dev, "pbias set voltage failed\n"); return ret; } if (omap_host->pbias_enabled) return 0; ret = regulator_enable(omap_host->pbias); if (ret) { dev_err(dev, "pbias reg enable fail\n"); return ret; } omap_host->pbias_enabled = true; } else { if (!omap_host->pbias_enabled) return 0; ret = regulator_disable(omap_host->pbias); if (ret) { dev_err(dev, "pbias reg disable fail\n"); return ret; } omap_host->pbias_enabled = false; } return 0; } static int sdhci_omap_enable_iov(struct sdhci_omap_host *omap_host, unsigned int iov) { int ret; struct sdhci_host *host = omap_host->host; struct mmc_host *mmc = host->mmc; ret = sdhci_omap_set_pbias(omap_host, false, 0); if (ret) return ret; if (!IS_ERR(mmc->supply.vqmmc)) { ret = regulator_set_voltage(mmc->supply.vqmmc, iov, iov); if (ret) { dev_err(mmc_dev(mmc), "vqmmc set voltage failed\n"); return ret; } } ret = sdhci_omap_set_pbias(omap_host, true, iov); if (ret) return ret; return 0; } static void sdhci_omap_conf_bus_power(struct sdhci_omap_host *omap_host, unsigned char signal_voltage) { u32 reg; ktime_t timeout; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_HCTL); reg &= ~HCTL_SDVS_MASK; if (signal_voltage == MMC_SIGNAL_VOLTAGE_330) reg |= HCTL_SDVS_33; else reg |= HCTL_SDVS_18; sdhci_omap_writel(omap_host, SDHCI_OMAP_HCTL, reg); reg |= HCTL_SDBP; sdhci_omap_writel(omap_host, SDHCI_OMAP_HCTL, reg); /* wait 1ms */ timeout = ktime_add_ms(ktime_get(), SDHCI_OMAP_TIMEOUT); while (1) { bool timedout = ktime_after(ktime_get(), timeout); if (sdhci_omap_readl(omap_host, SDHCI_OMAP_HCTL) & HCTL_SDBP) break; if (WARN_ON(timedout)) return; usleep_range(5, 10); } } static void sdhci_omap_enable_sdio_irq(struct mmc_host *mmc, int enable) { struct sdhci_host *host = mmc_priv(mmc); struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); u32 reg; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); if (enable) reg |= (CON_CTPL | CON_CLKEXTFREE); else reg &= ~(CON_CTPL | CON_CLKEXTFREE); sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); sdhci_enable_sdio_irq(mmc, enable); } static inline void sdhci_omap_set_dll(struct sdhci_omap_host *omap_host, int count) { int i; u32 reg; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_DLL); reg |= DLL_FORCE_VALUE; reg &= ~DLL_FORCE_SR_C_MASK; reg |= (count << DLL_FORCE_SR_C_SHIFT); sdhci_omap_writel(omap_host, SDHCI_OMAP_DLL, reg); reg |= DLL_CALIB; sdhci_omap_writel(omap_host, SDHCI_OMAP_DLL, reg); for (i = 0; i < 1000; i++) { reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_DLL); if (reg & DLL_CALIB) break; } reg &= ~DLL_CALIB; sdhci_omap_writel(omap_host, SDHCI_OMAP_DLL, reg); } static void sdhci_omap_disable_tuning(struct sdhci_omap_host *omap_host) { u32 reg; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_AC12); reg &= ~AC12_SCLK_SEL; sdhci_omap_writel(omap_host, SDHCI_OMAP_AC12, reg); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_DLL); reg &= ~(DLL_FORCE_VALUE | DLL_SWT); sdhci_omap_writel(omap_host, SDHCI_OMAP_DLL, reg); } static int sdhci_omap_execute_tuning(struct mmc_host *mmc, u32 opcode) { struct sdhci_host *host = mmc_priv(mmc); struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); struct thermal_zone_device *thermal_dev; struct device *dev = omap_host->dev; struct mmc_ios *ios = &mmc->ios; u32 start_window = 0, max_window = 0; bool single_point_failure = false; bool dcrc_was_enabled = false; u8 cur_match, prev_match = 0; u32 length = 0, max_len = 0; u32 phase_delay = 0; int temperature; int ret = 0; u32 reg; int i; /* clock tuning is not needed for upto 52MHz */ if (ios->clock <= 52000000) return 0; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CAPA2); if (ios->timing == MMC_TIMING_UHS_SDR50 && !(reg & CAPA2_TSDR50)) return 0; thermal_dev = thermal_zone_get_zone_by_name("cpu_thermal"); if (IS_ERR(thermal_dev)) { dev_err(dev, "Unable to get thermal zone for tuning\n"); return PTR_ERR(thermal_dev); } ret = thermal_zone_get_temp(thermal_dev, &temperature); if (ret) return ret; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_DLL); reg |= DLL_SWT; sdhci_omap_writel(omap_host, SDHCI_OMAP_DLL, reg); /* * OMAP5/DRA74X/DRA72x Errata i802: * DCRC error interrupts (MMCHS_STAT[21] DCRC=0x1) can occur * during the tuning procedure. So disable it during the * tuning procedure. */ if (host->ier & SDHCI_INT_DATA_CRC) { host->ier &= ~SDHCI_INT_DATA_CRC; dcrc_was_enabled = true; } omap_host->is_tuning = true; /* * Stage 1: Search for a maximum pass window ignoring any * any single point failures. If the tuning value ends up * near it, move away from it in stage 2 below */ while (phase_delay <= MAX_PHASE_DELAY) { sdhci_omap_set_dll(omap_host, phase_delay); cur_match = !mmc_send_tuning(mmc, opcode, NULL); if (cur_match) { if (prev_match) { length++; } else if (single_point_failure) { /* ignore single point failure */ length++; } else { start_window = phase_delay; length = 1; } } else { single_point_failure = prev_match; } if (length > max_len) { max_window = start_window; max_len = length; } prev_match = cur_match; phase_delay += 4; } if (!max_len) { dev_err(dev, "Unable to find match\n"); ret = -EIO; goto tuning_error; } /* * Assign tuning value as a ratio of maximum pass window based * on temperature */ if (temperature < -20000) phase_delay = min(max_window + 4 * max_len - 24, max_window + DIV_ROUND_UP(13 * max_len, 16) * 4); else if (temperature < 20000) phase_delay = max_window + DIV_ROUND_UP(9 * max_len, 16) * 4; else if (temperature < 40000) phase_delay = max_window + DIV_ROUND_UP(8 * max_len, 16) * 4; else if (temperature < 70000) phase_delay = max_window + DIV_ROUND_UP(7 * max_len, 16) * 4; else if (temperature < 90000) phase_delay = max_window + DIV_ROUND_UP(5 * max_len, 16) * 4; else if (temperature < 120000) phase_delay = max_window + DIV_ROUND_UP(4 * max_len, 16) * 4; else phase_delay = max_window + DIV_ROUND_UP(3 * max_len, 16) * 4; /* * Stage 2: Search for a single point failure near the chosen tuning * value in two steps. First in the +3 to +10 range and then in the * +2 to -10 range. If found, move away from it in the appropriate * direction by the appropriate amount depending on the temperature. */ for (i = 3; i <= 10; i++) { sdhci_omap_set_dll(omap_host, phase_delay + i); if (mmc_send_tuning(mmc, opcode, NULL)) { if (temperature < 10000) phase_delay += i + 6; else if (temperature < 20000) phase_delay += i - 12; else if (temperature < 70000) phase_delay += i - 8; else phase_delay += i - 6; goto single_failure_found; } } for (i = 2; i >= -10; i--) { sdhci_omap_set_dll(omap_host, phase_delay + i); if (mmc_send_tuning(mmc, opcode, NULL)) { if (temperature < 10000) phase_delay += i + 12; else if (temperature < 20000) phase_delay += i + 8; else if (temperature < 70000) phase_delay += i + 8; else if (temperature < 90000) phase_delay += i + 10; else phase_delay += i + 12; goto single_failure_found; } } single_failure_found: reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_AC12); if (!(reg & AC12_SCLK_SEL)) { ret = -EIO; goto tuning_error; } sdhci_omap_set_dll(omap_host, phase_delay); omap_host->is_tuning = false; goto ret; tuning_error: omap_host->is_tuning = false; dev_err(dev, "Tuning failed\n"); sdhci_omap_disable_tuning(omap_host); ret: sdhci_reset(host, SDHCI_RESET_CMD | SDHCI_RESET_DATA); /* Reenable forbidden interrupt */ if (dcrc_was_enabled) host->ier |= SDHCI_INT_DATA_CRC; sdhci_writel(host, host->ier, SDHCI_INT_ENABLE); sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE); return ret; } static int sdhci_omap_card_busy(struct mmc_host *mmc) { u32 reg, ac12; int ret = false; struct sdhci_host *host = mmc_priv(mmc); struct sdhci_pltfm_host *pltfm_host; struct sdhci_omap_host *omap_host; u32 ier = host->ier; pltfm_host = sdhci_priv(host); omap_host = sdhci_pltfm_priv(pltfm_host); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); ac12 = sdhci_omap_readl(omap_host, SDHCI_OMAP_AC12); reg &= ~CON_CLKEXTFREE; if (ac12 & AC12_V1V8_SIGEN) reg |= CON_CLKEXTFREE; reg |= CON_PADEN; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); disable_irq(host->irq); ier |= SDHCI_INT_CARD_INT; sdhci_writel(host, ier, SDHCI_INT_ENABLE); sdhci_writel(host, ier, SDHCI_SIGNAL_ENABLE); /* * Delay is required for PSTATE to correctly reflect * DLEV/CLEV values after PADEN is set. */ usleep_range(50, 100); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_PSTATE); if ((reg & PSTATE_DATI) || !(reg & PSTATE_DLEV_DAT0)) ret = true; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); reg &= ~(CON_CLKEXTFREE | CON_PADEN); sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); sdhci_writel(host, host->ier, SDHCI_INT_ENABLE); sdhci_writel(host, host->ier, SDHCI_SIGNAL_ENABLE); enable_irq(host->irq); return ret; } static int sdhci_omap_start_signal_voltage_switch(struct mmc_host *mmc, struct mmc_ios *ios) { u32 reg; int ret; unsigned int iov; struct sdhci_host *host = mmc_priv(mmc); struct sdhci_pltfm_host *pltfm_host; struct sdhci_omap_host *omap_host; struct device *dev; pltfm_host = sdhci_priv(host); omap_host = sdhci_pltfm_priv(pltfm_host); dev = omap_host->dev; if (ios->signal_voltage == MMC_SIGNAL_VOLTAGE_330) { reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CAPA); if (!(reg & CAPA_VS33)) return -EOPNOTSUPP; sdhci_omap_conf_bus_power(omap_host, ios->signal_voltage); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_AC12); reg &= ~AC12_V1V8_SIGEN; sdhci_omap_writel(omap_host, SDHCI_OMAP_AC12, reg); iov = IOV_3V3; } else if (ios->signal_voltage == MMC_SIGNAL_VOLTAGE_180) { reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CAPA); if (!(reg & CAPA_VS18)) return -EOPNOTSUPP; sdhci_omap_conf_bus_power(omap_host, ios->signal_voltage); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_AC12); reg |= AC12_V1V8_SIGEN; sdhci_omap_writel(omap_host, SDHCI_OMAP_AC12, reg); iov = IOV_1V8; } else { return -EOPNOTSUPP; } ret = sdhci_omap_enable_iov(omap_host, iov); if (ret) { dev_err(dev, "failed to switch IO voltage to %dmV\n", iov); return ret; } dev_dbg(dev, "IO voltage switched to %dmV\n", iov); return 0; } static void sdhci_omap_set_timing(struct sdhci_omap_host *omap_host, u8 timing) { int ret; struct pinctrl_state *pinctrl_state; struct device *dev = omap_host->dev; if (!(omap_host->flags & SDHCI_OMAP_REQUIRE_IODELAY)) return; if (omap_host->timing == timing) return; sdhci_omap_stop_clock(omap_host); pinctrl_state = omap_host->pinctrl_state[timing]; ret = pinctrl_select_state(omap_host->pinctrl, pinctrl_state); if (ret) { dev_err(dev, "failed to select pinctrl state\n"); return; } sdhci_omap_start_clock(omap_host); omap_host->timing = timing; } static void sdhci_omap_set_power_mode(struct sdhci_omap_host *omap_host, u8 power_mode) { if (omap_host->bus_mode == MMC_POWER_OFF) sdhci_omap_disable_tuning(omap_host); omap_host->power_mode = power_mode; } static void sdhci_omap_set_bus_mode(struct sdhci_omap_host *omap_host, unsigned int mode) { u32 reg; if (omap_host->bus_mode == mode) return; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); if (mode == MMC_BUSMODE_OPENDRAIN) reg |= CON_OD; else reg &= ~CON_OD; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); omap_host->bus_mode = mode; } static void sdhci_omap_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct sdhci_host *host = mmc_priv(mmc); struct sdhci_pltfm_host *pltfm_host; struct sdhci_omap_host *omap_host; pltfm_host = sdhci_priv(host); omap_host = sdhci_pltfm_priv(pltfm_host); sdhci_omap_set_bus_mode(omap_host, ios->bus_mode); sdhci_omap_set_timing(omap_host, ios->timing); sdhci_set_ios(mmc, ios); sdhci_omap_set_power_mode(omap_host, ios->power_mode); } static u16 sdhci_omap_calc_divisor(struct sdhci_pltfm_host *host, unsigned int clock) { u16 dsor; dsor = DIV_ROUND_UP(clk_get_rate(host->clk), clock); if (dsor > SYSCTL_CLKD_MAX) dsor = SYSCTL_CLKD_MAX; return dsor; } static void sdhci_omap_start_clock(struct sdhci_omap_host *omap_host) { u32 reg; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_SYSCTL); reg |= SYSCTL_CEN; sdhci_omap_writel(omap_host, SDHCI_OMAP_SYSCTL, reg); } static void sdhci_omap_stop_clock(struct sdhci_omap_host *omap_host) { u32 reg; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_SYSCTL); reg &= ~SYSCTL_CEN; sdhci_omap_writel(omap_host, SDHCI_OMAP_SYSCTL, reg); } static void sdhci_omap_set_clock(struct sdhci_host *host, unsigned int clock) { struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); unsigned long clkdiv; sdhci_omap_stop_clock(omap_host); if (!clock) return; clkdiv = sdhci_omap_calc_divisor(pltfm_host, clock); clkdiv = (clkdiv & SYSCTL_CLKD_MASK) << SYSCTL_CLKD_SHIFT; sdhci_enable_clk(host, clkdiv); sdhci_omap_start_clock(omap_host); } static void sdhci_omap_set_power(struct sdhci_host *host, unsigned char mode, unsigned short vdd) { struct mmc_host *mmc = host->mmc; mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, vdd); } static int sdhci_omap_enable_dma(struct sdhci_host *host) { u32 reg; struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); reg |= CON_DMA_MASTER; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); return 0; } static unsigned int sdhci_omap_get_min_clock(struct sdhci_host *host) { struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); return clk_get_rate(pltfm_host->clk) / SYSCTL_CLKD_MAX; } static void sdhci_omap_set_bus_width(struct sdhci_host *host, int width) { struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); u32 reg; reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); if (width == MMC_BUS_WIDTH_8) reg |= CON_DW8; else reg &= ~CON_DW8; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); sdhci_set_bus_width(host, width); } static void sdhci_omap_init_74_clocks(struct sdhci_host *host, u8 power_mode) { u32 reg; ktime_t timeout; struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); if (omap_host->power_mode == power_mode) return; if (power_mode != MMC_POWER_ON) return; disable_irq(host->irq); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); reg |= CON_INIT; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); sdhci_omap_writel(omap_host, SDHCI_OMAP_CMD, 0x0); /* wait 1ms */ timeout = ktime_add_ms(ktime_get(), SDHCI_OMAP_TIMEOUT); while (1) { bool timedout = ktime_after(ktime_get(), timeout); if (sdhci_omap_readl(omap_host, SDHCI_OMAP_STAT) & INT_CC_EN) break; if (WARN_ON(timedout)) return; usleep_range(5, 10); } reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); reg &= ~CON_INIT; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); sdhci_omap_writel(omap_host, SDHCI_OMAP_STAT, INT_CC_EN); enable_irq(host->irq); } static void sdhci_omap_set_uhs_signaling(struct sdhci_host *host, unsigned int timing) { u32 reg; struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); sdhci_omap_stop_clock(omap_host); reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CON); if (timing == MMC_TIMING_UHS_DDR50 || timing == MMC_TIMING_MMC_DDR52) reg |= CON_DDR; else reg &= ~CON_DDR; sdhci_omap_writel(omap_host, SDHCI_OMAP_CON, reg); sdhci_set_uhs_signaling(host, timing); sdhci_omap_start_clock(omap_host); } void sdhci_omap_reset(struct sdhci_host *host, u8 mask) { struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); /* Don't reset data lines during tuning operation */ if (omap_host->is_tuning) mask &= ~SDHCI_RESET_DATA; sdhci_reset(host, mask); } #define CMD_ERR_MASK (SDHCI_INT_CRC | SDHCI_INT_END_BIT | SDHCI_INT_INDEX |\ SDHCI_INT_TIMEOUT) #define CMD_MASK (CMD_ERR_MASK | SDHCI_INT_RESPONSE) static u32 sdhci_omap_irq(struct sdhci_host *host, u32 intmask) { struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); struct sdhci_omap_host *omap_host = sdhci_pltfm_priv(pltfm_host); if (omap_host->is_tuning && host->cmd && !host->data_early && (intmask & CMD_ERR_MASK)) { /* * Since we are not resetting data lines during tuning * operation, data error or data complete interrupts * might still arrive. Mark this request as a failure * but still wait for the data interrupt */ if (intmask & SDHCI_INT_TIMEOUT) host->cmd->error = -ETIMEDOUT; else host->cmd->error = -EILSEQ; host->cmd = NULL; /* * Sometimes command error interrupts and command complete * interrupt will arrive together. Clear all command related * interrupts here. */ sdhci_writel(host, intmask & CMD_MASK, SDHCI_INT_STATUS); intmask &= ~CMD_MASK; } return intmask; } static struct sdhci_ops sdhci_omap_ops = { .set_clock = sdhci_omap_set_clock, .set_power = sdhci_omap_set_power, .enable_dma = sdhci_omap_enable_dma, .get_max_clock = sdhci_pltfm_clk_get_max_clock, .get_min_clock = sdhci_omap_get_min_clock, .set_bus_width = sdhci_omap_set_bus_width, .platform_send_init_74_clocks = sdhci_omap_init_74_clocks, .reset = sdhci_omap_reset, .set_uhs_signaling = sdhci_omap_set_uhs_signaling, .irq = sdhci_omap_irq, }; static int sdhci_omap_set_capabilities(struct sdhci_omap_host *omap_host) { u32 reg; int ret = 0; struct device *dev = omap_host->dev; struct regulator *vqmmc; vqmmc = regulator_get(dev, "vqmmc"); if (IS_ERR(vqmmc)) { ret = PTR_ERR(vqmmc); goto reg_put; } /* voltage capabilities might be set by boot loader, clear it */ reg = sdhci_omap_readl(omap_host, SDHCI_OMAP_CAPA); reg &= ~(CAPA_VS18 | CAPA_VS30 | CAPA_VS33); if (regulator_is_supported_voltage(vqmmc, IOV_3V3, IOV_3V3)) reg |= CAPA_VS33; if (regulator_is_supported_voltage(vqmmc, IOV_1V8, IOV_1V8)) reg |= CAPA_VS18; sdhci_omap_writel(omap_host, SDHCI_OMAP_CAPA, reg); reg_put: regulator_put(vqmmc); return ret; } static const struct sdhci_pltfm_data sdhci_omap_pdata = { .quirks = SDHCI_QUIRK_BROKEN_CARD_DETECTION | SDHCI_QUIRK_DATA_TIMEOUT_USES_SDCLK | SDHCI_QUIRK_CAP_CLOCK_BASE_BROKEN | SDHCI_QUIRK_NO_HISPD_BIT | SDHCI_QUIRK_BROKEN_ADMA_ZEROLEN_DESC, .quirks2 = SDHCI_QUIRK2_ACMD23_BROKEN | SDHCI_QUIRK2_PRESET_VALUE_BROKEN | SDHCI_QUIRK2_RSP_136_HAS_CRC | SDHCI_QUIRK2_DISABLE_HW_TIMEOUT, .ops = &sdhci_omap_ops, }; static const struct sdhci_omap_data k2g_data = { .offset = 0x200, }; static const struct sdhci_omap_data dra7_data = { .offset = 0x200, .flags = SDHCI_OMAP_REQUIRE_IODELAY, }; static const struct of_device_id omap_sdhci_match[] = { { .compatible = "ti,dra7-sdhci", .data = &dra7_data }, { .compatible = "ti,k2g-sdhci", .data = &k2g_data }, {}, }; MODULE_DEVICE_TABLE(of, omap_sdhci_match); static struct pinctrl_state *sdhci_omap_iodelay_pinctrl_state(struct sdhci_omap_host *omap_host, char *mode, u32 *caps, u32 capmask) { struct device *dev = omap_host->dev; char *version = omap_host->version; struct pinctrl_state *pinctrl_state = ERR_PTR(-ENODEV); char str[20]; if (!(*caps & capmask)) goto ret; if (version) { snprintf(str, 20, "%s-%s", mode, version); pinctrl_state = pinctrl_lookup_state(omap_host->pinctrl, str); } if (IS_ERR(pinctrl_state)) pinctrl_state = pinctrl_lookup_state(omap_host->pinctrl, mode); if (IS_ERR(pinctrl_state)) { dev_err(dev, "no pinctrl state for %s mode", mode); *caps &= ~capmask; } ret: return pinctrl_state; } static int sdhci_omap_config_iodelay_pinctrl_state(struct sdhci_omap_host *omap_host) { struct device *dev = omap_host->dev; struct sdhci_host *host = omap_host->host; struct mmc_host *mmc = host->mmc; u32 *caps = &mmc->caps; u32 *caps2 = &mmc->caps2; struct pinctrl_state *state; struct pinctrl_state **pinctrl_state; if (!(omap_host->flags & SDHCI_OMAP_REQUIRE_IODELAY)) return 0; pinctrl_state = devm_kcalloc(dev, MMC_TIMING_MMC_HS200 + 1, sizeof(*pinctrl_state), GFP_KERNEL); if (!pinctrl_state) return -ENOMEM; omap_host->pinctrl = devm_pinctrl_get(omap_host->dev); if (IS_ERR(omap_host->pinctrl)) { dev_err(dev, "Cannot get pinctrl\n"); return PTR_ERR(omap_host->pinctrl); } state = pinctrl_lookup_state(omap_host->pinctrl, "default"); if (IS_ERR(state)) { dev_err(dev, "no pinctrl state for default mode\n"); return PTR_ERR(state); } pinctrl_state[MMC_TIMING_LEGACY] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "sdr104", caps, MMC_CAP_UHS_SDR104); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_UHS_SDR104] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "ddr50", caps, MMC_CAP_UHS_DDR50); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_UHS_DDR50] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "sdr50", caps, MMC_CAP_UHS_SDR50); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_UHS_SDR50] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "sdr25", caps, MMC_CAP_UHS_SDR25); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_UHS_SDR25] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "sdr12", caps, MMC_CAP_UHS_SDR12); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_UHS_SDR12] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "ddr_1_8v", caps, MMC_CAP_1_8V_DDR); if (!IS_ERR(state)) { pinctrl_state[MMC_TIMING_MMC_DDR52] = state; } else { state = sdhci_omap_iodelay_pinctrl_state(omap_host, "ddr_3_3v", caps, MMC_CAP_3_3V_DDR); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_MMC_DDR52] = state; } state = sdhci_omap_iodelay_pinctrl_state(omap_host, "hs", caps, MMC_CAP_SD_HIGHSPEED); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_SD_HS] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "hs", caps, MMC_CAP_MMC_HIGHSPEED); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_MMC_HS] = state; state = sdhci_omap_iodelay_pinctrl_state(omap_host, "hs200_1_8v", caps2, MMC_CAP2_HS200_1_8V_SDR); if (!IS_ERR(state)) pinctrl_state[MMC_TIMING_MMC_HS200] = state; omap_host->pinctrl_state = pinctrl_state; return 0; } static const struct soc_device_attribute sdhci_omap_soc_devices[] = { { .machine = "DRA7[45]*", .revision = "ES1.[01]", }, { /* sentinel */ } }; static int sdhci_omap_probe(struct platform_device *pdev) { int ret; u32 offset; struct device *dev = &pdev->dev; struct sdhci_host *host; struct sdhci_pltfm_host *pltfm_host; struct sdhci_omap_host *omap_host; struct mmc_host *mmc; const struct of_device_id *match; struct sdhci_omap_data *data; const struct soc_device_attribute *soc; match = of_match_device(omap_sdhci_match, dev); if (!match) return -EINVAL; data = (struct sdhci_omap_data *)match->data; if (!data) { dev_err(dev, "no sdhci omap data\n"); return -EINVAL; } offset = data->offset; host = sdhci_pltfm_init(pdev, &sdhci_omap_pdata, sizeof(*omap_host)); if (IS_ERR(host)) { dev_err(dev, "Failed sdhci_pltfm_init\n"); return PTR_ERR(host); } pltfm_host = sdhci_priv(host); omap_host = sdhci_pltfm_priv(pltfm_host); omap_host->host = host; omap_host->base = host->ioaddr; omap_host->dev = dev; omap_host->power_mode = MMC_POWER_UNDEFINED; omap_host->timing = MMC_TIMING_LEGACY; omap_host->flags = data->flags; host->ioaddr += offset; mmc = host->mmc; sdhci_get_of_property(pdev); ret = mmc_of_parse(mmc); if (ret) goto err_pltfm_free; soc = soc_device_match(sdhci_omap_soc_devices); if (soc) { omap_host->version = "rev11"; if (!strcmp(dev_name(dev), "4809c000.mmc")) mmc->f_max = 96000000; if (!strcmp(dev_name(dev), "480b4000.mmc")) mmc->f_max = 48000000; if (!strcmp(dev_name(dev), "480ad000.mmc")) mmc->f_max = 48000000; } if (!mmc_can_gpio_ro(mmc)) mmc->caps2 |= MMC_CAP2_NO_WRITE_PROTECT; pltfm_host->clk = devm_clk_get(dev, "fck"); if (IS_ERR(pltfm_host->clk)) { ret = PTR_ERR(pltfm_host->clk); goto err_pltfm_free; } ret = clk_set_rate(pltfm_host->clk, mmc->f_max); if (ret) { dev_err(dev, "failed to set clock to %d\n", mmc->f_max); goto err_pltfm_free; } omap_host->pbias = devm_regulator_get_optional(dev, "pbias"); if (IS_ERR(omap_host->pbias)) { ret = PTR_ERR(omap_host->pbias); if (ret != -ENODEV) goto err_pltfm_free; dev_dbg(dev, "unable to get pbias regulator %d\n", ret); } omap_host->pbias_enabled = false; /* * omap_device_pm_domain has callbacks to enable the main * functional clock, interface clock and also configure the * SYSCONFIG register of omap devices. The callback will be invoked * as part of pm_runtime_get_sync. */ pm_runtime_enable(dev); ret = pm_runtime_get_sync(dev); if (ret < 0) { dev_err(dev, "pm_runtime_get_sync failed\n"); pm_runtime_put_noidle(dev); goto err_rpm_disable; } ret = sdhci_omap_set_capabilities(omap_host); if (ret) { dev_err(dev, "failed to set system capabilities\n"); goto err_put_sync; } host->mmc_host_ops.start_signal_voltage_switch = sdhci_omap_start_signal_voltage_switch; host->mmc_host_ops.set_ios = sdhci_omap_set_ios; host->mmc_host_ops.card_busy = sdhci_omap_card_busy; host->mmc_host_ops.execute_tuning = sdhci_omap_execute_tuning; host->mmc_host_ops.enable_sdio_irq = sdhci_omap_enable_sdio_irq; ret = sdhci_setup_host(host); if (ret) goto err_put_sync; ret = sdhci_omap_config_iodelay_pinctrl_state(omap_host); if (ret) goto err_cleanup_host; ret = __sdhci_add_host(host); if (ret) goto err_cleanup_host; return 0; err_cleanup_host: sdhci_cleanup_host(host); err_put_sync: pm_runtime_put_sync(dev); err_rpm_disable: pm_runtime_disable(dev); err_pltfm_free: sdhci_pltfm_free(pdev); return ret; } static int sdhci_omap_remove(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct sdhci_host *host = platform_get_drvdata(pdev); sdhci_remove_host(host, true); pm_runtime_put_sync(dev); pm_runtime_disable(dev); sdhci_pltfm_free(pdev); return 0; } static struct platform_driver sdhci_omap_driver = { .probe = sdhci_omap_probe, .remove = sdhci_omap_remove, .driver = { .name = "sdhci-omap", .of_match_table = omap_sdhci_match, }, }; module_platform_driver(sdhci_omap_driver); MODULE_DESCRIPTION("SDHCI driver for OMAP SoCs"); MODULE_AUTHOR("Texas Instruments Inc."); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:sdhci_omap");
Taeung/tip
drivers/mmc/host/sdhci-omap.c
C
gpl-2.0
30,998
/* * Universal Media Server, for streaming any medias to DLNA * compatible renderers based on the http://www.ps3mediaserver.org. * Copyright (C) 2012 UMS developers. * * This program is a free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * Based on http://transoceanic.blogspot.cz/2011/12/java-read-key-from-windows-registry.html */ package net.pms.util; import java.io.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WindowsRegistry { private static final Logger LOGGER = LoggerFactory.getLogger(WindowsRegistry.class); /** * @param location path in the registry * @param key registry key * @return registry value or null if not found */ public static String readRegistry(String location, String key) { try { // Run reg query, then read output with StreamReader (internal class) String query = "reg query " + '"' + location + "\" /v \"" + key + '"'; Process process = Runtime.getRuntime().exec(query); StreamReader reader = new StreamReader(process.getInputStream(), System.getProperty("file.encoding")); reader.start(); process.waitFor(); reader.join(); // Parse out the value if (reader.getResult().length() > 6) { String parsed = reader.getResult().substring(reader.getResult().indexOf("REG_SZ") + 6).trim(); if (parsed.length() > 1) { return parsed; } } } catch (IOException | InterruptedException e) {} return null; } static class StreamReader extends Thread { private InputStream inputStream; private String charsetName; private StringBuffer result = new StringBuffer(); public StreamReader(InputStream is, String charsetName) { this.inputStream = is; this.charsetName = charsetName; } @Override public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charsetName)); String line = null; while ((line = br.readLine()) != null) { result.append(line); } } catch (UnsupportedEncodingException e) { LOGGER.error(null, e); } catch (IOException e1) { LOGGER.error(null, e1); } } public String getResult() { return result.toString(); } } }
mindwarper/UniversalMediaServer
src/main/java/net/pms/util/WindowsRegistry.java
Java
gpl-2.0
2,782
<?php /** * @package Joomla.Platform * @subpackage HTTP * * @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * HTTP response data object class. * * @package Joomla.Platform * @subpackage HTTP * @since 11.3 */ class JHttpResponse { /** * @var integer The server response code. * @since 11.3 */ public $code; /** * @var array Response headers. * @since 11.3 */ public $headers = array(); /** * @var string Server response body. * @since 11.3 */ public $body; }
tharunaredweb/redCORE
libraries/redcore/joomla/http/response.php
PHP
gpl-2.0
682
test = "test of the localtime() function" import time times = [ 0, 100000, int (time.time()) ] filedata = """ {$ for (i, %(times)s) { locals { v : localtime(i) } print ("${v[0]} ${v[1]} ${v[2]} ${v[3]} ${v[4]} "); } $} """ % { "times" : times } # in publand, localtime(0) should give the time now times[0] = int (time.time()) outcome_v = [] for i in times: lt = time.localtime (i) outcome_v += [ lt.tm_year, lt.tm_mon, lt.tm_mday, lt.tm_hour, lt.tm_min ] outcome = " ".join ([ str (i) for i in outcome_v ])
OkCupid/okws
test/regtest/cases/98.py
Python
gpl-2.0
542
/* * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import sun.misc.SharedSecrets; /** * A specialized {@link Set} implementation for use with enum types. All of * the elements in an enum set must come from a single enum type that is * specified, explicitly or implicitly, when the set is created. Enum sets * are represented internally as bit vectors. This representation is * extremely compact and efficient. The space and time performance of this * class should be good enough to allow its use as a high-quality, typesafe * alternative to traditional <tt>int</tt>-based "bit flags." Even bulk * operations (such as <tt>containsAll</tt> and <tt>retainAll</tt>) should * run very quickly if their argument is also an enum set. * * <p>The iterator returned by the <tt>iterator</tt> method traverses the * elements in their <i>natural order</i> (the order in which the enum * constants are declared). The returned iterator is <i>weakly * consistent</i>: it will never throw {@link ConcurrentModificationException} * and it may or may not show the effects of any modifications to the set that * occur while the iteration is in progress. * * <p>Null elements are not permitted. Attempts to insert a null element * will throw {@link NullPointerException}. Attempts to test for the * presence of a null element or to remove one will, however, function * properly. * * <P>Like most collection implementations, <tt>EnumSet</tt> is not * synchronized. If multiple threads access an enum set concurrently, and at * least one of the threads modifies the set, it should be synchronized * externally. This is typically accomplished by synchronizing on some * object that naturally encapsulates the enum set. If no such object exists, * the set should be "wrapped" using the {@link Collections#synchronizedSet} * method. This is best done at creation time, to prevent accidental * unsynchronized access: * * <pre> * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class)); * </pre> * * <p>Implementation note: All basic operations execute in constant time. * They are likely (though not guaranteed) to be much faster than their * {@link HashSet} counterparts. Even bulk operations execute in * constant time if their argument is also an enum set. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @since 1.5 * @see EnumMap * @serial exclude */ @SuppressWarnings("serial") // No serialVersionUID due to usage of // serial proxy pattern public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, java.io.Serializable { /** * The class of all the elements of this set. */ final Class<E> elementType; /** * All of the values comprising T. (Cached for performance.) */ final Enum<?>[] universe; private static Enum<?>[] ZERO_LENGTH_ENUM_ARRAY = new Enum<?>[0]; EnumSet(Class<E>elementType, Enum<?>[] universe) { this.elementType = elementType; this.universe = universe; } /** * Creates an empty enum set with the specified element type. * * @param <E> The class of the elements in the set * @param elementType the class object of the element type for this enum * set * @return An empty enum set of the specified type. * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { Enum<?>[] universe = getUniverse(elementType); if (universe == null) throw new ClassCastException(elementType + " not an enum"); if (universe.length <= 64) return new RegularEnumSet<>(elementType, universe); else return new JumboEnumSet<>(elementType, universe); } /** * Creates an enum set containing all of the elements in the specified * element type. * * @param <E> The class of the elements in the set * @param elementType the class object of the element type for this enum * set * @return An enum set containing all the elements in the specified type. * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) { EnumSet<E> result = noneOf(elementType); result.addAll(); return result; } /** * Adds all of the elements from the appropriate enum type to this enum * set, which is empty prior to the call. */ abstract void addAll(); /** * Creates an enum set with the same element type as the specified enum * set, initially containing the same elements (if any). * * @param <E> The class of the elements in the set * @param s the enum set from which to initialize this enum set * @return A copy of the specified enum set. * @throws NullPointerException if <tt>s</tt> is null */ public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) { return s.clone(); } /** * Creates an enum set initialized from the specified collection. If * the specified collection is an <tt>EnumSet</tt> instance, this static * factory method behaves identically to {@link #copyOf(EnumSet)}. * Otherwise, the specified collection must contain at least one element * (in order to determine the new enum set's element type). * * @param <E> The class of the elements in the collection * @param c the collection from which to initialize this enum set * @return An enum set initialized from the given collection. * @throws IllegalArgumentException if <tt>c</tt> is not an * <tt>EnumSet</tt> instance and contains no elements * @throws NullPointerException if <tt>c</tt> is null */ public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) { if (c instanceof EnumSet) { return ((EnumSet<E>)c).clone(); } else { if (c.isEmpty()) throw new IllegalArgumentException("Collection is empty"); Iterator<E> i = c.iterator(); E first = i.next(); EnumSet<E> result = EnumSet.of(first); while (i.hasNext()) result.add(i.next()); return result; } } /** * Creates an enum set with the same element type as the specified enum * set, initially containing all the elements of this type that are * <i>not</i> contained in the specified set. * * @param <E> The class of the elements in the enum set * @param s the enum set from whose complement to initialize this enum set * @return The complement of the specified set in this set * @throws NullPointerException if <tt>s</tt> is null */ public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) { EnumSet<E> result = copyOf(s); result.complement(); return result; } /** * Creates an enum set initially containing the specified element. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param <E> The class of the specified element and of the set * @param e the element that this set is to contain initially * @throws NullPointerException if <tt>e</tt> is null * @return an enum set initially containing the specified element */ public static <E extends Enum<E>> EnumSet<E> of(E e) { EnumSet<E> result = noneOf(e.getDeclaringClass()); result.add(e); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param <E> The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param <E> The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param <E> The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @param e4 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); result.add(e4); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param <E> The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @param e4 another element that this set is to contain initially * @param e5 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4, E e5) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); result.add(e4); result.add(e5); return result; } /** * Creates an enum set initially containing the specified elements. * This factory, whose parameter list uses the varargs feature, may * be used to create an enum set initially containing an arbitrary * number of elements, but it is likely to run slower than the overloadings * that do not use varargs. * * @param <E> The class of the parameter elements and of the set * @param first an element that the set is to contain initially * @param rest the remaining elements the set is to contain initially * @throws NullPointerException if any of the specified elements are null, * or if <tt>rest</tt> is null * @return an enum set initially containing the specified elements */ @SafeVarargs public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) { EnumSet<E> result = noneOf(first.getDeclaringClass()); result.add(first); for (E e : rest) result.add(e); return result; } /** * Creates an enum set initially containing all of the elements in the * range defined by the two specified endpoints. The returned set will * contain the endpoints themselves, which may be identical but must not * be out of order. * * @param <E> The class of the parameter elements and of the set * @param from the first element in the range * @param to the last element in the range * @throws NullPointerException if {@code from} or {@code to} are null * @throws IllegalArgumentException if {@code from.compareTo(to) > 0} * @return an enum set initially containing all of the elements in the * range defined by the two specified endpoints */ public static <E extends Enum<E>> EnumSet<E> range(E from, E to) { if (from.compareTo(to) > 0) throw new IllegalArgumentException(from + " > " + to); EnumSet<E> result = noneOf(from.getDeclaringClass()); result.addRange(from, to); return result; } /** * Adds the specified range to this enum set, which is empty prior * to the call. */ abstract void addRange(E from, E to); /** * Returns a copy of this set. * * @return a copy of this set */ @SuppressWarnings("unchecked") public EnumSet<E> clone() { try { return (EnumSet<E>) super.clone(); } catch(CloneNotSupportedException e) { throw new AssertionError(e); } } /** * Complements the contents of this enum set. */ abstract void complement(); /** * Throws an exception if e is not of the correct type for this enum set. */ final void typeCheck(E e) { Class<?> eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) throw new ClassCastException(eClass + " != " + elementType); } /** * Returns all of the values comprising E. * The result is uncloned, cached, and shared by all callers. */ private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) { return SharedSecrets.getJavaLangAccess() .getEnumConstantsShared(elementType); } /** * This class is used to serialize all EnumSet instances, regardless of * implementation type. It captures their "logical contents" and they * are reconstructed using public static factories. This is necessary * to ensure that the existence of a particular implementation type is * an implementation detail. * * @serial include */ private static class SerializationProxy <E extends Enum<E>> implements java.io.Serializable { /** * The element type of this enum set. * * @serial */ private final Class<E> elementType; /** * The elements contained in this enum set. * * @serial */ private final Enum<?>[] elements; SerializationProxy(EnumSet<E> set) { elementType = set.elementType; elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY); } // instead of cast to E, we should perhaps use elementType.cast() // to avoid injection of forged stream, but it will slow the implementation @SuppressWarnings("unchecked") private Object readResolve() { EnumSet<E> result = EnumSet.noneOf(elementType); for (Enum<?> e : elements) result.add((E)e); return result; } private static final long serialVersionUID = 362491234563181265L; } Object writeReplace() { return new SerializationProxy<>(this); } // readObject method for the serialization proxy pattern // See Effective Java, Second Ed., Item 78. private void readObject(java.io.ObjectInputStream stream) throws java.io.InvalidObjectException { throw new java.io.InvalidObjectException("Proxy required"); } }
isaacl/openjdk-jdk
src/share/classes/java/util/EnumSet.java
Java
gpl-2.0
19,077
/* * m_police.c Parse/print policing module options. * * This program is free software; you can u32istribute 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. * * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * FIXES: 19990619 - J Hadi Salim (hadi@cyberus.ca) * simple addattr packaging fix. * 2002: J Hadi Salim - Add tc action extensions syntax * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <syslog.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include "utils.h" #include "tc_util.h" struct action_util police_action_util = { .id = "police", .parse_aopt = act_parse_police, .print_aopt = print_police, }; static void usage(void) { fprintf(stderr, "Usage: ... police rate BPS burst BYTES[/BYTES] [ mtu BYTES[/BYTES] ]\n"); fprintf(stderr, " [ peakrate BPS ] [ avrate BPS ] [ overhead BYTES ]\n"); fprintf(stderr, " [ linklayer TYPE ] [ ACTIONTERM ]\n"); fprintf(stderr, "Old Syntax ACTIONTERM := action <EXCEEDACT>[/NOTEXCEEDACT] \n"); fprintf(stderr, "New Syntax ACTIONTERM := conform-exceed <EXCEEDACT>[/NOTEXCEEDACT] \n"); fprintf(stderr, "Where: *EXCEEDACT := pipe | ok | reclassify | drop | continue \n"); fprintf(stderr, "Where: pipe is only valid for new syntax \n"); exit(-1); } static void explain1(char *arg) { fprintf(stderr, "Illegal \"%s\"\n", arg); } static const char *police_action_n2a(int action, char *buf, int len) { switch (action) { case -1: return "continue"; break; case TC_POLICE_OK: return "pass"; break; case TC_POLICE_SHOT: return "drop"; break; case TC_POLICE_RECLASSIFY: return "reclassify"; case TC_POLICE_PIPE: return "pipe"; default: snprintf(buf, len, "%d", action); return buf; } } static int police_action_a2n(const char *arg, int *result) { int res; if (matches(arg, "continue") == 0) res = -1; else if (matches(arg, "drop") == 0) res = TC_POLICE_SHOT; else if (matches(arg, "shot") == 0) res = TC_POLICE_SHOT; else if (matches(arg, "pass") == 0) res = TC_POLICE_OK; else if (strcmp(arg, "ok") == 0) res = TC_POLICE_OK; else if (matches(arg, "reclassify") == 0) res = TC_POLICE_RECLASSIFY; else if (matches(arg, "pipe") == 0) res = TC_POLICE_PIPE; else { char dummy; if (sscanf(arg, "%d%c", &res, &dummy) != 1) return -1; } *result = res; return 0; } static int get_police_result(int *action, int *result, char *arg) { char *p = strchr(arg, '/'); if (p) *p = 0; if (police_action_a2n(arg, action)) { if (p) *p = '/'; return -1; } if (p) { *p = '/'; if (police_action_a2n(p+1, result)) return -1; } return 0; } int act_parse_police(struct action_util *a,int *argc_p, char ***argv_p, int tca_id, struct nlmsghdr *n) { int argc = *argc_p; char **argv = *argv_p; int res = -1; int ok=0; struct tc_police p; __u32 rtab[256]; __u32 ptab[256]; __u32 avrate = 0; int presult = 0; unsigned buffer=0, mtu=0, mpu=0; unsigned short overhead=0; unsigned int linklayer = LINKLAYER_ETHERNET; /* Assume ethernet */ int Rcell_log=-1, Pcell_log = -1; struct rtattr *tail; memset(&p, 0, sizeof(p)); p.action = TC_POLICE_RECLASSIFY; if (a) /* new way of doing things */ NEXT_ARG(); if (argc <= 0) return -1; while (argc > 0) { if (matches(*argv, "index") == 0) { NEXT_ARG(); if (get_u32(&p.index, *argv, 10)) { fprintf(stderr, "Illegal \"index\"\n"); return -1; } } else if (matches(*argv, "burst") == 0 || strcmp(*argv, "buffer") == 0 || strcmp(*argv, "maxburst") == 0) { NEXT_ARG(); if (buffer) { fprintf(stderr, "Double \"buffer/burst\" spec\n"); return -1; } if (get_size_and_cell(&buffer, &Rcell_log, *argv) < 0) { explain1("buffer"); return -1; } } else if (strcmp(*argv, "mtu") == 0 || strcmp(*argv, "minburst") == 0) { NEXT_ARG(); if (mtu) { fprintf(stderr, "Double \"mtu/minburst\" spec\n"); return -1; } if (get_size_and_cell(&mtu, &Pcell_log, *argv) < 0) { explain1("mtu"); return -1; } } else if (strcmp(*argv, "mpu") == 0) { NEXT_ARG(); if (mpu) { fprintf(stderr, "Double \"mpu\" spec\n"); return -1; } if (get_size(&mpu, *argv)) { explain1("mpu"); return -1; } } else if (strcmp(*argv, "rate") == 0) { NEXT_ARG(); if (p.rate.rate) { fprintf(stderr, "Double \"rate\" spec\n"); return -1; } if (get_rate(&p.rate.rate, *argv)) { explain1("rate"); return -1; } } else if (strcmp(*argv, "avrate") == 0) { NEXT_ARG(); if (avrate) { fprintf(stderr, "Double \"avrate\" spec\n"); return -1; } if (get_rate(&avrate, *argv)) { explain1("avrate"); return -1; } } else if (matches(*argv, "peakrate") == 0) { NEXT_ARG(); if (p.peakrate.rate) { fprintf(stderr, "Double \"peakrate\" spec\n"); return -1; } if (get_rate(&p.peakrate.rate, *argv)) { explain1("peakrate"); return -1; } } else if (matches(*argv, "reclassify") == 0) { p.action = TC_POLICE_RECLASSIFY; } else if (matches(*argv, "drop") == 0 || matches(*argv, "shot") == 0) { p.action = TC_POLICE_SHOT; } else if (matches(*argv, "continue") == 0) { p.action = TC_POLICE_UNSPEC; } else if (matches(*argv, "pass") == 0) { p.action = TC_POLICE_OK; } else if (matches(*argv, "pipe") == 0) { p.action = TC_POLICE_PIPE; } else if (strcmp(*argv, "action") == 0 || strcmp(*argv, "conform-exceed") == 0) { NEXT_ARG(); if (get_police_result(&p.action, &presult, *argv)) { fprintf(stderr, "Illegal \"action\"\n"); return -1; } } else if (matches(*argv, "overhead") == 0) { NEXT_ARG(); if (get_u16(&overhead, *argv, 10)) { explain1("overhead"); return -1; } } else if (matches(*argv, "linklayer") == 0) { NEXT_ARG(); if (get_linklayer(&linklayer, *argv)) { explain1("linklayer"); return -1; } } else if (strcmp(*argv, "help") == 0) { usage(); } else { break; } ok++; argc--; argv++; } if (!ok) return -1; if (p.rate.rate && !buffer) { fprintf(stderr, "\"burst\" requires \"rate\".\n"); return -1; } if (p.peakrate.rate) { if (!p.rate.rate) { fprintf(stderr, "\"peakrate\" requires \"rate\".\n"); return -1; } if (!mtu) { fprintf(stderr, "\"mtu\" is required, if \"peakrate\" is requested.\n"); return -1; } } if (p.rate.rate) { p.rate.mpu = mpu; p.rate.overhead = overhead; if (tc_calc_rtable(&p.rate, rtab, Rcell_log, mtu, linklayer) < 0) { fprintf(stderr, "TBF: failed to calculate rate table.\n"); return -1; } p.burst = tc_calc_xmittime(p.rate.rate, buffer); } p.mtu = mtu; if (p.peakrate.rate) { p.peakrate.mpu = mpu; p.peakrate.overhead = overhead; if (tc_calc_rtable(&p.peakrate, ptab, Pcell_log, mtu, linklayer) < 0) { fprintf(stderr, "POLICE: failed to calculate peak rate table.\n"); return -1; } } tail = NLMSG_TAIL(n); addattr_l(n, MAX_MSG, tca_id, NULL, 0); addattr_l(n, MAX_MSG, TCA_POLICE_TBF, &p, sizeof(p)); if (p.rate.rate) addattr_l(n, MAX_MSG, TCA_POLICE_RATE, rtab, 1024); if (p.peakrate.rate) addattr_l(n, MAX_MSG, TCA_POLICE_PEAKRATE, ptab, 1024); if (avrate) addattr32(n, MAX_MSG, TCA_POLICE_AVRATE, avrate); if (presult) addattr32(n, MAX_MSG, TCA_POLICE_RESULT, presult); tail->rta_len = (void *) NLMSG_TAIL(n) - (void *) tail; res = 0; *argc_p = argc; *argv_p = argv; return res; } int parse_police(int *argc_p, char ***argv_p, int tca_id, struct nlmsghdr *n) { return act_parse_police(NULL,argc_p,argv_p,tca_id,n); } int print_police(struct action_util *a, FILE *f, struct rtattr *arg) { SPRINT_BUF(b1); struct tc_police *p; struct rtattr *tb[TCA_POLICE_MAX+1]; unsigned buffer; if (arg == NULL) return 0; parse_rtattr_nested(tb, TCA_POLICE_MAX, arg); if (tb[TCA_POLICE_TBF] == NULL) { fprintf(f, "[NULL police tbf]"); return 0; } #ifndef STOOPID_8BYTE if (RTA_PAYLOAD(tb[TCA_POLICE_TBF]) < sizeof(*p)) { fprintf(f, "[truncated police tbf]"); return -1; } #endif p = RTA_DATA(tb[TCA_POLICE_TBF]); fprintf(f, " police 0x%x ", p->index); fprintf(f, "rate %s ", sprint_rate(p->rate.rate, b1)); buffer = tc_calc_xmitsize(p->rate.rate, p->burst); fprintf(f, "burst %s ", sprint_size(buffer, b1)); fprintf(f, "mtu %s ", sprint_size(p->mtu, b1)); if (show_raw) fprintf(f, "[%08x] ", p->burst); if (p->peakrate.rate) fprintf(f, "peakrate %s ", sprint_rate(p->peakrate.rate, b1)); if (tb[TCA_POLICE_AVRATE]) fprintf(f, "avrate %s ", sprint_rate(rta_getattr_u32(tb[TCA_POLICE_AVRATE]), b1)); fprintf(f, "action %s", police_action_n2a(p->action, b1, sizeof(b1))); if (tb[TCA_POLICE_RESULT]) { fprintf(f, "/%s ", police_action_n2a(*(int*)RTA_DATA(tb[TCA_POLICE_RESULT]), b1, sizeof(b1))); } else fprintf(f, " "); fprintf(f, "overhead %ub ", p->rate.overhead); fprintf(f, "\nref %d bind %d\n",p->refcnt, p->bindcnt); return 0; } int tc_print_police(FILE *f, struct rtattr *arg) { return print_police(&police_action_util,f,arg); }
wertarbyte/iproute2
tc/m_police.c
C
gpl-2.0
9,241
/** * * $Id: BubbleButton.h,v 1.2 2003/12/25 06:55:07 tksoh Exp $ * * Copyright (C) 1996 Free Software Foundation, Inc. * Copyright © 1999-2001 by the LessTif developers. * * This file is part of the GNU LessTif Extension Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * **/ #ifndef _BUBBLEBUTTON_H #define _BUBBLEBUTTON_H #include <X11/IntrinsicP.h> #ifdef __cplusplus extern "C" { #endif #ifndef XltNfadeRate #define XltNfadeRate "fadeRate" #endif #ifndef XltCFadeRate #define XltCFadeRate "FadeRate" #endif #ifndef XltNdelay #define XltNdelay "delay" #endif #ifndef XltCDelay #define XltCDelay "Delay" #endif #define XltNbubbleString "bubbleString" #define XltCBubbleString "BubbleString" #define XltNshowBubble "showBubble" #define XltCShowBubble "ShowBubble" #ifndef XltNmouseOverPixmap #define XltNmouseOverPixmap "mouseOverPixmap" #define XltCMouseOverPixmap "MouseOverPixmap" #endif #ifndef XltNmouseOverString #define XltNmouseOverString "mouseOverString" #define XltCMouseOverString "MouseOverString" #endif #ifndef XltNbubbleDuration #define XltNbubbleDuration "bubbleDuration" #endif #ifndef XltCBubbleDuration #define XltCBubbleDuration "BubbleDuration" #endif #ifndef XltNslidingBubble #define XltNslidingBubble "slidingBubble" #endif #ifndef XltCslidingBubble #define XltCslidingBubble "SlidingBubble" #endif #ifndef XltNautoParkBubble #define XltNautoParkBubble "autoParkBubble" #endif #ifndef XltCautoParkBubble #define XltCautoParkBubble "AutoParkBubble" #endif extern WidgetClass xrwsBubbleButtonWidgetClass; typedef struct _XltBubbleButtonRec *XltBubbleButtonWidget; typedef struct _XltBubbleButtonClassRec *XltBubbleButtonWidgetClass; #if 0 typedef struct { int reason; char *data; int len; } XltHostCallbackStruct, _XltHostCallbackStruct; #endif #define XltIsBubbleButton(w) XtIsSubclass((w), xrwsBubbleButtonWidgetClass) extern Widget XltCreateBubbleButton(Widget parent, char *name, Arg *arglist, Cardinal argCount); #ifdef __cplusplus } /* Close scope of 'extern "C"' declaration which encloses file. */ #endif #endif
fjardon/nedit
Xlt/BubbleButton.h
C
gpl-2.0
2,776
/* * COPYRIGHT (C) 2006-2021, RT-Thread Development Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * Change Logs: * Date Author Notes * 2012-12-8 Bernard add file header * export bsd socket symbol for RT-Thread Application Module * 2017-11-15 Bernard add lock for init_done callback. * 2018-11-02 MurphyZhao port to lwip2.1.0 */ #include <rtthread.h> #include <rthw.h> #include "lwip/sys.h" #include "lwip/opt.h" #include "lwip/stats.h" #include "lwip/err.h" #include "arch/sys_arch.h" #include "lwip/debug.h" #include "lwip/netif.h" #include "lwip/netifapi.h" #include "lwip/tcpip.h" #include "netif/ethernetif.h" #include "lwip/sio.h" #include "lwip/init.h" #include "lwip/dhcp.h" #include "lwip/inet.h" #include "netif/etharp.h" #include <string.h> #include <stdio.h> /* * Initialize the network interface device * * @return the operation status, ERR_OK on OK, ERR_IF on error */ static err_t netif_device_init(struct netif *netif) { struct eth_device *ethif; ethif = (struct eth_device *)netif->state; if (ethif != RT_NULL) { rt_device_t device; /* get device object */ device = (rt_device_t) ethif; if (rt_device_init(device) != RT_EOK) { return ERR_IF; } /* copy device flags to netif flags */ netif->flags = ethif->flags; netif->mtu = ETHERNET_MTU; /* set output */ netif->output = etharp_output; return ERR_OK; } return ERR_IF; } /* * Initialize the ethernetif layer and set network interface device up */ static void tcpip_init_done_callback(void *arg) { rt_device_t device; struct eth_device *ethif; ip4_addr_t ipaddr, netmask, gw; struct rt_list_node* node; struct rt_object* object; struct rt_object_information *information; LWIP_ASSERT("invalid arg.\n",arg); IP4_ADDR(&gw, 0,0,0,0); IP4_ADDR(&ipaddr, 0,0,0,0); IP4_ADDR(&netmask, 0,0,0,0); /* enter critical */ rt_enter_critical(); /* for each network interfaces */ information = rt_object_get_information(RT_Object_Class_Device); RT_ASSERT(information != RT_NULL); for (node = information->object_list.next; node != &(information->object_list); node = node->next) { object = rt_list_entry(node, struct rt_object, list); device = (rt_device_t)object; if (device->type == RT_Device_Class_NetIf) { ethif = (struct eth_device *)device; /* leave critical */ rt_exit_critical(); LOCK_TCPIP_CORE(); netif_add(ethif->netif, &ipaddr, &netmask, &gw, ethif, netif_device_init, tcpip_input); if (netif_default == RT_NULL) netif_set_default(ethif->netif); #if LWIP_DHCP /* set interface up */ netif_set_up(ethif->netif); /* if this interface uses DHCP, start the DHCP client */ dhcp_start(ethif->netif); #else /* set interface up */ netif_set_up(ethif->netif); #endif if (ethif->flags & ETHIF_LINK_PHYUP) { netif_set_link_up(ethif->netif); } UNLOCK_TCPIP_CORE(); /* enter critical */ rt_enter_critical(); } } /* leave critical */ rt_exit_critical(); rt_sem_release((rt_sem_t)arg); } /** * LwIP system initialization */ extern int eth_system_device_init_private(void); int lwip_system_init(void) { rt_err_t rc; struct rt_semaphore done_sem; static rt_bool_t init_ok = RT_FALSE; if (init_ok) { rt_kprintf("lwip system already init.\n"); return 0; } eth_system_device_init_private(); /* set default netif to NULL */ netif_default = RT_NULL; rc = rt_sem_init(&done_sem, "done", 0, RT_IPC_FLAG_FIFO); if (rc != RT_EOK) { LWIP_ASSERT("Failed to create semaphore", 0); return -1; } tcpip_init(tcpip_init_done_callback, (void *)&done_sem); /* waiting for initialization done */ if (rt_sem_take(&done_sem, RT_WAITING_FOREVER) != RT_EOK) { rt_sem_detach(&done_sem); return -1; } rt_sem_detach(&done_sem); /* set default ip address */ #if !LWIP_DHCP if (netif_default != RT_NULL) { struct ip4_addr ipaddr, netmask, gw; ipaddr.addr = inet_addr(RT_LWIP_IPADDR); gw.addr = inet_addr(RT_LWIP_GWADDR); netmask.addr = inet_addr(RT_LWIP_MSKADDR); netifapi_netif_set_addr(netif_default, &ipaddr, &netmask, &gw); } #endif rt_kprintf("lwIP-%d.%d.%d initialized!\n", LWIP_VERSION_MAJOR, LWIP_VERSION_MINOR, LWIP_VERSION_REVISION); init_ok = RT_TRUE; return 0; } INIT_PREV_EXPORT(lwip_system_init); void sys_init(void) { /* nothing on RT-Thread porting */ } void lwip_sys_init(void) { lwip_system_init(); } /* * Create a new semaphore * * @return the operation status, ERR_OK on OK; others on error */ err_t sys_sem_new(sys_sem_t *sem, u8_t count) { static unsigned short counter = 0; char tname[RT_NAME_MAX]; sys_sem_t tmpsem; RT_DEBUG_NOT_IN_INTERRUPT; rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_SEM_NAME, counter); counter ++; tmpsem = rt_sem_create(tname, count, RT_IPC_FLAG_FIFO); if (tmpsem == RT_NULL) return ERR_MEM; else { *sem = tmpsem; return ERR_OK; } } /* * Deallocate a semaphore */ void sys_sem_free(sys_sem_t *sem) { RT_DEBUG_NOT_IN_INTERRUPT; rt_sem_delete(*sem); } /* * Signal a semaphore */ void sys_sem_signal(sys_sem_t *sem) { rt_sem_release(*sem); } /* * Block the thread while waiting for the semaphore to be signaled * * @return If the timeout argument is non-zero, it will return the number of milliseconds * spent waiting for the semaphore to be signaled; If the semaphore isn't signaled * within the specified time, it will return SYS_ARCH_TIMEOUT; If the thread doesn't * wait for the semaphore, it will return zero */ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) { rt_err_t ret; s32_t t; u32_t tick; RT_DEBUG_NOT_IN_INTERRUPT; /* get the begin tick */ tick = rt_tick_get(); if (timeout == 0) t = RT_WAITING_FOREVER; else { /* convert msecond to os tick */ if (timeout < (1000/RT_TICK_PER_SECOND)) t = 1; else t = timeout / (1000/RT_TICK_PER_SECOND); } ret = rt_sem_take(*sem, t); if (ret == -RT_ETIMEOUT) return SYS_ARCH_TIMEOUT; else { if (ret == RT_EOK) ret = 1; } /* get elapse msecond */ tick = rt_tick_get() - tick; /* convert tick to msecond */ tick = tick * (1000 / RT_TICK_PER_SECOND); if (tick == 0) tick = 1; return tick; } #ifndef sys_sem_valid /** Check if a semaphore is valid/allocated: * return 1 for valid, 0 for invalid */ int sys_sem_valid(sys_sem_t *sem) { return (int)(*sem); } #endif #ifndef sys_sem_set_invalid /** Set a semaphore invalid so that sys_sem_valid returns 0 */ void sys_sem_set_invalid(sys_sem_t *sem) { *sem = RT_NULL; } #endif /* ====================== Mutex ====================== */ /** Create a new mutex * @param mutex pointer to the mutex to create * @return a new mutex */ err_t sys_mutex_new(sys_mutex_t *mutex) { static unsigned short counter = 0; char tname[RT_NAME_MAX]; sys_mutex_t tmpmutex; RT_DEBUG_NOT_IN_INTERRUPT; rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_MUTEX_NAME, counter); counter ++; tmpmutex = rt_mutex_create(tname, RT_IPC_FLAG_FIFO); if (tmpmutex == RT_NULL) return ERR_MEM; else { *mutex = tmpmutex; return ERR_OK; } } /** Lock a mutex * @param mutex the mutex to lock */ void sys_mutex_lock(sys_mutex_t *mutex) { RT_DEBUG_NOT_IN_INTERRUPT; rt_mutex_take(*mutex, RT_WAITING_FOREVER); return; } /** Unlock a mutex * @param mutex the mutex to unlock */ void sys_mutex_unlock(sys_mutex_t *mutex) { rt_mutex_release(*mutex); } /** Delete a semaphore * @param mutex the mutex to delete */ void sys_mutex_free(sys_mutex_t *mutex) { RT_DEBUG_NOT_IN_INTERRUPT; rt_mutex_delete(*mutex); } #ifndef sys_mutex_valid /** Check if a mutex is valid/allocated: * return 1 for valid, 0 for invalid */ int sys_mutex_valid(sys_mutex_t *mutex) { return (int)(*mutex); } #endif #ifndef sys_mutex_set_invalid /** Set a mutex invalid so that sys_mutex_valid returns 0 */ void sys_mutex_set_invalid(sys_mutex_t *mutex) { *mutex = RT_NULL; } #endif /* ====================== Mailbox ====================== */ /* * Create an empty mailbox for maximum "size" elements * * @return the operation status, ERR_OK on OK; others on error */ err_t sys_mbox_new(sys_mbox_t *mbox, int size) { static unsigned short counter = 0; char tname[RT_NAME_MAX]; sys_mbox_t tmpmbox; RT_DEBUG_NOT_IN_INTERRUPT; rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_MBOX_NAME, counter); counter ++; tmpmbox = rt_mb_create(tname, size, RT_IPC_FLAG_FIFO); if (tmpmbox != RT_NULL) { *mbox = tmpmbox; return ERR_OK; } return ERR_MEM; } /* * Deallocate a mailbox */ void sys_mbox_free(sys_mbox_t *mbox) { RT_DEBUG_NOT_IN_INTERRUPT; rt_mb_delete(*mbox); return; } /** Post a message to an mbox - may not fail * -> blocks if full, only used from tasks not from ISR * @param mbox mbox to posts the message * @param msg message to post (ATTENTION: can be NULL) */ void sys_mbox_post(sys_mbox_t *mbox, void *msg) { RT_DEBUG_NOT_IN_INTERRUPT; rt_mb_send_wait(*mbox, (rt_uint32_t)msg, RT_WAITING_FOREVER); return; } /* * Try to post the "msg" to the mailbox * * @return return ERR_OK if the "msg" is posted, ERR_MEM if the mailbox is full */ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg) { if (rt_mb_send(*mbox, (rt_uint32_t)msg) == RT_EOK) return ERR_OK; return ERR_MEM; } err_t sys_mbox_trypost_fromisr(sys_mbox_t *q, void *msg) { return sys_mbox_trypost(q, msg); } /** Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message * @return time (in milliseconds) waited for a message, may be 0 if not waited or SYS_ARCH_TIMEOUT on timeout * The returned time has to be accurate to prevent timer jitter! */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout) { rt_err_t ret; s32_t t; u32_t tick; RT_DEBUG_NOT_IN_INTERRUPT; /* get the begin tick */ tick = rt_tick_get(); if(timeout == 0) t = RT_WAITING_FOREVER; else { /* convirt msecond to os tick */ if (timeout < (1000/RT_TICK_PER_SECOND)) t = 1; else t = timeout / (1000/RT_TICK_PER_SECOND); } ret = rt_mb_recv(*mbox, (rt_ubase_t *)msg, t); if(ret != RT_EOK) { return SYS_ARCH_TIMEOUT; } /* get elapse msecond */ tick = rt_tick_get() - tick; /* convert tick to msecond */ tick = tick * (1000 / RT_TICK_PER_SECOND); if (tick == 0) tick = 1; return tick; } /** Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message * @return 0 (milliseconds) if a message has been received * or SYS_MBOX_EMPTY if the mailbox is empty */ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg) { int ret; ret = rt_mb_recv(*mbox, (rt_ubase_t *)msg, 0); if(ret == -RT_ETIMEOUT) return SYS_ARCH_TIMEOUT; else { if (ret == RT_EOK) ret = 1; } return ret; } #ifndef sys_mbox_valid /** Check if an mbox is valid/allocated: * return 1 for valid, 0 for invalid */ int sys_mbox_valid(sys_mbox_t *mbox) { return (int)(*mbox); } #endif #ifndef sys_mbox_set_invalid /** Set an mbox invalid so that sys_mbox_valid returns 0 */ void sys_mbox_set_invalid(sys_mbox_t *mbox) { *mbox = RT_NULL; } #endif /* ====================== System ====================== */ /* * Start a new thread named "name" with priority "prio" that will begin * its execution in the function "thread()". The "arg" argument will be * passed as an argument to the thread() function */ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio) { rt_thread_t t; RT_DEBUG_NOT_IN_INTERRUPT; /* create thread */ t = rt_thread_create(name, thread, arg, stacksize, prio, 20); RT_ASSERT(t != RT_NULL); /* startup thread */ rt_thread_startup(t); return t; } sys_prot_t sys_arch_protect(void) { rt_base_t level; /* disable interrupt */ level = rt_hw_interrupt_disable(); return level; } void sys_arch_unprotect(sys_prot_t pval) { /* enable interrupt */ rt_hw_interrupt_enable(pval); return; } void sys_arch_assert(const char *file, int line) { rt_kprintf("\nAssertion: %d in %s, thread %s\n", line, file, rt_thread_self()->name); RT_ASSERT(0); } u32_t sys_jiffies(void) { return rt_tick_get(); } u32_t sys_now(void) { return rt_tick_get_millisecond(); } #if MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK /** * Check if a mep element was victim of an overflow or underflow * (e.g. the restricted area after/before it has been altered) * * @param p the mem element to check * @param size allocated size of the element * @param descr1 description of the element source shown on error * @param descr2 description of the element source shown on error */ void mem_overflow_check_raw(void *p, size_t size, const char *descr1, const char *descr2) { #if MEM_SANITY_REGION_AFTER_ALIGNED || MEM_SANITY_REGION_BEFORE_ALIGNED u16_t k; u8_t *m; #if MEM_SANITY_REGION_AFTER_ALIGNED > 0 m = (u8_t *)p + size; for (k = 0; k < MEM_SANITY_REGION_AFTER_ALIGNED; k++) { if (m[k] != 0xcd) { char errstr[128]; snprintf(errstr, sizeof(errstr), "detected mem overflow in %s%s", descr1, descr2); LWIP_ASSERT(errstr, 0); } } #endif /* MEM_SANITY_REGION_AFTER_ALIGNED > 0 */ #if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 m = (u8_t *)p - MEM_SANITY_REGION_BEFORE_ALIGNED; for (k = 0; k < MEM_SANITY_REGION_BEFORE_ALIGNED; k++) { if (m[k] != 0xcd) { char errstr[128]; snprintf(errstr, sizeof(errstr), "detected mem underflow in %s%s", descr1, descr2); LWIP_ASSERT(errstr, 0); } } #endif /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 */ #else LWIP_UNUSED_ARG(p); LWIP_UNUSED_ARG(desc); LWIP_UNUSED_ARG(descr); #endif } /** * Initialize the restricted area of a mem element. */ void mem_overflow_init_raw(void *p, size_t size) { #if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 u8_t *m; #if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 m = (u8_t *)p - MEM_SANITY_REGION_BEFORE_ALIGNED; memset(m, 0xcd, MEM_SANITY_REGION_BEFORE_ALIGNED); #endif #if MEM_SANITY_REGION_AFTER_ALIGNED > 0 m = (u8_t *)p + size; memset(m, 0xcd, MEM_SANITY_REGION_AFTER_ALIGNED); #endif #else /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 */ LWIP_UNUSED_ARG(p); LWIP_UNUSED_ARG(desc); #endif /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 */ } #endif /* MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK */ RT_WEAK void mem_init(void) { } void *mem_calloc(mem_size_t count, mem_size_t size) { return rt_calloc(count, size); } void *mem_trim(void *mem, mem_size_t size) { // return rt_realloc(mem, size); /* not support trim yet */ return mem; } void *mem_malloc(mem_size_t size) { return rt_malloc(size); } void mem_free(void *mem) { rt_free(mem); } #ifdef RT_LWIP_PPP u32_t sio_read(sio_fd_t fd, u8_t *buf, u32_t size) { u32_t len; RT_ASSERT(fd != RT_NULL); len = rt_device_read((rt_device_t)fd, 0, buf, size); if (len <= 0) return 0; return len; } u32_t sio_write(sio_fd_t fd, u8_t *buf, u32_t size) { RT_ASSERT(fd != RT_NULL); return rt_device_write((rt_device_t)fd, 0, buf, size); } void sio_read_abort(sio_fd_t fd) { rt_kprintf("read_abort\n"); } void ppp_trace(int level, const char *format, ...) { va_list args; rt_size_t length; static char rt_log_buf[RT_CONSOLEBUF_SIZE]; va_start(args, format); length = rt_vsprintf(rt_log_buf, format, args); rt_device_write((rt_device_t)rt_console_get_device(), 0, rt_log_buf, length); va_end(args); } #endif /* * export bsd socket symbol for RT-Thread Application Module */ #if LWIP_SOCKET #include <lwip/sockets.h> RTM_EXPORT(lwip_accept); RTM_EXPORT(lwip_bind); RTM_EXPORT(lwip_shutdown); RTM_EXPORT(lwip_getpeername); RTM_EXPORT(lwip_getsockname); RTM_EXPORT(lwip_getsockopt); RTM_EXPORT(lwip_setsockopt); RTM_EXPORT(lwip_close); RTM_EXPORT(lwip_connect); RTM_EXPORT(lwip_listen); RTM_EXPORT(lwip_recv); RTM_EXPORT(lwip_read); RTM_EXPORT(lwip_recvfrom); RTM_EXPORT(lwip_send); RTM_EXPORT(lwip_sendto); RTM_EXPORT(lwip_socket); RTM_EXPORT(lwip_write); RTM_EXPORT(lwip_select); RTM_EXPORT(lwip_ioctl); RTM_EXPORT(lwip_fcntl); RTM_EXPORT(lwip_htons); RTM_EXPORT(lwip_htonl); #if LWIP_DNS #include <lwip/netdb.h> RTM_EXPORT(lwip_gethostbyname); RTM_EXPORT(lwip_gethostbyname_r); RTM_EXPORT(lwip_freeaddrinfo); RTM_EXPORT(lwip_getaddrinfo); #endif #endif #if LWIP_DHCP #include <lwip/dhcp.h> RTM_EXPORT(dhcp_start); RTM_EXPORT(dhcp_renew); RTM_EXPORT(dhcp_stop); #endif #if LWIP_NETIF_API #include <lwip/netifapi.h> RTM_EXPORT(netifapi_netif_set_addr); #endif #if LWIP_NETIF_LINK_CALLBACK RTM_EXPORT(netif_set_link_callback); #endif #if LWIP_NETIF_STATUS_CALLBACK RTM_EXPORT(netif_set_status_callback); #endif RTM_EXPORT(netif_find); RTM_EXPORT(netif_set_addr); RTM_EXPORT(netif_set_ipaddr); RTM_EXPORT(netif_set_gw); RTM_EXPORT(netif_set_netmask);
grissiom/rt-thread
components/net/lwip-2.1.2/src/arch/sys_arch.c
C
gpl-2.0
19,817
#!/bin/sh # This test is a part of RPC & TI-RPC Test Suite created by Cyril LACABANNE # (c) 2007 BULL S.A.S. # Please refer to RPC & TI-RPC Test Suite documentation. # More details at http://nfsv4.bullopensource.org/doc/rpc_testsuite.php # TEST : TIRPC svcerr_systemerr basic # creation : 2007-06-06 revision 2007-06-13 # ********************** # *** INITIALISATION *** # ********************** # Parameters such as tests information, threads number... # test information TESTNAME="TIRPC_err_svcerr_systemerr.basic" TESTVERS="1.0" # test binaries, used to call TESTCLIENTPATH="rpc_suite/tirpc/tirpc_err_svcerr_systemerr" TESTCLIENTBIN="1-basic.bin" TESTCLIENT=$CLIENTTSTPACKDIR/$TESTCLIENTPATH/$TESTCLIENTBIN # table to save all tests result result= # tmp file declaration to store test returned result TMPRESULTFILE=/tmp/rpcts.tmp # ***************** # *** PROCESSUS *** # ***************** # erase temp. result file echo -n "">$TMPRESULTFILE # function to collect log result get_test_result() { # default : test failed r_value=1 # if result table is empty last test crashes (segment fault), so return must be "failed" if [ ${#result[*]} -eq 0 ] then return fi for ((a=0; a < TESTINSTANCE-1 ; a++)) do if [ ${result[$a]} -ne ${result[`expr $a + 1`]} ] then return fi done # if all test instances return same result return the first element, note that test succeeds if value is 0 r_value=${result[0]} } # function to put test result into logfile result_to_logFile() { case $r_value in 0)r_valueTxt="PASS";; 1)r_valueTxt="FAILED";; 2)r_valueTxt="HUNG";; 3)r_valueTxt="INTERRUPTED";; 4)r_valueTxt="SKIP";; 5)r_valueTxt="UNTESTED";; esac echo $TESTCLIENTPATH"/"$( echo $TESTCLIENTBIN | cut -d . -f1 )": execution: "$r_valueTxt>>$LOCLOGDIR/$TESTLOGFILE } # test needs this server to run serv=$( $REMOTESHELL $SERVERUSER@$SERVERIP "ps -e | grep $TESTSERVER_1_BIN" ) if [ -z "$serv" ] then echo " - Skipped..." echo "/!\ Panic : no test server found" echo " $TESTSERVER_1_BIN needed, but not running on server" echo " Test skipped with status 4" r_value=4 result_to_logFile echo " * $TESTNAME execution: "$r_valueTxt exit 4 fi # launch client instances depeding on test... if [ "$TESTWAY" = "onetomany" ] then # run many client linked to the same server if [ $VERBOSE -eq 1 ] then echo " - Mode one server to many client : "$TESTINSTANCE" instance(s)" fi for ((a=0; a < TESTINSTANCE ; a++)) do $REMOTESHELL $CLIENTUSER@$CLIENTIP "$TESTCLIENT $SERVERIP $PROGNUMBASE" >>$TMPRESULTFILE& done else # launch as much client instances as server instances if [ $VERBOSE -eq 1 ] then echo " - Mode many couple client/server : "$TESTINSTANCE" instance(s)" fi for ((a=0; a < TESTINSTANCE ; a++)) do $REMOTESHELL $CLIENTUSER@$CLIENTIP "$TESTCLIENT $SERVERIP `expr $PROGNUMBASE + $a`" >>$TMPRESULTFILE& done fi # wait for the end of all test sleep $GLOBALTIMEOUT # test if all test instances have stopped # if it remains at least one instances, script kills instances and put status HUNG to the whole test case IS_EX=`$REMOTESHELL $CLIENTUSER@$CLIENTIP "ps -e | grep $TESTCLIENTBIN"` if [ "$IS_EX" ] then if [ $VERBOSE -eq 1 ] then echo " - error : prog is still running -> kill" fi $REMOTESHELL $CLIENTUSER@$CLIENTIP "killall -9 $TESTCLIENTBIN" r_value=2 result_to_logFile echo " * $TESTNAME execution: "$r_valueTxt exit 2 fi # *************** # *** RESULTS *** # *************** # if test program correctly run, this part aims to collect all test results and put result into log file result=( $(cat $TMPRESULTFILE) ) get_test_result result_to_logFile echo " * $TESTNAME execution: "$r_valueTxt
rogerq/ltp-ddt
testcases/network/rpc/rpc-tirpc-full-test-suite/scripts/tirpc_err_svcerr_systemerr.sh
Shell
gpl-2.0
3,675
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ucl.physiol.neuroconstruct.simulation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import org.junit.runner.Result; import static org.junit.Assert.*; import ucl.physiol.neuroconstruct.dataset.DataSet; import ucl.physiol.neuroconstruct.test.MainTest; import ucl.physiol.neuroconstruct.utils.GeneralUtils; /** * * @author Padraig */ public class SimulationDataTest { @Before public void setUp() { System.out.println("--------------- setUp() SimulationDataTest"); } @Test public void testTextHDF5Load() throws IOException, SimulationDataException { System.out.println("--- testTextHDF5Load..."); ArrayList<File> files = new ArrayList<File>(); files.add(new File("testProjects/TestHDF5/simulations/TestText")); files.add(new File("testProjects/TestHDF5/simulations/TestH5")); files.add(new File("testProjects/TestHDF5/simulations/TestH5Parallel")); files.add(new File("testProjects/TestHDF5/simulations/TestSpikesText")); files.add(new File("testProjects/TestHDF5/simulations/TestSpikesHDF5")); files.add(new File("testProjects/TestHDF5/simulations/TestSpikesHDF5Parallel")); SimulationData simulationData1 = null; for (File f: files) { GeneralUtils.timeCheck("Going to load data from: "+ f.getCanonicalPath(), true); simulationData1 = new SimulationData(f, true); simulationData1.initialise(); GeneralUtils.timeCheck("Loaded data from: "+ f.getCanonicalPath(), true); ArrayList<DataStore> dss= simulationData1.getAllLoadedDataStores(); GeneralUtils.timeCheck("Grabbed data from: "+ f.getCanonicalPath(), true); int numTimeSteps = simulationData1.getNumberTimeSteps(); System.out.println("Total number of data stores: "+dss.size()); int expected = 20; if (f.getName().indexOf("Spike")>0) expected = 80; assertEquals(dss.size(), expected); for(int i=0;i<Math.min(20, dss.size());i++) { DataStore ds = dss.get(i); System.out.println(ds); DataSet dataSet = simulationData1.getDataSet(ds.getCellSegRef(), ds.getVariable(), true); System.out.println(dataSet); assertEquals(numTimeSteps, dataSet.getNumberPoints()); } } System.out.println("Tests completed!"); } @Test public void testConvertSpikeTimesToContinuous1() { double[] times = new double[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; double[] spikes = new double[]{3,6,8,12}; int non = 0; int spi = 1; double[] volts = SimulationData.convertSpikeTimesToContinuous(spikes, times, non, spi, 1); int spikeNum = 0; for (int i=0;i<times.length;i++){ System.out.println("Time: "+times[i]+", volt: "+volts[i]); if (spikes[spikeNum] == times[i]) { assertEquals(volts[i], spi, 0); System.out.println("Spike match..."); if (spikeNum < spikes.length-1) spikeNum++; } else { assertEquals(volts[i], non, 0); } } } @Test public void testConvertSpikeTimesToContinuous2() { double[] spikes = new double[]{100.333,103,106.999,108}; int non = 0; int spi = 1; double start = 100; double end = 110; double step = 0.1; int expNum = 1+ (int)Math.floor((end-start)/step); double[] volts = SimulationData.convertSpikeTimesToContinuous(spikes, start, end, step, non, spi); assertEquals(volts.length, expNum, 0); int spikeNum = 0; for (int i=0;i<expNum;i++){ double time = start + (i*step); System.out.println("Time: "+time+/*", next spike: "+spikes[spikeNum]+*/" volt: "+volts[i]); if (spikeNum<spikes.length && time >=spikes[spikeNum]) { assertEquals(volts[i], spi, 0); System.out.println("Spike match..."); spikeNum++; } else { assertEquals(volts[i], non, 0); } } } public static void main(String[] args) { SimulationDataTest ct = new SimulationDataTest(); Result r = org.junit.runner.JUnitCore.runClasses(ct.getClass()); MainTest.checkResults(r); } }
rgerkin/neuroConstruct
tests/ucl/physiol/neuroconstruct/simulation/SimulationDataTest.java
Java
gpl-2.0
4,783
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * Copyright (C) 2015 XiaoMi, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/leds.h> #include <linux/err.h> #include <linux/spinlock.h> #include <linux/of_platform.h> #include <linux/of_device.h> #include <linux/spmi.h> #include <linux/qpnp/pwm.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/regulator/consumer.h> #include <linux/delay.h> #define WLED_MOD_EN_REG(base, n) (base + 0x60 + n*0x10) #define WLED_IDAC_DLY_REG(base, n) (WLED_MOD_EN_REG(base, n) + 0x01) #define WLED_FULL_SCALE_REG(base, n) (WLED_IDAC_DLY_REG(base, n) + 0x01) #define WLED_MOD_SRC_SEL_REG(base, n) (WLED_FULL_SCALE_REG(base, n) + 0x01) #define WLED_CABC_EN_REG(base, n) (WLED_FULL_SCALE_REG(base, n) + 0x04) /* wled control registers */ #define WLED_BRIGHTNESS_CNTL_LSB(base, n) (base + 0x40 + 2*n) #define WLED_BRIGHTNESS_CNTL_MSB(base, n) (base + 0x41 + 2*n) #define WLED_MOD_CTRL_REG(base) (base + 0x46) #define WLED_SYNC_REG(base) (base + 0x47) #define WLED_FDBCK_CTRL_REG(base) (base + 0x48) #define WLED_MOD_SCHEME(base) (base + 0x4A) #define WLED_SWITCHING_FREQ_REG(base) (base + 0x4C) #define WLED_OVP_CFG_REG(base) (base + 0x4D) #define WLED_BOOST_LIMIT_REG(base) (base + 0x4E) #define WLED_CURR_SINK_REG(base) (base + 0x4F) #define WLED_HIGH_POLE_CAP_REG(base) (base + 0x58) #define WLED_CURR_SINK_MASK 0xE0 #define WLED_CURR_SINK_SHFT 0x05 #define WLED_DISABLE_ALL_SINKS 0x00 #define WLED_SWITCH_FREQ_MASK 0x0F #define WLED_OVP_VAL_MASK 0x03 #define WLED_OVP_VAL_BIT_SHFT 0x00 #define WLED_BOOST_LIMIT_MASK 0x07 #define WLED_BOOST_LIMIT_BIT_SHFT 0x00 #define WLED_BOOST_ON 0x80 #define WLED_BOOST_OFF 0x00 #define WLED_EN_MASK 0x80 #define WLED_NO_MASK 0x00 #define WLED_CP_SELECT_MAX 0x03 #define WLED_CP_SELECT_MASK 0x02 #define WLED_USE_EXT_GEN_MOD_SRC 0x01 #define WLED_CTL_DLY_STEP 200 #define WLED_CTL_DLY_MAX 1400 #define WLED_MAX_CURR 25 #define WLED_NO_CURRENT 0x00 #define WLED_OVP_DELAY 1000 #define WLED_MSB_MASK 0x0F #define WLED_MAX_CURR_MASK 0x1F #define WLED_OP_FDBCK_MASK 0x07 #define WLED_OP_FDBCK_BIT_SHFT 0x00 #define WLED_OP_FDBCK_DEFAULT 0x00 #define WLED_MOD_DIM_METHOD 0x01 #define WLED_MOD_DIM_DIG 0x01 #define WLED_MOD_DIM_ANALOG 0x00 #define WLED_MAX_LEVEL 4095 #define WLED_8_BIT_MASK 0xFF #define WLED_4_BIT_MASK 0x0F #define WLED_8_BIT_SHFT 0x08 #define WLED_MAX_DUTY_CYCLE 0xFFF #define WLED_SCALE_VAL 0x4 #define WLED_SCALE_THRESHOLD 512 #define WLED_SYNC_VAL 0x07 #define WLED_SYNC_RESET_VAL 0x00 #define PMIC_VER_8026 0x04 #define PMIC_VERSION_REG 0x0105 #define WLED_DEFAULT_STRINGS 0x01 #define WLED_DEFAULT_OVP_VAL 0x02 #define WLED_BOOST_LIM_DEFAULT 0x03 #define WLED_CP_SEL_DEFAULT 0x00 #define WLED_CTRL_DLY_DEFAULT 0x00 #define WLED_SWITCH_FREQ_DEFAULT 0x0B #define FLASH_SAFETY_TIMER(base) (base + 0x40) #define FLASH_MAX_CURR(base) (base + 0x41) #define FLASH_LED_0_CURR(base) (base + 0x42) #define FLASH_LED_1_CURR(base) (base + 0x43) #define FLASH_CLAMP_CURR(base) (base + 0x44) #define FLASH_LED_TMR_CTRL(base) (base + 0x48) #define FLASH_HEADROOM(base) (base + 0x4A) #define FLASH_STARTUP_DELAY(base) (base + 0x4B) #define FLASH_MASK_ENABLE(base) (base + 0x4C) #define FLASH_VREG_OK_FORCE(base) (base + 0x4F) #define FLASH_ENABLE_CONTROL(base) (base + 0x46) #define FLASH_LED_STROBE_CTRL(base) (base + 0x47) #define FLASH_LED_UNLOCK_SECURE(base) (base + 0xD0) #define FLASH_LED_TORCH(base) (base + 0xE4) #define FLASH_FAULT_DETECT(base) (base + 0x51) #define FLASH_PERIPHERAL_SUBTYPE(base) (base + 0x05) #define FLASH_CURRENT_RAMP(base) (base + 0x54) #define FLASH_MAX_LEVEL 0x4F #define TORCH_MAX_LEVEL 0x0F #define FLASH_NO_MASK 0x00 #define FLASH_MASK_1 0x20 #define FLASH_MASK_REG_MASK 0xE0 #define FLASH_HEADROOM_MASK 0x03 #define FLASH_SAFETY_TIMER_MASK 0x7F #define FLASH_CURRENT_MASK 0xFF #define FLASH_MAX_CURRENT_MASK 0x7F #define FLASH_TMR_MASK 0x03 #define FLASH_TMR_WATCHDOG 0x03 #define FLASH_TMR_SAFETY 0x00 #define FLASH_FAULT_DETECT_MASK 0X80 #define FLASH_HW_VREG_OK 0x40 #define FLASH_VREG_MASK 0xC0 #define FLASH_STARTUP_DLY_MASK 0x02 #define FLASH_CURRENT_RAMP_MASK 0xBF #define FLASH_ENABLE_ALL 0xE0 #define FLASH_ENABLE_MODULE 0x80 #define FLASH_ENABLE_MODULE_MASK 0x80 #define FLASH_DISABLE_ALL 0x00 #define FLASH_ENABLE_MASK 0xE0 #define FLASH_ENABLE_LED_0 0xC0 #define FLASH_ENABLE_LED_1 0xA0 #define FLASH_INIT_MASK 0xE0 #define FLASH_SELFCHECK_ENABLE 0x80 #define FLASH_RAMP_STEP_27US 0xBF #define FLASH_STROBE_SW 0xC0 #define FLASH_STROBE_HW 0x04 #define FLASH_STROBE_MASK 0xC7 #define FLASH_LED_0_OUTPUT 0x80 #define FLASH_LED_1_OUTPUT 0x40 #define FLASH_CURRENT_PRGM_MIN 1 #define FLASH_CURRENT_PRGM_SHIFT 1 #define FLASH_CURRENT_MAX 0x4F #define FLASH_CURRENT_TORCH 0x07 #define FLASH_DURATION_200ms 0x13 #define FLASH_CLAMP_200mA 0x0F #define FLASH_TORCH_MASK 0x03 #define FLASH_LED_TORCH_ENABLE 0x00 #define FLASH_LED_TORCH_DISABLE 0x03 #define FLASH_UNLOCK_SECURE 0xA5 #define FLASH_SECURE_MASK 0xFF #define FLASH_SUBTYPE_DUAL 0x01 #define FLASH_SUBTYPE_SINGLE 0x02 #define FLASH_RAMP_UP_DELAY_US 1000 #define FLASH_RAMP_DN_DELAY_US 2160 #define LED_TRIGGER_DEFAULT "none" #define RGB_LED_SRC_SEL(base) (base + 0x45) #define RGB_LED_EN_CTL(base) (base + 0x46) #define RGB_LED_ATC_CTL(base) (base + 0x47) #define RGB_MAX_LEVEL LED_FULL #define RGB_LED_ENABLE_RED 0x80 #define RGB_LED_ENABLE_GREEN 0x40 #define RGB_LED_ENABLE_BLUE 0x20 #define RGB_LED_SOURCE_VPH_PWR 0x01 #define RGB_LED_ENABLE_MASK 0xE0 #define RGB_LED_SRC_MASK 0x03 #define QPNP_LED_PWM_FLAGS (PM_PWM_LUT_LOOP | PM_PWM_LUT_RAMP_UP) #define QPNP_LUT_RAMP_STEP_DEFAULT 255 #define PWM_LUT_MAX_SIZE 63 #define PWM_GPLED_LUT_MAX_SIZE 31 #define RGB_LED_DISABLE 0x00 #define MPP_MAX_LEVEL LED_FULL #define LED_MPP_MODE_CTRL(base) (base + 0x40) #define LED_MPP_VIN_CTRL(base) (base + 0x41) #define LED_MPP_EN_CTRL(base) (base + 0x46) #define LED_MPP_SINK_CTRL(base) (base + 0x4C) #define LED_MPP_CURRENT_MIN 5 #define LED_MPP_CURRENT_MAX 40 #define LED_MPP_VIN_CTRL_DEFAULT 0 #define LED_MPP_CURRENT_PER_SETTING 5 #define LED_MPP_SOURCE_SEL_DEFAULT LED_MPP_MODE_ENABLE #define LED_MPP_SINK_MASK 0x07 #define LED_MPP_MODE_MASK 0x7F #define LED_MPP_VIN_MASK 0x03 #define LED_MPP_EN_MASK 0x80 #define LED_MPP_SRC_MASK 0x0F #define LED_MPP_MODE_CTRL_MASK 0x70 #define LED_MPP_MODE_SINK (0x06 << 4) #define LED_MPP_MODE_ENABLE 0x01 #define LED_MPP_MODE_OUTPUT 0x10 #define LED_MPP_MODE_DISABLE 0x00 #define LED_MPP_EN_ENABLE 0x80 #define LED_MPP_EN_DISABLE 0x00 #define MPP_SOURCE_DTEST1 0x08 #define KPDBL_MAX_LEVEL LED_FULL #define KPDBL_ROW_SRC_SEL(base) (base + 0x40) #define KPDBL_ENABLE(base) (base + 0x46) #define KPDBL_ROW_SRC(base) (base + 0xE5) #define KPDBL_ROW_SRC_SEL_VAL_MASK 0x0F #define KPDBL_ROW_SCAN_EN_MASK 0x80 #define KPDBL_ROW_SCAN_VAL_MASK 0x0F #define KPDBL_ROW_SCAN_EN_SHIFT 7 #define KPDBL_MODULE_EN 0x80 #define KPDBL_MODULE_DIS 0x00 #define KPDBL_MODULE_EN_MASK 0x80 /** * enum qpnp_leds - QPNP supported led ids * @QPNP_ID_WLED - White led backlight */ enum qpnp_leds { QPNP_ID_WLED = 0, QPNP_ID_FLASH1_LED0, QPNP_ID_FLASH1_LED1, QPNP_ID_RGB_RED, QPNP_ID_RGB_GREEN, QPNP_ID_RGB_BLUE, QPNP_ID_LED_MPP, QPNP_ID_KPDBL, QPNP_ID_MAX, }; /* current boost limit */ enum wled_current_boost_limit { WLED_CURR_LIMIT_105mA, WLED_CURR_LIMIT_385mA, WLED_CURR_LIMIT_525mA, WLED_CURR_LIMIT_805mA, WLED_CURR_LIMIT_980mA, WLED_CURR_LIMIT_1260mA, WLED_CURR_LIMIT_1400mA, WLED_CURR_LIMIT_1680mA, }; /* over voltage protection threshold */ enum wled_ovp_threshold { WLED_OVP_35V, WLED_OVP_32V, WLED_OVP_29V, WLED_OVP_27V, }; enum flash_headroom { HEADROOM_250mV = 0, HEADROOM_300mV, HEADROOM_400mV, HEADROOM_500mV, }; enum flash_startup_dly { DELAY_10us = 0, DELAY_32us, DELAY_64us, DELAY_128us, }; enum led_mode { PWM_MODE = 0, LPG_MODE, MANUAL_MODE, }; static u8 wled_debug_regs[] = { /* common registers */ 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, /* LED1 */ 0x60, 0x61, 0x62, 0x63, 0x66, /* LED2 */ 0x70, 0x71, 0x72, 0x73, 0x76, /* LED3 */ 0x80, 0x81, 0x82, 0x83, 0x86, }; static u8 flash_debug_regs[] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x48, 0x49, 0x4b, 0x4c, 0x4f, 0x46, 0x47, }; static u8 rgb_pwm_debug_regs[] = { 0x45, 0x46, 0x47, }; static u8 mpp_debug_regs[] = { 0x40, 0x41, 0x42, 0x45, 0x46, 0x4c, }; static u8 kpdbl_debug_regs[] = { 0x40, 0x46, 0xb1, 0xb3, 0xb4, 0xe5, }; /** * pwm_config_data - pwm configuration data * @lut_params - lut parameters to be used by pwm driver * @pwm_device - pwm device * @pwm_channel - pwm channel to be configured for led * @pwm_period_us - period for pwm, in us * @mode - mode the led operates in * @old_duty_pcts - storage for duty pcts that may need to be reused * @default_mode - default mode of LED as set in device tree * @use_blink - use blink sysfs entry * @blinking - device is currently blinking w/LPG mode */ struct pwm_config_data { struct lut_params lut_params; struct pwm_device *pwm_dev; int pwm_channel; u32 pwm_period_us; struct pwm_duty_cycles *duty_cycles; int *old_duty_pcts; u8 mode; u8 default_mode; bool use_blink; bool blinking; }; /** * wled_config_data - wled configuration data * @num_strings - number of wled strings supported * @ovp_val - over voltage protection threshold * @boost_curr_lim - boot current limit * @cp_select - high pole capacitance * @ctrl_delay_us - delay in activation of led * @dig_mod_gen_en - digital module generator * @cs_out_en - current sink output enable * @op_fdbck - selection of output as feedback for the boost */ struct wled_config_data { u8 num_strings; u8 ovp_val; u8 boost_curr_lim; u8 cp_select; u8 ctrl_delay_us; u8 switch_freq; u8 op_fdbck; u8 pmic_version; bool cabc_en; bool dig_mod_gen_en; bool cs_out_en; }; /** * mpp_config_data - mpp configuration data * @pwm_cfg - device pwm configuration * @current_setting - current setting, 5ma-40ma in 5ma increments * @source_sel - source selection * @mode_ctrl - mode control * @vin_ctrl - input control * @min_brightness - minimum brightness supported * @pwm_mode - pwm mode in use */ struct mpp_config_data { struct pwm_config_data *pwm_cfg; u8 current_setting; u8 source_sel; u8 mode_ctrl; u8 vin_ctrl; u8 min_brightness; u8 pwm_mode; }; /** * flash_config_data - flash configuration data * @current_prgm - current to be programmed, scaled by max level * @clamp_curr - clamp current to use * @headroom - headroom value to use * @duration - duration of the flash * @enable_module - enable address for particular flash * @trigger_flash - trigger flash * @startup_dly - startup delay for flash * @strobe_type - select between sw and hw strobe * @peripheral_subtype - module peripheral subtype * @current_addr - address to write for current * @second_addr - address of secondary flash to be written * @safety_timer - enable safety timer or watchdog timer * @torch_enable - enable flash LED torch mode * @flash_reg_get - flash regulator attached or not * @flash_on - flash status, on or off * @torch_on - torch status, on or off * @flash_boost_reg - boost regulator for flash * @torch_boost_reg - boost regulator for torch */ struct flash_config_data { u8 current_prgm; u8 clamp_curr; u8 headroom; u8 duration; u8 enable_module; u8 trigger_flash; u8 startup_dly; u8 strobe_type; u8 peripheral_subtype; u16 current_addr; u16 second_addr; bool safety_timer; bool torch_enable; bool flash_reg_get; bool flash_on; bool torch_on; struct regulator *flash_boost_reg; struct regulator *torch_boost_reg; }; /** * kpdbl_config_data - kpdbl configuration data * @pwm_cfg - device pwm configuration * @mode - running mode: pwm or lut * @row_id - row id of the led * @row_src_vbst - 0 for vph_pwr and 1 for vbst * @row_src_en - enable row source * @always_on - always on row * @lut_params - lut parameters to be used by pwm driver * @duty_cycles - duty cycles for lut */ struct kpdbl_config_data { struct pwm_config_data *pwm_cfg; u32 row_id; bool row_src_vbst; bool row_src_en; bool always_on; struct pwm_duty_cycles *duty_cycles; struct lut_params lut_params; }; /** * rgb_config_data - rgb configuration data * @pwm_cfg - device pwm configuration * @enable - bits to enable led */ struct rgb_config_data { struct pwm_config_data *pwm_cfg; u8 enable; }; /** * struct qpnp_led_data - internal led data structure * @led_classdev - led class device * @delayed_work - delayed work for turning off the LED * @work - workqueue for led * @id - led index * @base_reg - base register given in device tree * @lock - to protect the transactions * @reg - cached value of led register * @num_leds - number of leds in the module * @max_current - maximum current supported by LED * @default_on - true: default state max, false, default state 0 * @turn_off_delay_ms - number of msec before turning off the LED */ struct qpnp_led_data { struct led_classdev cdev; struct spmi_device *spmi_dev; struct delayed_work dwork; struct work_struct work; int id; u16 base; u8 reg; u8 num_leds; struct mutex lock; struct wled_config_data *wled_cfg; struct flash_config_data *flash_cfg; struct kpdbl_config_data *kpdbl_cfg; struct rgb_config_data *rgb_cfg; struct mpp_config_data *mpp_cfg; int max_current; bool default_on; int turn_off_delay_ms; }; static int num_kpbl_leds_on; static int qpnp_led_masked_write(struct qpnp_led_data *led, u16 addr, u8 mask, u8 val) { int rc; u8 reg; rc = spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, addr, &reg, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to read from addr=%x, rc(%d)\n", addr, rc); } reg &= ~mask; reg |= val; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, addr, &reg, 1); if (rc) dev_err(&led->spmi_dev->dev, "Unable to write to addr=%x, rc(%d)\n", addr, rc); return rc; } static void qpnp_dump_regs(struct qpnp_led_data *led, u8 regs[], u8 array_size) { int i; u8 val; pr_debug("===== %s LED register dump start =====\n", led->cdev.name); for (i = 0; i < array_size; i++) { spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, led->base + regs[i], &val, sizeof(val)); pr_debug("%s: 0x%x = 0x%x\n", led->cdev.name, led->base + regs[i], val); } pr_debug("===== %s LED register dump end =====\n", led->cdev.name); } static int qpnp_wled_sync(struct qpnp_led_data *led) { int rc; u8 val; /* sync */ val = WLED_SYNC_VAL; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_SYNC_REG(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED set sync reg failed(%d)\n", rc); return rc; } val = WLED_SYNC_RESET_VAL; mdelay(1); rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_SYNC_REG(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED reset sync reg failed(%d)\n", rc); return rc; } return 0; } static int qpnp_wled_set(struct qpnp_led_data *led) { static int max_current, digital; int rc, duty, level, scale_ratio = WLED_SCALE_VAL; u8 val, i, num_wled_strings, sink_val; num_wled_strings = led->wled_cfg->num_strings; level = led->cdev.brightness; if (level > WLED_MAX_LEVEL) level = WLED_MAX_LEVEL; if (level == 0) { for (i = 0; i < num_wled_strings; i++) { rc = qpnp_led_masked_write(led, WLED_FULL_SCALE_REG(led->base, i), WLED_MAX_CURR_MASK, WLED_NO_CURRENT); if (rc) { dev_err(&led->spmi_dev->dev, "Write max current failure (%d)\n", rc); return rc; } } rc = qpnp_wled_sync(led); if (rc) { dev_err(&led->spmi_dev->dev, "WLED sync failed(%d)\n", rc); return rc; } rc = spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_CURR_SINK_REG(led->base), &sink_val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED read sink reg failed(%d)\n", rc); return rc; } if (led->wled_cfg->pmic_version == PMIC_VER_8026) { val = WLED_DISABLE_ALL_SINKS; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_CURR_SINK_REG(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED write sink reg failed(%d)\n", rc); return rc; } usleep(WLED_OVP_DELAY); } val = WLED_BOOST_OFF; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_MOD_CTRL_REG(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED write ctrl reg failed(%d)\n", rc); return rc; } for (i = 0; i < num_wled_strings; i++) { rc = qpnp_led_masked_write(led, WLED_FULL_SCALE_REG(led->base, i), WLED_MAX_CURR_MASK, led->max_current); if (rc) { dev_err(&led->spmi_dev->dev, "Write max current failure (%d)\n", rc); return rc; } } rc = qpnp_wled_sync(led); if (rc) { dev_err(&led->spmi_dev->dev, "WLED sync failed(%d)\n", rc); return rc; } rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_CURR_SINK_REG(led->base), &sink_val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED write sink reg failed(%d)\n", rc); return rc; } digital = 0; max_current = 0; } else if (level < WLED_SCALE_THRESHOLD) { if (max_current != led->max_current/scale_ratio) { max_current = led->max_current/scale_ratio; dev_info(&led->spmi_dev->dev, "bl: change to lower light %d\n", level); for (i = 0; i < num_wled_strings; i++) { rc = qpnp_led_masked_write(led, WLED_FULL_SCALE_REG(led->base, i), WLED_MAX_CURR_MASK, max_current); if (rc) { dev_err(&led->spmi_dev->dev, "Write max current failure (%d)\n", rc); return rc; } } } duty = (WLED_MAX_DUTY_CYCLE * level * scale_ratio) / WLED_MAX_LEVEL; if (digital != 2) { //1 - analog 2 - digital dev_info(&led->spmi_dev->dev, "bl: change to digital %d\n", level); val = WLED_BOOST_ON; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_MOD_CTRL_REG(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED write ctrl reg failed(%d)\n", rc); return rc; } digital = 2; } } else { if (max_current != led->max_current) { max_current = led->max_current; dev_info(&led->spmi_dev->dev, "bl: change to higher light %d\n", level); for (i = 0; i < num_wled_strings; i++) { rc = qpnp_led_masked_write(led, WLED_FULL_SCALE_REG(led->base, i), WLED_MAX_CURR_MASK, max_current); if (rc) { dev_err(&led->spmi_dev->dev, "Write max current failure (%d)\n", rc); return rc; } } } duty = (WLED_MAX_DUTY_CYCLE * level) / WLED_MAX_LEVEL; if (digital != 1) { dev_info(&led->spmi_dev->dev, "bl: change to analog %d\n", level); val = WLED_BOOST_ON; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_MOD_CTRL_REG(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED write ctrl reg failed(%d)\n", rc); return rc; } digital = 1; } } /* program brightness control registers */ for (i = 0; i < num_wled_strings; i++) { rc = qpnp_led_masked_write(led, WLED_BRIGHTNESS_CNTL_MSB(led->base, i), WLED_MSB_MASK, (duty >> WLED_8_BIT_SHFT) & WLED_4_BIT_MASK); if (rc) { dev_err(&led->spmi_dev->dev, "WLED set brightness MSB failed(%d)\n", rc); return rc; } val = duty & WLED_8_BIT_MASK; rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, WLED_BRIGHTNESS_CNTL_LSB(led->base, i), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "WLED set brightness LSB failed(%d)\n", rc); return rc; } } rc = qpnp_wled_sync(led); if (rc) { dev_err(&led->spmi_dev->dev, "WLED sync failed(%d)\n", rc); return rc; } return 0; } static int qpnp_mpp_set(struct qpnp_led_data *led) { int rc, val; int duty_us; if (led->cdev.brightness) { if (led->cdev.brightness < led->mpp_cfg->min_brightness) { dev_warn(&led->spmi_dev->dev, "brightness is less than supported..." \ "set to minimum supported\n"); led->cdev.brightness = led->mpp_cfg->min_brightness; } if (led->mpp_cfg->pwm_mode != MANUAL_MODE) { if (!led->mpp_cfg->pwm_cfg->blinking) { led->mpp_cfg->pwm_cfg->mode = led->mpp_cfg->pwm_cfg->default_mode; led->mpp_cfg->pwm_mode = led->mpp_cfg->pwm_cfg->default_mode; } } if (led->mpp_cfg->pwm_mode == PWM_MODE) { pwm_disable(led->mpp_cfg->pwm_cfg->pwm_dev); duty_us = (led->mpp_cfg->pwm_cfg->pwm_period_us * led->cdev.brightness) / LED_FULL; /*config pwm for brightness scaling*/ rc = pwm_config_us(led->mpp_cfg->pwm_cfg->pwm_dev, duty_us, led->mpp_cfg->pwm_cfg->pwm_period_us); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Failed to " \ "configure pwm for new values\n"); return rc; } } if (led->mpp_cfg->pwm_mode != MANUAL_MODE) pwm_enable(led->mpp_cfg->pwm_cfg->pwm_dev); else { if (led->cdev.brightness < LED_MPP_CURRENT_MIN) led->cdev.brightness = LED_MPP_CURRENT_MIN; val = (led->cdev.brightness / LED_MPP_CURRENT_MIN) - 1; rc = qpnp_led_masked_write(led, LED_MPP_SINK_CTRL(led->base), LED_MPP_SINK_MASK, val); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write sink control reg\n"); return rc; } } val = (led->mpp_cfg->source_sel & LED_MPP_SRC_MASK) | (led->mpp_cfg->mode_ctrl & LED_MPP_MODE_CTRL_MASK); rc = qpnp_led_masked_write(led, LED_MPP_MODE_CTRL(led->base), LED_MPP_MODE_MASK, val); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led mode reg\n"); return rc; } rc = qpnp_led_masked_write(led, LED_MPP_EN_CTRL(led->base), LED_MPP_EN_MASK, LED_MPP_EN_ENABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led enable " \ "reg\n"); return rc; } } else { if (led->mpp_cfg->pwm_mode != MANUAL_MODE) { led->mpp_cfg->pwm_cfg->mode = led->mpp_cfg->pwm_cfg->default_mode; led->mpp_cfg->pwm_mode = led->mpp_cfg->pwm_cfg->default_mode; pwm_disable(led->mpp_cfg->pwm_cfg->pwm_dev); } rc = qpnp_led_masked_write(led, LED_MPP_MODE_CTRL(led->base), LED_MPP_MODE_MASK, LED_MPP_MODE_DISABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led mode reg\n"); return rc; } rc = qpnp_led_masked_write(led, LED_MPP_EN_CTRL(led->base), LED_MPP_EN_MASK, LED_MPP_EN_DISABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led enable reg\n"); return rc; } } if (led->mpp_cfg->pwm_mode != MANUAL_MODE) led->mpp_cfg->pwm_cfg->blinking = false; qpnp_dump_regs(led, mpp_debug_regs, ARRAY_SIZE(mpp_debug_regs)); return 0; } static int qpnp_flash_regulator_operate(struct qpnp_led_data *led, bool on) { int rc, i; struct qpnp_led_data *led_array; bool regulator_on = false; led_array = dev_get_drvdata(&led->spmi_dev->dev); if (!led_array) { dev_err(&led->spmi_dev->dev, "Unable to get LED array\n"); return -EINVAL; } for (i = 0; i < led->num_leds; i++) regulator_on |= led_array[i].flash_cfg->flash_on; if (!on) goto regulator_turn_off; if (!regulator_on && !led->flash_cfg->flash_on) { for (i = 0; i < led->num_leds; i++) { if (led_array[i].flash_cfg->flash_reg_get) { rc = regulator_enable( led_array[i].flash_cfg->\ flash_boost_reg); if (rc) { dev_err(&led->spmi_dev->dev, "Regulator enable failed(%d)\n", rc); return rc; } led->flash_cfg->flash_on = true; } break; } } return 0; regulator_turn_off: if (regulator_on && led->flash_cfg->flash_on) { for (i = 0; i < led->num_leds; i++) { if (led_array[i].flash_cfg->flash_reg_get) { rc = qpnp_led_masked_write(led, FLASH_ENABLE_CONTROL(led->base), FLASH_ENABLE_MASK, FLASH_DISABLE_ALL); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); } rc = regulator_disable(led_array[i].flash_cfg->\ flash_boost_reg); if (rc) { dev_err(&led->spmi_dev->dev, "Regulator disable failed(%d)\n", rc); return rc; } led->flash_cfg->flash_on = false; } break; } } return 0; } static int qpnp_torch_regulator_operate(struct qpnp_led_data *led, bool on) { int rc; if (!on) goto regulator_turn_off; if (!led->flash_cfg->torch_on) { rc = regulator_enable(led->flash_cfg->torch_boost_reg); if (rc) { dev_err(&led->spmi_dev->dev, "Regulator enable failed(%d)\n", rc); return rc; } led->flash_cfg->torch_on = true; } return 0; regulator_turn_off: if (led->flash_cfg->torch_on) { rc = qpnp_led_masked_write(led, FLASH_ENABLE_CONTROL(led->base), FLASH_ENABLE_MODULE_MASK, FLASH_DISABLE_ALL); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); } rc = regulator_disable(led->flash_cfg->torch_boost_reg); if (rc) { dev_err(&led->spmi_dev->dev, "Regulator disable failed(%d)\n", rc); return rc; } led->flash_cfg->torch_on = false; } return 0; } static int qpnp_flash_set(struct qpnp_led_data *led) { int rc, error; int val = led->cdev.brightness; if (led->flash_cfg->torch_enable) led->flash_cfg->current_prgm = (val * TORCH_MAX_LEVEL / led->max_current); else led->flash_cfg->current_prgm = (val * FLASH_MAX_LEVEL / led->max_current); /* Set led current */ if (val > 0) { if (led->flash_cfg->torch_enable) { if (led->flash_cfg->peripheral_subtype == FLASH_SUBTYPE_DUAL) { rc = qpnp_torch_regulator_operate(led, true); if (rc) { dev_err(&led->spmi_dev->dev, "Torch regulator operate failed(%d)\n", rc); return rc; } } else if (led->flash_cfg->peripheral_subtype == FLASH_SUBTYPE_SINGLE) { rc = qpnp_flash_regulator_operate(led, true); if (rc) { dev_err(&led->spmi_dev->dev, "Flash regulator operate failed(%d)\n", rc); goto error_flash_set; } } rc = qpnp_led_masked_write(led, FLASH_LED_UNLOCK_SECURE(led->base), FLASH_SECURE_MASK, FLASH_UNLOCK_SECURE); if (rc) { dev_err(&led->spmi_dev->dev, "Secure reg write failed(%d)\n", rc); goto error_reg_write; } rc = qpnp_led_masked_write(led, FLASH_LED_TORCH(led->base), FLASH_TORCH_MASK, FLASH_LED_TORCH_ENABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Torch reg write failed(%d)\n", rc); goto error_reg_write; } rc = qpnp_led_masked_write(led, led->flash_cfg->current_addr, FLASH_CURRENT_MASK, led->flash_cfg->current_prgm); if (rc) { dev_err(&led->spmi_dev->dev, "Current reg write failed(%d)\n", rc); goto error_reg_write; } rc = qpnp_led_masked_write(led, led->flash_cfg->second_addr, FLASH_CURRENT_MASK, led->flash_cfg->current_prgm); if (rc) { dev_err(&led->spmi_dev->dev, "2nd Current reg write failed(%d)\n", rc); goto error_reg_write; } qpnp_led_masked_write(led, FLASH_MAX_CURR(led->base), FLASH_CURRENT_MASK, TORCH_MAX_LEVEL); if (rc) { dev_err(&led->spmi_dev->dev, "Max current reg write failed(%d)\n", rc); goto error_reg_write; } rc = qpnp_led_masked_write(led, FLASH_ENABLE_CONTROL(led->base), FLASH_ENABLE_MASK, led->flash_cfg->enable_module); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); goto error_reg_write; } rc = qpnp_led_masked_write(led, FLASH_LED_STROBE_CTRL(led->base), led->flash_cfg->trigger_flash, led->flash_cfg->trigger_flash); if (rc) { dev_err(&led->spmi_dev->dev, "LED %d strobe reg write failed(%d)\n", led->id, rc); goto error_reg_write; } } else { rc = qpnp_flash_regulator_operate(led, true); if (rc) { dev_err(&led->spmi_dev->dev, "Flash regulator operate failed(%d)\n", rc); goto error_flash_set; } /* Set flash safety timer */ rc = qpnp_led_masked_write(led, FLASH_SAFETY_TIMER(led->base), FLASH_SAFETY_TIMER_MASK, led->flash_cfg->duration); if (rc) { dev_err(&led->spmi_dev->dev, "Safety timer reg write failed(%d)\n", rc); goto error_flash_set; } /* Set max current */ rc = qpnp_led_masked_write(led, FLASH_MAX_CURR(led->base), FLASH_CURRENT_MASK, FLASH_MAX_LEVEL); if (rc) { dev_err(&led->spmi_dev->dev, "Max current reg write failed(%d)\n", rc); goto error_flash_set; } /* Set clamp current */ rc = qpnp_led_masked_write(led, FLASH_CLAMP_CURR(led->base), FLASH_CURRENT_MASK, led->flash_cfg->clamp_curr); if (rc) { dev_err(&led->spmi_dev->dev, "Clamp current reg write failed(%d)\n", rc); goto error_flash_set; } rc = qpnp_led_masked_write(led, led->flash_cfg->current_addr, FLASH_CURRENT_MASK, led->flash_cfg->current_prgm); if (rc) { dev_err(&led->spmi_dev->dev, "Current reg write failed(%d)\n", rc); goto error_flash_set; } rc = qpnp_led_masked_write(led, FLASH_ENABLE_CONTROL(led->base), led->flash_cfg->enable_module, led->flash_cfg->enable_module); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); goto error_flash_set; } /* * Add 1ms delay for bharger enter stable state */ usleep(FLASH_RAMP_UP_DELAY_US); if (!led->flash_cfg->strobe_type) { rc = qpnp_led_masked_write(led, FLASH_LED_STROBE_CTRL(led->base), led->flash_cfg->trigger_flash, led->flash_cfg->trigger_flash); if (rc) { dev_err(&led->spmi_dev->dev, "LED %d strobe reg write failed(%d)\n", led->id, rc); goto error_flash_set; } } else { rc = qpnp_led_masked_write(led, FLASH_LED_STROBE_CTRL(led->base), (led->flash_cfg->trigger_flash | FLASH_STROBE_HW), (led->flash_cfg->trigger_flash | FLASH_STROBE_HW)); if (rc) { dev_err(&led->spmi_dev->dev, "LED %d strobe reg write failed(%d)\n", led->id, rc); goto error_flash_set; } } } } else { rc = qpnp_led_masked_write(led, FLASH_LED_STROBE_CTRL(led->base), led->flash_cfg->trigger_flash, FLASH_DISABLE_ALL); if (rc) { dev_err(&led->spmi_dev->dev, "LED %d flash write failed(%d)\n", led->id, rc); if (led->flash_cfg->torch_enable) goto error_torch_set; else goto error_flash_set; } if (led->flash_cfg->torch_enable) { rc = qpnp_led_masked_write(led, FLASH_LED_UNLOCK_SECURE(led->base), FLASH_SECURE_MASK, FLASH_UNLOCK_SECURE); if (rc) { dev_err(&led->spmi_dev->dev, "Secure reg write failed(%d)\n", rc); goto error_torch_set; } rc = qpnp_led_masked_write(led, FLASH_LED_TORCH(led->base), FLASH_TORCH_MASK, FLASH_LED_TORCH_DISABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Torch reg write failed(%d)\n", rc); goto error_torch_set; } if (led->flash_cfg->peripheral_subtype == FLASH_SUBTYPE_DUAL) { rc = qpnp_torch_regulator_operate(led, false); if (rc) { dev_err(&led->spmi_dev->dev, "Torch regulator operate failed(%d)\n", rc); return rc; } } else if (led->flash_cfg->peripheral_subtype == FLASH_SUBTYPE_SINGLE) { rc = qpnp_flash_regulator_operate(led, false); if (rc) { dev_err(&led->spmi_dev->dev, "Flash regulator operate failed(%d)\n", rc); return rc; } } } else { /* * Disable module after ramp down complete for stable * behavior */ usleep(FLASH_RAMP_DN_DELAY_US); rc = qpnp_led_masked_write(led, FLASH_ENABLE_CONTROL(led->base), led->flash_cfg->enable_module & ~FLASH_ENABLE_MODULE_MASK, FLASH_DISABLE_ALL); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); if (led->flash_cfg->torch_enable) goto error_torch_set; else goto error_flash_set; } rc = qpnp_flash_regulator_operate(led, false); if (rc) { dev_err(&led->spmi_dev->dev, "Flash regulator operate failed(%d)\n", rc); return rc; } } } qpnp_dump_regs(led, flash_debug_regs, ARRAY_SIZE(flash_debug_regs)); return 0; error_reg_write: if (led->flash_cfg->peripheral_subtype == FLASH_SUBTYPE_SINGLE) goto error_flash_set; error_torch_set: error = qpnp_torch_regulator_operate(led, false); if (error) { dev_err(&led->spmi_dev->dev, "Torch regulator operate failed(%d)\n", rc); return error; } return rc; error_flash_set: error = qpnp_flash_regulator_operate(led, false); if (error) { dev_err(&led->spmi_dev->dev, "Flash regulator operate failed(%d)\n", rc); return error; } return rc; } static int qpnp_kpdbl_set(struct qpnp_led_data *led) { int duty_us; int rc; if (led->cdev.brightness) { if (!led->kpdbl_cfg->pwm_cfg->blinking) led->kpdbl_cfg->pwm_cfg->mode = led->kpdbl_cfg->pwm_cfg->default_mode; if (!num_kpbl_leds_on) { rc = qpnp_led_masked_write(led, KPDBL_ENABLE(led->base), KPDBL_MODULE_EN_MASK, KPDBL_MODULE_EN); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); return rc; } } if (led->kpdbl_cfg->pwm_cfg->mode == PWM_MODE) { duty_us = (led->kpdbl_cfg->pwm_cfg->pwm_period_us * led->cdev.brightness) / KPDBL_MAX_LEVEL; rc = pwm_config_us(led->kpdbl_cfg->pwm_cfg->pwm_dev, duty_us, led->kpdbl_cfg->pwm_cfg->pwm_period_us); if (rc < 0) { dev_err(&led->spmi_dev->dev, "pwm config failed\n"); return rc; } } rc = pwm_enable(led->kpdbl_cfg->pwm_cfg->pwm_dev); if (rc < 0) { dev_err(&led->spmi_dev->dev, "pwm enable failed\n"); return rc; } num_kpbl_leds_on++; } else { led->kpdbl_cfg->pwm_cfg->mode = led->kpdbl_cfg->pwm_cfg->default_mode; if (led->kpdbl_cfg->always_on) { rc = pwm_config_us(led->kpdbl_cfg->pwm_cfg->pwm_dev, 0, led->kpdbl_cfg->pwm_cfg->pwm_period_us); if (rc < 0) { dev_err(&led->spmi_dev->dev, "pwm config failed\n"); return rc; } rc = pwm_enable(led->kpdbl_cfg->pwm_cfg->pwm_dev); if (rc < 0) { dev_err(&led->spmi_dev->dev, "pwm enable failed\n"); return rc; } } else pwm_disable(led->kpdbl_cfg->pwm_cfg->pwm_dev); if (num_kpbl_leds_on > 0) num_kpbl_leds_on--; if (!num_kpbl_leds_on) { rc = qpnp_led_masked_write(led, KPDBL_ENABLE(led->base), KPDBL_MODULE_EN_MASK, KPDBL_MODULE_DIS); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led enable reg\n"); return rc; } } } led->kpdbl_cfg->pwm_cfg->blinking = false; qpnp_dump_regs(led, kpdbl_debug_regs, ARRAY_SIZE(kpdbl_debug_regs)); return 0; } static int qpnp_rgb_set(struct qpnp_led_data *led) { int duty_us; int rc; if (led->cdev.brightness) { if (!led->rgb_cfg->pwm_cfg->blinking) led->rgb_cfg->pwm_cfg->mode = led->rgb_cfg->pwm_cfg->default_mode; if (led->rgb_cfg->pwm_cfg->mode == PWM_MODE) { duty_us = (led->rgb_cfg->pwm_cfg->pwm_period_us * led->cdev.brightness) / LED_FULL; rc = pwm_config_us(led->rgb_cfg->pwm_cfg->pwm_dev, duty_us, led->rgb_cfg->pwm_cfg->pwm_period_us); if (rc < 0) { dev_err(&led->spmi_dev->dev, "pwm config failed\n"); return rc; } } rc = qpnp_led_masked_write(led, RGB_LED_EN_CTL(led->base), led->rgb_cfg->enable, led->rgb_cfg->enable); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led enable reg\n"); return rc; } rc = pwm_enable(led->rgb_cfg->pwm_cfg->pwm_dev); if (rc < 0) { dev_err(&led->spmi_dev->dev, "pwm enable failed\n"); return rc; } } else { led->rgb_cfg->pwm_cfg->mode = led->rgb_cfg->pwm_cfg->default_mode; pwm_disable(led->rgb_cfg->pwm_cfg->pwm_dev); rc = qpnp_led_masked_write(led, RGB_LED_EN_CTL(led->base), led->rgb_cfg->enable, RGB_LED_DISABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led enable reg\n"); return rc; } } led->rgb_cfg->pwm_cfg->blinking = false; qpnp_dump_regs(led, rgb_pwm_debug_regs, ARRAY_SIZE(rgb_pwm_debug_regs)); return 0; } static void qpnp_led_set(struct led_classdev *led_cdev, enum led_brightness value) { struct qpnp_led_data *led; led = container_of(led_cdev, struct qpnp_led_data, cdev); if (value < LED_OFF) { dev_err(&led->spmi_dev->dev, "Invalid brightness value\n"); return; } if (value > led->cdev.max_brightness) value = led->cdev.max_brightness; led->cdev.brightness = value; schedule_work(&led->work); } static void __qpnp_led_work(struct qpnp_led_data *led, enum led_brightness value) { int rc; mutex_lock(&led->lock); switch (led->id) { case QPNP_ID_WLED: rc = qpnp_wled_set(led); if (rc < 0) dev_err(&led->spmi_dev->dev, "WLED set brightness failed (%d)\n", rc); break; case QPNP_ID_FLASH1_LED0: case QPNP_ID_FLASH1_LED1: rc = qpnp_flash_set(led); if (rc < 0) dev_err(&led->spmi_dev->dev, "FLASH set brightness failed (%d)\n", rc); break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: rc = qpnp_rgb_set(led); if (rc < 0) dev_err(&led->spmi_dev->dev, "RGB set brightness failed (%d)\n", rc); break; case QPNP_ID_LED_MPP: rc = qpnp_mpp_set(led); if (rc < 0) dev_err(&led->spmi_dev->dev, "MPP set brightness failed (%d)\n", rc); break; case QPNP_ID_KPDBL: rc = qpnp_kpdbl_set(led); if (rc < 0) dev_err(&led->spmi_dev->dev, "KPDBL set brightness failed (%d)\n", rc); break; default: dev_err(&led->spmi_dev->dev, "Invalid LED(%d)\n", led->id); break; } mutex_unlock(&led->lock); } static void qpnp_led_work(struct work_struct *work) { struct qpnp_led_data *led = container_of(work, struct qpnp_led_data, work); __qpnp_led_work(led, led->cdev.brightness); return; } static int __devinit qpnp_led_set_max_brightness(struct qpnp_led_data *led) { switch (led->id) { case QPNP_ID_WLED: led->cdev.max_brightness = WLED_MAX_LEVEL; break; case QPNP_ID_FLASH1_LED0: case QPNP_ID_FLASH1_LED1: led->cdev.max_brightness = led->max_current; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: led->cdev.max_brightness = RGB_MAX_LEVEL; break; case QPNP_ID_LED_MPP: if (led->mpp_cfg->pwm_mode == MANUAL_MODE) led->cdev.max_brightness = led->max_current; else led->cdev.max_brightness = MPP_MAX_LEVEL; break; case QPNP_ID_KPDBL: led->cdev.max_brightness = KPDBL_MAX_LEVEL; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED(%d)\n", led->id); return -EINVAL; } return 0; } static enum led_brightness qpnp_led_get(struct led_classdev *led_cdev) { struct qpnp_led_data *led; led = container_of(led_cdev, struct qpnp_led_data, cdev); return led->cdev.brightness; } static void qpnp_led_turn_off_delayed(struct work_struct *work) { struct delayed_work *dwork = to_delayed_work(work); struct qpnp_led_data *led = container_of(dwork, struct qpnp_led_data, dwork); led->cdev.brightness = LED_OFF; qpnp_led_set(&led->cdev, led->cdev.brightness); } static void qpnp_led_turn_off(struct qpnp_led_data *led) { INIT_DELAYED_WORK(&led->dwork, qpnp_led_turn_off_delayed); schedule_delayed_work(&led->dwork, msecs_to_jiffies(led->turn_off_delay_ms)); } static int __devinit qpnp_wled_init(struct qpnp_led_data *led) { int rc, i; u8 num_wled_strings; num_wled_strings = led->wled_cfg->num_strings; /* verify ranges */ if (led->wled_cfg->ovp_val > WLED_OVP_27V) { dev_err(&led->spmi_dev->dev, "Invalid ovp value\n"); return -EINVAL; } if (led->wled_cfg->boost_curr_lim > WLED_CURR_LIMIT_1680mA) { dev_err(&led->spmi_dev->dev, "Invalid boost current limit\n"); return -EINVAL; } if (led->wled_cfg->cp_select > WLED_CP_SELECT_MAX) { dev_err(&led->spmi_dev->dev, "Invalid pole capacitance\n"); return -EINVAL; } if ((led->max_current > WLED_MAX_CURR)) { dev_err(&led->spmi_dev->dev, "Invalid max current\n"); return -EINVAL; } if ((led->wled_cfg->ctrl_delay_us % WLED_CTL_DLY_STEP) || (led->wled_cfg->ctrl_delay_us > WLED_CTL_DLY_MAX)) { dev_err(&led->spmi_dev->dev, "Invalid control delay\n"); return -EINVAL; } /* program over voltage protection threshold */ rc = qpnp_led_masked_write(led, WLED_OVP_CFG_REG(led->base), WLED_OVP_VAL_MASK, (led->wled_cfg->ovp_val << WLED_OVP_VAL_BIT_SHFT)); if (rc) { dev_err(&led->spmi_dev->dev, "WLED OVP reg write failed(%d)\n", rc); return rc; } /* program current boost limit */ rc = qpnp_led_masked_write(led, WLED_BOOST_LIMIT_REG(led->base), WLED_BOOST_LIMIT_MASK, led->wled_cfg->boost_curr_lim); if (rc) { dev_err(&led->spmi_dev->dev, "WLED boost limit reg write failed(%d)\n", rc); return rc; } /* program output feedback */ rc = qpnp_led_masked_write(led, WLED_FDBCK_CTRL_REG(led->base), WLED_OP_FDBCK_MASK, (led->wled_cfg->op_fdbck << WLED_OP_FDBCK_BIT_SHFT)); if (rc) { dev_err(&led->spmi_dev->dev, "WLED fdbck ctrl reg write failed(%d)\n", rc); return rc; } /* program switch frequency */ rc = qpnp_led_masked_write(led, WLED_SWITCHING_FREQ_REG(led->base), WLED_SWITCH_FREQ_MASK, led->wled_cfg->switch_freq); if (rc) { dev_err(&led->spmi_dev->dev, "WLED switch freq reg write failed(%d)\n", rc); return rc; } /* program current sink */ if (led->wled_cfg->cs_out_en) { rc = qpnp_led_masked_write(led, WLED_CURR_SINK_REG(led->base), WLED_CURR_SINK_MASK, (((1 << led->wled_cfg->num_strings) - 1) << WLED_CURR_SINK_SHFT)); if (rc) { dev_err(&led->spmi_dev->dev, "WLED curr sink reg write failed(%d)\n", rc); return rc; } } /* program high pole capacitance */ rc = qpnp_led_masked_write(led, WLED_HIGH_POLE_CAP_REG(led->base), WLED_CP_SELECT_MASK, led->wled_cfg->cp_select); if (rc) { dev_err(&led->spmi_dev->dev, "WLED pole cap reg write failed(%d)\n", rc); return rc; } /* program modulator, current mod src and cabc */ for (i = 0; i < num_wled_strings; i++) { rc = qpnp_led_masked_write(led, WLED_MOD_EN_REG(led->base, i), WLED_NO_MASK, WLED_EN_MASK); if (rc) { dev_err(&led->spmi_dev->dev, "WLED mod enable reg write failed(%d)\n", rc); return rc; } if (led->wled_cfg->dig_mod_gen_en) { rc = qpnp_led_masked_write(led, WLED_MOD_SRC_SEL_REG(led->base, i), WLED_NO_MASK, WLED_USE_EXT_GEN_MOD_SRC); if (rc) { dev_err(&led->spmi_dev->dev, "WLED dig mod en reg write failed(%d)\n", rc); } } if (led->wled_cfg->cabc_en) { rc = qpnp_led_masked_write(led, WLED_CABC_EN_REG(led->base, i), WLED_NO_MASK, WLED_EN_MASK); if (rc) { dev_err(&led->spmi_dev->dev, "WLED cabc en reg write failed(%d)\n", rc); } } rc = qpnp_led_masked_write(led, WLED_FULL_SCALE_REG(led->base, i), WLED_MAX_CURR_MASK, led->max_current); if (rc) { dev_err(&led->spmi_dev->dev, "WLED max current reg write failed(%d)\n", rc); return rc; } } /* dump wled registers */ qpnp_dump_regs(led, wled_debug_regs, ARRAY_SIZE(wled_debug_regs)); return 0; } static ssize_t led_mode_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; unsigned long state; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret = -EINVAL; ret = kstrtoul(buf, 10, &state); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); /* '1' to enable torch mode; '0' to switch to flash mode */ if (state == 1) led->flash_cfg->torch_enable = true; else led->flash_cfg->torch_enable = false; return count; } static ssize_t led_strobe_type_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; unsigned long state; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret = -EINVAL; ret = kstrtoul(buf, 10, &state); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); /* '0' for sw strobe; '1' for hw strobe */ if (state == 1) led->flash_cfg->strobe_type = 1; else led->flash_cfg->strobe_type = 0; return count; } static int qpnp_pwm_init(struct pwm_config_data *pwm_cfg, struct spmi_device *spmi_dev, const char *name) { int rc, start_idx, idx_len; if (pwm_cfg->pwm_channel != -1) { pwm_cfg->pwm_dev = pwm_request(pwm_cfg->pwm_channel, name); if (IS_ERR_OR_NULL(pwm_cfg->pwm_dev)) { dev_err(&spmi_dev->dev, "could not acquire PWM Channel %d, " \ "error %ld\n", pwm_cfg->pwm_channel, PTR_ERR(pwm_cfg->pwm_dev)); pwm_cfg->pwm_dev = NULL; return -ENODEV; } if (pwm_cfg->mode == LPG_MODE) { start_idx = pwm_cfg->duty_cycles->start_idx; idx_len = pwm_cfg->duty_cycles->num_duty_pcts; if (idx_len >= PWM_LUT_MAX_SIZE && start_idx) { dev_err(&spmi_dev->dev, "Wrong LUT size or index\n"); return -EINVAL; } if ((start_idx + idx_len) > PWM_LUT_MAX_SIZE) { dev_err(&spmi_dev->dev, "Exceed LUT limit\n"); return -EINVAL; } rc = pwm_lut_config(pwm_cfg->pwm_dev, PM_PWM_PERIOD_MIN, /* ignored by hardware */ pwm_cfg->duty_cycles->duty_pcts, pwm_cfg->lut_params); if (rc < 0) { dev_err(&spmi_dev->dev, "Failed to " \ "configure pwm LUT\n"); return rc; } } } else { dev_err(&spmi_dev->dev, "Invalid PWM channel\n"); return -EINVAL; } return 0; } static ssize_t pwm_us_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; u32 pwm_us; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret; u32 previous_pwm_us; struct pwm_config_data *pwm_cfg; led = container_of(led_cdev, struct qpnp_led_data, cdev); ret = kstrtou32(buf, 10, &pwm_us); if (ret) return ret; switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for pwm_us\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; previous_pwm_us = pwm_cfg->pwm_period_us; pwm_cfg->pwm_period_us = pwm_us; pwm_free(pwm_cfg->pwm_dev); ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) { pwm_cfg->pwm_period_us = previous_pwm_us; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new pwm_us value\n"); return ret; } qpnp_led_set(&led->cdev, led->cdev.brightness); return count; } static ssize_t pause_lo_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; u32 pause_lo; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret; u32 previous_pause_lo; struct pwm_config_data *pwm_cfg; ret = kstrtou32(buf, 10, &pause_lo); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for pause lo\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; previous_pause_lo = pwm_cfg->lut_params.lut_pause_lo; pwm_free(pwm_cfg->pwm_dev); pwm_cfg->lut_params.lut_pause_lo = pause_lo; ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) { pwm_cfg->lut_params.lut_pause_lo = previous_pause_lo; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new pause lo value\n"); return ret; } qpnp_led_set(&led->cdev, led->cdev.brightness); return count; } static ssize_t pause_hi_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; u32 pause_hi; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret; u32 previous_pause_hi; struct pwm_config_data *pwm_cfg; ret = kstrtou32(buf, 10, &pause_hi); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for pause hi\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; previous_pause_hi = pwm_cfg->lut_params.lut_pause_hi; pwm_free(pwm_cfg->pwm_dev); pwm_cfg->lut_params.lut_pause_hi = pause_hi; ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) { pwm_cfg->lut_params.lut_pause_hi = previous_pause_hi; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new pause hi value\n"); return ret; } qpnp_led_set(&led->cdev, led->cdev.brightness); return count; } static ssize_t start_idx_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; u32 start_idx; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret; u32 previous_start_idx; struct pwm_config_data *pwm_cfg; ret = kstrtou32(buf, 10, &start_idx); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for start idx\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; previous_start_idx = pwm_cfg->duty_cycles->start_idx; pwm_cfg->duty_cycles->start_idx = start_idx; pwm_cfg->lut_params.start_idx = pwm_cfg->duty_cycles->start_idx; pwm_free(pwm_cfg->pwm_dev); ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) { pwm_cfg->duty_cycles->start_idx = previous_start_idx; pwm_cfg->lut_params.start_idx = pwm_cfg->duty_cycles->start_idx; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new start idx value\n"); return ret; } qpnp_led_set(&led->cdev, led->cdev.brightness); return count; } static ssize_t ramp_step_ms_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; u32 ramp_step_ms; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret; u32 previous_ramp_step_ms; struct pwm_config_data *pwm_cfg; ret = kstrtou32(buf, 10, &ramp_step_ms); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for ramp step\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; previous_ramp_step_ms = pwm_cfg->lut_params.ramp_step_ms; pwm_free(pwm_cfg->pwm_dev); pwm_cfg->lut_params.ramp_step_ms = ramp_step_ms; ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) { pwm_cfg->lut_params.ramp_step_ms = previous_ramp_step_ms; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new ramp step value\n"); return ret; } qpnp_led_set(&led->cdev, led->cdev.brightness); return count; } static ssize_t lut_flags_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; u32 lut_flags; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret; u32 previous_lut_flags; struct pwm_config_data *pwm_cfg; ret = kstrtou32(buf, 10, &lut_flags); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for lut flags\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; previous_lut_flags = pwm_cfg->lut_params.flags; pwm_free(pwm_cfg->pwm_dev); pwm_cfg->lut_params.flags = lut_flags; ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) { pwm_cfg->lut_params.flags = previous_lut_flags; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new lut flags value\n"); return ret; } qpnp_led_set(&led->cdev, led->cdev.brightness); return count; } static ssize_t duty_pcts_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; int num_duty_pcts = 0; struct led_classdev *led_cdev = dev_get_drvdata(dev); char *buffer; ssize_t ret; int i = 0; int max_duty_pcts; struct pwm_config_data *pwm_cfg; u32 previous_num_duty_pcts; int value; int *previous_duty_pcts; led = container_of(led_cdev, struct qpnp_led_data, cdev); switch (led->id) { case QPNP_ID_LED_MPP: pwm_cfg = led->mpp_cfg->pwm_cfg; max_duty_pcts = PWM_LUT_MAX_SIZE; break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: pwm_cfg = led->rgb_cfg->pwm_cfg; max_duty_pcts = PWM_LUT_MAX_SIZE; break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for duty pcts\n"); return -EINVAL; } if (pwm_cfg->mode == LPG_MODE) pwm_cfg->blinking = true; buffer = (char *)buf; for (i = 0; i < max_duty_pcts; i++) { if (buffer == NULL) break; ret = sscanf((const char *)buffer, "%u,%s", &value, buffer); pwm_cfg->old_duty_pcts[i] = value; num_duty_pcts++; if (ret <= 1) break; } if (num_duty_pcts >= max_duty_pcts) { dev_err(&led->spmi_dev->dev, "Number of duty pcts given exceeds max (%d)\n", max_duty_pcts); return -EINVAL; } previous_num_duty_pcts = pwm_cfg->duty_cycles->num_duty_pcts; previous_duty_pcts = pwm_cfg->duty_cycles->duty_pcts; pwm_cfg->duty_cycles->num_duty_pcts = num_duty_pcts; pwm_cfg->duty_cycles->duty_pcts = pwm_cfg->old_duty_pcts; pwm_cfg->old_duty_pcts = previous_duty_pcts; pwm_cfg->lut_params.idx_len = pwm_cfg->duty_cycles->num_duty_pcts; pwm_free(pwm_cfg->pwm_dev); ret = qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); if (ret) goto restore; qpnp_led_set(&led->cdev, led->cdev.brightness); return count; restore: dev_err(&led->spmi_dev->dev, "Failed to initialize pwm with new duty pcts value\n"); pwm_cfg->duty_cycles->num_duty_pcts = previous_num_duty_pcts; pwm_cfg->old_duty_pcts = pwm_cfg->duty_cycles->duty_pcts; pwm_cfg->duty_cycles->duty_pcts = previous_duty_pcts; pwm_cfg->lut_params.idx_len = pwm_cfg->duty_cycles->num_duty_pcts; pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); return ret; } static void led_blink(struct qpnp_led_data *led, struct pwm_config_data *pwm_cfg) { if (pwm_cfg->use_blink) { if (led->cdev.brightness) { pwm_cfg->blinking = true; if (led->id == QPNP_ID_LED_MPP) led->mpp_cfg->pwm_mode = LPG_MODE; pwm_cfg->mode = LPG_MODE; } else { pwm_cfg->blinking = false; pwm_cfg->mode = pwm_cfg->default_mode; if (led->id == QPNP_ID_LED_MPP) led->mpp_cfg->pwm_mode = pwm_cfg->default_mode; } pwm_free(pwm_cfg->pwm_dev); qpnp_pwm_init(pwm_cfg, led->spmi_dev, led->cdev.name); qpnp_led_set(&led->cdev, led->cdev.brightness); } } static ssize_t blink_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct qpnp_led_data *led; unsigned long blinking; struct led_classdev *led_cdev = dev_get_drvdata(dev); ssize_t ret = -EINVAL; ret = kstrtoul(buf, 10, &blinking); if (ret) return ret; led = container_of(led_cdev, struct qpnp_led_data, cdev); led->cdev.brightness = blinking ? led->cdev.max_brightness : 0; switch (led->id) { case QPNP_ID_LED_MPP: led_blink(led, led->mpp_cfg->pwm_cfg); break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: led_blink(led, led->rgb_cfg->pwm_cfg); break; default: dev_err(&led->spmi_dev->dev, "Invalid LED id type for blink\n"); return -EINVAL; } return count; } static DEVICE_ATTR(led_mode, 0664, NULL, led_mode_store); static DEVICE_ATTR(strobe, 0664, NULL, led_strobe_type_store); static DEVICE_ATTR(pwm_us, 0664, NULL, pwm_us_store); static DEVICE_ATTR(pause_lo, 0664, NULL, pause_lo_store); static DEVICE_ATTR(pause_hi, 0664, NULL, pause_hi_store); static DEVICE_ATTR(start_idx, 0664, NULL, start_idx_store); static DEVICE_ATTR(ramp_step_ms, 0664, NULL, ramp_step_ms_store); static DEVICE_ATTR(lut_flags, 0664, NULL, lut_flags_store); static DEVICE_ATTR(duty_pcts, 0664, NULL, duty_pcts_store); static DEVICE_ATTR(blink, 0664, NULL, blink_store); static struct attribute *led_attrs[] = { &dev_attr_led_mode.attr, &dev_attr_strobe.attr, NULL }; static const struct attribute_group led_attr_group = { .attrs = led_attrs, }; static struct attribute *pwm_attrs[] = { &dev_attr_pwm_us.attr, NULL }; static struct attribute *lpg_attrs[] = { &dev_attr_pause_lo.attr, &dev_attr_pause_hi.attr, &dev_attr_start_idx.attr, &dev_attr_ramp_step_ms.attr, &dev_attr_lut_flags.attr, &dev_attr_duty_pcts.attr, NULL }; static struct attribute *blink_attrs[] = { &dev_attr_blink.attr, NULL }; static const struct attribute_group pwm_attr_group = { .attrs = pwm_attrs, }; static const struct attribute_group lpg_attr_group = { .attrs = lpg_attrs, }; static const struct attribute_group blink_attr_group = { .attrs = blink_attrs, }; static int __devinit qpnp_flash_init(struct qpnp_led_data *led) { int rc; led->flash_cfg->flash_on = false; rc = qpnp_led_masked_write(led, FLASH_LED_STROBE_CTRL(led->base), FLASH_STROBE_MASK, FLASH_DISABLE_ALL); if (rc) { dev_err(&led->spmi_dev->dev, "LED %d flash write failed(%d)\n", led->id, rc); return rc; } /* Disable flash LED module */ rc = qpnp_led_masked_write(led, FLASH_ENABLE_CONTROL(led->base), FLASH_ENABLE_MASK, FLASH_DISABLE_ALL); if (rc) { dev_err(&led->spmi_dev->dev, "Enable reg write failed(%d)\n", rc); return rc; } if (led->flash_cfg->torch_enable) return 0; /* Set headroom */ rc = qpnp_led_masked_write(led, FLASH_HEADROOM(led->base), FLASH_HEADROOM_MASK, led->flash_cfg->headroom); if (rc) { dev_err(&led->spmi_dev->dev, "Headroom reg write failed(%d)\n", rc); return rc; } /* Set startup delay */ rc = qpnp_led_masked_write(led, FLASH_STARTUP_DELAY(led->base), FLASH_STARTUP_DLY_MASK, led->flash_cfg->startup_dly); if (rc) { dev_err(&led->spmi_dev->dev, "Startup delay reg write failed(%d)\n", rc); return rc; } /* Set timer control - safety or watchdog */ if (led->flash_cfg->safety_timer) { rc = qpnp_led_masked_write(led, FLASH_LED_TMR_CTRL(led->base), FLASH_TMR_MASK, FLASH_TMR_SAFETY); if (rc) { dev_err(&led->spmi_dev->dev, "LED timer ctrl reg write failed(%d)\n", rc); return rc; } } /* Set Vreg force */ rc = qpnp_led_masked_write(led, FLASH_VREG_OK_FORCE(led->base), FLASH_VREG_MASK, FLASH_HW_VREG_OK); if (rc) { dev_err(&led->spmi_dev->dev, "Vreg OK reg write failed(%d)\n", rc); return rc; } /* Set self fault check */ rc = qpnp_led_masked_write(led, FLASH_FAULT_DETECT(led->base), FLASH_FAULT_DETECT_MASK, FLASH_SELFCHECK_ENABLE); if (rc) { dev_err(&led->spmi_dev->dev, "Fault detect reg write failed(%d)\n", rc); return rc; } /* Set mask enable */ rc = qpnp_led_masked_write(led, FLASH_MASK_ENABLE(led->base), FLASH_MASK_REG_MASK, FLASH_MASK_1); if (rc) { dev_err(&led->spmi_dev->dev, "Mask enable reg write failed(%d)\n", rc); return rc; } /* Set current ramp */ rc = qpnp_led_masked_write(led, FLASH_CURRENT_RAMP(led->base), FLASH_CURRENT_RAMP_MASK, FLASH_RAMP_STEP_27US); if (rc) { dev_err(&led->spmi_dev->dev, "Current ramp reg write failed(%d)\n", rc); return rc; } led->flash_cfg->strobe_type = 0; /* dump flash registers */ qpnp_dump_regs(led, flash_debug_regs, ARRAY_SIZE(flash_debug_regs)); return 0; } static int __devinit qpnp_kpdbl_init(struct qpnp_led_data *led) { int rc; u8 val; /* select row source - vbst or vph */ rc = spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, KPDBL_ROW_SRC_SEL(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to read from addr=%x, rc(%d)\n", KPDBL_ROW_SRC_SEL(led->base), rc); return rc; } if (led->kpdbl_cfg->row_src_vbst) val |= 1 << led->kpdbl_cfg->row_id; else val &= ~(1 << led->kpdbl_cfg->row_id); rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, KPDBL_ROW_SRC_SEL(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to read from addr=%x, rc(%d)\n", KPDBL_ROW_SRC_SEL(led->base), rc); return rc; } /* row source enable */ rc = spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, KPDBL_ROW_SRC(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to read from addr=%x, rc(%d)\n", KPDBL_ROW_SRC(led->base), rc); return rc; } if (led->kpdbl_cfg->row_src_en) val |= KPDBL_ROW_SCAN_EN_MASK | (1 << led->kpdbl_cfg->row_id); else val &= ~(1 << led->kpdbl_cfg->row_id); rc = spmi_ext_register_writel(led->spmi_dev->ctrl, led->spmi_dev->sid, KPDBL_ROW_SRC(led->base), &val, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to write to addr=%x, rc(%d)\n", KPDBL_ROW_SRC(led->base), rc); return rc; } /* enable module */ rc = qpnp_led_masked_write(led, KPDBL_ENABLE(led->base), KPDBL_MODULE_EN_MASK, KPDBL_MODULE_EN); if (rc) { dev_err(&led->spmi_dev->dev, "Enable module write failed(%d)\n", rc); return rc; } rc = qpnp_pwm_init(led->kpdbl_cfg->pwm_cfg, led->spmi_dev, led->cdev.name); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to initialize pwm\n"); return rc; } /* dump kpdbl registers */ qpnp_dump_regs(led, kpdbl_debug_regs, ARRAY_SIZE(kpdbl_debug_regs)); return 0; } static int __devinit qpnp_rgb_init(struct qpnp_led_data *led) { int rc; rc = qpnp_led_masked_write(led, RGB_LED_SRC_SEL(led->base), RGB_LED_SRC_MASK, RGB_LED_SOURCE_VPH_PWR); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led source select register\n"); return rc; } rc = qpnp_pwm_init(led->rgb_cfg->pwm_cfg, led->spmi_dev, led->cdev.name); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to initialize pwm\n"); return rc; } /* Initialize led for use in auto trickle charging mode */ rc = qpnp_led_masked_write(led, RGB_LED_ATC_CTL(led->base), led->rgb_cfg->enable, led->rgb_cfg->enable); return 0; } static int __devinit qpnp_mpp_init(struct qpnp_led_data *led) { int rc, val; if (led->max_current < LED_MPP_CURRENT_MIN || led->max_current > LED_MPP_CURRENT_MAX) { dev_err(&led->spmi_dev->dev, "max current for mpp is not valid\n"); return -EINVAL; } val = (led->mpp_cfg->current_setting / LED_MPP_CURRENT_PER_SETTING) - 1; if (val < 0) val = 0; rc = qpnp_led_masked_write(led, LED_MPP_VIN_CTRL(led->base), LED_MPP_VIN_MASK, led->mpp_cfg->vin_ctrl); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write led vin control reg\n"); return rc; } rc = qpnp_led_masked_write(led, LED_MPP_SINK_CTRL(led->base), LED_MPP_SINK_MASK, val); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to write sink control reg\n"); return rc; } if (led->mpp_cfg->pwm_mode != MANUAL_MODE) { rc = qpnp_pwm_init(led->mpp_cfg->pwm_cfg, led->spmi_dev, led->cdev.name); if (rc) { dev_err(&led->spmi_dev->dev, "Failed to initialize pwm\n"); return rc; } } return 0; } static int __devinit qpnp_led_initialize(struct qpnp_led_data *led) { int rc = 0; switch (led->id) { case QPNP_ID_WLED: rc = qpnp_wled_init(led); if (rc) dev_err(&led->spmi_dev->dev, "WLED initialize failed(%d)\n", rc); break; case QPNP_ID_FLASH1_LED0: case QPNP_ID_FLASH1_LED1: rc = qpnp_flash_init(led); if (rc) dev_err(&led->spmi_dev->dev, "FLASH initialize failed(%d)\n", rc); break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: rc = qpnp_rgb_init(led); if (rc) dev_err(&led->spmi_dev->dev, "RGB initialize failed(%d)\n", rc); break; case QPNP_ID_LED_MPP: rc = qpnp_mpp_init(led); if (rc) dev_err(&led->spmi_dev->dev, "MPP initialize failed(%d)\n", rc); break; case QPNP_ID_KPDBL: rc = qpnp_kpdbl_init(led); if (rc) dev_err(&led->spmi_dev->dev, "KPDBL initialize failed(%d)\n", rc); break; default: dev_err(&led->spmi_dev->dev, "Invalid LED(%d)\n", led->id); return -EINVAL; } return rc; } static int __devinit qpnp_get_common_configs(struct qpnp_led_data *led, struct device_node *node) { int rc; u32 val; const char *temp_string; led->cdev.default_trigger = LED_TRIGGER_DEFAULT; rc = of_property_read_string(node, "linux,default-trigger", &temp_string); if (!rc) led->cdev.default_trigger = temp_string; else if (rc != -EINVAL) return rc; led->default_on = false; rc = of_property_read_string(node, "qcom,default-state", &temp_string); if (!rc) { if (strncmp(temp_string, "on", sizeof("on")) == 0) led->default_on = true; } else if (rc != -EINVAL) return rc; led->turn_off_delay_ms = 0; rc = of_property_read_u32(node, "qcom,turn-off-delay-ms", &val); if (!rc) led->turn_off_delay_ms = val; else if (rc != -EINVAL) return rc; return 0; } /* * Handlers for alternative sources of platform_data */ static int __devinit qpnp_get_config_wled(struct qpnp_led_data *led, struct device_node *node) { u32 val; int rc; led->wled_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct wled_config_data), GFP_KERNEL); if (!led->wled_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } rc = spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, PMIC_VERSION_REG, &led->wled_cfg->pmic_version, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to read pmic ver, rc(%d)\n", rc); } led->wled_cfg->num_strings = WLED_DEFAULT_STRINGS; rc = of_property_read_u32(node, "qcom,num-strings", &val); if (!rc) led->wled_cfg->num_strings = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->ovp_val = WLED_DEFAULT_OVP_VAL; rc = of_property_read_u32(node, "qcom,ovp-val", &val); if (!rc) led->wled_cfg->ovp_val = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->boost_curr_lim = WLED_BOOST_LIM_DEFAULT; rc = of_property_read_u32(node, "qcom,boost-curr-lim", &val); if (!rc) led->wled_cfg->boost_curr_lim = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->cp_select = WLED_CP_SEL_DEFAULT; rc = of_property_read_u32(node, "qcom,cp-sel", &val); if (!rc) led->wled_cfg->cp_select = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->ctrl_delay_us = WLED_CTRL_DLY_DEFAULT; rc = of_property_read_u32(node, "qcom,ctrl-delay-us", &val); if (!rc) led->wled_cfg->ctrl_delay_us = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->op_fdbck = WLED_OP_FDBCK_DEFAULT; rc = of_property_read_u32(node, "qcom,op-fdbck", &val); if (!rc) led->wled_cfg->op_fdbck = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->switch_freq = WLED_SWITCH_FREQ_DEFAULT; rc = of_property_read_u32(node, "qcom,switch-freq", &val); if (!rc) led->wled_cfg->switch_freq = (u8) val; else if (rc != -EINVAL) return rc; led->wled_cfg->dig_mod_gen_en = of_property_read_bool(node, "qcom,dig-mod-gen-en"); led->wled_cfg->cs_out_en = of_property_read_bool(node, "qcom,cs-out-en"); led->wled_cfg->cabc_en = of_property_read_bool(node, "qcom,cabc-en"); return 0; } static int __devinit qpnp_get_config_flash(struct qpnp_led_data *led, struct device_node *node, bool *reg_set) { int rc; u32 val; led->flash_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct flash_config_data), GFP_KERNEL); if (!led->flash_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } rc = spmi_ext_register_readl(led->spmi_dev->ctrl, led->spmi_dev->sid, FLASH_PERIPHERAL_SUBTYPE(led->base), &led->flash_cfg->peripheral_subtype, 1); if (rc) { dev_err(&led->spmi_dev->dev, "Unable to read from addr=%x, rc(%d)\n", FLASH_PERIPHERAL_SUBTYPE(led->base), rc); } led->flash_cfg->torch_enable = of_property_read_bool(node, "qcom,torch-enable"); if (led->id == QPNP_ID_FLASH1_LED0) { led->flash_cfg->enable_module = FLASH_ENABLE_LED_0; led->flash_cfg->current_addr = FLASH_LED_0_CURR(led->base); led->flash_cfg->trigger_flash = FLASH_LED_0_OUTPUT; if (!*reg_set) { led->flash_cfg->flash_boost_reg = regulator_get(&led->spmi_dev->dev, "flash-boost"); if (IS_ERR(led->flash_cfg->flash_boost_reg)) { rc = PTR_ERR(led->flash_cfg->flash_boost_reg); dev_err(&led->spmi_dev->dev, "Regulator get failed(%d)\n", rc); goto error_get_flash_reg; } led->flash_cfg->flash_reg_get = true; *reg_set = true; } else led->flash_cfg->flash_reg_get = false; if (led->flash_cfg->torch_enable) { led->flash_cfg->second_addr = FLASH_LED_1_CURR(led->base); } } else if (led->id == QPNP_ID_FLASH1_LED1) { led->flash_cfg->enable_module = FLASH_ENABLE_LED_1; led->flash_cfg->current_addr = FLASH_LED_1_CURR(led->base); led->flash_cfg->trigger_flash = FLASH_LED_1_OUTPUT; if (!*reg_set) { led->flash_cfg->flash_boost_reg = regulator_get(&led->spmi_dev->dev, "flash-boost"); if (IS_ERR(led->flash_cfg->flash_boost_reg)) { rc = PTR_ERR(led->flash_cfg->flash_boost_reg); dev_err(&led->spmi_dev->dev, "Regulator get failed(%d)\n", rc); goto error_get_flash_reg; } led->flash_cfg->flash_reg_get = true; *reg_set = true; } else led->flash_cfg->flash_reg_get = false; if (led->flash_cfg->torch_enable) { led->flash_cfg->second_addr = FLASH_LED_0_CURR(led->base); } } else { dev_err(&led->spmi_dev->dev, "Unknown flash LED name given\n"); return -EINVAL; } if (led->flash_cfg->torch_enable) { if (of_find_property(of_get_parent(node), "torch-boost-supply", NULL)) { led->flash_cfg->torch_boost_reg = regulator_get(&led->spmi_dev->dev, "torch-boost"); if (IS_ERR(led->flash_cfg->torch_boost_reg)) { rc = PTR_ERR(led->flash_cfg->torch_boost_reg); dev_err(&led->spmi_dev->dev, "Torch regulator get failed(%d)\n", rc); goto error_get_torch_reg; } led->flash_cfg->enable_module = FLASH_ENABLE_MODULE; } else led->flash_cfg->enable_module = FLASH_ENABLE_ALL; led->flash_cfg->trigger_flash = FLASH_STROBE_SW; } rc = of_property_read_u32(node, "qcom,current", &val); if (!rc) { if (led->flash_cfg->torch_enable) { led->flash_cfg->current_prgm = (val * TORCH_MAX_LEVEL / led->max_current); return 0; } else led->flash_cfg->current_prgm = (val * FLASH_MAX_LEVEL / led->max_current); } else if (led->flash_cfg->torch_enable) goto error_get_torch_reg; else goto error_get_flash_reg; rc = of_property_read_u32(node, "qcom,headroom", &val); if (!rc) led->flash_cfg->headroom = (u8) val; else if (rc == -EINVAL) led->flash_cfg->headroom = HEADROOM_500mV; else goto error_get_flash_reg; rc = of_property_read_u32(node, "qcom,duration", &val); if (!rc) led->flash_cfg->duration = (u8)((val - 10) / 10); else if (rc == -EINVAL) led->flash_cfg->duration = FLASH_DURATION_200ms; else goto error_get_flash_reg; rc = of_property_read_u32(node, "qcom,clamp-curr", &val); if (!rc) led->flash_cfg->clamp_curr = (val * FLASH_MAX_LEVEL / led->max_current); else if (rc == -EINVAL) led->flash_cfg->clamp_curr = FLASH_CLAMP_200mA; else goto error_get_flash_reg; rc = of_property_read_u32(node, "qcom,startup-dly", &val); if (!rc) led->flash_cfg->startup_dly = (u8) val; else if (rc == -EINVAL) led->flash_cfg->startup_dly = DELAY_128us; else goto error_get_flash_reg; led->flash_cfg->safety_timer = of_property_read_bool(node, "qcom,safety-timer"); return 0; error_get_torch_reg: regulator_put(led->flash_cfg->torch_boost_reg); error_get_flash_reg: regulator_put(led->flash_cfg->flash_boost_reg); return rc; } static int __devinit qpnp_get_config_pwm(struct pwm_config_data *pwm_cfg, struct spmi_device *spmi_dev, struct device_node *node) { struct property *prop; int rc, i; u32 val; u8 *temp_cfg; rc = of_property_read_u32(node, "qcom,pwm-channel", &val); if (!rc) pwm_cfg->pwm_channel = val; else return rc; if (pwm_cfg->mode == PWM_MODE) { rc = of_property_read_u32(node, "qcom,pwm-us", &val); if (!rc) pwm_cfg->pwm_period_us = val; else return rc; } pwm_cfg->use_blink = of_property_read_bool(node, "qcom,use-blink"); if (pwm_cfg->mode == LPG_MODE || pwm_cfg->use_blink) { pwm_cfg->duty_cycles = devm_kzalloc(&spmi_dev->dev, sizeof(struct pwm_duty_cycles), GFP_KERNEL); if (!pwm_cfg->duty_cycles) { dev_err(&spmi_dev->dev, "Unable to allocate memory\n"); rc = -ENOMEM; goto bad_lpg_params; } prop = of_find_property(node, "qcom,duty-pcts", &pwm_cfg->duty_cycles->num_duty_pcts); if (!prop) { dev_err(&spmi_dev->dev, "Looking up property " \ "node qcom,duty-pcts failed\n"); rc = -ENODEV; goto bad_lpg_params; } else if (!pwm_cfg->duty_cycles->num_duty_pcts) { dev_err(&spmi_dev->dev, "Invalid length of " \ "duty pcts\n"); rc = -EINVAL; goto bad_lpg_params; } pwm_cfg->duty_cycles->duty_pcts = devm_kzalloc(&spmi_dev->dev, sizeof(int) * PWM_LUT_MAX_SIZE, GFP_KERNEL); if (!pwm_cfg->duty_cycles->duty_pcts) { dev_err(&spmi_dev->dev, "Unable to allocate memory\n"); rc = -ENOMEM; goto bad_lpg_params; } pwm_cfg->old_duty_pcts = devm_kzalloc(&spmi_dev->dev, sizeof(int) * PWM_LUT_MAX_SIZE, GFP_KERNEL); if (!pwm_cfg->old_duty_pcts) { dev_err(&spmi_dev->dev, "Unable to allocate memory\n"); rc = -ENOMEM; goto bad_lpg_params; } temp_cfg = devm_kzalloc(&spmi_dev->dev, pwm_cfg->duty_cycles->num_duty_pcts * sizeof(u8), GFP_KERNEL); if (!temp_cfg) { dev_err(&spmi_dev->dev, "Failed to allocate " \ "memory for duty pcts\n"); rc = -ENOMEM; goto bad_lpg_params; } memcpy(temp_cfg, prop->value, pwm_cfg->duty_cycles->num_duty_pcts); for (i = 0; i < pwm_cfg->duty_cycles->num_duty_pcts; i++) pwm_cfg->duty_cycles->duty_pcts[i] = (int) temp_cfg[i]; rc = of_property_read_u32(node, "qcom,start-idx", &val); if (!rc) { pwm_cfg->lut_params.start_idx = val; pwm_cfg->duty_cycles->start_idx = val; } else goto bad_lpg_params; pwm_cfg->lut_params.lut_pause_hi = 0; rc = of_property_read_u32(node, "qcom,pause-hi", &val); if (!rc) pwm_cfg->lut_params.lut_pause_hi = val; else if (rc != -EINVAL) goto bad_lpg_params; pwm_cfg->lut_params.lut_pause_lo = 0; rc = of_property_read_u32(node, "qcom,pause-lo", &val); if (!rc) pwm_cfg->lut_params.lut_pause_lo = val; else if (rc != -EINVAL) goto bad_lpg_params; pwm_cfg->lut_params.ramp_step_ms = QPNP_LUT_RAMP_STEP_DEFAULT; rc = of_property_read_u32(node, "qcom,ramp-step-ms", &val); if (!rc) pwm_cfg->lut_params.ramp_step_ms = val; else if (rc != -EINVAL) goto bad_lpg_params; pwm_cfg->lut_params.flags = QPNP_LED_PWM_FLAGS; rc = of_property_read_u32(node, "qcom,lut-flags", &val); if (!rc) pwm_cfg->lut_params.flags = (u8) val; else if (rc != -EINVAL) goto bad_lpg_params; pwm_cfg->lut_params.idx_len = pwm_cfg->duty_cycles->num_duty_pcts; } return 0; bad_lpg_params: pwm_cfg->use_blink = false; if (pwm_cfg->mode == PWM_MODE) { dev_err(&spmi_dev->dev, "LPG parameters not set for" \ " blink mode, defaulting to PWM mode\n"); return 0; } return rc; }; static int qpnp_led_get_mode(const char *mode) { if (strncmp(mode, "manual", strlen(mode)) == 0) return MANUAL_MODE; else if (strncmp(mode, "pwm", strlen(mode)) == 0) return PWM_MODE; else if (strncmp(mode, "lpg", strlen(mode)) == 0) return LPG_MODE; else return -EINVAL; }; static int __devinit qpnp_get_config_kpdbl(struct qpnp_led_data *led, struct device_node *node) { int rc; u32 val; u8 led_mode; const char *mode; led->kpdbl_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct kpdbl_config_data), GFP_KERNEL); if (!led->kpdbl_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } rc = of_property_read_string(node, "qcom,mode", &mode); if (!rc) { led_mode = qpnp_led_get_mode(mode); if ((led_mode == MANUAL_MODE) || (led_mode == -EINVAL)) { dev_err(&led->spmi_dev->dev, "Selected mode not " \ "supported for kpdbl.\n"); return -EINVAL; } led->kpdbl_cfg->pwm_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct pwm_config_data), GFP_KERNEL); if (!led->kpdbl_cfg->pwm_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } led->kpdbl_cfg->pwm_cfg->mode = led_mode; led->kpdbl_cfg->pwm_cfg->default_mode = led_mode; } else return rc; rc = qpnp_get_config_pwm(led->kpdbl_cfg->pwm_cfg, led->spmi_dev, node); if (rc < 0) return rc; rc = of_property_read_u32(node, "qcom,row-id", &val); if (!rc) led->kpdbl_cfg->row_id = val; else return rc; led->kpdbl_cfg->row_src_vbst = of_property_read_bool(node, "qcom,row-src-vbst"); led->kpdbl_cfg->row_src_en = of_property_read_bool(node, "qcom,row-src-en"); led->kpdbl_cfg->always_on = of_property_read_bool(node, "qcom,always-on"); return 0; } static int __devinit qpnp_get_config_rgb(struct qpnp_led_data *led, struct device_node *node) { int rc; u8 led_mode; const char *mode; led->rgb_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct rgb_config_data), GFP_KERNEL); if (!led->rgb_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } if (led->id == QPNP_ID_RGB_RED) led->rgb_cfg->enable = RGB_LED_ENABLE_RED; else if (led->id == QPNP_ID_RGB_GREEN) led->rgb_cfg->enable = RGB_LED_ENABLE_GREEN; else if (led->id == QPNP_ID_RGB_BLUE) led->rgb_cfg->enable = RGB_LED_ENABLE_BLUE; else return -EINVAL; rc = of_property_read_string(node, "qcom,mode", &mode); if (!rc) { led_mode = qpnp_led_get_mode(mode); if ((led_mode == MANUAL_MODE) || (led_mode == -EINVAL)) { dev_err(&led->spmi_dev->dev, "Selected mode not " \ "supported for rgb.\n"); return -EINVAL; } led->rgb_cfg->pwm_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct pwm_config_data), GFP_KERNEL); if (!led->rgb_cfg->pwm_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } led->rgb_cfg->pwm_cfg->mode = led_mode; led->rgb_cfg->pwm_cfg->default_mode = led_mode; } else return rc; rc = qpnp_get_config_pwm(led->rgb_cfg->pwm_cfg, led->spmi_dev, node); if (rc < 0) return rc; return 0; } static int __devinit qpnp_get_config_mpp(struct qpnp_led_data *led, struct device_node *node) { int rc; u32 val; u8 led_mode; const char *mode; led->mpp_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct mpp_config_data), GFP_KERNEL); if (!led->mpp_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } led->mpp_cfg->current_setting = LED_MPP_CURRENT_MIN; rc = of_property_read_u32(node, "qcom,current-setting", &val); if (!rc) { if (val < LED_MPP_CURRENT_MIN) led->mpp_cfg->current_setting = LED_MPP_CURRENT_MIN; else if (val > LED_MPP_CURRENT_MAX) led->mpp_cfg->current_setting = LED_MPP_CURRENT_MAX; else led->mpp_cfg->current_setting = (u8) val; } else if (rc != -EINVAL) return rc; led->mpp_cfg->source_sel = LED_MPP_SOURCE_SEL_DEFAULT; rc = of_property_read_u32(node, "qcom,source-sel", &val); if (!rc) led->mpp_cfg->source_sel = (u8) val; else if (rc != -EINVAL) return rc; led->mpp_cfg->mode_ctrl = LED_MPP_MODE_SINK; rc = of_property_read_u32(node, "qcom,mode-ctrl", &val); if (!rc) led->mpp_cfg->mode_ctrl = (u8) val; else if (rc != -EINVAL) return rc; led->mpp_cfg->vin_ctrl = LED_MPP_VIN_CTRL_DEFAULT; rc = of_property_read_u32(node, "qcom,vin-ctrl", &val); if (!rc) led->mpp_cfg->vin_ctrl = (u8) val; else if (rc != -EINVAL) return rc; led->mpp_cfg->min_brightness = 0; rc = of_property_read_u32(node, "qcom,min-brightness", &val); if (!rc) led->mpp_cfg->min_brightness = (u8) val; else if (rc != -EINVAL) return rc; rc = of_property_read_string(node, "qcom,mode", &mode); if (!rc) { led_mode = qpnp_led_get_mode(mode); led->mpp_cfg->pwm_mode = led_mode; if (led_mode == MANUAL_MODE) return MANUAL_MODE; else if (led_mode == -EINVAL) { dev_err(&led->spmi_dev->dev, "Selected mode not " \ "supported for mpp.\n"); return -EINVAL; } led->mpp_cfg->pwm_cfg = devm_kzalloc(&led->spmi_dev->dev, sizeof(struct pwm_config_data), GFP_KERNEL); if (!led->mpp_cfg->pwm_cfg) { dev_err(&led->spmi_dev->dev, "Unable to allocate memory\n"); return -ENOMEM; } led->mpp_cfg->pwm_cfg->mode = led_mode; led->mpp_cfg->pwm_cfg->default_mode = led_mode; } else return rc; rc = qpnp_get_config_pwm(led->mpp_cfg->pwm_cfg, led->spmi_dev, node); if (rc < 0) return rc; return 0; } static int __devinit qpnp_leds_probe(struct spmi_device *spmi) { struct qpnp_led_data *led, *led_array; struct resource *led_resource; struct device_node *node, *temp; int rc, i, num_leds = 0, parsed_leds = 0; const char *led_label; bool regulator_probe = false; node = spmi->dev.of_node; if (node == NULL) return -ENODEV; temp = NULL; while ((temp = of_get_next_child(node, temp))) num_leds++; if (!num_leds) return -ECHILD; led_array = devm_kzalloc(&spmi->dev, (sizeof(struct qpnp_led_data) * num_leds), GFP_KERNEL); if (!led_array) { dev_err(&spmi->dev, "Unable to allocate memory\n"); return -ENOMEM; } for_each_child_of_node(node, temp) { led = &led_array[parsed_leds]; led->num_leds = num_leds; led->spmi_dev = spmi; led_resource = spmi_get_resource(spmi, NULL, IORESOURCE_MEM, 0); if (!led_resource) { dev_err(&spmi->dev, "Unable to get LED base address\n"); rc = -ENXIO; goto fail_id_check; } led->base = led_resource->start; rc = of_property_read_string(temp, "label", &led_label); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Failure reading label, rc = %d\n", rc); goto fail_id_check; } rc = of_property_read_string(temp, "linux,name", &led->cdev.name); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Failure reading led name, rc = %d\n", rc); goto fail_id_check; } rc = of_property_read_u32(temp, "qcom,max-current", &led->max_current); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Failure reading max_current, rc = %d\n", rc); goto fail_id_check; } rc = of_property_read_u32(temp, "qcom,id", &led->id); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Failure reading led id, rc = %d\n", rc); goto fail_id_check; } rc = qpnp_get_common_configs(led, temp); if (rc) { dev_err(&led->spmi_dev->dev, "Failure reading common led configuration," \ " rc = %d\n", rc); goto fail_id_check; } led->cdev.brightness_set = qpnp_led_set; led->cdev.brightness_get = qpnp_led_get; if (strncmp(led_label, "wled", sizeof("wled")) == 0) { rc = qpnp_get_config_wled(led, temp); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Unable to read wled config data\n"); goto fail_id_check; } } else if (strncmp(led_label, "flash", sizeof("flash")) == 0) { if (!of_find_property(node, "flash-boost-supply", NULL)) regulator_probe = true; rc = qpnp_get_config_flash(led, temp, &regulator_probe); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Unable to read flash config data\n"); goto fail_id_check; } } else if (strncmp(led_label, "rgb", sizeof("rgb")) == 0) { rc = qpnp_get_config_rgb(led, temp); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Unable to read rgb config data\n"); goto fail_id_check; } } else if (strncmp(led_label, "mpp", sizeof("mpp")) == 0) { rc = qpnp_get_config_mpp(led, temp); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Unable to read mpp config data\n"); goto fail_id_check; } } else if (strncmp(led_label, "kpdbl", sizeof("kpdbl")) == 0) { num_kpbl_leds_on = 0; rc = qpnp_get_config_kpdbl(led, temp); if (rc < 0) { dev_err(&led->spmi_dev->dev, "Unable to read kpdbl config data\n"); goto fail_id_check; } } else { dev_err(&led->spmi_dev->dev, "No LED matching label\n"); rc = -EINVAL; goto fail_id_check; } mutex_init(&led->lock); INIT_WORK(&led->work, qpnp_led_work); rc = qpnp_led_initialize(led); if (rc < 0) goto fail_id_check; rc = qpnp_led_set_max_brightness(led); if (rc < 0) goto fail_id_check; rc = led_classdev_register(&spmi->dev, &led->cdev); if (rc) { dev_err(&spmi->dev, "unable to register led %d,rc=%d\n", led->id, rc); goto fail_id_check; } if (led->id == QPNP_ID_FLASH1_LED0 || led->id == QPNP_ID_FLASH1_LED1) { rc = sysfs_create_group(&led->cdev.dev->kobj, &led_attr_group); if (rc) goto fail_id_check; } if (led->id == QPNP_ID_LED_MPP) { if (!led->mpp_cfg->pwm_cfg) break; if (led->mpp_cfg->pwm_cfg->mode == PWM_MODE) { rc = sysfs_create_group(&led->cdev.dev->kobj, &pwm_attr_group); if (rc) goto fail_id_check; } if (led->mpp_cfg->pwm_cfg->use_blink) { rc = sysfs_create_group(&led->cdev.dev->kobj, &blink_attr_group); if (rc) goto fail_id_check; rc = sysfs_create_group(&led->cdev.dev->kobj, &lpg_attr_group); if (rc) goto fail_id_check; } else if (led->mpp_cfg->pwm_cfg->mode == LPG_MODE) { rc = sysfs_create_group(&led->cdev.dev->kobj, &lpg_attr_group); if (rc) goto fail_id_check; } } else if ((led->id == QPNP_ID_RGB_RED) || (led->id == QPNP_ID_RGB_GREEN) || (led->id == QPNP_ID_RGB_BLUE)) { if (led->rgb_cfg->pwm_cfg->mode == PWM_MODE) { rc = sysfs_create_group(&led->cdev.dev->kobj, &pwm_attr_group); if (rc) goto fail_id_check; } if (led->rgb_cfg->pwm_cfg->use_blink) { rc = sysfs_create_group(&led->cdev.dev->kobj, &blink_attr_group); if (rc) goto fail_id_check; rc = sysfs_create_group(&led->cdev.dev->kobj, &lpg_attr_group); if (rc) goto fail_id_check; } else if (led->rgb_cfg->pwm_cfg->mode == LPG_MODE) { rc = sysfs_create_group(&led->cdev.dev->kobj, &lpg_attr_group); if (rc) goto fail_id_check; } } /* configure default state */ if (led->default_on) { led->cdev.brightness = led->cdev.max_brightness; __qpnp_led_work(led, led->cdev.brightness); if (led->turn_off_delay_ms > 0) qpnp_led_turn_off(led); } else led->cdev.brightness = LED_OFF; parsed_leds++; } dev_set_drvdata(&spmi->dev, led_array); return 0; fail_id_check: for (i = 0; i < parsed_leds; i++) { mutex_destroy(&led_array[i].lock); led_classdev_unregister(&led_array[i].cdev); } return rc; } static int __devexit qpnp_leds_remove(struct spmi_device *spmi) { struct qpnp_led_data *led_array = dev_get_drvdata(&spmi->dev); int i, parsed_leds = led_array->num_leds; for (i = 0; i < parsed_leds; i++) { cancel_work_sync(&led_array[i].work); mutex_destroy(&led_array[i].lock); led_classdev_unregister(&led_array[i].cdev); switch (led_array[i].id) { case QPNP_ID_WLED: break; case QPNP_ID_FLASH1_LED0: case QPNP_ID_FLASH1_LED1: if (led_array[i].flash_cfg->flash_reg_get) regulator_put(led_array[i].flash_cfg-> \ flash_boost_reg); if (led_array[i].flash_cfg->torch_enable) regulator_put(led_array[i].flash_cfg->\ torch_boost_reg); sysfs_remove_group(&led_array[i].cdev.dev->kobj, &led_attr_group); break; case QPNP_ID_RGB_RED: case QPNP_ID_RGB_GREEN: case QPNP_ID_RGB_BLUE: if (led_array[i].rgb_cfg->pwm_cfg->mode == PWM_MODE) sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &pwm_attr_group); if (led_array[i].rgb_cfg->pwm_cfg->use_blink) { sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &blink_attr_group); sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &lpg_attr_group); } else if (led_array[i].rgb_cfg->pwm_cfg->mode\ == LPG_MODE) sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &lpg_attr_group); break; case QPNP_ID_LED_MPP: if (!led_array[i].mpp_cfg->pwm_cfg) break; if (led_array[i].mpp_cfg->pwm_cfg->mode == PWM_MODE) sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &pwm_attr_group); if (led_array[i].mpp_cfg->pwm_cfg->use_blink) { sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &blink_attr_group); sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &lpg_attr_group); } else if (led_array[i].mpp_cfg->pwm_cfg->mode\ == LPG_MODE) sysfs_remove_group(&led_array[i].cdev.dev->\ kobj, &lpg_attr_group); break; default: dev_err(&led_array[i].spmi_dev->dev, "Invalid LED(%d)\n", led_array[i].id); return -EINVAL; } } return 0; } #ifdef CONFIG_OF static struct of_device_id spmi_match_table[] = { { .compatible = "qcom,leds-qpnp",}, { }, }; #else #define spmi_match_table NULL #endif static struct spmi_driver qpnp_leds_driver = { .driver = { .name = "qcom,leds-qpnp", .of_match_table = spmi_match_table, }, .probe = qpnp_leds_probe, .remove = __devexit_p(qpnp_leds_remove), }; static int __init qpnp_led_init(void) { return spmi_driver_register(&qpnp_leds_driver); } module_init(qpnp_led_init); static void __exit qpnp_led_exit(void) { spmi_driver_unregister(&qpnp_leds_driver); } module_exit(qpnp_led_exit); MODULE_DESCRIPTION("QPNP LEDs driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("leds:leds-qpnp");
zeroblade1984/Xiaomi-MSM8226
drivers/leds/leds-qpnp.c
C
gpl-2.0
91,994
<?php // NOTATIONS: http://www.cob.sjsu.edu/johnson_f/notation.htm abstract class QConvertNotationBase { public static function PrefixFromType($strType) { switch ($strType) { case QType::ArrayType: return "obj"; case QType::Boolean: return "bln"; case QType::DateTime: return "dtt"; case QType::Float: return "flt"; case QType::Integer: return "int"; case QType::Object: return "obj"; case QType::String: return "str"; } } public static function WordsFromUnderscore($strName) { $strToReturn = trim(str_replace('_', ' ', $strName)); if (strtolower($strToReturn) == $strToReturn) return ucwords($strToReturn); return $strToReturn; } public static function CamelCaseFromUnderscore($strName) { $strToReturn = ''; // If entire underscore string is all uppercase, force to all lowercase // (mixed case and all lowercase can remain as is) if ($strName == strtoupper($strName)) $strName = strtolower($strName); while (($intPosition = strpos($strName, "_")) !== false) { // Use 'ucfirst' to create camelcasing $strName = ucfirst($strName); if ($intPosition == 0) { $strName = substr($strName, 1); } else { $strToReturn .= substr($strName, 0, $intPosition); $strName = substr($strName, $intPosition + 1); } } $strToReturn .= ucfirst($strName); return $strToReturn; } public static function WordsFromCamelCase($strName) { if (strlen($strName) == 0) return ''; $strToReturn = QString::FirstCharacter($strName); for ($intIndex = 1; $intIndex < strlen($strName); $intIndex++) { // Get the current character we're examining $strChar = substr($strName, $intIndex, 1); // Get the character previous to this $strPrevChar = substr($strName, $intIndex - 1, 1); // If an upper case letter if ((ord($strChar) >= ord('A')) && (ord($strChar) <= ord('Z'))) // Add a Space $strToReturn .= ' ' . $strChar; // If a digit, and the previous character is NOT a digit else if ((ord($strChar) >= ord('0')) && (ord($strChar) <= ord('9')) && ((ord($strPrevChar) < ord('0')) || (ord($strPrevChar) > ord('9')))) // Add a space $strToReturn .= ' ' . $strChar; // If a letter, and the previous character is a digit else if ((ord(strtolower($strChar)) >= ord('a')) && (ord(strtolower($strChar)) <= ord('z')) && (ord($strPrevChar) >= ord('0')) && (ord($strPrevChar) <= ord('9'))) // Add a space $strToReturn .= ' ' . $strChar; // Otherwise else // Don't add a space $strToReturn .= $strChar; } return $strToReturn; } public static function UnderscoreFromCamelCase($strName) { if (strlen($strName) == 0) return ''; $strToReturn = QString::FirstCharacter($strName); for ($intIndex = 1; $intIndex < strlen($strName); $intIndex++) { $strChar = substr($strName, $intIndex, 1); if (strtoupper($strChar) == $strChar) $strToReturn .= '_' . $strChar; else $strToReturn .= $strChar; } return strtolower($strToReturn); } public static function JavaCaseFromUnderscore($strName) { $strToReturn = QConvertNotation::CamelCaseFromUnderscore($strName); return strtolower(substr($strToReturn, 0, 1)) . substr($strToReturn, 1); } } ?>
dsuess/tracmor
includes/qcodo/_core/codegen/QConvertNotationBase.class.php
PHP
gpl-2.0
3,376
/***************************************************************************** * smb.c: SMB input module ***************************************************************************** * Copyright (C) 2001-2009 the VideoLAN team * $Id: c9b931477a697a5b694e9036c56f73ab34ad87a1 $ * * Authors: Gildas Bazin <gbazin@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_fs.h> #include <vlc_plugin.h> #include <vlc_access.h> #ifdef WIN32 # ifdef HAVE_FCNTL_H # include <fcntl.h> # endif # ifdef HAVE_SYS_STAT_H # include <sys/stat.h> # endif # include <io.h> # define smbc_open(a,b,c) vlc_open(a,b,c) # define smbc_fstat(a,b) _fstati64(a,b) # define smbc_read read # define smbc_lseek _lseeki64 # define smbc_close close #else # include <libsmbclient.h> #endif #include <errno.h> /***************************************************************************** * Module descriptor *****************************************************************************/ static int Open ( vlc_object_t * ); static void Close( vlc_object_t * ); #define USER_TEXT N_("SMB user name") #define USER_LONGTEXT N_("User name that will " \ "be used for the connection.") #define PASS_TEXT N_("SMB password") #define PASS_LONGTEXT N_("Password that will be " \ "used for the connection.") #define DOMAIN_TEXT N_("SMB domain") #define DOMAIN_LONGTEXT N_("Domain/Workgroup that " \ "will be used for the connection.") #define SMB_HELP N_("Samba (Windows network shares) input") vlc_module_begin () set_shortname( "SMB" ) set_description( N_("SMB input") ) set_help(SMB_HELP) set_capability( "access", 0 ) set_category( CAT_INPUT ) set_subcategory( SUBCAT_INPUT_ACCESS ) add_string( "smb-user", NULL, USER_TEXT, USER_LONGTEXT, false ) add_password( "smb-pwd", NULL, PASS_TEXT, PASS_LONGTEXT, false ) add_string( "smb-domain", NULL, DOMAIN_TEXT, DOMAIN_LONGTEXT, false ) add_shortcut( "smb" ) set_callbacks( Open, Close ) vlc_module_end () /***************************************************************************** * Local prototypes *****************************************************************************/ static ssize_t Read( access_t *, uint8_t *, size_t ); static int Seek( access_t *, uint64_t ); static int Control( access_t *, int, va_list ); struct access_sys_t { int i_smb; }; #ifdef WIN32 static void Win32AddConnection( access_t *, char *, char *, char *, char * ); #else static void smb_auth( const char *srv, const char *shr, char *wg, int wglen, char *un, int unlen, char *pw, int pwlen ) { VLC_UNUSED(srv); VLC_UNUSED(shr); VLC_UNUSED(wg); VLC_UNUSED(wglen); VLC_UNUSED(un); VLC_UNUSED(unlen); VLC_UNUSED(pw); VLC_UNUSED(pwlen); //wglen = unlen = pwlen = 0; } #endif /**************************************************************************** * Open: connect to smb server and ask for file ****************************************************************************/ static int Open( vlc_object_t *p_this ) { access_t *p_access = (access_t*)p_this; access_sys_t *p_sys; struct stat filestat; char *psz_location, *psz_uri; char *psz_user = NULL, *psz_pwd = NULL, *psz_domain = NULL; int i_ret; int i_smb; /* Parse input URI * [[[domain;]user[:password@]]server[/share[/path[/file]]]] */ psz_location = strchr( p_access->psz_location, '/' ); if( !psz_location ) { msg_Err( p_access, "invalid SMB URI: smb://%s", psz_location ); return VLC_EGENERIC; } else { char *psz_tmp = strdup( p_access->psz_location ); char *psz_parser; psz_tmp[ psz_location - p_access->psz_location ] = 0; psz_location = p_access->psz_location; psz_parser = strchr( psz_tmp, '@' ); if( psz_parser ) { /* User info is there */ *psz_parser = 0; psz_location = p_access->psz_location + (psz_parser - psz_tmp) + 1; psz_parser = strchr( psz_tmp, ':' ); if( psz_parser ) { /* Password found */ psz_pwd = strdup( psz_parser+1 ); *psz_parser = 0; } psz_parser = strchr( psz_tmp, ';' ); if( psz_parser ) { /* Domain found */ *psz_parser = 0; psz_parser++; psz_domain = strdup( psz_tmp ); } else psz_parser = psz_tmp; psz_user = strdup( psz_parser ); } free( psz_tmp ); } /* Build an SMB URI * smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]] */ if( !psz_user ) psz_user = var_InheritString( p_access, "smb-user" ); if( psz_user && !*psz_user ) { free( psz_user ); psz_user = NULL; } if( !psz_pwd ) psz_pwd = var_InheritString( p_access, "smb-pwd" ); if( psz_pwd && !*psz_pwd ) { free( psz_pwd ); psz_pwd = NULL; } if( !psz_domain ) psz_domain = var_InheritString( p_access, "smb-domain" ); if( psz_domain && !*psz_domain ) { free( psz_domain ); psz_domain = NULL; } #ifdef WIN32 if( psz_user ) Win32AddConnection( p_access, psz_location, psz_user, psz_pwd, psz_domain); i_ret = asprintf( &psz_uri, "//%s", psz_location ); #else if( psz_user ) i_ret = asprintf( &psz_uri, "smb://%s%s%s%s%s@%s", psz_domain ? psz_domain : "", psz_domain ? ";" : "", psz_user, psz_pwd ? ":" : "", psz_pwd ? psz_pwd : "", psz_location ); else i_ret = asprintf( &psz_uri, "smb://%s", psz_location ); #endif free( psz_user ); free( psz_pwd ); free( psz_domain ); if( i_ret == -1 ) return VLC_ENOMEM; #ifndef WIN32 if( smbc_init( smb_auth, 0 ) ) { free( psz_uri ); return VLC_EGENERIC; } #endif /* ** some version of glibc defines open as a macro, causing havoc ** with other macros using 'open' under the hood, such as the ** following one: */ #if defined(smbc_open) && defined(open) # undef open #endif if( (i_smb = smbc_open( psz_uri, O_RDONLY, 0 )) < 0 ) { msg_Err( p_access, "open failed for '%s' (%m)", p_access->psz_location ); free( psz_uri ); return VLC_EGENERIC; } /* Init p_access */ STANDARD_READ_ACCESS_INIT; i_ret = smbc_fstat( i_smb, &filestat ); if( i_ret ) { errno = i_ret; msg_Err( p_access, "stat failed (%m)" ); } else p_access->info.i_size = filestat.st_size; free( psz_uri ); p_sys->i_smb = i_smb; return VLC_SUCCESS; } /***************************************************************************** * Close: free unused data structures *****************************************************************************/ static void Close( vlc_object_t *p_this ) { access_t *p_access = (access_t*)p_this; access_sys_t *p_sys = p_access->p_sys; smbc_close( p_sys->i_smb ); free( p_sys ); } /***************************************************************************** * Seek: try to go at the right place *****************************************************************************/ static int Seek( access_t *p_access, uint64_t i_pos ) { access_sys_t *p_sys = p_access->p_sys; int64_t i_ret; if( i_pos >= INT64_MAX ) return VLC_EGENERIC; msg_Dbg( p_access, "seeking to %"PRId64, i_pos ); i_ret = smbc_lseek( p_sys->i_smb, i_pos, SEEK_SET ); if( i_ret == -1 ) { msg_Err( p_access, "seek failed (%m)" ); return VLC_EGENERIC; } p_access->info.b_eof = false; p_access->info.i_pos = i_ret; return VLC_SUCCESS; } /***************************************************************************** * Read: *****************************************************************************/ static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len ) { access_sys_t *p_sys = p_access->p_sys; int i_read; if( p_access->info.b_eof ) return 0; i_read = smbc_read( p_sys->i_smb, p_buffer, i_len ); if( i_read < 0 ) { msg_Err( p_access, "read failed (%m)" ); return -1; } if( i_read == 0 ) p_access->info.b_eof = true; else if( i_read > 0 ) p_access->info.i_pos += i_read; return i_read; } /***************************************************************************** * Control: *****************************************************************************/ static int Control( access_t *p_access, int i_query, va_list args ) { switch( i_query ) { case ACCESS_CAN_SEEK: case ACCESS_CAN_FASTSEEK: case ACCESS_CAN_PAUSE: case ACCESS_CAN_CONTROL_PACE: *va_arg( args, bool* ) = true; break; case ACCESS_GET_PTS_DELAY: *va_arg( args, int64_t * ) = INT64_C(1000) * var_InheritInteger( p_access, "network-caching" ); break; case ACCESS_SET_PAUSE_STATE: /* Nothing to do */ break; case ACCESS_GET_TITLE_INFO: case ACCESS_SET_TITLE: case ACCESS_SET_SEEKPOINT: case ACCESS_SET_PRIVATE_ID_STATE: case ACCESS_GET_CONTENT_TYPE: return VLC_EGENERIC; default: msg_Warn( p_access, "unimplemented query in control" ); return VLC_EGENERIC; } return VLC_SUCCESS; } #ifdef WIN32 static void Win32AddConnection( access_t *p_access, char *psz_path, char *psz_user, char *psz_pwd, char *psz_domain ) { char psz_remote[MAX_PATH], psz_server[MAX_PATH], psz_share[MAX_PATH]; NETRESOURCE net_resource; DWORD i_result; char *psz_parser; VLC_UNUSED( psz_domain ); memset( &net_resource, 0, sizeof(net_resource) ); net_resource.dwType = RESOURCETYPE_DISK; /* Find out server and share names */ strlcpy( psz_server, psz_path, sizeof( psz_server ) ); psz_share[0] = 0; psz_parser = strchr( psz_path, '/' ); if( psz_parser ) { char *psz_parser2 = strchr( ++psz_parser, '/' ); if( psz_parser2 ) strlcpy( psz_share, psz_parser, sizeof( psz_share ) ); } snprintf( psz_remote, sizeof( psz_remote ), "\\\\%s\\%s", psz_server, psz_share ); net_resource.lpRemoteName = psz_remote; i_result = WNetAddConnection2( &net_resource, psz_pwd, psz_user, 0 ); if( i_result != NO_ERROR ) { msg_Dbg( p_access, "connected to %s", psz_remote ); } else if( i_result != ERROR_ALREADY_ASSIGNED && i_result != ERROR_DEVICE_ALREADY_REMEMBERED ) { msg_Dbg( p_access, "already connected to %s", psz_remote ); } else { msg_Dbg( p_access, "failed to connect to %s", psz_remote ); } } #endif // WIN32
hustcalm/vlc-player
modules/access/smb.c
C
gpl-2.0
11,988
// Copyright (C) 2004 David Griffiths <dave@pawfal.org> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "Event.h" #ifndef SPIRALCORE_EVENT_QUEUE #define SPIRALCORE_EVENT_QUEUE static const int EVENT_QUEUE_SIZE = 256; namespace spiralcore { // no mallocs, so a bit of diy memory allocation class EventQueue { public: EventQueue(); ~EventQueue(); bool Add(const Event &e); // you should keep calling this function for the specified // time slice until it returns false bool Get(Time from, Time till, Event &e); private: struct QueueItem { QueueItem() : m_IsEmpty(true) {} bool m_IsEmpty; Event m_Event; }; QueueItem m_Queue[EVENT_QUEUE_SIZE]; }; } #endif
nebogeo/libspiralcore
include/EventQueue.h
C
gpl-2.0
1,364
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from invenio.legacy.dbquery import run_sql depends_on = ['invenio_release_1_1_0'] def info(): return "New bibsched status (schSTATUS) table" def do_upgrade(): run_sql("""CREATE TABLE IF NOT EXISTS schSTATUS ( name varchar(50), value mediumblob, PRIMARY KEY (name) ) ENGINE=MyISAM """) def estimate(): return 1
SamiHiltunen/invenio-upgrader
invenio_upgrader/upgrades/invenio_2013_06_24_new_bibsched_status_table.py
Python
gpl-2.0
1,112
/* * (C) Copyright 2000, 2001 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * SPDX-License-Identifier: GPL-2.0+ */ /* * Support for read and write access to EEPROM like memory devices. This * includes regular EEPROM as well as FRAM (ferroelectic nonvolaile RAM). * FRAM devices read and write data at bus speed. In particular, there is no * write delay. Also, there is no limit imposed on the number of bytes that can * be transferred with a single read or write. * * Use the following configuration options to ensure no unneeded performance * degradation (typical for EEPROM) is incured for FRAM memory: * * #define CONFIG_SYS_I2C_FRAM * #undef CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS * */ #include <common.h> #include <config.h> #include <command.h> #include <i2c.h> extern void eeprom_init (void); extern int eeprom_read (unsigned dev_addr, unsigned offset, uchar *buffer, unsigned cnt); extern int eeprom_write (unsigned dev_addr, unsigned offset, uchar *buffer, unsigned cnt); #if defined(CONFIG_SYS_EEPROM_WREN) extern int eeprom_write_enable (unsigned dev_addr, int state); #endif #if defined(CONFIG_SYS_EEPROM_X40430) /* Maximum number of times to poll for acknowledge after write */ #define MAX_ACKNOWLEDGE_POLLS 10 #endif /* ------------------------------------------------------------------------- */ #if defined(CONFIG_CMD_EEPROM) static int do_eeprom(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { const char *const fmt = "\nEEPROM @0x%lX %s: addr %08lx off %04lx count %ld ... "; #if defined(CONFIG_SYS_I2C_MULTI_EEPROMS) if (argc == 6) { ulong dev_addr = simple_strtoul (argv[2], NULL, 16); ulong addr = simple_strtoul (argv[3], NULL, 16); ulong off = simple_strtoul (argv[4], NULL, 16); ulong cnt = simple_strtoul (argv[5], NULL, 16); #else if (argc == 5) { ulong dev_addr = CONFIG_SYS_DEF_EEPROM_ADDR; ulong addr = simple_strtoul (argv[2], NULL, 16); ulong off = simple_strtoul (argv[3], NULL, 16); ulong cnt = simple_strtoul (argv[4], NULL, 16); #endif /* CONFIG_SYS_I2C_MULTI_EEPROMS */ # if !defined(CONFIG_SPI) || defined(CONFIG_ENV_EEPROM_IS_ON_I2C) eeprom_init (); # endif /* !CONFIG_SPI */ if (strcmp (argv[1], "read") == 0) { int rcode; printf (fmt, dev_addr, argv[1], addr, off, cnt); rcode = eeprom_read (dev_addr, off, (uchar *) addr, cnt); puts ("done\n"); return rcode; } else if (strcmp (argv[1], "write") == 0) { int rcode; printf (fmt, dev_addr, argv[1], addr, off, cnt); rcode = eeprom_write (dev_addr, off, (uchar *) addr, cnt); puts ("done\n"); return rcode; } } return CMD_RET_USAGE; } #endif /*----------------------------------------------------------------------- * * for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 2 (16-bit EEPROM address) offset is * 0x000nxxxx for EEPROM address selectors at n, offset xxxx in EEPROM. * * for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 (8-bit EEPROM page address) offset is * 0x00000nxx for EEPROM address selectors and page number at n. */ #if !defined(CONFIG_SPI) || defined(CONFIG_ENV_EEPROM_IS_ON_I2C) #if !defined(CONFIG_SYS_I2C_EEPROM_ADDR_LEN) || CONFIG_SYS_I2C_EEPROM_ADDR_LEN < 1 || CONFIG_SYS_I2C_EEPROM_ADDR_LEN > 2 #error CONFIG_SYS_I2C_EEPROM_ADDR_LEN must be 1 or 2 #endif #endif int eeprom_read (unsigned dev_addr, unsigned offset, uchar *buffer, unsigned cnt) { unsigned end = offset + cnt; unsigned blk_off; int rcode = 0; /* Read data until done or would cross a page boundary. * We must write the address again when changing pages * because the next page may be in a different device. */ while (offset < end) { unsigned alen, len; #if !defined(CONFIG_SYS_I2C_FRAM) unsigned maxlen; #endif #if CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 && !defined(CONFIG_SPI_X) uchar addr[2]; blk_off = offset & 0xFF; /* block offset */ addr[0] = offset >> 8; /* block number */ addr[1] = blk_off; /* block offset */ alen = 2; #else uchar addr[3]; blk_off = offset & 0xFF; /* block offset */ addr[0] = offset >> 16; /* block number */ addr[1] = offset >> 8; /* upper address octet */ addr[2] = blk_off; /* lower address octet */ alen = 3; #endif /* CONFIG_SYS_I2C_EEPROM_ADDR_LEN, CONFIG_SPI_X */ addr[0] |= dev_addr; /* insert device address */ len = end - offset; /* * For a FRAM device there is no limit on the number of the * bytes that can be ccessed with the single read or write * operation. */ #if !defined(CONFIG_SYS_I2C_FRAM) maxlen = 0x100 - blk_off; if (maxlen > I2C_RXTX_LEN) maxlen = I2C_RXTX_LEN; if (len > maxlen) len = maxlen; #endif #if defined(CONFIG_SPI) && !defined(CONFIG_ENV_EEPROM_IS_ON_I2C) spi_read (addr, alen, buffer, len); #else #if defined(CONFIG_SYS_I2C_EEPROM_BUS) i2c_set_bus_num(CONFIG_SYS_I2C_EEPROM_BUS); #endif if (i2c_read(addr[0], offset, alen - 1, buffer, len)) rcode = 1; #endif buffer += len; offset += len; } return rcode; } /*----------------------------------------------------------------------- * * for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 2 (16-bit EEPROM address) offset is * 0x000nxxxx for EEPROM address selectors at n, offset xxxx in EEPROM. * * for CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 (8-bit EEPROM page address) offset is * 0x00000nxx for EEPROM address selectors and page number at n. */ int eeprom_write (unsigned dev_addr, unsigned offset, uchar *buffer, unsigned cnt) { unsigned end = offset + cnt; unsigned blk_off; int rcode = 0; #if defined(CONFIG_SYS_EEPROM_X40430) uchar contr_r_addr[2]; uchar addr_void[2]; uchar contr_reg[2]; uchar ctrl_reg_v; int i; #endif #if defined(CONFIG_SYS_EEPROM_WREN) eeprom_write_enable (dev_addr,1); #endif /* Write data until done or would cross a write page boundary. * We must write the address again when changing pages * because the address counter only increments within a page. */ while (offset < end) { unsigned alen, len; #if !defined(CONFIG_SYS_I2C_FRAM) unsigned maxlen; #endif #if CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 && !defined(CONFIG_SPI_X) uchar addr[2]; blk_off = offset & 0xFF; /* block offset */ addr[0] = offset >> 8; /* block number */ addr[1] = blk_off; /* block offset */ alen = 2; #else uchar addr[3]; blk_off = offset & 0xFF; /* block offset */ addr[0] = offset >> 16; /* block number */ addr[1] = offset >> 8; /* upper address octet */ addr[2] = blk_off; /* lower address octet */ alen = 3; #endif /* CONFIG_SYS_I2C_EEPROM_ADDR_LEN, CONFIG_SPI_X */ addr[0] |= dev_addr; /* insert device address */ len = end - offset; /* * For a FRAM device there is no limit on the number of the * bytes that can be accessed with the single read or write * operation. */ #if !defined(CONFIG_SYS_I2C_FRAM) #if defined(CONFIG_SYS_EEPROM_PAGE_WRITE_BITS) #define EEPROM_PAGE_SIZE (1 << CONFIG_SYS_EEPROM_PAGE_WRITE_BITS) #define EEPROM_PAGE_OFFSET(x) ((x) & (EEPROM_PAGE_SIZE - 1)) maxlen = EEPROM_PAGE_SIZE - EEPROM_PAGE_OFFSET(blk_off); #else maxlen = 0x100 - blk_off; #endif if (maxlen > I2C_RXTX_LEN) maxlen = I2C_RXTX_LEN; if (len > maxlen) len = maxlen; #endif #if defined(CONFIG_SPI) && !defined(CONFIG_ENV_EEPROM_IS_ON_I2C) spi_write (addr, alen, buffer, len); #else #if defined(CONFIG_SYS_EEPROM_X40430) /* Get the value of the control register. * Set current address (internal pointer in the x40430) * to 0x1ff. */ contr_r_addr[0] = 9; contr_r_addr[1] = 0xff; addr_void[0] = 0; addr_void[1] = addr[1]; #ifdef CONFIG_SYS_I2C_EEPROM_ADDR contr_r_addr[0] |= CONFIG_SYS_I2C_EEPROM_ADDR; addr_void[0] |= CONFIG_SYS_I2C_EEPROM_ADDR; #endif contr_reg[0] = 0xff; if (i2c_read (contr_r_addr[0], contr_r_addr[1], 1, contr_reg, 1) != 0) { rcode = 1; } ctrl_reg_v = contr_reg[0]; /* Are any of the eeprom blocks write protected? */ if (ctrl_reg_v & 0x18) { ctrl_reg_v &= ~0x18; /* reset block protect bits */ ctrl_reg_v |= 0x02; /* set write enable latch */ ctrl_reg_v &= ~0x04; /* clear RWEL */ /* Set write enable latch. */ contr_reg[0] = 0x02; if (i2c_write (contr_r_addr[0], 0xff, 1, contr_reg, 1) != 0) { rcode = 1; } /* Set register write enable latch. */ contr_reg[0] = 0x06; if (i2c_write (contr_r_addr[0], 0xFF, 1, contr_reg, 1) != 0) { rcode = 1; } /* Modify ctrl register. */ contr_reg[0] = ctrl_reg_v; if (i2c_write (contr_r_addr[0], 0xFF, 1, contr_reg, 1) != 0) { rcode = 1; } /* The write (above) is an operation on NV memory. * These can take some time (~5ms), and the device * will not respond to further I2C messages till * it's completed the write. * So poll device for an I2C acknowledge. * When we get one we know we can continue with other * operations. */ contr_reg[0] = 0; for (i = 0; i < MAX_ACKNOWLEDGE_POLLS; i++) { if (i2c_read (addr_void[0], addr_void[1], 1, contr_reg, 1) == 0) break; /* got ack */ #if defined(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS) udelay(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS * 1000); #endif } if (i == MAX_ACKNOWLEDGE_POLLS) { puts ("EEPROM poll acknowledge failed\n"); rcode = 1; } } /* Is the write enable latch on?. */ else if (!(ctrl_reg_v & 0x02)) { /* Set write enable latch. */ contr_reg[0] = 0x02; if (i2c_write (contr_r_addr[0], 0xFF, 1, contr_reg, 1) != 0) { rcode = 1; } } /* Write is enabled ... now write eeprom value. */ #endif #if defined(CONFIG_SYS_I2C_EEPROM_BUS) i2c_set_bus_num(CONFIG_SYS_I2C_EEPROM_BUS); #endif if (i2c_write(addr[0], offset, alen - 1, buffer, len)) rcode = 1; #endif buffer += len; offset += len; #if defined(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS) udelay(CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS * 1000); #endif } #if defined(CONFIG_SYS_EEPROM_WREN) eeprom_write_enable (dev_addr,0); #endif return rcode; } #if !defined(CONFIG_SPI) || defined(CONFIG_ENV_EEPROM_IS_ON_I2C) int eeprom_probe (unsigned dev_addr, unsigned offset) { unsigned char chip; /* Probe the chip address */ #if CONFIG_SYS_I2C_EEPROM_ADDR_LEN == 1 && !defined(CONFIG_SPI_X) chip = offset >> 8; /* block number */ #else chip = offset >> 16; /* block number */ #endif /* CONFIG_SYS_I2C_EEPROM_ADDR_LEN, CONFIG_SPI_X */ chip |= dev_addr; /* insert device address */ return (i2c_probe (chip)); } #endif /*----------------------------------------------------------------------- * Set default values */ #ifndef CONFIG_SYS_I2C_SPEED #define CONFIG_SYS_I2C_SPEED 50000 #endif void eeprom_init (void) { #if defined(CONFIG_SPI) && !defined(CONFIG_ENV_EEPROM_IS_ON_I2C) spi_init_f (); #endif #if defined(CONFIG_HARD_I2C) || defined(CONFIG_SYS_I2C_SOFT) i2c_init (CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); #endif } /*----------------------------------------------------------------------- */ /***************************************************/ #if defined(CONFIG_CMD_EEPROM) #ifdef CONFIG_SYS_I2C_MULTI_EEPROMS U_BOOT_CMD( eeprom, 6, 1, do_eeprom, "EEPROM sub-system", "read devaddr addr off cnt\n" "eeprom write devaddr addr off cnt\n" " - read/write `cnt' bytes from `devaddr` EEPROM at offset `off'" ) #else /* One EEPROM */ U_BOOT_CMD( eeprom, 5, 1, do_eeprom, "EEPROM sub-system", "read addr off cnt\n" "eeprom write addr off cnt\n" " - read/write `cnt' bytes at EEPROM offset `off'" ) #endif /* CONFIG_SYS_I2C_MULTI_EEPROMS */ #endif
mdxy2010/forlinux-ok6410
u-boot15/common/cmd_eeprom.c
C
gpl-2.0
11,537
/* * ints.c -- 680x0 Linux general interrupt handling code * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. * * 07/03/96: Timer initialization, and thus mach_sched_init(), * removed from request_irq() and moved to init_time(). * We should therefore consider renaming our add_isr() and * remove_isr() to request_irq() and free_irq() * respectively, so they are compliant with the other * architectures. /Jes */ #include <linux/types.h> #include <linux/sched.h> #include <linux/kernel_stat.h> #include <linux/errno.h> #include <asm/system.h> #include <asm/irq.h> #include <asm/traps.h> #include <asm/page.h> #include <asm/machdep.h> /* list is accessed 0-6 for IRQs 1-7 */ static isr_node_t *isr_list[7]; /* The number of spurious interrupts */ volatile unsigned long num_spurious; /* unsigned long interrupt_stack[PAGE_SIZE/sizeof(long)]; */ /* * void init_IRQ(void) * * Parameters: None * * Returns: Nothing * * This function should be called during kernel startup to initialize * the IRQ handling routines. */ void init_IRQ(void) { /* Setup interrupt stack pointer */ /* asm ("movec %0,%/isp" : : "r" (interrupt_stack + sizeof (interrupt_stack) / sizeof (long))); */ mach_init_INTS (); } void insert_isr (isr_node_t **listp, isr_node_t *node) { unsigned long spl; isr_node_t *cur; save_flags(spl); cli(); cur = *listp; while (cur && cur->pri <= node->pri) { listp = &cur->next; cur = cur->next; } node->next = cur; *listp = node; restore_flags(spl); } void delete_isr (isr_node_t **listp, isrfunc isr, void *data) { unsigned long flags; isr_node_t *np; save_flags(flags); cli(); for (np = *listp; np; listp = &np->next, np = *listp) { if (np->isr == isr && np->data == data) { *listp = np->next; /* Mark it as free. */ np->isr = NULL; restore_flags(flags); return; } } restore_flags(flags); printk ("delete_isr: isr %p not found on list!\n", isr); } #define NUM_ISR_NODES 100 static isr_node_t nodes[NUM_ISR_NODES]; isr_node_t *new_isr_node(void) { isr_node_t *np; for (np = nodes; np < &nodes[NUM_ISR_NODES]; np++) if (np->isr == NULL) return np; printk ("new_isr_node: out of nodes"); return NULL; } int add_isr (unsigned long source, isrfunc isr, int pri, void *data, char *name) { isr_node_t *p; if (source & IRQ_MACHSPEC) { return mach_add_isr (source, isr, pri, data, name); } if (source < IRQ1 || source > IRQ7) panic ("add_isr: Incorrect IRQ source %ld from %s\n", source, name); p = new_isr_node(); if (p == NULL) return 0; p->isr = isr; p->pri = pri; p->data = data; p->name = name; p->next = NULL; insert_isr (&isr_list[source-1], p); return 1; } int remove_isr (unsigned long source, isrfunc isr, void *data) { if (source & IRQ_MACHSPEC) return mach_remove_isr (source, isr, data); if (source < IRQ1 || source > IRQ7) { printk ("remove_isr: Incorrect IRQ source %ld\n", source); return 0; } delete_isr (&isr_list[source - 1], isr, data); return 1; } void call_isr_list(int irq, isr_node_t *p, struct pt_regs *fp) { while (p) { p->isr (irq, fp, p->data); p = p->next; } } asmlinkage void process_int(int vec, struct pt_regs *regs) { int level; if (vec >= VECOFF(VEC_INT1) && vec <= VECOFF(VEC_INT7)) level = (vec - VECOFF(VEC_SPUR)) >> 2; else { if (mach_process_int) mach_process_int(vec, regs); else panic("Can't process interrupt vector 0x%03x\n", vec); return; } kstat.interrupts[level]++; call_isr_list (level, isr_list[level-1], regs); } int request_irq(unsigned int irq, void (*handler)(int, void *, struct pt_regs *), unsigned long flags, const char * devname, void *dev_id) { return -EINVAL; } void free_irq(unsigned int irq, void *dev_id) { } /* * Do we need these probe functions on the m68k? */ unsigned long probe_irq_on (void) { return 0; } int probe_irq_off (unsigned long irqs) { return 0; } void enable_irq(unsigned int irq_nr) { if ((irq_nr & IRQ_MACHSPEC) && mach_enable_irq) mach_enable_irq(irq_nr); } void disable_irq(unsigned int irq_nr) { if ((irq_nr & IRQ_MACHSPEC) && mach_disable_irq) mach_disable_irq(irq_nr); } int get_irq_list(char *buf) { int i, len = 0; isr_node_t *p; /* autovector interrupts */ for (i = IRQ1; i <= IRQ7; ++i) { if (!isr_list[i-1]) continue; len += sprintf(buf+len, "auto %2d: %8d ", i, kstat.interrupts[i]); for (p = isr_list[i-1]; p; p = p->next) { len += sprintf(buf+len, "%s\n", p->name); if (p->next) len += sprintf(buf+len, " "); } } len = mach_get_irq_list(buf, len); return len; }
carlobar/uclinux_leon3_UD
linux-2.0.x/arch/m68k/kernel/ints.c
C
gpl-2.0
4,972
// license:BSD-3-Clause // copyright-holders:Carl, Miodrag Milanovic #include "emu.h" #include "osdnet.h" device_network_interface::device_network_interface(const machine_config &mconfig, device_t &device, float bandwidth) : device_interface(device, "network") { m_promisc = false; m_bandwidth = bandwidth; set_mac("\0\0\0\0\0\0"); m_intf = -1; m_loopback_control = false; } device_network_interface::~device_network_interface() { } void device_network_interface::interface_pre_start() { m_send_timer = device().machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(device_network_interface::send_complete), this)); m_recv_timer = device().machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(device_network_interface::recv_complete), this)); } void device_network_interface::interface_post_start() { device().save_item(NAME(m_loopback_control)); } int device_network_interface::send(u8 *buf, int len) { // TODO: enable this check when other devices implement delayed transmit //if (m_send_timer->enabled()) //throw emu_fatalerror("%s(%s): attempted to transmit while transmit already in progress", device().shortname(), device().tag()); int result = 0; if (m_loopback_control) { // loop data back to receiver result = recv_start_cb(buf, len); if (result) { // schedule receive complete callback m_recv_timer->adjust(attotime::from_ticks(len, m_bandwidth * 1'000'000 / 8), result); } } else if (m_dev) { // send the data result = m_dev->send(buf, len); } // schedule transmit complete callback m_send_timer->adjust(attotime::from_ticks(len, m_bandwidth * 1'000'000 / 8), result); return result; } TIMER_CALLBACK_MEMBER(device_network_interface::send_complete) { send_complete_cb(param); } void device_network_interface::recv_cb(u8 *buf, int len) { if (m_recv_timer->enabled()) throw emu_fatalerror("%s(%s): attempted to receive while receive already in progress", device().shortname(), device().tag()); int result = 0; // process the received data if (!m_loopback_control) result = recv_start_cb(buf, len); if (result) { // stop receiving more data from the network if (m_dev) m_dev->stop(); // schedule receive complete callback m_recv_timer->adjust(attotime::from_ticks(len, m_bandwidth * 1'000'000 / 8), result); } } TIMER_CALLBACK_MEMBER(device_network_interface::recv_complete) { recv_complete_cb(param); // start receiving data from the network again if (m_dev && !m_loopback_control) m_dev->start(); } void device_network_interface::set_promisc(bool promisc) { m_promisc = promisc; if(m_dev) m_dev->set_promisc(promisc); } void device_network_interface::set_mac(const char *mac) { memcpy(m_mac, mac, 6); if(m_dev) m_dev->set_mac(m_mac); } void device_network_interface::set_interface(int id) { if(m_dev) m_dev->stop(); m_dev.reset(open_netdev(id, this, (int)(m_bandwidth*1000000/8.0f/1500))); if(!m_dev) { device().logerror("Network interface %d not found\n", id); id = -1; } m_intf = id; } void device_network_interface::set_loopback(bool loopback) { if (m_loopback_control == loopback) return; m_loopback_control = loopback; if (m_dev) { if (loopback) m_dev->stop(); else if (!m_recv_timer->enabled()) m_dev->start(); } }
johnparker007/mame
src/emu/dinetwork.cpp
C++
gpl-2.0
3,275
<?php /** * @version $Id: upload.http.html.php 1110 2010-01-11 14:02:43Z tom $ * @category DOCman * @package DOCman15 * @copyright Copyright (C) 2003 - 2009 Johan Janssens and Mathias Verraes. All rights reserved. * @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html> * @link http://www.joomladocman.org */ defined('_JEXEC') or die('Restricted access'); class HTML_DMUploadMethod { function uploadFileForm($lists) { $progressImg = JURI::root(true).'/components/com_docman/assets/images/dm_progress.gif'; ob_start(); ?> <form action="<?php echo JRoute::_($lists['action']) ;?>" method="post" enctype="multipart/form-data" id="dm_frmupload" class="dm_form"> <fieldset class="dm_adminform"> <table class="dm_admintable"> <tr> <td colspan="2"><div id="progress" style="display:none;"><img style="border:1px solid black;" src="<?php echo $progressImg?>" alt="Upload Progress" />&nbsp;<?php echo _DML_ISUPLOADING?></div></td> </tr> <tr> <td class="dm_key"> <label for="upload"><?php echo _DML_SELECTFILE;?></label> </td> <td> <input id="upload" name="upload" type="file" name="file" /> </td> </tr> </table> </fieldset> <fieldset class="dm_button"> <input name="submit" id="dm_btn_back" class="button" value="<?php echo _DML_BACK;?>" onclick="window.history.back()" type="button" > <input name="submit" id="dm_btn_submit" class="button" value="<?php echo _DML_UPLOAD;?>" type="submit" onclick="document.getElementById('progress').style.display = 'block';" /> </fieldset> <input type="hidden" name="method" value="http" /> <?php echo DOCMAN_token::render();?> </form> <?php $html = ob_get_contents(); ob_end_clean(); return $html; } }
kuwox/wwwfranar
tmp/install_4ec164b97d40c/components/com_docman/includes/upload.http.html.php
PHP
gpl-2.0
1,841
<?php /** * @file * Contains \Drupal\file\Tests\SaveTest. */ namespace Drupal\file\Tests; use Drupal\file\Entity\File; use Drupal\Core\Entity\EntityStorageException; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Entity\Sql\SqlEntityStorageInterface; /** * File saving tests. * * @group file */ class SaveTest extends FileManagedUnitTestBase { function testFileSave() { // Create a new file entity. $file = File::create(array( 'uid' => 1, 'filename' => 'druplicon.txt', 'uri' => 'public://druplicon.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT, )); file_put_contents($file->getFileUri(), 'hello world'); // Save it, inserting a new record. $file->save(); // Check that the correct hooks were called. $this->assertFileHooksCalled(array('insert')); $this->assertTrue($file->id() > 0, 'A new file ID is set when saving a new file to the database.', 'File'); $loaded_file = file_load($file->id()); $this->assertNotNull($loaded_file, 'Record exists in the database.'); $this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.'); $this->assertEqual($file->getSize(), filesize($file->getFileUri()), 'File size was set correctly.', 'File'); $this->assertTrue($file->getChangedTime() > 1, 'File size was set correctly.', 'File'); $this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was defaulted correctly.'); // Resave the file, updating the existing record. file_test_reset(); $file->status->value = 7; $file->save(); // Check that the correct hooks were called. $this->assertFileHooksCalled(array('load', 'update')); $this->assertEqual($file->id(), $file->id(), 'The file ID of an existing file is not changed when updating the database.', 'File'); $this->assertTrue($file->getChangedTime() >= $file->getChangedTime(), "Timestamp didn't go backwards.", 'File'); $loaded_file = file_load($file->id()); $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File'); $this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.'); $this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was saved correctly.'); // Try to insert a second file with the same name apart from case insensitivity // to ensure the 'uri' index allows for filenames with different cases. $uppercase_values = array( 'uid' => 1, 'filename' => 'DRUPLICON.txt', 'uri' => 'public://DRUPLICON.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT, ); $uppercase_file = File::create($uppercase_values); file_put_contents($uppercase_file->getFileUri(), 'hello world'); $violations = $uppercase_file->validate(); $this->assertEqual(count($violations), 0, 'No violations when adding an URI with an existing filename in upper case.'); $uppercase_file->save(); // Ensure the database URI uniqueness constraint is triggered. $uppercase_file_duplicate = File::create($uppercase_values); file_put_contents($uppercase_file_duplicate->getFileUri(), 'hello world'); $violations = $uppercase_file_duplicate->validate(); $this->assertEqual(count($violations), 1); $this->assertEqual($violations[0]->getMessage(), t('The file %value already exists. Enter a unique file URI.', [ '%value' => $uppercase_file_duplicate->getFileUri(), ])); // Ensure that file URI entity queries are case sensitive. $fids = \Drupal::entityQuery('file') ->condition('uri', $uppercase_file->getFileUri()) ->execute(); $this->assertEqual(1, count($fids)); $this->assertEqual(array($uppercase_file->id() => $uppercase_file->id()), $fids); } }
cpjobling/proman-d8
proman.swan.ac.uk/core/modules/file/src/Tests/SaveTest.php
PHP
gpl-2.0
3,832
/* * ahci.c - AHCI SATA support * * Maintained by: Tejun Heo <tj@kernel.org> * Please ALWAYS copy linux-ide@vger.kernel.org * on emails. * * Copyright 2004-2005 Red Hat, Inc. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * * * libata documentation is available via 'make {ps|pdf}docs', * as Documentation/DocBook/libata.* * * AHCI hardware documentation: * http://www.intel.com/technology/serialata/pdf/rev1_0.pdf * http://www.intel.com/technology/serialata/pdf/rev1_1.pdf * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/device.h> #include <linux/dmi.h> #include <linux/gfp.h> #include <scsi/scsi_host.h> #include <scsi/scsi_cmnd.h> #include <linux/libata.h> #include "ahci.h" #define DRV_NAME "ahci" #define DRV_VERSION "3.0" enum { AHCI_PCI_BAR_STA2X11 = 0, AHCI_PCI_BAR_ENMOTUS = 2, AHCI_PCI_BAR_STANDARD = 5, }; enum board_ids { /* board IDs by feature in alphabetical order */ board_ahci, board_ahci_ign_iferr, board_ahci_nomsi, board_ahci_noncq, board_ahci_nosntf, board_ahci_yes_fbs, /* board IDs for specific chipsets in alphabetical order */ board_ahci_mcp65, board_ahci_mcp77, board_ahci_mcp89, board_ahci_mv, board_ahci_sb600, board_ahci_sb700, /* for SB700 and SB800 */ board_ahci_vt8251, /* aliases */ board_ahci_mcp_linux = board_ahci_mcp65, board_ahci_mcp67 = board_ahci_mcp65, board_ahci_mcp73 = board_ahci_mcp65, board_ahci_mcp79 = board_ahci_mcp77, }; static int ahci_init_one(struct pci_dev *pdev, const struct pci_device_id *ent); static int ahci_vt8251_hardreset(struct ata_link *link, unsigned int *class, unsigned long deadline); static void ahci_mcp89_apple_enable(struct pci_dev *pdev); static bool is_mcp89_apple(struct pci_dev *pdev); static int ahci_p5wdh_hardreset(struct ata_link *link, unsigned int *class, unsigned long deadline); #ifdef CONFIG_PM static int ahci_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg); static int ahci_pci_device_resume(struct pci_dev *pdev); #endif static struct scsi_host_template ahci_sht = { AHCI_SHT("ahci"), }; static struct ata_port_operations ahci_vt8251_ops = { .inherits = &ahci_ops, .hardreset = ahci_vt8251_hardreset, }; static struct ata_port_operations ahci_p5wdh_ops = { .inherits = &ahci_ops, .hardreset = ahci_p5wdh_hardreset, }; static const struct ata_port_info ahci_port_info[] = { /* by features */ [board_ahci] = { .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_ign_iferr] = { AHCI_HFLAGS (AHCI_HFLAG_IGN_IRQ_IF_ERR), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_nomsi] = { AHCI_HFLAGS (AHCI_HFLAG_NO_MSI), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_noncq] = { AHCI_HFLAGS (AHCI_HFLAG_NO_NCQ), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_nosntf] = { AHCI_HFLAGS (AHCI_HFLAG_NO_SNTF), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_yes_fbs] = { AHCI_HFLAGS (AHCI_HFLAG_YES_FBS), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, /* by chipsets */ [board_ahci_mcp65] = { AHCI_HFLAGS (AHCI_HFLAG_NO_FPDMA_AA | AHCI_HFLAG_NO_PMP | AHCI_HFLAG_YES_NCQ), .flags = AHCI_FLAG_COMMON | ATA_FLAG_NO_DIPM, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_mcp77] = { AHCI_HFLAGS (AHCI_HFLAG_NO_FPDMA_AA | AHCI_HFLAG_NO_PMP), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_mcp89] = { AHCI_HFLAGS (AHCI_HFLAG_NO_FPDMA_AA), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_mv] = { AHCI_HFLAGS (AHCI_HFLAG_NO_NCQ | AHCI_HFLAG_NO_MSI | AHCI_HFLAG_MV_PATA | AHCI_HFLAG_NO_PMP), .flags = ATA_FLAG_SATA | ATA_FLAG_PIO_DMA, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_ops, }, [board_ahci_sb600] = { AHCI_HFLAGS (AHCI_HFLAG_IGN_SERR_INTERNAL | AHCI_HFLAG_NO_MSI | AHCI_HFLAG_SECT255 | AHCI_HFLAG_32BIT_ONLY), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_pmp_retry_srst_ops, }, [board_ahci_sb700] = { /* for SB700 and SB800 */ AHCI_HFLAGS (AHCI_HFLAG_IGN_SERR_INTERNAL), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_pmp_retry_srst_ops, }, [board_ahci_vt8251] = { AHCI_HFLAGS (AHCI_HFLAG_NO_NCQ | AHCI_HFLAG_NO_PMP), .flags = AHCI_FLAG_COMMON, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_vt8251_ops, }, }; static const struct pci_device_id ahci_pci_tbl[] = { /* Intel */ { PCI_VDEVICE(INTEL, 0x2652), board_ahci }, /* ICH6 */ { PCI_VDEVICE(INTEL, 0x2653), board_ahci }, /* ICH6M */ { PCI_VDEVICE(INTEL, 0x27c1), board_ahci }, /* ICH7 */ { PCI_VDEVICE(INTEL, 0x27c5), board_ahci }, /* ICH7M */ { PCI_VDEVICE(INTEL, 0x27c3), board_ahci }, /* ICH7R */ { PCI_VDEVICE(AL, 0x5288), board_ahci_ign_iferr }, /* ULi M5288 */ { PCI_VDEVICE(INTEL, 0x2681), board_ahci }, /* ESB2 */ { PCI_VDEVICE(INTEL, 0x2682), board_ahci }, /* ESB2 */ { PCI_VDEVICE(INTEL, 0x2683), board_ahci }, /* ESB2 */ { PCI_VDEVICE(INTEL, 0x27c6), board_ahci }, /* ICH7-M DH */ { PCI_VDEVICE(INTEL, 0x2821), board_ahci }, /* ICH8 */ { PCI_VDEVICE(INTEL, 0x2822), board_ahci_nosntf }, /* ICH8 */ { PCI_VDEVICE(INTEL, 0x2824), board_ahci }, /* ICH8 */ { PCI_VDEVICE(INTEL, 0x2829), board_ahci }, /* ICH8M */ { PCI_VDEVICE(INTEL, 0x282a), board_ahci }, /* ICH8M */ { PCI_VDEVICE(INTEL, 0x2922), board_ahci }, /* ICH9 */ { PCI_VDEVICE(INTEL, 0x2923), board_ahci }, /* ICH9 */ { PCI_VDEVICE(INTEL, 0x2924), board_ahci }, /* ICH9 */ { PCI_VDEVICE(INTEL, 0x2925), board_ahci }, /* ICH9 */ { PCI_VDEVICE(INTEL, 0x2927), board_ahci }, /* ICH9 */ { PCI_VDEVICE(INTEL, 0x2929), board_ahci }, /* ICH9M */ { PCI_VDEVICE(INTEL, 0x292a), board_ahci }, /* ICH9M */ { PCI_VDEVICE(INTEL, 0x292b), board_ahci }, /* ICH9M */ { PCI_VDEVICE(INTEL, 0x292c), board_ahci }, /* ICH9M */ { PCI_VDEVICE(INTEL, 0x292f), board_ahci }, /* ICH9M */ { PCI_VDEVICE(INTEL, 0x294d), board_ahci }, /* ICH9 */ { PCI_VDEVICE(INTEL, 0x294e), board_ahci }, /* ICH9M */ { PCI_VDEVICE(INTEL, 0x502a), board_ahci }, /* Tolapai */ { PCI_VDEVICE(INTEL, 0x502b), board_ahci }, /* Tolapai */ { PCI_VDEVICE(INTEL, 0x3a05), board_ahci }, /* ICH10 */ { PCI_VDEVICE(INTEL, 0x3a22), board_ahci }, /* ICH10 */ { PCI_VDEVICE(INTEL, 0x3a25), board_ahci }, /* ICH10 */ { PCI_VDEVICE(INTEL, 0x3b22), board_ahci }, /* PCH AHCI */ { PCI_VDEVICE(INTEL, 0x3b23), board_ahci }, /* PCH AHCI */ { PCI_VDEVICE(INTEL, 0x3b24), board_ahci }, /* PCH RAID */ { PCI_VDEVICE(INTEL, 0x3b25), board_ahci }, /* PCH RAID */ { PCI_VDEVICE(INTEL, 0x3b29), board_ahci }, /* PCH AHCI */ { PCI_VDEVICE(INTEL, 0x3b2b), board_ahci }, /* PCH RAID */ { PCI_VDEVICE(INTEL, 0x3b2c), board_ahci }, /* PCH RAID */ { PCI_VDEVICE(INTEL, 0x3b2f), board_ahci }, /* PCH AHCI */ { PCI_VDEVICE(INTEL, 0x1c02), board_ahci }, /* CPT AHCI */ { PCI_VDEVICE(INTEL, 0x1c03), board_ahci }, /* CPT AHCI */ { PCI_VDEVICE(INTEL, 0x1c04), board_ahci }, /* CPT RAID */ { PCI_VDEVICE(INTEL, 0x1c05), board_ahci }, /* CPT RAID */ { PCI_VDEVICE(INTEL, 0x1c06), board_ahci }, /* CPT RAID */ { PCI_VDEVICE(INTEL, 0x1c07), board_ahci }, /* CPT RAID */ { PCI_VDEVICE(INTEL, 0x1d02), board_ahci }, /* PBG AHCI */ { PCI_VDEVICE(INTEL, 0x1d04), board_ahci }, /* PBG RAID */ { PCI_VDEVICE(INTEL, 0x1d06), board_ahci }, /* PBG RAID */ { PCI_VDEVICE(INTEL, 0x2826), board_ahci }, /* PBG RAID */ { PCI_VDEVICE(INTEL, 0x2323), board_ahci }, /* DH89xxCC AHCI */ { PCI_VDEVICE(INTEL, 0x1e02), board_ahci }, /* Panther Point AHCI */ { PCI_VDEVICE(INTEL, 0x1e03), board_ahci }, /* Panther Point AHCI */ { PCI_VDEVICE(INTEL, 0x1e04), board_ahci }, /* Panther Point RAID */ { PCI_VDEVICE(INTEL, 0x1e05), board_ahci }, /* Panther Point RAID */ { PCI_VDEVICE(INTEL, 0x1e06), board_ahci }, /* Panther Point RAID */ { PCI_VDEVICE(INTEL, 0x1e07), board_ahci }, /* Panther Point RAID */ { PCI_VDEVICE(INTEL, 0x1e0e), board_ahci }, /* Panther Point RAID */ { PCI_VDEVICE(INTEL, 0x8c02), board_ahci }, /* Lynx Point AHCI */ { PCI_VDEVICE(INTEL, 0x8c03), board_ahci }, /* Lynx Point AHCI */ { PCI_VDEVICE(INTEL, 0x8c04), board_ahci }, /* Lynx Point RAID */ { PCI_VDEVICE(INTEL, 0x8c05), board_ahci }, /* Lynx Point RAID */ { PCI_VDEVICE(INTEL, 0x8c06), board_ahci }, /* Lynx Point RAID */ { PCI_VDEVICE(INTEL, 0x8c07), board_ahci }, /* Lynx Point RAID */ { PCI_VDEVICE(INTEL, 0x8c0e), board_ahci }, /* Lynx Point RAID */ { PCI_VDEVICE(INTEL, 0x8c0f), board_ahci }, /* Lynx Point RAID */ { PCI_VDEVICE(INTEL, 0x9c02), board_ahci }, /* Lynx Point-LP AHCI */ { PCI_VDEVICE(INTEL, 0x9c03), board_ahci }, /* Lynx Point-LP AHCI */ { PCI_VDEVICE(INTEL, 0x9c04), board_ahci }, /* Lynx Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c05), board_ahci }, /* Lynx Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c06), board_ahci }, /* Lynx Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c07), board_ahci }, /* Lynx Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c0e), board_ahci }, /* Lynx Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c0f), board_ahci }, /* Lynx Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x1f22), board_ahci }, /* Avoton AHCI */ { PCI_VDEVICE(INTEL, 0x1f23), board_ahci }, /* Avoton AHCI */ { PCI_VDEVICE(INTEL, 0x1f24), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f25), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f26), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f27), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f2e), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f2f), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f32), board_ahci }, /* Avoton AHCI */ { PCI_VDEVICE(INTEL, 0x1f33), board_ahci }, /* Avoton AHCI */ { PCI_VDEVICE(INTEL, 0x1f34), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f35), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f36), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f37), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f3e), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x1f3f), board_ahci }, /* Avoton RAID */ { PCI_VDEVICE(INTEL, 0x2823), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x2827), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x8d02), board_ahci }, /* Wellsburg AHCI */ { PCI_VDEVICE(INTEL, 0x8d04), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x8d06), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x8d0e), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x8d62), board_ahci }, /* Wellsburg AHCI */ { PCI_VDEVICE(INTEL, 0x8d64), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x8d66), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x8d6e), board_ahci }, /* Wellsburg RAID */ { PCI_VDEVICE(INTEL, 0x23a3), board_ahci }, /* Coleto Creek AHCI */ { PCI_VDEVICE(INTEL, 0x9c83), board_ahci }, /* Wildcat Point-LP AHCI */ { PCI_VDEVICE(INTEL, 0x9c85), board_ahci }, /* Wildcat Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c87), board_ahci }, /* Wildcat Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x9c8f), board_ahci }, /* Wildcat Point-LP RAID */ { PCI_VDEVICE(INTEL, 0x8c82), board_ahci }, /* 9 Series AHCI */ { PCI_VDEVICE(INTEL, 0x8c83), board_ahci }, /* 9 Series AHCI */ { PCI_VDEVICE(INTEL, 0x8c84), board_ahci }, /* 9 Series RAID */ { PCI_VDEVICE(INTEL, 0x8c85), board_ahci }, /* 9 Series RAID */ { PCI_VDEVICE(INTEL, 0x8c86), board_ahci }, /* 9 Series RAID */ { PCI_VDEVICE(INTEL, 0x8c87), board_ahci }, /* 9 Series RAID */ { PCI_VDEVICE(INTEL, 0x8c8e), board_ahci }, /* 9 Series RAID */ { PCI_VDEVICE(INTEL, 0x8c8f), board_ahci }, /* 9 Series RAID */ { PCI_VDEVICE(INTEL, 0xa103), board_ahci }, /* Sunrise Point-H AHCI */ { PCI_VDEVICE(INTEL, 0xa103), board_ahci }, /* Sunrise Point-H RAID */ { PCI_VDEVICE(INTEL, 0xa105), board_ahci }, /* Sunrise Point-H RAID */ { PCI_VDEVICE(INTEL, 0xa107), board_ahci }, /* Sunrise Point-H RAID */ { PCI_VDEVICE(INTEL, 0xa10f), board_ahci }, /* Sunrise Point-H RAID */ /* JMicron 360/1/3/5/6, match class to avoid IDE function */ { PCI_VENDOR_ID_JMICRON, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_SATA_AHCI, 0xffffff, board_ahci_ign_iferr }, /* JMicron 362B and 362C have an AHCI function with IDE class code */ { PCI_VDEVICE(JMICRON, 0x2362), board_ahci_ign_iferr }, { PCI_VDEVICE(JMICRON, 0x236f), board_ahci_ign_iferr }, /* ATI */ { PCI_VDEVICE(ATI, 0x4380), board_ahci_sb600 }, /* ATI SB600 */ { PCI_VDEVICE(ATI, 0x4390), board_ahci_sb700 }, /* ATI SB700/800 */ { PCI_VDEVICE(ATI, 0x4391), board_ahci_sb700 }, /* ATI SB700/800 */ { PCI_VDEVICE(ATI, 0x4392), board_ahci_sb700 }, /* ATI SB700/800 */ { PCI_VDEVICE(ATI, 0x4393), board_ahci_sb700 }, /* ATI SB700/800 */ { PCI_VDEVICE(ATI, 0x4394), board_ahci_sb700 }, /* ATI SB700/800 */ { PCI_VDEVICE(ATI, 0x4395), board_ahci_sb700 }, /* ATI SB700/800 */ /* AMD */ { PCI_VDEVICE(AMD, 0x7800), board_ahci }, /* AMD Hudson-2 */ { PCI_VDEVICE(AMD, 0x7900), board_ahci }, /* AMD CZ */ /* AMD is using RAID class only for ahci controllers */ { PCI_VENDOR_ID_AMD, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_RAID << 8, 0xffffff, board_ahci }, /* VIA */ { PCI_VDEVICE(VIA, 0x3349), board_ahci_vt8251 }, /* VIA VT8251 */ { PCI_VDEVICE(VIA, 0x6287), board_ahci_vt8251 }, /* VIA VT8251 */ /* NVIDIA */ { PCI_VDEVICE(NVIDIA, 0x044c), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x044d), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x044e), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x044f), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x045c), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x045d), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x045e), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x045f), board_ahci_mcp65 }, /* MCP65 */ { PCI_VDEVICE(NVIDIA, 0x0550), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0551), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0552), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0553), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0554), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0555), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0556), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0557), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0558), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0559), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x055a), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x055b), board_ahci_mcp67 }, /* MCP67 */ { PCI_VDEVICE(NVIDIA, 0x0580), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0581), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0582), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0583), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0584), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0585), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0586), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0587), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0588), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x0589), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x058a), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x058b), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x058c), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x058d), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x058e), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x058f), board_ahci_mcp_linux }, /* Linux ID */ { PCI_VDEVICE(NVIDIA, 0x07f0), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f1), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f2), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f3), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f4), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f5), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f6), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f7), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f8), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07f9), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07fa), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x07fb), board_ahci_mcp73 }, /* MCP73 */ { PCI_VDEVICE(NVIDIA, 0x0ad0), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad1), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad2), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad3), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad4), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad5), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad6), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad7), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad8), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ad9), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ada), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0adb), board_ahci_mcp77 }, /* MCP77 */ { PCI_VDEVICE(NVIDIA, 0x0ab4), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0ab5), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0ab6), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0ab7), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0ab8), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0ab9), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0aba), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0abb), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0abc), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0abd), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0abe), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0abf), board_ahci_mcp79 }, /* MCP79 */ { PCI_VDEVICE(NVIDIA, 0x0d84), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d85), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d86), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d87), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d88), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d89), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d8a), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d8b), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d8c), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d8d), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d8e), board_ahci_mcp89 }, /* MCP89 */ { PCI_VDEVICE(NVIDIA, 0x0d8f), board_ahci_mcp89 }, /* MCP89 */ /* SiS */ { PCI_VDEVICE(SI, 0x1184), board_ahci }, /* SiS 966 */ { PCI_VDEVICE(SI, 0x1185), board_ahci }, /* SiS 968 */ { PCI_VDEVICE(SI, 0x0186), board_ahci }, /* SiS 968 */ /* ST Microelectronics */ { PCI_VDEVICE(STMICRO, 0xCC06), board_ahci }, /* ST ConneXt */ /* Marvell */ { PCI_VDEVICE(MARVELL, 0x6145), board_ahci_mv }, /* 6145 */ { PCI_VDEVICE(MARVELL, 0x6121), board_ahci_mv }, /* 6121 */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x9123), .class = PCI_CLASS_STORAGE_SATA_AHCI, .class_mask = 0xffffff, .driver_data = board_ahci_yes_fbs }, /* 88se9128 */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x9125), .driver_data = board_ahci_yes_fbs }, /* 88se9125 */ { PCI_DEVICE_SUB(PCI_VENDOR_ID_MARVELL_EXT, 0x9178, PCI_VENDOR_ID_MARVELL_EXT, 0x9170), .driver_data = board_ahci_yes_fbs }, /* 88se9170 */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x917a), .driver_data = board_ahci_yes_fbs }, /* 88se9172 */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x9172), .driver_data = board_ahci_yes_fbs }, /* 88se9182 */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x9182), .driver_data = board_ahci_yes_fbs }, /* 88se9172 */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x9192), .driver_data = board_ahci_yes_fbs }, /* 88se9172 on some Gigabyte */ { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x91a0), .driver_data = board_ahci_yes_fbs }, { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x91a3), .driver_data = board_ahci_yes_fbs }, { PCI_DEVICE(PCI_VENDOR_ID_MARVELL_EXT, 0x9230), .driver_data = board_ahci_yes_fbs }, { PCI_DEVICE(PCI_VENDOR_ID_TTI, 0x0642), .driver_data = board_ahci_yes_fbs }, /* Promise */ { PCI_VDEVICE(PROMISE, 0x3f20), board_ahci }, /* PDC42819 */ { PCI_VDEVICE(PROMISE, 0x3781), board_ahci }, /* FastTrak TX8660 ahci-mode */ /* Asmedia */ { PCI_VDEVICE(ASMEDIA, 0x0601), board_ahci }, /* ASM1060 */ { PCI_VDEVICE(ASMEDIA, 0x0602), board_ahci }, /* ASM1060 */ { PCI_VDEVICE(ASMEDIA, 0x0611), board_ahci }, /* ASM1061 */ { PCI_VDEVICE(ASMEDIA, 0x0612), board_ahci }, /* ASM1062 */ /* * Samsung SSDs found on some macbooks. NCQ times out if MSI is * enabled. https://bugzilla.kernel.org/show_bug.cgi?id=60731 */ { PCI_VDEVICE(SAMSUNG, 0x1600), board_ahci_nomsi }, /* Enmotus */ { PCI_DEVICE(0x1c44, 0x8000), board_ahci }, /* Generic, PCI class code for AHCI */ { PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_STORAGE_SATA_AHCI, 0xffffff, board_ahci }, { } /* terminate list */ }; static struct pci_driver ahci_pci_driver = { .name = DRV_NAME, .id_table = ahci_pci_tbl, .probe = ahci_init_one, .remove = ata_pci_remove_one, #ifdef CONFIG_PM .suspend = ahci_pci_device_suspend, .resume = ahci_pci_device_resume, #endif }; #if defined(CONFIG_PATA_MARVELL) || defined(CONFIG_PATA_MARVELL_MODULE) static int marvell_enable; #else static int marvell_enable = 1; #endif module_param(marvell_enable, int, 0644); MODULE_PARM_DESC(marvell_enable, "Marvell SATA via AHCI (1 = enabled)"); static void ahci_pci_save_initial_config(struct pci_dev *pdev, struct ahci_host_priv *hpriv) { unsigned int force_port_map = 0; unsigned int mask_port_map = 0; if (pdev->vendor == PCI_VENDOR_ID_JMICRON && pdev->device == 0x2361) { dev_info(&pdev->dev, "JMB361 has only one port\n"); force_port_map = 1; } /* * Temporary Marvell 6145 hack: PATA port presence * is asserted through the standard AHCI port * presence register, as bit 4 (counting from 0) */ if (hpriv->flags & AHCI_HFLAG_MV_PATA) { if (pdev->device == 0x6121) mask_port_map = 0x3; else mask_port_map = 0xf; dev_info(&pdev->dev, "Disabling your PATA port. Use the boot option 'ahci.marvell_enable=0' to avoid this.\n"); } ahci_save_initial_config(&pdev->dev, hpriv, force_port_map, mask_port_map); } static int ahci_pci_reset_controller(struct ata_host *host) { struct pci_dev *pdev = to_pci_dev(host->dev); ahci_reset_controller(host); if (pdev->vendor == PCI_VENDOR_ID_INTEL) { struct ahci_host_priv *hpriv = host->private_data; u16 tmp16; /* configure PCS */ pci_read_config_word(pdev, 0x92, &tmp16); if ((tmp16 & hpriv->port_map) != hpriv->port_map) { tmp16 |= hpriv->port_map; pci_write_config_word(pdev, 0x92, tmp16); } } return 0; } static void ahci_pci_init_controller(struct ata_host *host) { struct ahci_host_priv *hpriv = host->private_data; struct pci_dev *pdev = to_pci_dev(host->dev); void __iomem *port_mmio; u32 tmp; int mv; if (hpriv->flags & AHCI_HFLAG_MV_PATA) { if (pdev->device == 0x6121) mv = 2; else mv = 4; port_mmio = __ahci_port_base(host, mv); writel(0, port_mmio + PORT_IRQ_MASK); /* clear port IRQ */ tmp = readl(port_mmio + PORT_IRQ_STAT); VPRINTK("PORT_IRQ_STAT 0x%x\n", tmp); if (tmp) writel(tmp, port_mmio + PORT_IRQ_STAT); } ahci_init_controller(host); } static int ahci_vt8251_hardreset(struct ata_link *link, unsigned int *class, unsigned long deadline) { struct ata_port *ap = link->ap; bool online; int rc; DPRINTK("ENTER\n"); ahci_stop_engine(ap); rc = sata_link_hardreset(link, sata_ehc_deb_timing(&link->eh_context), deadline, &online, NULL); ahci_start_engine(ap); DPRINTK("EXIT, rc=%d, class=%u\n", rc, *class); /* vt8251 doesn't clear BSY on signature FIS reception, * request follow-up softreset. */ return online ? -EAGAIN : rc; } static int ahci_p5wdh_hardreset(struct ata_link *link, unsigned int *class, unsigned long deadline) { struct ata_port *ap = link->ap; struct ahci_port_priv *pp = ap->private_data; u8 *d2h_fis = pp->rx_fis + RX_FIS_D2H_REG; struct ata_taskfile tf; bool online; int rc; ahci_stop_engine(ap); /* clear D2H reception area to properly wait for D2H FIS */ ata_tf_init(link->device, &tf); tf.command = ATA_BUSY; ata_tf_to_fis(&tf, 0, 0, d2h_fis); rc = sata_link_hardreset(link, sata_ehc_deb_timing(&link->eh_context), deadline, &online, NULL); ahci_start_engine(ap); /* The pseudo configuration device on SIMG4726 attached to * ASUS P5W-DH Deluxe doesn't send signature FIS after * hardreset if no device is attached to the first downstream * port && the pseudo device locks up on SRST w/ PMP==0. To * work around this, wait for !BSY only briefly. If BSY isn't * cleared, perform CLO and proceed to IDENTIFY (achieved by * ATA_LFLAG_NO_SRST and ATA_LFLAG_ASSUME_ATA). * * Wait for two seconds. Devices attached to downstream port * which can't process the following IDENTIFY after this will * have to be reset again. For most cases, this should * suffice while making probing snappish enough. */ if (online) { rc = ata_wait_after_reset(link, jiffies + 2 * HZ, ahci_check_ready); if (rc) ahci_kick_engine(ap); } return rc; } #ifdef CONFIG_PM static int ahci_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg) { struct ata_host *host = pci_get_drvdata(pdev); struct ahci_host_priv *hpriv = host->private_data; void __iomem *mmio = hpriv->mmio; u32 ctl; if (mesg.event & PM_EVENT_SUSPEND && hpriv->flags & AHCI_HFLAG_NO_SUSPEND) { dev_err(&pdev->dev, "BIOS update required for suspend/resume\n"); return -EIO; } if (mesg.event & PM_EVENT_SLEEP) { /* AHCI spec rev1.1 section 8.3.3: * Software must disable interrupts prior to requesting a * transition of the HBA to D3 state. */ ctl = readl(mmio + HOST_CTL); ctl &= ~HOST_IRQ_EN; writel(ctl, mmio + HOST_CTL); readl(mmio + HOST_CTL); /* flush */ } return ata_pci_device_suspend(pdev, mesg); } static int ahci_pci_device_resume(struct pci_dev *pdev) { struct ata_host *host = pci_get_drvdata(pdev); int rc; rc = ata_pci_device_do_resume(pdev); if (rc) return rc; /* Apple BIOS helpfully mangles the registers on resume */ if (is_mcp89_apple(pdev)) ahci_mcp89_apple_enable(pdev); if (pdev->dev.power.power_state.event == PM_EVENT_SUSPEND) { rc = ahci_pci_reset_controller(host); if (rc) return rc; ahci_pci_init_controller(host); } ata_host_resume(host); return 0; } #endif static int ahci_configure_dma_masks(struct pci_dev *pdev, int using_dac) { int rc; /* * If the device fixup already set the dma_mask to some non-standard * value, don't extend it here. This happens on STA2X11, for example. */ if (pdev->dma_mask && pdev->dma_mask < DMA_BIT_MASK(32)) return 0; if (using_dac && !pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) { rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64)); if (rc) { rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)); if (rc) { dev_err(&pdev->dev, "64-bit DMA enable failed\n"); return rc; } } } else { rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (rc) { dev_err(&pdev->dev, "32-bit DMA enable failed\n"); return rc; } rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)); if (rc) { dev_err(&pdev->dev, "32-bit consistent DMA enable failed\n"); return rc; } } return 0; } static void ahci_pci_print_info(struct ata_host *host) { struct pci_dev *pdev = to_pci_dev(host->dev); u16 cc; const char *scc_s; pci_read_config_word(pdev, 0x0a, &cc); if (cc == PCI_CLASS_STORAGE_IDE) scc_s = "IDE"; else if (cc == PCI_CLASS_STORAGE_SATA) scc_s = "SATA"; else if (cc == PCI_CLASS_STORAGE_RAID) scc_s = "RAID"; else scc_s = "unknown"; ahci_print_info(host, scc_s); } /* On ASUS P5W DH Deluxe, the second port of PCI device 00:1f.2 is * hardwired to on-board SIMG 4726. The chipset is ICH8 and doesn't * support PMP and the 4726 either directly exports the device * attached to the first downstream port or acts as a hardware storage * controller and emulate a single ATA device (can be RAID 0/1 or some * other configuration). * * When there's no device attached to the first downstream port of the * 4726, "Config Disk" appears, which is a pseudo ATA device to * configure the 4726. However, ATA emulation of the device is very * lame. It doesn't send signature D2H Reg FIS after the initial * hardreset, pukes on SRST w/ PMP==0 and has bunch of other issues. * * The following function works around the problem by always using * hardreset on the port and not depending on receiving signature FIS * afterward. If signature FIS isn't received soon, ATA class is * assumed without follow-up softreset. */ static void ahci_p5wdh_workaround(struct ata_host *host) { static struct dmi_system_id sysids[] = { { .ident = "P5W DH Deluxe", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "ASUSTEK COMPUTER INC"), DMI_MATCH(DMI_PRODUCT_NAME, "P5W DH Deluxe"), }, }, { } }; struct pci_dev *pdev = to_pci_dev(host->dev); if (pdev->bus->number == 0 && pdev->devfn == PCI_DEVFN(0x1f, 2) && dmi_check_system(sysids)) { struct ata_port *ap = host->ports[1]; dev_info(&pdev->dev, "enabling ASUS P5W DH Deluxe on-board SIMG4726 workaround\n"); ap->ops = &ahci_p5wdh_ops; ap->link.flags |= ATA_LFLAG_NO_SRST | ATA_LFLAG_ASSUME_ATA; } } /* * Macbook7,1 firmware forcibly disables MCP89 AHCI and changes PCI ID when * booting in BIOS compatibility mode. We restore the registers but not ID. */ static void ahci_mcp89_apple_enable(struct pci_dev *pdev) { u32 val; printk(KERN_INFO "ahci: enabling MCP89 AHCI mode\n"); pci_read_config_dword(pdev, 0xf8, &val); val |= 1 << 0x1b; /* the following changes the device ID, but appears not to affect function */ /* val = (val & ~0xf0000000) | 0x80000000; */ pci_write_config_dword(pdev, 0xf8, val); pci_read_config_dword(pdev, 0x54c, &val); val |= 1 << 0xc; pci_write_config_dword(pdev, 0x54c, val); pci_read_config_dword(pdev, 0x4a4, &val); val &= 0xff; val |= 0x01060100; pci_write_config_dword(pdev, 0x4a4, val); pci_read_config_dword(pdev, 0x54c, &val); val &= ~(1 << 0xc); pci_write_config_dword(pdev, 0x54c, val); pci_read_config_dword(pdev, 0xf8, &val); val &= ~(1 << 0x1b); pci_write_config_dword(pdev, 0xf8, val); } static bool is_mcp89_apple(struct pci_dev *pdev) { return pdev->vendor == PCI_VENDOR_ID_NVIDIA && pdev->device == PCI_DEVICE_ID_NVIDIA_NFORCE_MCP89_SATA && pdev->subsystem_vendor == PCI_VENDOR_ID_APPLE && pdev->subsystem_device == 0xcb89; } /* only some SB600 ahci controllers can do 64bit DMA */ static bool ahci_sb600_enable_64bit(struct pci_dev *pdev) { static const struct dmi_system_id sysids[] = { /* * The oldest version known to be broken is 0901 and * working is 1501 which was released on 2007-10-26. * Enable 64bit DMA on 1501 and anything newer. * * Please read bko#9412 for more info. */ { .ident = "ASUS M2A-VM", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."), DMI_MATCH(DMI_BOARD_NAME, "M2A-VM"), }, .driver_data = "20071026", /* yyyymmdd */ }, /* * All BIOS versions for the MSI K9A2 Platinum (MS-7376) * support 64bit DMA. * * BIOS versions earlier than 1.5 had the Manufacturer DMI * fields as "MICRO-STAR INTERANTIONAL CO.,LTD". * This spelling mistake was fixed in BIOS version 1.5, so * 1.5 and later have the Manufacturer as * "MICRO-STAR INTERNATIONAL CO.,LTD". * So try to match on DMI_BOARD_VENDOR of "MICRO-STAR INTER". * * BIOS versions earlier than 1.9 had a Board Product Name * DMI field of "MS-7376". This was changed to be * "K9A2 Platinum (MS-7376)" in version 1.9, but we can still * match on DMI_BOARD_NAME of "MS-7376". */ { .ident = "MSI K9A2 Platinum", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "MICRO-STAR INTER"), DMI_MATCH(DMI_BOARD_NAME, "MS-7376"), }, }, /* * All BIOS versions for the MSI K9AGM2 (MS-7327) support * 64bit DMA. * * This board also had the typo mentioned above in the * Manufacturer DMI field (fixed in BIOS version 1.5), so * match on DMI_BOARD_VENDOR of "MICRO-STAR INTER" again. */ { .ident = "MSI K9AGM2", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "MICRO-STAR INTER"), DMI_MATCH(DMI_BOARD_NAME, "MS-7327"), }, }, /* * All BIOS versions for the Asus M3A support 64bit DMA. * (all release versions from 0301 to 1206 were tested) */ { .ident = "ASUS M3A", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."), DMI_MATCH(DMI_BOARD_NAME, "M3A"), }, }, { } }; const struct dmi_system_id *match; int year, month, date; char buf[9]; match = dmi_first_match(sysids); if (pdev->bus->number != 0 || pdev->devfn != PCI_DEVFN(0x12, 0) || !match) return false; if (!match->driver_data) goto enable_64bit; dmi_get_date(DMI_BIOS_DATE, &year, &month, &date); snprintf(buf, sizeof(buf), "%04d%02d%02d", year, month, date); if (strcmp(buf, match->driver_data) >= 0) goto enable_64bit; else { dev_warn(&pdev->dev, "%s: BIOS too old, forcing 32bit DMA, update BIOS\n", match->ident); return false; } enable_64bit: dev_warn(&pdev->dev, "%s: enabling 64bit DMA\n", match->ident); return true; } static bool ahci_broken_system_poweroff(struct pci_dev *pdev) { static const struct dmi_system_id broken_systems[] = { { .ident = "HP Compaq nx6310", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq nx6310"), }, /* PCI slot number of the controller */ .driver_data = (void *)0x1FUL, }, { .ident = "HP Compaq 6720s", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Compaq 6720s"), }, /* PCI slot number of the controller */ .driver_data = (void *)0x1FUL, }, { } /* terminate list */ }; const struct dmi_system_id *dmi = dmi_first_match(broken_systems); if (dmi) { unsigned long slot = (unsigned long)dmi->driver_data; /* apply the quirk only to on-board controllers */ return slot == PCI_SLOT(pdev->devfn); } return false; } static bool ahci_broken_suspend(struct pci_dev *pdev) { static const struct dmi_system_id sysids[] = { /* * On HP dv[4-6] and HDX18 with earlier BIOSen, link * to the harddisk doesn't become online after * resuming from STR. Warn and fail suspend. * * http://bugzilla.kernel.org/show_bug.cgi?id=12276 * * Use dates instead of versions to match as HP is * apparently recycling both product and version * strings. * * http://bugzilla.kernel.org/show_bug.cgi?id=15462 */ { .ident = "dv4", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Pavilion dv4 Notebook PC"), }, .driver_data = "20090105", /* F.30 */ }, { .ident = "dv5", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Pavilion dv5 Notebook PC"), }, .driver_data = "20090506", /* F.16 */ }, { .ident = "dv6", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP Pavilion dv6 Notebook PC"), }, .driver_data = "20090423", /* F.21 */ }, { .ident = "HDX18", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "HP HDX18 Notebook PC"), }, .driver_data = "20090430", /* F.23 */ }, /* * Acer eMachines G725 has the same problem. BIOS * V1.03 is known to be broken. V3.04 is known to * work. Between, there are V1.06, V2.06 and V3.03 * that we don't have much idea about. For now, * blacklist anything older than V3.04. * * http://bugzilla.kernel.org/show_bug.cgi?id=15104 */ { .ident = "G725", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "eMachines"), DMI_MATCH(DMI_PRODUCT_NAME, "eMachines G725"), }, .driver_data = "20091216", /* V3.04 */ }, { } /* terminate list */ }; const struct dmi_system_id *dmi = dmi_first_match(sysids); int year, month, date; char buf[9]; if (!dmi || pdev->bus->number || pdev->devfn != PCI_DEVFN(0x1f, 2)) return false; dmi_get_date(DMI_BIOS_DATE, &year, &month, &date); snprintf(buf, sizeof(buf), "%04d%02d%02d", year, month, date); return strcmp(buf, dmi->driver_data) < 0; } static bool ahci_broken_online(struct pci_dev *pdev) { #define ENCODE_BUSDEVFN(bus, slot, func) \ (void *)(unsigned long)(((bus) << 8) | PCI_DEVFN((slot), (func))) static const struct dmi_system_id sysids[] = { /* * There are several gigabyte boards which use * SIMG5723s configured as hardware RAID. Certain * 5723 firmware revisions shipped there keep the link * online but fail to answer properly to SRST or * IDENTIFY when no device is attached downstream * causing libata to retry quite a few times leading * to excessive detection delay. * * As these firmwares respond to the second reset try * with invalid device signature, considering unknown * sig as offline works around the problem acceptably. */ { .ident = "EP45-DQ6", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "Gigabyte Technology Co., Ltd."), DMI_MATCH(DMI_BOARD_NAME, "EP45-DQ6"), }, .driver_data = ENCODE_BUSDEVFN(0x0a, 0x00, 0), }, { .ident = "EP45-DS5", .matches = { DMI_MATCH(DMI_BOARD_VENDOR, "Gigabyte Technology Co., Ltd."), DMI_MATCH(DMI_BOARD_NAME, "EP45-DS5"), }, .driver_data = ENCODE_BUSDEVFN(0x03, 0x00, 0), }, { } /* terminate list */ }; #undef ENCODE_BUSDEVFN const struct dmi_system_id *dmi = dmi_first_match(sysids); unsigned int val; if (!dmi) return false; val = (unsigned long)dmi->driver_data; return pdev->bus->number == (val >> 8) && pdev->devfn == (val & 0xff); } #ifdef CONFIG_ATA_ACPI static void ahci_gtf_filter_workaround(struct ata_host *host) { static const struct dmi_system_id sysids[] = { /* * Aspire 3810T issues a bunch of SATA enable commands * via _GTF including an invalid one and one which is * rejected by the device. Among the successful ones * is FPDMA non-zero offset enable which when enabled * only on the drive side leads to NCQ command * failures. Filter it out. */ { .ident = "Aspire 3810T", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Acer"), DMI_MATCH(DMI_PRODUCT_NAME, "Aspire 3810T"), }, .driver_data = (void *)ATA_ACPI_FILTER_FPDMA_OFFSET, }, { } }; const struct dmi_system_id *dmi = dmi_first_match(sysids); unsigned int filter; int i; if (!dmi) return; filter = (unsigned long)dmi->driver_data; dev_info(host->dev, "applying extra ACPI _GTF filter 0x%x for %s\n", filter, dmi->ident); for (i = 0; i < host->n_ports; i++) { struct ata_port *ap = host->ports[i]; struct ata_link *link; struct ata_device *dev; ata_for_each_link(link, ap, EDGE) ata_for_each_dev(dev, link, ALL) dev->gtf_filter |= filter; } } #else static inline void ahci_gtf_filter_workaround(struct ata_host *host) {} #endif static int ahci_init_interrupts(struct pci_dev *pdev, unsigned int n_ports, struct ahci_host_priv *hpriv) { int rc, nvec; if (hpriv->flags & AHCI_HFLAG_NO_MSI) goto intx; rc = pci_msi_vec_count(pdev); if (rc < 0) goto intx; /* * If number of MSIs is less than number of ports then Sharing Last * Message mode could be enforced. In this case assume that advantage * of multipe MSIs is negated and use single MSI mode instead. */ if (rc < n_ports) goto single_msi; nvec = rc; rc = pci_enable_msi_block(pdev, nvec); if (rc < 0) goto intx; else if (rc > 0) goto single_msi; /* fallback to single MSI mode if the controller enforced MRSM mode */ if (readl(hpriv->mmio + HOST_CTL) & HOST_MRSM) { pci_disable_msi(pdev); printk(KERN_INFO "ahci: MRSM is on, fallback to single MSI\n"); goto single_msi; } return nvec; single_msi: rc = pci_enable_msi(pdev); if (rc) goto intx; return 1; intx: pci_intx(pdev, 1); return 0; } /** * ahci_host_activate - start AHCI host, request IRQs and register it * @host: target ATA host * @irq: base IRQ number to request * @n_msis: number of MSIs allocated for this host * @irq_handler: irq_handler used when requesting IRQs * @irq_flags: irq_flags used when requesting IRQs * * Similar to ata_host_activate, but requests IRQs according to AHCI-1.1 * when multiple MSIs were allocated. That is one MSI per port, starting * from @irq. * * LOCKING: * Inherited from calling layer (may sleep). * * RETURNS: * 0 on success, -errno otherwise. */ int ahci_host_activate(struct ata_host *host, int irq, unsigned int n_msis) { int i, rc; /* Sharing Last Message among several ports is not supported */ if (n_msis < host->n_ports) return -EINVAL; rc = ata_host_start(host); if (rc) return rc; for (i = 0; i < host->n_ports; i++) { struct ahci_port_priv *pp = host->ports[i]->private_data; /* Do not receive interrupts sent by dummy ports */ if (!pp) { disable_irq(irq + i); continue; } rc = devm_request_threaded_irq(host->dev, irq + i, ahci_hw_interrupt, ahci_thread_fn, IRQF_SHARED, pp->irq_desc, host->ports[i]); if (rc) goto out_free_irqs; } for (i = 0; i < host->n_ports; i++) ata_port_desc(host->ports[i], "irq %d", irq + i); rc = ata_host_register(host, &ahci_sht); if (rc) goto out_free_all_irqs; return 0; out_free_all_irqs: i = host->n_ports; out_free_irqs: for (i--; i >= 0; i--) devm_free_irq(host->dev, irq + i, host->ports[i]); return rc; } static int ahci_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { unsigned int board_id = ent->driver_data; struct ata_port_info pi = ahci_port_info[board_id]; const struct ata_port_info *ppi[] = { &pi, NULL }; struct device *dev = &pdev->dev; struct ahci_host_priv *hpriv; struct ata_host *host; int n_ports, n_msis, i, rc; int ahci_pci_bar = AHCI_PCI_BAR_STANDARD; VPRINTK("ENTER\n"); WARN_ON((int)ATA_MAX_QUEUE > AHCI_MAX_CMDS); ata_print_version_once(&pdev->dev, DRV_VERSION); /* The AHCI driver can only drive the SATA ports, the PATA driver can drive them all so if both drivers are selected make sure AHCI stays out of the way */ if (pdev->vendor == PCI_VENDOR_ID_MARVELL && !marvell_enable) return -ENODEV; /* Apple BIOS on MCP89 prevents us using AHCI */ if (is_mcp89_apple(pdev)) ahci_mcp89_apple_enable(pdev); /* Promise's PDC42819 is a SAS/SATA controller that has an AHCI mode. * At the moment, we can only use the AHCI mode. Let the users know * that for SAS drives they're out of luck. */ if (pdev->vendor == PCI_VENDOR_ID_PROMISE) dev_info(&pdev->dev, "PDC42819 can only drive SATA devices with this driver\n"); /* Both Connext and Enmotus devices use non-standard BARs */ if (pdev->vendor == PCI_VENDOR_ID_STMICRO && pdev->device == 0xCC06) ahci_pci_bar = AHCI_PCI_BAR_STA2X11; else if (pdev->vendor == 0x1c44 && pdev->device == 0x8000) ahci_pci_bar = AHCI_PCI_BAR_ENMOTUS; /* acquire resources */ rc = pcim_enable_device(pdev); if (rc) return rc; if (pdev->vendor == PCI_VENDOR_ID_INTEL && (pdev->device == 0x2652 || pdev->device == 0x2653)) { u8 map; /* ICH6s share the same PCI ID for both piix and ahci * modes. Enabling ahci mode while MAP indicates * combined mode is a bad idea. Yield to ata_piix. */ pci_read_config_byte(pdev, ICH_MAP, &map); if (map & 0x3) { dev_info(&pdev->dev, "controller is in combined mode, can't enable AHCI mode\n"); return -ENODEV; } } /* AHCI controllers often implement SFF compatible interface. * Grab all PCI BARs just in case. */ rc = pcim_iomap_regions_request_all(pdev, 1 << ahci_pci_bar, DRV_NAME); if (rc == -EBUSY) pcim_pin_device(pdev); if (rc) return rc; hpriv = devm_kzalloc(dev, sizeof(*hpriv), GFP_KERNEL); if (!hpriv) return -ENOMEM; hpriv->flags |= (unsigned long)pi.private_data; /* MCP65 revision A1 and A2 can't do MSI */ if (board_id == board_ahci_mcp65 && (pdev->revision == 0xa1 || pdev->revision == 0xa2)) hpriv->flags |= AHCI_HFLAG_NO_MSI; /* SB800 does NOT need the workaround to ignore SERR_INTERNAL */ if (board_id == board_ahci_sb700 && pdev->revision >= 0x40) hpriv->flags &= ~AHCI_HFLAG_IGN_SERR_INTERNAL; /* only some SB600s can do 64bit DMA */ if (ahci_sb600_enable_64bit(pdev)) hpriv->flags &= ~AHCI_HFLAG_32BIT_ONLY; hpriv->mmio = pcim_iomap_table(pdev)[ahci_pci_bar]; /* save initial config */ ahci_pci_save_initial_config(pdev, hpriv); /* prepare host */ if (hpriv->cap & HOST_CAP_NCQ) { pi.flags |= ATA_FLAG_NCQ; /* * Auto-activate optimization is supposed to be * supported on all AHCI controllers indicating NCQ * capability, but it seems to be broken on some * chipsets including NVIDIAs. */ if (!(hpriv->flags & AHCI_HFLAG_NO_FPDMA_AA)) pi.flags |= ATA_FLAG_FPDMA_AA; /* * All AHCI controllers should be forward-compatible * with the new auxiliary field. This code should be * conditionalized if any buggy AHCI controllers are * encountered. */ pi.flags |= ATA_FLAG_FPDMA_AUX; } if (hpriv->cap & HOST_CAP_PMP) pi.flags |= ATA_FLAG_PMP; ahci_set_em_messages(hpriv, &pi); if (ahci_broken_system_poweroff(pdev)) { pi.flags |= ATA_FLAG_NO_POWEROFF_SPINDOWN; dev_info(&pdev->dev, "quirky BIOS, skipping spindown on poweroff\n"); } if (ahci_broken_suspend(pdev)) { hpriv->flags |= AHCI_HFLAG_NO_SUSPEND; dev_warn(&pdev->dev, "BIOS update required for suspend/resume\n"); } if (ahci_broken_online(pdev)) { hpriv->flags |= AHCI_HFLAG_SRST_TOUT_IS_OFFLINE; dev_info(&pdev->dev, "online status unreliable, applying workaround\n"); } /* CAP.NP sometimes indicate the index of the last enabled * port, at other times, that of the last possible port, so * determining the maximum port number requires looking at * both CAP.NP and port_map. */ n_ports = max(ahci_nr_ports(hpriv->cap), fls(hpriv->port_map)); n_msis = ahci_init_interrupts(pdev, n_ports, hpriv); if (n_msis > 1) hpriv->flags |= AHCI_HFLAG_MULTI_MSI; host = ata_host_alloc_pinfo(&pdev->dev, ppi, n_ports); if (!host) return -ENOMEM; host->private_data = hpriv; if (!(hpriv->cap & HOST_CAP_SSS) || ahci_ignore_sss) host->flags |= ATA_HOST_PARALLEL_SCAN; else dev_info(&pdev->dev, "SSS flag set, parallel bus scan disabled\n"); if (pi.flags & ATA_FLAG_EM) ahci_reset_em(host); for (i = 0; i < host->n_ports; i++) { struct ata_port *ap = host->ports[i]; ata_port_pbar_desc(ap, ahci_pci_bar, -1, "abar"); ata_port_pbar_desc(ap, ahci_pci_bar, 0x100 + ap->port_no * 0x80, "port"); /* set enclosure management message type */ if (ap->flags & ATA_FLAG_EM) ap->em_message_type = hpriv->em_msg_type; /* disabled/not-implemented port */ if (!(hpriv->port_map & (1 << i))) ap->ops = &ata_dummy_port_ops; } /* apply workaround for ASUS P5W DH Deluxe mainboard */ ahci_p5wdh_workaround(host); /* apply gtf filter quirk */ ahci_gtf_filter_workaround(host); /* initialize adapter */ rc = ahci_configure_dma_masks(pdev, hpriv->cap & HOST_CAP_64); if (rc) return rc; rc = ahci_pci_reset_controller(host); if (rc) return rc; ahci_pci_init_controller(host); ahci_pci_print_info(host); pci_set_master(pdev); if (hpriv->flags & AHCI_HFLAG_MULTI_MSI) return ahci_host_activate(host, pdev->irq, n_msis); return ata_host_activate(host, pdev->irq, ahci_interrupt, IRQF_SHARED, &ahci_sht); } module_pci_driver(ahci_pci_driver); MODULE_AUTHOR("Jeff Garzik"); MODULE_DESCRIPTION("AHCI SATA low-level driver"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(pci, ahci_pci_tbl); MODULE_VERSION(DRV_VERSION);
WesternStar/tilinux
drivers/ata/ahci.c
C
gpl-2.0
49,689
/* * Copyright (c) 2012-2017 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ /* * This file limProcessMlmMessages.cc contains the code * for processing MLM request messages. * Author: Chandra Modumudi * Date: 02/12/02 * History:- * Date Modified by Modification Information * -------------------------------------------------------------------- * */ #include "palTypes.h" #include "wniCfg.h" #include "aniGlobal.h" #include "sirApi.h" #include "sirParams.h" #include "cfgApi.h" #include "schApi.h" #include "utilsApi.h" #include "limUtils.h" #include "limAssocUtils.h" #include "limPropExtsUtils.h" #include "limSecurityUtils.h" #include "limSendMessages.h" #include "pmmApi.h" #include "limSendMessages.h" //#include "limSessionUtils.h" #include "limSessionUtils.h" #ifdef WLAN_FEATURE_VOWIFI_11R #include <limFT.h> #endif #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM #include "vos_diag_core_log.h" #endif #ifdef WLAN_FEATURE_LFR_MBB #include "lim_mbb.h" #endif // MLM REQ processing function templates static void limProcessMlmStartReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmScanReq(tpAniSirGlobal, tANI_U32 *); #ifdef FEATURE_OEM_DATA_SUPPORT static void limProcessMlmOemDataReq(tpAniSirGlobal, tANI_U32 *); #endif static void limProcessMlmJoinReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmAuthReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmAssocReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmReassocReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmDisassocReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmDeauthReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmSetKeysReq(tpAniSirGlobal, tANI_U32 *); static void limProcessMlmAddBAReq( tpAniSirGlobal, tANI_U32 * ); static void limProcessMlmAddBARsp( tpAniSirGlobal, tANI_U32 * ); static void limProcessMlmDelBAReq( tpAniSirGlobal, tANI_U32 * ); // MLM Timeout event handler templates static void limProcessMinChannelTimeout(tpAniSirGlobal); static void limProcessMaxChannelTimeout(tpAniSirGlobal); static void limProcessPeriodicProbeReqTimer(tpAniSirGlobal pMac); static void limProcessJoinFailureTimeout(tpAniSirGlobal); static void limProcessAuthFailureTimeout(tpAniSirGlobal); static void limProcessAuthRspTimeout(tpAniSirGlobal, tANI_U32); static void limProcessAssocFailureTimeout(tpAniSirGlobal, tANI_U32); static void limProcessPeriodicJoinProbeReqTimer(tpAniSirGlobal); static void limProcessAuthRetryTimer(tpAniSirGlobal); static void limProcessMlmRemoveKeyReq(tpAniSirGlobal pMac, tANI_U32 * pMsgBuf); void limSetChannel(tpAniSirGlobal pMac, tANI_U8 channel, tANI_U8 secChannelOffset, tPowerdBm maxTxPower, tANI_U8 peSessionId); #define IS_MLM_SCAN_REQ_BACKGROUND_SCAN_AGGRESSIVE(pMac) (pMac->lim.gpLimMlmScanReq->backgroundScanMode == eSIR_AGGRESSIVE_BACKGROUND_SCAN) #define IS_MLM_SCAN_REQ_BACKGROUND_SCAN_NORMAL(pMac) (pMac->lim.gpLimMlmScanReq->backgroundScanMode == eSIR_NORMAL_BACKGROUND_SCAN) /** * limProcessMlmReqMessages() * *FUNCTION: * This function is called by limPostMlmMessage(). This * function handles MLM primitives invoked by SME. * *LOGIC: * Depending on the message type, corresponding function will be * called. * *ASSUMPTIONS: * 1. Upon receiving Beacon in WT_JOIN_STATE, MLM module invokes * APIs exposed by Beacon Processing module for setting parameters * at MAC hardware. * 2. If attempt to Reassociate with an AP fails, link with current * AP is restored back. * *NOTE: * * @param pMac Pointer to Global MAC structure * @param msgType Indicates the MLM primitive message type * @param *pMsgBuf A pointer to the MLM message buffer * * @return None */ void limProcessMlmReqMessages(tpAniSirGlobal pMac, tpSirMsgQ Msg) { switch (Msg->type) { case LIM_MLM_START_REQ: limProcessMlmStartReq(pMac, Msg->bodyptr); break; case LIM_MLM_SCAN_REQ: limProcessMlmScanReq(pMac, Msg->bodyptr); break; #ifdef FEATURE_OEM_DATA_SUPPORT case LIM_MLM_OEM_DATA_REQ: limProcessMlmOemDataReq(pMac, Msg->bodyptr); break; #endif case LIM_MLM_JOIN_REQ: limProcessMlmJoinReq(pMac, Msg->bodyptr); break; case LIM_MLM_AUTH_REQ: limProcessMlmAuthReq(pMac, Msg->bodyptr); break; case LIM_MLM_ASSOC_REQ: limProcessMlmAssocReq(pMac, Msg->bodyptr); break; case LIM_MLM_REASSOC_REQ: limProcessMlmReassocReq(pMac, Msg->bodyptr); break; case LIM_MLM_DISASSOC_REQ: limProcessMlmDisassocReq(pMac, Msg->bodyptr); break; case LIM_MLM_DEAUTH_REQ: limProcessMlmDeauthReq(pMac, Msg->bodyptr); break; case LIM_MLM_SETKEYS_REQ: limProcessMlmSetKeysReq(pMac, Msg->bodyptr); break; case LIM_MLM_REMOVEKEY_REQ: limProcessMlmRemoveKeyReq(pMac, Msg->bodyptr); break; case SIR_LIM_MIN_CHANNEL_TIMEOUT: limProcessMinChannelTimeout(pMac); break; case SIR_LIM_MAX_CHANNEL_TIMEOUT: limProcessMaxChannelTimeout(pMac); break; case SIR_LIM_PERIODIC_PROBE_REQ_TIMEOUT: limProcessPeriodicProbeReqTimer(pMac); break; case SIR_LIM_JOIN_FAIL_TIMEOUT: limProcessJoinFailureTimeout(pMac); break; case SIR_LIM_PERIODIC_JOIN_PROBE_REQ_TIMEOUT: limProcessPeriodicJoinProbeReqTimer(pMac); break; case SIR_LIM_AUTH_FAIL_TIMEOUT: limProcessAuthFailureTimeout(pMac); break; case SIR_LIM_AUTH_RSP_TIMEOUT: limProcessAuthRspTimeout(pMac, Msg->bodyval); break; case SIR_LIM_ASSOC_FAIL_TIMEOUT: limProcessAssocFailureTimeout(pMac, Msg->bodyval); break; #ifdef WLAN_FEATURE_VOWIFI_11R case SIR_LIM_FT_PREAUTH_RSP_TIMEOUT:limProcessFTPreauthRspTimeout(pMac); break; #endif #ifdef WLAN_FEATURE_LFR_MBB case SIR_LIM_PREAUTH_MBB_RSP_TIMEOUT: lim_process_preauth_mbb_rsp_timeout(pMac); break; case SIR_LIM_REASSOC_MBB_RSP_TIMEOUT: lim_process_reassoc_mbb_rsp_timeout(pMac); break; #endif case SIR_LIM_REMAIN_CHN_TIMEOUT: limProcessRemainOnChnTimeout(pMac); break; case SIR_LIM_INSERT_SINGLESHOT_NOA_TIMEOUT: limProcessInsertSingleShotNOATimeout(pMac); break; case SIR_LIM_CONVERT_ACTIVE_CHANNEL_TO_PASSIVE: limConvertActiveChannelToPassiveChannel(pMac); break; case SIR_LIM_AUTH_RETRY_TIMEOUT: limProcessAuthRetryTimer(pMac); break; case SIR_LIM_DISASSOC_ACK_TIMEOUT: limProcessDisassocAckTimeout(pMac); break; case SIR_LIM_DEAUTH_ACK_TIMEOUT: limProcessDeauthAckTimeout(pMac); break; case SIR_LIM_SAP_ECSA_TIMEOUT: lim_process_ap_ecsa_timeout(pMac);break; case LIM_MLM_ADDBA_REQ: limProcessMlmAddBAReq( pMac, Msg->bodyptr ); break; case LIM_MLM_ADDBA_RSP: limProcessMlmAddBARsp( pMac, Msg->bodyptr ); break; case LIM_MLM_DELBA_REQ: limProcessMlmDelBAReq( pMac, Msg->bodyptr ); break; case LIM_MLM_TSPEC_REQ: default: break; } // switch (msgType) } /*** end limProcessMlmReqMessages() ***/ /** * limSetScanMode() * *FUNCTION: * This function is called to setup system into Scan mode * *LOGIC: * NA * *ASSUMPTIONS: * NA * *NOTE: * * @param pMac - Pointer to Global MAC structure * @return None */ void limSetScanMode(tpAniSirGlobal pMac) { tSirLinkTrafficCheck checkTraffic; /// Set current scan channel id to the first in the channel list pMac->lim.gLimCurrentScanChannelId = 0; if ( IS_MLM_SCAN_REQ_BACKGROUND_SCAN_AGGRESSIVE(pMac) ) { checkTraffic = eSIR_DONT_CHECK_LINK_TRAFFIC_BEFORE_SCAN; } else if (IS_MLM_SCAN_REQ_BACKGROUND_SCAN_NORMAL(pMac)) { checkTraffic = eSIR_CHECK_LINK_TRAFFIC_BEFORE_SCAN; } else checkTraffic = eSIR_CHECK_ROAMING_SCAN; limLog(pMac, LOG1, FL("Calling limSendHalInitScanReq")); limSendHalInitScanReq(pMac, eLIM_HAL_INIT_SCAN_WAIT_STATE, checkTraffic); return ; } /*** end limSetScanMode() ***/ //WLAN_SUSPEND_LINK Related /* limIsLinkSuspended() * *FUNCTION: * This function returns is link is suspended or not. * *LOGIC: * Since Suspend link uses init scan, it just returns * gLimSystemInScanLearnMode flag. * *ASSUMPTIONS: * NA * *NOTE: * * @param pMac - Pointer to Global MAC structure * @return None */ tANI_U8 limIsLinkSuspended(tpAniSirGlobal pMac) { return pMac->lim.gLimSystemInScanLearnMode; } /** * limSuspendLink() * *FUNCTION: * This function is called to suspend traffic. Internally this function uses WDA_INIT_SCAN_REQ. * *LOGIC: * NA * *ASSUMPTIONS: * NA * *NOTE: * * @param pMac - Pointer to Global MAC structure * @param trafficCheck - Takes value from enum tSirLinkTrafficCheck. * @param callback - Callback function to be called after suspending the link. * @param data - Pointer to any buffer that will be passed to callback. * @return None */ void limSuspendLink(tpAniSirGlobal pMac, tSirLinkTrafficCheck trafficCheck, SUSPEND_RESUME_LINK_CALLBACK callback, tANI_U32 *data) { if( NULL == callback ) { limLog( pMac, LOGE, "%s:%d: Invalid parameters", __func__, __LINE__ ); return; } if( pMac->lim.gpLimSuspendCallback || pMac->lim.gLimSystemInScanLearnMode ) { limLog( pMac, LOGE, FL("Something is wrong, SuspendLinkCbk:%pK " "IsSystemInScanLearnMode:%d"), pMac->lim.gpLimSuspendCallback, pMac->lim.gLimSystemInScanLearnMode ); callback( pMac, eHAL_STATUS_FAILURE, data ); return; } pMac->lim.gLimSystemInScanLearnMode = 1; pMac->lim.gpLimSuspendCallback = callback; pMac->lim.gpLimSuspendData = data; limSendHalInitScanReq(pMac, eLIM_HAL_SUSPEND_LINK_WAIT_STATE, trafficCheck ); WDA_TrafficStatsTimerActivate(FALSE); } /** * limResumeLink() * *FUNCTION: * This function is called to Resume traffic after a suspend. Internally this function uses WDA_FINISH_SCAN_REQ. * *LOGIC: * NA * *ASSUMPTIONS: * NA * *NOTE: * * @param pMac - Pointer to Global MAC structure * @param callback - Callback function to be called after Resuming the link. * @param data - Pointer to any buffer that will be passed to callback. * @return None */ void limResumeLink(tpAniSirGlobal pMac, SUSPEND_RESUME_LINK_CALLBACK callback, tANI_U32 *data) { if( NULL == callback ) { limLog( pMac, LOGE, "%s:%d: Invalid parameters", __func__, __LINE__ ); return; } if( pMac->lim.gpLimResumeCallback ) { limLog( pMac, LOGE, "%s:%d: gLimResumeLink callback is not NULL...something is wrong", __func__, __LINE__ ); callback( pMac, eHAL_STATUS_FAILURE, data ); return; } pMac->lim.gpLimResumeCallback = callback; pMac->lim.gpLimResumeData = data; /* eLIM_HAL_IDLE_SCAN_STATE state indicate limSendHalInitScanReq failed. * In case limSendHalInitScanReq is success, Scanstate would be * eLIM_HAL_SUSPEND_LINK_STATE */ if( eLIM_HAL_IDLE_SCAN_STATE != pMac->lim.gLimHalScanState ) { limSendHalFinishScanReq(pMac, eLIM_HAL_RESUME_LINK_WAIT_STATE ); } else { limLog(pMac, LOGW, FL("Init Scan failed, we will not call finish scan." " calling the callback with failure status")); pMac->lim.gpLimResumeCallback( pMac, eSIR_FAILURE, pMac->lim.gpLimResumeData); pMac->lim.gpLimResumeCallback = NULL; pMac->lim.gpLimResumeData = NULL; pMac->lim.gLimSystemInScanLearnMode = 0; } if(limIsInMCC(pMac)) { WDA_TrafficStatsTimerActivate(TRUE); } } //end WLAN_SUSPEND_LINK Related /** * * limChangeChannelWithCallback() * * FUNCTION: * This function is called to change channel and perform off channel operation * if required. The caller registers a callback to be called at the end of the * channel change. * */ void limChangeChannelWithCallback(tpAniSirGlobal pMac, tANI_U8 newChannel, CHANGE_CHANNEL_CALLBACK callback, tANI_U32 *cbdata, tpPESession psessionEntry) { // Sanity checks for the current and new channel #if defined WLAN_VOWIFI_DEBUG PELOGE(limLog( pMac, LOGE, "Switching channel to %d", newChannel);) #endif psessionEntry->channelChangeReasonCode=LIM_SWITCH_CHANNEL_OPERATION; pMac->lim.gpchangeChannelCallback = callback; pMac->lim.gpchangeChannelData = cbdata; limSendSwitchChnlParams(pMac, newChannel, PHY_SINGLE_CHANNEL_CENTERED, psessionEntry->maxTxPower, psessionEntry->peSessionId); return; } /** * limContinuePostChannelScan() * *FUNCTION: * This function is called to scan the current channel. * *LOGIC: * *ASSUMPTIONS: * NA * *NOTE: * NA * * @param pMac - Pointer to Global MAC structure * * @return None */ void limContinuePostChannelScan(tpAniSirGlobal pMac) { tANI_U8 channelNum; tANI_U8 i = 0; tSirRetStatus status = eSIR_SUCCESS; if( pMac->lim.abortScan || (NULL == pMac->lim.gpLimMlmScanReq ) || (pMac->lim.gLimCurrentScanChannelId > (tANI_U32)(pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1))) { pMac->lim.abortScan = 0; limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); //Set the resume channel to Any valid channel (invalid). //This will instruct HAL to set it to any previous valid channel. peSetResumeChannel(pMac, 0, 0); limSendHalFinishScanReq(pMac, eLIM_HAL_FINISH_SCAN_WAIT_STATE); return; } channelNum = limGetCurrentScanChannel(pMac); if (channelNum == limGetCurrentOperatingChannel(pMac) && limIsconnectedOnDFSChannel(channelNum)) { limCovertChannelScanType(pMac, channelNum, true); } if ((pMac->lim.gpLimMlmScanReq->scanType == eSIR_ACTIVE_SCAN) && (limActiveScanAllowed(pMac, channelNum))) { TX_TIMER *periodicScanTimer; pMac->lim.probeCounter++; /* Prepare and send Probe Request frame for all * the SSIDs present in the saved MLM */ do { tSirMacAddr gSelfMacAddr; /* Send self MAC as src address if * MAC spoof is not enabled OR * spoofMacAddr is all 0 OR * disableP2PMacSpoof is enabled and scan is P2P scan * else use the spoofMac as src address */ if ((pMac->lim.isSpoofingEnabled != TRUE) || (TRUE == vos_is_macaddr_zero((v_MACADDR_t *)&pMac->lim.spoofMacAddr)) || (pMac->roam.configParam.disableP2PMacSpoofing && pMac->lim.gpLimMlmScanReq->p2pSearch)) { vos_mem_copy(gSelfMacAddr, pMac->lim.gSelfMacAddr, VOS_MAC_ADDRESS_LEN); } else { vos_mem_copy(gSelfMacAddr, pMac->lim.spoofMacAddr, VOS_MAC_ADDRESS_LEN); } limLog(pMac, LOG1, FL(" Mac Addr "MAC_ADDRESS_STR " used in sending ProbeReq number %d, for SSID %s on channel: %d"), MAC_ADDR_ARRAY(gSelfMacAddr) ,i, pMac->lim.gpLimMlmScanReq->ssId[i].ssId, channelNum); // include additional IE if there is status = limSendProbeReqMgmtFrame( pMac, &pMac->lim.gpLimMlmScanReq->ssId[i], pMac->lim.gpLimMlmScanReq->bssId, channelNum, gSelfMacAddr, pMac->lim.gpLimMlmScanReq->dot11mode, pMac->lim.gpLimMlmScanReq->uIEFieldLen, (tANI_U8 *)(pMac->lim.gpLimMlmScanReq)+pMac->lim.gpLimMlmScanReq->uIEFieldOffset); if ( status != eSIR_SUCCESS) { PELOGE(limLog(pMac, LOGE, FL("send ProbeReq failed for SSID %s on channel: %d"), pMac->lim.gpLimMlmScanReq->ssId[i].ssId, channelNum);) limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); return; } i++; } while (i < pMac->lim.gpLimMlmScanReq->numSsid); { #if defined WLAN_FEATURE_VOWIFI //If minChannelTime is set to zero, SME is requesting scan to not use min channel timer. //This is used in 11k to request for beacon measurement request with a fixed duration in //max channel time. if( pMac->lim.gpLimMlmScanReq->minChannelTime != 0 ) { #endif /// TXP has sent Probe Request /// Activate minChannelTimer limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); #ifdef GEN6_TODO /* revisit this piece of code to assign the appropriate sessionId * below priority - LOW/might not be needed */ pMac->lim.limTimers.gLimMinChannelTimer.sessionId = sessionId; #endif if (tx_timer_activate(&pMac->lim.limTimers.gLimMinChannelTimer) != TX_SUCCESS) { limLog(pMac, LOGE, FL("could not start min channel timer")); limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); return; } // Initialize max timer too limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); #if defined WLAN_FEATURE_VOWIFI } else { #if defined WLAN_VOWIFI_DEBUG PELOGE(limLog( pMac, LOGE, "Min channel time == 0, Use only max chan timer" );) #endif //No Need to start Min channel timer. Start Max Channel timer. limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); if (tx_timer_activate(&pMac->lim.limTimers.gLimMaxChannelTimer) == TX_TIMER_ERROR) { /// Could not activate max channel timer. // Log error limLog(pMac,LOGE, FL("could not start max channel timer")); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); return; } } #endif } /* Start peridic timer which will trigger probe req based on min/max channel timer */ periodicScanTimer = &pMac->lim.limTimers.gLimPeriodicProbeReqTimer; limDeactivateAndChangeTimer(pMac, eLIM_PERIODIC_PROBE_REQ_TIMER); if (tx_timer_activate(periodicScanTimer) != TX_SUCCESS) { limLog(pMac, LOGE, FL("could not start periodic probe req " "timer")); } periodicScanTimer->sessionId = channelNum; } else { tANI_U32 val; limLog(pMac, LOG1, FL("START PASSIVE Scan chan %d"), channelNum); /// Passive Scanning. Activate maxChannelTimer if (tx_timer_deactivate(&pMac->lim.limTimers.gLimMaxChannelTimer) != TX_SUCCESS) { // Could not deactivate max channel timer. // Log error limLog(pMac, LOGE, FL("Unable to deactivate max channel timer")); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); } else { if (pMac->miracast_mode) { val = DEFAULT_MIN_CHAN_TIME_DURING_MIRACAST + DEFAULT_MAX_CHAN_TIME_DURING_MIRACAST; } else if (wlan_cfgGetInt(pMac, WNI_CFG_PASSIVE_MAXIMUM_CHANNEL_TIME, &val) != eSIR_SUCCESS) { /** * Could not get max channel value * from CFG. Log error. */ limLog(pMac, LOGE, FL("could not retrieve passive max chan value, Use Def val")); val= WNI_CFG_PASSIVE_MAXIMUM_CHANNEL_TIME_STADEF; } val = SYS_MS_TO_TICKS(val); if (tx_timer_change(&pMac->lim.limTimers.gLimMaxChannelTimer, val, 0) != TX_SUCCESS) { // Could not change max channel timer. // Log error limLog(pMac, LOGE, FL("Unable to change max channel timer")); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); return; } else if (tx_timer_activate(&pMac->lim.limTimers.gLimMaxChannelTimer) != TX_SUCCESS) { limLog(pMac, LOGE, FL("could not start max channel timer")); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); return; } } // Wait for Beacons to arrive } // if (pMac->lim.gLimMlmScanReq->scanType == eSIR_ACTIVE_SCAN) limAddScanChannelInfo(pMac, channelNum); return; } /* limCovertChannelScanType() * *FUNCTION: * This function is called to get the list, change the channel type and set again. * *LOGIC: * *ASSUMPTIONS: * NA * *NOTE: If a channel is ACTIVE, this function will make it as PASSIVE * If a channel is PASSIVE, this fucntion will make it as ACTIVE * NA * * @param pMac - Pointer to Global MAC structure * channelNum - Channel which need to be convert PassiveToActive - Boolean flag to convert channel * * @return None */ void limCovertChannelScanType(tpAniSirGlobal pMac,tANI_U8 channelNum, tANI_BOOLEAN passiveToActive) { tANI_U32 i; tANI_U8 channelPair[WNI_CFG_SCAN_CONTROL_LIST_LEN]; tANI_U32 len = WNI_CFG_SCAN_CONTROL_LIST_LEN; if (wlan_cfgGetStr(pMac, WNI_CFG_SCAN_CONTROL_LIST, channelPair, &len) != eSIR_SUCCESS) { PELOGE(limLog(pMac, LOGE, FL("Unable to get scan control list"));) return ; } if (len > WNI_CFG_SCAN_CONTROL_LIST_LEN) { limLog(pMac, LOGE, FL("Invalid scan control list length:%d"), len); return ; } if (pMac->fActiveScanOnDFSChannels) { limLog(pMac, LOG1, FL("DFS feature triggered," "block scan type conversion")); return ; } for (i=0; (i+1) < len; i+=2) { if (channelPair[i] == channelNum) { if ((eSIR_PASSIVE_SCAN == channelPair[i+1]) && TRUE == passiveToActive) { limLog(pMac, LOG1, FL("Channel %d changed from Passive to Active"), channelNum); channelPair[i+1] = eSIR_ACTIVE_SCAN; break ; } if ((eSIR_ACTIVE_SCAN == channelPair[i+1]) && FALSE == passiveToActive) { limLog(pMac, LOG1, FL("Channel %d changed from Active to Passive"), channelNum); channelPair[i+1] = eSIR_PASSIVE_SCAN; break ; } } } cfgSetStrNotify(pMac, WNI_CFG_SCAN_CONTROL_LIST, (tANI_U8 *)channelPair, len, FALSE); return ; } /* limSetDFSChannelList() * *FUNCTION: * This function is called to convert DFS channel list to active channel list when any * beacon is present on that channel. This function store time for passive channels * which help to know that for how much time channel has been passive. * *LOGIC: * *ASSUMPTIONS: * NA * *NOTE: If a channel is ACTIVE, it won't store any time * If a channel is PAssive, it will store time as timestamp * NA * * @param pMac - Pointer to Global MAC structure * dfsChannelList - DFS channel list. * @return None */ void limSetDFSChannelList(tpAniSirGlobal pMac,tANI_U8 channelNum, tSirDFSChannelList *dfsChannelList) { tANI_BOOLEAN passiveToActive = TRUE; tANI_U32 cfgVal; if (eSIR_SUCCESS == wlan_cfgGetInt(pMac, WNI_CFG_ACTIVE_PASSIVE_CON, &cfgVal)) { limLog(pMac, LOG1, FL("WNI_CFG_ACTIVE_PASSIVE_CON: %d"), cfgVal); if (!cfgVal) return; } if ((1 <= channelNum) && (165 >= channelNum)) { if (eANI_BOOLEAN_TRUE == limIsconnectedOnDFSChannel(channelNum)) { if (dfsChannelList->timeStamp[channelNum] == 0) { //Received first beacon; Convert DFS channel to Active channel. limLog(pMac, LOG1, FL("Received first beacon on DFS channel: %d"), channelNum); limCovertChannelScanType(pMac,channelNum, passiveToActive); } if (!pMac->fActiveScanOnDFSChannels && dfsChannelList->timeStamp[channelNum] && !limActiveScanAllowed(pMac, channelNum)) limLog(pMac, LOGE, FL("Received beacon on DFS channel %d with dfs time stamp %lu, but channel is still DFS"), channelNum, dfsChannelList->timeStamp[channelNum]); dfsChannelList->timeStamp[channelNum] = vos_timer_get_system_time(); } else { return; } if (!tx_timer_running(&pMac->lim.limTimers.gLimActiveToPassiveChannelTimer)) { tx_timer_activate(&pMac->lim.limTimers.gLimActiveToPassiveChannelTimer); } } else { PELOGE(limLog(pMac, LOGE, FL("Invalid Channel: %d"), channelNum);) return; } return; } void limDoSendAuthMgmtFrame(tpAniSirGlobal pMac, tpPESession psessionEntry) { tSirMacAuthFrameBody authFrameBody; //Prepare & send Authentication frame authFrameBody.authAlgoNumber = (tANI_U8) pMac->lim.gpLimMlmAuthReq->authType; authFrameBody.authTransactionSeqNumber = SIR_MAC_AUTH_FRAME_1; authFrameBody.authStatusCode = 0; pMac->authAckStatus = LIM_AUTH_ACK_NOT_RCD; limSendAuthMgmtFrame(pMac, &authFrameBody, pMac->lim.gpLimMlmAuthReq->peerMacAddr, LIM_NO_WEP_IN_FC, psessionEntry, eSIR_TRUE); if (tx_timer_activate(&pMac->lim.limTimers.gLimAuthFailureTimer) != TX_SUCCESS) { //Could not start Auth failure timer. //Log error limLog(pMac, LOGP, FL("could not start Auth failure timer")); //Cleanup as if auth timer expired limProcessAuthFailureTimeout(pMac); } else { MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_AUTH_RETRY_TIMER)); //Activate Auth Retry timer if (tx_timer_activate (&pMac->lim.limTimers.gLimPeriodicAuthRetryTimer) != TX_SUCCESS) { limLog(pMac, LOGP, FL("could not activate Auth Retry timer")); } } return; } /* * Creates a Raw frame to be sent before every Scan, if required. * If only infra link is active (mlmState = Link Estb), then send Data Null * If only BT-AMP-AP link is active(mlmState = BSS_STARTED), then send CTS2Self frame. * If only BT-AMP-STA link is active(mlmState = BSS_STARTED or Link Est) then send CTS2Self * If Only IBSS link is active, then send CTS2Self * for concurrent scenario: Infra+BT or Infra+IBSS, always send CTS2Self, no need to send Data Null * */ static void __limCreateInitScanRawFrame(tpAniSirGlobal pMac, tpInitScanParams pInitScanParam) { tANI_U8 i; pInitScanParam->scanEntry.activeBSScnt = 0; /* Don't send CTS to self as we have issue with BTQM queues where BTQM can * not handle transmition of CTS2self frames. Sending CTS 2 self at this * juncture also doesn't serve much purpose as probe request frames go out * immediately, No need to notify BSS in IBSS case. * */ for(i =0; i < pMac->lim.maxBssId; i++) { if(pMac->lim.gpSession[i].valid == TRUE) { if(pMac->lim.gpSession[i].limMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE) { if ((pMac->lim.gpSession[i].limSystemRole != eLIM_BT_AMP_STA_ROLE) && (pInitScanParam->scanEntry.activeBSScnt < HAL_NUM_BSSID)) { pInitScanParam->scanEntry.bssIdx[pInitScanParam->scanEntry.activeBSScnt] = pMac->lim.gpSession[i].bssIdx; pInitScanParam->scanEntry.activeBSScnt++; } } else if( (eLIM_AP_ROLE == pMac->lim.gpSession[i].limSystemRole ) && ( VOS_P2P_GO_MODE == pMac->lim.gpSession[i].pePersona ) ) { pInitScanParam->useNoA = TRUE; } } } if (pInitScanParam->scanEntry.activeBSScnt) { pInitScanParam->notifyBss = TRUE; pInitScanParam->frameType = SIR_MAC_DATA_FRAME; pInitScanParam->frameLength = 0; } } /* * Creates a Raw frame to be sent during finish scan, if required. * Send data null frame, only when there is just one session active and that session is * in 'link Estb' state. * if more than one session is active, don't send any frame. * for concurrent scenario: Infra+BT or Infra+IBSS, no need to send Data Null * */ static void __limCreateFinishScanRawFrame(tpAniSirGlobal pMac, tpFinishScanParams pFinishScanParam) { tANI_U8 i; pFinishScanParam->scanEntry.activeBSScnt = 0; for(i =0; i < pMac->lim.maxBssId; i++) { if(pMac->lim.gpSession[i].valid == TRUE) { if(pMac->lim.gpSession[i].limMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE) { //BT-STA can either be in LINK-ESTB state or BSS_STARTED State //for BT, need to send CTS2Self if ((pMac->lim.gpSession[i].limSystemRole != eLIM_BT_AMP_STA_ROLE) && (pFinishScanParam->scanEntry.activeBSScnt < HAL_NUM_BSSID)) { pFinishScanParam->scanEntry.bssIdx[pFinishScanParam->scanEntry.activeBSScnt] = pMac->lim.gpSession[i].bssIdx; pFinishScanParam->scanEntry.activeBSScnt++; } } } } if (pFinishScanParam->scanEntry.activeBSScnt) { pFinishScanParam->notifyBss = TRUE; pFinishScanParam->frameType = SIR_MAC_DATA_FRAME; pFinishScanParam->frameLength = 0; } } void limSendHalInitScanReq(tpAniSirGlobal pMac, tLimLimHalScanState nextState, tSirLinkTrafficCheck trafficCheck) { tSirMsgQ msg; tpInitScanParams pInitScanParam; tSirRetStatus rc = eSIR_SUCCESS; pInitScanParam = vos_mem_malloc(sizeof(*pInitScanParam)); if ( NULL == pInitScanParam ) { PELOGW(limLog(pMac, LOGW, FL("AllocateMemory() failed"));) goto error; } /*Initialize the pInitScanParam with 0*/ vos_mem_set((tANI_U8 *)pInitScanParam, sizeof(*pInitScanParam), 0); msg.type = WDA_INIT_SCAN_REQ; msg.bodyptr = pInitScanParam; msg.bodyval = 0; vos_mem_set((tANI_U8 *)&pInitScanParam->macMgmtHdr, sizeof(tSirMacMgmtHdr), 0); if (nextState == eLIM_HAL_INIT_LEARN_WAIT_STATE) { pInitScanParam->notifyBss = TRUE; pInitScanParam->notifyHost = FALSE; if (eSIR_CHECK_ROAMING_SCAN == trafficCheck) { pInitScanParam->scanMode = eHAL_SYS_MODE_ROAM_SCAN; } else { pInitScanParam->scanMode = eHAL_SYS_MODE_LEARN; } pInitScanParam->frameType = SIR_MAC_CTRL_CTS; __limCreateInitScanRawFrame(pMac, pInitScanParam); pInitScanParam->checkLinkTraffic = trafficCheck; } else { if(nextState == eLIM_HAL_SUSPEND_LINK_WAIT_STATE) { if (eSIR_CHECK_ROAMING_SCAN == trafficCheck) { pInitScanParam->scanMode = eHAL_SYS_MODE_ROAM_SUSPEND_LINK; } else { pInitScanParam->scanMode = eHAL_SYS_MODE_SUSPEND_LINK; } } else { if (eSIR_CHECK_ROAMING_SCAN == trafficCheck) { pInitScanParam->scanMode = eHAL_SYS_MODE_ROAM_SCAN; } else { pInitScanParam->scanMode = eHAL_SYS_MODE_SCAN; } } __limCreateInitScanRawFrame(pMac, pInitScanParam); if (pInitScanParam->useNoA) { pInitScanParam->scanDuration = pMac->lim.gTotalScanDuration; } /* Inform HAL whether it should check for traffic on the link * prior to performing a background scan */ pInitScanParam->checkLinkTraffic = trafficCheck; } pMac->lim.gLimHalScanState = nextState; SET_LIM_PROCESS_DEFD_MESGS(pMac, false); MTRACE(macTraceMsgTx(pMac, NO_SESSION, msg.type)); rc = wdaPostCtrlMsg(pMac, &msg); if (rc == eSIR_SUCCESS) { PELOG3(limLog(pMac, LOG3, FL("wdaPostCtrlMsg() return eSIR_SUCCESS pMac=%x nextState=%d"), pMac, pMac->lim.gLimHalScanState);) return; } SET_LIM_PROCESS_DEFD_MESGS(pMac, true); vos_mem_free(pInitScanParam); PELOGW(limLog(pMac, LOGW, FL("wdaPostCtrlMsg failed, error code %d"), rc);) error: switch(nextState) { case eLIM_HAL_START_SCAN_WAIT_STATE: case eLIM_HAL_INIT_SCAN_WAIT_STATE: limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_INIT_FAILED); break; //WLAN_SUSPEND_LINK Related case eLIM_HAL_SUSPEND_LINK_WAIT_STATE: pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE; if( pMac->lim.gpLimSuspendCallback ) { pMac->lim.gpLimSuspendCallback( pMac, rc, pMac->lim.gpLimSuspendData ); pMac->lim.gpLimSuspendCallback = NULL; pMac->lim.gpLimSuspendData = NULL; } pMac->lim.gLimSystemInScanLearnMode = 0; break; //end WLAN_SUSPEND_LINK Related default: break; } pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE; return ; } void limSendHalStartScanReq(tpAniSirGlobal pMac, tANI_U8 channelNum, tLimLimHalScanState nextState) { tSirMsgQ msg; tpStartScanParams pStartScanParam; tSirRetStatus rc = eSIR_SUCCESS; /** * The Start scan request to be sent only if Start Scan is not already requested */ if(pMac->lim.gLimHalScanState != eLIM_HAL_START_SCAN_WAIT_STATE) { pStartScanParam = vos_mem_malloc(sizeof(*pStartScanParam)); if ( NULL == pStartScanParam ) { PELOGW(limLog(pMac, LOGW, FL("AllocateMemory() failed"));) goto error; } msg.type = WDA_START_SCAN_REQ; msg.bodyptr = pStartScanParam; msg.bodyval = 0; pStartScanParam->status = eHAL_STATUS_SUCCESS; pStartScanParam->scanChannel = (tANI_U8)channelNum; pMac->lim.gLimHalScanState = nextState; SET_LIM_PROCESS_DEFD_MESGS(pMac, false); MTRACE(macTraceMsgTx(pMac, NO_SESSION, msg.type)); rc = wdaPostCtrlMsg(pMac, &msg); if (rc == eSIR_SUCCESS) { return; } SET_LIM_PROCESS_DEFD_MESGS(pMac, true); vos_mem_free(pStartScanParam); PELOGW(limLog(pMac, LOGW, FL("wdaPostCtrlMsg failed, error code %d"), rc);) error: switch(nextState) { case eLIM_HAL_START_SCAN_WAIT_STATE: limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_INIT_FAILED); break; default: break; } pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE; } else { PELOGW(limLog(pMac, LOGW, FL("Invalid state for START_SCAN_REQ message=%d"), pMac->lim.gLimHalScanState);) } return; } void limSendHalEndScanReq(tpAniSirGlobal pMac, tANI_U8 channelNum, tLimLimHalScanState nextState) { tSirMsgQ msg; tpEndScanParams pEndScanParam; tSirRetStatus rc = eSIR_SUCCESS; /** * The End scan request to be sent only if End Scan is not already requested or * Start scan is not already requestd. * after finish scan rsp from firmware host is sending endscan request so adding * check for IDLE SCAN STATE also added to avoid this issue */ if((pMac->lim.gLimHalScanState != eLIM_HAL_END_SCAN_WAIT_STATE) && (pMac->lim.gLimHalScanState != eLIM_HAL_IDLE_SCAN_STATE) && (pMac->lim.gLimHalScanState == eLIM_HAL_SCANNING_STATE) && (pMac->lim.gLimHalScanState != eLIM_HAL_FINISH_SCAN_WAIT_STATE) && (pMac->lim.gLimHalScanState != eLIM_HAL_START_SCAN_WAIT_STATE)) { pEndScanParam = vos_mem_malloc(sizeof(*pEndScanParam)); if ( NULL == pEndScanParam ) { PELOGW(limLog(pMac, LOGW, FL("AllocateMemory() failed"));) goto error; } msg.type = WDA_END_SCAN_REQ; msg.bodyptr = pEndScanParam; msg.bodyval = 0; pEndScanParam->status = eHAL_STATUS_SUCCESS; pEndScanParam->scanChannel = (tANI_U8)channelNum; pMac->lim.gLimHalScanState = nextState; SET_LIM_PROCESS_DEFD_MESGS(pMac, false); MTRACE(macTraceMsgTx(pMac, NO_SESSION, msg.type)); rc = wdaPostCtrlMsg(pMac, &msg); if (rc == eSIR_SUCCESS) { return; } SET_LIM_PROCESS_DEFD_MESGS(pMac, true); vos_mem_free(pEndScanParam); PELOGW(limLog(pMac, LOGW, FL("wdaPostCtrlMsg failed, error code %d"), rc);) error: switch(nextState) { case eLIM_HAL_END_SCAN_WAIT_STATE: limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_END_FAILED); break; default: PELOGW(limLog(pMac, LOGW, FL("wdaPostCtrlMsg Rcvd invalid nextState %d"), nextState);) break; } pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE; PELOGW(limLog(pMac, LOGW, FL("wdaPostCtrlMsg failed, error code %d"), rc);) } else { PELOGW(limLog(pMac, LOGW, FL("Invalid state for END_SCAN_REQ message=%d"), pMac->lim.gLimHalScanState);) } return; } void limSendTLPauseInd(tpAniSirGlobal pMac, uint16_t staId) { tSirMsgQ msg; tSirRetStatus rc = eSIR_SUCCESS; msg.type = WDA_PAUSE_TL_IND; msg.bodyval = staId; MTRACE(macTraceMsgTx(pMac, NO_SESSION, msg.type)); rc = wdaPostCtrlMsg(pMac, &msg); if (rc == eSIR_SUCCESS) { return; } limLog(pMac, LOGW, FL("wdaPostCtrlMsg failed, error code %d"), rc); return; } /** * limSendHalFinishScanReq() * *FUNCTION: * This function is called to finish scan/learn request.. * *LOGIC: * *ASSUMPTIONS: * NA * *NOTE: * NA * * @param pMac - Pointer to Global MAC structure * @param nextState - this parameters determines whether this call is for scan or learn * * @return None */ void limSendHalFinishScanReq(tpAniSirGlobal pMac, tLimLimHalScanState nextState) { tSirMsgQ msg; tpFinishScanParams pFinishScanParam; tSirRetStatus rc = eSIR_SUCCESS; if(pMac->lim.gLimHalScanState == nextState) { /* * PE may receive multiple probe responses, while waiting for HAL to send 'FINISH_SCAN_RSP' message * PE was sending multiple finish scan req messages to HAL * this check will avoid that. * If PE is already waiting for the 'finish_scan_rsp' message from HAL, it will ignore this request. */ PELOGW(limLog(pMac, LOGW, FL("Next Scan State is same as the current state: %d "), nextState);) return; } pFinishScanParam = vos_mem_malloc(sizeof(*pFinishScanParam)); if ( NULL == pFinishScanParam ) { PELOGW(limLog(pMac, LOGW, FL("AllocateMemory() failed"));) goto error; } msg.type = WDA_FINISH_SCAN_REQ; msg.bodyptr = pFinishScanParam; msg.bodyval = 0; peGetResumeChannel(pMac, &pFinishScanParam->currentOperChannel, &pFinishScanParam->cbState); vos_mem_set((tANI_U8 *)&pFinishScanParam->macMgmtHdr, sizeof(tSirMacMgmtHdr), 0); if (nextState == eLIM_HAL_FINISH_LEARN_WAIT_STATE) { //AP - No pkt need to be transmitted pFinishScanParam->scanMode = eHAL_SYS_MODE_LEARN; pFinishScanParam->notifyBss = FALSE; pFinishScanParam->notifyHost = FALSE; pFinishScanParam->frameType = 0; pFinishScanParam->frameLength = 0; pMac->lim.gLimHalScanState = nextState; } else { /* If STA is associated with an AP (ie. STA is in * LINK_ESTABLISHED state), then STA need to inform * the AP via either DATA-NULL */ if (nextState == eLIM_HAL_RESUME_LINK_WAIT_STATE) { pFinishScanParam->scanMode = eHAL_SYS_MODE_SUSPEND_LINK; } else { pFinishScanParam->scanMode = eHAL_SYS_MODE_SCAN; } pFinishScanParam->notifyHost = FALSE; __limCreateFinishScanRawFrame(pMac, pFinishScanParam); //WLAN_SUSPEND_LINK Related pMac->lim.gLimHalScanState = nextState; //end WLAN_SUSPEND_LINK Related } SET_LIM_PROCESS_DEFD_MESGS(pMac, false); MTRACE(macTraceMsgTx(pMac, NO_SESSION, msg.type)); rc = wdaPostCtrlMsg(pMac, &msg); if (rc == eSIR_SUCCESS) { return; } SET_LIM_PROCESS_DEFD_MESGS(pMac, true); vos_mem_free(pFinishScanParam); PELOGW(limLog(pMac, LOGW, FL("wdaPostCtrlMsg failed, error code %d"), rc);) error: if(nextState == eLIM_HAL_FINISH_SCAN_WAIT_STATE) limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_FINISH_FAILED); //WLAN_SUSPEND_LINK Related else if ( nextState == eLIM_HAL_RESUME_LINK_WAIT_STATE ) { if( pMac->lim.gpLimResumeCallback ) { pMac->lim.gpLimResumeCallback( pMac, rc, pMac->lim.gpLimResumeData ); pMac->lim.gpLimResumeCallback = NULL; pMac->lim.gpLimResumeData = NULL; pMac->lim.gLimSystemInScanLearnMode = 0; } } //end WLAN_SUSPEND_LINK Related pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE; return; } /** * limContinueChannelScan() * *FUNCTION: * This function is called by limPerformChannelScan(). * This function is called to continue channel scanning when * Beacon/Probe Response frame are received. * *LOGIC: * Scan criteria stored in pMac->lim.gLimMlmScanReq is used * to perform channel scan. In this function MLM sub module * makes channel switch, sends PROBE REQUEST frame in case of * ACTIVE SCANNING, starts min/max channel timers, programs * NAV to probeDelay timer and waits for Beacon/Probe Response. * Once all required channels are scanned, LIM_MLM_SCAN_CNF * primitive is used to send Scan results to SME sub module. * *ASSUMPTIONS: * 1. In case of Active scanning, start MAX channel time iff * MIN channel timer expired and activity is observed on * the channel. * *NOTE: * NA * * @param pMac Pointer to Global MAC structure * @return None */ void limContinueChannelScan(tpAniSirGlobal pMac) { tANI_U8 channelNum; if (pMac->lim.gLimCurrentScanChannelId > (tANI_U32) (pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1) || pMac->lim.abortScan) { pMac->lim.abortScan = 0; limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); //Set the resume channel to Any valid channel (invalid). //This will instruct HAL to set it to any previous valid channel. peSetResumeChannel(pMac, 0, 0); /// Done scanning all required channels limSendHalFinishScanReq(pMac, eLIM_HAL_FINISH_SCAN_WAIT_STATE); return; } /// Atleast one more channel is to be scanned if ((pMac->lim.gLimReturnAfterFirstMatch & 0x40) || (pMac->lim.gLimReturnAfterFirstMatch & 0x80)) { while (pMac->lim.gLimCurrentScanChannelId <= (tANI_U32) (pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1)) { if (((limGetCurrentScanChannel(pMac) <= 14) && pMac->lim.gLim24Band11dScanDone) || ((limGetCurrentScanChannel(pMac) > 14) && pMac->lim.gLim50Band11dScanDone)) { limLog(pMac, LOGW, FL("skipping chan %d"), limGetCurrentScanChannel(pMac)); pMac->lim.gLimCurrentScanChannelId++; } else break; } if (pMac->lim.gLimCurrentScanChannelId > (tANI_U32) (pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1)) { pMac->lim.abortScan = 0; limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); /// Done scanning all required channels //Set the resume channel to Any valid channel (invalid). //This will instruct HAL to set it to any previous valid channel. peSetResumeChannel(pMac, 0, 0); limSendHalFinishScanReq(pMac, eLIM_HAL_FINISH_SCAN_WAIT_STATE); return; } } channelNum = limGetCurrentScanChannel(pMac); limLog(pMac, LOG1, FL("Current Channel to be scanned is %d"), channelNum); limSendHalStartScanReq(pMac, channelNum, eLIM_HAL_START_SCAN_WAIT_STATE); return; } /*** end limContinueChannelScan() ***/ /** * limRestorePreScanState() * *FUNCTION: * This function is called by limContinueChannelScan() * to restore HW state prior to entering 'scan state' * *LOGIC * *ASSUMPTIONS: * *NOTE: * NA * * @param pMac Pointer to Global MAC structure * @return None */ void limRestorePreScanState(tpAniSirGlobal pMac) { int i; /// Deactivate MIN/MAX channel timers if running limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); /* Re-activate Heartbeat timers for connected sessions as scan * is done if the DUT is in active mode * AND it is not a ROAMING ("background") scan */ if(((ePMM_STATE_BMPS_WAKEUP == pMac->pmm.gPmmState) || (ePMM_STATE_READY == pMac->pmm.gPmmState)) && (pMac->lim.gLimBackgroundScanMode != eSIR_ROAMING_SCAN )) { for(i=0;i<pMac->lim.maxBssId;i++) { if((peFindSessionBySessionId(pMac,i) != NULL) && (pMac->lim.gpSession[i].valid == TRUE) && (eLIM_MLM_LINK_ESTABLISHED_STATE == pMac->lim.gpSession[i].limMlmState) && (!IS_ACTIVEMODE_OFFLOAD_FEATURE_ENABLE)) { limReactivateHeartBeatTimer(pMac, peFindSessionBySessionId(pMac,i)); } } } /** * clean up message queue. * If SME messages, redirect to deferred queue. * The rest will be discarded. */ //limCleanupMsgQ(pMac); pMac->lim.gLimSystemInScanLearnMode = 0; limLog(pMac, LOG1, FL("Scan ended, took %ld tu"), (tx_time_get() - pMac->lim.scanStartTime)); } /*** limRestorePreScanState() ***/ #ifdef FEATURE_OEM_DATA_SUPPORT void limSendHalOemDataReq(tpAniSirGlobal pMac) { tSirMsgQ msg; tpStartOemDataReq pStartOemDataReq = NULL; tSirRetStatus rc = eSIR_SUCCESS; tpLimMlmOemDataRsp pMlmOemDataRsp; tANI_U32 reqLen = 0; if(NULL == pMac->lim.gpLimMlmOemDataReq) { PELOGE(limLog(pMac, LOGE, FL("Null pointer"));) goto error; } reqLen = sizeof(tStartOemDataReq); pStartOemDataReq = vos_mem_malloc(reqLen); if ( NULL == pStartOemDataReq ) { PELOGE(limLog(pMac, LOGE, FL("OEM_DATA: Could not allocate memory for pStartOemDataReq"));) goto error; } vos_mem_set((tANI_U8*)(pStartOemDataReq), reqLen, 0); //Now copy over the information to the OEM DATA REQ to HAL vos_mem_copy(pStartOemDataReq->selfMacAddr, pMac->lim.gpLimMlmOemDataReq->selfMacAddr, sizeof(tSirMacAddr)); vos_mem_copy(pStartOemDataReq->oemDataReq, pMac->lim.gpLimMlmOemDataReq->oemDataReq, OEM_DATA_REQ_SIZE); //Create the message to be passed to HAL msg.type = WDA_START_OEM_DATA_REQ; msg.bodyptr = pStartOemDataReq; msg.bodyval = 0; SET_LIM_PROCESS_DEFD_MESGS(pMac, false); MTRACE(macTraceMsgTx(pMac, NO_SESSION, msg.type)); rc = wdaPostCtrlMsg(pMac, &msg); if(rc == eSIR_SUCCESS) { return; } SET_LIM_PROCESS_DEFD_MESGS(pMac, true); vos_mem_free(pStartOemDataReq); PELOGE(limLog(pMac, LOGE, FL("OEM_DATA: posting WDA_START_OEM_DATA_REQ to HAL failed"));) error: pMac->lim.gLimMlmState = pMac->lim.gLimPrevMlmState; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, NO_SESSION, pMac->lim.gLimMlmState)); pMlmOemDataRsp = vos_mem_malloc(sizeof(tLimMlmOemDataRsp)); if ( NULL == pMlmOemDataRsp ) { limLog(pMac->hHdd, LOGP, FL("OEM_DATA: memory allocation for pMlmOemDataRsp failed under suspend link failure")); return; } if(NULL != pMac->lim.gpLimMlmOemDataReq) { vos_mem_free(pMac->lim.gpLimMlmOemDataReq); pMac->lim.gpLimMlmOemDataReq = NULL; } limPostSmeMessage(pMac, LIM_MLM_OEM_DATA_CNF, (tANI_U32*)pMlmOemDataRsp); return; } /** * limSetOemDataReqModeFailed() * * FUNCTION: * This function is used as callback to resume link after the suspend fails while * starting oem data req mode. * LOGIC: * NA * * ASSUMPTIONS: * NA * * NOTE: * * @param pMac - Pointer to Global MAC structure * @return None */ void limSetOemDataReqModeFailed(tpAniSirGlobal pMac, eHalStatus status, tANI_U32* data) { tpLimMlmOemDataRsp pMlmOemDataRsp; pMac->lim.gLimMlmState = pMac->lim.gLimPrevMlmState; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, NO_SESSION, pMac->lim.gLimMlmState)); pMlmOemDataRsp = vos_mem_malloc(sizeof(tLimMlmOemDataRsp)); if ( NULL == pMlmOemDataRsp ) { limLog(pMac->hHdd, LOGP, FL("OEM_DATA: memory allocation for pMlmOemDataRsp failed under suspend link failure")); return; } if (NULL != pMac->lim.gpLimMlmOemDataReq) { vos_mem_free(pMac->lim.gpLimMlmOemDataReq); pMac->lim.gpLimMlmOemDataReq = NULL; } vos_mem_set(pMlmOemDataRsp, sizeof(tLimMlmOemDataRsp), 0); limPostSmeMessage(pMac, LIM_MLM_OEM_DATA_CNF, (tANI_U32*)pMlmOemDataRsp); return; } /** * limSetOemDataReqMode() * *FUNCTION: * This function is called to setup system into OEM DATA REQ mode * *LOGIC: * NA * *ASSUMPTIONS: * NA * *NOTE: * * @param pMac - Pointer to Global MAC structure * @return None */ void limSetOemDataReqMode(tpAniSirGlobal pMac, eHalStatus status, tANI_U32* data) { if(status != eHAL_STATUS_SUCCESS) { limLog(pMac, LOGE, FL("OEM_DATA: failed in suspend link")); /* If failed to suspend the link, there is no need * to resume link. Return failure. */ limSetOemDataReqModeFailed(pMac, status, data); } else { PELOGE(limLog(pMac, LOGE, FL("OEM_DATA: Calling limSendHalOemDataReq"));) limSendHalOemDataReq(pMac); } return; } /*** end limSendHalOemDataReq() ***/ #endif //FEATURE_OEM_DATA_SUPPORT static void mlm_add_sta( tpAniSirGlobal pMac, tpAddStaParams pSta, tANI_U8 *pBssid, tANI_U8 htCapable, tpPESession psessionEntry) //psessionEntry may required in future { tANI_U32 val; int i; pSta->staType = STA_ENTRY_SELF; // Identifying self vos_mem_copy(pSta->bssId, pBssid, sizeof( tSirMacAddr )); vos_mem_copy(pSta->staMac, psessionEntry->selfMacAddr, sizeof(tSirMacAddr)); /* Configuration related parameters to be changed to support BT-AMP */ if( eSIR_SUCCESS != wlan_cfgGetInt( pMac, WNI_CFG_LISTEN_INTERVAL, &val )) limLog(pMac, LOGP, FL("Couldn't get LISTEN_INTERVAL")); pSta->listenInterval = (tANI_U16) val; if (eSIR_SUCCESS != wlan_cfgGetInt(pMac, WNI_CFG_SHORT_PREAMBLE, &val) ) limLog(pMac, LOGP, FL("Couldn't get SHORT_PREAMBLE")); pSta->shortPreambleSupported = (tANI_U8)val; pSta->assocId = 0; // Is SMAC OK with this? pSta->wmmEnabled = 0; pSta->uAPSD = 0; pSta->maxSPLen = 0; pSta->us32MaxAmpduDuration = 0; pSta->maxAmpduSize = 0; // 0: 8k, 1: 16k,2: 32k,3: 64k /* For Self STA get the LDPC capability from config.ini*/ pSta->htLdpcCapable = (psessionEntry->txLdpcIniFeatureEnabled & 0x01); pSta->vhtLdpcCapable = ((psessionEntry->txLdpcIniFeatureEnabled >> 1)& 0x01); if(IS_DOT11_MODE_HT(psessionEntry->dot11mode)) { pSta->htCapable = htCapable; pSta->greenFieldCapable = limGetHTCapability( pMac, eHT_GREENFIELD, psessionEntry); pSta->txChannelWidthSet = limGetHTCapability( pMac, eHT_SUPPORTED_CHANNEL_WIDTH_SET, psessionEntry ); pSta->mimoPS = (tSirMacHTMIMOPowerSaveState)limGetHTCapability( pMac, eHT_MIMO_POWER_SAVE, psessionEntry ); pSta->rifsMode = limGetHTCapability( pMac, eHT_RIFS_MODE, psessionEntry ); pSta->lsigTxopProtection = limGetHTCapability( pMac, eHT_LSIG_TXOP_PROTECTION, psessionEntry ); pSta->delBASupport = limGetHTCapability( pMac, eHT_DELAYED_BA, psessionEntry ); pSta->maxAmpduDensity = limGetHTCapability( pMac, eHT_MPDU_DENSITY, psessionEntry ); pSta->maxAmsduSize = limGetHTCapability( pMac, eHT_MAX_AMSDU_LENGTH, psessionEntry ); pSta->fDsssCckMode40Mhz = limGetHTCapability( pMac, eHT_DSSS_CCK_MODE_40MHZ, psessionEntry); pSta->fShortGI20Mhz = limGetHTCapability( pMac, eHT_SHORT_GI_20MHZ, psessionEntry); pSta->fShortGI40Mhz = limGetHTCapability( pMac, eHT_SHORT_GI_40MHZ, psessionEntry); } #ifdef WLAN_FEATURE_11AC if (psessionEntry->vhtCapability) { pSta->vhtCapable = VOS_TRUE; pSta->vhtTxBFCapable = psessionEntry->txBFIniFeatureEnabled; } #endif #ifdef WLAN_FEATURE_11AC limPopulateOwnRateSet(pMac, &pSta->supportedRates, NULL, false,psessionEntry,NULL); #else limPopulateOwnRateSet(pMac, &pSta->supportedRates, NULL, false,psessionEntry); #endif limFillSupportedRatesInfo(pMac, NULL, &pSta->supportedRates,psessionEntry); limLog( pMac, LOGE, FL( "GF: %d, ChnlWidth: %d, MimoPS: %d, lsigTXOP: %d, dsssCCK: %d, SGI20: %d, SGI40%d") , pSta->greenFieldCapable, pSta->txChannelWidthSet, pSta->mimoPS, pSta->lsigTxopProtection, pSta->fDsssCckMode40Mhz,pSta->fShortGI20Mhz, pSta->fShortGI40Mhz); if (VOS_P2P_GO_MODE == psessionEntry->pePersona) { pSta->p2pCapableSta = 1; } //Disable BA. It will be set as part of ADDBA negotiation. for( i = 0; i < STACFG_MAX_TC; i++ ) { pSta->staTCParams[i].txUseBA = eBA_DISABLE; pSta->staTCParams[i].rxUseBA = eBA_DISABLE; } } // // New HAL interface - WDA_ADD_BSS_REQ // Package WDA_ADD_BSS_REQ to HAL, in order to start a BSS // tSirResultCodes limMlmAddBss ( tpAniSirGlobal pMac, tLimMlmStartReq *pMlmStartReq, tpPESession psessionEntry) { tSirMsgQ msgQ; tpAddBssParams pAddBssParams = NULL; tANI_U32 retCode; // Package WDA_ADD_BSS_REQ message parameters pAddBssParams = vos_mem_malloc(sizeof( tAddBssParams )); if ( NULL == pAddBssParams ) { limLog( pMac, LOGE, FL( "Unable to allocate memory during ADD_BSS" )); // Respond to SME with LIM_MLM_START_CNF return eSIR_SME_HAL_SEND_MESSAGE_FAIL; } vos_mem_set(pAddBssParams, sizeof(tAddBssParams), 0); // Fill in tAddBssParams members vos_mem_copy(pAddBssParams->bssId, pMlmStartReq->bssId, sizeof( tSirMacAddr )); // Fill in tAddBssParams selfMacAddr vos_mem_copy (pAddBssParams->selfMacAddr, psessionEntry->selfMacAddr, sizeof( tSirMacAddr )); pAddBssParams->bssType = pMlmStartReq->bssType; if ((pMlmStartReq->bssType == eSIR_IBSS_MODE) || (pMlmStartReq->bssType == eSIR_BTAMP_AP_MODE)|| (pMlmStartReq->bssType == eSIR_BTAMP_STA_MODE)) { pAddBssParams->operMode = BSS_OPERATIONAL_MODE_STA; } else if (pMlmStartReq->bssType == eSIR_INFRA_AP_MODE){ pAddBssParams->operMode = BSS_OPERATIONAL_MODE_AP; } pAddBssParams->shortSlotTimeSupported = psessionEntry->shortSlotTimeSupported; pAddBssParams->beaconInterval = pMlmStartReq->beaconPeriod; pAddBssParams->dtimPeriod = pMlmStartReq->dtimPeriod; pAddBssParams->cfParamSet.cfpCount = pMlmStartReq->cfParamSet.cfpCount; pAddBssParams->cfParamSet.cfpPeriod = pMlmStartReq->cfParamSet.cfpPeriod; pAddBssParams->cfParamSet.cfpMaxDuration = pMlmStartReq->cfParamSet.cfpMaxDuration; pAddBssParams->cfParamSet.cfpDurRemaining = pMlmStartReq->cfParamSet.cfpDurRemaining; pAddBssParams->rateSet.numRates = pMlmStartReq->rateSet.numRates; vos_mem_copy(pAddBssParams->rateSet.rate, pMlmStartReq->rateSet.rate, pMlmStartReq->rateSet.numRates); pAddBssParams->nwType = pMlmStartReq->nwType; pAddBssParams->htCapable = pMlmStartReq->htCapable; #ifdef WLAN_FEATURE_11AC pAddBssParams->vhtCapable = psessionEntry->vhtCapability; pAddBssParams->vhtTxChannelWidthSet = psessionEntry->vhtTxChannelWidthSet; #endif pAddBssParams->htOperMode = pMlmStartReq->htOperMode; pAddBssParams->dualCTSProtection = pMlmStartReq->dualCTSProtection; pAddBssParams->txChannelWidthSet = pMlmStartReq->txChannelWidthSet; pAddBssParams->currentOperChannel = pMlmStartReq->channelNumber; pAddBssParams->currentExtChannel = pMlmStartReq->cbMode; #ifdef WLAN_FEATURE_11W pAddBssParams->rmfEnabled = psessionEntry->limRmfEnabled; #endif /* Update PE sessionId*/ pAddBssParams->sessionId = pMlmStartReq->sessionId; //Send the SSID to HAL to enable SSID matching for IBSS vos_mem_copy(&(pAddBssParams->ssId.ssId), pMlmStartReq->ssId.ssId, pMlmStartReq->ssId.length); pAddBssParams->ssId.length = pMlmStartReq->ssId.length; pAddBssParams->bHiddenSSIDEn = pMlmStartReq->ssidHidden; limLog( pMac, LOGE, FL( "TRYING TO HIDE SSID %d" ),pAddBssParams->bHiddenSSIDEn); // CR309183. Disable Proxy Probe Rsp. Host handles Probe Requests. Until FW fixed. pAddBssParams->bProxyProbeRespEn = 0; pAddBssParams->obssProtEnabled = pMlmStartReq->obssProtEnabled; #if defined WLAN_FEATURE_VOWIFI pAddBssParams->maxTxPower = psessionEntry->maxTxPower; #endif mlm_add_sta(pMac, &pAddBssParams->staContext, pAddBssParams->bssId, pAddBssParams->htCapable,psessionEntry); pAddBssParams->status = eHAL_STATUS_SUCCESS; pAddBssParams->respReqd = 1; // Set a new state for MLME psessionEntry->limMlmState = eLIM_MLM_WT_ADD_BSS_RSP_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); pAddBssParams->halPersona=psessionEntry->pePersona; //pass on the session persona to hal pAddBssParams->bSpectrumMgtEnabled = psessionEntry->spectrumMgtEnabled; #if defined WLAN_FEATURE_VOWIFI_11R pAddBssParams->extSetStaKeyParamValid = 0; #endif // // FIXME_GEN4 // A global counter (dialog token) is required to keep track of // all PE <-> HAL communication(s) // msgQ.type = WDA_ADD_BSS_REQ; msgQ.reserved = 0; msgQ.bodyptr = pAddBssParams; msgQ.bodyval = 0; MTRACE(macTraceMsgTx(pMac, psessionEntry->peSessionId, msgQ.type)); limLog( pMac, LOGW, FL( "Sending WDA_ADD_BSS_REQ..." )); if( eSIR_SUCCESS != (retCode = wdaPostCtrlMsg( pMac, &msgQ ))) { limLog( pMac, LOGE, FL("Posting ADD_BSS_REQ to HAL failed, reason=%X"), retCode ); vos_mem_free(pAddBssParams); return eSIR_SME_HAL_SEND_MESSAGE_FAIL; } return eSIR_SME_SUCCESS; } /** * limProcessMlmStartReq() * *FUNCTION: * This function is called to process MLM_START_REQ message * from SME * *LOGIC: * 1) MLME receives LIM_MLM_START_REQ from LIM * 2) MLME sends WDA_ADD_BSS_REQ to HAL * 3) MLME changes state to eLIM_MLM_WT_ADD_BSS_RSP_STATE * MLME now waits for HAL to send WDA_ADD_BSS_RSP * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmStartReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tLimMlmStartReq *pMlmStartReq; tLimMlmStartCnf mlmStartCnf; tpPESession psessionEntry = NULL; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmStartReq = (tLimMlmStartReq *) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmStartReq->sessionId))==NULL) { limLog(pMac, LOGP,FL("Session Does not exist for given sessionID")); mlmStartCnf.resultCode = eSIR_SME_REFUSED; goto end; } if (psessionEntry->limMlmState != eLIM_MLM_IDLE_STATE) { /** * Should not have received Start req in states other than idle. * Return Start confirm with failure code. */ PELOGE(limLog(pMac, LOGE, FL("received unexpected MLM_START_REQ in state %X"),psessionEntry->limMlmState);) limPrintMlmState(pMac, LOGE, psessionEntry->limMlmState); mlmStartCnf.resultCode = eSIR_SME_BSS_ALREADY_STARTED_OR_JOINED; goto end; } #if 0 if (cfgSetInt(pMac, WNI_CFG_CURRENT_CHANNEL, pMlmStartReq->channelNumber)!= eSIR_SUCCESS) limLog(pMac, LOGP, FL("could not set CURRENT_CHANNEL at CFG")); pMac->lim.gLimCurrentChannelId = pMlmStartReq->channelNumber; #endif //TO SUPPORT BT-AMP // Update BSSID & SSID at CFG database #if 0 //We are not using the BSSID and SSID from the config file, instead we are reading form the session table if (cfgSetStr(pMac, WNI_CFG_BSSID, (tANI_U8 *) pMlmStartReq->bssId, sizeof(tSirMacAddr)) != eSIR_SUCCESS) limLog(pMac, LOGP, FL("could not update BSSID at CFG")); vos_mem_copy( pMac->lim.gLimCurrentBssId, pMlmStartReq->bssId, sizeof(tSirMacAddr)); #endif //TO SUPPORT BT-AMP #if 0 if (cfgSetStr(pMac, WNI_CFG_SSID, (tANI_U8 *) &pMlmStartReq->ssId.ssId, pMlmStartReq->ssId.length) != eSIR_SUCCESS) limLog(pMac, LOGP, FL("could not update SSID at CFG")); #endif //To SUPPORT BT-AMP // pMac->lim.gLimCurrentSSID.length = pMlmStartReq->ssId.length; #if 0 if (cfgSetStr(pMac, WNI_CFG_OPERATIONAL_RATE_SET, (tANI_U8 *) &pMac->lim.gpLimStartBssReq->operationalRateSet.rate, pMac->lim.gpLimStartBssReq->operationalRateSet.numRates) != eSIR_SUCCESS) limLog(pMac, LOGP, FL("could not update Operational Rateset at CFG")); #endif //TO SUPPORT BT-AMP #if 0 // Periodic timer for remove WPS PBC proble response entry in PE is disbaled now. if (psessionEntry->limSystemRole == eLIM_AP_ROLE) { if(pMac->lim.limTimers.gLimWPSOverlapTimerObj.isTimerCreated == eANI_BOOLEAN_FALSE) { if (tx_timer_create(&pMac->lim.limTimers.gLimWPSOverlapTimerObj.gLimWPSOverlapTimer, "PS OVERLAP Timer", limWPSOverlapTimerHandler, SIR_LIM_WPS_OVERLAP_TIMEOUT, // expiration_input SYS_MS_TO_TICKS(LIM_WPS_OVERLAP_TIMER_MS), // initial_ticks SYS_MS_TO_TICKS(LIM_WPS_OVERLAP_TIMER_MS), // reschedule_ticks TX_AUTO_ACTIVATE /* TX_NO_ACTIVATE*/) != TX_SUCCESS) { limLog(pMac, LOGP, FL("failed to create WPS overlap Timer")); } pMac->lim.limTimers.gLimWPSOverlapTimerObj.sessionId = pMlmStartReq->sessionId; pMac->lim.limTimers.gLimWPSOverlapTimerObj.isTimerCreated = eANI_BOOLEAN_TRUE; limLog(pMac, LOGE, FL("Create WPS overlap Timer, session=%d"), pMlmStartReq->sessionId); if (tx_timer_activate(&pMac->lim.limTimers.gLimWPSOverlapTimerObj.gLimWPSOverlapTimer) != TX_SUCCESS) { limLog(pMac, LOGP, FL("tx_timer_activate failed")); } } } #endif mlmStartCnf.resultCode = limMlmAddBss(pMac, pMlmStartReq,psessionEntry); end: /* Update PE session Id */ mlmStartCnf.sessionId = pMlmStartReq->sessionId; /// Free up buffer allocated for LimMlmScanReq vos_mem_free(pMsgBuf); // // Respond immediately to LIM, only if MLME has not been // successfully able to send WDA_ADD_BSS_REQ to HAL. // Else, LIM_MLM_START_CNF will be sent after receiving // WDA_ADD_BSS_RSP from HAL // if( eSIR_SME_SUCCESS != mlmStartCnf.resultCode ) limPostSmeMessage(pMac, LIM_MLM_START_CNF, (tANI_U32 *) &mlmStartCnf); } /*** limProcessMlmStartReq() ***/ /* * This function checks if Scan is allowed or not. * It checks each session and if any session is not in the normal state, * it will return false. * Note: BTAMP_STA can be in LINK_EST as well as BSS_STARTED State, so * both cases are handled below. */ static tANI_U8 __limMlmScanAllowed(tpAniSirGlobal pMac) { int i; if(pMac->lim.gLimMlmState != eLIM_MLM_IDLE_STATE) { return FALSE; } for(i =0; i < pMac->lim.maxBssId; i++) { if(pMac->lim.gpSession[i].valid == TRUE) { if(!( ( ( (pMac->lim.gpSession[i].bssType == eSIR_INFRASTRUCTURE_MODE) || (pMac->lim.gpSession[i].limSystemRole == eLIM_BT_AMP_STA_ROLE))&& (pMac->lim.gpSession[i].limMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE) )|| ( ( (pMac->lim.gpSession[i].bssType == eSIR_IBSS_MODE)|| (pMac->lim.gpSession[i].limSystemRole == eLIM_BT_AMP_AP_ROLE)|| (pMac->lim.gpSession[i].limSystemRole == eLIM_BT_AMP_STA_ROLE) )&& (pMac->lim.gpSession[i].limMlmState == eLIM_MLM_BSS_STARTED_STATE) ) || ( ( ( (pMac->lim.gpSession[i].bssType == eSIR_INFRA_AP_MODE) && ( pMac->lim.gpSession[i].pePersona == VOS_P2P_GO_MODE) ) || (pMac->lim.gpSession[i].limSystemRole == eLIM_AP_ROLE) ) && (pMac->lim.gpSession[i].limMlmState == eLIM_MLM_BSS_STARTED_STATE) ) )) { return FALSE; } } } return TRUE; } /** * limProcessMlmScanReq() * *FUNCTION: * This function is called to process MLM_SCAN_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmScanReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tLimMlmScanCnf mlmScanCnf; tANI_U8 i = 0; tANI_U32 val = 0; if (pMac->lim.gLimSystemInScanLearnMode) { PELOGE(limLog(pMac, LOGE, FL("Sending START_SCAN from LIM while one req is pending"));) vos_mem_free(pMsgBuf); /*Send back a failure*/ mlmScanCnf.resultCode = eSIR_SME_SCAN_FAILED; mlmScanCnf.scanResultLength = 0; limPostSmeMessage(pMac, LIM_MLM_SCAN_CNF, (tANI_U32 *) &mlmScanCnf); return; } if(__limMlmScanAllowed(pMac) && (((tLimMlmScanReq *) pMsgBuf)->channelList.numChannels != 0)) { /// Hold onto SCAN REQ criteria pMac->lim.gpLimMlmScanReq = (tLimMlmScanReq *) pMsgBuf; limLog(pMac, LOG1, FL("Number of channels to scan are %d "), pMac->lim.gpLimMlmScanReq->channelList.numChannels); pMac->lim.gLimPrevMlmState = pMac->lim.gLimMlmState; if (pMac->lim.gpLimMlmScanReq->scanType == eSIR_ACTIVE_SCAN) pMac->lim.gLimMlmState = eLIM_MLM_WT_PROBE_RESP_STATE; else // eSIR_PASSIVE_SCAN pMac->lim.gLimMlmState = eLIM_MLM_PASSIVE_SCAN_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, NO_SESSION, pMac->lim.gLimMlmState)); pMac->lim.gLimSystemInScanLearnMode = 1; /* temporary fix to handle case where NOA duration calculation is incorrect * for scanning on DFS channels */ pMac->lim.gTotalScanDuration = 0; if (wlan_cfgGetInt(pMac, WNI_CFG_PASSIVE_MAXIMUM_CHANNEL_TIME, &val) != eSIR_SUCCESS) { /* * Could not get max channel value * from CFG. Log error. */ limLog(pMac, LOGP, FL("could not retrieve passive max channel value use def")); /* use a default value */ val= WNI_CFG_PASSIVE_MAXIMUM_CHANNEL_TIME_STADEF; } for (i = 0; i < pMac->lim.gpLimMlmScanReq->channelList.numChannels; i++) { tANI_U8 channelNum = pMac->lim.gpLimMlmScanReq->channelList.channelNumber[i]; if (pMac->miracast_mode) { pMac->lim.gTotalScanDuration += (DEFAULT_MIN_CHAN_TIME_DURING_MIRACAST + DEFAULT_MAX_CHAN_TIME_DURING_MIRACAST); } else if (limActiveScanAllowed(pMac, channelNum)) { /* Use min + max channel time to calculate the total duration of scan */ pMac->lim.gTotalScanDuration += pMac->lim.gpLimMlmScanReq->minChannelTime + pMac->lim.gpLimMlmScanReq->maxChannelTime; } else { /* using the value from WNI_CFG_PASSIVE_MINIMUM_CHANNEL_TIME as is done in * void limContinuePostChannelScan(tpAniSirGlobal pMac) */ pMac->lim.gTotalScanDuration += val; } } /* Adding an overhead of 5ms to account for the scan messaging delays */ pMac->lim.gTotalScanDuration += 5; limSetScanMode(pMac); } else { /** * Should not have received SCAN req in other states * OR should not have received LIM_MLM_SCAN_REQ with * zero number of channels * Log error */ limLog(pMac, LOGW, FL("received unexpected MLM_SCAN_REQ in state %d OR zero number of channels: %d"), pMac->lim.gLimMlmState, ((tLimMlmScanReq *) pMsgBuf)->channelList.numChannels); limPrintMlmState(pMac, LOGW, pMac->lim.gLimMlmState); /// Free up buffer allocated for /// pMac->lim.gLimMlmScanReq vos_mem_free(pMsgBuf); /// Return Scan confirm with INVALID_PARAMETERS mlmScanCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; mlmScanCnf.scanResultLength = 0; limPostSmeMessage(pMac, LIM_MLM_SCAN_CNF, (tANI_U32 *) &mlmScanCnf); } } /*** limProcessMlmScanReq() ***/ #ifdef FEATURE_OEM_DATA_SUPPORT static void limProcessMlmOemDataReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tLimMlmOemDataRsp* pMlmOemDataRsp; if (((pMac->lim.gLimMlmState == eLIM_MLM_IDLE_STATE) || (pMac->lim.gLimMlmState == eLIM_MLM_JOINED_STATE) || (pMac->lim.gLimMlmState == eLIM_MLM_AUTHENTICATED_STATE) || (pMac->lim.gLimMlmState == eLIM_MLM_BSS_STARTED_STATE) || (pMac->lim.gLimMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE))) { //Hold onto the oem data request criteria pMac->lim.gpLimMlmOemDataReq = (tLimMlmOemDataReq*)pMsgBuf; pMac->lim.gLimPrevMlmState = pMac->lim.gLimMlmState; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, NO_SESSION, pMac->lim.gLimMlmState)); //Now request for link suspension limSuspendLink(pMac, eSIR_CHECK_LINK_TRAFFIC_BEFORE_SCAN, limSetOemDataReqMode, NULL); } else { /** * Should not have received oem data req in other states * Log error */ PELOGW(limLog(pMac, LOGW, FL("OEM_DATA: unexpected LIM_MLM_OEM_DATA_REQ in invalid state %d"),pMac->lim.gLimMlmState);) limPrintMlmState(pMac, LOGW, pMac->lim.gLimMlmState); /// Free up buffer allocated vos_mem_free(pMsgBuf); /// Return Meas confirm with INVALID_PARAMETERS pMlmOemDataRsp = vos_mem_malloc(sizeof(tLimMlmOemDataRsp)); if ( pMlmOemDataRsp != NULL) { limPostSmeMessage(pMac, LIM_MLM_OEM_DATA_CNF, (tANI_U32*)pMlmOemDataRsp); vos_mem_free(pMlmOemDataRsp); } else { limLog(pMac, LOGP, FL("Could not allocate memory for pMlmOemDataRsp")); return; } } return; } #endif //FEATURE_OEM_DATA_SUPPORT /** * limProcessMlmPostJoinSuspendLink() * *FUNCTION: * This function is called after the suspend link while joining * off channel. * *LOGIC: * Check for suspend state. * If success, proceed with setting link state to recieve the * probe response/beacon from intended AP. * Switch to the APs channel. * On an error case, send the MLM_JOIN_CNF with error status. * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param status status of suspend link. * @param ctx passed while calling suspend link(psessionEntry) * @return None */ static void limProcessMlmPostJoinSuspendLink(tpAniSirGlobal pMac, eHalStatus status, tANI_U32 *ctx) { tANI_U8 chanNum, secChanOffset; tLimMlmJoinCnf mlmJoinCnf; tpPESession psessionEntry = (tpPESession)ctx; tSirLinkState linkState; if( eHAL_STATUS_SUCCESS != status ) { limLog(pMac, LOGE, FL("Sessionid %d Suspend link(NOTIFY_BSS) failed. " "still proceeding with join"),psessionEntry->peSessionId); } psessionEntry->limPrevMlmState = psessionEntry->limMlmState; psessionEntry->limMlmState = eLIM_MLM_WT_JOIN_BEACON_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); limLog(pMac, LOG1, FL("Sessionid %d prev lim state %d new lim state %d " "systemrole = %d"), psessionEntry->peSessionId, psessionEntry->limPrevMlmState, psessionEntry->limMlmState,psessionEntry->limSystemRole); limDeactivateAndChangeTimer(pMac, eLIM_JOIN_FAIL_TIMER); //assign appropriate sessionId to the timer object pMac->lim.limTimers.gLimJoinFailureTimer.sessionId = psessionEntry->peSessionId; linkState = ((psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE) ? eSIR_LINK_BTAMP_PREASSOC_STATE : eSIR_LINK_PREASSOC_STATE); limLog(pMac, LOG1, FL("[limProcessMlmJoinReq]: linkState:%d"),linkState); if (limSetLinkState(pMac, linkState, psessionEntry->pLimMlmJoinReq->bssDescription.bssId, psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS ) { limLog(pMac, LOGE, FL("SessionId:%d limSetLinkState to eSIR_LINK_PREASSOC_STATE" " Failed!!"),psessionEntry->peSessionId); limPrintMacAddr(pMac, psessionEntry->pLimMlmJoinReq->bssDescription.bssId,LOGE); mlmJoinCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE; psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); goto error; } /** Derive channel from BSS description and store it in the CFG */ // chanNum = pMac->lim.gpLimMlmJoinReq->bssDescription.channelId; chanNum = psessionEntry->currentOperChannel; secChanOffset = psessionEntry->htSecondaryChannelOffset; //store the channel switch sessionEntry in the lim global var psessionEntry->channelChangeReasonCode = LIM_SWITCH_CHANNEL_JOIN; #if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_ESE) || defined(FEATURE_WLAN_LFR) psessionEntry->pLimMlmReassocRetryReq = NULL; #endif #ifdef FEATURE_WLAN_DIAG_SUPPORT limDiagEventReport(pMac, WLAN_PE_DIAG_CHANNEL_SWITCH_ANOUNCEMENT, psessionEntry, eSIR_SUCCESS, LIM_SWITCH_CHANNEL_JOIN); #endif limLog(pMac, LOG1, FL("[limProcessMlmJoinReq]: suspend link success(%d) " "on sessionid: %d setting channel to: %d with secChanOffset:%d " "and maxtxPower: %d"), status, psessionEntry->peSessionId, chanNum, secChanOffset, psessionEntry->maxTxPower); limSetChannel(pMac, chanNum, secChanOffset, psessionEntry->maxTxPower, psessionEntry->peSessionId); return; error: mlmJoinCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE; mlmJoinCnf.sessionId = psessionEntry->peSessionId; mlmJoinCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; limPostSmeMessage(pMac, LIM_MLM_JOIN_CNF, (tANI_U32 *) &mlmJoinCnf); } /** * limProcessMlmJoinReq() * *FUNCTION: * This function is called to process MLM_JOIN_REQ message * from SME * *LOGIC: * 1) Initialize LIM, HAL, DPH * 2) Configure the BSS for which the JOIN REQ was received * a) Send WDA_ADD_BSS_REQ to HAL - * This will identify the BSS that we are interested in * --AND-- * Add a STA entry for the AP (in a STA context) * b) Wait for WDA_ADD_BSS_RSP * c) Send WDA_ADD_STA_REQ to HAL * This will add the "local STA" entry to the STA table * 3) Continue as before, i.e, * a) Send a PROBE REQ * b) Wait for PROBE RSP/BEACON containing the SSID that * we are interested in * c) Then start an AUTH seq * d) Followed by the ASSOC seq * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmJoinReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tLimMlmJoinCnf mlmJoinCnf; tANI_U8 sessionId; tpPESession psessionEntry; sessionId = ((tpLimMlmJoinReq)pMsgBuf)->sessionId; if((psessionEntry = peFindSessionBySessionId(pMac,sessionId))== NULL) { limLog(pMac, LOGE, FL("SessionId:%d session does not exist"),sessionId); goto error; } if (( (psessionEntry->limSystemRole != eLIM_AP_ROLE ) && (psessionEntry->limSystemRole != eLIM_BT_AMP_AP_ROLE )) && ( (psessionEntry->limMlmState == eLIM_MLM_IDLE_STATE) || (psessionEntry->limMlmState == eLIM_MLM_JOINED_STATE)) && (SIR_MAC_GET_ESS( ((tpLimMlmJoinReq) pMsgBuf)->bssDescription.capabilityInfo) != SIR_MAC_GET_IBSS( ((tpLimMlmJoinReq) pMsgBuf)->bssDescription.capabilityInfo))) { #if 0 if (pMac->lim.gpLimMlmJoinReq) vos_mem_free(pMac->lim.gpLimMlmJoinReq); #endif //TO SUPPORT BT-AMP , review 23sep /// Hold onto Join request parameters psessionEntry->pLimMlmJoinReq =(tpLimMlmJoinReq) pMsgBuf; if( isLimSessionOffChannel(pMac, sessionId) ) { //suspend link limLog(pMac, LOG1, FL("Suspend link as LimSession on sessionid %d" "is off channel"),sessionId); if (limIsLinkSuspended(pMac)) { limLog(pMac, LOGE, FL("Link is already suspended for some other" " reason. Return failure on sessionId:%d"), sessionId); goto error; } limSuspendLink(pMac, eSIR_DONT_CHECK_LINK_TRAFFIC_BEFORE_SCAN, limProcessMlmPostJoinSuspendLink, (tANI_U32*)psessionEntry ); } else { //No need to suspend link. limLog(pMac,LOG1,"SessionId:%d Join request on current channel", sessionId); limProcessMlmPostJoinSuspendLink( pMac, eHAL_STATUS_SUCCESS, (tANI_U32*) psessionEntry ); } return; } else { /** * Should not have received JOIN req in states other than * Idle state or on AP. * Return join confirm with invalid parameters code. */ limLog(pMac, LOGE, FL("SessionId:%d Unexpected Join request for role %d state %d "), psessionEntry->peSessionId,psessionEntry->limSystemRole, psessionEntry->limMlmState); limPrintMlmState(pMac, LOGE, psessionEntry->limMlmState); } error: vos_mem_free(pMsgBuf); if (psessionEntry != NULL) psessionEntry->pLimMlmJoinReq = NULL; mlmJoinCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE; mlmJoinCnf.sessionId = sessionId; mlmJoinCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; limPostSmeMessage(pMac, LIM_MLM_JOIN_CNF, (tANI_U32 *) &mlmJoinCnf); } /*** limProcessMlmJoinReq() ***/ /** * limProcessMlmAuthReq() * *FUNCTION: * This function is called to process MLM_AUTH_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmAuthReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tANI_U32 numPreAuthContexts; tSirMacAddr currentBssId; tLimMlmAuthCnf mlmAuthCnf; struct tLimPreAuthNode *preAuthNode; tpDphHashNode pStaDs; tANI_U8 sessionId; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMac->lim.gpLimMlmAuthReq = (tLimMlmAuthReq *) pMsgBuf; sessionId = pMac->lim.gpLimMlmAuthReq->sessionId; if((psessionEntry= peFindSessionBySessionId(pMac,sessionId) )== NULL) { limLog(pMac, LOGP, FL("SessionId:%d Session Does not exist"),sessionId); return; } limLog(pMac, LOG1,FL("Process Auth Req on sessionID %d Systemrole %d" "mlmstate %d from: "MAC_ADDRESS_STR" with authtype %d"), sessionId, psessionEntry->limSystemRole,psessionEntry->limMlmState, MAC_ADDR_ARRAY(pMac->lim.gpLimMlmAuthReq->peerMacAddr), pMac->lim.gpLimMlmAuthReq->authType); /** * Expect Auth request only when: * 1. STA joined/associated with a BSS or * 2. STA is in IBSS mode * and STA is going to authenticate with a unicast * adress and requested authentication algorithm is * supported. */ #if 0 if (wlan_cfgGetStr(pMac, WNI_CFG_BSSID, currentBssId, &cfg) != eSIR_SUCCESS) { /// Could not get BSSID from CFG. Log error. limLog(pMac, LOGP, FL("could not retrieve BSSID")); } #endif //To SuppoRT BT-AMP sirCopyMacAddr(currentBssId,psessionEntry->bssId); if (((((psessionEntry->limSystemRole== eLIM_STA_ROLE) || (psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE)) && ((psessionEntry->limMlmState == eLIM_MLM_JOINED_STATE) || (psessionEntry->limMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE))) || ((psessionEntry->limSystemRole == eLIM_STA_IN_IBSS_ROLE) && (psessionEntry->limMlmState == eLIM_MLM_BSS_STARTED_STATE))) && (limIsGroupAddr(pMac->lim.gpLimMlmAuthReq->peerMacAddr) == false) && (limIsAuthAlgoSupported( pMac, pMac->lim.gpLimMlmAuthReq->authType, psessionEntry) == true) ) { /** * This is a request for pre-authentication. * Check if there exists context already for * the requested peer OR * if this request is for the AP we're currently * associated with. * If yes, return auth confirm immediately when * requested auth type is same as the one used before. */ if ((((psessionEntry->limSystemRole == eLIM_STA_ROLE) ||(psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE) )&& (psessionEntry->limMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE) && (((pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable)) != NULL) && (pMac->lim.gpLimMlmAuthReq->authType == pStaDs->mlmStaContext.authType)) && (vos_mem_compare(pMac->lim.gpLimMlmAuthReq->peerMacAddr, currentBssId, sizeof(tSirMacAddr)) )) || (((preAuthNode = limSearchPreAuthList( pMac, pMac->lim.gpLimMlmAuthReq->peerMacAddr)) != NULL) && (preAuthNode->authType == pMac->lim.gpLimMlmAuthReq->authType))) { limLog(pMac, LOG2, FL("Already have pre-auth context with peer: "MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pMac->lim.gpLimMlmAuthReq->peerMacAddr)); mlmAuthCnf.resultCode = (tSirResultCodes) eSIR_MAC_SUCCESS_STATUS; goto end; } else { if (wlan_cfgGetInt(pMac, WNI_CFG_MAX_NUM_PRE_AUTH, (tANI_U32 *) &numPreAuthContexts) != eSIR_SUCCESS) { limLog(pMac, LOGP, FL("Could not retrieve NumPreAuthLimit from CFG")); } if (pMac->lim.gLimNumPreAuthContexts == numPreAuthContexts) { PELOGW(limLog(pMac, LOGW, FL("Number of pre-auth reached max limit"));) /// Return Auth confirm with reject code mlmAuthCnf.resultCode = eSIR_SME_MAX_NUM_OF_PRE_AUTH_REACHED; goto end; } } // Delete pre-auth node if exists if (preAuthNode) limDeletePreAuthNode(pMac, pMac->lim.gpLimMlmAuthReq->peerMacAddr); psessionEntry->limPrevMlmState = psessionEntry->limMlmState; psessionEntry->limMlmState = eLIM_MLM_WT_AUTH_FRAME2_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); //assign appropriate sessionId to the timer object pMac->lim.limTimers.gLimAuthFailureTimer.sessionId = sessionId; /* assign appropriate sessionId to the timer object */ pMac->lim.limTimers.gLimPeriodicAuthRetryTimer.sessionId = sessionId; limDeactivateAndChangeTimer(pMac, eLIM_AUTH_RETRY_TIMER); // Activate Auth failure timer MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_AUTH_FAIL_TIMER)); limDoSendAuthMgmtFrame(pMac, psessionEntry); return; } else { /** * Unexpected auth request. * Return Auth confirm with Invalid parameters code. */ mlmAuthCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } end: vos_mem_copy((tANI_U8 *) &mlmAuthCnf.peerMacAddr, (tANI_U8 *) &pMac->lim.gpLimMlmAuthReq->peerMacAddr, sizeof(tSirMacAddr)); mlmAuthCnf.authType = pMac->lim.gpLimMlmAuthReq->authType; mlmAuthCnf.sessionId = sessionId; /// Free up buffer allocated /// for pMac->lim.gLimMlmAuthReq vos_mem_free( pMac->lim.gpLimMlmAuthReq); pMac->lim.gpLimMlmAuthReq = NULL; limLog(pMac,LOG1,"SessionId:%d LimPostSme LIM_MLM_AUTH_CNF ",sessionId); limPostSmeMessage(pMac, LIM_MLM_AUTH_CNF, (tANI_U32 *) &mlmAuthCnf); } /*** limProcessMlmAuthReq() ***/ /** * limProcessMlmAssocReq() * *FUNCTION: * This function is called to process MLM_ASSOC_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmAssocReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tSirMacAddr currentBssId; tLimMlmAssocReq *pMlmAssocReq; tLimMlmAssocCnf mlmAssocCnf; tpPESession psessionEntry; // tANI_U8 sessionId; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmAssocReq = (tLimMlmAssocReq *) pMsgBuf; if( (psessionEntry = peFindSessionBySessionId(pMac,pMlmAssocReq->sessionId) )== NULL) { limLog(pMac, LOGP,FL("SessionId:%d Session Does not exist"), pMlmAssocReq->sessionId); vos_mem_free(pMlmAssocReq); return; } limLog(pMac, LOG1,FL("Process Assoc Req on sessionID %d Systemrole %d" "mlmstate %d from: "MAC_ADDRESS_STR), pMlmAssocReq->sessionId, psessionEntry->limSystemRole, psessionEntry->limMlmState, MAC_ADDR_ARRAY(pMlmAssocReq->peerMacAddr)); #if 0 if (wlan_cfgGetStr(pMac, WNI_CFG_BSSID, currentBssId, &cfg) != eSIR_SUCCESS) { /// Could not get BSSID from CFG. Log error. limLog(pMac, LOGP, FL("could not retrieve BSSID")); } #endif //TO SUPPORT BT-AMP sirCopyMacAddr(currentBssId,psessionEntry->bssId); if ( (psessionEntry->limSystemRole != eLIM_AP_ROLE && psessionEntry->limSystemRole != eLIM_BT_AMP_AP_ROLE) && (psessionEntry->limMlmState == eLIM_MLM_AUTHENTICATED_STATE || psessionEntry->limMlmState == eLIM_MLM_JOINED_STATE) && (vos_mem_compare(pMlmAssocReq->peerMacAddr, currentBssId, sizeof(tSirMacAddr))) ) { /// map the session entry pointer to the AssocFailureTimer pMac->lim.limTimers.gLimAssocFailureTimer.sessionId = pMlmAssocReq->sessionId; psessionEntry->limPrevMlmState = psessionEntry->limMlmState; psessionEntry->limMlmState = eLIM_MLM_WT_ASSOC_RSP_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); limLog(pMac,LOG1,"SessionId:%d Sending Assoc_Req Frame", psessionEntry->peSessionId); /// Prepare and send Association request frame limSendAssocReqMgmtFrame(pMac, pMlmAssocReq,psessionEntry); #ifdef FEATURE_WLAN_DIAG_SUPPORT limDiagEventReport(pMac, WLAN_PE_DIAG_ASSOC_REQ_EVENT, psessionEntry, eSIR_SUCCESS, eSIR_SUCCESS); #endif //Set the link state to postAssoc, so HW can start receiving frames from AP. if ((psessionEntry->bssType == eSIR_BTAMP_STA_MODE)|| ((psessionEntry->bssType == eSIR_BTAMP_AP_MODE) && (psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE))) { if(limSetLinkState(pMac, eSIR_LINK_BTAMP_POSTASSOC_STATE, currentBssId, psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS) PELOGE(limLog(pMac, LOGE, FL("Failed to set the LinkState"));) } /// Start association failure timer MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_ASSOC_FAIL_TIMER)); if (tx_timer_activate(&pMac->lim.limTimers.gLimAssocFailureTimer) != TX_SUCCESS) { /// Could not start Assoc failure timer. // Log error limLog(pMac, LOGP, FL("SessionId:%d could not start Association failure timer"), psessionEntry->peSessionId); // Cleanup as if assoc timer expired limProcessAssocFailureTimeout(pMac,LIM_ASSOC ); } return; } else { /** * Received Association request either in invalid state * or to a peer MAC entity whose address is different * from one that STA is currently joined with or on AP. * Return Assoc confirm with Invalid parameters code. */ // Log error PELOGW(limLog(pMac, LOGW, FL("received unexpected MLM_ASSOC_CNF in state %d for role=%d, MAC addr= " MAC_ADDRESS_STR), psessionEntry->limMlmState, psessionEntry->limSystemRole, MAC_ADDR_ARRAY(pMlmAssocReq->peerMacAddr));) limPrintMlmState(pMac, LOGW, psessionEntry->limMlmState); mlmAssocCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; mlmAssocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; goto end; } end: /* Update PE session Id*/ mlmAssocCnf.sessionId = pMlmAssocReq->sessionId; /// Free up buffer allocated for assocReq vos_mem_free(pMlmAssocReq); limPostSmeMessage(pMac, LIM_MLM_ASSOC_CNF, (tANI_U32 *) &mlmAssocCnf); } /*** limProcessMlmAssocReq() ***/ /** * limProcessMlmReassocReq() * *FUNCTION: * This function is called to process MLM_REASSOC_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmReassocReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tANI_U8 chanNum, secChannelOffset; struct tLimPreAuthNode *pAuthNode; tLimMlmReassocReq *pMlmReassocReq; tLimMlmReassocCnf mlmReassocCnf; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmReassocReq = (tLimMlmReassocReq *) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmReassocReq->sessionId)) == NULL) { limLog(pMac, LOGE,FL("Session Does not exist for given sessionId %d"), pMlmReassocReq->sessionId); vos_mem_free(pMlmReassocReq); return; } limLog(pMac, LOG1,FL("Process ReAssoc Req on sessionID %d Systemrole %d" "mlmstate %d from: "MAC_ADDRESS_STR), pMlmReassocReq->sessionId, psessionEntry->limSystemRole, psessionEntry->limMlmState, MAC_ADDR_ARRAY(pMlmReassocReq->peerMacAddr)); if (((psessionEntry->limSystemRole != eLIM_AP_ROLE) && (psessionEntry->limSystemRole != eLIM_BT_AMP_AP_ROLE)) && (psessionEntry->limMlmState == eLIM_MLM_LINK_ESTABLISHED_STATE)) { if (psessionEntry->pLimMlmReassocReq) vos_mem_free(psessionEntry->pLimMlmReassocReq); /* Hold Re-Assoc request as part of Session, knock-out pMac */ /// Hold onto Reassoc request parameters psessionEntry->pLimMlmReassocReq = pMlmReassocReq; // See if we have pre-auth context with new AP pAuthNode = limSearchPreAuthList(pMac, psessionEntry->limReAssocbssId); if (!pAuthNode && (!vos_mem_compare(pMlmReassocReq->peerMacAddr, psessionEntry->bssId, sizeof(tSirMacAddr)) )) { // Either pre-auth context does not exist AND // we are not reassociating with currently // associated AP. // Return Reassoc confirm with not authenticated mlmReassocCnf.resultCode = eSIR_SME_STA_NOT_AUTHENTICATED; mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; goto end; } //assign the sessionId to the timer object pMac->lim.limTimers.gLimReassocFailureTimer.sessionId = pMlmReassocReq->sessionId; psessionEntry->limPrevMlmState = psessionEntry->limMlmState; psessionEntry->limMlmState = eLIM_MLM_WT_REASSOC_RSP_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); #if 0 // Update BSSID at CFG database if (wlan_cfgSetStr(pMac, WNI_CFG_BSSID, pMac->lim.gLimReassocBssId, sizeof(tSirMacAddr)) != eSIR_SUCCESS) { /// Could not update BSSID at CFG. Log error. limLog(pMac, LOGP, FL("could not update BSSID at CFG")); } #endif //TO SUPPORT BT-AMP /* Copy Global Reassoc ID*/ // sirCopyMacAddr(psessionEntry->reassocbssId,pMac->lim.gLimReAssocBssId); /** * Derive channel from BSS description and * store it at CFG. */ chanNum = psessionEntry->limReassocChannelId; secChannelOffset = psessionEntry->reAssocHtSecondaryChannelOffset; /* To Support BT-AMP .. read channel number from psessionEntry*/ //chanNum = psessionEntry->currentOperChannel; // Apply previously set configuration at HW limApplyConfiguration(pMac,psessionEntry); //store the channel switch sessionEntry in the lim global var /* We have already saved the ReAssocreq Pointer abobe */ //psessionEntry->pLimReAssocReq = (void *)pMlmReassocReq; psessionEntry->channelChangeReasonCode = LIM_SWITCH_CHANNEL_REASSOC; /** Switch channel to the new Operating channel for Reassoc*/ #ifdef FEATURE_WLAN_DIAG_SUPPORT limDiagEventReport(pMac, WLAN_PE_DIAG_CHANNEL_SWITCH_ANOUNCEMENT, psessionEntry, eSIR_SUCCESS, LIM_SWITCH_CHANNEL_REASSOC); #endif limSetChannel(pMac, chanNum, secChannelOffset, psessionEntry->maxTxPower, psessionEntry->peSessionId); return; } else { /** * Received Reassoc request in invalid state or * in AP role.Return Reassoc confirm with Invalid * parameters code. */ // Log error limLog(pMac, LOGW, FL("received unexpected MLM_REASSOC_CNF in state %d for role=%d, " "MAC addr= " MAC_ADDRESS_STR), psessionEntry->limMlmState, psessionEntry->limSystemRole, MAC_ADDR_ARRAY(pMlmReassocReq->peerMacAddr)); limPrintMlmState(pMac, LOGW, psessionEntry->limMlmState); mlmReassocCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; goto end; } end: mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; /* Update PE sessio Id*/ mlmReassocCnf.sessionId = pMlmReassocReq->sessionId; /// Free up buffer allocated for reassocReq vos_mem_free(pMlmReassocReq); psessionEntry->pLimReAssocReq = NULL; limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf); } /*** limProcessMlmReassocReq() ***/ static void limProcessMlmDisassocReqNtf(tpAniSirGlobal pMac, eHalStatus suspendStatus, tANI_U32 *pMsgBuf) { tANI_U16 aid; tSirMacAddr currentBssId; tpDphHashNode pStaDs; tLimMlmDisassocReq *pMlmDisassocReq; tLimMlmDisassocCnf mlmDisassocCnf; tpPESession psessionEntry; extern tANI_BOOLEAN sendDisassocFrame; tSirSmeDisassocRsp *pSirSmeDisassocRsp; tANI_U32 *pMsg; tANI_U8 *pBuf; if(eHAL_STATUS_SUCCESS != suspendStatus) { PELOGE(limLog(pMac, LOGE,FL("Suspend Status is not success %X"), suspendStatus);) #if 0 //It can ignore the status and proceed with the disassoc processing. mlmDisassocCnf.resultCode = eSIR_SME_REFUSED; goto end; #endif } pMlmDisassocReq = (tLimMlmDisassocReq *) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmDisassocReq->sessionId))== NULL) { limLog(pMac, LOGE, FL("session does not exist for given sessionId %d"), pMlmDisassocReq->sessionId); mlmDisassocCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } limLog(pMac, LOG1,FL("Process DisAssoc Req on sessionID %d Systemrole %d" "mlmstate %d from: "MAC_ADDRESS_STR), pMlmDisassocReq->sessionId, psessionEntry->limSystemRole, psessionEntry->limMlmState, MAC_ADDR_ARRAY(pMlmDisassocReq->peerMacAddr)); #if 0 if (wlan_cfgGetStr(pMac, WNI_CFG_BSSID, currentBssId, &cfg) != eSIR_SUCCESS) { /// Could not get BSSID from CFG. Log error. limLog(pMac, LOGP, FL("could not retrieve BSSID")); } #endif //BT-AMP Support sirCopyMacAddr(currentBssId,psessionEntry->bssId); switch (psessionEntry->limSystemRole) { case eLIM_STA_ROLE: case eLIM_BT_AMP_STA_ROLE: if ( !vos_mem_compare(pMlmDisassocReq->peerMacAddr, currentBssId, sizeof(tSirMacAddr)) ) { PELOGW(limLog(pMac, LOGW, FL("received MLM_DISASSOC_REQ with invalid BSS id from: " MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pMlmDisassocReq->peerMacAddr));) /// Prepare and Send LIM_MLM_DISASSOC_CNF mlmDisassocCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } break; case eLIM_STA_IN_IBSS_ROLE: break; default: // eLIM_AP_ROLE // Fall through break; } // end switch (psessionEntry->limSystemRole) /** * Check if there exists a context for the peer entity * to be disassociated with. */ pStaDs = dphLookupHashEntry(pMac, pMlmDisassocReq->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable); if ((pStaDs == NULL) || (pStaDs && ((pStaDs->mlmStaContext.mlmState != eLIM_MLM_LINK_ESTABLISHED_STATE) && (pStaDs->mlmStaContext.mlmState != eLIM_MLM_WT_ASSOC_CNF_STATE) && (pStaDs->mlmStaContext.mlmState != eLIM_MLM_ASSOCIATED_STATE)))) { /** * Received LIM_MLM_DISASSOC_REQ for STA that does not * have context or in some transit state. * Log error */ limLog(pMac, LOGE, FL("received MLM_DISASSOC_REQ for STA that either has no context " "or in some transit state, Addr= " MAC_ADDRESS_STR),MAC_ADDR_ARRAY(pMlmDisassocReq->peerMacAddr)); if (pStaDs != NULL) limLog(pMac, LOGE, FL("Sta MlmState : %d"), pStaDs->mlmStaContext.mlmState); /* * Disassociation response due to * host triggered disassociation */ pSirSmeDisassocRsp = vos_mem_malloc(sizeof(tSirSmeDisassocRsp)); if ( NULL == pSirSmeDisassocRsp ) { // Log error limLog(pMac, LOGP, FL("call to AllocateMemory failed for eWNI_SME_DISASSOC_RSP")); return; } limLog(pMac, LOG1, FL("send eWNI_SME_DISASSOC_RSP with " "retCode: %d for "MAC_ADDRESS_STR),eSIR_SME_DEAUTH_STATUS, MAC_ADDR_ARRAY(pMlmDisassocReq->peerMacAddr)); pSirSmeDisassocRsp->messageType = eWNI_SME_DISASSOC_RSP; pSirSmeDisassocRsp->length = sizeof(tSirSmeDisassocRsp); pSirSmeDisassocRsp->sessionId = pMlmDisassocReq->sessionId; pSirSmeDisassocRsp->transactionId = 0; pSirSmeDisassocRsp->statusCode = eSIR_SME_DEAUTH_STATUS; pBuf = (tANI_U8 *) pSirSmeDisassocRsp->peerMacAddr; vos_mem_copy( pBuf, pMlmDisassocReq->peerMacAddr, sizeof(tSirMacAddr)); pMsg = (tANI_U32*) pSirSmeDisassocRsp; limSendSmeDisassocDeauthNtf( pMac, eHAL_STATUS_SUCCESS, (tANI_U32*) pMsg ); return; } //pStaDs->mlmStaContext.rxPurgeReq = 1; pStaDs->mlmStaContext.disassocReason = (tSirMacReasonCodes) pMlmDisassocReq->reasonCode; pStaDs->mlmStaContext.cleanupTrigger = pMlmDisassocReq->disassocTrigger; /** Set state to mlm State to eLIM_MLM_WT_DEL_STA_RSP_STATE * This is to address the issue of race condition between * disconnect request from the HDD and deauth from AP */ pStaDs->mlmStaContext.mlmState = eLIM_MLM_WT_DEL_STA_RSP_STATE; /// Send Disassociate frame to peer entity if (sendDisassocFrame && (pMlmDisassocReq->reasonCode != eSIR_MAC_DISASSOC_DUE_TO_FTHANDOFF_REASON)) { pMac->lim.limDisassocDeauthCnfReq.pMlmDisassocReq = pMlmDisassocReq; if (IS_FW_IN_TX_PATH_FEATURE_ENABLE) { limSendDisassocMgmtFrame(pMac, pMlmDisassocReq->reasonCode, pMlmDisassocReq->peerMacAddr, psessionEntry, FALSE); /* Send Disassoc CNF and receive path cleanup */ limSendDisassocCnf(pMac); } else { limSendDisassocMgmtFrame(pMac, pMlmDisassocReq->reasonCode, pMlmDisassocReq->peerMacAddr, psessionEntry, TRUE); } } else { /* Disassoc frame is not sent OTA */ sendDisassocFrame = 1; // Receive path cleanup with dummy packet if(eSIR_SUCCESS != limCleanupRxPath(pMac, pStaDs,psessionEntry)) { mlmDisassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE; goto end; } // Free up buffer allocated for mlmDisassocReq vos_mem_free(pMlmDisassocReq); } return; end: vos_mem_copy((tANI_U8 *) &mlmDisassocCnf.peerMacAddr, (tANI_U8 *) pMlmDisassocReq->peerMacAddr, sizeof(tSirMacAddr)); mlmDisassocCnf.aid = pMlmDisassocReq->aid; mlmDisassocCnf.disassocTrigger = pMlmDisassocReq->disassocTrigger; /* Update PE session ID*/ mlmDisassocCnf.sessionId = pMlmDisassocReq->sessionId; /// Free up buffer allocated for mlmDisassocReq vos_mem_free(pMlmDisassocReq); limPostSmeMessage(pMac, LIM_MLM_DISASSOC_CNF, (tANI_U32 *) &mlmDisassocCnf); } tANI_BOOLEAN limCheckDisassocDeauthAckPending(tpAniSirGlobal pMac, tANI_U8 *staMac ) { tLimMlmDisassocReq *pMlmDisassocReq; tLimMlmDeauthReq *pMlmDeauthReq; pMlmDisassocReq = pMac->lim.limDisassocDeauthCnfReq.pMlmDisassocReq; pMlmDeauthReq = pMac->lim.limDisassocDeauthCnfReq.pMlmDeauthReq; if ( (pMlmDisassocReq && (vos_mem_compare((tANI_U8 *) staMac, (tANI_U8 *) &pMlmDisassocReq->peerMacAddr, sizeof(tSirMacAddr)))) || (pMlmDeauthReq && (vos_mem_compare((tANI_U8 *) staMac, (tANI_U8 *) &pMlmDeauthReq->peerMacAddr, sizeof(tSirMacAddr)))) ) { PELOG1(limLog(pMac, LOG1, FL("Disassoc/Deauth ack pending"));) return eANI_BOOLEAN_TRUE; } else { PELOG1(limLog(pMac, LOG1, FL("Disassoc/Deauth Ack not pending"));) return eANI_BOOLEAN_FALSE; } } void limCleanUpDisassocDeauthReq(tpAniSirGlobal pMac, tANI_U8 *staMac, tANI_BOOLEAN cleanRxPath) { tLimMlmDisassocReq *pMlmDisassocReq; tLimMlmDeauthReq *pMlmDeauthReq; pMlmDisassocReq = pMac->lim.limDisassocDeauthCnfReq.pMlmDisassocReq; if (pMlmDisassocReq && (vos_mem_compare((tANI_U8 *) staMac, (tANI_U8 *) &pMlmDisassocReq->peerMacAddr, sizeof(tSirMacAddr)))) { if (cleanRxPath) { limProcessDisassocAckTimeout(pMac); } else { if (tx_timer_running(&pMac->lim.limTimers.gLimDisassocAckTimer)) { limDeactivateAndChangeTimer(pMac, eLIM_DISASSOC_ACK_TIMER); } vos_mem_free(pMlmDisassocReq); pMac->lim.limDisassocDeauthCnfReq.pMlmDisassocReq = NULL; } } pMlmDeauthReq = pMac->lim.limDisassocDeauthCnfReq.pMlmDeauthReq; if (pMlmDeauthReq && (vos_mem_compare((tANI_U8 *) staMac, (tANI_U8 *) &pMlmDeauthReq->peerMacAddr, sizeof(tSirMacAddr)))) { if (cleanRxPath) { limProcessDeauthAckTimeout(pMac); } else { if (tx_timer_running(&pMac->lim.limTimers.gLimDeauthAckTimer)) { limDeactivateAndChangeTimer(pMac, eLIM_DEAUTH_ACK_TIMER); } vos_mem_free(pMlmDeauthReq); pMac->lim.limDisassocDeauthCnfReq.pMlmDeauthReq = NULL; } } } void limProcessDisassocAckTimeout(tpAniSirGlobal pMac) { limLog(pMac, LOG1, FL("")); limSendDisassocCnf(pMac); } /** * limProcessMlmDisassocReq() * *FUNCTION: * This function is called to process MLM_DISASSOC_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmDisassocReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tLimMlmDisassocReq *pMlmDisassocReq; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmDisassocReq = (tLimMlmDisassocReq *) pMsgBuf; limLog(pMac, LOG1,FL("Process DisAssoc Req on sessionID %d " "from: "MAC_ADDRESS_STR), pMlmDisassocReq->sessionId, MAC_ADDR_ARRAY(pMlmDisassocReq->peerMacAddr)); limProcessMlmDisassocReqNtf( pMac, eHAL_STATUS_SUCCESS, (tANI_U32*) pMsgBuf ); } /*** limProcessMlmDisassocReq() ***/ static void limProcessMlmDeauthReqNtf(tpAniSirGlobal pMac, eHalStatus suspendStatus, tANI_U32 *pMsgBuf) { tANI_U16 aid; tSirMacAddr currentBssId; tpDphHashNode pStaDs; struct tLimPreAuthNode *pAuthNode; tLimMlmDeauthReq *pMlmDeauthReq; tLimMlmDeauthCnf mlmDeauthCnf; tpPESession psessionEntry; tSirSmeDeauthRsp *pSirSmeDeauthRsp; tANI_U8 *pBuf; tANI_U32 *pMsg; if(eHAL_STATUS_SUCCESS != suspendStatus) { PELOGE(limLog(pMac, LOGE,FL("Suspend Status is not success %X"), suspendStatus);) #if 0 //It can ignore the status and proceed with the disassoc processing. mlmDisassocCnf.resultCode = eSIR_SME_REFUSED; goto end; #endif } pMlmDeauthReq = (tLimMlmDeauthReq *) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmDeauthReq->sessionId))== NULL) { limLog(pMac, LOGE, FL("session does not exist for given sessionId %d"), pMlmDeauthReq->sessionId); vos_mem_free(pMlmDeauthReq); return; } limLog(pMac, LOG1,FL("Process Deauth Req on sessionID %d Systemrole %d" "mlmstate %d from: "MAC_ADDRESS_STR), pMlmDeauthReq->sessionId, psessionEntry->limSystemRole, psessionEntry->limMlmState, MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr)); #if 0 if (wlan_cfgGetStr(pMac, WNI_CFG_BSSID, currentBssId, &cfg) != eSIR_SUCCESS) { /// Could not get BSSID from CFG. Log error. limLog(pMac, LOGP, FL("could not retrieve BSSID")); } #endif //SUPPORT BT-AMP sirCopyMacAddr(currentBssId,psessionEntry->bssId); switch (psessionEntry->limSystemRole) { case eLIM_STA_ROLE: case eLIM_BT_AMP_STA_ROLE: switch (psessionEntry->limMlmState) { case eLIM_MLM_IDLE_STATE: // Attempting to Deauthenticate // with a pre-authenticated peer. // Deauthetiate with peer if there // exists a pre-auth context below. break; case eLIM_MLM_AUTHENTICATED_STATE: case eLIM_MLM_WT_ASSOC_RSP_STATE: case eLIM_MLM_LINK_ESTABLISHED_STATE: if (!vos_mem_compare(pMlmDeauthReq->peerMacAddr, currentBssId, sizeof(tSirMacAddr)) ) { limLog(pMac, LOGE, FL("received MLM_DEAUTH_REQ with invalid BSS id " "Peer MAC: "MAC_ADDRESS_STR " CFG BSSID Addr : " MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr), MAC_ADDR_ARRAY(currentBssId)); /// Prepare and Send LIM_MLM_DEAUTH_CNF mlmDeauthCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } if ((psessionEntry->limMlmState == eLIM_MLM_AUTHENTICATED_STATE) || (psessionEntry->limMlmState == eLIM_MLM_WT_ASSOC_RSP_STATE)) { // Send Deauthentication frame // to peer entity limSendDeauthMgmtFrame( pMac, pMlmDeauthReq->reasonCode, pMlmDeauthReq->peerMacAddr, psessionEntry, FALSE); /// Prepare and Send LIM_MLM_DEAUTH_CNF mlmDeauthCnf.resultCode = eSIR_SME_SUCCESS; psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); goto end; } else { // LINK_ESTABLISED_STATE // Cleanup RX & TX paths // below } break; default: PELOGW(limLog(pMac, LOGW, FL("received MLM_DEAUTH_REQ with in state %d for peer "MAC_ADDRESS_STR), psessionEntry->limMlmState,MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr));) limPrintMlmState(pMac, LOGW, psessionEntry->limMlmState); /// Prepare and Send LIM_MLM_DEAUTH_CNF mlmDeauthCnf.resultCode = eSIR_SME_STA_NOT_AUTHENTICATED; goto end; } break; case eLIM_STA_IN_IBSS_ROLE: limLog(pMac, LOGE, FL("received MLM_DEAUTH_REQ IBSS Mode ")); mlmDeauthCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; default: // eLIM_AP_ROLE break; } // end switch (psessionEntry->limSystemRole) /** * Check if there exists a context for the peer entity * to be deauthenticated with. */ pStaDs = dphLookupHashEntry(pMac, pMlmDeauthReq->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable); if (pStaDs == NULL) { /// Check if there exists pre-auth context for this STA pAuthNode = limSearchPreAuthList(pMac, pMlmDeauthReq->peerMacAddr); if (pAuthNode == NULL) { /** * Received DEAUTH REQ for a STA that is neither * Associated nor Pre-authenticated. Log error, * Prepare and Send LIM_MLM_DEAUTH_CNF */ PELOGW(limLog(pMac, LOGW, FL("received MLM_DEAUTH_REQ in mlme state %d for STA that " "does not have context, Addr="MAC_ADDRESS_STR), psessionEntry->limMlmState, MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr));) mlmDeauthCnf.resultCode = eSIR_SME_STA_NOT_AUTHENTICATED; } else { mlmDeauthCnf.resultCode = eSIR_SME_SUCCESS; /// Delete STA from pre-auth STA list limDeletePreAuthNode(pMac, pMlmDeauthReq->peerMacAddr); /// Send Deauthentication frame to peer entity limSendDeauthMgmtFrame(pMac, pMlmDeauthReq->reasonCode, pMlmDeauthReq->peerMacAddr, psessionEntry, FALSE); } goto end; } else if ((pStaDs->mlmStaContext.mlmState != eLIM_MLM_LINK_ESTABLISHED_STATE) && (pStaDs->mlmStaContext.mlmState != eLIM_MLM_WT_ASSOC_CNF_STATE)) { /** * Received LIM_MLM_DEAUTH_REQ for STA that is n * some transit state. Log error. */ PELOGW(limLog(pMac, LOGW, FL("received MLM_DEAUTH_REQ for STA that either has no context or in some transit state, Addr=" MAC_ADDRESS_STR),MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr));) /* * Deauthentication response to host triggered * deauthentication. */ pSirSmeDeauthRsp = vos_mem_malloc(sizeof(tSirSmeDeauthRsp)); if ( NULL == pSirSmeDeauthRsp ) { // Log error limLog(pMac, LOGP, FL("call to AllocateMemory failed for eWNI_SME_DEAUTH_RSP")); return; } limLog(pMac, LOG1, FL("send eWNI_SME_DEAUTH_RSP with " "retCode: %d for"MAC_ADDRESS_STR),eSIR_SME_DEAUTH_STATUS, MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr)); pSirSmeDeauthRsp->messageType = eWNI_SME_DEAUTH_RSP; pSirSmeDeauthRsp->length = sizeof(tSirSmeDeauthRsp); pSirSmeDeauthRsp->statusCode = eSIR_SME_DEAUTH_STATUS; pSirSmeDeauthRsp->sessionId = pMlmDeauthReq->sessionId; pSirSmeDeauthRsp->transactionId = 0; pBuf = (tANI_U8 *) pSirSmeDeauthRsp->peerMacAddr; vos_mem_copy( pBuf, pMlmDeauthReq->peerMacAddr, sizeof(tSirMacAddr)); pMsg = (tANI_U32*)pSirSmeDeauthRsp; limSendSmeDisassocDeauthNtf( pMac, eHAL_STATUS_SUCCESS, (tANI_U32*) pMsg ); return; } //pStaDs->mlmStaContext.rxPurgeReq = 1; pStaDs->mlmStaContext.disassocReason = (tSirMacReasonCodes) pMlmDeauthReq->reasonCode; pStaDs->mlmStaContext.cleanupTrigger = pMlmDeauthReq->deauthTrigger; pMac->lim.limDisassocDeauthCnfReq.pMlmDeauthReq = pMlmDeauthReq; /* Set state to mlm State to eLIM_MLM_WT_DEL_STA_RSP_STATE * This is to address the issue of race condition between * disconnect request from the HDD and disassoc from * inactivity timer. This will make sure that we will not * process disassoc if deauth is in progress for the station * and thus mlmStaContext.cleanupTrigger will not be overwritten. */ pStaDs->mlmStaContext.mlmState = eLIM_MLM_WT_DEL_STA_RSP_STATE; /// Send Deauthentication frame to peer entity /* If FW_IN_TX_PATH feature is enabled do not wait for ACK */ if( IS_FW_IN_TX_PATH_FEATURE_ENABLE ) { limSendDeauthMgmtFrame(pMac, pMlmDeauthReq->reasonCode, pMlmDeauthReq->peerMacAddr, psessionEntry, FALSE); /* Send Deauth CNF and receive path cleanup */ limSendDeauthCnf(pMac); } else { limSendDeauthMgmtFrame(pMac, pMlmDeauthReq->reasonCode, pMlmDeauthReq->peerMacAddr, psessionEntry, TRUE); } return; end: vos_mem_copy((tANI_U8 *) &mlmDeauthCnf.peerMacAddr, (tANI_U8 *) pMlmDeauthReq->peerMacAddr, sizeof(tSirMacAddr)); mlmDeauthCnf.deauthTrigger = pMlmDeauthReq->deauthTrigger; mlmDeauthCnf.aid = pMlmDeauthReq->aid; mlmDeauthCnf.sessionId = pMlmDeauthReq->sessionId; // Free up buffer allocated // for mlmDeauthReq vos_mem_free(pMlmDeauthReq); limPostSmeMessage(pMac, LIM_MLM_DEAUTH_CNF, (tANI_U32 *) &mlmDeauthCnf); } void limProcessDeauthAckTimeout(tpAniSirGlobal pMac) { limLog(pMac, LOG1, FL("")); limSendDeauthCnf(pMac); } void lim_process_ap_ecsa_timeout(tpAniSirGlobal mac_ctx) { tSirMsgQ msg = {0}; struct sir_ecsa_ie_complete_ind *ecsa_ie_cmp_ind; tpPESession session; session = peFindSessionBySessionId(mac_ctx, mac_ctx->lim.limTimers.g_lim_ap_ecsa_timer.sessionId); if(!session) { limLog(mac_ctx, LOGE, FL("session does not exist for given sessionId %d"), mac_ctx->lim.limTimers.g_lim_ap_ecsa_timer.sessionId); return; } limLog(mac_ctx, LOG1, FL("session id %d switch count %d"), mac_ctx->lim.limTimers.g_lim_ap_ecsa_timer.sessionId, session->gLimChannelSwitch.switchCount); /* * For each beacon interval decrement switch count to use proper value * in probe resp sent by host. Once it becomes 0 send tx complete * indication to SME. */ if (session->gLimChannelSwitch.switchCount > 0) { session->gLimChannelSwitch.switchCount--; lim_send_chan_switch_action_frame(mac_ctx, session->gLimChannelSwitch.primaryChannel, session); mac_ctx->lim.limTimers.g_lim_ap_ecsa_timer.sessionId = session->peSessionId; limDeactivateAndChangeTimer(mac_ctx, eLIM_AP_ECSA_TIMER); if (tx_timer_activate(&mac_ctx->lim.limTimers.g_lim_ap_ecsa_timer) != TX_SUCCESS) { limLog(mac_ctx, LOGE, FL("Couldn't activate g_lim_ap_ecsa_timer")); lim_process_ap_ecsa_timeout(mac_ctx); } return; } session->include_ecsa_ie = false; session->include_wide_ch_bw_ie = false; ecsa_ie_cmp_ind = vos_mem_malloc(sizeof(*ecsa_ie_cmp_ind)); if(!ecsa_ie_cmp_ind) { limLog(mac_ctx, LOGE, FL("failed to allocate ecsa_ie_cmp_ind")); return; } ecsa_ie_cmp_ind->session_id = session->smeSessionId; msg.type = eWNI_SME_ECSA_IE_BEACON_COMP_IND; msg.bodyptr = ecsa_ie_cmp_ind; limSysProcessMmhMsgApi(mac_ctx, &msg, ePROT); return; } void lim_send_sme_ap_channel_switch_resp(tpAniSirGlobal mac_ctx, tpPESession session, tpSwitchChannelParams chan_params) { tSirMsgQ msg = {0}; struct sir_channel_chanege_rsp *params; params = vos_mem_malloc(sizeof(*params)); if (!params) { limLog(mac_ctx, LOGE, FL("AllocateMemory failed for pSmeSwithChnlParams")); return; } params->sme_session_id = session->smeSessionId; params->new_channel = chan_params->channelNumber; params->status = chan_params->status; msg.type = eWNI_SME_ECSA_CHAN_CHANGE_RSP; msg.bodyptr = params; msg.bodyval = 0; limSysProcessMmhMsgApi(mac_ctx, &msg, ePROT); if (chan_params->channelNumber == session->currentOperChannel) { limApplyConfiguration(mac_ctx, session); limSendBeaconInd(mac_ctx, session); } else { limLog(mac_ctx, LOGE, FL("channel switch resp chan %d and session channel doesnt match %d"), chan_params->channelNumber, session->currentOperChannel); } return; } /** * limProcessMlmDeauthReq() * *FUNCTION: * This function is called to process MLM_DEAUTH_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmDeauthReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { // tANI_U16 aid; // tSirMacAddr currentBssId; // tpDphHashNode pStaDs; // struct tLimPreAuthNode *pAuthNode; tLimMlmDeauthReq *pMlmDeauthReq; // tLimMlmDeauthCnf mlmDeauthCnf; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmDeauthReq = (tLimMlmDeauthReq *) pMsgBuf; limLog(pMac, LOG1,FL("Process Deauth Req on sessionID %d " "from: "MAC_ADDRESS_STR), pMlmDeauthReq->sessionId, MAC_ADDR_ARRAY(pMlmDeauthReq->peerMacAddr)); if((psessionEntry = peFindSessionBySessionId(pMac,pMlmDeauthReq->sessionId))== NULL) { limLog(pMac, LOGE, FL("session does not exist for given sessionId %d"), pMlmDeauthReq->sessionId); return; } limProcessMlmDeauthReqNtf( pMac, eHAL_STATUS_SUCCESS, (tANI_U32*) pMsgBuf ); } /*** limProcessMlmDeauthReq() ***/ /** * @function : limProcessMlmSetKeysReq() * * @brief : This function is called to process MLM_SETKEYS_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmSetKeysReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tANI_U16 aid; tANI_U16 staIdx = 0; tANI_U32 defaultKeyId = 0; tSirMacAddr currentBssId; tpDphHashNode pStaDs; tLimMlmSetKeysReq *pMlmSetKeysReq; tLimMlmSetKeysCnf mlmSetKeysCnf; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmSetKeysReq = (tLimMlmSetKeysReq *) pMsgBuf; // Hold onto the SetKeys request parameters pMac->lim.gpLimMlmSetKeysReq = (void *) pMlmSetKeysReq; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmSetKeysReq->sessionId))== NULL) { PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionId"));) return; } limLog( pMac, LOGW, FL( "Received MLM_SETKEYS_REQ with parameters:" "AID [%d], ED Type [%d], # Keys [%d] & Peer MAC Addr - "), pMlmSetKeysReq->aid, pMlmSetKeysReq->edType, pMlmSetKeysReq->numKeys ); limPrintMacAddr( pMac, pMlmSetKeysReq->peerMacAddr, LOGW ); #if 0 if( eSIR_SUCCESS != wlan_cfgGetStr( pMac, WNI_CFG_BSSID, currentBssId, &cfg )) { limLog( pMac, LOGP, FL("Could not retrieve BSSID")); return; } #endif //TO SUPPORT BT-AMP sirCopyMacAddr(currentBssId,psessionEntry->bssId); switch( psessionEntry->limSystemRole ) { case eLIM_STA_ROLE: case eLIM_BT_AMP_STA_ROLE: //In case of TDLS, peerMac address need not be BssId. Skip this check //if TDLS is enabled. #ifndef FEATURE_WLAN_TDLS if((!limIsAddrBC( pMlmSetKeysReq->peerMacAddr ) ) && (!vos_mem_compare(pMlmSetKeysReq->peerMacAddr, currentBssId, sizeof(tSirMacAddr))) ){ limLog( pMac, LOGW, FL("Received MLM_SETKEYS_REQ with invalid BSSID")); limPrintMacAddr( pMac, pMlmSetKeysReq->peerMacAddr, LOGW ); // Prepare and Send LIM_MLM_SETKEYS_CNF with error code mlmSetKeysCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } #endif // Fall thru' & 'Plumb' keys below break; case eLIM_STA_IN_IBSS_ROLE: default: // others // Fall thru... break; } /** * Use the "unicast" parameter to determine if the "Group Keys" * are being set. * pMlmSetKeysReq->key.unicast = 0 -> Multicast/broadcast * pMlmSetKeysReq->key.unicast - 1 -> Unicast keys are being set */ if( limIsAddrBC( pMlmSetKeysReq->peerMacAddr )) { limLog( pMac, LOG1, FL("Trying to set Group Keys...%d "), pMlmSetKeysReq->sessionId); /** When trying to set Group Keys for any * security mode other than WEP, use the * STA Index corresponding to the AP... */ switch( pMlmSetKeysReq->edType ) { case eSIR_ED_CCMP: #ifdef WLAN_FEATURE_11W case eSIR_ED_AES_128_CMAC: #endif staIdx = psessionEntry->staId; break; default: break; } }else { limLog( pMac, LOG1, FL("Trying to set Unicast Keys...")); /** * Check if there exists a context for the * peer entity for which keys need to be set. */ pStaDs = dphLookupHashEntry( pMac, pMlmSetKeysReq->peerMacAddr, &aid , &psessionEntry->dph.dphHashTable); if ((pStaDs == NULL) || ((pStaDs->mlmStaContext.mlmState != eLIM_MLM_LINK_ESTABLISHED_STATE) && (psessionEntry->limSystemRole != eLIM_AP_ROLE))) { /** * Received LIM_MLM_SETKEYS_REQ for STA * that does not have context or in some * transit state. Log error. */ limLog( pMac, LOG1, FL("Received MLM_SETKEYS_REQ for STA that either has no context or in some transit state, Addr = ")); limPrintMacAddr( pMac, pMlmSetKeysReq->peerMacAddr, LOGW ); // Prepare and Send LIM_MLM_SETKEYS_CNF mlmSetKeysCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } else staIdx = pStaDs->staIndex; } if ((pMlmSetKeysReq->numKeys == 0) && (pMlmSetKeysReq->edType != eSIR_ED_NONE)) { // // Broadcast/Multicast Keys (for WEP!!) are NOT sent // via this interface!! // // This indicates to HAL that the WEP Keys need to be // extracted from the CFG and applied to hardware defaultKeyId = 0xff; }else if(pMlmSetKeysReq->key[0].keyId && ((pMlmSetKeysReq->edType == eSIR_ED_WEP40) || (pMlmSetKeysReq->edType == eSIR_ED_WEP104))){ /* If the Key Id is non zero and encryption mode is WEP, * the key index is coming from the upper layers so that key only * need to be used as the default tx key, This is being used only * in case of WEP mode in HAL */ defaultKeyId = pMlmSetKeysReq->key[0].keyId; }else defaultKeyId = 0; limLog( pMac, LOG1, FL( "Trying to set keys for STA Index [%d], using defaultKeyId [%d]" ), staIdx, defaultKeyId ); if(limIsAddrBC( pMlmSetKeysReq->peerMacAddr )) { psessionEntry->limPrevMlmState = psessionEntry->limMlmState; psessionEntry->limMlmState = eLIM_MLM_WT_SET_BSS_KEY_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); limLog( pMac, LOG1, FL("Trying to set Group Keys...%d "), psessionEntry->peSessionId); // Package WDA_SET_BSSKEY_REQ message parameters limSendSetBssKeyReq(pMac, pMlmSetKeysReq,psessionEntry); return; }else { // Package WDA_SET_STAKEY_REQ / WDA_SET_STA_BCASTKEY_REQ message parameters limSendSetStaKeyReq(pMac, pMlmSetKeysReq, staIdx, (tANI_U8) defaultKeyId,psessionEntry); return; } end: mlmSetKeysCnf.sessionId= pMlmSetKeysReq->sessionId; limPostSmeSetKeysCnf( pMac, pMlmSetKeysReq, &mlmSetKeysCnf ); } /*** limProcessMlmSetKeysReq() ***/ /** * limProcessMlmRemoveKeyReq() * *FUNCTION: * This function is called to process MLM_REMOVEKEY_REQ message * from SME * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param *pMsgBuf A pointer to the MLM message buffer * @return None */ static void limProcessMlmRemoveKeyReq(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf) { tANI_U16 aid; tANI_U16 staIdx = 0; tSirMacAddr currentBssId; tpDphHashNode pStaDs; tLimMlmRemoveKeyReq *pMlmRemoveKeyReq; tLimMlmRemoveKeyCnf mlmRemoveKeyCnf; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmRemoveKeyReq = (tLimMlmRemoveKeyReq *) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmRemoveKeyReq->sessionId))== NULL) { PELOGE(limLog(pMac, LOGE, FL("session does not exist for given sessionId"));) vos_mem_free(pMsgBuf); return; } if( pMac->lim.gpLimMlmRemoveKeyReq != NULL ) { // Free any previous requests. vos_mem_free(pMac->lim.gpLimMlmRemoveKeyReq); pMac->lim.gpLimMlmRemoveKeyReq = NULL; } // Hold onto the RemoveKeys request parameters pMac->lim.gpLimMlmRemoveKeyReq = (void *) pMlmRemoveKeyReq; #if 0 if( eSIR_SUCCESS != wlan_cfgGetStr( pMac, WNI_CFG_BSSID, currentBssId, &cfg )) limLog( pMac, LOGP, FL("Could not retrieve BSSID")); #endif //TO-SUPPORT BT-AMP sirCopyMacAddr(currentBssId,psessionEntry->bssId); switch( psessionEntry->limSystemRole ) { case eLIM_STA_ROLE: case eLIM_BT_AMP_STA_ROLE: if (( limIsAddrBC( pMlmRemoveKeyReq->peerMacAddr ) != true ) && (!vos_mem_compare(pMlmRemoveKeyReq->peerMacAddr, currentBssId, sizeof(tSirMacAddr)))) { limLog( pMac, LOGW, FL("Received MLM_REMOVEKEY_REQ with invalid BSSID")); limPrintMacAddr( pMac, pMlmRemoveKeyReq->peerMacAddr, LOGW ); // Prepare and Send LIM_MLM_REMOVEKEY_CNF with error code mlmRemoveKeyCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; goto end; } break; case eLIM_STA_IN_IBSS_ROLE: default: // eLIM_AP_ROLE // Fall thru... break; } psessionEntry->limPrevMlmState = psessionEntry->limMlmState; if(limIsAddrBC( pMlmRemoveKeyReq->peerMacAddr )) //Second condition for IBSS or AP role. { psessionEntry->limMlmState = eLIM_MLM_WT_REMOVE_BSS_KEY_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); // Package WDA_REMOVE_BSSKEY_REQ message parameters limSendRemoveBssKeyReq( pMac,pMlmRemoveKeyReq,psessionEntry); return; } /** * Check if there exists a context for the * peer entity for which keys need to be removed. */ pStaDs = dphLookupHashEntry( pMac, pMlmRemoveKeyReq->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable ); if ((pStaDs == NULL) || (pStaDs && (pStaDs->mlmStaContext.mlmState != eLIM_MLM_LINK_ESTABLISHED_STATE))) { /** * Received LIM_MLM_REMOVEKEY_REQ for STA * that does not have context or in some * transit state. Log error. */ limLog( pMac, LOGW, FL("Received MLM_REMOVEKEYS_REQ for STA that either has no context or in some transit state, Addr = ")); limPrintMacAddr( pMac, pMlmRemoveKeyReq->peerMacAddr, LOGW ); // Prepare and Send LIM_MLM_REMOVEKEY_CNF mlmRemoveKeyCnf.resultCode = eSIR_SME_INVALID_PARAMETERS; mlmRemoveKeyCnf.sessionId = pMlmRemoveKeyReq->sessionId; goto end; } else staIdx = pStaDs->staIndex; psessionEntry->limMlmState = eLIM_MLM_WT_REMOVE_STA_KEY_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); // Package WDA_REMOVE_STAKEY_REQ message parameters limSendRemoveStaKeyReq( pMac,pMlmRemoveKeyReq,staIdx,psessionEntry); return; end: limPostSmeRemoveKeyCnf( pMac, psessionEntry, pMlmRemoveKeyReq, &mlmRemoveKeyCnf ); } /*** limProcessMlmRemoveKeyReq() ***/ /** * limProcessMinChannelTimeout() * *FUNCTION: * This function is called to process Min Channel Timeout * during channel scan. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessMinChannelTimeout(tpAniSirGlobal pMac) { tANI_U8 channelNum; #ifdef GEN6_TODO //if the min Channel is maintained per session, then use the below seesionEntry //priority - LOW/might not be needed //TBD-RAJESH HOW TO GET sessionEntry????? tpPESession psessionEntry; if((psessionEntry = peFindSessionBySessionId(pMac, pMac->lim.limTimers.gLimMinChannelTimer.sessionId))== NULL) { limLog(pMac, LOGP,FL("Session Does not exist for given sessionID")); return; } #endif /*do not process if we are in finish scan wait state i.e. scan is aborted or finished*/ if (pMac->lim.gLimMlmState == eLIM_MLM_WT_PROBE_RESP_STATE && pMac->lim.gLimHalScanState != eLIM_HAL_FINISH_SCAN_WAIT_STATE) { /// Min channel timer timed out pMac->lim.limTimers.gLimPeriodicProbeReqTimer.sessionId = 0xff; limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER); limDeactivateAndChangeTimer(pMac, eLIM_PERIODIC_PROBE_REQ_TIMER); pMac->lim.probeCounter = 0; if (pMac->lim.gLimCurrentScanChannelId <= (tANI_U32)(pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1)) { channelNum = (tANI_U8)limGetCurrentScanChannel(pMac); } else { // This shouldn't be the case, but when this happens, this timeout should be for the last channelId. // Get the channelNum as close to correct as possible. if(pMac->lim.gpLimMlmScanReq->channelList.channelNumber) { channelNum = pMac->lim.gpLimMlmScanReq->channelList.channelNumber[pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1]; } else { channelNum = 1; } } limLog(pMac, LOGW, FL("Sending End Scan req from MIN_CH_TIMEOUT in state %d ch-%d"), pMac->lim.gLimMlmState,channelNum); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); } else { /** * MIN channel timer should not have timed out * in states other than wait_probe_response. * Log error. */ limLog(pMac, LOGW, FL("received unexpected MIN channel timeout in mlme state %d and hal scan State %d"), pMac->lim.gLimMlmState,pMac->lim.gLimHalScanState); limPrintMlmState(pMac, LOGE, pMac->lim.gLimMlmState); } } /*** limProcessMinChannelTimeout() ***/ /** * limProcessMaxChannelTimeout() * *FUNCTION: * This function is called to process Max Channel Timeout * during channel scan. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessMaxChannelTimeout(tpAniSirGlobal pMac) { tANI_U8 channelNum; /*do not process if we are in finish scan wait state i.e. scan is aborted or finished*/ if ((pMac->lim.gLimMlmState == eLIM_MLM_WT_PROBE_RESP_STATE || pMac->lim.gLimMlmState == eLIM_MLM_PASSIVE_SCAN_STATE) && pMac->lim.gLimHalScanState != eLIM_HAL_FINISH_SCAN_WAIT_STATE) { limLog(pMac, LOG1, FL("Scanning : Max channel timed out")); /** * MAX channel timer timed out * Continue channel scan. */ limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER); limDeactivateAndChangeTimer(pMac, eLIM_PERIODIC_PROBE_REQ_TIMER); pMac->lim.limTimers.gLimPeriodicProbeReqTimer.sessionId = 0xff; pMac->lim.probeCounter = 0; if (pMac->lim.gLimCurrentScanChannelId <= (tANI_U32)(pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1)) { channelNum = limGetCurrentScanChannel(pMac); } else { if(pMac->lim.gpLimMlmScanReq->channelList.channelNumber) { channelNum = pMac->lim.gpLimMlmScanReq->channelList.channelNumber[pMac->lim.gpLimMlmScanReq->channelList.numChannels - 1]; } else { channelNum = 1; } } limLog(pMac, LOGW, FL("Sending End Scan req from MAX_CH_TIMEOUT in state %d on ch-%d"), pMac->lim.gLimMlmState,channelNum); limSendHalEndScanReq(pMac, channelNum, eLIM_HAL_END_SCAN_WAIT_STATE); } else { /** * MAX channel timer should not have timed out * in states other than wait_scan. * Log error. */ limLog(pMac, LOGW, FL("received unexpected MAX channel timeout in mlme state %d and hal scan state %d"), pMac->lim.gLimMlmState, pMac->lim.gLimHalScanState); limPrintMlmState(pMac, LOGW, pMac->lim.gLimMlmState); } } /*** limProcessMaxChannelTimeout() ***/ /** * limProcessPeriodicProbeReqTimer() * *FUNCTION: * This function is called to process periodic probe request * to send during scan. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessPeriodicProbeReqTimer(tpAniSirGlobal pMac) { tANI_U8 channelNum; tANI_U8 i = 0; tSirRetStatus status = eSIR_SUCCESS; TX_TIMER *pPeriodicProbeReqTimer; pPeriodicProbeReqTimer = &pMac->lim.limTimers.gLimPeriodicProbeReqTimer; if(vos_timer_getCurrentState(&pPeriodicProbeReqTimer->vosTimer) != VOS_TIMER_STATE_STOPPED) { limLog(pMac, LOG1, FL("Invalid state of timer")); return; } if ((pMac->lim.gLimMlmState == eLIM_MLM_WT_PROBE_RESP_STATE) && (pPeriodicProbeReqTimer->sessionId != 0xff) && (pMac->lim.probeCounter < pMac->lim.maxProbe)) { tLimMlmScanReq *pLimMlmScanReq = pMac->lim.gpLimMlmScanReq; pMac->lim.probeCounter++; /** * Periodic channel timer timed out * to send probe request. */ channelNum = limGetCurrentScanChannel(pMac); /* Prepare and send Probe Request frame for all the SSIDs * present in the saved MLM */ do { tSirMacAddr gSelfMacAddr; /* Send self MAC as src address if * MAC spoof is not enabled OR * spoofMacAddr is all 0 OR * disableP2PMacSpoof is enabled and scan is P2P scan * else use the spoofMac as src address */ if ((pMac->lim.isSpoofingEnabled != TRUE) || (TRUE == vos_is_macaddr_zero((v_MACADDR_t *)&pMac->lim.spoofMacAddr)) || (pMac->roam.configParam.disableP2PMacSpoofing && pMac->lim.gpLimMlmScanReq->p2pSearch)) { vos_mem_copy(gSelfMacAddr, pMac->lim.gSelfMacAddr, VOS_MAC_ADDRESS_LEN); } else { vos_mem_copy(gSelfMacAddr, pMac->lim.spoofMacAddr, VOS_MAC_ADDRESS_LEN); } limLog( pMac, LOG1, FL("Mac Addr used in Probe Req is :"MAC_ADDRESS_STR), MAC_ADDR_ARRAY(gSelfMacAddr)); /* * PELOGE(limLog(pMac, LOGW, FL("sending ProbeReq number %d," * " for SSID %s on channel: %d"), * i, pLimMlmScanReq->ssId[i].ssId, * channelNum);) */ status = limSendProbeReqMgmtFrame( pMac, &pLimMlmScanReq->ssId[i], pLimMlmScanReq->bssId, channelNum, gSelfMacAddr, pLimMlmScanReq->dot11mode, pLimMlmScanReq->uIEFieldLen, (tANI_U8 *)(pLimMlmScanReq) + pLimMlmScanReq->uIEFieldOffset); if ( status != eSIR_SUCCESS) { PELOGE(limLog(pMac, LOGE, FL("send ProbeReq failed for SSID " "%s on channel: %d"), pLimMlmScanReq->ssId[i].ssId, channelNum);) return; } i++; } while (i < pLimMlmScanReq->numSsid); /* Activate timer again */ if (tx_timer_activate(pPeriodicProbeReqTimer) != TX_SUCCESS) { limLog(pMac, LOGP, FL("could not start periodic probe" " req timer")); return; } } else { /** * Periodic scan is timeout is happening in * in states other than wait_scan. * Log error. */ limLog(pMac, LOG1, FL("received unexpected Periodic scan timeout in state %d"), pMac->lim.gLimMlmState); } } /*** limProcessPeriodicProbeReqTimer() ***/ /** * limProcessJoinFailureTimeout() * *FUNCTION: * This function is called to process JoinFailureTimeout * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessJoinFailureTimeout(tpAniSirGlobal pMac) { tLimMlmJoinCnf mlmJoinCnf; tSirMacAddr bssid; tANI_U32 len; #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT_LIM vos_log_rssi_pkt_type *pRssiLog = NULL; #endif //FEATURE_WLAN_DIAG_SUPPORT_LIM //fetch the sessionEntry based on the sessionId tpPESession psessionEntry; if((psessionEntry = peFindSessionBySessionId(pMac, pMac->lim.limTimers.gLimJoinFailureTimer.sessionId))== NULL) { limLog(pMac, LOGE, FL("Session Does not exist for given sessionID")); return; } #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT_LIM WLAN_VOS_DIAG_LOG_ALLOC(pRssiLog, vos_log_rssi_pkt_type, LOG_WLAN_RSSI_UPDATE_C); if (pRssiLog) { pRssiLog->rssi = psessionEntry->rssi; } WLAN_VOS_DIAG_LOG_REPORT(pRssiLog); #endif //FEATURE_WLAN_DIAG_SUPPORT_LIM if (psessionEntry->limMlmState == eLIM_MLM_WT_JOIN_BEACON_STATE) { len = sizeof(tSirMacAddr); if (wlan_cfgGetStr(pMac, WNI_CFG_BSSID, bssid, &len) != eSIR_SUCCESS) { /// Could not get BSSID from CFG. Log error. limLog(pMac, LOGP, FL("could not retrieve BSSID")); return; } // 'Change' timer for future activations limDeactivateAndChangeTimer(pMac, eLIM_JOIN_FAIL_TIMER); // Change Periodic probe req timer for future activation limDeactivateAndChangeTimer(pMac, eLIM_PERIODIC_JOIN_PROBE_REQ_TIMER); /** * Issue MLM join confirm with timeout reason code */ PELOGE(limLog(pMac, LOGE, FL(" In state eLIM_MLM_WT_JOIN_BEACON_STATE."));) PELOGE(limLog(pMac, LOGE, FL(" Join Failure Timeout occurred for session %d with BSS "), psessionEntry->peSessionId); limPrintMacAddr(pMac, psessionEntry->bssId, LOGE);) mlmJoinCnf.resultCode = eSIR_SME_JOIN_TIMEOUT_RESULT_CODE; mlmJoinCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); if(limSetLinkState(pMac, eSIR_LINK_IDLE_STATE, psessionEntry->bssId, psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS) PELOGE(limLog(pMac, LOGE, FL("Failed to set the LinkState"));) /* Update PE session Id */ mlmJoinCnf.sessionId = psessionEntry->peSessionId; // Freeup buffer allocated to join request if (psessionEntry->pLimMlmJoinReq) { vos_mem_free(psessionEntry->pLimMlmJoinReq); psessionEntry->pLimMlmJoinReq = NULL; } limPostSmeMessage(pMac, LIM_MLM_JOIN_CNF, (tANI_U32 *) &mlmJoinCnf); return; } else { /** * Join failure timer should not have timed out * in states other than wait_join_beacon state. * Log error. */ limLog(pMac, LOGW, FL("received unexpected JOIN failure timeout in state %d"),psessionEntry->limMlmState); limPrintMlmState(pMac, LOGW, psessionEntry->limMlmState); } } /*** limProcessJoinFailureTimeout() ***/ /** * limProcessPeriodicJoinProbeReqTimer() * *FUNCTION: * This function is called to process periodic probe request * send during joining process. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessPeriodicJoinProbeReqTimer(tpAniSirGlobal pMac) { tpPESession psessionEntry; tSirMacSSid ssId; if((psessionEntry = peFindSessionBySessionId(pMac, pMac->lim.limTimers.gLimPeriodicJoinProbeReqTimer.sessionId))== NULL) { limLog(pMac, LOGE,FL("session does not exist for given SessionId : %d"), pMac->lim.limTimers.gLimPeriodicJoinProbeReqTimer.sessionId); return; } if((VOS_TRUE == tx_timer_running(&pMac->lim.limTimers.gLimJoinFailureTimer)) && (psessionEntry->limMlmState == eLIM_MLM_WT_JOIN_BEACON_STATE)) { vos_mem_copy(ssId.ssId, psessionEntry->ssId.ssId, psessionEntry->ssId.length); ssId.length = psessionEntry->ssId.length; limSendProbeReqMgmtFrame( pMac, &ssId, psessionEntry->pLimMlmJoinReq->bssDescription.bssId, psessionEntry->currentOperChannel/*chanNum*/, psessionEntry->selfMacAddr, psessionEntry->dot11mode, psessionEntry->pLimJoinReq->addIEScan.length, psessionEntry->pLimJoinReq->addIEScan.addIEdata); limDeactivateAndChangeTimer(pMac, eLIM_PERIODIC_JOIN_PROBE_REQ_TIMER); // Activate Join Periodic Probe Req timer if (tx_timer_activate(&pMac->lim.limTimers.gLimPeriodicJoinProbeReqTimer) != TX_SUCCESS) { limLog(pMac, LOGP, FL("could not activate Periodic Join req failure timer")); return; } } return; } /*** limProcessPeriodicJoinProbeReqTimer() ***/ /** * limProcessAuthRetryTimer() * *FUNCTION: * This function is called to process Auth Retry request * send during joining process. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessAuthRetryTimer(tpAniSirGlobal pMac) { tpPESession psessionEntry; limLog(pMac, LOG1, FL(" ENTER ")); if ((psessionEntry = peFindSessionBySessionId(pMac, pMac->lim.limTimers.gLimPeriodicAuthRetryTimer.sessionId)) == NULL) { limLog(pMac, LOGE,FL("session does not exist for given SessionId : %d"), pMac->lim.limTimers.gLimPeriodicAuthRetryTimer.sessionId); return; } if ((VOS_TRUE == tx_timer_running(&pMac->lim.limTimers.gLimAuthFailureTimer)) && (psessionEntry->limMlmState == eLIM_MLM_WT_AUTH_FRAME2_STATE) && (LIM_AUTH_ACK_RCD_SUCCESS != pMac->authAckStatus)) { tSirMacAuthFrameBody authFrameBody; /* Send the auth retry only in case we have received ack failure * else just restart the retry timer. */ if (LIM_AUTH_ACK_RCD_FAILURE == pMac->authAckStatus) { /// Prepare & send Authentication frame authFrameBody.authAlgoNumber = (tANI_U8) pMac->lim.gpLimMlmAuthReq->authType; authFrameBody.authTransactionSeqNumber = SIR_MAC_AUTH_FRAME_1; authFrameBody.authStatusCode = 0; limLog(pMac, LOGW, FL("Retry Auth ")); pMac->authAckStatus = LIM_AUTH_ACK_NOT_RCD; limSendAuthMgmtFrame(pMac, &authFrameBody, pMac->lim.gpLimMlmAuthReq->peerMacAddr, LIM_NO_WEP_IN_FC, psessionEntry, eSIR_TRUE); } limDeactivateAndChangeTimer(pMac, eLIM_AUTH_RETRY_TIMER); // Activate Auth Retry timer if (tx_timer_activate(&pMac->lim.limTimers.gLimPeriodicAuthRetryTimer) != TX_SUCCESS) { limLog(pMac, LOGE, FL("could not activate Auth Retry failure timer")); return; } } return; } /*** limProcessAuthRetryTimer() ***/ /** * limProcessAuthFailureTimeout() * *FUNCTION: * This function is called to process Min Channel Timeout * during channel scan. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessAuthFailureTimeout(tpAniSirGlobal pMac) { //fetch the sessionEntry based on the sessionId tpPESession psessionEntry; #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT_LIM vos_log_rssi_pkt_type *pRssiLog = NULL; #endif //FEATURE_WLAN_DIAG_SUPPORT_LIM if((psessionEntry = peFindSessionBySessionId(pMac, pMac->lim.limTimers.gLimAuthFailureTimer.sessionId))== NULL) { limLog(pMac, LOGP,FL("Session Does not exist for given sessionID")); return; } limLog(pMac, LOGE, FL("received AUTH failure timeout in sessionid %d " "limMlmstate %d limSmeState %d"), psessionEntry->peSessionId, psessionEntry->limMlmState, psessionEntry->limSmeState); #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT_LIM WLAN_VOS_DIAG_LOG_ALLOC(pRssiLog, vos_log_rssi_pkt_type, LOG_WLAN_RSSI_UPDATE_C); if (pRssiLog) { pRssiLog->rssi = psessionEntry->rssi; } WLAN_VOS_DIAG_LOG_REPORT(pRssiLog); #endif //FEATURE_WLAN_DIAG_SUPPORT_LIM switch (psessionEntry->limMlmState) { case eLIM_MLM_WT_AUTH_FRAME2_STATE: case eLIM_MLM_WT_AUTH_FRAME4_STATE: /** * Requesting STA did not receive next auth frame * before Auth Failure timeout. * Issue MLM auth confirm with timeout reason code */ //Restore default failure timeout if (VOS_P2P_CLIENT_MODE == psessionEntry->pePersona && psessionEntry->defaultAuthFailureTimeout) { ccmCfgSetInt(pMac,WNI_CFG_AUTHENTICATE_FAILURE_TIMEOUT , psessionEntry->defaultAuthFailureTimeout, NULL, eANI_BOOLEAN_FALSE); } limRestoreFromAuthState(pMac,eSIR_SME_AUTH_TIMEOUT_RESULT_CODE,eSIR_MAC_UNSPEC_FAILURE_REASON,psessionEntry); break; default: /** * Auth failure timer should not have timed out * in states other than wt_auth_frame2/4 * Log error. */ PELOGE(limLog(pMac, LOGE, FL("received unexpected AUTH failure timeout in state %d"), psessionEntry->limMlmState);) limPrintMlmState(pMac, LOGE, psessionEntry->limMlmState); break; } /* Reinit scan results to remove the unreachable BSS */ limReInitScanResults(pMac); } /*** limProcessAuthFailureTimeout() ***/ /** * limProcessAuthRspTimeout() * *FUNCTION: * This function is called to process Min Channel Timeout * during channel scan. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessAuthRspTimeout(tpAniSirGlobal pMac, tANI_U32 authIndex) { struct tLimPreAuthNode *pAuthNode; tpPESession psessionEntry; tANI_U8 sessionId; pAuthNode = limGetPreAuthNodeFromIndex(pMac, &pMac->lim.gLimPreAuthTimerTable, authIndex); if (NULL == pAuthNode) { limLog(pMac, LOGW, FL("Invalid auth node")); return; } if ((psessionEntry = peFindSessionByBssid(pMac, pAuthNode->peerMacAddr, &sessionId)) == NULL) { limLog(pMac, LOGW, FL("session does not exist for given BSSID ")); return; } if (psessionEntry->limSystemRole == eLIM_AP_ROLE || psessionEntry->limSystemRole == eLIM_STA_IN_IBSS_ROLE) { if (pAuthNode->mlmState != eLIM_MLM_WT_AUTH_FRAME3_STATE) { /** * Authentication response timer timedout * in unexpected state. Log error */ PELOGE(limLog(pMac, LOGE, FL("received AUTH rsp timeout in unexpected state " "for MAC address: "MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pAuthNode->peerMacAddr));) } else { // Authentication response timer // timedout for an STA. pAuthNode->mlmState = eLIM_MLM_AUTH_RSP_TIMEOUT_STATE; pAuthNode->fTimerStarted = 0; limLog(pMac, LOG1, FL("AUTH rsp timedout for MAC address "MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pAuthNode->peerMacAddr)); // Change timer to reactivate it in future limDeactivateAndChangePerStaIdTimer(pMac, eLIM_AUTH_RSP_TIMER, pAuthNode->authNodeIdx); limDeletePreAuthNode(pMac, pAuthNode->peerMacAddr); } } } /*** limProcessAuthRspTimeout() ***/ /** * limProcessAssocFailureTimeout() * *FUNCTION: * This function is called to process Min Channel Timeout * during channel scan. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @return None */ static void limProcessAssocFailureTimeout(tpAniSirGlobal pMac, tANI_U32 MsgType) { tLimMlmAssocCnf mlmAssocCnf; tpPESession psessionEntry; #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT_LIM vos_log_rssi_pkt_type *pRssiLog = NULL; #endif //FEATURE_WLAN_DIAG_SUPPORT_LIM //to fetch the lim/mlm state based on the sessionId, use the below sessionEntry tANI_U8 sessionId; if(MsgType == LIM_ASSOC) { sessionId = pMac->lim.limTimers.gLimAssocFailureTimer.sessionId; } else { sessionId = pMac->lim.limTimers.gLimReassocFailureTimer.sessionId; } if((psessionEntry = peFindSessionBySessionId(pMac, sessionId))== NULL) { limLog(pMac, LOGP,FL("Session Does not exist for given sessionID")); return; } #ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT_LIM WLAN_VOS_DIAG_LOG_ALLOC(pRssiLog, vos_log_rssi_pkt_type, LOG_WLAN_RSSI_UPDATE_C); if (pRssiLog) { pRssiLog->rssi = psessionEntry->rssi; } WLAN_VOS_DIAG_LOG_REPORT(pRssiLog); #endif //FEATURE_WLAN_DIAG_SUPPORT_LIM /** * Expected Re/Association Response frame * not received within Re/Association Failure Timeout. */ /* * CR: vos packet memory is leaked when assoc rsp timeouted/failed. * notify TL that association is failed so that TL can flush the * cached frame */ WLANTL_AssocFailed (psessionEntry->staId); /* Log error */ limLog(pMac, LOG1, FL("Re/Association Response not received before timeout ")); /* * Send Deauth to handle the scenareo where association timeout happened * when device has missed the assoc resp sent by peer. * By sending deauth try to clear the session created on peer device. */ limLog(pMac, LOGE, FL("Sessionid: %d try sending Send deauth on channel %d to BSSID: " MAC_ADDRESS_STR ), psessionEntry->peSessionId, psessionEntry->currentOperChannel, MAC_ADDR_ARRAY(psessionEntry->bssId)); limSendDeauthMgmtFrame(pMac, eSIR_MAC_UNSPEC_FAILURE_REASON, psessionEntry->bssId, psessionEntry, FALSE); if (((psessionEntry->limSystemRole == eLIM_AP_ROLE) || (psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE) )|| ((psessionEntry->limMlmState != eLIM_MLM_WT_ASSOC_RSP_STATE) && (psessionEntry->limMlmState != eLIM_MLM_WT_REASSOC_RSP_STATE) && (psessionEntry->limMlmState != eLIM_MLM_WT_FT_REASSOC_RSP_STATE))) { /** * Re/Assoc failure timer should not have timedout on AP * or in a state other than wt_re/assoc_response. */ // Log error limLog(pMac, LOGW, FL("received unexpected REASSOC failure timeout in state %d for role %d"), psessionEntry->limMlmState, psessionEntry->limSystemRole); limPrintMlmState(pMac, LOGW, psessionEntry->limMlmState); } else { if ((MsgType == LIM_ASSOC) || ((MsgType == LIM_REASSOC) && (psessionEntry->limMlmState == eLIM_MLM_WT_FT_REASSOC_RSP_STATE))) { PELOGE(limLog(pMac, LOGE, FL("(Re)Assoc Failure Timeout occurred."));) psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); // 'Change' timer for future activations limDeactivateAndChangeTimer(pMac, eLIM_ASSOC_FAIL_TIMER); // Free up buffer allocated for JoinReq held by // MLM state machine if (psessionEntry->pLimMlmJoinReq) { vos_mem_free(psessionEntry->pLimMlmJoinReq); psessionEntry->pLimMlmJoinReq = NULL; } //To remove the preauth node in case of fail to associate if (limSearchPreAuthList(pMac, psessionEntry->bssId)) { limLog(pMac, LOG1, FL(" delete pre auth node for " MAC_ADDRESS_STR), MAC_ADDR_ARRAY(psessionEntry->bssId)); limDeletePreAuthNode(pMac, psessionEntry->bssId); } mlmAssocCnf.resultCode = eSIR_SME_ASSOC_TIMEOUT_RESULT_CODE; mlmAssocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; /* Update PE session Id*/ mlmAssocCnf.sessionId = psessionEntry->peSessionId; if (MsgType == LIM_ASSOC) limPostSmeMessage(pMac, LIM_MLM_ASSOC_CNF, (tANI_U32 *) &mlmAssocCnf); else { /* Will come here only in case of 11r, ESE, FT when reassoc rsp is not received and we receive a reassoc - timesout */ mlmAssocCnf.resultCode = eSIR_SME_FT_REASSOC_TIMEOUT_FAILURE; limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmAssocCnf); } } else { /** * Restore pre-reassoc req state. * Set BSSID to currently associated AP address. */ psessionEntry->limMlmState = psessionEntry->limPrevMlmState; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); limRestorePreReassocState(pMac, eSIR_SME_REASSOC_TIMEOUT_RESULT_CODE, eSIR_MAC_UNSPEC_FAILURE_STATUS,psessionEntry); } } /* Reinit scan results to remove the unreachable BSS */ limReInitScanResults(pMac); } /*** limProcessAssocFailureTimeout() ***/ /** * limCompleteMlmScan() * *FUNCTION: * This function is called to send MLM_SCAN_CNF message * to SME state machine. * *LOGIC: * *ASSUMPTIONS: * *NOTE: * * @param pMac Pointer to Global MAC structure * @param retCode Result code to be sent * @return None */ void limCompleteMlmScan(tpAniSirGlobal pMac, tSirResultCodes retCode) { tLimMlmScanCnf mlmScanCnf; /// Restore previous MLM state pMac->lim.gLimMlmState = pMac->lim.gLimPrevMlmState; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, NO_SESSION, pMac->lim.gLimMlmState)); limRestorePreScanState(pMac); // Free up pMac->lim.gLimMlmScanReq if( NULL != pMac->lim.gpLimMlmScanReq ) { vos_mem_free(pMac->lim.gpLimMlmScanReq); pMac->lim.gpLimMlmScanReq = NULL; } mlmScanCnf.resultCode = retCode; mlmScanCnf.scanResultLength = pMac->lim.gLimMlmScanResultLength; limPostSmeMessage(pMac, LIM_MLM_SCAN_CNF, (tANI_U32 *) &mlmScanCnf); } /*** limCompleteMlmScan() ***/ /** * \brief Setup an A-MPDU/BA session * * \sa limProcessMlmAddBAReq * * \param pMac The global tpAniSirGlobal object * * \param pMsgBuf The MLME ADDBA Req message buffer * * \return none */ void limProcessMlmAddBAReq( tpAniSirGlobal pMac, tANI_U32 *pMsgBuf ) { tSirRetStatus status = eSIR_SUCCESS; tpLimMlmAddBAReq pMlmAddBAReq; tpLimMlmAddBACnf pMlmAddBACnf; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmAddBAReq = (tpLimMlmAddBAReq) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmAddBAReq->sessionId))== NULL) { PELOGE(limLog(pMac, LOGE, FL("session does not exist for given sessionId"));) vos_mem_free(pMsgBuf); return; } // Send ADDBA Req over the air status = limSendAddBAReq( pMac, pMlmAddBAReq,psessionEntry); // // Respond immediately to LIM, only if MLME has not been // successfully able to send WDA_ADDBA_REQ to HAL. // Else, LIM_MLM_ADDBA_CNF will be sent after receiving // ADDBA Rsp from peer entity // if( eSIR_SUCCESS != status ) { // Allocate for LIM_MLM_ADDBA_CNF pMlmAddBACnf = vos_mem_malloc(sizeof( tLimMlmAddBACnf )); if ( NULL == pMlmAddBACnf ) { limLog( pMac, LOGP, FL("AllocateMemory failed")); vos_mem_free(pMsgBuf); return; } else { vos_mem_set((void *) pMlmAddBACnf, sizeof( tLimMlmAddBACnf ), 0); vos_mem_copy((void *) pMlmAddBACnf->peerMacAddr, (void *) pMlmAddBAReq->peerMacAddr, sizeof( tSirMacAddr )); pMlmAddBACnf->baDialogToken = pMlmAddBAReq->baDialogToken; pMlmAddBACnf->baTID = pMlmAddBAReq->baTID; pMlmAddBACnf->baPolicy = pMlmAddBAReq->baPolicy; pMlmAddBACnf->baBufferSize = pMlmAddBAReq->baBufferSize; pMlmAddBACnf->baTimeout = pMlmAddBAReq->baTimeout; pMlmAddBACnf->sessionId = pMlmAddBAReq->sessionId; // Update the result code pMlmAddBACnf->addBAResultCode = eSIR_MAC_UNSPEC_FAILURE_STATUS; limPostSmeMessage( pMac, LIM_MLM_ADDBA_CNF, (tANI_U32 *) pMlmAddBACnf ); } // Restore MLME state psessionEntry->limMlmState = psessionEntry->limPrevMlmState; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState)); } // Free the buffer allocated for tLimMlmAddBAReq vos_mem_free(pMsgBuf); } /** * \brief Send an ADDBA Rsp to peer STA in response * to an ADDBA Req received earlier * * \sa limProcessMlmAddBARsp * * \param pMac The global tpAniSirGlobal object * * \param pMsgBuf The MLME ADDBA Rsp message buffer * * \return none */ void limProcessMlmAddBARsp( tpAniSirGlobal pMac, tANI_U32 *pMsgBuf ) { tpLimMlmAddBARsp pMlmAddBARsp; tANI_U16 aid; tpDphHashNode pSta; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } pMlmAddBARsp = (tpLimMlmAddBARsp) pMsgBuf; if(( psessionEntry = peFindSessionBySessionId(pMac,pMlmAddBARsp->sessionId))== NULL) { PELOGE(limLog(pMac, LOGE, FL("session does not exist for given session ID"));) vos_mem_free(pMsgBuf); return; } // Send ADDBA Rsp over the air if( eSIR_SUCCESS != limSendAddBARsp( pMac,pMlmAddBARsp,psessionEntry)) { limLog( pMac, LOGE, FL("Failed to send ADDBA Rsp to peer ")); limPrintMacAddr( pMac, pMlmAddBARsp->peerMacAddr, LOGE ); /* Clean the BA context maintained by HAL and TL on failure */ pSta = dphLookupHashEntry( pMac, pMlmAddBARsp->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable); if( NULL != pSta ) { limPostMsgDelBAInd( pMac, pSta, pMlmAddBARsp->baTID, eBA_RECIPIENT, psessionEntry); } } // Time to post a WDA_DELBA_IND to HAL in order // to cleanup the HAL and SoftMAC entries // Free the buffer allocated for tLimMlmAddBARsp vos_mem_free(pMsgBuf); } /** * \brief Setup an A-MPDU/BA session * * \sa limProcessMlmDelBAReq * * \param pMac The global tpAniSirGlobal object * * \param pMsgBuf The MLME DELBA Req message buffer * * \return none */ void limProcessMlmDelBAReq( tpAniSirGlobal pMac, tANI_U32 *pMsgBuf ) { tSirRetStatus status = eSIR_SUCCESS; tpLimMlmDelBAReq pMlmDelBAReq; tpLimMlmDelBACnf pMlmDelBACnf; tpPESession psessionEntry; if(pMsgBuf == NULL) { PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));) return; } // TODO - Need to validate MLME state pMlmDelBAReq = (tpLimMlmDelBAReq) pMsgBuf; if((psessionEntry = peFindSessionBySessionId(pMac,pMlmDelBAReq->sessionId))== NULL) { PELOGE(limLog(pMac, LOGE,FL("session does not exist for given bssId"));) vos_mem_free(pMsgBuf); return; } // Send DELBA Ind over the air if( eSIR_SUCCESS != (status = limSendDelBAInd( pMac, pMlmDelBAReq,psessionEntry))) status = eSIR_SME_HAL_SEND_MESSAGE_FAIL; else { tANI_U16 aid; tpDphHashNode pSta; // Time to post a WDA_DELBA_IND to HAL in order // to cleanup the HAL and SoftMAC entries pSta = dphLookupHashEntry( pMac, pMlmDelBAReq->peerMacAddr, &aid , &psessionEntry->dph.dphHashTable); if( NULL != pSta ) { status = limPostMsgDelBAInd( pMac, pSta, pMlmDelBAReq->baTID, pMlmDelBAReq->baDirection,psessionEntry); } } // // Respond immediately to SME with DELBA CNF using // LIM_MLM_DELBA_CNF with appropriate status // // Allocate for LIM_MLM_DELBA_CNF pMlmDelBACnf = vos_mem_malloc(sizeof( tLimMlmDelBACnf )); if ( NULL == pMlmDelBACnf ) { limLog( pMac, LOGP, FL("AllocateMemory failed")); vos_mem_free(pMsgBuf); return; } else { vos_mem_set((void *) pMlmDelBACnf, sizeof( tLimMlmDelBACnf ), 0); vos_mem_copy((void *) pMlmDelBACnf, (void *) pMlmDelBAReq, sizeof( tLimMlmDelBAReq )); // Update DELBA result code pMlmDelBACnf->delBAReasonCode = pMlmDelBAReq->delBAReasonCode; /* Update PE session Id*/ pMlmDelBACnf->sessionId = pMlmDelBAReq->sessionId; limPostSmeMessage( pMac, LIM_MLM_DELBA_CNF, (tANI_U32 *) pMlmDelBACnf ); } // Free the buffer allocated for tLimMlmDelBAReq vos_mem_free(pMsgBuf); } /** * @function : limSMPowerSaveStateInd( ) * * @brief : This function is called upon receiving the PMC Indication to update the STA's MimoPs State. * * LOGIC: * * ASSUMPTIONS: * NA * * NOTE: * NA * * @param pMac - Pointer to Global MAC structure * @param limMsg - Lim Message structure object with the MimoPSparam in body * @return None */ tSirRetStatus limSMPowerSaveStateInd(tpAniSirGlobal pMac, tSirMacHTMIMOPowerSaveState state) { #if 0 tSirRetStatus retStatus = eSIR_SUCCESS; #if 0 tANI_U32 cfgVal1; tANI_U16 cfgVal2; tSirMacHTCapabilityInfo *pHTCapabilityInfo; tpDphHashNode pSta = NULL; tpPESession psessionEntry = &pMac->lim.gpSession[0]; //TBD-RAJESH HOW TO GET sessionEntry????? /** Verify the Mode of operation */ if (pMac->lim.gLimSystemRole != eSYSTEM_STA_ROLE) { PELOGE(limLog(pMac, LOGE, FL("Got PMC indication when System not in the STA Role"));) return eSIR_FAILURE; } if ((pMac->lim.gHTMIMOPSState == state) || (state == eSIR_HT_MIMO_PS_NA )) { PELOGE(limLog(pMac, LOGE, FL("Got Indication when already in the same mode or State passed is NA:%d "), state);) return eSIR_FAILURE; } if (!pMac->lim.htCapability){ PELOGW(limLog(pMac, LOGW, FL(" Not in 11n or HT capable mode"));) return eSIR_FAILURE; } /** Update the CFG about the default MimoPS State */ if (wlan_cfgGetInt(pMac, WNI_CFG_HT_CAP_INFO, &cfgVal1) != eSIR_SUCCESS) { limLog(pMac, LOGP, FL("could not retrieve HT Cap CFG ")); return eSIR_FAILURE; } cfgVal2 = (tANI_U16)cfgVal1; pHTCapabilityInfo = (tSirMacHTCapabilityInfo *) &cfgVal2; pHTCapabilityInfo->mimoPowerSave = state; if(cfgSetInt(pMac, WNI_CFG_HT_CAP_INFO, *(tANI_U16*)pHTCapabilityInfo) != eSIR_SUCCESS) { limLog(pMac, LOGP, FL("could not update HT Cap Info CFG")); return eSIR_FAILURE; } PELOG2(limLog(pMac, LOG2, FL(" The HT Capability for Mimo Pwr is updated to State: %u "),state);) if (pMac->lim.gLimSmeState != eLIM_SME_LINK_EST_STATE) { PELOG2(limLog(pMac, LOG2,FL(" The STA is not in the Connected/Link Est Sme_State: %d "), pMac->lim.gLimSmeState);) /** Update in the LIM the MIMO PS state of the SELF */ pMac->lim.gHTMIMOPSState = state; return eSIR_SUCCESS; } pSta = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable); if (!pSta->mlmStaContext.htCapability) { limLog( pMac, LOGE,FL( "limSendSMPowerState: Peer is not HT Capable " )); return eSIR_FAILURE; } if (isEnteringMimoPS(pMac->lim.gHTMIMOPSState, state)) { tSirMacAddr macAddr; /** Obtain the AP's Mac Address */ vos_mem_copy((tANI_U8 *)macAddr, psessionEntry->bssId, sizeof(tSirMacAddr)); /** Send Action Frame with the corresponding mode */ retStatus = limSendSMPowerStateFrame(pMac, macAddr, state); if (retStatus != eSIR_SUCCESS) { PELOGE(limLog(pMac, LOGE, "Update SM POWER: Sending Action Frame has failed");) return retStatus; } } /** Update MlmState about the SetMimoPS State */ pMac->lim.gLimPrevMlmState = pMac->lim.gLimMlmState; pMac->lim.gLimMlmState = eLIM_MLM_WT_SET_MIMOPS_STATE; MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, 0, pMac->lim.gLimMlmState)); /** Update the HAL and s/w mac about the mode to be set */ retStatus = limPostSMStateUpdate( pMac,psessionEntry->staId, state); PELOG2(limLog(pMac, LOG2, " Updated the New SMPS State");) /** Update in the LIM the MIMO PS state of the SELF */ pMac->lim.gHTMIMOPSState = state; #endif return retStatus; #endif return eSIR_SUCCESS; } #ifdef WLAN_FEATURE_11AC ePhyChanBondState limGet11ACPhyCBState(tpAniSirGlobal pMac, tANI_U8 channel, tANI_U8 htSecondaryChannelOffset,tANI_U8 peerCenterChan, tpPESession psessionEntry) { ePhyChanBondState cbState = PHY_SINGLE_CHANNEL_CENTERED; if(!psessionEntry->apChanWidth) { return htSecondaryChannelOffset; } if ( (htSecondaryChannelOffset == PHY_DOUBLE_CHANNEL_LOW_PRIMARY) ) { if ((channel + 2 ) == peerCenterChan ) cbState = PHY_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_CENTERED; else if ((channel + 6 ) == peerCenterChan ) cbState = PHY_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_LOW; else if ((channel - 2 ) == peerCenterChan ) cbState = PHY_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_HIGH; else limLog (pMac, LOGP, FL("Invalid Channel Number = %d Center Chan = %d "), channel, peerCenterChan); } if ( (htSecondaryChannelOffset == PHY_DOUBLE_CHANNEL_HIGH_PRIMARY) ) { if ((channel - 2 ) == peerCenterChan ) cbState = PHY_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_CENTERED; else if ((channel + 2 ) == peerCenterChan ) cbState = PHY_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_LOW; else if ((channel - 6 ) == peerCenterChan ) cbState = PHY_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_HIGH; else limLog (pMac, LOGP, FL("Invalid Channel Number = %d Center Chan = %d "), channel, peerCenterChan); } return cbState; } #endif void limSetChannel(tpAniSirGlobal pMac, tANI_U8 channel, tANI_U8 secChannelOffset, tPowerdBm maxTxPower, tANI_U8 peSessionId) { #if !defined WLAN_FEATURE_VOWIFI tANI_U32 localPwrConstraint; #endif tpPESession peSession; peSession = peFindSessionBySessionId (pMac, peSessionId); if ( NULL == peSession) { limLog (pMac, LOGP, FL("Invalid PE session = %d"), peSessionId); return; } #if defined WLAN_FEATURE_VOWIFI #ifdef WLAN_FEATURE_11AC if ( peSession->vhtCapability ) { limSendSwitchChnlParams( pMac, channel, limGet11ACPhyCBState( pMac,channel,secChannelOffset,peSession->apCenterChan, peSession), maxTxPower, peSessionId); } else #endif { limSendSwitchChnlParams( pMac, channel, secChannelOffset, maxTxPower, peSessionId); } #else if (wlan_cfgGetInt(pMac, WNI_CFG_LOCAL_POWER_CONSTRAINT, &localPwrConstraint) != eSIR_SUCCESS) { limLog(pMac, LOGP, FL("could not read WNI_CFG_LOCAL_POWER_CONSTRAINT from CFG")); return; } // Send WDA_CHNL_SWITCH_IND to HAL #ifdef WLAN_FEATURE_11AC if ( peSession->vhtCapability && peSession->vhtCapabilityPresentInBeacon) { limSendSwitchChnlParams( pMac, channel, limGet11ACPhyCBState( pMac,channel,secChannelOffset,peSession->apCenterChan, peSession), maxTxPower, peSessionId); } else #endif { limSendSwitchChnlParams( pMac, channel, secChannelOffset, (tPowerdBm)localPwrConstraint, peSessionId); } #endif }
M8s-dev/kernel_htc_msm8939
drivers/staging/prima/CORE/MAC/src/pe/lim/limProcessMlmReqMessages.c
C
gpl-2.0
180,775
/* * mtrr.c: MTRR/PAT virtualization * * Copyright (c) 2007, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307 USA. */ #include <public/hvm/e820.h> #include <xen/types.h> #include <asm/e820.h> #include <asm/mm.h> #include <asm/paging.h> #include <asm/p2m.h> #include <xen/domain_page.h> #include <asm/mtrr.h> #include <asm/hvm/support.h> #include <asm/hvm/cacheattr.h> static uint32_t size_or_mask; /* Get page attribute fields (PAn) from PAT MSR. */ #define pat_cr_2_paf(pat_cr,n) ((((uint64_t)pat_cr) >> ((n)<<3)) & 0xff) /* PAT entry to PTE flags (PAT, PCD, PWT bits). */ static uint8_t pat_entry_2_pte_flags[8] = { 0, _PAGE_PWT, _PAGE_PCD, _PAGE_PCD | _PAGE_PWT, _PAGE_PAT, _PAGE_PAT | _PAGE_PWT, _PAGE_PAT | _PAGE_PCD, _PAGE_PAT | _PAGE_PCD | _PAGE_PWT }; /* Effective mm type lookup table, according to MTRR and PAT. */ static uint8_t mm_type_tbl[MTRR_NUM_TYPES][PAT_TYPE_NUMS] = { /********PAT(UC,WC,RS,RS,WT,WP,WB,UC-)*/ /* RS means reserved type(2,3), and type is hardcoded here */ /*MTRR(UC):(UC,WC,RS,RS,UC,UC,UC,UC)*/ {0, 1, 2, 2, 0, 0, 0, 0}, /*MTRR(WC):(UC,WC,RS,RS,UC,UC,WC,WC)*/ {0, 1, 2, 2, 0, 0, 1, 1}, /*MTRR(RS):(RS,RS,RS,RS,RS,RS,RS,RS)*/ {2, 2, 2, 2, 2, 2, 2, 2}, /*MTRR(RS):(RS,RS,RS,RS,RS,RS,RS,RS)*/ {2, 2, 2, 2, 2, 2, 2, 2}, /*MTRR(WT):(UC,WC,RS,RS,WT,WP,WT,UC)*/ {0, 1, 2, 2, 4, 5, 4, 0}, /*MTRR(WP):(UC,WC,RS,RS,WT,WP,WP,WC)*/ {0, 1, 2, 2, 4, 5, 5, 1}, /*MTRR(WB):(UC,WC,RS,RS,WT,WP,WB,UC)*/ {0, 1, 2, 2, 4, 5, 6, 0} }; /* * Reverse lookup table, to find a pat type according to MTRR and effective * memory type. This table is dynamically generated. */ static uint8_t mtrr_epat_tbl[MTRR_NUM_TYPES][MEMORY_NUM_TYPES]; /* Lookup table for PAT entry of a given PAT value in host PAT. */ static uint8_t pat_entry_tbl[PAT_TYPE_NUMS]; static void get_mtrr_range(uint64_t base_msr, uint64_t mask_msr, uint64_t *base, uint64_t *end) { uint32_t mask_lo = (uint32_t)mask_msr; uint32_t mask_hi = (uint32_t)(mask_msr >> 32); uint32_t base_lo = (uint32_t)base_msr; uint32_t base_hi = (uint32_t)(base_msr >> 32); uint32_t size; if ( (mask_lo & 0x800) == 0 ) { /* Invalid (i.e. free) range */ *base = 0; *end = 0; return; } /* Work out the shifted address mask. */ mask_lo = (size_or_mask | (mask_hi << (32 - PAGE_SHIFT)) | (mask_lo >> PAGE_SHIFT)); /* This works correctly if size is a power of two (a contiguous range). */ size = -mask_lo; *base = base_hi << (32 - PAGE_SHIFT) | base_lo >> PAGE_SHIFT; *end = *base + size - 1; } bool_t is_var_mtrr_overlapped(struct mtrr_state *m) { int32_t seg, i; uint64_t phys_base, phys_mask, phys_base_pre, phys_mask_pre; uint64_t base_pre, end_pre, base, end; uint8_t num_var_ranges = (uint8_t)m->mtrr_cap; for ( i = 0; i < num_var_ranges; i++ ) { phys_base_pre = ((uint64_t*)m->var_ranges)[i*2]; phys_mask_pre = ((uint64_t*)m->var_ranges)[i*2 + 1]; get_mtrr_range(phys_base_pre, phys_mask_pre, &base_pre, &end_pre); for ( seg = i + 1; seg < num_var_ranges; seg ++ ) { phys_base = ((uint64_t*)m->var_ranges)[seg*2]; phys_mask = ((uint64_t*)m->var_ranges)[seg*2 + 1]; get_mtrr_range(phys_base, phys_mask, &base, &end); if ( ((base_pre != end_pre) && (base != end)) || ((base >= base_pre) && (base <= end_pre)) || ((end >= base_pre) && (end <= end_pre)) || ((base_pre >= base) && (base_pre <= end)) || ((end_pre >= base) && (end_pre <= end)) ) { /* MTRR is overlapped. */ return 1; } } } return 0; } #define MTRR_PHYSMASK_VALID_BIT 11 #define MTRR_PHYSMASK_SHIFT 12 #define MTRR_PHYSBASE_TYPE_MASK 0xff /* lowest 8 bits */ #define MTRR_PHYSBASE_SHIFT 12 #define MTRR_VCNT 8 #define MTRRphysBase_MSR(reg) (0x200 + 2 * (reg)) #define MTRRphysMask_MSR(reg) (0x200 + 2 * (reg) + 1) static int hvm_mtrr_pat_init(void) { unsigned int i, j, phys_addr; memset(&mtrr_epat_tbl, INVALID_MEM_TYPE, sizeof(mtrr_epat_tbl)); for ( i = 0; i < MTRR_NUM_TYPES; i++ ) { for ( j = 0; j < PAT_TYPE_NUMS; j++ ) { int32_t tmp = mm_type_tbl[i][j]; if ( (tmp >= 0) && (tmp < MEMORY_NUM_TYPES) ) mtrr_epat_tbl[i][tmp] = j; } } memset(&pat_entry_tbl, INVALID_MEM_TYPE, PAT_TYPE_NUMS * sizeof(pat_entry_tbl[0])); for ( i = 0; i < PAT_TYPE_NUMS; i++ ) { for ( j = 0; j < PAT_TYPE_NUMS; j++ ) { if ( pat_cr_2_paf(host_pat, j) == i ) { pat_entry_tbl[i] = j; break; } } } phys_addr = 36; if ( cpuid_eax(0x80000000) >= 0x80000008 ) phys_addr = (uint8_t)cpuid_eax(0x80000008); size_or_mask = ~((1 << (phys_addr - PAGE_SHIFT)) - 1); return 0; } __initcall(hvm_mtrr_pat_init); uint8_t pat_type_2_pte_flags(uint8_t pat_type) { int32_t pat_entry = pat_entry_tbl[pat_type]; /* INVALID_MEM_TYPE, means doesn't find the pat_entry in host pat for * a given pat_type. If host pat covers all the pat types, * it can't happen. */ if ( likely(pat_entry != INVALID_MEM_TYPE) ) return pat_entry_2_pte_flags[pat_entry]; return pat_entry_2_pte_flags[pat_entry_tbl[PAT_TYPE_UNCACHABLE]]; } int hvm_vcpu_cacheattr_init(struct vcpu *v) { struct mtrr_state *m = &v->arch.hvm_vcpu.mtrr; memset(m, 0, sizeof(*m)); m->var_ranges = xzalloc_array(struct mtrr_var_range, MTRR_VCNT); if ( m->var_ranges == NULL ) return -ENOMEM; m->mtrr_cap = (1u << 10) | (1u << 8) | MTRR_VCNT; v->arch.hvm_vcpu.pat_cr = ((uint64_t)PAT_TYPE_WRBACK) | /* PAT0: WB */ ((uint64_t)PAT_TYPE_WRTHROUGH << 8) | /* PAT1: WT */ ((uint64_t)PAT_TYPE_UC_MINUS << 16) | /* PAT2: UC- */ ((uint64_t)PAT_TYPE_UNCACHABLE << 24) | /* PAT3: UC */ ((uint64_t)PAT_TYPE_WRBACK << 32) | /* PAT4: WB */ ((uint64_t)PAT_TYPE_WRTHROUGH << 40) | /* PAT5: WT */ ((uint64_t)PAT_TYPE_UC_MINUS << 48) | /* PAT6: UC- */ ((uint64_t)PAT_TYPE_UNCACHABLE << 56); /* PAT7: UC */ return 0; } void hvm_vcpu_cacheattr_destroy(struct vcpu *v) { xfree(v->arch.hvm_vcpu.mtrr.var_ranges); } /* * Get MTRR memory type for physical address pa. */ static uint8_t get_mtrr_type(struct mtrr_state *m, paddr_t pa) { int32_t addr, seg, index; uint8_t overlap_mtrr = 0; uint8_t overlap_mtrr_pos = 0; uint64_t phys_base; uint64_t phys_mask; uint8_t num_var_ranges = m->mtrr_cap & 0xff; if ( unlikely(!(m->enabled & 0x2)) ) return MTRR_TYPE_UNCACHABLE; if ( (pa < 0x100000) && (m->enabled & 1) ) { /* Fixed range MTRR takes effective */ addr = (uint32_t) pa; if ( addr < 0x80000 ) { seg = (addr >> 16); return m->fixed_ranges[seg]; } else if ( addr < 0xc0000 ) { seg = (addr - 0x80000) >> 14; index = (seg >> 3) + 1; seg &= 7; /* select 0-7 segments */ return m->fixed_ranges[index*8 + seg]; } else { /* 0xC0000 --- 0x100000 */ seg = (addr - 0xc0000) >> 12; index = (seg >> 3) + 3; seg &= 7; /* select 0-7 segments */ return m->fixed_ranges[index*8 + seg]; } } /* Match with variable MTRRs. */ for ( seg = 0; seg < num_var_ranges; seg++ ) { phys_base = ((uint64_t*)m->var_ranges)[seg*2]; phys_mask = ((uint64_t*)m->var_ranges)[seg*2 + 1]; if ( phys_mask & (1 << MTRR_PHYSMASK_VALID_BIT) ) { if ( ((uint64_t) pa & phys_mask) >> MTRR_PHYSMASK_SHIFT == (phys_base & phys_mask) >> MTRR_PHYSMASK_SHIFT ) { if ( unlikely(m->overlapped) ) { overlap_mtrr |= 1 << (phys_base & MTRR_PHYSBASE_TYPE_MASK); overlap_mtrr_pos = phys_base & MTRR_PHYSBASE_TYPE_MASK; } else { /* If no overlap, return the found one */ return (phys_base & MTRR_PHYSBASE_TYPE_MASK); } } } } /* Overlapped or not found. */ if ( unlikely(overlap_mtrr == 0) ) return m->def_type; if ( likely(!(overlap_mtrr & ~( ((uint8_t)1) << overlap_mtrr_pos ))) ) /* Covers both one variable memory range matches and * two or more identical match. */ return overlap_mtrr_pos; if ( overlap_mtrr & 0x1 ) /* Two or more match, one is UC. */ return MTRR_TYPE_UNCACHABLE; if ( !(overlap_mtrr & 0xaf) ) /* Two or more match, WT and WB. */ return MTRR_TYPE_WRTHROUGH; /* Behaviour is undefined, but return the last overlapped type. */ return overlap_mtrr_pos; } /* * return the memory type from PAT. * NOTE: valid only when paging is enabled. * Only 4K page PTE is supported now. */ static uint8_t page_pat_type(uint64_t pat_cr, uint32_t pte_flags) { int32_t pat_entry; /* PCD/PWT -> bit 1/0 of PAT entry */ pat_entry = ( pte_flags >> 3 ) & 0x3; /* PAT bits as bit 2 of PAT entry */ if ( pte_flags & _PAGE_PAT ) pat_entry |= 4; return (uint8_t)pat_cr_2_paf(pat_cr, pat_entry); } /* * Effective memory type for leaf page. */ static uint8_t effective_mm_type(struct mtrr_state *m, uint64_t pat, paddr_t gpa, uint32_t pte_flags, uint8_t gmtrr_mtype) { uint8_t mtrr_mtype, pat_value, effective; /* if get_pat_flags() gives a dedicated MTRR type, * just use it */ if ( gmtrr_mtype == NO_HARDCODE_MEM_TYPE ) mtrr_mtype = get_mtrr_type(m, gpa); else mtrr_mtype = gmtrr_mtype; pat_value = page_pat_type(pat, pte_flags); effective = mm_type_tbl[mtrr_mtype][pat_value]; return effective; } uint32_t get_pat_flags(struct vcpu *v, uint32_t gl1e_flags, paddr_t gpaddr, paddr_t spaddr, uint8_t gmtrr_mtype) { uint8_t guest_eff_mm_type; uint8_t shadow_mtrr_type; uint8_t pat_entry_value; uint64_t pat = v->arch.hvm_vcpu.pat_cr; struct mtrr_state *g = &v->arch.hvm_vcpu.mtrr; /* 1. Get the effective memory type of guest physical address, * with the pair of guest MTRR and PAT */ guest_eff_mm_type = effective_mm_type(g, pat, gpaddr, gl1e_flags, gmtrr_mtype); /* 2. Get the memory type of host physical address, with MTRR */ shadow_mtrr_type = get_mtrr_type(&mtrr_state, spaddr); /* 3. Find the memory type in PAT, with host MTRR memory type * and guest effective memory type. */ pat_entry_value = mtrr_epat_tbl[shadow_mtrr_type][guest_eff_mm_type]; /* If conflit occurs(e.g host MTRR is UC, guest memory type is * WB),set UC as effective memory. Here, returning PAT_TYPE_UNCACHABLE will * always set effective memory as UC. */ if ( pat_entry_value == INVALID_MEM_TYPE ) { struct domain *d = v->domain; p2m_type_t p2mt; get_gfn_query_unlocked(d, paddr_to_pfn(gpaddr), &p2mt); if (p2m_is_ram(p2mt)) gdprintk(XENLOG_WARNING, "Conflict occurs for a given guest l1e flags:%x " "at %"PRIx64" (the effective mm type:%d), " "because the host mtrr type is:%d\n", gl1e_flags, (uint64_t)gpaddr, guest_eff_mm_type, shadow_mtrr_type); pat_entry_value = PAT_TYPE_UNCACHABLE; } /* 4. Get the pte flags */ return pat_type_2_pte_flags(pat_entry_value); } bool_t mtrr_def_type_msr_set(struct mtrr_state *m, uint64_t msr_content) { uint8_t def_type = msr_content & 0xff; uint8_t enabled = (msr_content >> 10) & 0x3; if ( unlikely(!(def_type == 0 || def_type == 1 || def_type == 4 || def_type == 5 || def_type == 6)) ) { HVM_DBG_LOG(DBG_LEVEL_MSR, "invalid MTRR def type:%x\n", def_type); return 0; } if ( unlikely(msr_content && (msr_content & ~0xcffUL)) ) { HVM_DBG_LOG(DBG_LEVEL_MSR, "invalid msr content:%"PRIx64"\n", msr_content); return 0; } m->enabled = enabled; m->def_type = def_type; return 1; } bool_t mtrr_fix_range_msr_set(struct mtrr_state *m, uint32_t row, uint64_t msr_content) { uint64_t *fixed_range_base = (uint64_t *)m->fixed_ranges; if ( fixed_range_base[row] != msr_content ) { uint8_t *range = (uint8_t*)&msr_content; int32_t i, type; for ( i = 0; i < 8; i++ ) { type = range[i]; if ( unlikely(!(type == 0 || type == 1 || type == 4 || type == 5 || type == 6)) ) return 0; } fixed_range_base[row] = msr_content; } return 1; } bool_t mtrr_var_range_msr_set( struct domain *d, struct mtrr_state *m, uint32_t msr, uint64_t msr_content) { uint32_t index, type, phys_addr, eax, ebx, ecx, edx; uint64_t msr_mask; uint64_t *var_range_base = (uint64_t*)m->var_ranges; index = msr - MSR_IA32_MTRR_PHYSBASE0; if ( var_range_base[index] == msr_content ) return 1; type = (uint8_t)msr_content; if ( unlikely(!(type == 0 || type == 1 || type == 4 || type == 5 || type == 6)) ) return 0; phys_addr = 36; domain_cpuid(d, 0x80000000, 0, &eax, &ebx, &ecx, &edx); if ( eax >= 0x80000008 ) { domain_cpuid(d, 0x80000008, 0, &eax, &ebx, &ecx, &edx); phys_addr = (uint8_t)eax; } msr_mask = ~((((uint64_t)1) << phys_addr) - 1); msr_mask |= (index & 1) ? 0x7ffUL : 0xf00UL; if ( unlikely(msr_content && (msr_content & msr_mask)) ) { HVM_DBG_LOG(DBG_LEVEL_MSR, "invalid msr content:%"PRIx64"\n", msr_content); return 0; } var_range_base[index] = msr_content; m->overlapped = is_var_mtrr_overlapped(m); return 1; } bool_t mtrr_pat_not_equal(struct vcpu *vd, struct vcpu *vs) { struct mtrr_state *md = &vd->arch.hvm_vcpu.mtrr; struct mtrr_state *ms = &vs->arch.hvm_vcpu.mtrr; int32_t res; uint8_t num_var_ranges = (uint8_t)md->mtrr_cap; /* Test fixed ranges. */ res = memcmp(md->fixed_ranges, ms->fixed_ranges, NUM_FIXED_RANGES*sizeof(mtrr_type)); if ( res ) return 1; /* Test var ranges. */ res = memcmp(md->var_ranges, ms->var_ranges, num_var_ranges*sizeof(struct mtrr_var_range)); if ( res ) return 1; /* Test default type MSR. */ if ( (md->def_type != ms->def_type) && (md->enabled != ms->enabled) ) return 1; /* Test PAT. */ if ( vd->arch.hvm_vcpu.pat_cr != vs->arch.hvm_vcpu.pat_cr ) return 1; return 0; } void hvm_init_cacheattr_region_list( struct domain *d) { INIT_LIST_HEAD(&d->arch.hvm_domain.pinned_cacheattr_ranges); } void hvm_destroy_cacheattr_region_list( struct domain *d) { struct list_head *head = &d->arch.hvm_domain.pinned_cacheattr_ranges; struct hvm_mem_pinned_cacheattr_range *range; while ( !list_empty(head) ) { range = list_entry(head->next, struct hvm_mem_pinned_cacheattr_range, list); list_del(&range->list); xfree(range); } } int32_t hvm_get_mem_pinned_cacheattr( struct domain *d, uint64_t guest_fn, uint32_t *type) { struct hvm_mem_pinned_cacheattr_range *range; *type = 0; if ( !is_hvm_domain(d) ) return 0; list_for_each_entry_rcu ( range, &d->arch.hvm_domain.pinned_cacheattr_ranges, list ) { if ( (guest_fn >= range->start) && (guest_fn <= range->end) ) { *type = range->type; return 1; } } return 0; } int32_t hvm_set_mem_pinned_cacheattr( struct domain *d, uint64_t gfn_start, uint64_t gfn_end, uint32_t type) { struct hvm_mem_pinned_cacheattr_range *range; if ( !((type == PAT_TYPE_UNCACHABLE) || (type == PAT_TYPE_WRCOMB) || (type == PAT_TYPE_WRTHROUGH) || (type == PAT_TYPE_WRPROT) || (type == PAT_TYPE_WRBACK) || (type == PAT_TYPE_UC_MINUS)) || !is_hvm_domain(d) ) return -EINVAL; range = xzalloc(struct hvm_mem_pinned_cacheattr_range); if ( range == NULL ) return -ENOMEM; range->start = gfn_start; range->end = gfn_end; range->type = type; list_add_rcu(&range->list, &d->arch.hvm_domain.pinned_cacheattr_ranges); return 0; } static int hvm_save_mtrr_msr(struct domain *d, hvm_domain_context_t *h) { int i; struct vcpu *v; struct hvm_hw_mtrr hw_mtrr; struct mtrr_state *mtrr_state; /* save mtrr&pat */ for_each_vcpu(d, v) { mtrr_state = &v->arch.hvm_vcpu.mtrr; hvm_get_guest_pat(v, &hw_mtrr.msr_pat_cr); hw_mtrr.msr_mtrr_def_type = mtrr_state->def_type | (mtrr_state->enabled << 10); hw_mtrr.msr_mtrr_cap = mtrr_state->mtrr_cap; for ( i = 0; i < MTRR_VCNT; i++ ) { /* save physbase */ hw_mtrr.msr_mtrr_var[i*2] = ((uint64_t*)mtrr_state->var_ranges)[i*2]; /* save physmask */ hw_mtrr.msr_mtrr_var[i*2+1] = ((uint64_t*)mtrr_state->var_ranges)[i*2+1]; } for ( i = 0; i < NUM_FIXED_MSR; i++ ) hw_mtrr.msr_mtrr_fixed[i] = ((uint64_t*)mtrr_state->fixed_ranges)[i]; if ( hvm_save_entry(MTRR, v->vcpu_id, h, &hw_mtrr) != 0 ) return 1; } return 0; } static int hvm_load_mtrr_msr(struct domain *d, hvm_domain_context_t *h) { int vcpuid, i; struct vcpu *v; struct mtrr_state *mtrr_state; struct hvm_hw_mtrr hw_mtrr; vcpuid = hvm_load_instance(h); if ( vcpuid >= d->max_vcpus || (v = d->vcpu[vcpuid]) == NULL ) { dprintk(XENLOG_G_ERR, "HVM restore: dom%d has no vcpu%u\n", d->domain_id, vcpuid); return -EINVAL; } if ( hvm_load_entry(MTRR, h, &hw_mtrr) != 0 ) return -EINVAL; mtrr_state = &v->arch.hvm_vcpu.mtrr; hvm_set_guest_pat(v, hw_mtrr.msr_pat_cr); mtrr_state->mtrr_cap = hw_mtrr.msr_mtrr_cap; for ( i = 0; i < NUM_FIXED_MSR; i++ ) mtrr_fix_range_msr_set(mtrr_state, i, hw_mtrr.msr_mtrr_fixed[i]); for ( i = 0; i < MTRR_VCNT; i++ ) { mtrr_var_range_msr_set(d, mtrr_state, MTRRphysBase_MSR(i), hw_mtrr.msr_mtrr_var[i*2]); mtrr_var_range_msr_set(d, mtrr_state, MTRRphysMask_MSR(i), hw_mtrr.msr_mtrr_var[i*2+1]); } mtrr_def_type_msr_set(mtrr_state, hw_mtrr.msr_mtrr_def_type); return 0; } HVM_REGISTER_SAVE_RESTORE(MTRR, hvm_save_mtrr_msr, hvm_load_mtrr_msr, 1, HVMSR_PER_VCPU); uint8_t epte_get_entry_emt(struct domain *d, unsigned long gfn, mfn_t mfn, uint8_t *ipat, bool_t direct_mmio) { uint8_t gmtrr_mtype, hmtrr_mtype; uint32_t type; struct vcpu *v = current; *ipat = 0; if ( (current->domain != d) && ((d->vcpu == NULL) || ((v = d->vcpu[0]) == NULL)) ) return MTRR_TYPE_WRBACK; if ( !v->domain->arch.hvm_domain.params[HVM_PARAM_IDENT_PT] ) return MTRR_TYPE_WRBACK; if ( (v == current) && v->domain->arch.hvm_domain.is_in_uc_mode ) return MTRR_TYPE_UNCACHABLE; if ( !mfn_valid(mfn_x(mfn)) ) return MTRR_TYPE_UNCACHABLE; if ( hvm_get_mem_pinned_cacheattr(d, gfn, &type) ) return type; if ( !iommu_enabled ) { *ipat = 1; return MTRR_TYPE_WRBACK; } if ( direct_mmio ) return MTRR_TYPE_UNCACHABLE; if ( iommu_snoop ) { *ipat = 1; return MTRR_TYPE_WRBACK; } gmtrr_mtype = get_mtrr_type(&v->arch.hvm_vcpu.mtrr, (gfn << PAGE_SHIFT)); hmtrr_mtype = get_mtrr_type(&mtrr_state, (mfn_x(mfn) << PAGE_SHIFT)); return ((gmtrr_mtype <= hmtrr_mtype) ? gmtrr_mtype : hmtrr_mtype); }
abligh/xen4.2-minideb
xen/arch/x86/hvm/mtrr.c
C
gpl-2.0
21,579
<?php /** * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests * @since 1.2.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Test\TestCase\Network; use Cake\Cache\Cache; use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Network\Session; use Cake\Network\Session\CacheSession; use Cake\Network\Session\DatabaseSession; use Cake\TestSuite\TestCase; /** * Class TestCacheSession * */ class TestCacheSession extends CacheSession { protected function _writeSession() { return true; } } /** * Class TestDatabaseSession * */ class TestDatabaseSession extends DatabaseSession { protected function _writeSession() { return true; } } /** * SessionTest class * */ class SessionTest extends TestCase { protected static $_gcDivisor; /** * Fixtures used in the SessionTest * * @var array */ public $fixtures = ['core.sessions', 'core.cake_sessions']; /** * setup before class. * * @return void */ public static function setupBeforeClass() { // Make sure garbage collector will be called static::$_gcDivisor = ini_get('session.gc_divisor'); ini_set('session.gc_divisor', '1'); } /** * teardown after class * * @return void */ public static function teardownAfterClass() { // Revert to the default setting ini_set('session.gc_divisor', static::$_gcDivisor); } /** * setUp method * * @return void */ public function setUp() { parent::setUp(); } /** * tearDown method * * @return void */ public function tearDown() { unset($_SESSION); parent::tearDown(); } /** * test setting ini properties with Session configuration. * * @return void */ public function testSessionConfigIniSetting() { $_SESSION = null; $config = [ 'cookie' => 'test', 'checkAgent' => false, 'timeout' => 86400, 'ini' => [ 'session.referer_check' => 'example.com', 'session.use_trans_sid' => false ] ]; $session = Session::create($config); $this->assertEquals('', ini_get('session.use_trans_sid'), 'Ini value is incorrect'); $this->assertEquals('example.com', ini_get('session.referer_check'), 'Ini value is incorrect'); $this->assertEquals('test', ini_get('session.name'), 'Ini value is incorrect'); } /** * test session cookie path setting * * @return void */ public function testCookiePath() { ini_set('session.cookie_path', '/foo'); $session = new Session(); $this->assertEquals('/', ini_get('session.cookie_path')); $session = new Session(['cookiePath' => '/base']); $this->assertEquals('/base', ini_get('session.cookie_path')); } /** * testCheck method * * @return void */ public function testCheck() { $session = new Session(); $session->write('SessionTestCase', 'value'); $this->assertTrue($session->check('SessionTestCase')); $this->assertFalse($session->check('NotExistingSessionTestCase')); $this->assertFalse($session->check('Crazy.foo')); $session->write('Crazy.foo', ['bar' => 'baz']); $this->assertTrue($session->check('Crazy.foo')); $this->assertTrue($session->check('Crazy.foo.bar')); } /** * testSimpleRead method * * @return void */ public function testSimpleRead() { $session = new Session(); $session->write('testing', '1,2,3'); $result = $session->read('testing'); $this->assertEquals('1,2,3', $result); $session->write('testing', ['1' => 'one', '2' => 'two', '3' => 'three']); $result = $session->read('testing.1'); $this->assertEquals('one', $result); $result = $session->read('testing'); $this->assertEquals(['1' => 'one', '2' => 'two', '3' => 'three'], $result); $result = $session->read(); $this->assertTrue(isset($result['testing'])); $session->write('This.is.a.deep.array.my.friend', 'value'); $result = $session->read('This.is.a.deep.array'); $this->assertEquals(['my' => ['friend' => 'value']], $result); } /** * testReadEmpty * * @return void */ public function testReadEmpty() { $session = new Session(); $this->assertNull($session->read('')); } /** * test writing a hash of values/ * * @return void */ public function testWriteArray() { $session = new Session(); $session->write([ 'one' => 1, 'two' => 2, 'three' => ['something'], 'null' => null ]); $this->assertEquals(1, $session->read('one')); $this->assertEquals(['something'], $session->read('three')); $this->assertEquals(null, $session->read('null')); } /** * Test overwriting a string value as if it were an array. * * @return void */ public function testWriteOverwriteStringValue() { $session = new Session(); $session->write('Some.string', 'value'); $this->assertEquals('value', $session->read('Some.string')); $session->write('Some.string.array', ['values']); $this->assertEquals(['values'], $session->read('Some.string.array')); } /** * Test consuming session data. * * @return void */ public function testConsume() { $session = new Session(); $session->write('Some.string', 'value'); $session->write('Some.array', ['key1' => 'value1', 'key2' => 'value2']); $this->assertEquals('value', $session->read('Some.string')); $value = $session->consume('Some.string'); $this->assertEquals('value', $value); $this->assertFalse($session->check('Some.string')); $value = $session->consume(''); $this->assertNull($value); $value = $session->consume(null); $this->assertNull($value); $value = $session->consume('Some.array'); $expected = ['key1' => 'value1', 'key2' => 'value2']; $this->assertEquals($expected, $value); $this->assertFalse($session->check('Some.array')); } /** * testId method * * @return void */ public function testId() { $session = new Session(); $result = $session->id(); $expected = session_id(); $this->assertEquals($expected, $result); $session->id('MySessionId'); $this->assertEquals('MySessionId', $session->id()); $this->assertEquals('MySessionId', session_id()); $session->id(''); $this->assertEquals('', session_id()); } /** * testStarted method * * @return void */ public function testStarted() { $session = new Session(); $this->assertFalse($session->started()); $this->assertTrue($session->start()); $this->assertTrue($session->started()); } /** * testClear method * * @return void */ public function testClear() { $session = new Session(); $session->write('Delete.me', 'Clearing out'); $session->clear(); $this->assertFalse($session->check('Delete.me')); $this->assertFalse($session->check('Delete')); } /** * testDelete method * * @return void */ public function testDelete() { $session = new Session(); $session->write('Delete.me', 'Clearing out'); $session->delete('Delete.me'); $this->assertFalse($session->check('Delete.me')); $this->assertTrue($session->check('Delete')); $session->write('Clearing.sale', 'everything must go'); $session->delete(''); $this->assertTrue($session->check('Clearing.sale')); $session->delete(null); $this->assertTrue($session->check('Clearing.sale')); $session->delete('Clearing'); $this->assertFalse($session->check('Clearing.sale')); $this->assertFalse($session->check('Clearing')); } /** * testDestroy method * * @return void */ public function testDestroy() { $session = new Session(); $session->start(); $session->write('bulletProof', 'invincible'); $session->id('foo'); $session->destroy(); $this->assertFalse($session->check('bulletProof')); } /** * testCheckingSavedEmpty method * * @return void */ public function testCheckingSavedEmpty() { $session = new Session(); $session->write('SessionTestCase', 0); $this->assertTrue($session->check('SessionTestCase')); $session->write('SessionTestCase', '0'); $this->assertTrue($session->check('SessionTestCase')); $session->write('SessionTestCase', false); $this->assertTrue($session->check('SessionTestCase')); $session->write('SessionTestCase', null); $this->assertFalse($session->check('SessionTestCase')); } /** * testCheckKeyWithSpaces method * * @return void */ public function testCheckKeyWithSpaces() { $session = new Session(); $session->write('Session Test', "test"); $this->assertTrue($session->check('Session Test')); $session->delete('Session Test'); $session->write('Session Test.Test Case', "test"); $this->assertTrue($session->check('Session Test.Test Case')); } /** * testCheckEmpty * * @return void */ public function testCheckEmpty() { $session = new Session(); $this->assertFalse($session->check()); } /** * test key exploitation * * @return void */ public function testKeyExploit() { $session = new Session(); $key = "a'] = 1; phpinfo(); \$_SESSION['a"; $session->write($key, 'haxored'); $result = $session->read($key); $this->assertNull($result); } /** * testReadingSavedEmpty method * * @return void */ public function testReadingSavedEmpty() { $session = new Session(); $session->write('SessionTestCase', 0); $this->assertEquals(0, $session->read('SessionTestCase')); $session->write('SessionTestCase', '0'); $this->assertEquals('0', $session->read('SessionTestCase')); $this->assertFalse($session->read('SessionTestCase') === 0); $session->write('SessionTestCase', false); $this->assertFalse($session->read('SessionTestCase')); $session->write('SessionTestCase', null); $this->assertEquals(null, $session->read('SessionTestCase')); } /** * test using a handler from app/Model/Datasource/Session. * * @return void */ public function testUsingAppLibsHandler() { Configure::write('App.namespace', 'TestApp'); $config = [ 'defaults' => 'cake', 'handler' => [ 'engine' => 'TestAppLibSession', 'these' => 'are', 'a few' => 'options' ] ]; $session = Session::create($config); $this->assertInstanceOf('TestApp\Network\Session\TestAppLibSession', $session->engine()); $this->assertEquals('user', ini_get('session.save_handler')); $this->assertEquals(['these' => 'are', 'a few' => 'options'], $session->engine()->options); } /** * test using a handler from a plugin. * * @return void */ public function testUsingPluginHandler() { Configure::write('App.namespace', 'TestApp'); \Cake\Core\Plugin::load('TestPlugin'); $config = [ 'defaults' => 'cake', 'handler' => [ 'engine' => 'TestPlugin.TestPluginSession' ] ]; $session = Session::create($config); $this->assertInstanceOf('TestPlugin\Network\Session\TestPluginSession', $session->engine()); $this->assertEquals('user', ini_get('session.save_handler')); } /** * Tests that it is possible to pass an already made instance as the session engine * * @return void */ public function testEngineWithPreMadeInstance() { Configure::write('App.namespace', 'TestApp'); $engine = new \TestApp\Network\Session\TestAppLibSession; $session = new Session(['handler' => ['engine' => $engine]]); $this->assertSame($engine, $session->engine()); $session = new Session(); $session->engine($engine); $this->assertSame($engine, $session->engine()); } /** * Tests instantiating a missing engine * * @expectedException \InvalidArgumentException * @expectedExceptionMessage The class "Derp" does not exist and cannot be used as a session engine * @return void */ public function testBadEngine() { $session = new Session(); $session->engine('Derp'); } /** * Test that cookieTimeout matches timeout when unspecified. * * @return void */ public function testCookieTimeoutFallback() { $config = [ 'defaults' => 'cake', 'timeout' => 400, ]; new Session($config); $this->assertEquals(0, ini_get('session.cookie_lifetime')); $this->assertEquals(400 * 60, ini_get('session.gc_maxlifetime')); } /** * Tests that the cookie name can be changed with configuration * * @return void */ public function testSessionName() { new Session(['cookie' => 'made_up_name']); $this->assertEquals('made_up_name', session_name()); } }
ringiait/portal
vendor/cakephp/cakephp/tests/TestCase/Network/SessionTest.php
PHP
gpl-2.0
14,575
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /* * * (C) Copyright IBM Corp and Others. 1998-2013 - All Rights Reserved * */ #include "LETypes.h" #include "MorphTables.h" #include "StateTables.h" #include "MorphStateTables.h" #include "SubtableProcessor2.h" #include "StateTableProcessor2.h" #include "LigatureSubstProc2.h" #include "LEGlyphStorage.h" #include "LESwaps.h" U_NAMESPACE_BEGIN #define ExtendedComplement(m) ((le_int32) (~((le_uint32) (m)))) #define SignBit(m) ((ExtendedComplement(m) >> 1) & (le_int32)(m)) #define SignExtend(v,m) (((v) & SignBit(m))? ((v) | ExtendedComplement(m)): (v)) UOBJECT_DEFINE_RTTI_IMPLEMENTATION(LigatureSubstitutionProcessor2) LigatureSubstitutionProcessor2::LigatureSubstitutionProcessor2(const LEReferenceTo<MorphSubtableHeader2> &morphSubtableHeader, LEErrorCode &success) : StateTableProcessor2(morphSubtableHeader, success), ligActionOffset(0), ligatureSubstitutionHeader(morphSubtableHeader, success), componentOffset(0), ligatureOffset(0), entryTable() { if (LE_FAILURE(success)) return; ligActionOffset = SWAPL(ligatureSubstitutionHeader->ligActionOffset); componentOffset = SWAPL(ligatureSubstitutionHeader->componentOffset); ligatureOffset = SWAPL(ligatureSubstitutionHeader->ligatureOffset); entryTable = LEReferenceToArrayOf<LigatureSubstitutionStateEntry2>(stHeader, success, entryTableOffset, LE_UNBOUNDED_ARRAY); } LigatureSubstitutionProcessor2::~LigatureSubstitutionProcessor2() { } void LigatureSubstitutionProcessor2::beginStateTable() { m = -1; } le_uint16 LigatureSubstitutionProcessor2::processStateEntry(LEGlyphStorage &glyphStorage, le_int32 &currGlyph, EntryTableIndex2 index, LEErrorCode &success) { const LigatureSubstitutionStateEntry2 *entry = entryTable.getAlias(index, success); if(LE_FAILURE(success)) return 0; le_uint16 nextStateIndex = SWAPW(entry->nextStateIndex); le_uint16 flags = SWAPW(entry->entryFlags); le_uint16 ligActionIndex = SWAPW(entry->ligActionIndex); if (flags & lsfSetComponent) { if (++m >= nComponents) { m = 0; } componentStack[m] = currGlyph; } else if ( m == -1) { // bad font- skip this glyph. //LE_DEBUG_BAD_FONT("m==-1 (componentCount went negative)") currGlyph+= dir; return nextStateIndex; } ByteOffset actionOffset = flags & lsfPerformAction; if (actionOffset != 0) { LEReferenceTo<LigatureActionEntry> ap(stHeader, success, ligActionOffset); // byte offset ap.addObject(ligActionIndex, success); LEReferenceToArrayOf<TTGlyphID> ligatureTable(stHeader, success, ligatureOffset, LE_UNBOUNDED_ARRAY); LigatureActionEntry action; le_int32 offset, i = 0, j = 0; le_int32 stack[nComponents]; le_int16 mm = -1; LEReferenceToArrayOf<le_uint16> componentTable(stHeader, success, componentOffset, LE_UNBOUNDED_ARRAY); if(LE_FAILURE(success)) { currGlyph+= dir; return nextStateIndex; // get out! bad font } do { le_uint32 componentGlyph = componentStack[m--]; // pop off if (j++ > 0) { ap.addObject(success); } action = SWAPL(*ap.getAlias()); if (m < 0) { m = nComponents - 1; } offset = action & lafComponentOffsetMask; if (offset != 0) { if(componentGlyph >= glyphStorage.getGlyphCount()) { LE_DEBUG_BAD_FONT("preposterous componentGlyph"); currGlyph+= dir; return nextStateIndex; // get out! bad font } i += SWAPW(componentTable(LE_GET_GLYPH(glyphStorage[componentGlyph]) + (SignExtend(offset, lafComponentOffsetMask)),success)); if (action & (lafLast | lafStore)) { TTGlyphID ligatureGlyph = SWAPW(ligatureTable(i,success)); glyphStorage[componentGlyph] = LE_SET_GLYPH(glyphStorage[componentGlyph], ligatureGlyph); if(mm==nComponents) { LE_DEBUG_BAD_FONT("exceeded nComponents"); mm--; // don't overrun the stack. } stack[++mm] = componentGlyph; i = 0; } else { glyphStorage[componentGlyph] = LE_SET_GLYPH(glyphStorage[componentGlyph], 0xFFFF); } } #if LE_ASSERT_BAD_FONT if(m<0) { LE_DEBUG_BAD_FONT("m<0") } #endif } while (LE_SUCCESS(success) && !(action & lafLast) && (m>=0) ); // stop if last bit is set, or if run out of items while (mm >= 0) { if (++m >= nComponents) { m = 0; } componentStack[m] = stack[mm--]; } } if (!(flags & lsfDontAdvance)) { currGlyph += dir; } return nextStateIndex; } void LigatureSubstitutionProcessor2::endStateTable() { } U_NAMESPACE_END
lizhekang/TCJDK
sources/openjdk8/jdk/src/share/native/sun/font/layout/LigatureSubstProc2.cpp
C++
gpl-2.0
6,152
/* * linux/drivers/mmc/core/bus.c * * Copyright (C) 2003 Russell King, All Rights Reserved. * Copyright (C) 2007 Pierre Ossman * * 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. * * MMC card bus driver model */ #include <linux/export.h> #include <linux/device.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/stat.h> #include <linux/pm_runtime.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include "core.h" #include "sdio_cis.h" #include "bus.h" #define to_mmc_driver(d) container_of(d, struct mmc_driver, drv) #define RUNTIME_SUSPEND_DELAY_MS 10000 static ssize_t mmc_type_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_card *card = mmc_dev_to_card(dev); switch (card->type) { case MMC_TYPE_MMC: return sprintf(buf, "MMC\n"); case MMC_TYPE_SD: return sprintf(buf, "SD\n"); case MMC_TYPE_SDIO: return sprintf(buf, "SDIO\n"); case MMC_TYPE_SD_COMBO: return sprintf(buf, "SDcombo\n"); default: return -EFAULT; } } static struct device_attribute mmc_dev_attrs[] = { __ATTR(type, S_IRUGO, mmc_type_show, NULL), __ATTR_NULL, }; static int mmc_bus_match(struct device *dev, struct device_driver *drv) { return 1; } static int mmc_bus_uevent(struct device *dev, struct kobj_uevent_env *env) { struct mmc_card *card = mmc_dev_to_card(dev); const char *type; int retval = 0; switch (card->type) { case MMC_TYPE_MMC: type = "MMC"; break; case MMC_TYPE_SD: type = "SD"; break; case MMC_TYPE_SDIO: type = "SDIO"; break; case MMC_TYPE_SD_COMBO: type = "SDcombo"; break; default: type = NULL; } if (type) { retval = add_uevent_var(env, "MMC_TYPE=%s", type); if (retval) return retval; } retval = add_uevent_var(env, "MMC_NAME=%s", mmc_card_name(card)); if (retval) return retval; retval = add_uevent_var(env, "MODALIAS=mmc:block"); return retval; } static int mmc_bus_probe(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = mmc_dev_to_card(dev); return drv->probe(card); } static int mmc_bus_remove(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = mmc_dev_to_card(dev); drv->remove(card); return 0; } static void mmc_bus_shutdown(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = mmc_dev_to_card(dev); if (!drv) { pr_debug("%s: %s: drv is NULL\n", dev_name(dev), __func__); return; } if (!card) { pr_debug("%s: %s: card is NULL\n", dev_name(dev), __func__); return; } if (drv->shutdown) drv->shutdown(card); } #ifdef CONFIG_PM_SLEEP static int mmc_bus_suspend(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = mmc_dev_to_card(dev); int ret = 0; if (dev->driver && drv->suspend) ret = drv->suspend(card); return ret; } static int mmc_bus_resume(struct device *dev) { struct mmc_driver *drv = to_mmc_driver(dev->driver); struct mmc_card *card = mmc_dev_to_card(dev); int ret = 0; if (dev->driver && drv->resume) ret = drv->resume(card); return ret; } #endif #ifdef CONFIG_PM_RUNTIME static int mmc_runtime_suspend(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); if (mmc_use_core_runtime_pm(card->host)) { if (mmc_card_doing_bkops(card) && mmc_card_is_prog_state(card)) return -EBUSY; else return 0; } else { return mmc_power_save_host(card->host); } } static int mmc_runtime_resume(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); if (mmc_use_core_runtime_pm(card->host)) return 0; else return mmc_power_restore_host(card->host); } static int mmc_runtime_idle(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); struct mmc_host *host = card->host; int ret = 0; if (mmc_use_core_runtime_pm(card->host)) { ret = pm_schedule_suspend(dev, card->idle_timeout); if ((ret < 0) && (dev->power.runtime_error || dev->power.disable_depth > 0)) { pr_err("%s: %s: %s: pm_schedule_suspend failed: err: %d\n", mmc_hostname(host), __func__, dev_name(dev), ret); return ret; } } return ret; } #endif static const struct dev_pm_ops mmc_bus_pm_ops = { SET_RUNTIME_PM_OPS(mmc_runtime_suspend, mmc_runtime_resume, mmc_runtime_idle) SET_SYSTEM_SLEEP_PM_OPS(mmc_bus_suspend, mmc_bus_resume) }; static ssize_t show_rpm_delay(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_card *card = mmc_dev_to_card(dev); if (!card) { pr_err("%s: %s: card is NULL\n", dev_name(dev), __func__); return -EINVAL; } return snprintf(buf, PAGE_SIZE, "%u\n", card->idle_timeout); } static ssize_t store_rpm_delay(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct mmc_card *card = mmc_dev_to_card(dev); unsigned int delay; if (!card) { pr_err("%s: %s: card is NULL\n", dev_name(dev), __func__); return -EINVAL; } if (!kstrtou32(buf, 0, &delay)) { if (delay < 2000) { pr_err("%s: %s: less than 2 sec delay is unsupported\n", mmc_hostname(card->host), __func__); return -EINVAL; } card->idle_timeout = delay; } return count; } static struct bus_type mmc_bus_type = { .name = "mmc", .dev_attrs = mmc_dev_attrs, .match = mmc_bus_match, .uevent = mmc_bus_uevent, .probe = mmc_bus_probe, .remove = mmc_bus_remove, .shutdown = mmc_bus_shutdown, .pm = &mmc_bus_pm_ops, }; int mmc_register_bus(void) { return bus_register(&mmc_bus_type); } void mmc_unregister_bus(void) { bus_unregister(&mmc_bus_type); } int mmc_register_driver(struct mmc_driver *drv) { drv->drv.bus = &mmc_bus_type; return driver_register(&drv->drv); } EXPORT_SYMBOL(mmc_register_driver); void mmc_unregister_driver(struct mmc_driver *drv) { drv->drv.bus = &mmc_bus_type; driver_unregister(&drv->drv); } EXPORT_SYMBOL(mmc_unregister_driver); static void mmc_release_card(struct device *dev) { struct mmc_card *card = mmc_dev_to_card(dev); sdio_free_common_cis(card); kfree(card->info); kfree(card); } struct mmc_card *mmc_alloc_card(struct mmc_host *host, struct device_type *type) { struct mmc_card *card; card = kzalloc(sizeof(struct mmc_card), GFP_KERNEL); if (!card) return ERR_PTR(-ENOMEM); card->host = host; device_initialize(&card->dev); card->dev.parent = mmc_classdev(host); card->dev.bus = &mmc_bus_type; card->dev.release = mmc_release_card; card->dev.type = type; spin_lock_init(&card->bkops_info.bkops_stats.lock); spin_lock_init(&card->wr_pack_stats.lock); return card; } int mmc_add_card(struct mmc_card *card) { int ret; const char *type; const char *uhs_bus_speed_mode = ""; static const char *const uhs_speeds[] = { [UHS_SDR12_BUS_SPEED] = "SDR12 ", [UHS_SDR25_BUS_SPEED] = "SDR25 ", [UHS_SDR50_BUS_SPEED] = "SDR50 ", [UHS_SDR104_BUS_SPEED] = "SDR104 ", [UHS_DDR50_BUS_SPEED] = "DDR50 ", }; dev_set_name(&card->dev, "%s:%04x", mmc_hostname(card->host), card->rca); switch (card->type) { case MMC_TYPE_MMC: type = "MMC"; if (stats_workqueue && !card->host->perf_enable) { card->host->perf_enable = true; queue_delayed_work(stats_workqueue, &card->host->stats_work, msecs_to_jiffies(MMC_STATS_INTERVAL)); } break; case MMC_TYPE_SD: type = "SD"; if (mmc_card_blockaddr(card)) { if (mmc_card_ext_capacity(card)) type = "SDXC"; else type = "SDHC"; } if (stats_workqueue && !card->host->perf_enable) { card->host->perf_enable = true; queue_delayed_work(stats_workqueue, &card->host->stats_work, msecs_to_jiffies(MMC_STATS_INTERVAL)); } break; case MMC_TYPE_SDIO: type = "SDIO"; break; case MMC_TYPE_SD_COMBO: type = "SD-combo"; if (mmc_card_blockaddr(card)) type = "SDHC-combo"; break; default: type = "?"; break; } if (mmc_sd_card_uhs(card) && (card->sd_bus_speed < ARRAY_SIZE(uhs_speeds))) uhs_bus_speed_mode = uhs_speeds[card->sd_bus_speed]; if (mmc_host_is_spi(card->host)) { pr_info("%s: new %s%s%s card on SPI\n", mmc_hostname(card->host), mmc_card_highspeed(card) ? "high speed " : "", mmc_card_ddr_mode(card) ? "DDR " : "", type); } else { pr_info("%s: new %s%s%s%s%s%s card at address %04x\n", mmc_hostname(card->host), mmc_card_uhs(card) ? "ultra high speed " : (mmc_card_highspeed(card) ? "high speed " : ""), (mmc_card_hs400(card) ? "HS400 " : ""), (mmc_card_hs200(card) ? "HS200 " : ""), mmc_card_ddr_mode(card) ? "DDR " : "", uhs_bus_speed_mode, type, card->rca); } #ifdef CONFIG_DEBUG_FS mmc_add_card_debugfs(card); #endif mmc_init_context_info(card->host); ret = pm_runtime_set_active(&card->dev); if (ret) pr_err("%s: %s: failed setting runtime active: ret: %d\n", mmc_hostname(card->host), __func__, ret); else if (!mmc_card_sdio(card) && mmc_use_core_runtime_pm(card->host)) pm_runtime_enable(&card->dev); if (mmc_card_sdio(card)) { ret = device_init_wakeup(&card->dev, true); if (ret) pr_err("%s: %s: failed to init wakeup: %d\n", mmc_hostname(card->host), __func__, ret); } ret = device_add(&card->dev); if (ret) return ret; device_enable_async_suspend(&card->dev); if (mmc_use_core_runtime_pm(card->host) && !mmc_card_sdio(card)) { card->rpm_attrib.show = show_rpm_delay; card->rpm_attrib.store = store_rpm_delay; sysfs_attr_init(&card->rpm_attrib.attr); card->rpm_attrib.attr.name = "runtime_pm_timeout"; card->rpm_attrib.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(&card->dev, &card->rpm_attrib); if (ret) pr_err("%s: %s: creating runtime pm sysfs entry: failed: %d\n", mmc_hostname(card->host), __func__, ret); card->idle_timeout = RUNTIME_SUSPEND_DELAY_MS; } mmc_card_set_present(card); return 0; } void mmc_remove_card(struct mmc_card *card) { #ifdef CONFIG_DEBUG_FS mmc_remove_card_debugfs(card); #endif if (mmc_card_present(card)) { if (mmc_host_is_spi(card->host)) { pr_info("%s: SPI card removed\n", mmc_hostname(card->host)); } else { pr_info("%s: card %04x removed\n", mmc_hostname(card->host), card->rca); } device_del(&card->dev); pr_info("%s: %s done\n", mmc_hostname(card->host), __func__); } kfree(card->wr_pack_stats.packing_events); kfree(card->cached_ext_csd); put_device(&card->dev); }
Bigcountry907/kernel_htc_a32eul
drivers/mmc/core/bus.c
C
gpl-2.0
10,495
/******************************************************************************* *\ Copyright (C) 2007-2018 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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. File Name: mfxstructures.h *******************************************************************************/ #ifndef __MFXSTRUCTURES_H__ #define __MFXSTRUCTURES_H__ #include "mfxcommon.h" #if !defined (__GNUC__) #pragma warning(disable: 4201) #endif #ifdef __cplusplus extern "C" { #endif /* Frame ID for SVC and MVC */ typedef struct { mfxU16 TemporalId; mfxU16 PriorityId; union { struct { mfxU16 DependencyId; mfxU16 QualityId; }; struct { mfxU16 ViewId; }; }; } mfxFrameId; #pragma pack(push, 4) /* Frame Info */ typedef struct { mfxU32 reserved[4]; mfxU16 reserved4; mfxU16 BitDepthLuma; mfxU16 BitDepthChroma; mfxU16 Shift; mfxFrameId FrameId; mfxU32 FourCC; union { struct { /* Frame parameters */ mfxU16 Width; mfxU16 Height; mfxU16 CropX; mfxU16 CropY; mfxU16 CropW; mfxU16 CropH; }; struct { /* Buffer parameters (for plain formats like P8) */ mfxU64 BufferSize; mfxU32 reserved5; }; }; mfxU32 FrameRateExtN; mfxU32 FrameRateExtD; mfxU16 reserved3; mfxU16 AspectRatioW; mfxU16 AspectRatioH; mfxU16 PicStruct; mfxU16 ChromaFormat; mfxU16 reserved2; } mfxFrameInfo; #pragma pack(pop) /* FourCC */ enum { MFX_FOURCC_NV12 = MFX_MAKEFOURCC('N','V','1','2'), /* Native Format */ MFX_FOURCC_YV12 = MFX_MAKEFOURCC('Y','V','1','2'), MFX_FOURCC_NV16 = MFX_MAKEFOURCC('N','V','1','6'), MFX_FOURCC_YUY2 = MFX_MAKEFOURCC('Y','U','Y','2'), MFX_FOURCC_RGB3 = MFX_MAKEFOURCC('R','G','B','3'), /* deprecated */ MFX_FOURCC_RGB4 = MFX_MAKEFOURCC('R','G','B','4'), /* ARGB in that order, A channel is 8 MSBs */ MFX_FOURCC_P8 = 41, /* D3DFMT_P8 */ MFX_FOURCC_P8_TEXTURE = MFX_MAKEFOURCC('P','8','M','B'), MFX_FOURCC_P010 = MFX_MAKEFOURCC('P','0','1','0'), MFX_FOURCC_P210 = MFX_MAKEFOURCC('P','2','1','0'), MFX_FOURCC_BGR4 = MFX_MAKEFOURCC('B','G','R','4'), /* ABGR in that order, A channel is 8 MSBs */ MFX_FOURCC_A2RGB10 = MFX_MAKEFOURCC('R','G','1','0'), /* ARGB in that order, A channel is two MSBs */ MFX_FOURCC_ARGB16 = MFX_MAKEFOURCC('R','G','1','6'), /* ARGB in that order, 64 bits, A channel is 16 MSBs */ MFX_FOURCC_ABGR16 = MFX_MAKEFOURCC('B','G','1','6'), /* ABGR in that order, 64 bits, A channel is 16 MSBs */ MFX_FOURCC_R16 = MFX_MAKEFOURCC('R','1','6','U'), MFX_FOURCC_AYUV = MFX_MAKEFOURCC('A','Y','U','V'), /* YUV 4:4:4, AYUV in that order, A channel is 8 MSBs */ MFX_FOURCC_AYUV_RGB4 = MFX_MAKEFOURCC('A','V','U','Y'), /* ARGB in that order, A channel is 8 MSBs stored in AYUV surface*/ MFX_FOURCC_UYVY = MFX_MAKEFOURCC('U','Y','V','Y'), MFX_FOURCC_Y210 = MFX_MAKEFOURCC('Y','2','1','0'), MFX_FOURCC_Y410 = MFX_MAKEFOURCC('Y','4','1','0'), }; /* PicStruct */ enum { MFX_PICSTRUCT_UNKNOWN =0x00, MFX_PICSTRUCT_PROGRESSIVE =0x01, MFX_PICSTRUCT_FIELD_TFF =0x02, MFX_PICSTRUCT_FIELD_BFF =0x04, MFX_PICSTRUCT_FIELD_REPEATED=0x10, /* first field repeated, pic_struct=5 or 6 in H.264 */ MFX_PICSTRUCT_FRAME_DOUBLING=0x20, /* pic_struct=7 in H.264 */ MFX_PICSTRUCT_FRAME_TRIPLING=0x40, /* pic_struct=8 in H.264 */ MFX_PICSTRUCT_FIELD_SINGLE =0x100, MFX_PICSTRUCT_FIELD_TOP =MFX_PICSTRUCT_FIELD_SINGLE | MFX_PICSTRUCT_FIELD_TFF, MFX_PICSTRUCT_FIELD_BOTTOM =MFX_PICSTRUCT_FIELD_SINGLE | MFX_PICSTRUCT_FIELD_BFF, MFX_PICSTRUCT_FIELD_PAIRED_PREV =0x200, MFX_PICSTRUCT_FIELD_PAIRED_NEXT =0x400, }; /* ColorFormat */ enum { MFX_CHROMAFORMAT_MONOCHROME =0, MFX_CHROMAFORMAT_YUV420 =1, MFX_CHROMAFORMAT_YUV422 =2, MFX_CHROMAFORMAT_YUV444 =3, MFX_CHROMAFORMAT_YUV400 = MFX_CHROMAFORMAT_MONOCHROME, MFX_CHROMAFORMAT_YUV411 = 4, MFX_CHROMAFORMAT_YUV422H = MFX_CHROMAFORMAT_YUV422, MFX_CHROMAFORMAT_YUV422V = 5, MFX_CHROMAFORMAT_RESERVED1 = 6 }; enum { MFX_TIMESTAMP_UNKNOWN = -1 }; enum { MFX_FRAMEORDER_UNKNOWN = -1 }; /* DataFlag in mfxFrameData */ enum { MFX_FRAMEDATA_ORIGINAL_TIMESTAMP = 0x0001 }; /* Corrupted in mfxFrameData */ enum { MFX_CORRUPTION_MINOR = 0x0001, MFX_CORRUPTION_MAJOR = 0x0002, MFX_CORRUPTION_ABSENT_TOP_FIELD = 0x0004, MFX_CORRUPTION_ABSENT_BOTTOM_FIELD = 0x0008, MFX_CORRUPTION_REFERENCE_FRAME = 0x0010, MFX_CORRUPTION_REFERENCE_LIST = 0x0020 }; #pragma pack(push, 4) typedef struct { mfxU32 U : 10; mfxU32 Y : 10; mfxU32 V : 10; mfxU32 A : 2; } mfxY410; #pragma pack(pop) #pragma pack(push, 4) typedef struct { mfxU32 B : 10; mfxU32 G : 10; mfxU32 R : 10; mfxU32 A : 2; } mfxA2RGB10; #pragma pack(pop) /* Frame Data Info */ typedef struct { union { mfxExtBuffer **ExtParam; mfxU64 reserved2; }; mfxU16 NumExtParam; mfxU16 reserved[9]; mfxU16 MemType; mfxU16 PitchHigh; mfxU64 TimeStamp; mfxU32 FrameOrder; mfxU16 Locked; union{ mfxU16 Pitch; mfxU16 PitchLow; }; /* color planes */ union { mfxU8 *Y; mfxU16 *Y16; mfxU8 *R; }; union { mfxU8 *UV; /* for UV merged formats */ mfxU8 *VU; /* for VU merged formats */ mfxU8 *CbCr; /* for CbCr merged formats */ mfxU8 *CrCb; /* for CrCb merged formats */ mfxU8 *Cb; mfxU8 *U; mfxU16 *U16; mfxU8 *G; mfxY410 *Y410; /* for Y410 format (merged AVYU) */ }; union { mfxU8 *Cr; mfxU8 *V; mfxU16 *V16; mfxU8 *B; mfxA2RGB10 *A2RGB10; /* for A2RGB10 format (merged ARGB) */ }; mfxU8 *A; mfxMemId MemId; /* Additional Flags */ mfxU16 Corrupted; mfxU16 DataFlag; } mfxFrameData; /* Frame Surface */ typedef struct { mfxU32 reserved[4]; mfxFrameInfo Info; mfxFrameData Data; } mfxFrameSurface1; enum { MFX_TIMESTAMPCALC_UNKNOWN = 0, MFX_TIMESTAMPCALC_TELECINE = 1, }; /* Transcoding Info */ typedef struct { mfxU32 reserved[7]; mfxU16 LowPower; mfxU16 BRCParamMultiplier; mfxFrameInfo FrameInfo; mfxU32 CodecId; mfxU16 CodecProfile; mfxU16 CodecLevel; mfxU16 NumThread; union { struct { /* Encoding Options */ mfxU16 TargetUsage; mfxU16 GopPicSize; mfxU16 GopRefDist; mfxU16 GopOptFlag; mfxU16 IdrInterval; mfxU16 RateControlMethod; union { mfxU16 InitialDelayInKB; mfxU16 QPI; mfxU16 Accuracy; }; mfxU16 BufferSizeInKB; union { mfxU16 TargetKbps; mfxU16 QPP; mfxU16 ICQQuality; }; union { mfxU16 MaxKbps; mfxU16 QPB; mfxU16 Convergence; }; mfxU16 NumSlice; mfxU16 NumRefFrame; mfxU16 EncodedOrder; }; struct { /* Decoding Options */ mfxU16 DecodedOrder; mfxU16 ExtendedPicStruct; mfxU16 TimeStampCalc; mfxU16 SliceGroupsPresent; mfxU16 MaxDecFrameBuffering; mfxU16 EnableReallocRequest; mfxU16 reserved2[7]; }; struct { /* JPEG Decoding Options */ mfxU16 JPEGChromaFormat; mfxU16 Rotation; mfxU16 JPEGColorFormat; mfxU16 InterleavedDec; mfxU8 SamplingFactorH[4]; mfxU8 SamplingFactorV[4]; mfxU16 reserved3[5]; }; struct { /* JPEG Encoding Options */ mfxU16 Interleaved; mfxU16 Quality; mfxU16 RestartInterval; mfxU16 reserved5[10]; }; }; } mfxInfoMFX; typedef struct { mfxU32 reserved[8]; mfxFrameInfo In; mfxFrameInfo Out; } mfxInfoVPP; typedef struct { mfxU32 AllocId; mfxU32 reserved[2]; mfxU16 reserved3; mfxU16 AsyncDepth; union { mfxInfoMFX mfx; mfxInfoVPP vpp; }; mfxU16 Protected; mfxU16 IOPattern; mfxExtBuffer** ExtParam; mfxU16 NumExtParam; mfxU16 reserved2; } mfxVideoParam; /* IOPattern */ enum { MFX_IOPATTERN_IN_VIDEO_MEMORY = 0x01, MFX_IOPATTERN_IN_SYSTEM_MEMORY = 0x02, MFX_IOPATTERN_IN_OPAQUE_MEMORY = 0x04, MFX_IOPATTERN_OUT_VIDEO_MEMORY = 0x10, MFX_IOPATTERN_OUT_SYSTEM_MEMORY = 0x20, MFX_IOPATTERN_OUT_OPAQUE_MEMORY = 0x40 }; /* CodecId */ enum { MFX_CODEC_AVC =MFX_MAKEFOURCC('A','V','C',' '), MFX_CODEC_HEVC =MFX_MAKEFOURCC('H','E','V','C'), MFX_CODEC_MPEG2 =MFX_MAKEFOURCC('M','P','G','2'), MFX_CODEC_VC1 =MFX_MAKEFOURCC('V','C','1',' '), MFX_CODEC_CAPTURE =MFX_MAKEFOURCC('C','A','P','T'), MFX_CODEC_VP9 =MFX_MAKEFOURCC('V','P','9',' '), MFX_CODEC_AV1 =MFX_MAKEFOURCC('A','V','1',' ') }; /* CodecProfile, CodecLevel */ enum { MFX_PROFILE_UNKNOWN =0, MFX_LEVEL_UNKNOWN =0, /* AVC Profiles & Levels */ MFX_PROFILE_AVC_CONSTRAINT_SET0 = (0x100 << 0), MFX_PROFILE_AVC_CONSTRAINT_SET1 = (0x100 << 1), MFX_PROFILE_AVC_CONSTRAINT_SET2 = (0x100 << 2), MFX_PROFILE_AVC_CONSTRAINT_SET3 = (0x100 << 3), MFX_PROFILE_AVC_CONSTRAINT_SET4 = (0x100 << 4), MFX_PROFILE_AVC_CONSTRAINT_SET5 = (0x100 << 5), MFX_PROFILE_AVC_BASELINE =66, MFX_PROFILE_AVC_MAIN =77, MFX_PROFILE_AVC_EXTENDED =88, MFX_PROFILE_AVC_HIGH =100, MFX_PROFILE_AVC_HIGH_422 =122, MFX_PROFILE_AVC_CONSTRAINED_BASELINE =MFX_PROFILE_AVC_BASELINE + MFX_PROFILE_AVC_CONSTRAINT_SET1, MFX_PROFILE_AVC_CONSTRAINED_HIGH =MFX_PROFILE_AVC_HIGH + MFX_PROFILE_AVC_CONSTRAINT_SET4 + MFX_PROFILE_AVC_CONSTRAINT_SET5, MFX_PROFILE_AVC_PROGRESSIVE_HIGH =MFX_PROFILE_AVC_HIGH + MFX_PROFILE_AVC_CONSTRAINT_SET4, MFX_LEVEL_AVC_1 =10, MFX_LEVEL_AVC_1b =9, MFX_LEVEL_AVC_11 =11, MFX_LEVEL_AVC_12 =12, MFX_LEVEL_AVC_13 =13, MFX_LEVEL_AVC_2 =20, MFX_LEVEL_AVC_21 =21, MFX_LEVEL_AVC_22 =22, MFX_LEVEL_AVC_3 =30, MFX_LEVEL_AVC_31 =31, MFX_LEVEL_AVC_32 =32, MFX_LEVEL_AVC_4 =40, MFX_LEVEL_AVC_41 =41, MFX_LEVEL_AVC_42 =42, MFX_LEVEL_AVC_5 =50, MFX_LEVEL_AVC_51 =51, MFX_LEVEL_AVC_52 =52, /* MPEG-2 Profiles & Levels */ MFX_PROFILE_MPEG2_SIMPLE =0x50, MFX_PROFILE_MPEG2_MAIN =0x40, MFX_PROFILE_MPEG2_HIGH =0x10, MFX_LEVEL_MPEG2_LOW =0xA, MFX_LEVEL_MPEG2_MAIN =0x8, MFX_LEVEL_MPEG2_HIGH =0x4, MFX_LEVEL_MPEG2_HIGH1440 =0x6, /* VC1 Profiles & Levels */ MFX_PROFILE_VC1_SIMPLE =(0+1), MFX_PROFILE_VC1_MAIN =(4+1), MFX_PROFILE_VC1_ADVANCED =(12+1), /* VC1 levels for simple & main profiles */ MFX_LEVEL_VC1_LOW =(0+1), MFX_LEVEL_VC1_MEDIAN =(2+1), MFX_LEVEL_VC1_HIGH =(4+1), /* VC1 levels for the advanced profile */ MFX_LEVEL_VC1_0 =(0x00+1), MFX_LEVEL_VC1_1 =(0x01+1), MFX_LEVEL_VC1_2 =(0x02+1), MFX_LEVEL_VC1_3 =(0x03+1), MFX_LEVEL_VC1_4 =(0x04+1), /* HEVC Profiles & Levels & Tiers */ MFX_PROFILE_HEVC_MAIN =1, MFX_PROFILE_HEVC_MAIN10 =2, MFX_PROFILE_HEVC_MAINSP =3, MFX_PROFILE_HEVC_REXT =4, MFX_LEVEL_HEVC_1 = 10, MFX_LEVEL_HEVC_2 = 20, MFX_LEVEL_HEVC_21 = 21, MFX_LEVEL_HEVC_3 = 30, MFX_LEVEL_HEVC_31 = 31, MFX_LEVEL_HEVC_4 = 40, MFX_LEVEL_HEVC_41 = 41, MFX_LEVEL_HEVC_5 = 50, MFX_LEVEL_HEVC_51 = 51, MFX_LEVEL_HEVC_52 = 52, MFX_LEVEL_HEVC_6 = 60, MFX_LEVEL_HEVC_61 = 61, MFX_LEVEL_HEVC_62 = 62, MFX_TIER_HEVC_MAIN = 0, MFX_TIER_HEVC_HIGH = 0x100, /* VP9 Profiles */ MFX_PROFILE_VP9_0 = 1, MFX_PROFILE_VP9_1 = 2, MFX_PROFILE_VP9_2 = 3, MFX_PROFILE_VP9_3 = 4, }; /* GopOptFlag */ enum { MFX_GOP_CLOSED =1, MFX_GOP_STRICT =2 }; /* TargetUsages: from 1 to 7 inclusive */ enum { MFX_TARGETUSAGE_1 =1, MFX_TARGETUSAGE_2 =2, MFX_TARGETUSAGE_3 =3, MFX_TARGETUSAGE_4 =4, MFX_TARGETUSAGE_5 =5, MFX_TARGETUSAGE_6 =6, MFX_TARGETUSAGE_7 =7, MFX_TARGETUSAGE_UNKNOWN =0, MFX_TARGETUSAGE_BEST_QUALITY =MFX_TARGETUSAGE_1, MFX_TARGETUSAGE_BALANCED =MFX_TARGETUSAGE_4, MFX_TARGETUSAGE_BEST_SPEED =MFX_TARGETUSAGE_7 }; /* RateControlMethod */ enum { MFX_RATECONTROL_CBR =1, MFX_RATECONTROL_VBR =2, MFX_RATECONTROL_CQP =3, MFX_RATECONTROL_AVBR =4, MFX_RATECONTROL_RESERVED1 =5, MFX_RATECONTROL_RESERVED2 =6, MFX_RATECONTROL_RESERVED3 =100, MFX_RATECONTROL_RESERVED4 =7, MFX_RATECONTROL_LA =8, MFX_RATECONTROL_ICQ =9, MFX_RATECONTROL_VCM =10, MFX_RATECONTROL_LA_ICQ =11, MFX_RATECONTROL_LA_EXT =12, MFX_RATECONTROL_LA_HRD =13, MFX_RATECONTROL_QVBR =14, }; /* Trellis control*/ enum { MFX_TRELLIS_UNKNOWN =0, MFX_TRELLIS_OFF =0x01, MFX_TRELLIS_I =0x02, MFX_TRELLIS_P =0x04, MFX_TRELLIS_B =0x08 }; typedef struct { mfxExtBuffer Header; mfxU16 reserved1; mfxU16 RateDistortionOpt; /* tri-state option */ mfxU16 MECostType; mfxU16 MESearchType; mfxI16Pair MVSearchWindow; mfxU16 EndOfSequence; /* tri-state option */ mfxU16 FramePicture; /* tri-state option */ mfxU16 CAVLC; /* tri-state option */ mfxU16 reserved2[2]; mfxU16 RecoveryPointSEI; /* tri-state option */ mfxU16 ViewOutput; /* tri-state option */ mfxU16 NalHrdConformance; /* tri-state option */ mfxU16 SingleSeiNalUnit; /* tri-state option */ mfxU16 VuiVclHrdParameters; /* tri-state option */ mfxU16 RefPicListReordering; /* tri-state option */ mfxU16 ResetRefList; /* tri-state option */ mfxU16 RefPicMarkRep; /* tri-state option */ mfxU16 FieldOutput; /* tri-state option */ mfxU16 IntraPredBlockSize; mfxU16 InterPredBlockSize; mfxU16 MVPrecision; mfxU16 MaxDecFrameBuffering; mfxU16 AUDelimiter; /* tri-state option */ mfxU16 EndOfStream; /* tri-state option */ mfxU16 PicTimingSEI; /* tri-state option */ mfxU16 VuiNalHrdParameters; /* tri-state option */ } mfxExtCodingOption; enum { MFX_B_REF_UNKNOWN = 0, MFX_B_REF_OFF = 1, MFX_B_REF_PYRAMID = 2 }; enum { MFX_LOOKAHEAD_DS_UNKNOWN = 0, MFX_LOOKAHEAD_DS_OFF = 1, MFX_LOOKAHEAD_DS_2x = 2, MFX_LOOKAHEAD_DS_4x = 3 }; enum { MFX_BPSEI_DEFAULT = 0x00, MFX_BPSEI_IFRAME = 0x01 }; enum { MFX_SKIPFRAME_NO_SKIP = 0, MFX_SKIPFRAME_INSERT_DUMMY = 1, MFX_SKIPFRAME_INSERT_NOTHING = 2, MFX_SKIPFRAME_BRC_ONLY = 3, }; /* Intra refresh types */ enum { MFX_REFRESH_NO = 0, MFX_REFRESH_VERTICAL = 1, MFX_REFRESH_HORIZONTAL = 2, MFX_REFRESH_SLICE = 3 }; typedef struct { mfxExtBuffer Header; mfxU16 IntRefType; mfxU16 IntRefCycleSize; mfxI16 IntRefQPDelta; mfxU32 MaxFrameSize; mfxU32 MaxSliceSize; mfxU16 BitrateLimit; /* tri-state option */ mfxU16 MBBRC; /* tri-state option */ mfxU16 ExtBRC; /* tri-state option */ mfxU16 LookAheadDepth; mfxU16 Trellis; mfxU16 RepeatPPS; /* tri-state option */ mfxU16 BRefType; mfxU16 AdaptiveI; /* tri-state option */ mfxU16 AdaptiveB; /* tri-state option */ mfxU16 LookAheadDS; mfxU16 NumMbPerSlice; mfxU16 SkipFrame; mfxU8 MinQPI; /* 1..51, 0 = default */ mfxU8 MaxQPI; /* 1..51, 0 = default */ mfxU8 MinQPP; /* 1..51, 0 = default */ mfxU8 MaxQPP; /* 1..51, 0 = default */ mfxU8 MinQPB; /* 1..51, 0 = default */ mfxU8 MaxQPB; /* 1..51, 0 = default */ mfxU16 FixedFrameRate; /* tri-state option */ mfxU16 DisableDeblockingIdc; mfxU16 DisableVUI; mfxU16 BufferingPeriodSEI; mfxU16 EnableMAD; /* tri-state option */ mfxU16 UseRawRef; /* tri-state option */ } mfxExtCodingOption2; /* WeightedPred */ enum { MFX_WEIGHTED_PRED_UNKNOWN = 0, MFX_WEIGHTED_PRED_DEFAULT = 1, MFX_WEIGHTED_PRED_EXPLICIT = 2, MFX_WEIGHTED_PRED_IMPLICIT = 3 }; /* ScenarioInfo */ enum { MFX_SCENARIO_UNKNOWN = 0, MFX_SCENARIO_DISPLAY_REMOTING = 1, MFX_SCENARIO_VIDEO_CONFERENCE = 2, MFX_SCENARIO_ARCHIVE = 3, MFX_SCENARIO_LIVE_STREAMING = 4, MFX_SCENARIO_CAMERA_CAPTURE = 5 }; /* ContentInfo */ enum { MFX_CONTENT_UNKNOWN = 0, MFX_CONTENT_FULL_SCREEN_VIDEO = 1, MFX_CONTENT_NON_VIDEO_SCREEN = 2 }; /* PRefType */ enum { MFX_P_REF_DEFAULT = 0, MFX_P_REF_SIMPLE = 1, MFX_P_REF_PYRAMID = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 NumSliceI; mfxU16 NumSliceP; mfxU16 NumSliceB; mfxU16 WinBRCMaxAvgKbps; mfxU16 WinBRCSize; mfxU16 QVBRQuality; mfxU16 EnableMBQP; mfxU16 IntRefCycleDist; mfxU16 DirectBiasAdjustment; /* tri-state option */ mfxU16 GlobalMotionBiasAdjustment; /* tri-state option */ mfxU16 MVCostScalingFactor; mfxU16 MBDisableSkipMap; /* tri-state option */ mfxU16 WeightedPred; mfxU16 WeightedBiPred; mfxU16 AspectRatioInfoPresent; /* tri-state option */ mfxU16 OverscanInfoPresent; /* tri-state option */ mfxU16 OverscanAppropriate; /* tri-state option */ mfxU16 TimingInfoPresent; /* tri-state option */ mfxU16 BitstreamRestriction; /* tri-state option */ mfxU16 LowDelayHrd; /* tri-state option */ mfxU16 MotionVectorsOverPicBoundaries; /* tri-state option */ mfxU16 reserved1[2]; mfxU16 ScenarioInfo; mfxU16 ContentInfo; mfxU16 PRefType; mfxU16 FadeDetection; /* tri-state option */ mfxU16 reserved2[2]; mfxU16 GPB; /* tri-state option */ mfxU32 MaxFrameSizeI; mfxU32 MaxFrameSizeP; mfxU32 reserved3[3]; mfxU16 EnableQPOffset; /* tri-state option */ mfxI16 QPOffset[8]; /* FrameQP = QPX + QPOffset[pyramid_layer]; QPX = QPB for B-pyramid, QPP for P-pyramid */ mfxU16 NumRefActiveP[8]; mfxU16 NumRefActiveBL0[8]; mfxU16 NumRefActiveBL1[8]; mfxU16 reserved6; mfxU16 TransformSkip; /* tri-state option; HEVC transform_skip_enabled_flag */ mfxU16 TargetChromaFormatPlus1; /* Minus 1 specifies target encoding chroma format (see ColorFormat enum). May differ from input one. */ mfxU16 TargetBitDepthLuma; /* Target encoding bit depth for luma samples. May differ from input one. */ mfxU16 TargetBitDepthChroma; /* Target encoding bit depth for chroma samples. May differ from input one. */ mfxU16 BRCPanicMode; /* tri-state option */ mfxU16 LowDelayBRC; /* tri-state option */ mfxU16 EnableMBForceIntra; /* tri-state option */ mfxU16 AdaptiveMaxFrameSize; /* tri-state option */ mfxU16 RepartitionCheckEnable; /* tri-state option */ mfxU16 reserved5[3]; mfxU16 EncodedUnitsInfo; /* tri-state option */ mfxU16 EnableNalUnitType; /* tri-state option */ mfxU16 ExtBrcAdaptiveLTR; /* tri-state option for ExtBRC */ mfxU16 reserved[163]; } mfxExtCodingOption3; /* IntraPredBlockSize/InterPredBlockSize */ enum { MFX_BLOCKSIZE_UNKNOWN = 0, MFX_BLOCKSIZE_MIN_16X16 = 1, /* 16x16 */ MFX_BLOCKSIZE_MIN_8X8 = 2, /* 16x16, 8x8 */ MFX_BLOCKSIZE_MIN_4X4 = 3 /* 16x16, 8x8, 4x4 */ }; /* MVPrecision */ enum { MFX_MVPRECISION_UNKNOWN = 0, MFX_MVPRECISION_INTEGER = (1 << 0), MFX_MVPRECISION_HALFPEL = (1 << 1), MFX_MVPRECISION_QUARTERPEL = (1 << 2) }; enum { MFX_CODINGOPTION_UNKNOWN =0, MFX_CODINGOPTION_ON =0x10, MFX_CODINGOPTION_OFF =0x20, MFX_CODINGOPTION_ADAPTIVE =0x30 }; /* Data Flag for mfxBitstream*/ enum { MFX_BITSTREAM_COMPLETE_FRAME = 0x0001, /* the bitstream contains a complete frame or field pair of data */ MFX_BITSTREAM_EOS = 0x0002 }; /* Extended Buffer Ids */ enum { MFX_EXTBUFF_CODING_OPTION = MFX_MAKEFOURCC('C','D','O','P'), MFX_EXTBUFF_CODING_OPTION_SPSPPS = MFX_MAKEFOURCC('C','O','S','P'), MFX_EXTBUFF_VPP_DONOTUSE = MFX_MAKEFOURCC('N','U','S','E'), MFX_EXTBUFF_VPP_AUXDATA = MFX_MAKEFOURCC('A','U','X','D'), MFX_EXTBUFF_VPP_DENOISE = MFX_MAKEFOURCC('D','N','I','S'), MFX_EXTBUFF_VPP_SCENE_ANALYSIS = MFX_MAKEFOURCC('S','C','L','Y'), MFX_EXTBUFF_VPP_SCENE_CHANGE = MFX_EXTBUFF_VPP_SCENE_ANALYSIS, MFX_EXTBUFF_VPP_PROCAMP = MFX_MAKEFOURCC('P','A','M','P'), MFX_EXTBUFF_VPP_DETAIL = MFX_MAKEFOURCC('D','E','T',' '), MFX_EXTBUFF_VIDEO_SIGNAL_INFO = MFX_MAKEFOURCC('V','S','I','N'), MFX_EXTBUFF_VPP_DOUSE = MFX_MAKEFOURCC('D','U','S','E'), MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION = MFX_MAKEFOURCC('O','P','Q','S'), MFX_EXTBUFF_AVC_REFLIST_CTRL = MFX_MAKEFOURCC('R','L','S','T'), MFX_EXTBUFF_VPP_FRAME_RATE_CONVERSION = MFX_MAKEFOURCC('F','R','C',' '), MFX_EXTBUFF_PICTURE_TIMING_SEI = MFX_MAKEFOURCC('P','T','S','E'), MFX_EXTBUFF_AVC_TEMPORAL_LAYERS = MFX_MAKEFOURCC('A','T','M','L'), MFX_EXTBUFF_CODING_OPTION2 = MFX_MAKEFOURCC('C','D','O','2'), MFX_EXTBUFF_VPP_IMAGE_STABILIZATION = MFX_MAKEFOURCC('I','S','T','B'), MFX_EXTBUFF_VPP_PICSTRUCT_DETECTION = MFX_MAKEFOURCC('I','D','E','T'), MFX_EXTBUFF_ENCODER_CAPABILITY = MFX_MAKEFOURCC('E','N','C','P'), MFX_EXTBUFF_ENCODER_RESET_OPTION = MFX_MAKEFOURCC('E','N','R','O'), MFX_EXTBUFF_ENCODED_FRAME_INFO = MFX_MAKEFOURCC('E','N','F','I'), MFX_EXTBUFF_VPP_COMPOSITE = MFX_MAKEFOURCC('V','C','M','P'), MFX_EXTBUFF_VPP_VIDEO_SIGNAL_INFO = MFX_MAKEFOURCC('V','V','S','I'), MFX_EXTBUFF_ENCODER_ROI = MFX_MAKEFOURCC('E','R','O','I'), MFX_EXTBUFF_VPP_DEINTERLACING = MFX_MAKEFOURCC('V','P','D','I'), MFX_EXTBUFF_AVC_REFLISTS = MFX_MAKEFOURCC('R','L','T','S'), MFX_EXTBUFF_DEC_VIDEO_PROCESSING = MFX_MAKEFOURCC('D','E','C','V'), MFX_EXTBUFF_VPP_FIELD_PROCESSING = MFX_MAKEFOURCC('F','P','R','O'), MFX_EXTBUFF_CODING_OPTION3 = MFX_MAKEFOURCC('C','D','O','3'), MFX_EXTBUFF_CHROMA_LOC_INFO = MFX_MAKEFOURCC('C','L','I','N'), MFX_EXTBUFF_MBQP = MFX_MAKEFOURCC('M','B','Q','P'), MFX_EXTBUFF_MB_FORCE_INTRA = MFX_MAKEFOURCC('M','B','F','I'), MFX_EXTBUFF_HEVC_TILES = MFX_MAKEFOURCC('2','6','5','T'), MFX_EXTBUFF_MB_DISABLE_SKIP_MAP = MFX_MAKEFOURCC('M','D','S','M'), MFX_EXTBUFF_HEVC_PARAM = MFX_MAKEFOURCC('2','6','5','P'), MFX_EXTBUFF_DECODED_FRAME_INFO = MFX_MAKEFOURCC('D','E','F','I'), MFX_EXTBUFF_TIME_CODE = MFX_MAKEFOURCC('T','M','C','D'), MFX_EXTBUFF_HEVC_REGION = MFX_MAKEFOURCC('2','6','5','R'), MFX_EXTBUFF_PRED_WEIGHT_TABLE = MFX_MAKEFOURCC('E','P','W','T'), MFX_EXTBUFF_DIRTY_RECTANGLES = MFX_MAKEFOURCC('D','R','O','I'), MFX_EXTBUFF_MOVING_RECTANGLES = MFX_MAKEFOURCC('M','R','O','I'), MFX_EXTBUFF_CODING_OPTION_VPS = MFX_MAKEFOURCC('C','O','V','P'), MFX_EXTBUFF_VPP_ROTATION = MFX_MAKEFOURCC('R','O','T',' '), MFX_EXTBUFF_ENCODED_SLICES_INFO = MFX_MAKEFOURCC('E','N','S','I'), MFX_EXTBUFF_VPP_SCALING = MFX_MAKEFOURCC('V','S','C','L'), MFX_EXTBUFF_HEVC_REFLIST_CTRL = MFX_EXTBUFF_AVC_REFLIST_CTRL, MFX_EXTBUFF_HEVC_REFLISTS = MFX_EXTBUFF_AVC_REFLISTS, MFX_EXTBUFF_HEVC_TEMPORAL_LAYERS = MFX_EXTBUFF_AVC_TEMPORAL_LAYERS, MFX_EXTBUFF_VPP_MIRRORING = MFX_MAKEFOURCC('M','I','R','R'), MFX_EXTBUFF_MV_OVER_PIC_BOUNDARIES = MFX_MAKEFOURCC('M','V','P','B'), MFX_EXTBUFF_VPP_COLORFILL = MFX_MAKEFOURCC('V','C','L','F'), MFX_EXTBUFF_DECODE_ERROR_REPORT = MFX_MAKEFOURCC('D', 'E', 'R', 'R'), MFX_EXTBUFF_VPP_COLOR_CONVERSION = MFX_MAKEFOURCC('V', 'C', 'S', 'C'), MFX_EXTBUFF_CONTENT_LIGHT_LEVEL_INFO = MFX_MAKEFOURCC('L', 'L', 'I', 'S'), MFX_EXTBUFF_MASTERING_DISPLAY_COLOUR_VOLUME = MFX_MAKEFOURCC('D', 'C', 'V', 'S'), MFX_EXTBUFF_MULTI_FRAME_PARAM = MFX_MAKEFOURCC('M', 'F', 'R', 'P'), MFX_EXTBUFF_MULTI_FRAME_CONTROL = MFX_MAKEFOURCC('M', 'F', 'R', 'C'), MFX_EXTBUFF_ENCODED_UNITS_INFO = MFX_MAKEFOURCC('E', 'N', 'U', 'I'), MFX_EXTBUFF_VPP_MCTF = MFX_MAKEFOURCC('M', 'C', 'T', 'F'), MFX_EXTBUFF_VP9_SEGMENTATION = MFX_MAKEFOURCC('9', 'S', 'E', 'G'), MFX_EXTBUFF_VP9_TEMPORAL_LAYERS = MFX_MAKEFOURCC('9', 'T', 'M', 'L'), MFX_EXTBUFF_VP9_PARAM = MFX_MAKEFOURCC('9', 'P', 'A', 'R'), MFX_EXTBUFF_AVC_ROUNDING_OFFSET = MFX_MAKEFOURCC('R','N','D','O'), }; /* VPP Conf: Do not use certain algorithms */ typedef struct { mfxExtBuffer Header; mfxU32 NumAlg; mfxU32* AlgList; } mfxExtVPPDoNotUse; typedef struct { mfxExtBuffer Header; mfxU16 DenoiseFactor; } mfxExtVPPDenoise; typedef struct { mfxExtBuffer Header; mfxU16 DetailFactor; } mfxExtVPPDetail; typedef struct { mfxExtBuffer Header; mfxF64 Brightness; mfxF64 Contrast; mfxF64 Hue; mfxF64 Saturation; } mfxExtVPPProcAmp; /* statistics collected for decode, encode and vpp */ typedef struct { mfxU32 reserved[16]; mfxU32 NumFrame; mfxU64 NumBit; mfxU32 NumCachedFrame; } mfxEncodeStat; typedef struct { mfxU32 reserved[16]; mfxU32 NumFrame; mfxU32 NumSkippedFrame; mfxU32 NumError; mfxU32 NumCachedFrame; } mfxDecodeStat; typedef struct { mfxU32 reserved[16]; mfxU32 NumFrame; mfxU32 NumCachedFrame; } mfxVPPStat; typedef struct { mfxExtBuffer Header; union{ struct{ mfxU32 SpatialComplexity; mfxU32 TemporalComplexity; }; struct{ mfxU16 PicStruct; mfxU16 reserved[3]; }; }; mfxU16 SceneChangeRate; mfxU16 RepeatedFrame; } mfxExtVppAuxData; /* CtrlFlags */ enum { MFX_PAYLOAD_CTRL_SUFFIX = 0x00000001 /* HEVC suffix SEI */ }; typedef struct { mfxU32 CtrlFlags; mfxU32 reserved[3]; mfxU8 *Data; /* buffer pointer */ mfxU32 NumBit; /* number of bits */ mfxU16 Type; /* SEI message type in H.264 or user data start_code in MPEG-2 */ mfxU16 BufSize; /* payload buffer size in bytes */ } mfxPayload; typedef struct { mfxExtBuffer Header; mfxU32 reserved[4]; mfxU16 reserved1; mfxU16 MfxNalUnitType; mfxU16 SkipFrame; mfxU16 QP; /* per frame QP */ mfxU16 FrameType; mfxU16 NumExtParam; mfxU16 NumPayload; /* MPEG-2 user data or H.264 SEI message(s) */ mfxU16 reserved2; mfxExtBuffer **ExtParam; mfxPayload **Payload; /* for field pair, first field uses even payloads and second field uses odd payloads */ } mfxEncodeCtrl; /* Buffer Memory Types */ enum { /* Buffer types */ MFX_MEMTYPE_PERSISTENT_MEMORY =0x0002 }; /* Frame Memory Types */ #define MFX_MEMTYPE_BASE(x) (0x90ff & (x)) enum { MFX_MEMTYPE_DXVA2_DECODER_TARGET =0x0010, MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET =0x0020, MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET = MFX_MEMTYPE_DXVA2_DECODER_TARGET, MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET = MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET, MFX_MEMTYPE_SYSTEM_MEMORY =0x0040, MFX_MEMTYPE_RESERVED1 =0x0080, MFX_MEMTYPE_FROM_ENCODE = 0x0100, MFX_MEMTYPE_FROM_DECODE = 0x0200, MFX_MEMTYPE_FROM_VPPIN = 0x0400, MFX_MEMTYPE_FROM_VPPOUT = 0x0800, MFX_MEMTYPE_FROM_ENC = 0x2000, MFX_MEMTYPE_FROM_PAK = 0x4000, //reserved MFX_MEMTYPE_INTERNAL_FRAME = 0x0001, MFX_MEMTYPE_EXTERNAL_FRAME = 0x0002, MFX_MEMTYPE_OPAQUE_FRAME = 0x0004, MFX_MEMTYPE_EXPORT_FRAME = 0x0008, MFX_MEMTYPE_SHARED_RESOURCE = MFX_MEMTYPE_EXPORT_FRAME, MFX_MEMTYPE_VIDEO_MEMORY_ENCODER_TARGET = 0x1000 }; typedef struct { union { mfxU32 AllocId; mfxU32 reserved[1]; }; mfxU32 reserved3[3]; mfxFrameInfo Info; mfxU16 Type; /* decoder or processor render targets */ mfxU16 NumFrameMin; mfxU16 NumFrameSuggested; mfxU16 reserved2; } mfxFrameAllocRequest; typedef struct { mfxU32 AllocId; mfxU32 reserved[3]; mfxMemId *mids; /* the array allocated by application */ mfxU16 NumFrameActual; mfxU16 reserved2; } mfxFrameAllocResponse; /* FrameType */ enum { MFX_FRAMETYPE_UNKNOWN =0x0000, MFX_FRAMETYPE_I =0x0001, MFX_FRAMETYPE_P =0x0002, MFX_FRAMETYPE_B =0x0004, MFX_FRAMETYPE_S =0x0008, MFX_FRAMETYPE_REF =0x0040, MFX_FRAMETYPE_IDR =0x0080, MFX_FRAMETYPE_xI =0x0100, MFX_FRAMETYPE_xP =0x0200, MFX_FRAMETYPE_xB =0x0400, MFX_FRAMETYPE_xS =0x0800, MFX_FRAMETYPE_xREF =0x4000, MFX_FRAMETYPE_xIDR =0x8000 }; enum { MFX_HEVC_NALU_TYPE_UNKNOWN = 0, MFX_HEVC_NALU_TYPE_TRAIL_N = ( 0+1), MFX_HEVC_NALU_TYPE_TRAIL_R = ( 1+1), MFX_HEVC_NALU_TYPE_RADL_N = ( 6+1), MFX_HEVC_NALU_TYPE_RADL_R = ( 7+1), MFX_HEVC_NALU_TYPE_RASL_N = ( 8+1), MFX_HEVC_NALU_TYPE_RASL_R = ( 9+1), MFX_HEVC_NALU_TYPE_IDR_W_RADL = (19+1), MFX_HEVC_NALU_TYPE_IDR_N_LP = (20+1), MFX_HEVC_NALU_TYPE_CRA_NUT = (21+1) }; typedef enum { MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9 =1, /* IDirect3DDeviceManager9 */ MFX_HANDLE_D3D9_DEVICE_MANAGER = MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9, MFX_HANDLE_RESERVED1 = 2, MFX_HANDLE_D3D11_DEVICE = 3, MFX_HANDLE_VA_DISPLAY = 4, MFX_HANDLE_RESERVED3 = 5, } mfxHandleType; typedef enum { MFX_SKIPMODE_NOSKIP=0, MFX_SKIPMODE_MORE=1, MFX_SKIPMODE_LESS=2 } mfxSkipMode; typedef struct { mfxExtBuffer Header; mfxU8 *SPSBuffer; mfxU8 *PPSBuffer; mfxU16 SPSBufSize; mfxU16 PPSBufSize; mfxU16 SPSId; mfxU16 PPSId; } mfxExtCodingOptionSPSPPS; typedef struct { mfxExtBuffer Header; union { mfxU8 *VPSBuffer; mfxU64 reserved1; }; mfxU16 VPSBufSize; mfxU16 VPSId; mfxU16 reserved[6]; } mfxExtCodingOptionVPS; typedef struct { mfxExtBuffer Header; mfxU16 VideoFormat; mfxU16 VideoFullRange; mfxU16 ColourDescriptionPresent; mfxU16 ColourPrimaries; mfxU16 TransferCharacteristics; mfxU16 MatrixCoefficients; } mfxExtVideoSignalInfo; typedef struct { mfxExtBuffer Header; mfxU32 NumAlg; mfxU32 *AlgList; } mfxExtVPPDoUse; typedef struct { mfxExtBuffer Header; mfxU32 reserved1[2]; struct { mfxFrameSurface1 **Surfaces; mfxU32 reserved2[5]; mfxU16 Type; mfxU16 NumSurface; } In, Out; } mfxExtOpaqueSurfaceAlloc; typedef struct { mfxExtBuffer Header; mfxU16 NumRefIdxL0Active; mfxU16 NumRefIdxL1Active; struct { mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 ViewId; mfxU16 LongTermIdx; mfxU16 reserved[3]; } PreferredRefList[32], RejectedRefList[16], LongTermRefList[16]; mfxU16 ApplyLongTermIdx; mfxU16 reserved[15]; } mfxExtAVCRefListCtrl; enum { MFX_FRCALGM_PRESERVE_TIMESTAMP = 0x0001, MFX_FRCALGM_DISTRIBUTED_TIMESTAMP = 0x0002, MFX_FRCALGM_FRAME_INTERPOLATION = 0x0004 }; typedef struct { mfxExtBuffer Header; mfxU16 Algorithm; mfxU16 reserved; mfxU32 reserved2[15]; } mfxExtVPPFrameRateConversion; enum { MFX_IMAGESTAB_MODE_UPSCALE = 0x0001, MFX_IMAGESTAB_MODE_BOXING = 0x0002 }; typedef struct { mfxExtBuffer Header; mfxU16 Mode; mfxU16 reserved[11]; } mfxExtVPPImageStab; enum { MFX_PAYLOAD_OFF = 0, MFX_PAYLOAD_IDR = 1 }; typedef struct { mfxExtBuffer Header; mfxU16 reserved[15]; mfxU16 InsertPayloadToggle; mfxU16 DisplayPrimariesX[3]; mfxU16 DisplayPrimariesY[3]; mfxU16 WhitePointX; mfxU16 WhitePointY; mfxU32 MaxDisplayMasteringLuminance; mfxU32 MinDisplayMasteringLuminance; } mfxExtMasteringDisplayColourVolume; typedef struct { mfxExtBuffer Header; mfxU16 reserved[9]; mfxU16 InsertPayloadToggle; mfxU16 MaxContentLightLevel; mfxU16 MaxPicAverageLightLevel; } mfxExtContentLightLevelInfo; typedef struct { mfxExtBuffer Header; mfxU32 reserved[14]; struct { mfxU16 ClockTimestampFlag; mfxU16 CtType; mfxU16 NuitFieldBasedFlag; mfxU16 CountingType; mfxU16 FullTimestampFlag; mfxU16 DiscontinuityFlag; mfxU16 CntDroppedFlag; mfxU16 NFrames; mfxU16 SecondsFlag; mfxU16 MinutesFlag; mfxU16 HoursFlag; mfxU16 SecondsValue; mfxU16 MinutesValue; mfxU16 HoursValue; mfxU32 TimeOffset; } TimeStamp[3]; } mfxExtPictureTimingSEI; typedef struct { mfxExtBuffer Header; mfxU32 reserved1[4]; mfxU16 reserved2; mfxU16 BaseLayerPID; struct { mfxU16 Scale; mfxU16 reserved[3]; }Layer[8]; } mfxExtAvcTemporalLayers; typedef struct { mfxExtBuffer Header; mfxU32 MBPerSec; mfxU16 reserved[58]; } mfxExtEncoderCapability; typedef struct { mfxExtBuffer Header; mfxU16 StartNewSequence; mfxU16 reserved[11]; } mfxExtEncoderResetOption; /*LongTermIdx*/ enum { MFX_LONGTERM_IDX_NO_IDX = 0xFFFF }; typedef struct { mfxExtBuffer Header; mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 LongTermIdx; mfxU32 MAD; mfxU16 BRCPanicMode; mfxU16 QP; mfxU32 SecondFieldOffset; mfxU16 reserved[2]; struct { mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 LongTermIdx; mfxU16 reserved[4]; } UsedRefListL0[32], UsedRefListL1[32]; } mfxExtAVCEncodedFrameInfo; typedef struct mfxVPPCompInputStream { mfxU32 DstX; mfxU32 DstY; mfxU32 DstW; mfxU32 DstH; mfxU16 LumaKeyEnable; mfxU16 LumaKeyMin; mfxU16 LumaKeyMax; mfxU16 GlobalAlphaEnable; mfxU16 GlobalAlpha; mfxU16 PixelAlphaEnable; mfxU16 TileId; mfxU16 reserved2[17]; } mfxVPPCompInputStream; typedef struct { mfxExtBuffer Header; /* background color*/ union { mfxU16 Y; mfxU16 R; }; union { mfxU16 U; mfxU16 G; }; union { mfxU16 V; mfxU16 B; }; mfxU16 NumTiles; mfxU16 reserved1[23]; mfxU16 NumInputStream; mfxVPPCompInputStream *InputStream; } mfxExtVPPComposite; /* TransferMatrix */ enum { MFX_TRANSFERMATRIX_UNKNOWN = 0, MFX_TRANSFERMATRIX_BT709 = 1, MFX_TRANSFERMATRIX_BT601 = 2 }; /* NominalRange */ enum { MFX_NOMINALRANGE_UNKNOWN = 0, MFX_NOMINALRANGE_0_255 = 1, MFX_NOMINALRANGE_16_235 = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 reserved1[4]; union { struct { // Init struct { mfxU16 TransferMatrix; mfxU16 NominalRange; mfxU16 reserved2[6]; } In, Out; }; struct { // Runtime mfxU16 TransferMatrix; mfxU16 NominalRange; mfxU16 reserved3[14]; }; }; } mfxExtVPPVideoSignalInfo; /* ROI encoding mode */ enum { MFX_ROI_MODE_PRIORITY = 0, MFX_ROI_MODE_QP_DELTA = 1 }; typedef struct { mfxExtBuffer Header; mfxU16 NumROI; mfxU16 ROIMode; mfxU16 reserved1[10]; struct { mfxU32 Left; mfxU32 Top; mfxU32 Right; mfxU32 Bottom; union { mfxI16 Priority; mfxI16 DeltaQP; }; mfxU16 reserved2[7]; } ROI[256]; } mfxExtEncoderROI; /*Deinterlacing Mode*/ enum { MFX_DEINTERLACING_BOB = 1, MFX_DEINTERLACING_ADVANCED = 2, MFX_DEINTERLACING_AUTO_DOUBLE = 3, MFX_DEINTERLACING_AUTO_SINGLE = 4, MFX_DEINTERLACING_FULL_FR_OUT = 5, MFX_DEINTERLACING_HALF_FR_OUT = 6, MFX_DEINTERLACING_24FPS_OUT = 7, MFX_DEINTERLACING_FIXED_TELECINE_PATTERN = 8, MFX_DEINTERLACING_30FPS_OUT = 9, MFX_DEINTERLACING_DETECT_INTERLACE = 10, MFX_DEINTERLACING_ADVANCED_NOREF = 11, MFX_DEINTERLACING_ADVANCED_SCD = 12, MFX_DEINTERLACING_FIELD_WEAVING = 13 }; /*TelecinePattern*/ enum { MFX_TELECINE_PATTERN_32 = 0, MFX_TELECINE_PATTERN_2332 = 1, MFX_TELECINE_PATTERN_FRAME_REPEAT = 2, MFX_TELECINE_PATTERN_41 = 3, MFX_TELECINE_POSITION_PROVIDED = 4 }; typedef struct { mfxExtBuffer Header; mfxU16 Mode; mfxU16 TelecinePattern; mfxU16 TelecineLocation; mfxU16 reserved[9]; } mfxExtVPPDeinterlacing; typedef struct { mfxExtBuffer Header; mfxU16 NumRefIdxL0Active; mfxU16 NumRefIdxL1Active; mfxU16 reserved[2]; struct mfxRefPic{ mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 reserved[5]; } RefPicList0[32], RefPicList1[32]; }mfxExtAVCRefLists; enum { MFX_VPP_COPY_FRAME =0x01, MFX_VPP_COPY_FIELD =0x02, MFX_VPP_SWAP_FIELDS =0x03 }; /*PicType*/ enum { MFX_PICTYPE_UNKNOWN =0x00, MFX_PICTYPE_FRAME =0x01, MFX_PICTYPE_TOPFIELD =0x02, MFX_PICTYPE_BOTTOMFIELD =0x04 }; typedef struct { mfxExtBuffer Header; mfxU16 Mode; mfxU16 InField; mfxU16 OutField; mfxU16 reserved[25]; } mfxExtVPPFieldProcessing; typedef struct { mfxExtBuffer Header; struct mfxIn{ mfxU16 CropX; mfxU16 CropY; mfxU16 CropW; mfxU16 CropH; mfxU16 reserved[12]; }In; struct mfxOut{ mfxU32 FourCC; mfxU16 ChromaFormat; mfxU16 reserved1; mfxU16 Width; mfxU16 Height; mfxU16 CropX; mfxU16 CropY; mfxU16 CropW; mfxU16 CropH; mfxU16 reserved[22]; }Out; mfxU16 reserved[13]; } mfxExtDecVideoProcessing; typedef struct { mfxExtBuffer Header; mfxU16 ChromaLocInfoPresentFlag; mfxU16 ChromaSampleLocTypeTopField; mfxU16 ChromaSampleLocTypeBottomField; mfxU16 reserved[9]; } mfxExtChromaLocInfo; /* MBQPMode */ enum { MFX_MBQP_MODE_QP_VALUE = 0, // supported in CQP mode only MFX_MBQP_MODE_QP_DELTA = 1 }; typedef struct { mfxExtBuffer Header; mfxU32 reserved[10]; mfxU16 Mode; // see MBQPMode enum mfxU16 BlockSize; // QP block size, valid for HEVC only during Init and Runtime mfxU32 NumQPAlloc; // Size of allocated by application QP or DeltaQP array union { mfxU8 *QP; // Block QP value. Valid when Mode = MFX_MBQP_MODE_QP_VALUE mfxI8 *DeltaQP; // For block i: QP[i] = BrcQP[i] + DeltaQP[i]. Valid when Mode = MFX_MBQP_MODE_QP_DELTA mfxU64 reserved2; }; } mfxExtMBQP; typedef struct { mfxExtBuffer Header; mfxU32 reserved[11]; mfxU32 MapSize; union { mfxU8 *Map; mfxU64 reserved2; }; } mfxExtMBForceIntra; typedef struct { mfxExtBuffer Header; mfxU16 NumTileRows; mfxU16 NumTileColumns; mfxU16 reserved[74]; }mfxExtHEVCTiles; typedef struct { mfxExtBuffer Header; mfxU32 reserved[11]; mfxU32 MapSize; union { mfxU8 *Map; mfxU64 reserved2; }; } mfxExtMBDisableSkipMap; /*GeneralConstraintFlags*/ enum { /* REXT Profile constraint flags*/ MFX_HEVC_CONSTR_REXT_MAX_12BIT = (1 << 0), MFX_HEVC_CONSTR_REXT_MAX_10BIT = (1 << 1), MFX_HEVC_CONSTR_REXT_MAX_8BIT = (1 << 2), MFX_HEVC_CONSTR_REXT_MAX_422CHROMA = (1 << 3), MFX_HEVC_CONSTR_REXT_MAX_420CHROMA = (1 << 4), MFX_HEVC_CONSTR_REXT_MAX_MONOCHROME = (1 << 5), MFX_HEVC_CONSTR_REXT_INTRA = (1 << 6), MFX_HEVC_CONSTR_REXT_ONE_PICTURE_ONLY = (1 << 7), MFX_HEVC_CONSTR_REXT_LOWER_BIT_RATE = (1 << 8) }; /* SampleAdaptiveOffset */ enum { MFX_SAO_UNKNOWN = 0x00, MFX_SAO_DISABLE = 0x01, MFX_SAO_ENABLE_LUMA = 0x02, MFX_SAO_ENABLE_CHROMA = 0x04 }; #pragma pack(push, 4) typedef struct { mfxExtBuffer Header; mfxU16 PicWidthInLumaSamples; mfxU16 PicHeightInLumaSamples; mfxU64 GeneralConstraintFlags; mfxU16 SampleAdaptiveOffset; /* see enum SampleAdaptiveOffset, valid during Init and Runtime */ mfxU16 LCUSize; mfxU16 reserved[116]; } mfxExtHEVCParam; #pragma pack(pop) /*ErrorTypes in mfxExtDecodeErrorReport*/ enum { MFX_ERROR_PPS = (1 << 0), MFX_ERROR_SPS = (1 << 1), MFX_ERROR_SLICEHEADER = (1 << 2), MFX_ERROR_SLICEDATA = (1 << 3), MFX_ERROR_FRAME_GAP = (1 << 4), }; typedef struct { mfxExtBuffer Header; mfxU32 ErrorTypes; mfxU16 reserved[10]; } mfxExtDecodeErrorReport; typedef struct { mfxExtBuffer Header; mfxU16 FrameType; mfxU16 reserved[59]; } mfxExtDecodedFrameInfo; typedef struct { mfxExtBuffer Header; mfxU16 DropFrameFlag; mfxU16 TimeCodeHours; mfxU16 TimeCodeMinutes; mfxU16 TimeCodeSeconds; mfxU16 TimeCodePictures; mfxU16 reserved[7]; } mfxExtTimeCode; /*RegionType*/ enum { MFX_HEVC_REGION_SLICE = 0 }; /*RegionEncoding*/ enum { MFX_HEVC_REGION_ENCODING_ON = 0, MFX_HEVC_REGION_ENCODING_OFF = 1 }; typedef struct { mfxExtBuffer Header; mfxU32 RegionId; mfxU16 RegionType; mfxU16 RegionEncoding; mfxU16 reserved[24]; } mfxExtHEVCRegion; typedef struct { mfxExtBuffer Header; mfxU16 LumaLog2WeightDenom; // 0..7 mfxU16 ChromaLog2WeightDenom; // 0..7 mfxU16 LumaWeightFlag[2][32]; // [list] 0,1 mfxU16 ChromaWeightFlag[2][32]; // [list] 0,1 mfxI16 Weights[2][32][3][2]; // [list][list entry][Y, Cb, Cr][weight, offset] mfxU16 reserved[58]; } mfxExtPredWeightTable; typedef struct { mfxExtBuffer Header; mfxU16 EnableRoundingIntra; // tri-state option mfxU16 RoundingOffsetIntra; // valid value [0,7] mfxU16 EnableRoundingInter; // tri-state option mfxU16 RoundingOffsetInter; // valid value [0,7] mfxU16 reserved[24]; } mfxExtAVCRoundingOffset; typedef struct { mfxExtBuffer Header; mfxU16 NumRect; mfxU16 reserved1[11]; struct { mfxU32 Left; mfxU32 Top; mfxU32 Right; mfxU32 Bottom; mfxU16 reserved2[8]; } Rect[256]; } mfxExtDirtyRect; typedef struct { mfxExtBuffer Header; mfxU16 NumRect; mfxU16 reserved1[11]; struct { mfxU32 DestLeft; mfxU32 DestTop; mfxU32 DestRight; mfxU32 DestBottom; mfxU32 SourceLeft; mfxU32 SourceTop; mfxU16 reserved2[4]; } Rect[256]; } mfxExtMoveRect; /* Angle */ enum { MFX_ANGLE_0 = 0, MFX_ANGLE_90 = 90, MFX_ANGLE_180 = 180, MFX_ANGLE_270 = 270 }; typedef struct { mfxExtBuffer Header; mfxU16 Angle; mfxU16 reserved[11]; } mfxExtVPPRotation; typedef struct { mfxExtBuffer Header; mfxU16 SliceSizeOverflow; mfxU16 NumSliceNonCopliant; mfxU16 NumEncodedSlice; mfxU16 NumSliceSizeAlloc; union { mfxU16 *SliceSize; mfxU64 reserved1; }; mfxU16 reserved[20]; } mfxExtEncodedSlicesInfo; /* ScalingMode */ enum { MFX_SCALING_MODE_DEFAULT = 0, MFX_SCALING_MODE_LOWPOWER = 1, MFX_SCALING_MODE_QUALITY = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 ScalingMode; mfxU16 reserved[11]; } mfxExtVPPScaling; typedef mfxExtAVCRefListCtrl mfxExtHEVCRefListCtrl; typedef mfxExtAVCRefLists mfxExtHEVCRefLists; typedef mfxExtAvcTemporalLayers mfxExtHEVCTemporalLayers; /* MirroringType */ enum { MFX_MIRRORING_DISABLED = 0, MFX_MIRRORING_HORIZONTAL = 1, MFX_MIRRORING_VERTICAL = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 Type; mfxU16 reserved[11]; } mfxExtVPPMirroring; typedef struct { mfxExtBuffer Header; mfxU16 StickTop; /* tri-state option */ mfxU16 StickBottom; /* tri-state option */ mfxU16 StickLeft; /* tri-state option */ mfxU16 StickRight; /* tri-state option */ mfxU16 reserved[8]; } mfxExtMVOverPicBoundaries; typedef struct { mfxExtBuffer Header; mfxU16 Enable; /* tri-state option */ mfxU16 reserved[11]; } mfxExtVPPColorFill; /* ChromaSiting */ enum { MFX_CHROMA_SITING_UNKNOWN = 0x0000, MFX_CHROMA_SITING_VERTICAL_TOP = 0x0001, /* Chroma samples are co-sited vertically on the top with the luma samples. */ MFX_CHROMA_SITING_VERTICAL_CENTER = 0x0002, /* Chroma samples are not co-sited vertically with the luma samples. */ MFX_CHROMA_SITING_VERTICAL_BOTTOM = 0x0004, /* Chroma samples are co-sited vertically on the bottom with the luma samples. */ MFX_CHROMA_SITING_HORIZONTAL_LEFT = 0x0010, /* Chroma samples are co-sited horizontally on the left with the luma samples. */ MFX_CHROMA_SITING_HORIZONTAL_CENTER = 0x0020 /* Chroma samples are not co-sited horizontally with the luma samples. */ }; typedef struct { mfxExtBuffer Header; mfxU16 ChromaSiting; mfxU16 reserved[27]; } mfxExtColorConversion; /* VP9ReferenceFrame */ enum { MFX_VP9_REF_INTRA = 0, MFX_VP9_REF_LAST = 1, MFX_VP9_REF_GOLDEN = 2, MFX_VP9_REF_ALTREF = 3 }; /* SegmentIdBlockSize */ enum { MFX_VP9_SEGMENT_ID_BLOCK_SIZE_UNKNOWN = 0, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_8x8 = 8, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_16x16 = 16, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_32x32 = 32, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_64x64 = 64, }; /* SegmentFeature */ enum { MFX_VP9_SEGMENT_FEATURE_QINDEX = 0x0001, MFX_VP9_SEGMENT_FEATURE_LOOP_FILTER = 0x0002, MFX_VP9_SEGMENT_FEATURE_REFERENCE = 0x0004, MFX_VP9_SEGMENT_FEATURE_SKIP = 0x0008 /* (0,0) MV, no residual */ }; typedef struct { mfxU16 FeatureEnabled; /* see enum SegmentFeature */ mfxI16 QIndexDelta; mfxI16 LoopFilterLevelDelta; mfxU16 ReferenceFrame; /* see enum VP9ReferenceFrame */ mfxU16 reserved[12]; } mfxVP9SegmentParam; typedef struct { mfxExtBuffer Header; mfxU16 NumSegments; /* 0..8 */ mfxVP9SegmentParam Segment[8]; mfxU16 SegmentIdBlockSize; /* see enum SegmentIdBlockSize */ mfxU32 NumSegmentIdAlloc; /* >= (Ceil(Width / SegmentIdBlockSize) * Ceil(Height / SegmentIdBlockSize)) */ union { mfxU8 *SegmentId; /*[NumSegmentIdAlloc] = 0..7, index in Segment array, blocks of SegmentIdBlockSize map */ mfxU64 reserved1; }; mfxU16 reserved[52]; } mfxExtVP9Segmentation; typedef struct { mfxU16 FrameRateScale; /* Layer[n].FrameRateScale = Layer[n - 1].FrameRateScale * (uint)m */ mfxU16 TargetKbps; /* affected by BRCParamMultiplier, Layer[n].TargetKbps > Layer[n - 1].TargetKbps */ mfxU16 reserved[14]; } mfxVP9TemporalLayer; typedef struct { mfxExtBuffer Header; mfxVP9TemporalLayer Layer[8]; mfxU16 reserved[60]; } mfxExtVP9TemporalLayers; typedef struct { mfxExtBuffer Header; mfxU16 FrameWidth; mfxU16 FrameHeight; mfxU16 WriteIVFHeaders; /* tri-state option */ mfxI16 reserved1[6]; mfxI16 QIndexDeltaLumaDC; mfxI16 QIndexDeltaChromaAC; mfxI16 QIndexDeltaChromaDC; mfxU16 reserved[112]; } mfxExtVP9Param; /* Multi-Frame Mode */ enum { MFX_MF_DEFAULT = 0, MFX_MF_DISABLED = 1, MFX_MF_AUTO = 2, MFX_MF_MANUAL = 3 }; /* Multi-Frame Initialization parameters */ typedef struct { mfxExtBuffer Header; mfxU16 MFMode; mfxU16 MaxNumFrames; mfxU16 reserved[58]; } mfxExtMultiFrameParam; /* Multi-Frame Run-time controls */ typedef struct { mfxExtBuffer Header; mfxU32 Timeout; /* timeout in millisecond */ mfxU16 Flush; /* Flush internal frame buffer, e.g. submit all collected frames. */ mfxU16 reserved[57]; } mfxExtMultiFrameControl; typedef struct { mfxU16 Type; mfxU16 reserved1; mfxU32 Offset; mfxU32 Size; mfxU32 reserved[5]; } mfxEncodedUnitInfo; typedef struct { mfxExtBuffer Header; union { mfxEncodedUnitInfo *UnitInfo; mfxU64 reserved1; }; mfxU16 NumUnitsAlloc; mfxU16 NumUnitsEncoded; mfxU16 reserved[22]; } mfxExtEncodedUnitsInfo; /* MCTF initialization & runtime */ typedef struct { mfxExtBuffer Header; mfxU16 FilterStrength; mfxU16 reserved[27]; } mfxExtVppMctf; #ifdef __cplusplus } // extern "C" #endif #endif
Bl00drav3n/obs-studio
plugins/obs-qsv11/libmfx/include/msdk/include/mfxstructures.h
C
gpl-2.0
55,070
/* * 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.commons.math.genetics; import java.util.ArrayList; import java.util.List; import org.apache.commons.math.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * This is also an example of usage. * * This algorithm does "stochastic sorting" of a sequence 0,...,N. * */ public class GeneticAlgorithmTestPermutations { // parameters for the GA private static final int DIMENSION = 20; private static final int POPULATION_SIZE = 80; private static final int NUM_GENERATIONS = 200; private static final double ELITISM_RATE = 0.2; private static final double CROSSOVER_RATE = 1; private static final double MUTATION_RATE = 0.08; private static final int TOURNAMENT_ARITY = 2; // numbers from 0 to N-1 private static final List<Integer> sequence = new ArrayList<Integer>(); static { for (int i=0; i<DIMENSION; i++) { sequence.add(i); } } @Test public void test() { // to test a stochastic algorithm is hard, so this will rather be an usage example // initialize a new genetic algorithm GeneticAlgorithm ga = new GeneticAlgorithm( new OnePointCrossover<Integer>(), CROSSOVER_RATE, new RandomKeyMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY) ); // initial population Population initial = randomPopulation(); // stopping conditions StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS); // best initial chromosome Chromosome bestInitial = initial.getFittestChromosome(); // run the algorithm Population finalPopulation = ga.evolve(initial, stopCond); // best chromosome from the final population Chromosome bestFinal = finalPopulation.getFittestChromosome(); // the only thing we can test is whether the final solution is not worse than the initial one // however, for some implementations of GA, this need not be true :) Assert.assertTrue(bestFinal.compareTo(bestInitial) > 0); //System.out.println(bestInitial); //System.out.println(bestFinal); } /** * Initializes a random population */ private static ElitisticListPopulation randomPopulation() { List<Chromosome> popList = new ArrayList<Chromosome>(); for (int i=0; i<POPULATION_SIZE; i++) { Chromosome randChrom = new MinPermutations(RandomKey.randomPermutation(DIMENSION)); popList.add(randChrom); } return new ElitisticListPopulation(popList, popList.size(), ELITISM_RATE); } /** * Chromosomes representing a permutation of (0,1,2,...,DIMENSION-1). * * The goal is to sort the sequence. */ private static class MinPermutations extends RandomKey<Integer> { public MinPermutations(List<Double> representation) { super(representation); } public double fitness() { int res = 0; List<Integer> decoded = decode(sequence); for (int i=0; i<decoded.size(); i++) { int value = decoded.get(i); if (value != i) { // bad position found res += FastMath.abs(value - i); } } // the most fitted chromosome is the one with minimal error // therefore we must return negative value return -res; } @Override public AbstractListChromosome<Double> newFixedLengthChromosome(List<Double> chromosomeRepresentation) { return new MinPermutations(chromosomeRepresentation); } } }
SpoonLabs/astor
examples/math_50v2/src/test/java/org/apache/commons/math/genetics/GeneticAlgorithmTestPermutations.java
Java
gpl-2.0
4,580
<?php /** * Kunena Component * @package Kunena.Framework * @subpackage Forum.Menu * * @copyright (C) 2008 - 2015 Kunena Team. All rights reserved. * @copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined ( '_JEXEC' ) or die (); /** * Class KunenaMenuHelper */ abstract class KunenaMenuHelper { public static function cleanCache() { /** @var JCache|JCacheController $cache */ $cache = JFactory::getCache(); $cache->clean('mod_menu'); } /** * Get a list of the menu items (taken from Joomla 2.5.1). * This only method need to be used only in frontend part * * @param JRegistry $params The module options. * * @return array * @see modules/mod_menu/helper.php */ public static function getList(&$params) { $app = JFactory::getApplication(); $menu = $app->getMenu(); // If no active menu, use default $active = ($menu->getActive()) ? $menu->getActive() : $menu->getDefault(); $levels = JFactory::getUser()->getAuthorisedViewLevels(); asort($levels); $key = 'menu_items'.$params.implode(',', $levels).'.'.$active->id; $cache = JFactory::getCache('com_kunena.menu', ''); // FIXME: enable caching after fixing the issues $items = array(); if (true) { // !($items = $cache->get($key))) { // Initialise variables. $path = $active->tree; $start = (int) $params->get('startLevel'); $end = (int) $params->get('endLevel'); $showAll = $params->get('showAllChildren'); $items = $menu->getItems('menutype', $params->get('menutype')); if ($items) { foreach($items as $i => $item) { if (($start && $start > $item->level) || ($end && $item->level > $end) || (!$showAll && $item->level > 1 && !in_array($item->parent_id, $path)) || ($start > 1 && !in_array($item->tree[$start-2], $path)) ) { unset($items[$i]); continue; } $item->deeper = false; $item->shallower = false; $item->level_diff = 0; if (isset($lastitem)) { $lastitem->deeper = ($item->level > $lastitem->level); $lastitem->shallower = ($item->level < $lastitem->level); $lastitem->level_diff = ($lastitem->level - $item->level); } $item->parent = (boolean) $menu->getItems('parent_id', (int) $item->id, true); $lastitem = $item; $item->active = false; $item->flink = $item->link; switch ($item->type) { case 'separator': // No further action needed. continue; case 'url': if ((strpos($item->link, 'index.php?') === 0) && (strpos($item->link, 'Itemid=') === false)) { // If this is an internal Joomla link, ensure the Itemid is set. $item->flink = $item->link.'&Itemid='.$item->id; } break; case 'alias': // If this is an alias use the item id stored in the parameters to make the link. $item->flink = 'index.php?Itemid='.$item->params->get('aliasoptions'); break; default: $router = $app::getRouter(); if ($router->getMode() == JROUTER_MODE_SEF) { $item->flink = 'index.php?Itemid='.$item->id; } else { $item->flink .= '&Itemid='.$item->id; } break; } if (strcasecmp(substr($item->flink, 0, 4), 'http') && (strpos($item->flink, 'index.php?') !== false)) { $item->flink = JRoute::_($item->flink, false, $item->params->get('secure')); } else { $item->flink = JRoute::_($item->flink, false); } $item->title = htmlspecialchars($item->title); $item->anchor_css = htmlspecialchars($item->params->get('menu-anchor_css', '')); $item->anchor_title = htmlspecialchars($item->params->get('menu-anchor_title', '')); $item->menu_image = $item->params->get('menu_image', '') ? htmlspecialchars($item->params->get('menu_image', '')) : ''; } if (isset($lastitem)) { $lastitem->deeper = (($start?$start:1) > $lastitem->level); $lastitem->shallower = (($start?$start:1) < $lastitem->level); $lastitem->level_diff = ($lastitem->level - ($start?$start:1)); } } // FIXME: enable caching after fixing the issues //$cache->store($items, $key); } return $items; } }
albert1974/WebMatrix
libraries/kunena/menu/helper.php
PHP
gpl-2.0
4,272
/************************************************************************* Copyright (c) 2007, Sergey Bochkanov (ALGLIB project). 1988, Pierre L'Ecuyer >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ #include <stdafx.h> #include "hqrnd.h" static const int hqrndmax = 2147483563; static const int hqrndm1 = 2147483563; static const int hqrndm2 = 2147483399; static const int hqrndmagic = 1634357784; static int hqrndintegerbase(hqrndstate& state); /************************************************************************* HQRNDState initialization with random values which come from standard RNG. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndrandomize(hqrndstate& state) { hqrndseed(ap::randominteger(hqrndm1), ap::randominteger(hqrndm2), state); } /************************************************************************* HQRNDState initialization with seed values -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndseed(int s1, int s2, hqrndstate& state) { state.s1 = s1%(hqrndm1-1)+1; state.s2 = s2%(hqrndm2-1)+1; state.v = double(1)/double(hqrndmax); state.magicv = hqrndmagic; } /************************************************************************* This function generates random real number in (0,1), not including interval boundaries State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrnduniformr(hqrndstate& state) { double result; result = state.v*hqrndintegerbase(state); return result; } /************************************************************************* This function generates random integer number in [0, N) 1. N must be less than HQRNDMax-1. 2. State structure must be initialized with HQRNDRandomize() or HQRNDSeed() -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ int hqrnduniformi(int n, hqrndstate& state) { int result; int mx; // // Correct handling of N's close to RNDBaseMax // (avoiding skewed distributions for RNDBaseMax<>K*N) // ap::ap_error::make_assertion(n>0, "HQRNDUniformI: N<=0!"); ap::ap_error::make_assertion(n<hqrndmax-1, "HQRNDUniformI: N>=RNDBaseMax-1!"); mx = hqrndmax-1-(hqrndmax-1)%n; do { result = hqrndintegerbase(state)-1; } while(result>=mx); result = result%n; return result; } /************************************************************************* Random number generator: normal numbers This function generates one random number from normal distribution. Its performance is equal to that of HQRNDNormal2() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndnormal(hqrndstate& state) { double result; double v1; double v2; hqrndnormal2(state, v1, v2); result = v1; return result; } /************************************************************************* Random number generator: random X and Y such that X^2+Y^2=1 State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndunit2(hqrndstate& state, double& x, double& y) { double result; double v; double mx; double mn; do { hqrndnormal2(state, x, y); } while(!(ap::fp_neq(x,0)||ap::fp_neq(y,0))); mx = ap::maxreal(fabs(x), fabs(y)); mn = ap::minreal(fabs(x), fabs(y)); v = mx*sqrt(1+ap::sqr(mn/mx)); x = x/v; y = y/v; return result; } /************************************************************************* Random number generator: normal numbers This function generates two independent random numbers from normal distribution. Its performance is equal to that of HQRNDNormal() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndnormal2(hqrndstate& state, double& x1, double& x2) { double u; double v; double s; while(true) { u = 2*hqrnduniformr(state)-1; v = 2*hqrnduniformr(state)-1; s = ap::sqr(u)+ap::sqr(v); if( ap::fp_greater(s,0)&&ap::fp_less(s,1) ) { // // two Sqrt's instead of one to // avoid overflow when S is too small // s = sqrt(-2*log(s))/sqrt(s); x1 = u*s; x2 = v*s; return; } } } /************************************************************************* Random number generator: exponential distribution State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 11.08.2007 by Bochkanov Sergey *************************************************************************/ double hqrndexponential(double lambda, hqrndstate& state) { double result; ap::ap_error::make_assertion(ap::fp_greater(lambda,0), "HQRNDExponential: Lambda<=0!"); result = -log(hqrnduniformr(state))/lambda; return result; } /************************************************************************* L'Ecuyer, Efficient and portable combined random number generators *************************************************************************/ static int hqrndintegerbase(hqrndstate& state) { int result; int k; ap::ap_error::make_assertion(state.magicv==hqrndmagic, "HQRNDIntegerBase: State is not correctly initialized!"); k = state.s1/53668; state.s1 = 40014*(state.s1-k*53668)-k*12211; if( state.s1<0 ) { state.s1 = state.s1+2147483563; } k = state.s2/52774; state.s2 = 40692*(state.s2-k*52774)-k*3791; if( state.s2<0 ) { state.s2 = state.s2+2147483399; } // // Result // result = state.s1-state.s2; if( result<1 ) { result = result+2147483562; } return result; }
christianurich/VIBe2GUI
src/3dparty/alglib/src/hqrnd.cpp
C++
gpl-2.0
7,457
/** * \file * <!-- * This file is part of BeRTOS. * * Bertos is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. * * Copyright 2008 Develer S.r.l. (http://www.develer.com/) * All Rights Reserved. * --> * * \brief Configuration file for data flash memory module. * * \version $Id$ * \author Daniele Basile <asterix@develer.com> */ #ifndef CFG_DATAFLASH_H #define CFG_DATAFLASH_H /** * Module logging level. * $WIZ$ type = "enum" * $WIZ$ value_list = "log_level" */ #define DATAFLASH_LOG_LEVEL LOG_LVL_INFO /** * Module logging format. * $WIZ$ type = "enum" * $WIZ$ value_list = "log_format" */ #define DATAFLASH_LOG_FORMAT LOG_FMT_TERSE #endif /* CFG_DATAFLASH_H */
mtarek/BeRTOS
boards/arduino-mega/templates/kernel/cfg/cfg_dataflash.h
C
gpl-2.0
1,905
var base = require('settings/teams/update-team-photo'); Vue.component('spark-update-team-photo', { mixins: [base] });
expoteca/expoteca.com
spark/install-stubs/resources/assets/js/spark-components/settings/teams/update-team-photo.js
JavaScript
gpl-3.0
123
/* wc - print the number of lines, words, and bytes in files Copyright (C) 1985-2016 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Written by Paul Rubin, phr@ocf.berkeley.edu and David MacKenzie, djm@gnu.ai.mit.edu. */ #include <config.h> #include <stdio.h> #include <assert.h> #include <getopt.h> #include <sys/types.h> #include <wchar.h> #include <wctype.h> #include "system.h" #include "argv-iter.h" #include "error.h" #include "fadvise.h" #include "mbchar.h" #include "physmem.h" #include "readtokens0.h" #include "safe-read.h" #include "stat-size.h" #include "xfreopen.h" #if !defined iswspace && !HAVE_ISWSPACE # define iswspace(wc) \ ((wc) == to_uchar (wc) && isspace (to_uchar (wc))) #endif /* The official name of this program (e.g., no 'g' prefix). */ #define PROGRAM_NAME "wc" #define AUTHORS \ proper_name ("Paul Rubin"), \ proper_name ("David MacKenzie") /* Size of atomic reads. */ #define BUFFER_SIZE (16 * 1024) /* Cumulative number of lines, words, chars and bytes in all files so far. max_line_length is the maximum over all files processed so far. */ static uintmax_t total_lines; static uintmax_t total_words; static uintmax_t total_chars; static uintmax_t total_bytes; static uintmax_t max_line_length; /* Which counts to print. */ static bool print_lines, print_words, print_chars, print_bytes; static bool print_linelength; /* The print width of each count. */ static int number_width; /* True if we have ever read the standard input. */ static bool have_read_stdin; /* The result of calling fstat or stat on a file descriptor or file. */ struct fstatus { /* If positive, fstat or stat has not been called yet. Otherwise, this is the value returned from fstat or stat. */ int failed; /* If FAILED is zero, this is the file's status. */ struct stat st; }; /* For long options that have no equivalent short option, use a non-character as a pseudo short option, starting with CHAR_MAX + 1. */ enum { FILES0_FROM_OPTION = CHAR_MAX + 1 }; static struct option const longopts[] = { {"bytes", no_argument, NULL, 'c'}, {"chars", no_argument, NULL, 'm'}, {"lines", no_argument, NULL, 'l'}, {"words", no_argument, NULL, 'w'}, {"files0-from", required_argument, NULL, FILES0_FROM_OPTION}, {"max-line-length", no_argument, NULL, 'L'}, {GETOPT_HELP_OPTION_DECL}, {GETOPT_VERSION_OPTION_DECL}, {NULL, 0, NULL, 0} }; void usage (int status) { if (status != EXIT_SUCCESS) emit_try_help (); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ or: %s [OPTION]... --files0-from=F\n\ "), program_name, program_name); fputs (_("\ Print newline, word, and byte counts for each FILE, and a total line if\n\ more than one FILE is specified. A word is a non-zero-length sequence of\n\ characters delimited by white space.\n\ "), stdout); emit_stdin_note (); fputs (_("\ \n\ The options below may be used to select which counts are printed, always in\n\ the following order: newline, word, character, byte, maximum line length.\n\ -c, --bytes print the byte counts\n\ -m, --chars print the character counts\n\ -l, --lines print the newline counts\n\ "), stdout); fputs (_("\ --files0-from=F read input from the files specified by\n\ NUL-terminated names in file F;\n\ If F is - then read names from standard input\n\ -L, --max-line-length print the maximum display width\n\ -w, --words print the word counts\n\ "), stdout); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); emit_ancillary_info (PROGRAM_NAME); } exit (status); } /* FILE is the name of the file (or NULL for standard input) associated with the specified counters. */ static void write_counts (uintmax_t lines, uintmax_t words, uintmax_t chars, uintmax_t bytes, uintmax_t linelength, const char *file) { static char const format_sp_int[] = " %*s"; char const *format_int = format_sp_int + 1; char buf[INT_BUFSIZE_BOUND (uintmax_t)]; if (print_lines) { printf (format_int, number_width, umaxtostr (lines, buf)); format_int = format_sp_int; } if (print_words) { printf (format_int, number_width, umaxtostr (words, buf)); format_int = format_sp_int; } if (print_chars) { printf (format_int, number_width, umaxtostr (chars, buf)); format_int = format_sp_int; } if (print_bytes) { printf (format_int, number_width, umaxtostr (bytes, buf)); format_int = format_sp_int; } if (print_linelength) { printf (format_int, number_width, umaxtostr (linelength, buf)); } if (file) printf (" %s", strchr (file, '\n') ? quotef (file) : file); putchar ('\n'); } /* Count words. FILE_X is the name of the file (or NULL for standard input) that is open on descriptor FD. *FSTATUS is its status. CURRENT_POS is the current file offset if known, negative if unknown. Return true if successful. */ static bool wc (int fd, char const *file_x, struct fstatus *fstatus, off_t current_pos) { bool ok = true; char buf[BUFFER_SIZE + 1]; size_t bytes_read; uintmax_t lines, words, chars, bytes, linelength; bool count_bytes, count_chars, count_complicated; char const *file = file_x ? file_x : _("standard input"); lines = words = chars = bytes = linelength = 0; /* If in the current locale, chars are equivalent to bytes, we prefer counting bytes, because that's easier. */ #if MB_LEN_MAX > 1 if (MB_CUR_MAX > 1) { count_bytes = print_bytes; count_chars = print_chars; } else #endif { count_bytes = print_bytes || print_chars; count_chars = false; } count_complicated = print_words || print_linelength; /* Advise the kernel of our access pattern only if we will read(). */ if (!count_bytes || count_chars || print_lines || count_complicated) fdadvise (fd, 0, 0, FADVISE_SEQUENTIAL); /* When counting only bytes, save some line- and word-counting overhead. If FD is a 'regular' Unix file, using lseek is enough to get its 'size' in bytes. Otherwise, read blocks of BUFFER_SIZE bytes at a time until EOF. Note that the 'size' (number of bytes) that wc reports is smaller than stats.st_size when the file is not positioned at its beginning. That's why the lseek calls below are necessary. For example the command '(dd ibs=99k skip=1 count=0; ./wc -c) < /etc/group' should make wc report '0' bytes. */ if (count_bytes && !count_chars && !print_lines && !count_complicated) { if (0 < fstatus->failed) fstatus->failed = fstat (fd, &fstatus->st); /* For sized files, seek to one st_blksize before EOF rather than to EOF. This works better for files in proc-like file systems where the size is only approximate. */ if (! fstatus->failed && usable_st_size (&fstatus->st) && 0 <= fstatus->st.st_size) { size_t end_pos = fstatus->st.st_size; off_t hi_pos = end_pos - end_pos % (ST_BLKSIZE (fstatus->st) + 1); if (current_pos < 0) current_pos = lseek (fd, 0, SEEK_CUR); if (0 <= current_pos && current_pos < hi_pos && 0 <= lseek (fd, hi_pos, SEEK_CUR)) bytes = hi_pos - current_pos; } fdadvise (fd, 0, 0, FADVISE_SEQUENTIAL); while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) { if (bytes_read == SAFE_READ_ERROR) { error (0, errno, "%s", quotef (file)); ok = false; break; } bytes += bytes_read; } } else if (!count_chars && !count_complicated) { /* Use a separate loop when counting only lines or lines and bytes -- but not chars or words. */ bool long_lines = false; while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) { if (bytes_read == SAFE_READ_ERROR) { error (0, errno, "%s", quotef (file)); ok = false; break; } bytes += bytes_read; char *p = buf; char *end = p + bytes_read; uintmax_t plines = lines; if (! long_lines) { /* Avoid function call overhead for shorter lines. */ while (p != end) lines += *p++ == '\n'; } else { /* memchr is more efficient with longer lines. */ while ((p = memchr (p, '\n', end - p))) { ++p; ++lines; } } /* If the average line length in the block is >= 15, then use memchr for the next block, where system specific optimizations may outweigh function call overhead. FIXME: This line length was determined in 2015, on both x86_64 and ppc64, but it's worth re-evaluating in future with newer compilers, CPUs, or memchr() implementations etc. */ if (lines - plines <= bytes_read / 15) long_lines = true; else long_lines = false; } } #if MB_LEN_MAX > 1 # define SUPPORT_OLD_MBRTOWC 1 else if (MB_CUR_MAX > 1) { bool in_word = false; uintmax_t linepos = 0; mbstate_t state = { 0, }; bool in_shift = false; # if SUPPORT_OLD_MBRTOWC /* Back-up the state before each multibyte character conversion and move the last incomplete character of the buffer to the front of the buffer. This is needed because we don't know whether the 'mbrtowc' function updates the state when it returns -2, -- this is the ISO C 99 and glibc-2.2 behaviour - or not - amended ANSI C, glibc-2.1 and Solaris 5.7 behaviour. We don't have an autoconf test for this, yet. */ size_t prev = 0; /* number of bytes carried over from previous round */ # else const size_t prev = 0; # endif while ((bytes_read = safe_read (fd, buf + prev, BUFFER_SIZE - prev)) > 0) { const char *p; # if SUPPORT_OLD_MBRTOWC mbstate_t backup_state; # endif if (bytes_read == SAFE_READ_ERROR) { error (0, errno, "%s", quotef (file)); ok = false; break; } bytes += bytes_read; p = buf; bytes_read += prev; do { wchar_t wide_char; size_t n; if (!in_shift && is_basic (*p)) { /* Handle most ASCII characters quickly, without calling mbrtowc(). */ n = 1; wide_char = *p; } else { in_shift = true; # if SUPPORT_OLD_MBRTOWC backup_state = state; # endif n = mbrtowc (&wide_char, p, bytes_read, &state); if (n == (size_t) -2) { # if SUPPORT_OLD_MBRTOWC state = backup_state; # endif break; } if (n == (size_t) -1) { /* Remember that we read a byte, but don't complain about the error. Because of the decoding error, this is a considered to be byte but not a character (that is, chars is not incremented). */ p++; bytes_read--; continue; } if (mbsinit (&state)) in_shift = false; if (n == 0) { wide_char = 0; n = 1; } } p += n; bytes_read -= n; chars++; switch (wide_char) { case '\n': lines++; /* Fall through. */ case '\r': case '\f': if (linepos > linelength) linelength = linepos; linepos = 0; goto mb_word_separator; case '\t': linepos += 8 - (linepos % 8); goto mb_word_separator; case ' ': linepos++; /* Fall through. */ case '\v': mb_word_separator: words += in_word; in_word = false; break; default: if (iswprint (wide_char)) { int width = wcwidth (wide_char); if (width > 0) linepos += width; if (iswspace (wide_char)) goto mb_word_separator; in_word = true; } break; } } while (bytes_read > 0); # if SUPPORT_OLD_MBRTOWC if (bytes_read > 0) { if (bytes_read == BUFFER_SIZE) { /* Encountered a very long redundant shift sequence. */ p++; bytes_read--; } memmove (buf, p, bytes_read); } prev = bytes_read; # endif } if (linepos > linelength) linelength = linepos; words += in_word; } #endif else { bool in_word = false; uintmax_t linepos = 0; while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) { const char *p = buf; if (bytes_read == SAFE_READ_ERROR) { error (0, errno, "%s", quotef (file)); ok = false; break; } bytes += bytes_read; do { switch (*p++) { case '\n': lines++; /* Fall through. */ case '\r': case '\f': if (linepos > linelength) linelength = linepos; linepos = 0; goto word_separator; case '\t': linepos += 8 - (linepos % 8); goto word_separator; case ' ': linepos++; /* Fall through. */ case '\v': word_separator: words += in_word; in_word = false; break; default: if (isprint (to_uchar (p[-1]))) { linepos++; if (isspace (to_uchar (p[-1]))) goto word_separator; in_word = true; } break; } } while (--bytes_read); } if (linepos > linelength) linelength = linepos; words += in_word; } if (count_chars < print_chars) chars = bytes; write_counts (lines, words, chars, bytes, linelength, file_x); total_lines += lines; total_words += words; total_chars += chars; total_bytes += bytes; if (linelength > max_line_length) max_line_length = linelength; return ok; } static bool wc_file (char const *file, struct fstatus *fstatus) { if (! file || STREQ (file, "-")) { have_read_stdin = true; if (O_BINARY && ! isatty (STDIN_FILENO)) xfreopen (NULL, "rb", stdin); return wc (STDIN_FILENO, file, fstatus, -1); } else { int fd = open (file, O_RDONLY | O_BINARY); if (fd == -1) { error (0, errno, "%s", quotef (file)); return false; } else { bool ok = wc (fd, file, fstatus, 0); if (close (fd) != 0) { error (0, errno, "%s", quotef (file)); return false; } return ok; } } } /* Return the file status for the NFILES files addressed by FILE. Optimize the case where only one number is printed, for just one file; in that case we can use a print width of 1, so we don't need to stat the file. Handle the case of (nfiles == 0) in the same way; that happens when we don't know how long the list of file names will be. */ static struct fstatus * get_input_fstatus (size_t nfiles, char *const *file) { struct fstatus *fstatus = xnmalloc (nfiles ? nfiles : 1, sizeof *fstatus); if (nfiles == 0 || (nfiles == 1 && ((print_lines + print_words + print_chars + print_bytes + print_linelength) == 1))) fstatus[0].failed = 1; else { size_t i; for (i = 0; i < nfiles; i++) fstatus[i].failed = (! file[i] || STREQ (file[i], "-") ? fstat (STDIN_FILENO, &fstatus[i].st) : stat (file[i], &fstatus[i].st)); } return fstatus; } /* Return a print width suitable for the NFILES files whose status is recorded in FSTATUS. Optimize the same special case that get_input_fstatus optimizes. */ static int _GL_ATTRIBUTE_PURE compute_number_width (size_t nfiles, struct fstatus const *fstatus) { int width = 1; if (0 < nfiles && fstatus[0].failed <= 0) { int minimum_width = 1; uintmax_t regular_total = 0; size_t i; for (i = 0; i < nfiles; i++) if (! fstatus[i].failed) { if (S_ISREG (fstatus[i].st.st_mode)) regular_total += fstatus[i].st.st_size; else minimum_width = 7; } for (; 10 <= regular_total; regular_total /= 10) width++; if (width < minimum_width) width = minimum_width; } return width; } int main (int argc, char **argv) { bool ok; int optc; size_t nfiles; char **files; char *files_from = NULL; struct fstatus *fstatus; struct Tokens tok; initialize_main (&argc, &argv); set_program_name (argv[0]); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); atexit (close_stdout); /* Line buffer stdout to ensure lines are written atomically and immediately so that processes running in parallel do not intersperse their output. */ setvbuf (stdout, NULL, _IOLBF, 0); print_lines = print_words = print_chars = print_bytes = false; print_linelength = false; total_lines = total_words = total_chars = total_bytes = max_line_length = 0; while ((optc = getopt_long (argc, argv, "clLmw", longopts, NULL)) != -1) switch (optc) { case 'c': print_bytes = true; break; case 'm': print_chars = true; break; case 'l': print_lines = true; break; case 'w': print_words = true; break; case 'L': print_linelength = true; break; case FILES0_FROM_OPTION: files_from = optarg; break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: usage (EXIT_FAILURE); } if (! (print_lines || print_words || print_chars || print_bytes || print_linelength)) print_lines = print_words = print_bytes = true; bool read_tokens = false; struct argv_iterator *ai; if (files_from) { FILE *stream; /* When using --files0-from=F, you may not specify any files on the command-line. */ if (optind < argc) { error (0, 0, _("extra operand %s"), quoteaf (argv[optind])); fprintf (stderr, "%s\n", _("file operands cannot be combined with --files0-from")); usage (EXIT_FAILURE); } if (STREQ (files_from, "-")) stream = stdin; else { stream = fopen (files_from, "r"); if (stream == NULL) error (EXIT_FAILURE, errno, _("cannot open %s for reading"), quoteaf (files_from)); } /* Read the file list into RAM if we can detect its size and that size is reasonable. Otherwise, we'll read a name at a time. */ struct stat st; if (fstat (fileno (stream), &st) == 0 && S_ISREG (st.st_mode) && st.st_size <= MIN (10 * 1024 * 1024, physmem_available () / 2)) { read_tokens = true; readtokens0_init (&tok); if (! readtokens0 (stream, &tok) || fclose (stream) != 0) error (EXIT_FAILURE, 0, _("cannot read file names from %s"), quoteaf (files_from)); files = tok.tok; nfiles = tok.n_tok; ai = argv_iter_init_argv (files); } else { files = NULL; nfiles = 0; ai = argv_iter_init_stream (stream); } } else { static char *stdin_only[] = { NULL }; files = (optind < argc ? argv + optind : stdin_only); nfiles = (optind < argc ? argc - optind : 1); ai = argv_iter_init_argv (files); } if (!ai) xalloc_die (); fstatus = get_input_fstatus (nfiles, files); number_width = compute_number_width (nfiles, fstatus); int i; ok = true; for (i = 0; /* */; i++) { bool skip_file = false; enum argv_iter_err ai_err; char *file_name = argv_iter (ai, &ai_err); if (!file_name) { switch (ai_err) { case AI_ERR_EOF: goto argv_iter_done; case AI_ERR_READ: error (0, errno, _("%s: read error"), quotef (files_from)); ok = false; goto argv_iter_done; case AI_ERR_MEM: xalloc_die (); default: assert (!"unexpected error code from argv_iter"); } } if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-")) { /* Give a better diagnostic in an unusual case: printf - | wc --files0-from=- */ error (0, 0, _("when reading file names from stdin, " "no file name of %s allowed"), quoteaf (file_name)); skip_file = true; } if (!file_name[0]) { /* Diagnose a zero-length file name. When it's one among many, knowing the record number may help. FIXME: currently print the record number only with --files0-from=FILE. Maybe do it for argv, too? */ if (files_from == NULL) error (0, 0, "%s", _("invalid zero-length file name")); else { /* Using the standard 'filename:line-number:' prefix here is not totally appropriate, since NUL is the separator, not NL, but it might be better than nothing. */ unsigned long int file_number = argv_iter_n_args (ai); error (0, 0, "%s:%lu: %s", quotef (files_from), file_number, _("invalid zero-length file name")); } skip_file = true; } if (skip_file) ok = false; else ok &= wc_file (file_name, &fstatus[nfiles ? i : 0]); } argv_iter_done: /* No arguments on the command line is fine. That means read from stdin. However, no arguments on the --files0-from input stream is an error means don't read anything. */ if (ok && !files_from && argv_iter_n_args (ai) == 0) ok &= wc_file (NULL, &fstatus[0]); if (read_tokens) readtokens0_free (&tok); if (1 < argv_iter_n_args (ai)) write_counts (total_lines, total_words, total_chars, total_bytes, max_line_length, _("total")); argv_iter_free (ai); free (fstatus); if (have_read_stdin && close (STDIN_FILENO) != 0) error (EXIT_FAILURE, errno, "-"); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
sunny256/coreutils
src/wc.c
C
gpl-3.0
25,096
<?php session_start(); if (empty($_POST) && !empty($_SESSION) && !isset($_REQUEST['stage'])) { $_POST = $_SESSION; } else { $_SESSION = $_POST; } $stage = isset($_POST['stage']) ? $_POST['stage'] : 0; // Before we do anything, if we see config.php, redirect back to the homepage. if (file_exists('../config.php') && $stage != 6) { header("Location: /"); exit; } // do not use the DB in init, we'll bring it up ourselves $init_modules = array('web', 'nodb'); if ($stage > 3) { $init_modules[] = 'auth'; } require realpath(__DIR__ . '/..') . '/includes/init.php'; // List of php modules we expect to see $modules = array('gd','mysqli','mcrypt'); $dbhost = @$_POST['dbhost'] ?: 'localhost'; $dbuser = @$_POST['dbuser'] ?: 'librenms'; $dbpass = @$_POST['dbpass'] ?: ''; $dbname = @$_POST['dbname'] ?: 'librenms'; $dbport = @$_POST['dbport'] ?: 3306; $dbsocket = @$_POST['dbsocket'] ?: ''; $config['db_host']=$dbhost; $config['db_user']=$dbuser; $config['db_pass']=$dbpass; $config['db_name']=$dbname; $config['db_port']=$dbport; $config['db_socket']=$dbsocket; if (!empty($config['db_socket'])) { $config['db_host'] = ''; $config['db_port'] = null; } else { $config['db_socket'] = null; } $add_user = @$_POST['add_user'] ?: ''; $add_pass = @$_POST['add_pass'] ?: ''; $add_email = @$_POST['add_email'] ?: ''; // Check we can connect to MySQL DB, if not, back to stage 1 :) if ($stage > 1) { try { dbConnect(); if ($stage == 2 && $_SESSION['build-ok'] == true) { $stage = 3; $msg = "It appears that the database is already setup so have moved onto stage $stage"; } } catch (\LibreNMS\Exceptions\DatabaseConnectException $e) { $stage = 1; $msg = "Couldn't connect to the database, please check your details<br /> " . $e->getMessage(); } $_SESSION['stage'] = $stage; } if ($stage == 4) { // Now check we have a username, password and email before adding new user if (empty($add_user) || empty($add_pass) || empty($add_email)) { $stage = 3; $msg = "You haven't entered enough information to add the user account, please check below and re-try"; } } elseif ($stage == 6) { session_destroy(); // If we get here then let's do some final checks. if (!file_exists("../config.php")) { // config.php file doesn't exist. go back to that stage $msg = "config.php still doesn't exist"; $stage = 5; } } if (empty($stage)) { $stage = 0; } $total_stages = 6; $stage_perc = $stage / $total_stages * 100; $complete = 1; ?> <!DOCTYPE HTML> <html> <head> <title><?php echo($config['page_title_prefix']); ?></title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta http-equiv="content-language" content="en-us" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo($config['stylesheet']); ?>" rel="stylesheet" type="text/css" /> <link href="css/typeahead.js-bootstrap.css" rel="stylesheet" type="text/css" /> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap-hover-dropdown.min.js"></script> <script src="js/typeahead.min.js"></script> <script src="js/hogan-2.0.0.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <h2 class="text-center">Welcome to the <?php echo($config['project_name']); ?> install</h2> </div> <div class="col-md-3"> </div> </div> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <h4 class="text-center">Stage <?php echo $stage; ?> of <?php echo $total_stages; ?> complete</h4> </div> <div class="col-md-3"> </div> </div> <?php if (!empty($msg)) { ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="alert alert-danger"><?php echo $msg; ?></div> </div> <div class="col-md-3"> </div> </div> <?php } ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="progress progress-striped"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="<?php echo $stage_perc; ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $stage_perc; ?>%"> <span class="sr-only"><?php echo $stage_perc; ?>% Complete</span> </div> </div> </div> <div class="col-md-3"> </div> </div> <?php if ($stage == 0) { ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <h5 class="text-center">Checking PHP module support</h5> </div> <div class="col-md-3"> </div> </div> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <table class="table table-condensed table-bordered"> <tr> <th>Module</th> <th>Installed</th> <th>Comments</th> </tr> <?php foreach ($modules as $extension) { if (extension_loaded("$extension")) { $ext_loaded = 'yes'; $row_class = 'success'; } else { $ext_loaded = 'no'; $row_class = 'danger'; $complete = 0; } echo(" <tr class='$row_class'> <td>$extension</td> <td>$ext_loaded</td>"); if ($ext_loaded == 'no') { echo("<td></td>"); } else { echo("<td></td>"); } echo("</tr>"); } // Check for pear install @include_once 'System.php'; if (class_exists('System') === true) { $ext_loaded = 'yes'; $row_class = 'success'; } else { $ext_loaded = 'no'; $row_class = 'danger'; } echo(" <tr class='$row_class'> <td>pear</td> <td>$ext_loaded</td>"); if ($ext_loaded == 'no') { echo("<td>apt-get install php-pear / yum install php-pear</td>"); } else { echo("<td></td>"); } echo("</tr>"); ?> </table> </div> <div class="col-md-3"> </div> </div> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <form class="form-inline" role="form" method="post"> <input type="hidden" name="stage" value="1"> <button type="submit" class="btn btn-success" <?php if ($complete == '0') { echo "disabled='disabled'"; } ?>>Next Stage</button> </form> </div> <div class="col-md-3"> </div> </div> <?php } elseif ($stage == 1) { ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <form class="form-horizontal" role="form" method="post"> <input type="hidden" name="stage" value="2"> <div class="form-group"> <label for="dbhost" class="col-sm-4" control-label">DB Host: </label> <div class="col-sm-8"> <input type="text" class="form-control" name="dbhost" id="dbhost" value="<?php echo $dbhost; ?>" placeholder="Leave empty if using Unix-Socket"> </div> </div> <div class="form-group"> <label for="dbport" class="col-sm-4" control-label">DB Port: </label> <div class="col-sm-8"> <input type="text" class="form-control" name="dbport" id="dbport" value="<?php echo $dbport; ?>" placeholder="Leave empty if using Unix-Socket"> </div> </div> <div class="form-group"> <label for="dbsocket" class="col-sm-4" control-label">DB Unix-Socket: </label> <div class="col-sm-8"> <input type="text" class="form-control" name="dbsocket" id="dbsocket" value="<?php echo $dbsocket; ?>" placeholder="Leave empty if using Host"> </div> </div> <div class="form-group"> <label for="dbuser" class="col-sm-4" control-label">DB User: </label> <div class="col-sm-8"> <input type="text" class="form-control" name="dbuser" id="dbuser" value="<?php echo $dbuser; ?>"> </div> </div> <div class="form-group"> <label for="dbpass" class="col-sm-4" control-label">DB Pass: </label> <div class="col-sm-8"> <input type="password" class="form-control" name="dbpass" id="dbpass" value="<?php echo $dbpass; ?>"> </div> </div> <div class="form-group"> <label for="dbname" class="col-sm-4" control-label">DB Name: </label> <div class="col-sm-8"> <input type="text" class="form-control" name="dbname" id="dbname" value="<?php echo $dbname; ?>"> </div> </div> <button type="submit" class="btn btn-success">Next Stage</button> </form> </div> <div class="col-md-3"> </div> </div> <?php } elseif ($stage == "2") { ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <h5 class="text-center">Importing MySQL DB - Do not close this page or interrupt the import</h5> <?php // Ok now let's set the db connection up $config['db_host'] = $dbhost; $config['db_user'] = $dbuser; $config['db_pass'] = $dbpass; $config['db_name'] = $dbname; $config['db_port'] = $dbport; $config['db_socket'] = $dbsocket; $sql_file = '../build.sql'; $_SESSION['last'] = time(); ob_end_flush(); ob_start(); if ($_SESSION['offset'] < 100 && $_REQUEST['offset'] < 94) { require '../build-base.php'; } else { require '../includes/sql-schema/update.php'; } $_SESSION['out'] .= ob_get_clean(); ob_end_clean(); ob_start(); echo $GLOBALS['refresh']; echo "<pre>".trim($_SESSION['out'])."</pre>"; ?> </div> <div class="col-md-3"> </div> </div> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> If you don't see any errors or messages above then the database setup has been successful.<br /> <form class="form-horizontal" role="form" method="post"> <input type="hidden" name="stage" value="3"> <input type="hidden" name="dbhost" value="<?php echo $dbhost; ?>"> <input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>"> <input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>"> <input type="hidden" name="dbname" value="<?php echo $dbname; ?>"> <input type="hidden" name="dbport" value="<?php echo $dbport; ?>"> <input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>"> <button type="submit" class="btn btn-success">Goto Add User</button> </form> </div> <div class="col-md-3"> </div> </div> <?php } elseif ($stage == "5") { ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <?php // Create the config file we will write or display $config_file = <<<"EOD" ## Have a look in defaults.inc.php for examples of settings you can set here. DO NOT EDIT defaults.inc.php! ### Database config \$config\['db_host'\] = '$dbhost'; \$config\['db_port'\] = '$dbport'; \$config\['db_user'\] = '$dbuser'; \$config\['db_pass'\] = '$dbpass'; \$config\['db_name'\] = '$dbname'; \$config\['db_socket'\] = '$dbsocket'; \$config\['db'\]\['extension'\] = "mysqli";// mysql or mysqli // This is the user LibreNMS will run as //Please ensure this user is created and has the correct permissions to your install \$config['user'] = 'librenms'; ### Memcached config - We use this to store realtime usage \$config\['memcached'\]\['enable'\] = FALSE; \$config\['memcached'\]\['host'\] = "localhost"; \$config\['memcached'\]\['port'\] = 11211; ### Locations - it is recommended to keep the default \$config\['install_dir'\] = "$install_dir"; ### This should *only* be set if you want to *force* a particular hostname/port ### It will prevent the web interface being usable form any other hostname #\$config\['base_url'\] = "http://librenms.company.com"; ### Enable this to use rrdcached. Be sure rrd_dir is within the rrdcached dir ### and that your web server has permission to talk to rrdcached. #\$config\['rrdcached'\] = "unix:/var/run/rrdcached.sock"; ### Default community \$config\['snmp'\]\['community'\] = array("public"); ### Authentication Model \$config\['auth_mechanism'\] = "mysql"; # default, other options: ldap, http-auth #\$config\['http_auth_guest'\] = "guest"; # remember to configure this user if you use http-auth ### List of RFC1918 networks to allow scanning-based discovery #\$config\['nets'\]\[\] = "10.0.0.0/8"; #\$config\['nets'\]\[\] = "172.16.0.0/12"; #\$config\['nets'\]\[\] = "192.168.0.0/16"; # Uncomment the next line to disable daily updates #\$config\['update'\] = 0; EOD; if (!file_exists("../config.php")) { $conf = fopen("../config.php", 'w'); if ($conf != false) { if (fwrite($conf, "<?php\n") === false) { echo("<div class='alert alert-danger'>We couldn't create the config.php file, please create this manually before continuing by copying the below into a config.php in the root directory of your install (typically /opt/librenms/)</div>"); echo("<pre>&lt;?php\n".stripslashes($config_file)."</pre>"); } else { $config_file = stripslashes($config_file); fwrite($conf, $config_file); echo("<div class='alert alert-success'>The config file has been created</div>"); } } else { echo("<div class='alert alert-danger'>We couldn't create the config.php file, please create this manually before continuing by copying the below into a config.php in the root directory of your install (typically /opt/librenms/)</div>"); echo("<pre>&lt;?php\n".stripslashes($config_file)."</pre>"); } } ?> <form class="form-horizontal" role="form" method="post"> <input type="hidden" name="stage" value="6"> <input type="hidden" name="dbhost" value="<?php echo $dbhost; ?>"> <input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>"> <input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>"> <input type="hidden" name="dbname" value="<?php echo $dbname; ?>"> <input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>"> <button type="submit" class="btn btn-success">Finish install</button> </form> <?php ?> </div> <div class="col-md-3"> </div> </div> <?php } elseif ($stage == "3") { ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <form class="form-horizontal" role="form" method="post"> <input type="hidden" name="stage" value="4"> <input type="hidden" name="dbhost" value="<?php echo $dbhost; ?>"> <input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>"> <input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>"> <input type="hidden" name="dbname" value="<?php echo $dbname; ?>"> <input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>"> <div class="form-group"> <label for="add_user" class="col-sm-4 control-label">Username</label> <div class="col-sm-8"> <input type="text" class="form-control" name="add_user" id="add_user" value="<?php echo $add_user; ?>"> </div> </div> <div class="form-group"> <label for="add_pass" class="col-sm-4 control-label">Password</label> <div class="col-sm-8"> <input type="password" class="form-control" name="add_pass" id="add_pass" value="<?php echo $add_pass; ?>"> </div> </div> <div class="form-group"> <label for="add_email" class="col-sm-4 control-label">Email</label> <div class="col-sm-8"> <input type="email" class="form-control" name="add_email" id="add_email" value="<?php echo $add_email; ?>"> </div> </div> <button type="submit" class="btn btn-success">Add User</button> </form> </div> <div class="col-md-3"> </div> </div> <?php } elseif ($stage == "4") { $proceed = 1; ?> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <?php if (auth_usermanagement()) { if (!user_exists($add_user)) { if (adduser($add_user, $add_pass, '10', $add_email)) { echo("<div class='alert alert-success'>User has been added successfully</div>"); $proceed = 0; } else { echo("<div class='alert alert-danger'>User hasn't been added, please try again</div>"); } } else { echo("<div class='alert alert-danger'>User $add_user already exists!</div>"); } } else { echo("<div class='alert alert-danger'>Auth module isn't loaded</div>"); } ?> <form class="form-horizontal" role="form" method="post"> <input type="hidden" name="stage" value="5"> <input type="hidden" name="dbhost" value="<?php echo $dbhost; ?>"> <input type="hidden" name="dbuser" value="<?php echo $dbuser; ?>"> <input type="hidden" name="dbpass" value="<?php echo $dbpass; ?>"> <input type="hidden" name="dbname" value="<?php echo $dbname; ?>"> <input type="hidden" name="dbsocket" value="<?php echo $dbsocket; ?>"> <button type="submit" class="btn btn-success" <?php if ($proceed == "1") { echo "disabled='disabled'"; } ?>>Generate Config</button> </form> </div> <div class="col-md-3"> </div> </div> <?php } elseif ($stage == "6") { ?> <div class="row"> <div class="col-md-offset-3 col-md-6"> <div class="alert alert-danger">You haven't quite finished yet - please go back to the install docs and carry on the necessary steps to finish the setup!</div> </div> </div> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="alert alert-success">Thank you for setting up LibreNMS.<br /> It would be great if you would consider contributing to our statistics, you can do this on the <a href="about/">/about/</a> page and check the box under Statistics.<br /> You can now click <a href="/">here to login to your new install.</a></div> </div> <div class="col-md-3"> </div> <?php } ?> </div> </body> </html>
worton/librenms
html/install.php
PHP
gpl-3.0
18,848
#!/usr/bin/python # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: aci_firmware_group_node short_description: This modules adds and remove nodes from the firmware group version_added: "2.8" description: - This module addes/deletes a node to the firmware group. This modules assigns 1 node at a time. options: group: description: - This is the name of the firmware group type: str required: true node: description: - The node to be added to the firmware group - the value equals the NodeID type: str required: true state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. type: str default: present choices: [ absent, present, query ] name_alias: version_added: '2.10' description: - The alias for the current object. This relates to the nameAlias field in ACI. type: str extends_documentation_fragment: - aci author: - Steven Gerhart (@sgerhart) ''' EXAMPLES = ''' - name: add firmware group node aci_firmware_group_node: host: "{{ inventory_hostname }}" username: "{{ user }}" password: "{{ pass }}" validate_certs: no group: testingfwgrp node: 1001 state: present - name: Remove firmware group node aci_firmware_group_node: host: "{{ inventory_hostname }}" username: "{{ user }}" password: "{{ pass }}" validate_certs: no group: testingfwgrp node: 1001 state: absent ''' RETURN = ''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: str sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: str sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: str sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: str sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: str sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' import json from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update( group=dict(type='str', aliases=['group']), # Not required for querying all objects node=dict(type='str', aliases=['node']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), name_alias=dict(type='str'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['node', 'group']], ['state', 'present', ['node', 'group']], ], ) state = module.params.get('state') group = module.params.get('group') node = module.params.get('node') name_alias = module.params.get('name_alias') aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='firmwareFwGrp', aci_rn='fabric/fwgrp-{0}'.format(group), target_filter={'name': group}, module_object=group, ), subclass_1=dict( aci_class='fabricNodeBlk', aci_rn='nodeblk-blk{0}-{0}'.format(node), target_filter={'name': node}, module_object=node, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='fabricNodeBlk', class_config=dict( from_=node, to_=node, nameAlias=name_alias, ), ) aci.get_diff(aci_class='fabricNodeBlk') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
roadmapper/ansible
lib/ansible/modules/network/aci/aci_firmware_group_node.py
Python
gpl-3.0
6,497
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Halver -- Involved in Mission 2-3, 3-3, 5-1, 5-2, 8-1 -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- !pos 2 0.1 0.1 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Chateau_dOraguille/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) --print(player:getVar("MissionStatus")); local pNation = player:getNation(); local currentMission = player:getCurrentMission(pNation); local WildcatSandy = player:getVar("WildcatSandy"); local MissionStatus = player:getVar("MissionStatus"); -- Lure of the Wildcat San d'Oria if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,16) == false) then player:startEvent(558); -- Blackmail quest elseif (player:getQuestStatus(SANDORIA, BLACKMAIL) == QUEST_ACCEPTED and player:hasKeyItem(SUSPICIOUS_ENVELOPE)) then player:startEvent(549); player:setVar("BlackMailQuest",1); player:delKeyItem(SUSPICIOUS_ENVELOPE); -- San D'Oria Flag check elseif (player:getVar("Flagsando") == 1) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,181); else player:setVar("Flagsando",0); player:addItem(181); player:messageSpecial(ITEM_OBTAINED,181); end elseif (player:getCurrentMission(TOAU) == CONFESSIONS_OF_ROYALTY and player:hasKeyItem(RAILLEFALS_LETTER)) then player:startEvent(564); elseif (player:getCurrentMission(TOAU) == EASTERLY_WINDS and player:getVar("AhtUrganStatus") == 0) then player:startEvent(565); elseif (pNation == NATION_SANDORIA) then -- Mission San D'Oria 9-2 The Heir to the Light if (player:hasCompletedMission(SANDORIA,THE_HEIR_TO_THE_LIGHT)) then player:startEvent(31); elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 7) then player:startEvent(9); elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 6) then player:startEvent(30); elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus >= 2 and MissionStatus <=5) then player:startEvent(29); -- Mission San d'Oria 8-1 Coming of Age -- elseif (currentMission == COMING_OF_AGE and MissionStatus == 3 and player:hasKeyItem(DROPS_OF_AMNIO)) then player:startEvent(102); elseif (currentMission == COMING_OF_AGE and MissionStatus == 1) then player:startEvent(58); -- Mission San D'Oria 6-1 Leaute's last wishes elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 3) then player:startEvent(22); elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 2) then player:startEvent(24); elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 1) then player:startEvent(23); elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 0) then player:startEvent(25); -- Mission San D'Oria 5-2 The Shadow Lord elseif (player:hasCompletedMission(SANDORIA,THE_SHADOW_LORD) and currentMission == 255) then player:showText(npc,HALVER_OFFSET+500); elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 5) then player:showText(npc,HALVER_OFFSET+471); elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 4 and player:hasKeyItem(SHADOW_FRAGMENT)) then player:startEvent(548); elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 0) then player:startEvent(546); -- Mission San D'Oria 5-1 The Ruins of Fei'Yin elseif (currentMission == THE_RUINS_OF_FEI_YIN and MissionStatus == 12 and player:hasKeyItem(BURNT_SEAL)) then player:startEvent(534); elseif (currentMission == THE_RUINS_OF_FEI_YIN and MissionStatus == 10) then player:showText(npc,HALVER_OFFSET+334); elseif (currentMission == THE_RUINS_OF_FEI_YIN and MissionStatus == 9) then player:startEvent(533); -- Mission San D'Oria 3-3 Appointment to Jeuno elseif (currentMission == APPOINTMENT_TO_JEUNO and MissionStatus == 0) then player:startEvent(508); -- Mission San D'Oria 2-3 Journey Abroad elseif (currentMission == JOURNEY_ABROAD and MissionStatus == 11) then player:startEvent(507); elseif (currentMission == JOURNEY_ABROAD and MissionStatus == 0) then player:startEvent(505); elseif (currentMission == JOURNEY_ABROAD) then player:startEvent(532); end elseif (pNation == NATION_BASTOK) then -- Bastok 2-3 San -> Win if (currentMission == THE_EMISSARY) then if (MissionStatus == 3) then player:startEvent(501); end -- Bastok 2-3 San -> Win, report to consulate elseif (currentMission == THE_EMISSARY_SANDORIA) then player:showText(npc,HALVER_OFFSET+279); -- Bastok 2-3 Win -> San elseif (currentMission == THE_EMISSARY_SANDORIA2) then if (MissionStatus == 8) then player:startEvent(503); elseif (MissionStatus <= 10) then player:showText(npc,HALVER_OFFSET+279); end else player:showText(npc,HALVER_OFFSET+1092); end elseif (pNation == NATION_WINDURST) then -- Windurst 2-3 if (currentMission == THE_THREE_KINGDOMS and MissionStatus < 3) then player:startEvent(532); elseif (currentMission == THE_THREE_KINGDOMS_SANDORIA or currentMission == THE_THREE_KINGDOMS_SANDORIA2) then if (MissionStatus == 3) then player:startEvent(502); elseif (MissionStatus == 8) then player:startEvent(504); else player:showText(npc,HALVER_OFFSET+279); end end else player:showText(npc,HALVER_OFFSET+1092); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 501) then player:addMission(BASTOK,THE_EMISSARY_SANDORIA); player:setVar("MissionStatus",4); elseif (csid == 503) then player:setVar("MissionStatus",9); elseif (csid == 508) then player:setVar("MissionStatus",2); elseif (csid == 505) then player:setVar("MissionStatus",2); player:addKeyItem(LETTER_TO_THE_CONSULS_SANDORIA); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_CONSULS_SANDORIA); elseif (csid == 502) then player:setVar("MissionStatus",4); elseif (csid == 558) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",16,true); elseif (csid == 504) then player:setVar("MissionStatus",9); elseif (csid == 546) then player:setVar("MissionStatus",1); elseif (csid == 507 or csid == 534 or csid == 548) then finishMissionTimeline(player,3,csid,option); elseif (csid == 533) then player:addKeyItem(NEW_FEIYIN_SEAL); player:setVar("MissionStatus",10); player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL); elseif (csid == 25) then player:setVar("MissionStatus",1); elseif (csid == 22) then player:setVar("MissionStatus",4); elseif (csid == 9) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,181); player:setVar("Flagsando",1); else player:addItem(181); player:messageSpecial(ITEM_OBTAINED,181); end player:setVar("MissionStatus",0); player:completeMission(SANDORIA,THE_HEIR_TO_THE_LIGHT); player:setRank(10); player:addGil(100000); player:messageSpecial(GIL_OBTAINED,100000); player:setTitle(295); player:setVar("SandoEpilogue",1); elseif (csid == 58) then player:setVar("MissionStatus",2); elseif (csid == 102) then finishMissionTimeline(player,3,csid,option); player:setVar("Wait1DayM8-1_date", os.date("%j")); elseif (csid == 564 and option == 1) then player:completeMission(TOAU,CONFESSIONS_OF_ROYALTY); player:addMission(TOAU,EASTERLY_WINDS); player:delKeyItem(RAILLEFALS_LETTER); elseif (csid == 565) then player:setVar("AhtUrganStatus", 1); end end;
HeavensSword/darkstar
scripts/zones/Chateau_dOraguille/npcs/Halver.lua
Lua
gpl-3.0
9,311
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* ---------------------------------------------------------------------------- * Easy!Appointments - Open Source Web Scheduler * * @package EasyAppointments * @author A.Tselegidis <alextselegidis@gmail.com> * @copyright Copyright (c) 2013 - 2016, Alex Tselegidis * @license http://opensource.org/licenses/GPL-3.0 - GPLv3 * @link http://easyappointments.org * @since v1.1.0 * ---------------------------------------------------------------------------- */ class Migration_Add_customer_notifications_setting extends CI_Migration { public function up() { $this->load->model('settings_model'); $this->settings_model->set_setting('customer_notifications', '1'); } public function down() { $this->load->model('settings_model'); $this->settings_model->remove_setting('customer_notifications'); } }
sis-direct/easyappointments
src/application/migrations/003_add_customer_notifications_setting.php
PHP
gpl-3.0
950
/* * Yongle Lai @ Rockchip */ #ifndef _WIFI_VERSION_H_ #define _WIFI_VERSION_H_ /* * Broadcom BCM4319 driver version. */ #define RTL8723BU_DRV_VERSION "4.39.WFD" #endif /* WIFI_VERSION_H */
s20121035/rk3288_android5.1_repo
kernel/drivers/net/wireless/rockchip_wlan/rtl8723bu/os_dep/linux/wifi_version.h
C
gpl-3.0
197
/* * Open BEAGLE * Copyright (C) 2001-2007 by Christian Gagne and Marc Parizeau * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact: * Laboratoire de Vision et Systemes Numeriques * Departement de genie electrique et de genie informatique * Universite Laval, Quebec, Canada, G1K 7P4 * http://vision.gel.ulaval.ca * */ /*! * \file Beagle/FltVec/CrossoverSBXOp.cpp * \brief Source code of class FltVec::CrossoverSBXOp. * \author Christian Gagne * \author Marc Parizeau * $Revision: 1.14 $ * $Date: 2007/08/17 18:09:10 $ */ #include "Beagle/FltVec.hpp" #include <cfloat> #include <cmath> #include <float.h> #include <algorithm> #include <string> using namespace Beagle; /*! * \brief Construct simulated binary crossover (SBX) operator. * \param inMatingPbName Mating probability parameter name. * \param inName Name of the operator. */ Beagle::FltVec::CrossoverSBXOp::CrossoverSBXOp(std::string inMatingPbName, std::string inName) : EC::CrossoverOp(inMatingPbName, inName) { } /*! * \brief Register the parameters of the simulated binary crossover (SBX) operator. * \param ioSystem System of the evolution. */ void Beagle::FltVec::CrossoverSBXOp::registerParams(Beagle::System& ioSystem) { Beagle_StackTraceBeginM(); { Register::Description lDescription( "Individual SBX crossover prob.", "Double", "0.3", "Simulated binary crossover (SBX) probability of a single individual." ); mMatingProba = castHandleT<Double>( ioSystem.getRegister().insertEntry(mMatingProbaName, new Double(0.3f), lDescription)); } EC::CrossoverOp::registerParams(ioSystem); { std::ostringstream lOSS; lOSS << "Maximum values assigned to vector's floats. "; lOSS << "Value can be a scalar, which limit the value for all float "; lOSS << "vector parameters, or a vector which limit the value for the parameters "; lOSS << "individually. If the maximum value is smaller than the "; lOSS << "float vector size, the limit used for the last values of the float vector "; lOSS << "is equal to the last value of the maximum value vector."; Register::Description lDescription( "Maximum vector values", "DoubleArray", dbl2str(DBL_MAX), lOSS.str() ); mMaxValue = castHandleT<DoubleArray>( ioSystem.getRegister().insertEntry("fltvec.float.maxvalue", new DoubleArray(1,DBL_MAX), lDescription)); } { std::ostringstream lOSS; lOSS << "Minimum values assigned to vector's floats. "; lOSS << "Value can be a scalar, which limit the value for all float "; lOSS << "vector parameters, or a vector which limit the value for the parameters "; lOSS << "individually. If the minimum value is smaller than the "; lOSS << "float vector size, the limit used for the last values of the float vector "; lOSS << "is equal to the last value of the minimum value vector."; Register::Description lDescription( "Minimum values", "DoubleArray", dbl2str(-DBL_MAX), lOSS.str() ); mMinValue = castHandleT<DoubleArray>( ioSystem.getRegister().insertEntry("fltvec.float.minvalue", new DoubleArray(1,-DBL_MAX), lDescription)); } { Register::Description lDescription( "SBX crossover nu value", "Double", "2.0", "SBX crossover nu parameter moduling crossover." ); mNu = castHandleT<Double>( ioSystem.getRegister().insertEntry("fltvec.cxsbx.nu", new Double(2.0), lDescription)); } Beagle_StackTraceEndM(); } /*! * \brief Mate two individuals for real-valued SBX crossover. * \param ioIndiv1 First individual to mate. * \param ioContext1 Evolutionary context of the first individual. * \param ioIndiv2 Second individual to mate. * \param ioContext2 Evolutionary context of the second individual. * \return True if the individuals are effectively mated, false if not. */ bool Beagle::FltVec::CrossoverSBXOp::mate(Beagle::Individual& ioIndiv1, Beagle::Context& ioContext1, Beagle::Individual& ioIndiv2, Beagle::Context& ioContext2) { Beagle_StackTraceBeginM(); unsigned int lNbGenotypes = minOf<unsigned int>(ioIndiv1.size(), ioIndiv2.size()); if(lNbGenotypes==0) return false; Beagle_LogDebugM( ioContext1.getSystem().getLogger(), ioIndiv1 ); Beagle_LogDebugM( ioContext1.getSystem().getLogger(), ioIndiv2 ); const double lNu=mNu->getWrappedValue(); for(unsigned int i=0; i<lNbGenotypes; ++i) { FltVec::FloatVector::Handle lFloatVector1 = castHandleT<FltVec::FloatVector>(ioIndiv1[i]); FltVec::FloatVector::Handle lFloatVector2 = castHandleT<FltVec::FloatVector>(ioIndiv2[i]); const unsigned int lSize = minOf<unsigned int>(lFloatVector1->size(), lFloatVector2->size()); for(unsigned int j=0; j<lSize; ++j) { const double lMaxVal = j<mMaxValue->size() ? (*mMaxValue)[j] : mMaxValue->back(); const double lMinVal = j<mMinValue->size() ? (*mMinValue)[j] : mMinValue->back(); const double lU_i = ioContext1.getSystem().getRandomizer().rollUniform(); const double lX1_i = (*lFloatVector1)[j]; const double lX2_i = (*lFloatVector2)[j]; double lBeta_i = (lU_i<=0.5) ? (2.0*lU_i) : (1.0/(2.0*(1.0-lU_i))); lBeta_i = std::pow(lBeta_i, 1.0/(lNu+1.0)); (*lFloatVector1)[j] = 0.5 * (((1.0+lBeta_i)*lX1_i) + ((1.0-lBeta_i)*lX2_i)); (*lFloatVector2)[j] = 0.5 * (((1.0-lBeta_i)*lX1_i) + ((1.0+lBeta_i)*lX2_i)); if((*lFloatVector1)[j] > lMaxVal) (*lFloatVector1)[j] = lMaxVal; if((*lFloatVector1)[j] < lMinVal) (*lFloatVector1)[j] = lMinVal; if((*lFloatVector2)[j] > lMaxVal) (*lFloatVector2)[j] = lMaxVal; if((*lFloatVector2)[j] < lMinVal) (*lFloatVector2)[j] = lMinVal; } } Beagle_LogDebugM( ioContext1.getSystem().getLogger(), ioIndiv1 ); Beagle_LogDebugM( ioContext1.getSystem().getLogger(), ioIndiv2 ); return true; Beagle_StackTraceEndM(); }
tectronics/beagle
src/Beagle/FltVec/CrossoverSBXOp.cpp
C++
gpl-3.0
6,621
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreRoot.h" #include "OgreGLPlugin.h" #ifndef OGRE_STATIC_LIB namespace Ogre { static GLPlugin* plugin; extern "C" void _OgreGLExport dllStartPlugin(void) throw() { plugin = new GLPlugin(); Root::getSingleton().installPlugin(plugin); } extern "C" void _OgreGLExport dllStopPlugin(void) { Root::getSingleton().uninstallPlugin(plugin); delete plugin; } } #endif
gorkinovich/DefendersOfMankind
dependencies/Ogre/RenderSystems/GL/src/OgreGLEngineDll.cpp
C++
gpl-3.0
1,774
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Contains class core_tag_external * * @package core_tag * @copyright 2015 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once("$CFG->libdir/externallib.php"); require_once("$CFG->dirroot/webservice/externallib.php"); /** * Tags-related web services * * @package core_tag * @copyright 2015 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class core_tag_external extends external_api { /** * Parameters for function update_tags() * * @return external_function_parameters */ public static function update_tags_parameters() { return new external_function_parameters( array( 'tags' => new external_multiple_structure( new external_single_structure( array( 'id' => new external_value(PARAM_INT, 'tag id'), 'rawname' => new external_value(PARAM_RAW, 'tag raw name (may contain capital letters)', VALUE_OPTIONAL), 'description' => new external_value(PARAM_RAW, 'tag description', VALUE_OPTIONAL), 'descriptionformat' => new external_value(PARAM_INT, 'tag description format', VALUE_OPTIONAL), 'flag' => new external_value(PARAM_INT, 'flag', VALUE_OPTIONAL), 'official' => new external_value(PARAM_INT, 'whether this flag is official', VALUE_OPTIONAL), ) ) ) ) ); } /** * Expose to AJAX * * @return boolean */ public static function update_tags_is_allowed_from_ajax() { return true; } /** * Update tags * * @param array $tags */ public static function update_tags($tags) { global $CFG, $PAGE, $DB; require_once($CFG->dirroot.'/tag/lib.php'); // Validate and normalize parameters. $tags = self::validate_parameters(self::update_tags_parameters(), array('tags' => $tags)); $systemcontext = context_system::instance(); $canmanage = has_capability('moodle/tag:manage', $systemcontext); $canedit = has_capability('moodle/tag:edit', $systemcontext); $warnings = array(); if (empty($CFG->usetags)) { throw new moodle_exception('tagsaredisabled', 'tag'); } $renderer = $PAGE->get_renderer('core'); foreach ($tags['tags'] as $tag) { $tag = (array)$tag; if (array_key_exists('rawname', $tag)) { $tag['rawname'] = clean_param($tag['rawname'], PARAM_TAG); if (empty($tag['rawname'])) { unset($tag['rawname']); } else { $tag['name'] = core_text::strtolower($tag['rawname']); } } if (!$canmanage) { // User without manage capability can not change any fields except for descriptions. $tag = array_intersect_key($tag, array('id' => 1, 'description' => 1, 'descriptionformat' => 1)); } if (!$canedit) { // User without edit capability can not change description. $tag = array_diff_key($tag, array('description' => 1, 'descriptionformat' => 1)); } if (count($tag) <= 1) { $warnings[] = array( 'item' => $tag['id'], 'warningcode' => 'nothingtoupdate', 'message' => get_string('nothingtoupdate', 'core_tag') ); continue; } if (!$tagobject = $DB->get_record('tag', array('id' => $tag['id']))) { $warnings[] = array( 'item' => $tag['id'], 'warningcode' => 'tagnotfound', 'message' => get_string('tagnotfound', 'error') ); continue; } // First check if new tag name is allowed. if (!empty($tag['name']) && ($existing = $DB->get_record('tag', array('name' => $tag['name']), 'id'))) { if ($existing->id != $tag['id']) { $warnings[] = array( 'item' => $tag['id'], 'warningcode' => 'namesalreadybeeingused', 'message' => get_string('namesalreadybeeingused', 'core_tag') ); continue; } } if (array_key_exists('official', $tag)) { $tag['tagtype'] = $tag['official'] ? 'official' : 'default'; unset($tag['official']); } $tag['timemodified'] = time(); $DB->update_record('tag', $tag); foreach ($tag as $key => $value) { $tagobject->$key = $value; } $event = \core\event\tag_updated::create(array( 'objectid' => $tagobject->id, 'relateduserid' => $tagobject->userid, 'context' => context_system::instance(), 'other' => array( 'name' => $tagobject->name, 'rawname' => $tagobject->rawname ) )); $event->trigger(); } return array('warnings' => $warnings); } /** * Return structure for update_tag() * * @return external_description */ public static function update_tags_returns() { return new external_single_structure( array( 'warnings' => new external_warnings() ) ); } /** * Parameters for function get_tags() * * @return external_function_parameters */ public static function get_tags_parameters() { return new external_function_parameters( array( 'tags' => new external_multiple_structure( new external_single_structure( array( 'id' => new external_value(PARAM_INT, 'tag id'), ) ) ) ) ); } /** * Expose to AJAX * * @return boolean */ public static function get_tags_is_allowed_from_ajax() { return true; } /** * Get tags by their ids * * @param array $tags */ public static function get_tags($tags) { global $CFG, $PAGE, $DB; require_once($CFG->dirroot.'/tag/lib.php'); // Validate and normalize parameters. $tags = self::validate_parameters(self::get_tags_parameters(), array('tags' => $tags)); require_login(null, false, null, false, true); $systemcontext = context_system::instance(); $canmanage = has_capability('moodle/tag:manage', $systemcontext); $canedit = has_capability('moodle/tag:edit', $systemcontext); $return = array(); $warnings = array(); if (empty($CFG->usetags)) { throw new moodle_exception('tagsaredisabled', 'tag'); } $renderer = $PAGE->get_renderer('core'); foreach ($tags['tags'] as $tag) { $tag = (array)$tag; if (!$tagobject = $DB->get_record('tag', array('id' => $tag['id']))) { $warnings[] = array( 'item' => $tag['id'], 'warningcode' => 'tagnotfound', 'message' => get_string('tagnotfound', 'error') ); continue; } $tagoutput = new \core_tag\output\tag($tagobject); // Do not return some information to users without permissions. $rv = $tagoutput->export_for_template($renderer); if (!$canmanage) { if (!$canedit) { unset($rv->official); } unset($rv->flag); unset($rv->changetypeurl); unset($rv->changeflagurl); } $return[] = $rv; } return array('tags' => $return, 'warnings' => $warnings); } /** * Return structure for get_tag() * * @return external_description */ public static function get_tags_returns() { return new external_single_structure( array( 'tags' => new external_multiple_structure( new external_single_structure( array( 'id' => new external_value(PARAM_INT, 'tag id'), 'name' => new external_value(PARAM_TAG, 'name'), 'rawname' => new external_value(PARAM_RAW, 'tag raw name (may contain capital letters)'), 'description' => new external_value(PARAM_RAW, 'tag description'), 'descriptionformat' => new external_format_value(PARAM_INT, 'tag description format'), 'flag' => new external_value(PARAM_INT, 'flag', VALUE_OPTIONAL), 'official' => new external_value(PARAM_INT, 'whether this flag is official', VALUE_OPTIONAL), 'viewurl' => new external_value(PARAM_URL, 'URL to view'), 'changetypeurl' => new external_value(PARAM_URL, 'URL to change type (official or not)', VALUE_OPTIONAL), 'changeflagurl' => new external_value(PARAM_URL, 'URL to set or reset flag', VALUE_OPTIONAL), ), 'information about one tag') ), 'warnings' => new external_warnings() ) ); } }
southasia/moodle
tag/classes/external.php
PHP
gpl-3.0
10,557
/* Copyright 2001 by Stephen L. Moshier <moshier@na-net.ornl.gov> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> /* Specification. */ #include <math.h> #if HAVE_SAME_LONG_DOUBLE_AS_DOUBLE long double logl (long double x) { return log (x); } #elif HAVE_LOGL long double logl (long double x) # undef logl { /* Work around the OSF/1 5.1 bug. */ if (x == 0.0L) /* Return -Infinity. */ return -1.0L / 0.0L; return logl (x); } #else /* Code based on glibc/sysdeps/ieee754/ldbl-128/e_logl.c. */ /* logll.c * * Natural logarithm for 128-bit long double precision. * * * * SYNOPSIS: * * long double x, y, logl(); * * y = logl( x ); * * * * DESCRIPTION: * * Returns the base e (2.718...) logarithm of x. * * The argument is separated into its exponent and fractional * parts. Use of a lookup table increases the speed of the routine. * The program uses logarithms tabulated at intervals of 1/128 to * cover the domain from approximately 0.7 to 1.4. * * On the interval [-1/128, +1/128] the logarithm of 1+x is approximated by * log(1+x) = x - 0.5 x^2 + x^3 P(x) . * * * * ACCURACY: * * Relative error: * arithmetic domain # trials peak rms * IEEE 0.875, 1.125 100000 1.2e-34 4.1e-35 * IEEE 0.125, 8 100000 1.2e-34 4.1e-35 * * * WARNING: * * This program uses integer operations on bit fields of floating-point * numbers. It does not work with data structures other than the * structure assumed. * */ /* log(1+x) = x - .5 x^2 + x^3 l(x) -.0078125 <= x <= +.0078125 peak relative error 1.2e-37 */ static const long double l3 = 3.333333333333333333333333333333336096926E-1L, l4 = -2.499999999999999999999999999486853077002E-1L, l5 = 1.999999999999999999999999998515277861905E-1L, l6 = -1.666666666666666666666798448356171665678E-1L, l7 = 1.428571428571428571428808945895490721564E-1L, l8 = -1.249999999999999987884655626377588149000E-1L, l9 = 1.111111111111111093947834982832456459186E-1L, l10 = -1.000000000000532974938900317952530453248E-1L, l11 = 9.090909090915566247008015301349979892689E-2L, l12 = -8.333333211818065121250921925397567745734E-2L, l13 = 7.692307559897661630807048686258659316091E-2L, l14 = -7.144242754190814657241902218399056829264E-2L, l15 = 6.668057591071739754844678883223432347481E-2L; /* Lookup table of ln(t) - (t-1) t = 0.5 + (k+26)/128) k = 0, ..., 91 */ static const long double logtbl[92] = { -5.5345593589352099112142921677820359632418E-2L, -5.2108257402767124761784665198737642086148E-2L, -4.8991686870576856279407775480686721935120E-2L, -4.5993270766361228596215288742353061431071E-2L, -4.3110481649613269682442058976885699556950E-2L, -4.0340872319076331310838085093194799765520E-2L, -3.7682072451780927439219005993827431503510E-2L, -3.5131785416234343803903228503274262719586E-2L, -3.2687785249045246292687241862699949178831E-2L, -3.0347913785027239068190798397055267411813E-2L, -2.8110077931525797884641940838507561326298E-2L, -2.5972247078357715036426583294246819637618E-2L, -2.3932450635346084858612873953407168217307E-2L, -2.1988775689981395152022535153795155900240E-2L, -2.0139364778244501615441044267387667496733E-2L, -1.8382413762093794819267536615342902718324E-2L, -1.6716169807550022358923589720001638093023E-2L, -1.5138929457710992616226033183958974965355E-2L, -1.3649036795397472900424896523305726435029E-2L, -1.2244881690473465543308397998034325468152E-2L, -1.0924898127200937840689817557742469105693E-2L, -9.6875626072830301572839422532631079809328E-3L, -8.5313926245226231463436209313499745894157E-3L, -7.4549452072765973384933565912143044991706E-3L, -6.4568155251217050991200599386801665681310E-3L, -5.5356355563671005131126851708522185605193E-3L, -4.6900728132525199028885749289712348829878E-3L, -3.9188291218610470766469347968659624282519E-3L, -3.2206394539524058873423550293617843896540E-3L, -2.5942708080877805657374888909297113032132E-3L, -2.0385211375711716729239156839929281289086E-3L, -1.5522183228760777967376942769773768850872E-3L, -1.1342191863606077520036253234446621373191E-3L, -7.8340854719967065861624024730268350459991E-4L, -4.9869831458030115699628274852562992756174E-4L, -2.7902661731604211834685052867305795169688E-4L, -1.2335696813916860754951146082826952093496E-4L, -3.0677461025892873184042490943581654591817E-5L, # define ZERO logtbl[38] 0.0000000000000000000000000000000000000000E0L, -3.0359557945051052537099938863236321874198E-5L, -1.2081346403474584914595395755316412213151E-4L, -2.7044071846562177120083903771008342059094E-4L, -4.7834133324631162897179240322783590830326E-4L, -7.4363569786340080624467487620270965403695E-4L, -1.0654639687057968333207323853366578860679E-3L, -1.4429854811877171341298062134712230604279E-3L, -1.8753781835651574193938679595797367137975E-3L, -2.3618380914922506054347222273705859653658E-3L, -2.9015787624124743013946600163375853631299E-3L, -3.4938307889254087318399313316921940859043E-3L, -4.1378413103128673800485306215154712148146E-3L, -4.8328735414488877044289435125365629849599E-3L, -5.5782063183564351739381962360253116934243E-3L, -6.3731336597098858051938306767880719015261E-3L, -7.2169643436165454612058905294782949315193E-3L, -8.1090214990427641365934846191367315083867E-3L, -9.0486422112807274112838713105168375482480E-3L, -1.0035177140880864314674126398350812606841E-2L, -1.1067990155502102718064936259435676477423E-2L, -1.2146457974158024928196575103115488672416E-2L, -1.3269969823361415906628825374158424754308E-2L, -1.4437927104692837124388550722759686270765E-2L, -1.5649743073340777659901053944852735064621E-2L, -1.6904842527181702880599758489058031645317E-2L, -1.8202661505988007336096407340750378994209E-2L, -1.9542647000370545390701192438691126552961E-2L, -2.0924256670080119637427928803038530924742E-2L, -2.2346958571309108496179613803760727786257E-2L, -2.3810230892650362330447187267648486279460E-2L, -2.5313561699385640380910474255652501521033E-2L, -2.6856448685790244233704909690165496625399E-2L, -2.8438398935154170008519274953860128449036E-2L, -3.0058928687233090922411781058956589863039E-2L, -3.1717563112854831855692484086486099896614E-2L, -3.3413836095418743219397234253475252001090E-2L, -3.5147290019036555862676702093393332533702E-2L, -3.6917475563073933027920505457688955423688E-2L, -3.8723951502862058660874073462456610731178E-2L, -4.0566284516358241168330505467000838017425E-2L, -4.2444048996543693813649967076598766917965E-2L, -4.4356826869355401653098777649745233339196E-2L, -4.6304207416957323121106944474331029996141E-2L, -4.8285787106164123613318093945035804818364E-2L, -5.0301169421838218987124461766244507342648E-2L, -5.2349964705088137924875459464622098310997E-2L, -5.4431789996103111613753440311680967840214E-2L, -5.6546268881465384189752786409400404404794E-2L, -5.8693031345788023909329239565012647817664E-2L, -6.0871713627532018185577188079210189048340E-2L, -6.3081958078862169742820420185833800925568E-2L, -6.5323413029406789694910800219643791556918E-2L, -6.7595732653791419081537811574227049288168E-2L }; /* ln(2) = ln2a + ln2b with extended precision. */ static const long double ln2a = 6.93145751953125e-1L, ln2b = 1.4286068203094172321214581765680755001344E-6L; long double logl (long double x) { long double z, y, w; long double t; int k, e; /* Check for IEEE special cases. */ /* log(NaN) = NaN. */ if (isnanl (x)) { return x; } /* log(0) = -infinity. */ if (x == 0.0L) { return -0.5L / ZERO; } /* log ( x < 0 ) = NaN */ if (x < 0.0L) { return (x - x) / ZERO; } /* log (infinity) */ if (x + x == x) { return x + x; } /* Extract exponent and reduce domain to 0.703125 <= u < 1.40625 */ x = frexpl (x, &e); if (x < 0.703125L) { x += x; e--; } /* On this interval the table is not used due to cancellation error. */ if ((x <= 1.0078125L) && (x >= 0.9921875L)) { z = x - 1.0L; k = 64; t = 1.0L; } else { k = floorl ((x - 0.5L) * 128.0L); t = 0.5L + k / 128.0L; z = (x - t) / t; } /* Series expansion of log(1+z). */ w = z * z; y = ((((((((((((l15 * z + l14) * z + l13) * z + l12) * z + l11) * z + l10) * z + l9) * z + l8) * z + l7) * z + l6) * z + l5) * z + l4) * z + l3) * z * w; y -= 0.5 * w; y += e * ln2b; /* Base 2 exponent offset times ln(2). */ y += z; y += logtbl[k-26]; /* log(t) - (t-1) */ y += (t - 1.0L); y += e * ln2a; return y; } #endif
Distrotech/radius
gnulib/lib/logl.c
C
gpl-3.0
9,300
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>cuon.DMS.documentTools</title> <link rel="stylesheet" href="epydoc.css" type="text/css"></link> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- =========== START OF NAVBAR =========== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="center"> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="cuon-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="trees.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="indices.html">Index</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <font size="-1"><b class="breadcrumbs"> <a href="cuon-module.html">Package&nbsp;cuon</a> :: <a href="cuon.DMS-module.html">Package&nbsp;DMS</a> :: Module&nbsp;documentTools </b></font></br> </td> <td><table cellpadding="0" cellspacing="0"> <tr><td align="right"><font size="-2">[<a href="../private/cuon.DMS.documentTools-module.html">show&nbsp;private</a>&nbsp;|&nbsp;hide&nbsp;private]</font></td></tr> <tr><td align="right"><font size="-2">[<a href="frames.html"target="_top">frames</a>&nbsp;|&nbsp;<a href="cuon.DMS.documentTools-module.html" target="_top">no&nbsp;frames</a>]</font></td></tr> </table></td> </tr></table> <!-- =========== START OF MODULE DESCRIPTION =========== --> <h2 class="module">Module cuon.DMS.documentTools</h2> <!-- =========== START OF CLASSES =========== --> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="summary"> <th colspan="2">Classes</th></tr> <tr><td width="15%"> <b><a href="cuon.DMS.documentTools.documentTools-class.html"><code>documentTools</code></a></b></td> <td>&nbsp;</td></tr> </table><br /> <!-- =========== START OF NAVBAR =========== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="center"> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="cuon-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="trees.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="indices.html">Index</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left"><font size="-2">Generated by Epydoc 2.1 on Sat Jul 7 09:54:34 2007</font></td> <td align="right"><a href="http://epydoc.sourceforge.net" ><font size="-2">http://epydoc.sf.net</font></a></td> </tr> </table> </body> </html>
juergenhamel/cuon
www/api/public/cuon.DMS.documentTools-module.html
HTML
gpl-3.0
3,399
/************************************************************ * AP_mount -- library to control a 2 or 3 axis mount. * * * * Author: Joe Holdsworth; * * Ritchie Wilson; * * Amilcar Lucas; * * Gregory Fletcher; * * heavily modified by Randy Mackay * * * * Purpose: Move a 2 or 3 axis mount attached to vehicle, * * Used for mount to track targets or stabilise * * camera plus other modes. * * * * Usage: Use in main code to control mounts attached to * * vehicle. * * * * Comments: All angles in degrees * 100, distances in meters* * unless otherwise stated. * ************************************************************/ #pragma once #include <AP_Math/AP_Math.h> #include <AP_Common/AP_Common.h> #include <AP_Common/Location.h> #include <GCS_MAVLink/GCS_MAVLink.h> // maximum number of mounts #define AP_MOUNT_MAX_INSTANCES 1 // declare backend classes class AP_Mount_Backend; class AP_Mount_Servo; class AP_Mount_SoloGimbal; class AP_Mount_Alexmos; class AP_Mount_SToRM32; class AP_Mount_SToRM32_serial; /* This is a workaround to allow the MAVLink backend access to the SmallEKF. It would be nice to find a neater solution to this */ class AP_Mount { // declare backends as friends friend class AP_Mount_Backend; friend class AP_Mount_Servo; friend class AP_Mount_SoloGimbal; friend class AP_Mount_Alexmos; friend class AP_Mount_SToRM32; friend class AP_Mount_SToRM32_serial; public: AP_Mount(const struct Location &current_loc); /* Do not allow copies */ AP_Mount(const AP_Mount &other) = delete; AP_Mount &operator=(const AP_Mount&) = delete; // get singleton instance static AP_Mount *get_singleton() { return _singleton; } // Enums enum MountType { Mount_Type_None = 0, /// no mount Mount_Type_Servo = 1, /// servo controlled mount Mount_Type_SoloGimbal = 2, /// Solo's gimbal Mount_Type_Alexmos = 3, /// Alexmos mount Mount_Type_SToRM32 = 4, /// SToRM32 mount using MAVLink protocol Mount_Type_SToRM32_serial = 5 /// SToRM32 mount using custom serial protocol }; // init - detect and initialise all mounts void init(); // update - give mount opportunity to update servos. should be called at 10hz or higher void update(); // used for gimbals that need to read INS data at full rate void update_fast(); // get_mount_type - returns the type of mount AP_Mount::MountType get_mount_type() const { return get_mount_type(_primary); } AP_Mount::MountType get_mount_type(uint8_t instance) const; // has_pan_control - returns true if the mount has yaw control (required for copters) bool has_pan_control() const { return has_pan_control(_primary); } bool has_pan_control(uint8_t instance) const; // get_mode - returns current mode of mount (i.e. Retracted, Neutral, RC_Targeting, GPS Point) enum MAV_MOUNT_MODE get_mode() const { return get_mode(_primary); } enum MAV_MOUNT_MODE get_mode(uint8_t instance) const; // set_mode - sets mount's mode // returns true if mode is successfully set void set_mode(enum MAV_MOUNT_MODE mode) { return set_mode(_primary, mode); } void set_mode(uint8_t instance, enum MAV_MOUNT_MODE mode); // set_mode_to_default - restores the mode to it's default mode held in the MNT_DEFLT_MODE parameter // this operation requires 60us on a Pixhawk/PX4 void set_mode_to_default() { set_mode_to_default(_primary); } void set_mode_to_default(uint8_t instance); // set_angle_targets - sets angle targets in degrees void set_angle_targets(float roll, float tilt, float pan) { set_angle_targets(_primary, roll, tilt, pan); } void set_angle_targets(uint8_t instance, float roll, float tilt, float pan); // set_roi_target - sets target location that mount should attempt to point towards void set_roi_target(const struct Location &target_loc) { set_roi_target(_primary,target_loc); } void set_roi_target(uint8_t instance, const struct Location &target_loc); // mavlink message handling: MAV_RESULT handle_command_long(const mavlink_command_long_t &packet); void handle_param_value(const mavlink_message_t &msg); void handle_message(mavlink_channel_t chan, const mavlink_message_t &msg); // send a GIMBAL_REPORT message to GCS void send_gimbal_report(mavlink_channel_t chan); // send a MOUNT_STATUS message to GCS: void send_mount_status(mavlink_channel_t chan); // parameter var table static const struct AP_Param::GroupInfo var_info[]; protected: static AP_Mount *_singleton; // private members const struct Location &_current_loc; // reference to the vehicle's current location // frontend parameters AP_Int8 _joystick_speed; // joystick gain // front end members uint8_t _num_instances; // number of mounts instantiated uint8_t _primary; // primary mount AP_Mount_Backend *_backends[AP_MOUNT_MAX_INSTANCES]; // pointers to instantiated mounts // backend state including parameters struct mount_state { // Parameters AP_Int8 _type; // mount type (None, Servo or MAVLink, see MountType enum) AP_Int8 _default_mode; // default mode on startup and when control is returned from autopilot AP_Int8 _stab_roll; // 1 = mount should stabilize earth-frame roll axis, 0 = no stabilization AP_Int8 _stab_tilt; // 1 = mount should stabilize earth-frame pitch axis AP_Int8 _stab_pan; // 1 = mount should stabilize earth-frame yaw axis // RC input channels from receiver used for direct angular input from pilot AP_Int8 _roll_rc_in; // pilot provides roll input on this channel AP_Int8 _tilt_rc_in; // pilot provides tilt input on this channel AP_Int8 _pan_rc_in; // pilot provides pan input on this channel // Mount's physical limits AP_Int16 _roll_angle_min; // min roll in 0.01 degree units AP_Int16 _roll_angle_max; // max roll in 0.01 degree units AP_Int16 _tilt_angle_min; // min tilt in 0.01 degree units AP_Int16 _tilt_angle_max; // max tilt in 0.01 degree units AP_Int16 _pan_angle_min; // min pan in 0.01 degree units AP_Int16 _pan_angle_max; // max pan in 0.01 degree units AP_Vector3f _retract_angles; // retracted position for mount, vector.x = roll vector.y = tilt, vector.z=pan AP_Vector3f _neutral_angles; // neutral position for mount, vector.x = roll vector.y = tilt, vector.z=pan AP_Float _roll_stb_lead; // roll lead control gain AP_Float _pitch_stb_lead; // pitch lead control gain MAV_MOUNT_MODE _mode; // current mode (see MAV_MOUNT_MODE enum) struct Location _roi_target; // roi target location } state[AP_MOUNT_MAX_INSTANCES]; private: void handle_gimbal_report(mavlink_channel_t chan, const mavlink_message_t &msg); void handle_mount_configure(const mavlink_message_t &msg); void handle_mount_control(const mavlink_message_t &msg); MAV_RESULT handle_command_do_mount_configure(const mavlink_command_long_t &packet); MAV_RESULT handle_command_do_mount_control(const mavlink_command_long_t &packet); }; namespace AP { AP_Mount *mount(); };
matternet/ardupilot
libraries/AP_Mount/AP_Mount.h
C
gpl-3.0
7,780
/******************************************************************************* OpenAirInterface Copyright(c) 1999 - 2014 Eurecom OpenAirInterface 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. OpenAirInterface 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 OpenAirInterface.The full GNU General Public License is included in this distribution in the file called "COPYING". If not, see <http://www.gnu.org/licenses/>. Contact Information OpenAirInterface Admin: openair_admin@eurecom.fr OpenAirInterface Tech : openair_tech@eurecom.fr OpenAirInterface Dev : openair4g-devel@eurecom.fr Address : Eurecom, Campus SophiaTech, 450 Route des Chappes, CS 50193 - 06904 Biot Sophia Antipolis cedex, FRANCE *******************************************************************************/ #include <stdlib.h> #include <stdint.h> #define MME_TEST_S1_MAX_BUF_LENGTH (1024) #define MME_TEST_S1_MAX_BYTES_TEST (32) typedef enum entity_s{ MME, ENB } entity_t; typedef struct s1ap_message_test_s{ char *procedure_name; uint8_t buffer[MME_TEST_S1_MAX_BUF_LENGTH]; uint16_t dont_check[MME_TEST_S1_MAX_BYTES_TEST]; // bytes index test that can be omitted uint32_t buf_len; entity_t originating; uint16_t sctp_stream_id; uint32_t assoc_id; } s1ap_message_test_t; void fail (const char *format, ...); void success (const char *format, ...); void escapeprint (const char *str, size_t len); void hexprint (const void *_str, size_t len); void binprint (const void *_str, size_t len); int compare_buffer(const uint8_t *buffer, const uint32_t length_buffer, const uint8_t *pattern, const uint32_t length_pattern); unsigned decode_hex_length(const char *h); int decode_hex(uint8_t *dst, const char *h); uint8_t *decode_hex_dup(const char *hex);
massar5289/openairinterface5G
openair-cn/TEST/oaisim_mme_test_s1c_scenario.h
C
gpl-3.0
2,291
// // Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef COMPILER_OUTPUTHLSL_H_ #define COMPILER_OUTPUTHLSL_H_ #include <list> #include <set> #include "compiler/intermediate.h" #include "compiler/ParseHelper.h" namespace sh { class UnfoldSelect; class OutputHLSL : public TIntermTraverser { public: explicit OutputHLSL(TParseContext &context); ~OutputHLSL(); void output(); TInfoSinkBase &getBodyStream(); TString typeString(const TType &type); static TString qualifierString(TQualifier qualifier); static TString arrayString(const TType &type); static TString initializer(const TType &type); static TString decorate(const TString &string); // Prepends an underscore to avoid naming clashes static TString decorateUniform(const TString &string, const TType &type); protected: void header(); // Visit AST nodes and output their code to the body stream void visitSymbol(TIntermSymbol*); void visitConstantUnion(TIntermConstantUnion*); bool visitBinary(Visit visit, TIntermBinary*); bool visitUnary(Visit visit, TIntermUnary*); bool visitSelection(Visit visit, TIntermSelection*); bool visitAggregate(Visit visit, TIntermAggregate*); bool visitLoop(Visit visit, TIntermLoop*); bool visitBranch(Visit visit, TIntermBranch*); bool isSingleStatement(TIntermNode *node); bool handleExcessiveLoop(TIntermLoop *node); void outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString); void outputLineDirective(int line); TString argumentString(const TIntermSymbol *symbol); int vectorSize(const TType &type) const; void addConstructor(const TType &type, const TString &name, const TIntermSequence *parameters); const ConstantUnion *writeConstantUnion(const TType &type, const ConstantUnion *constUnion); TString scopeString(unsigned int depthLimit); TString scopedStruct(const TString &typeName); TString structLookup(const TString &typeName); TParseContext &mContext; UnfoldSelect *mUnfoldSelect; bool mInsideFunction; // Output streams TInfoSinkBase mHeader; TInfoSinkBase mBody; TInfoSinkBase mFooter; std::set<std::string> mReferencedUniforms; std::set<std::string> mReferencedAttributes; std::set<std::string> mReferencedVaryings; // Parameters determining what goes in the header output bool mUsesTexture2D; bool mUsesTexture2D_bias; bool mUsesTexture2DLod; bool mUsesTexture2DProj; bool mUsesTexture2DProj_bias; bool mUsesTexture2DProjLod; bool mUsesTextureCube; bool mUsesTextureCube_bias; bool mUsesTextureCubeLod; bool mUsesDepthRange; bool mUsesFragCoord; bool mUsesPointCoord; bool mUsesFrontFacing; bool mUsesPointSize; bool mUsesXor; bool mUsesMod1; bool mUsesMod2v; bool mUsesMod2f; bool mUsesMod3v; bool mUsesMod3f; bool mUsesMod4v; bool mUsesMod4f; bool mUsesFaceforward1; bool mUsesFaceforward2; bool mUsesFaceforward3; bool mUsesFaceforward4; bool mUsesEqualMat2; bool mUsesEqualMat3; bool mUsesEqualMat4; bool mUsesEqualVec2; bool mUsesEqualVec3; bool mUsesEqualVec4; bool mUsesEqualIVec2; bool mUsesEqualIVec3; bool mUsesEqualIVec4; bool mUsesEqualBVec2; bool mUsesEqualBVec3; bool mUsesEqualBVec4; bool mUsesAtan2_1; bool mUsesAtan2_2; bool mUsesAtan2_3; bool mUsesAtan2_4; typedef std::set<TString> Constructors; Constructors mConstructors; typedef std::set<TString> StructNames; StructNames mStructNames; typedef std::list<TString> StructDeclarations; StructDeclarations mStructDeclarations; typedef std::vector<int> ScopeBracket; ScopeBracket mScopeBracket; unsigned int mScopeDepth; int mUniqueIndex; // For creating unique names }; } #endif // COMPILER_OUTPUTHLSL_H_
danialbehzadi/Nokia-RM-1013-2.0.0.11
webkit/Source/ThirdParty/ANGLE/src/compiler/OutputHLSL.h
C
gpl-3.0
4,093
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #ifndef __IMALSE_H__ #define __IMALSE_H__ #include <stdint.h> // #include "src/network/buffer.h" #include "ns3/header.h" #include "ns3/buffer.h" namespace ns3 { /* ... */ class ImalseHeader : public Header { public: void SetData (std::string data); std::string GetData (void); static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); virtual void Print (std::ostream &os) const; // private: std::string m_data; }; } #endif /* __IMALSE_H__ */
JBonsink/GSOC-2013
tools/ns3-module/imalse/model/imalse.h
C
gpl-3.0
777
<?php (defined('BASEPATH')) OR exit('No direct script access allowed'); class Dashboard_Settings extends Admin_Controller { function display() { if (!$_POST and $this->mdl_mcb_data->setting('dashboard_total_paid_cutoff_date')) { $this->mdl_mcb_data->set_setting('dashboard_total_paid_cutoff_date', format_date($this->mdl_mcb_data->setting('dashboard_total_paid_cutoff_date'))); } $this->load->view('settings'); } function save() { /* * As per the config file, this function will * execute when the core system settings are saved. */ if ($this->input->post('dashboard_show_open_invoices')) { $this->mdl_mcb_data->save('dashboard_show_open_invoices', 'TRUE'); } else { $this->mdl_mcb_data->save('dashboard_show_open_invoices', 'FALSE'); } if ($this->input->post('dashboard_show_closed_invoices')) { $this->mdl_mcb_data->save('dashboard_show_closed_invoices', 'TRUE'); } else { $this->mdl_mcb_data->save('dashboard_show_closed_invoices', 'FALSE'); } if ($this->input->post('dashboard_show_pending_invoices')) { $this->mdl_mcb_data->save('dashboard_show_pending_invoices', 'TRUE'); } else { $this->mdl_mcb_data->save('dashboard_show_pending_invoices', 'FALSE'); } if ($this->input->post('dashboard_show_overdue_invoices')) { $this->mdl_mcb_data->save('dashboard_show_overdue_invoices', 'TRUE'); } else { $this->mdl_mcb_data->save('dashboard_show_overdue_invoices', 'FALSE'); } if ($this->input->post('dashboard_show_quotes')) { $this->mdl_mcb_data->save('dashboard_show_quotes', 'TRUE'); } else { $this->mdl_mcb_data->save('dashboard_show_quotes', 'FALSE'); } $this->mdl_mcb_data->save('dashboard_override', $this->input->post('dashboard_override')); $this->mdl_mcb_data->save('dashboard_total_paid_cutoff_date', strtotime(standardize_date($this->input->post('dashboard_total_paid_cutoff_date')))); } } ?>
kwott/SimpleQuoteManager
application/modules_core/dashboard/controllers/dashboard_settings.php
PHP
gpl-3.0
1,973
<?php namespace Illuminate\Foundation\Console; use Illuminate\Support\Str; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; class KeyGenerateCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'key:generate'; /** * The console command description. * * @var string */ protected $description = 'Set the application key'; /** * Execute the console command. * * @return void */ public function fire() { $app = $this->laravel; $key = $this->getRandomKey($app['config']['app.cipher']); if ($this->option('show')) { return $this->line('<comment>'.$key.'</comment>'); } $path = $app->environmentPath().'/'.$app->environmentFile(); if (file_exists($path)) { $content = str_replace('APP_KEY='.$app['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)); if (! Str::contains($content, 'APP_KEY')) { $content = sprintf("%s\nAPP_KEY=%s\n", $content, $key); } file_put_contents($path, $content); } $app['config']['app.key'] = $key; $this->info("Application key [$key] set successfully."); } /** * Generate a random key for the application. * * @param string $cipher * @return string */ protected function getRandomKey($cipher) { if ($cipher === 'AES-128-CBC') { return Str::random(16); } return Str::random(32); } /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ['show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'], ]; } }
EnilPajic/CMDB
vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php
PHP
gpl-3.0
1,889
# -*- coding: utf-8 -*- from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo class SockshareCom(DeadHoster): __name__ = "SockshareCom" __type__ = "hoster" __version__ = "0.05" __pattern__ = r'http://(?:www\.)?sockshare\.com/(mobile/)?(file|embed)/(?P<ID>\w+)' __description__ = """Sockshare.com hoster plugin""" __license__ = "GPLv3" __authors__ = [("jeix", "jeix@hasnomail.de"), ("stickell", "l.stickell@yahoo.it"), ("Walter Purcaro", "vuolter@gmail.com")] getInfo = create_getInfo(SockshareCom)
sebdelsol/pyload
module/plugins/hoster/SockshareCom.py
Python
gpl-3.0
613
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2012-2015 - Michael Lelli * * RetroArch 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch 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 RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <alsa/asoundlib.h> #include <rthreads/rthreads.h> #include <queues/fifo_buffer.h> #include "../../driver.h" #include "../../general.h" #define TRY_ALSA(x) if (x < 0) { \ goto error; \ } typedef struct alsa_thread { snd_pcm_t *pcm; bool nonblock; bool is_paused; bool has_float; volatile bool thread_dead; size_t buffer_size; size_t period_size; snd_pcm_uframes_t period_frames; fifo_buffer_t *buffer; sthread_t *worker_thread; slock_t *fifo_lock; scond_t *cond; slock_t *cond_lock; } alsa_thread_t; static void alsa_worker_thread(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; uint8_t *buf = (uint8_t *)calloc(1, alsa->period_size); if (!buf) { RARCH_ERR("failed to allocate audio buffer"); goto end; } while (!alsa->thread_dead) { size_t avail; size_t fifo_size; snd_pcm_sframes_t frames; slock_lock(alsa->fifo_lock); avail = fifo_read_avail(alsa->buffer); fifo_size = min(alsa->period_size, avail); fifo_read(alsa->buffer, buf, fifo_size); scond_signal(alsa->cond); slock_unlock(alsa->fifo_lock); /* If underrun, fill rest with silence. */ memset(buf + fifo_size, 0, alsa->period_size - fifo_size); frames = snd_pcm_writei(alsa->pcm, buf, alsa->period_frames); if (frames == -EPIPE || frames == -EINTR || frames == -ESTRPIPE) { if (snd_pcm_recover(alsa->pcm, frames, 1) < 0) { RARCH_ERR("[ALSA]: (#2) Failed to recover from error (%s)\n", snd_strerror(frames)); break; } continue; } else if (frames < 0) { RARCH_ERR("[ALSA]: Unknown error occured (%s).\n", snd_strerror(frames)); break; } } end: slock_lock(alsa->cond_lock); alsa->thread_dead = true; scond_signal(alsa->cond); slock_unlock(alsa->cond_lock); free(buf); } static bool alsa_thread_use_float(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; return alsa->has_float; } static bool alsathread_find_float_format(snd_pcm_t *pcm, snd_pcm_hw_params_t *params) { if (snd_pcm_hw_params_test_format(pcm, params, SND_PCM_FORMAT_FLOAT) == 0) { RARCH_LOG("ALSA: Using floating point format.\n"); return true; } RARCH_LOG("ALSA: Using signed 16-bit format.\n"); return false; } static void alsa_thread_free(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; if (alsa) { if (alsa->worker_thread) { alsa->thread_dead = true; sthread_join(alsa->worker_thread); } if (alsa->buffer) fifo_free(alsa->buffer); if (alsa->cond) scond_free(alsa->cond); if (alsa->fifo_lock) slock_free(alsa->fifo_lock); if (alsa->cond_lock) slock_free(alsa->cond_lock); if (alsa->pcm) { snd_pcm_drop(alsa->pcm); snd_pcm_close(alsa->pcm); } free(alsa); } } static void *alsa_thread_init(const char *device, unsigned rate, unsigned latency) { alsa_thread_t *alsa = (alsa_thread_t*)calloc(1, sizeof(alsa_thread_t)); snd_pcm_hw_params_t *params = NULL; snd_pcm_sw_params_t *sw_params = NULL; const char *alsa_dev = device ? device : "default"; unsigned latency_usec = latency * 1000 / 2; unsigned channels = 2; unsigned periods = 4; snd_pcm_uframes_t buffer_size; snd_pcm_format_t format; if (!alsa) return NULL; TRY_ALSA(snd_pcm_open(&alsa->pcm, alsa_dev, SND_PCM_STREAM_PLAYBACK, 0)); TRY_ALSA(snd_pcm_hw_params_malloc(&params)); alsa->has_float = alsathread_find_float_format(alsa->pcm, params); format = alsa->has_float ? SND_PCM_FORMAT_FLOAT : SND_PCM_FORMAT_S16; TRY_ALSA(snd_pcm_hw_params_any(alsa->pcm, params)); TRY_ALSA(snd_pcm_hw_params_set_access( alsa->pcm, params, SND_PCM_ACCESS_RW_INTERLEAVED)); TRY_ALSA(snd_pcm_hw_params_set_format(alsa->pcm, params, format)); TRY_ALSA(snd_pcm_hw_params_set_channels(alsa->pcm, params, channels)); TRY_ALSA(snd_pcm_hw_params_set_rate(alsa->pcm, params, rate, 0)); TRY_ALSA(snd_pcm_hw_params_set_buffer_time_near( alsa->pcm, params, &latency_usec, NULL)); TRY_ALSA(snd_pcm_hw_params_set_periods_near( alsa->pcm, params, &periods, NULL)); TRY_ALSA(snd_pcm_hw_params(alsa->pcm, params)); /* Shouldn't have to bother with this, * but some drivers are apparently broken. */ if (snd_pcm_hw_params_get_period_size(params, &alsa->period_frames, NULL)) snd_pcm_hw_params_get_period_size_min( params, &alsa->period_frames, NULL); RARCH_LOG("ALSA: Period size: %d frames\n", (int)alsa->period_frames); if (snd_pcm_hw_params_get_buffer_size(params, &buffer_size)) snd_pcm_hw_params_get_buffer_size_max(params, &buffer_size); RARCH_LOG("ALSA: Buffer size: %d frames\n", (int)buffer_size); alsa->buffer_size = snd_pcm_frames_to_bytes(alsa->pcm, buffer_size); alsa->period_size = snd_pcm_frames_to_bytes(alsa->pcm, alsa->period_frames); TRY_ALSA(snd_pcm_sw_params_malloc(&sw_params)); TRY_ALSA(snd_pcm_sw_params_current(alsa->pcm, sw_params)); TRY_ALSA(snd_pcm_sw_params_set_start_threshold( alsa->pcm, sw_params, buffer_size / 2)); TRY_ALSA(snd_pcm_sw_params(alsa->pcm, sw_params)); snd_pcm_hw_params_free(params); snd_pcm_sw_params_free(sw_params); alsa->fifo_lock = slock_new(); alsa->cond_lock = slock_new(); alsa->cond = scond_new(); alsa->buffer = fifo_new(alsa->buffer_size); if (!alsa->fifo_lock || !alsa->cond_lock || !alsa->cond || !alsa->buffer) goto error; alsa->worker_thread = sthread_create(alsa_worker_thread, alsa); if (!alsa->worker_thread) { RARCH_ERR("error initializing worker thread"); goto error; } return alsa; error: RARCH_ERR("ALSA: Failed to initialize...\n"); if (params) snd_pcm_hw_params_free(params); if (sw_params) snd_pcm_sw_params_free(sw_params); alsa_thread_free(alsa); return NULL; } static ssize_t alsa_thread_write(void *data, const void *buf, size_t size) { alsa_thread_t *alsa = (alsa_thread_t*)data; if (alsa->thread_dead) return -1; if (alsa->nonblock) { size_t avail; size_t write_amt; slock_lock(alsa->fifo_lock); avail = fifo_write_avail(alsa->buffer); write_amt = min(avail, size); fifo_write(alsa->buffer, buf, write_amt); slock_unlock(alsa->fifo_lock); return write_amt; } else { size_t written = 0; while (written < size && !alsa->thread_dead) { size_t avail; slock_lock(alsa->fifo_lock); avail = fifo_write_avail(alsa->buffer); if (avail == 0) { slock_unlock(alsa->fifo_lock); slock_lock(alsa->cond_lock); if (!alsa->thread_dead) scond_wait(alsa->cond, alsa->cond_lock); slock_unlock(alsa->cond_lock); } else { size_t write_amt = min(size - written, avail); fifo_write(alsa->buffer, (const char*)buf + written, write_amt); slock_unlock(alsa->fifo_lock); written += write_amt; } } return written; } } static bool alsa_thread_alive(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; if (!alsa) return false; return !alsa->is_paused; } static bool alsa_thread_stop(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; if (alsa) alsa->is_paused = true; return true; } static void alsa_thread_set_nonblock_state(void *data, bool state) { alsa_thread_t *alsa = (alsa_thread_t*)data; alsa->nonblock = state; } static bool alsa_thread_start(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; if (alsa) alsa->is_paused = false; return true; } static size_t alsa_thread_write_avail(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; size_t val; if (alsa->thread_dead) return 0; slock_lock(alsa->fifo_lock); val = fifo_write_avail(alsa->buffer); slock_unlock(alsa->fifo_lock); return val; } static size_t alsa_thread_buffer_size(void *data) { alsa_thread_t *alsa = (alsa_thread_t*)data; return alsa->buffer_size; } audio_driver_t audio_alsathread = { alsa_thread_init, alsa_thread_write, alsa_thread_stop, alsa_thread_start, alsa_thread_alive, alsa_thread_set_nonblock_state, alsa_thread_free, alsa_thread_use_float, "alsathread", alsa_thread_write_avail, alsa_thread_buffer_size, };
jeapostrophe/RetroArch
audio/drivers/alsathread.c
C
gpl-3.0
9,534