code stringlengths 4 1.01M |
|---|
angular.module('examples', [])
.factory('formPostData', ['$document', function($document) {
return function(url, fields) {
var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>');
angular.forEach(fields, function(value, name) {
var input = angular.element('<input type="hidden" name="' + name + '">');
input.attr('value', value);
form.append(input);
});
$document.find('body').append(form);
form[0].submit();
form.remove();
};
}])
.factory('openPlunkr', ['formPostData', '$http', '$q', function(formPostData, $http, $q) {
return function(exampleFolder) {
var exampleName = 'AngularJS Example';
// Load the manifest for the example
$http.get(exampleFolder + '/manifest.json')
.then(function(response) {
return response.data;
})
.then(function(manifest) {
var filePromises = [];
// Build a pretty title for the Plunkr
var exampleNameParts = manifest.name.split('-');
exampleNameParts.unshift('AngularJS');
angular.forEach(exampleNameParts, function(part, index) {
exampleNameParts[index] = part.charAt(0).toUpperCase() + part.substr(1);
});
exampleName = exampleNameParts.join(' - ');
angular.forEach(manifest.files, function(filename) {
filePromises.push($http.get(exampleFolder + '/' + filename, { transformResponse: [] })
.then(function(response) {
// The manifests provide the production index file but Plunkr wants
// a straight index.html
if (filename === "index-production.html") {
filename = "index.html"
}
return {
name: filename,
content: response.data
};
}));
});
return $q.all(filePromises);
})
.then(function(files) {
var postData = {};
angular.forEach(files, function(file) {
postData['files[' + file.name + ']'] = file.content;
});
postData['tags[0]'] = "angularjs";
postData['tags[1]'] = "example";
postData.private = true;
postData.description = exampleName;
formPostData('http://plnkr.co/edit/?p=preview', postData);
});
};
}]); |
class UsersController < ApplicationController
def index
end
end
|
@echo off
rem *********************************************************************
rem ** the phing build script for Windows based systems
rem ** $Id$
rem *********************************************************************
rem This script will do the following:
rem - check for PHP_COMMAND env, if found, use it.
rem - if not found detect php, if found use it, otherwise err and terminate
rem - check for PHING_HOME evn, if found use it
rem - if not found error and leave
rem - check for PHP_CLASSPATH, if found use it
rem - if not found set it using PHING_HOME/classes
if "%OS%"=="Windows_NT" @setlocal
rem %~dp0 is expanded pathname of the current script under NT
set DEFAULT_PHING_HOME=%~dp0..
goto init
goto cleanup
:init
if "%PHING_HOME%" == "" set PHING_HOME=%DEFAULT_PHING_HOME%
set DEFAULT_PHING_HOME=
if "%PHP_COMMAND%" == "" goto no_phpcommand
if "%PHP_CLASSPATH%" == "" goto set_classpath
goto run
goto cleanup
:run
"%PHP_COMMAND%" -d html_errors=off -qC "%PHING_HOME%\bin\phing.php" %*
goto cleanup
:no_phpcommand
REM echo ------------------------------------------------------------------------
REM echo WARNING: Set environment var PHP_COMMAND to the location of your php.exe
REM echo executable (e.g. C:\PHP\php.exe). (Assuming php.exe on Path)
REM echo ------------------------------------------------------------------------
set PHP_COMMAND=php.exe
goto init
:err_home
echo ERROR: Environment var PHING_HOME not set. Please point this
echo variable to your local phing installation!
goto cleanup
:set_classpath
set PHP_CLASSPATH=%PHING_HOME%\classes
goto init
:cleanup
if "%OS%"=="Windows_NT" @endlocal
REM pause
|
// Copyright (c) 2010 libmv authors.
//
// 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.
#ifndef LIBMV_MULTIVIEW_ROBUST_AFFINE_H_
#define LIBMV_MULTIVIEW_ROBUST_AFFINE_H_
#include "libmv/base/vector.h"
#include "libmv/numeric/numeric.h"
namespace libmv {
/** Robust 2D affine transformation estimation
*
* This function estimates robustly the 2d affine matrix between two dataset
* of 2D point (image coords space). The 2d affine solver relies on the 3
* points solution.
*
* \param[in] x1 The first 2xN matrix of euclidean points
* \param[in] x2 The second 2xN matrix of euclidean points
* \param[in] max_error maximum error (in pixels)
* \param[out] H The 3x3 affine transformation matrix (6 dof)
* with the following parametrization
* |a b tx|
* H = |c d ty|
* |0 0 1 |
* such that x2 = H * x1
* \param[out] inliers the indexes list of the detected inliers
* \param[in] outliers_probability outliers probability (in ]0,1[).
* The number of iterations is controlled using the following equation:
* n_iter = log(outliers_prob) / log(1.0 - pow(inlier_ratio, min_samples)))
* The more this value is high, the less the function selects ramdom samples.
*
* \return the best error found (in pixels), associated to the solution H
*
* \note The function needs at least 3 points
* \note The overall iteration limit is 1000
*/
double Affine2DFromCorrespondences3PointRobust(
const Mat &x1,
const Mat &x2,
double max_error,
Mat3 *H,
vector<int> *inliers = NULL,
double outliers_probability = 1e-2);
} // namespace libmv
#endif // LIBMV_MULTIVIEW_ROBUST_AFFINE_H_
|
// Generated by CoffeeScript 1.4.0
var isDefined,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
window.serious = {};
window.serious.Utils = {};
isDefined = function(obj) {
return typeof obj !== 'undefined' && obj !== null;
};
jQuery.fn.opacity = function(int) {
return $(this).css({
opacity: int
});
};
window.serious.Utils.clone = function(obj) {
var flags, key, newInstance;
if (!(obj != null) || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
flags = '';
if (obj.global != null) {
flags += 'g';
}
if (obj.ignoreCase != null) {
flags += 'i';
}
if (obj.multiline != null) {
flags += 'm';
}
if (obj.sticky != null) {
flags += 'y';
}
return new RegExp(obj.source, flags);
}
newInstance = new obj.constructor();
for (key in obj) {
newInstance[key] = window.serious.Utils.clone(obj[key]);
}
return newInstance;
};
jQuery.fn.cloneTemplate = function(dict, removeUnusedField) {
var klass, nui, value;
if (removeUnusedField == null) {
removeUnusedField = false;
}
nui = $(this[0]).clone();
nui = nui.removeClass("template hidden").addClass("actual");
if (typeof dict === "object") {
for (klass in dict) {
value = dict[klass];
if (value !== null) {
nui.find(".out." + klass).html(value);
}
}
if (removeUnusedField) {
nui.find(".out").each(function() {
if ($(this).html() === "") {
return $(this).remove();
}
});
}
}
return nui;
};
Object.size = function(obj) {
var key, size;
size = 0;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
window.serious.States = (function() {
function States() {
this.states = {};
}
States.prototype.set = function(state, value, scope) {
if (value == null) {
value = true;
}
if (scope == null) {
scope = document;
}
this.states[state] = value;
return this._showState(state, value);
};
States.prototype._showState = function(state, value, scope) {
if (value == null) {
value = true;
}
if (scope == null) {
scope = document;
}
$(".when-" + state, scope).each(function(idx, element) {
var expected_value;
element = $(element);
expected_value = element.data('state') || true;
return $(element).toggleClass('hidden', expected_value.toString() !== value.toString());
});
return $(".when-not-" + state, scope).each(function(idx, element) {
var expected_value;
element = $(element);
expected_value = element.data('state') || true;
return $(element).toggleClass('hidden', expected_value.toString() === value.toString());
});
};
return States;
})();
window.serious.Widget = (function() {
function Widget() {
this.cloneTemplate = __bind(this.cloneTemplate, this);
this.show = __bind(this.show, this);
this.hide = __bind(this.hide, this);
this.get = __bind(this.get, this);
this.set = __bind(this.set, this);
}
Widget.bindAll = function() {
var first, firsts, _i, _len;
firsts = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (firsts) {
for (_i = 0, _len = firsts.length; _i < _len; _i++) {
first = firsts[_i];
Widget.ensureWidget($(first));
}
}
return $(".widget").each(function() {
var self;
self = $(this);
if (!self.hasClass('template') && !self.parents().hasClass('template')) {
return Widget.ensureWidget(self);
}
});
};
Widget.ensureWidget = function(ui) {
var widget, widget_class;
ui = $(ui);
if (!ui.length) {
return null;
} else if (ui[0]._widget != null) {
return ui[0]._widget;
} else {
widget_class = Widget.getWidgetClass(ui);
if (widget_class != null) {
widget = new widget_class();
widget.bindUI(ui);
return widget;
} else {
console.warn("widget not found for", ui);
return null;
}
}
};
Widget.getWidgetClass = function(ui) {
return eval("(" + $(ui).attr("data-widget") + ")");
};
Widget.prototype.bindUI = function(ui) {
var action, key, nui, value, _i, _len, _ref, _ref1, _results;
this.ui = $(ui);
if (this.ui[0]._widget) {
delete this.ui[0]._widget;
}
this.ui[0]._widget = this;
this.uis = {};
if (typeof this.UIS !== "undefined") {
_ref = this.UIS;
for (key in _ref) {
value = _ref[key];
nui = this.ui.find(value);
if (nui.length < 1) {
console.warn("uis", key, "not found in", ui);
}
this.uis[key] = nui;
}
}
if (this.ACTIONS != null) {
_ref1 = this.ACTIONS;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
action = _ref1[_i];
_results.push(this._bindClick(this.ui.find(".do[data-action=" + action + "]"), action));
}
return _results;
}
};
Widget.prototype.set = function(field, value, context) {
/* Set a value to all tag with the given data-field attribute.
Field can be a dict or a field name.
If it is a dict, the second parameter should be a context.
The default context is the widget itself.
*/
var name, _value;
if (typeof field === "object") {
context = value || this.ui;
for (name in field) {
_value = field[name];
context.find(".out[data-field=" + name + "]").html(_value);
}
} else {
context = context || this.ui;
context.find(".out[data-field=" + field + "]").html(value);
}
return context;
};
Widget.prototype.get = function(form) {
var data;
form = $(form);
data = {};
form.find('input.in').each(function() {
var input;
input = $(this);
if (!input.hasClass('template') && !input.parents().hasClass('template')) {
return data[input.attr('name')] = input.val();
}
});
return data;
};
Widget.prototype.hide = function() {
return this.ui.addClass("hidden");
};
Widget.prototype.show = function() {
return this.ui.removeClass("hidden");
};
Widget.prototype.cloneTemplate = function(template_nui, dict, removeUnusedField) {
var action, klass, nui, value, _i, _len, _ref;
if (removeUnusedField == null) {
removeUnusedField = false;
}
nui = template_nui.clone();
nui = nui.removeClass("template hidden").addClass("actual");
if (typeof dict === "object") {
for (klass in dict) {
value = dict[klass];
if (value !== null) {
nui.find(".out." + klass).html(value);
}
}
if (removeUnusedField) {
nui.find(".out").each(function() {
if ($(this).html() === "") {
return $(this).remove();
}
});
}
}
if (this.ACTIONS != null) {
_ref = this.ACTIONS;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
action = _ref[_i];
this._bindClick(nui.find(".do[data-action=" + action + "]"), action);
}
}
return nui;
};
Widget.prototype._bindClick = function(nui, action) {
var _this = this;
if ((action != null) && __indexOf.call(this.ACTIONS, action) >= 0) {
return nui.click(function(e) {
_this[action](e);
return e.preventDefault();
});
}
};
return Widget;
})();
window.serious.URL = (function() {
function URL() {
this.toString = __bind(this.toString, this);
this.fromString = __bind(this.fromString, this);
this.enableDynamicLinks = __bind(this.enableDynamicLinks, this);
this.updateUrl = __bind(this.updateUrl, this);
this.hasBeenAdded = __bind(this.hasBeenAdded, this);
this.hasChanged = __bind(this.hasChanged, this);
this.remove = __bind(this.remove, this);
this.update = __bind(this.update, this);
this.set = __bind(this.set, this);
this.onStateChanged = __bind(this.onStateChanged, this);
this.get = __bind(this.get, this);
var _this = this;
this.previousHash = [];
this.handlers = [];
this.hash = this.fromString(location.hash);
$(window).hashchange(function() {
var handler, _i, _len, _ref, _results;
_this.previousHash = window.serious.Utils.clone(_this.hash);
_this.hash = _this.fromString(location.hash);
_ref = _this.handlers;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
handler = _ref[_i];
_results.push(handler());
}
return _results;
});
}
URL.prototype.get = function(field) {
if (field == null) {
field = null;
}
if (field) {
return this.hash[field];
} else {
return this.hash;
}
};
URL.prototype.onStateChanged = function(handler) {
return this.handlers.push(handler);
};
URL.prototype.set = function(fields, silent) {
var hash, key, value;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
hash = [];
for (key in fields) {
value = fields[key];
if (isDefined(value)) {
hash[key] = value;
}
}
return this.updateUrl(hash);
};
URL.prototype.update = function(fields, silent) {
var hash, key, value;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
for (key in fields) {
value = fields[key];
if (isDefined(value)) {
hash[key] = value;
} else {
delete hash[key];
}
}
return this.updateUrl(hash);
};
URL.prototype.remove = function(key, silent) {
var hash;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
if (hash[key]) {
delete hash[key];
}
return this.updateUrl(hash);
};
URL.prototype.hasChanged = function(key) {
if (this.hash[key] != null) {
if (this.previousHash[key] != null) {
return this.hash[key].toString() !== this.previousHash[key].toString();
} else {
return true;
}
} else {
if (this.previousHash[key] != null) {
return true;
}
}
return false;
};
URL.prototype.hasBeenAdded = function(key) {
return console.error("not implemented");
};
URL.prototype.updateUrl = function(hash) {
if (hash == null) {
hash = null;
}
if (!hash || Object.size(hash) === 0) {
return location.hash = '_';
} else {
return location.hash = this.toString(hash);
}
};
URL.prototype.enableDynamicLinks = function(context) {
var _this = this;
if (context == null) {
context = null;
}
return $("a.internal[href]", context).click(function(e) {
var href, link;
link = $(e.currentTarget);
href = link.attr("data-href") || link.attr("href");
if (href[0] === "#") {
if (href.length > 1 && href[1] === "+") {
_this.update(_this.fromString(href.slice(2)));
} else if (href.length > 1 && href[1] === "-") {
_this.remove(_this.fromString(href.slice(2)));
} else {
_this.set(_this.fromString(href.slice(1)));
}
}
return false;
});
};
URL.prototype.fromString = function(value) {
var hash, hash_list, item, key, key_value, val, _i, _len;
value = value || location.hash;
hash = {};
value = value.replace('!', '');
hash_list = value.split("&");
for (_i = 0, _len = hash_list.length; _i < _len; _i++) {
item = hash_list[_i];
if (item != null) {
key_value = item.split("=");
if (key_value.length === 2) {
key = key_value[0].replace("#", "");
val = key_value[1].replace("#", "");
hash[key] = val;
}
}
}
return hash;
};
URL.prototype.toString = function(hash_list) {
var i, key, new_hash, value;
if (hash_list == null) {
hash_list = null;
}
hash_list = hash_list || this.hash;
new_hash = "!";
i = 0;
for (key in hash_list) {
value = hash_list[key];
if (i > 0) {
new_hash += "&";
}
new_hash += key + "=" + value;
i++;
}
return new_hash;
};
return URL;
})();
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'autoembed', 'pl', {
embeddingInProgress: 'Osadzanie wklejonego adresu URL...',
embeddingFailed: 'Ten adres URL multimediów nie może być automatycznie osadzony.'
} );
|
/*
* 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.jasper.tagplugins.jstl.core;
import org.apache.jasper.compiler.tagplugin.TagPlugin;
import org.apache.jasper.compiler.tagplugin.TagPluginContext;
public final class Choose implements TagPlugin {
@Override
public void doTag(TagPluginContext ctxt) {
// Not much to do here, much of the work will be done in the
// containing tags, <c:when> and <c:otherwise>.
ctxt.generateBody();
// See comments in When.java for the reason "}" is generated here.
ctxt.generateJavaSource("}");
}
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Nonterminals</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="Spirit 2.5.2">
<link rel="up" href="../quick_reference.html" title="Quick Reference">
<link rel="prev" href="compound_attribute_rules.html" title="Compound Attribute Rules">
<link rel="next" href="semantic_actions.html" title="Generator Semantic Actions">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="compound_attribute_rules.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../quick_reference.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="semantic_actions.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="spirit.karma.quick_reference.non_terminals"></a><a class="link" href="non_terminals.html" title="Nonterminals">Nonterminals</a>
</h4></div></div></div>
<p>
See here for more information about <a class="link" href="../reference/nonterminal.html" title="Nonterminal Generators"><code class="computeroutput"><span class="identifier">Nonterminals</span></code></a>.
</p>
<div class="variablelist">
<p class="title"><b>Notation</b></p>
<dl>
<dt><span class="term"><code class="computeroutput"><span class="identifier">RT</span></code></span></dt>
<dd><p>
Synthesized attribute. The rule or grammar's return type.
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">Arg1</span></code>, <code class="computeroutput"><span class="identifier">Arg2</span></code>, <code class="computeroutput"><span class="identifier">ArgN</span></code></span></dt>
<dd><p>
Inherited attributes. Zero or more arguments.
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">L1</span></code>, <code class="computeroutput"><span class="identifier">L2</span></code>, <code class="computeroutput"><span class="identifier">LN</span></code></span></dt>
<dd><p>
Zero or more local variables.
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">r</span><span class="special">,</span>
<span class="identifier">r2</span></code></span></dt>
<dd><p>
Rules
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">g</span></code></span></dt>
<dd><p>
A grammar
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">p</span></code></span></dt>
<dd><p>
A generator expression
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">my_grammar</span></code></span></dt>
<dd><p>
A user defined grammar
</p></dd>
</dl>
</div>
<div class="variablelist">
<p class="title"><b>Terminology</b></p>
<dl>
<dt><span class="term">Signature</span></dt>
<dd><p>
<code class="computeroutput"><span class="identifier">RT</span><span class="special">(</span><span class="identifier">Arg1</span><span class="special">,</span>
<span class="identifier">Arg2</span><span class="special">,</span>
<span class="special">...</span> <span class="special">,</span><span class="identifier">ArgN</span><span class="special">)</span></code>.
The signature specifies the synthesized (return value) and inherited
(arguments) attributes.
</p></dd>
<dt><span class="term">Locals</span></dt>
<dd><p>
<code class="computeroutput"><span class="identifier">locals</span><span class="special"><</span><span class="identifier">L1</span><span class="special">,</span> <span class="identifier">L2</span><span class="special">,</span> <span class="special">...,</span> <span class="identifier">LN</span><span class="special">></span></code>. The local variables.
</p></dd>
<dt><span class="term">Delimiter</span></dt>
<dd><p>
The delimit-generator type
</p></dd>
</dl>
</div>
<div class="variablelist">
<p class="title"><b>Template Arguments</b></p>
<dl>
<dt><span class="term"><code class="computeroutput"><span class="identifier">Iterator</span></code></span></dt>
<dd><p>
The iterator type you will use for parsing.
</p></dd>
<dt><span class="term"><code class="computeroutput"><span class="identifier">A1</span></code>, <code class="computeroutput"><span class="identifier">A2</span></code>, <code class="computeroutput"><span class="identifier">A3</span></code></span></dt>
<dd><p>
Can be one of 1) Signature 2) Locals 3) Delimiter.
</p></dd>
</dl>
</div>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Expression
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">rule</span><span class="special"><</span><span class="identifier">OutputIterator</span><span class="special">,</span>
<span class="identifier">A1</span><span class="special">,</span>
<span class="identifier">A2</span><span class="special">,</span>
<span class="identifier">A3</span><span class="special">></span>
<span class="identifier">r</span><span class="special">(</span><span class="identifier">name</span><span class="special">);</span></code>
</p>
</td>
<td>
<p>
Rule declaration. <code class="computeroutput"><span class="identifier">OutputIterator</span></code>
is required. <code class="computeroutput"><span class="identifier">A1</span><span class="special">,</span> <span class="identifier">A2</span><span class="special">,</span> <span class="identifier">A3</span></code>
are optional and can be specified in any order. <code class="computeroutput"><span class="identifier">name</span></code> is an optional string
that gives the rule its name, useful for debugging.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">rule</span><span class="special"><</span><span class="identifier">OutputIterator</span><span class="special">,</span>
<span class="identifier">A1</span><span class="special">,</span>
<span class="identifier">A2</span><span class="special">,</span>
<span class="identifier">A3</span><span class="special">></span>
<span class="identifier">r</span><span class="special">(</span><span class="identifier">r2</span><span class="special">);</span></code>
</p>
</td>
<td>
<p>
Copy construct rule <code class="computeroutput"><span class="identifier">r</span></code>
from rule <code class="computeroutput"><span class="identifier">r2</span></code>.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span> <span class="special">=</span>
<span class="identifier">r2</span><span class="special">;</span></code>
</p>
</td>
<td>
<p>
Assign rule <code class="computeroutput"><span class="identifier">r2</span></code>
to <code class="computeroutput"><span class="identifier">r</span></code>. <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">shared_ptr</span></code> semantics.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span><span class="special">.</span><span class="identifier">alias</span><span class="special">()</span></code>
</p>
</td>
<td>
<p>
Return an alias of <code class="computeroutput"><span class="identifier">r</span></code>.
The alias is a generator that holds a reference to <code class="computeroutput"><span class="identifier">r</span></code>. Reference semantics.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span><span class="special">.</span><span class="identifier">copy</span><span class="special">()</span></code>
</p>
</td>
<td>
<p>
Get a copy of <code class="computeroutput"><span class="identifier">r</span></code>.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span><span class="special">.</span><span class="identifier">name</span><span class="special">(</span><span class="identifier">name</span><span class="special">)</span></code>
</p>
</td>
<td>
<p>
Set the name of a rule
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span><span class="special">.</span><span class="identifier">name</span><span class="special">()</span></code>
</p>
</td>
<td>
<p>
Get the name of a rule
</p>
</td>
</tr>
<tr>
<td>
<p>
debug(r)
</p>
</td>
<td>
<p>
Debug rule <code class="computeroutput"><span class="identifier">r</span></code>
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span> <span class="special">=</span>
<span class="identifier">g</span><span class="special">;</span></code>
</p>
</td>
<td>
<p>
Rule definition
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">r</span> <span class="special">%=</span>
<span class="identifier">g</span><span class="special">;</span></code>
</p>
</td>
<td>
<p>
Auto-rule definition. The attribute of <code class="computeroutput"><span class="identifier">g</span></code>
should be compatible with the synthesized attribute of <code class="computeroutput"><span class="identifier">r</span></code>. When <code class="computeroutput"><span class="identifier">g</span></code>
is successful, its attribute is automatically propagated to
<code class="computeroutput"><span class="identifier">r</span></code>'s synthesized
attribute.
</p>
</td>
</tr>
<tr>
<td>
<p>
</p>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">typename</span> <span class="identifier">OutputIterator</span><span class="special">></span>
<span class="keyword">struct</span> <span class="identifier">my_grammar</span> <span class="special">:</span> <span class="identifier">grammar</span><span class="special"><</span><span class="identifier">OutputIterator</span><span class="special">,</span> <span class="identifier">A1</span><span class="special">,</span> <span class="identifier">A2</span><span class="special">,</span> <span class="identifier">A3</span><span class="special">></span>
<span class="special">{</span>
<span class="identifier">my_grammar</span><span class="special">()</span> <span class="special">:</span> <span class="identifier">my_grammar</span><span class="special">::</span><span class="identifier">base_type</span><span class="special">(</span><span class="identifier">start</span><span class="special">,</span> <span class="identifier">name</span><span class="special">)</span>
<span class="special">{</span>
<span class="comment">// Rule definitions</span>
<span class="identifier">start</span> <span class="special">=</span> <span class="comment">/* ... */</span><span class="special">;</span>
<span class="special">}</span>
<span class="identifier">rule</span><span class="special"><</span><span class="identifier">OutputIterator</span><span class="special">,</span> <span class="identifier">A1</span><span class="special">,</span> <span class="identifier">A2</span><span class="special">,</span> <span class="identifier">A3</span><span class="special">></span> <span class="identifier">start</span><span class="special">;</span>
<span class="comment">// more rule declarations...</span>
<span class="special">};</span>
</pre>
<p>
</p>
</td>
<td>
<p>
Grammar definition. <code class="computeroutput"><span class="identifier">name</span></code>
is an optional string that gives the grammar its name, useful
for debugging.
</p>
</td>
</tr>
<tr>
<td>
<p>
my_grammar<OutputIterator> g
</p>
</td>
<td>
<p>
Instantiate a grammar
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">g</span><span class="special">.</span><span class="identifier">name</span><span class="special">(</span><span class="identifier">name</span><span class="special">)</span></code>
</p>
</td>
<td>
<p>
Set the name of a grammar
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">g</span><span class="special">.</span><span class="identifier">name</span><span class="special">()</span></code>
</p>
</td>
<td>
<p>
Get the name of a grammar
</p>
</td>
</tr>
</tbody>
</table></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2011 Joel de Guzman, Hartmut Kaiser<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="compound_attribute_rules.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../quick_reference.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="semantic_actions.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
import * as amqp from "amqplib";
import * as amqpConMgr from 'amqp-connection-manager';
// from README.md
const connection = amqpConMgr.connect(['amqp://localhost']);
const channelWrapper: amqpConMgr.ChannelWrapper = connection.createChannel({
json: true,
setup: async (channel: amqp.ConfirmChannel): Promise<void> => {
// `channel` here is a regular amqplib `ConfirmChannel`. Unfortunately its typings make it return a bluebird-specific promise
// tslint:disable-next-line:await-promise
await channel.assertQueue('rxQueueName', {durable: true});
}
});
connection.on("connect", (_arg: { connection: amqp.Connection, url: string }): void => undefined);
connection.on("disconnect", (_arg: { err: Error }): void => undefined);
channelWrapper.on("close", () => undefined);
channelWrapper.on("connect", () => undefined);
channelWrapper.on("error", (_error: Error) => undefined);
channelWrapper.sendToQueue("foo", Buffer.from("bar"))
.catch((error: Error): void => {
// nothing
});
// Test that plain objects are implicitly serialized.
channelWrapper.sendToQueue("foo", {a: 'bar'}).catch(_ => {});
// Checking connection options
amqpConMgr.connect(["foo", "bar"], {
findServers(callback) {
callback("x");
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers(callback) {
callback(["x", "y"]);
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers() {
return Promise.resolve("x");
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers() {
return Promise.resolve(["x", "y"]);
}
});
amqpConMgr.connect(["foo", "bar"], {
reconnectTimeInSeconds: 123
});
amqpConMgr.connect(["foo", "bar"], {
heartbeatIntervalInSeconds: 123
});
amqpConMgr.connect(["foo", "bar"], {
connectionOptions: {
ca: "some CA",
servername: "foo.example.com"
}
});
|
# object-hash
Generate hashes from objects and values in node and the browser. Uses node.js
crypto module for hashing. Supports SHA1 and many others (depending on the platform)
as well as custom streams (e.g. CRC32).
[](https://www.npmjs.com/package/object-hash)
[](https://www.npmjs.com/package/object-hash)
[](https://secure.travis-ci.org/puleos/object-hash?branch=master)
[](https://coveralls.io/github/puleos/object-hash?branch=master)
* Hash values of any type.
* Supports a keys only option for grouping similar objects with different values.
```js
var hash = require('object-hash');
hash({foo: 'bar'}) // => '67b69634f9880a282c14a0f0cb7ba20cf5d677e9'
hash([1, 2, 2.718, 3.14159]) // => '136b9b88375971dff9f1af09d7356e3e04281951'
```
## Versioning Disclaimer
**IMPORTANT:** If you need lasting hash consistency, you should should lock `object-hash` at a specific version, because new versions (even patch versions) are likely to affect the result. For more info, see [this discussion](https://github.com/puleos/object-hash/issues/30).
## hash(value, options);
Generate a hash from any object or type. Defaults to sha1 with hex encoding.
* `algorithm` hash algo to be used: 'sha1', 'md5'. default: sha1
* `excludeValues` {true|false} hash object keys, values ignored. default: false
* `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex
* `ignoreUnknown` {true|*false} ignore unknown object types. default: false
* `replacer` optional function that replaces values before hashing. default: accept all values
* `respectFunctionProperties` {true|false} Whether properties on functions are considered when hashing. default: true
* `respectFunctionNames` {true|false} consider `name` property of functions for hashing. default: true
* `respectType` {true|false} Whether special type attributes (`.prototype`, `.__proto__`, `.constructor`)
are hashed. default: true
* `unorderedArrays` {true|false} Sort all arrays using before hashing. Note that this affects *all* collections,
i.e. including typed arrays, Sets, Maps, etc. default: false
* `unorderedSets` {true|false} Sort `Set` and `Map` instances before hashing, i.e. make
`hash(new Set([1, 2])) == hash(new Set([2, 1]))` return `true`. default: true
## hash.sha1(value);
Hash using the sha1 algorithm.
*Sugar method, equivalent to hash(value, {algorithm: 'sha1'})*
## hash.keys(value);
Hash object keys using the sha1 algorithm, values ignored.
*Sugar method, equivalent to hash(value, {excludeValues: true})*
## hash.MD5(value);
Hash using the md5 algorithm.
*Sugar method, equivalent to hash(value, {algorithm: 'md5'})*
## hash.keysMD5(value);
Hash object keys using the md5 algorithm, values ignored.
*Sugar method, equivalent to hash(value, {algorithm: 'md5', excludeValues: true})*
## hash.writeToStream(value, [options,] stream):
Write the information that would otherwise have been hashed to a stream, e.g.:
```js
hash.writeToStream({foo: 'bar', a: 42}, {respectType: false}, process.stdout)
// => e.g. 'object:a:number:42foo:string:bar'
```
## Installation
node:
```js
npm install object-hash
```
browser: */dist/object_hash.js*
```
<script src="object_hash.js" type="text/javascript"></script>
<script>
var hash = objectHash.sha({foo:'bar'});
console.log(hash); // e003c89cdf35cdf46d8239b4692436364b7259f9
</script>
```
## Example usage
```js
var hash = require('object-hash');
var peter = {name: 'Peter', stapler: false, friends: ['Joanna', 'Michael', 'Samir'] };
var michael = {name: 'Michael', stapler: false, friends: ['Peter', 'Samir'] };
var bob = {name: 'Bob', stapler: true, friends: [] };
/***
* sha1 hex encoding (default)
*/
hash(peter);
// 14fa461bf4b98155e82adc86532938553b4d33a9
hash(michael);
// 4b2b30e27699979ce46714253bc2213010db039c
hash(bob);
// 38d96106bc8ef3d8bd369b99bb6972702c9826d5
/***
* hash object keys, values ignored
*/
hash(peter, { excludeValues: true });
// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c
hash(michael, { excludeValues: true });
// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c
hash.keys(bob);
// 48f370a772c7496f6c9d2e6d92e920c87dd00a5c
/***
* md5 base64 encoding
*/
hash(peter, { algorithm: 'md5', encoding: 'base64' });
// 6rkWaaDiG3NynWw4svGH7g==
hash(michael, { algorithm: 'md5', encoding: 'base64' });
// djXaWpuWVJeOF8Sb6SFFNg==
hash(bob, { algorithm: 'md5', encoding: 'base64' });
// lFzkw/IJ8/12jZI0rQeS3w==
```
## Legacy Browser Support
IE <= 8 and Opera <= 11 support dropped in version 0.3.0. If you require
legacy browser support you must either use an ES5 shim or use version 0.2.5
of this module.
## Development
```
git clone https://github.com/puleos/object-hash
```
### gulp tasks
* `gulp watch` (default) watch files, test and lint on change/add
* `gulp test` unit tests
* `gulp karma` browser unit tests
* `gulp lint` jshint
* `gulp dist` create browser version in /dist
## License
MIT
|
<?php defined('C5_EXECUTE') or die("Access Denied."); ?>
<?php $f = Loader::helper('form'); ?>
<?php $co = Loader::helper('lists/countries'); ?>
<div class="ccm-attribute-address-composer-wrapper ccm-attribute-address-<?php echo $key->getAttributeKeyID()?>">
<div class="control-group">
<?php echo $f->label($this->field('address1'), t('Address 1'))?>
<div class="controls">
<?php echo $f->text($this->field('address1'), $address1)?>
</div>
</div>
<div class="control-group">
<?php echo $f->label($this->field('address2'), t('Address 2'))?>
<div class="controls">
<?php echo $f->text($this->field('address2'), $address2)?>
</div>
</div>
<div class="control-group">
<?php echo $f->label($this->field('city'), t('City'))?>
<div class="controls">
<?php echo $f->text($this->field('city'), $city)?>
</div>
</div>
<div class="control-group ccm-attribute-address-state-province">
<?php echo $f->label($this->field('state_province'), t('State/Province'))?>
<?php
$spreq = $f->getRequestValue($this->field('state_province'));
if ($spreq != false) {
$state_province = $spreq;
}
$creq = $f->getRequestValue($this->field('country'));
if ($creq != false) {
$country = $creq;
}
?>
<div class="controls">
<?php echo $f->select($this->field('state_province_select'), array('' => t('Choose State/Province')), $state_province, array('ccm-attribute-address-field-name' => $this->field('state_province')))?>
<?php echo $f->text($this->field('state_province_text'), $state_province, array('style' => 'display: none', 'ccm-attribute-address-field-name' => $this->field('state_province')))?>
</div>
</div>
<?php
if (!$country && !$search) {
if ($akDefaultCountry != '') {
$country = $akDefaultCountry;
} else {
$country = 'US';
}
}
$countriesTmp = $co->getCountries();
$countries = array();
foreach($countriesTmp as $_key => $_value) {
if ((!$akHasCustomCountries) || ($akHasCustomCountries && in_array($_key, $akCustomCountries))) {
$countries[$_key] = $_value;
}
}
$countries = array_merge(array('' => t('Choose Country')), $countries);
?>
<div class="control-group ccm-attribute-address-country">
<?php echo $f->label($this->field('country'), t('Country'))?>
<div class="controls">
<?php echo $f->select($this->field('country'), $countries, $country); ?>
</div>
</div>
<div class="control-group">
<?php echo $f->label($this->field('postal_code'), t('Postal Code'))?>
<div class="controls">
<?php echo $f->text($this->field('postal_code'), $postal_code)?>
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
$(function() {
ccm_setupAttributeTypeAddressSetupStateProvinceSelector('ccm-attribute-address-<?php echo $key->getAttributeKeyID()?>');
});
//]]>
</script> |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/***
*makepath.c - create path name from components
*
*
*Purpose:
* To provide support for creation of full path names from components
*
*******************************************************************************/
#include "stdafx.h"
#include "winwrap.h"
#include "utilcode.h"
#include "ex.h"
/***
*void Makepath() - build path name from components
*
*Purpose:
* create a path name from its individual components
*
*Entry:
* CQuickWSTR &szPath - Buffer for constructed path
* WCHAR *drive - pointer to drive component, may or may not contain
* trailing ':'
* WCHAR *dir - pointer to subdirectory component, may or may not include
* leading and/or trailing '/' or '\' characters
* WCHAR *fname - pointer to file base name component
* WCHAR *ext - pointer to extension component, may or may not contain
* a leading '.'.
*
*Exit:
* path - pointer to constructed path name
*
*Exceptions:
*
*******************************************************************************/
void MakePath (
__out CQuickWSTR &szPath,
__in LPCWSTR drive,
__in LPCWSTR dir,
__in LPCWSTR fname,
__in LPCWSTR ext
)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END
SIZE_T maxCount = 4 // Possible separators between components, plus null terminator
+ (drive != nullptr ? 2 : 0)
+ (dir != nullptr ? wcslen(dir) : 0)
+ (fname != nullptr ? wcslen(fname) : 0)
+ (ext != nullptr ? wcslen(ext) : 0);
LPWSTR path = szPath.AllocNoThrow(maxCount);
const WCHAR *p;
DWORD count = 0;
/* we assume that the arguments are in the following form (although we
* do not diagnose invalid arguments or illegal filenames (such as
* names longer than 8.3 or with illegal characters in them)
*
* drive:
* A ; or
* A:
* dir:
* \top\next\last\ ; or
* /top/next/last/ ; or
* either of the above forms with either/both the leading
* and trailing / or \ removed. Mixed use of '/' and '\' is
* also tolerated
* fname:
* any valid file name
* ext:
* any valid extension (none if empty or null )
*/
/* copy drive */
if (drive && *drive) {
*path++ = *drive;
*path++ = _T(':');
count += 2;
}
/* copy dir */
if ((p = dir)) {
while (*p) {
*path++ = *p++;
count++;
_ASSERTE(count < maxCount);
}
#ifdef _MBCS
if (*(p=_mbsdec(dir,p)) != _T('/') && *p != _T('\\')) {
#else /* _MBCS */
// suppress warning for the following line; this is safe but would require significant code
// delta for prefast to understand.
#ifdef _PREFAST_
#pragma warning( suppress: 26001 )
#endif
if (*(p-1) != _T('/') && *(p-1) != _T('\\')) {
#endif /* _MBCS */
*path++ = _T('\\');
count++;
_ASSERTE(count < maxCount);
}
}
/* copy fname */
if ((p = fname)) {
while (*p) {
*path++ = *p++;
count++;
_ASSERTE(count < maxCount);
}
}
/* copy ext, including 0-terminator - check to see if a '.' needs
* to be inserted.
*/
if ((p = ext)) {
if (*p && *p != _T('.')) {
*path++ = _T('.');
count++;
_ASSERTE(count < maxCount);
}
while ((*path++ = *p++)) {
count++;
_ASSERTE(count < maxCount);
}
}
else {
/* better add the 0-terminator */
*path = _T('\0');
}
szPath.Shrink(count + 1);
}
// Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL",
// then this would return "C:\Dir1\Dir2\" (note the trailing backslash).
HRESULT GetHModuleDirectory(
__in HMODULE hMod,
SString& wszPath)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
CANNOT_TAKE_LOCK;
}
CONTRACTL_END;
DWORD dwRet = WszGetModuleFileName(hMod, wszPath);
if (dwRet == 0)
{ // Some other error.
return HRESULT_FROM_GetLastError();
}
CopySystemDirectory(wszPath, wszPath);
return S_OK;
}
//
// Returns path name from a file name.
// Example: For input "C:\Windows\System.dll" returns "C:\Windows\".
// Warning: The input file name string might be destroyed.
//
// Arguments:
// pPathString - [in] SString with file name
//
// pBuffer - [out] SString .
//
// Return Value:
// S_OK - Output buffer contains path name.
// other errors - If Sstring throws.
//
HRESULT CopySystemDirectory(const SString& pPathString,
SString& pbuffer)
{
HRESULT hr = S_OK;
EX_TRY
{
pbuffer.Set(pPathString);
SString::Iterator iter = pbuffer.End();
if (pbuffer.FindBack(iter,DIRECTORY_SEPARATOR_CHAR_W))
{
iter++;
pbuffer.Truncate(iter);
}
else
{
hr = E_UNEXPECTED;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#ifndef __REGDISP_H
#define __REGDISP_H
#ifdef DEBUG_REGDISPLAY
class Thread;
struct REGDISPLAY;
void CheckRegDisplaySP (REGDISPLAY *pRD);
#endif // DEBUG_REGDISPLAY
struct REGDISPLAY_BASE {
PT_CONTEXT pContext; // This is the context of the active call frame;
// either returned by GetContext or provided at
// exception time.
//
// This will be used to resume execution, so
// do NOT trash it! But DO update any static
// registers here.
#ifdef FEATURE_EH_FUNCLETS
PT_CONTEXT pCurrentContext; // [trashed] points to current Context of stackwalk
PT_CONTEXT pCallerContext; // [trashed] points to the Context of the caller during stackwalk -- used for GC crawls
// [trashed] points to current context pointers of stackwalk
T_KNONVOLATILE_CONTEXT_POINTERS *pCurrentContextPointers;
// [trashed] points to the context pointers of the caller during stackwalk -- used for GC crawls
T_KNONVOLATILE_CONTEXT_POINTERS *pCallerContextPointers;
BOOL IsCallerContextValid; // TRUE if pCallerContext really contains the caller's context
BOOL IsCallerSPValid; // Don't add usage of this field. This is only temporary.
T_CONTEXT ctxOne; // used by stackwalk
T_CONTEXT ctxTwo; // used by stackwalk
T_KNONVOLATILE_CONTEXT_POINTERS ctxPtrsOne; // used by stackwalk
T_KNONVOLATILE_CONTEXT_POINTERS ctxPtrsTwo; // used by stackwalk
#endif // FEATURE_EH_FUNCLETS
#ifdef DEBUG_REGDISPLAY
Thread *_pThread;
#endif // DEBUG_REGDISPLAY
TADDR SP;
TADDR ControlPC;
};
inline PCODE GetControlPC(const REGDISPLAY_BASE *pRD) {
LIMITED_METHOD_DAC_CONTRACT;
return (PCODE)(pRD->ControlPC);
}
inline TADDR GetRegdisplaySP(REGDISPLAY_BASE *pRD) {
LIMITED_METHOD_DAC_CONTRACT;
return pRD->SP;
}
inline void SetRegdisplaySP(REGDISPLAY_BASE *pRD, LPVOID sp) {
LIMITED_METHOD_DAC_CONTRACT;
pRD->SP = (TADDR)sp;
}
#if defined(_TARGET_X86_)
struct REGDISPLAY : public REGDISPLAY_BASE {
#ifndef FEATURE_EH_FUNCLETS
// TODO: Unify with pCurrentContext / pCallerContext used on 64-bit
PCONTEXT pContextForUnwind; // scratch context for unwinding
// used to preserve context saved in the frame that
// could be otherwise wiped by the unwinding
DWORD * pEdi;
DWORD * pEsi;
DWORD * pEbx;
DWORD * pEdx;
DWORD * pEcx;
DWORD * pEax;
DWORD * pEbp;
#endif // !FEATURE_EH_FUNCLETS
#ifndef FEATURE_EH_FUNCLETS
#define REG_METHODS(reg) \
inline PDWORD Get##reg##Location(void) { return p##reg; } \
inline void Set##reg##Location(PDWORD p##reg) { this->p##reg = p##reg; }
#else // !FEATURE_EH_FUNCLETS
#define REG_METHODS(reg) \
inline PDWORD Get##reg##Location(void) { return pCurrentContextPointers->reg; } \
inline void Set##reg##Location(PDWORD p##reg) \
{ \
pCurrentContextPointers->reg = p##reg; \
pCurrentContext->reg = *p##reg; \
}
#endif // FEATURE_EH_FUNCLETS
REG_METHODS(Eax)
REG_METHODS(Ecx)
REG_METHODS(Edx)
REG_METHODS(Ebx)
REG_METHODS(Esi)
REG_METHODS(Edi)
REG_METHODS(Ebp)
#undef REG_METHODS
TADDR PCTAddr;
};
inline TADDR GetRegdisplayFP(REGDISPLAY *display) {
LIMITED_METHOD_DAC_CONTRACT;
#ifdef FEATURE_EH_FUNCLETS
return (TADDR)display->pCurrentContext->Ebp;
#else
return (TADDR)*display->GetEbpLocation();
#endif
}
inline LPVOID GetRegdisplayFPAddress(REGDISPLAY *display) {
LIMITED_METHOD_CONTRACT;
return (LPVOID)display->GetEbpLocation();
}
// This function tells us if the given stack pointer is in one of the frames of the functions called by the given frame
inline BOOL IsInCalleesFrames(REGDISPLAY *display, LPVOID stackPointer) {
LIMITED_METHOD_CONTRACT;
#ifdef FEATURE_EH_FUNCLETS
return stackPointer < ((LPVOID)(display->SP));
#else
return (TADDR)stackPointer < display->PCTAddr;
#endif
}
inline TADDR GetRegdisplayStackMark(REGDISPLAY *display) {
LIMITED_METHOD_DAC_CONTRACT;
#ifdef FEATURE_EH_FUNCLETS
_ASSERTE(GetRegdisplaySP(display) == GetSP(display->pCurrentContext));
return GetRegdisplaySP(display);
#else
return display->PCTAddr;
#endif
}
#elif defined(_TARGET_64BIT_)
#if defined(_TARGET_ARM64_)
typedef struct _Arm64VolatileContextPointer
{
union {
struct {
PDWORD64 X0;
PDWORD64 X1;
PDWORD64 X2;
PDWORD64 X3;
PDWORD64 X4;
PDWORD64 X5;
PDWORD64 X6;
PDWORD64 X7;
PDWORD64 X8;
PDWORD64 X9;
PDWORD64 X10;
PDWORD64 X11;
PDWORD64 X12;
PDWORD64 X13;
PDWORD64 X14;
PDWORD64 X15;
PDWORD64 X16;
PDWORD64 X17;
//X18 is reserved by OS, in userspace it represents TEB
};
PDWORD64 X[18];
};
} Arm64VolatileContextPointer;
#endif //_TARGET_ARM64_
struct REGDISPLAY : public REGDISPLAY_BASE {
#ifdef _TARGET_ARM64_
Arm64VolatileContextPointer volatileCurrContextPointers;
#endif
REGDISPLAY()
{
// Initialize
memset(this, 0, sizeof(REGDISPLAY));
}
};
inline TADDR GetRegdisplayFP(REGDISPLAY *display) {
LIMITED_METHOD_CONTRACT;
return NULL;
}
inline TADDR GetRegdisplayFPAddress(REGDISPLAY *display) {
LIMITED_METHOD_CONTRACT;
return NULL;
}
// This function tells us if the given stack pointer is in one of the frames of the functions called by the given frame
inline BOOL IsInCalleesFrames(REGDISPLAY *display, LPVOID stackPointer)
{
LIMITED_METHOD_CONTRACT;
return stackPointer < ((LPVOID)(display->SP));
}
inline TADDR GetRegdisplayStackMark(REGDISPLAY *display)
{
#if defined(_TARGET_AMD64_)
// On AMD64, the MemoryStackFp value is the current sp (i.e. the sp value when calling another method).
_ASSERTE(GetRegdisplaySP(display) == GetSP(display->pCurrentContext));
return GetRegdisplaySP(display);
#elif defined(_TARGET_ARM64_)
_ASSERTE(display->IsCallerContextValid);
return GetSP(display->pCallerContext);
#else // _TARGET_AMD64_
PORTABILITY_ASSERT("GetRegdisplayStackMark NYI for this platform (Regdisp.h)");
return NULL;
#endif // _TARGET_AMD64_
}
#elif defined(_TARGET_ARM_)
// ResumableFrame is pushed on the stack before
// starting the GC. registers r0-r3 in ResumableFrame can
// contain roots which might need to be updated if they are
// relocated. On Stack walking the addresses of the registers in the
// resumable Frame are passed to GC using pCurrentContextPointers
// member in _REGDISPLAY. However On ARM KNONVOLATILE_CONTEXT_POINTERS
// does not contain pointers for volatile registers. Therefore creating
// this structure to store pointers to volatile registers and adding an object
// as member in _REGDISPLAY
typedef struct _ArmVolatileContextPointer
{
PDWORD R0;
PDWORD R1;
PDWORD R2;
PDWORD R3;
PDWORD R12;
} ArmVolatileContextPointer;
struct REGDISPLAY : public REGDISPLAY_BASE {
ArmVolatileContextPointer volatileCurrContextPointers;
DWORD * pPC; // processor neutral name
#ifndef CROSSGEN_COMPILE
REGDISPLAY()
{
// Initialize regdisplay
memset(this, 0, sizeof(REGDISPLAY));
// Setup the pointer to ControlPC field
pPC = &ControlPC;
}
#else
private:
REGDISPLAY();
#endif
};
// This function tells us if the given stack pointer is in one of the frames of the functions called by the given frame
inline BOOL IsInCalleesFrames(REGDISPLAY *display, LPVOID stackPointer) {
LIMITED_METHOD_CONTRACT;
return stackPointer < ((LPVOID)(TADDR)(display->SP));
}
inline TADDR GetRegdisplayStackMark(REGDISPLAY *display) {
LIMITED_METHOD_CONTRACT;
// ARM uses the establisher frame as the marker
_ASSERTE(display->IsCallerContextValid);
return GetSP(display->pCallerContext);
}
#else // none of the above processors
#error "RegDisplay functions are not implemented on this platform."
#endif
#if defined(_TARGET_64BIT_) || defined(_TARGET_ARM_) || (defined(_TARGET_X86_) && defined(FEATURE_EH_FUNCLETS))
// This needs to be implemented for platforms that have funclets.
inline LPVOID GetRegdisplayReturnValue(REGDISPLAY *display)
{
LIMITED_METHOD_CONTRACT;
#if defined(_TARGET_AMD64_)
return (LPVOID)display->pCurrentContext->Rax;
#elif defined(_TARGET_ARM64_)
return (LPVOID)display->pCurrentContext->X0;
#elif defined(_TARGET_ARM_)
return (LPVOID)((TADDR)display->pCurrentContext->R0);
#elif defined(_TARGET_X86_)
return (LPVOID)display->pCurrentContext->Eax;
#else
PORTABILITY_ASSERT("GetRegdisplayReturnValue NYI for this platform (Regdisp.h)");
return NULL;
#endif
}
inline void SyncRegDisplayToCurrentContext(REGDISPLAY* pRD)
{
LIMITED_METHOD_CONTRACT;
#if defined(_TARGET_64BIT_)
pRD->SP = (INT_PTR)GetSP(pRD->pCurrentContext);
pRD->ControlPC = INT_PTR(GetIP(pRD->pCurrentContext));
#elif defined(_TARGET_ARM_)
pRD->SP = (DWORD)GetSP(pRD->pCurrentContext);
pRD->ControlPC = (DWORD)GetIP(pRD->pCurrentContext);
#elif defined(_TARGET_X86_)
pRD->SP = (DWORD)GetSP(pRD->pCurrentContext);
pRD->ControlPC = (DWORD)GetIP(pRD->pCurrentContext);
#else // _TARGET_X86_
PORTABILITY_ASSERT("SyncRegDisplayToCurrentContext");
#endif
#ifdef DEBUG_REGDISPLAY
CheckRegDisplaySP(pRD);
#endif // DEBUG_REGDISPLAY
}
#endif // _TARGET_64BIT_ || _TARGET_ARM_ || (_TARGET_X86_ && FEATURE_EH_FUNCLETS)
typedef REGDISPLAY *PREGDISPLAY;
#ifdef FEATURE_EH_FUNCLETS
inline void FillContextPointers(PT_KNONVOLATILE_CONTEXT_POINTERS pCtxPtrs, PT_CONTEXT pCtx)
{
#ifdef _TARGET_AMD64_
for (int i = 0; i < 16; i++)
{
*(&pCtxPtrs->Rax + i) = (&pCtx->Rax + i);
}
#elif defined(_TARGET_ARM64_) // _TARGET_AMD64_
for (int i = 0; i < 12; i++)
{
*(&pCtxPtrs->X19 + i) = (&pCtx->X19 + i);
}
#elif defined(_TARGET_ARM_) // _TARGET_ARM64_
// Copy over the nonvolatile integer registers (R4-R11)
for (int i = 0; i < 8; i++)
{
*(&pCtxPtrs->R4 + i) = (&pCtx->R4 + i);
}
#elif defined(_TARGET_X86_) // _TARGET_ARM_
for (int i = 0; i < 7; i++)
{
*(&pCtxPtrs->Edi + i) = (&pCtx->Edi + i);
}
#else // _TARGET_X86_
PORTABILITY_ASSERT("FillContextPointers");
#endif // _TARGET_???_ (ELSE)
}
#endif // FEATURE_EH_FUNCLETS
inline void FillRegDisplay(const PREGDISPLAY pRD, PT_CONTEXT pctx, PT_CONTEXT pCallerCtx = NULL)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
#ifndef FEATURE_EH_FUNCLETS
#ifdef _TARGET_X86_
pRD->pContext = pctx;
pRD->pContextForUnwind = NULL;
pRD->pEdi = &(pctx->Edi);
pRD->pEsi = &(pctx->Esi);
pRD->pEbx = &(pctx->Ebx);
pRD->pEbp = &(pctx->Ebp);
pRD->pEax = &(pctx->Eax);
pRD->pEcx = &(pctx->Ecx);
pRD->pEdx = &(pctx->Edx);
pRD->SP = pctx->Esp;
pRD->ControlPC = (PCODE)(pctx->Eip);
pRD->PCTAddr = (UINT_PTR)&(pctx->Eip);
#else // _TARGET_X86_
PORTABILITY_ASSERT("FillRegDisplay");
#endif // _TARGET_???_ (ELSE)
#else // !FEATURE_EH_FUNCLETS
pRD->pContext = pctx;
// Setup the references
pRD->pCurrentContextPointers = &pRD->ctxPtrsOne;
pRD->pCallerContextPointers = &pRD->ctxPtrsTwo;
pRD->pCurrentContext = &(pRD->ctxOne);
pRD->pCallerContext = &(pRD->ctxTwo);
// copy the active context to initialize our stackwalk
*(pRD->pCurrentContext) = *(pctx);
// copy the caller context as well if it's specified
if (pCallerCtx == NULL)
{
pRD->IsCallerContextValid = FALSE;
pRD->IsCallerSPValid = FALSE; // Don't add usage of this field. This is only temporary.
}
else
{
*(pRD->pCallerContext) = *(pCallerCtx);
pRD->IsCallerContextValid = TRUE;
pRD->IsCallerSPValid = TRUE; // Don't add usage of this field. This is only temporary.
}
FillContextPointers(&pRD->ctxPtrsOne, pctx);
#if defined(_TARGET_ARM_)
// Fill volatile context pointers. They can be used by GC in the case of the leaf frame
pRD->volatileCurrContextPointers.R0 = &pctx->R0;
pRD->volatileCurrContextPointers.R1 = &pctx->R1;
pRD->volatileCurrContextPointers.R2 = &pctx->R2;
pRD->volatileCurrContextPointers.R3 = &pctx->R3;
pRD->volatileCurrContextPointers.R12 = &pctx->R12;
pRD->ctxPtrsOne.Lr = &pctx->Lr;
pRD->pPC = &pRD->pCurrentContext->Pc;
#elif defined(_TARGET_ARM64_) // _TARGET_ARM_
// Fill volatile context pointers. They can be used by GC in the case of the leaf frame
for (int i=0; i < 18; i++)
pRD->volatileCurrContextPointers.X[i] = &pctx->X[i];
#endif // _TARGET_ARM64_
#ifdef DEBUG_REGDISPLAY
pRD->_pThread = NULL;
#endif // DEBUG_REGDISPLAY
// This will setup the PC and SP
SyncRegDisplayToCurrentContext(pRD);
#endif // !FEATURE_EH_FUNCLETS
}
// Initialize a new REGDISPLAY/CONTEXT pair from an existing valid REGDISPLAY.
inline void CopyRegDisplay(const PREGDISPLAY pInRD, PREGDISPLAY pOutRD, T_CONTEXT *pOutCtx)
{
WRAPPER_NO_CONTRACT;
// The general strategy is to extract the register state from the input REGDISPLAY
// into the new CONTEXT then simply call FillRegDisplay.
T_CONTEXT* pOutCallerCtx = NULL;
#ifndef FEATURE_EH_FUNCLETS
#if defined(_TARGET_X86_)
if (pInRD->pEdi != NULL) {pOutCtx->Edi = *pInRD->pEdi;} else {pInRD->pEdi = NULL;}
if (pInRD->pEsi != NULL) {pOutCtx->Esi = *pInRD->pEsi;} else {pInRD->pEsi = NULL;}
if (pInRD->pEbx != NULL) {pOutCtx->Ebx = *pInRD->pEbx;} else {pInRD->pEbx = NULL;}
if (pInRD->pEbp != NULL) {pOutCtx->Ebp = *pInRD->pEbp;} else {pInRD->pEbp = NULL;}
if (pInRD->pEax != NULL) {pOutCtx->Eax = *pInRD->pEax;} else {pInRD->pEax = NULL;}
if (pInRD->pEcx != NULL) {pOutCtx->Ecx = *pInRD->pEcx;} else {pInRD->pEcx = NULL;}
if (pInRD->pEdx != NULL) {pOutCtx->Edx = *pInRD->pEdx;} else {pInRD->pEdx = NULL;}
pOutCtx->Esp = pInRD->SP;
pOutCtx->Eip = pInRD->ControlPC;
#else // _TARGET_X86_
PORTABILITY_ASSERT("CopyRegDisplay");
#endif // _TARGET_???_
#else // FEATURE_EH_FUNCLETS
*pOutCtx = *(pInRD->pCurrentContext);
if (pInRD->IsCallerContextValid)
{
pOutCallerCtx = pInRD->pCallerContext;
}
#endif // FEATURE_EH_FUNCLETS
if (pOutRD)
FillRegDisplay(pOutRD, pOutCtx, pOutCallerCtx);
}
// Get address of a register in a CONTEXT given the reg number. For X86,
// the reg number is the R/M number from ModR/M byte or base in SIB byte
inline size_t * getRegAddr (unsigned regNum, PTR_CONTEXT regs)
{
#ifdef _TARGET_X86_
_ASSERTE(regNum < 8);
static const SIZE_T OFFSET_OF_REGISTERS[] =
{
offsetof(CONTEXT, Eax),
offsetof(CONTEXT, Ecx),
offsetof(CONTEXT, Edx),
offsetof(CONTEXT, Ebx),
offsetof(CONTEXT, Esp),
offsetof(CONTEXT, Ebp),
offsetof(CONTEXT, Esi),
offsetof(CONTEXT, Edi),
};
return (PTR_size_t)(PTR_BYTE(regs) + OFFSET_OF_REGISTERS[regNum]);
#elif defined(_TARGET_AMD64_)
_ASSERTE(regNum < 16);
return ®s->Rax + regNum;
#elif defined(_TARGET_ARM_)
_ASSERTE(regNum < 16);
return (size_t *)®s->R0 + regNum;
#elif defined(_TARGET_ARM64_)
_ASSERTE(regNum < 31);
return (size_t *)®s->X0 + regNum;
#else
_ASSERTE(!"@TODO Port - getRegAddr (Regdisp.h)");
#endif
return(0);
}
//---------------------------------------------------------------------------------------
//
// This is just a simpler helper function to convert a REGDISPLAY to a CONTEXT.
//
// Arguments:
// pRegDisp - the REGDISPLAY to be converted
// pContext - the buffer for storing the converted CONTEXT
//
inline void UpdateContextFromRegDisp(PREGDISPLAY pRegDisp, PT_CONTEXT pContext)
{
_ASSERTE((pRegDisp != NULL) && (pContext != NULL));
#ifndef FEATURE_EH_FUNCLETS
#if defined(_TARGET_X86_)
pContext->ContextFlags = (CONTEXT_INTEGER | CONTEXT_CONTROL);
pContext->Edi = *pRegDisp->pEdi;
pContext->Esi = *pRegDisp->pEsi;
pContext->Ebx = *pRegDisp->pEbx;
pContext->Ebp = *pRegDisp->pEbp;
pContext->Eax = *pRegDisp->pEax;
pContext->Ecx = *pRegDisp->pEcx;
pContext->Edx = *pRegDisp->pEdx;
pContext->Esp = pRegDisp->SP;
pContext->Eip = pRegDisp->ControlPC;
#else // _TARGET_X86_
PORTABILITY_ASSERT("UpdateContextFromRegDisp");
#endif // _TARGET_???_
#else // FEATURE_EH_FUNCLETS
*pContext = *pRegDisp->pCurrentContext;
#endif // FEATURE_EH_FUNCLETS
}
#endif // __REGDISP_H
|
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kmod.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/file.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/ratelimit.h>
static DEFINE_SPINLOCK(tty_ldisc_lock);
static DECLARE_WAIT_QUEUE_HEAD(tty_ldisc_wait);
static DECLARE_WAIT_QUEUE_HEAD(tty_ldisc_idle);
static struct tty_ldisc_ops *tty_ldiscs[NR_LDISCS];
static inline struct tty_ldisc *get_ldisc(struct tty_ldisc *ld)
{
if (ld)
atomic_inc(&ld->users);
return ld;
}
static void put_ldisc(struct tty_ldisc *ld)
{
unsigned long flags;
if (WARN_ON_ONCE(!ld))
return;
local_irq_save(flags);
if (atomic_dec_and_lock(&ld->users, &tty_ldisc_lock)) {
struct tty_ldisc_ops *ldo = ld->ops;
ldo->refcount--;
module_put(ldo->owner);
spin_unlock_irqrestore(&tty_ldisc_lock, flags);
kfree(ld);
return;
}
local_irq_restore(flags);
wake_up(&tty_ldisc_idle);
}
int tty_register_ldisc(int disc, struct tty_ldisc_ops *new_ldisc)
{
unsigned long flags;
int ret = 0;
if (disc < N_TTY || disc >= NR_LDISCS)
return -EINVAL;
spin_lock_irqsave(&tty_ldisc_lock, flags);
tty_ldiscs[disc] = new_ldisc;
new_ldisc->num = disc;
new_ldisc->refcount = 0;
spin_unlock_irqrestore(&tty_ldisc_lock, flags);
return ret;
}
EXPORT_SYMBOL(tty_register_ldisc);
int tty_unregister_ldisc(int disc)
{
unsigned long flags;
int ret = 0;
if (disc < N_TTY || disc >= NR_LDISCS)
return -EINVAL;
spin_lock_irqsave(&tty_ldisc_lock, flags);
if (tty_ldiscs[disc]->refcount)
ret = -EBUSY;
else
tty_ldiscs[disc] = NULL;
spin_unlock_irqrestore(&tty_ldisc_lock, flags);
return ret;
}
EXPORT_SYMBOL(tty_unregister_ldisc);
static struct tty_ldisc_ops *get_ldops(int disc)
{
unsigned long flags;
struct tty_ldisc_ops *ldops, *ret;
spin_lock_irqsave(&tty_ldisc_lock, flags);
ret = ERR_PTR(-EINVAL);
ldops = tty_ldiscs[disc];
if (ldops) {
ret = ERR_PTR(-EAGAIN);
if (try_module_get(ldops->owner)) {
ldops->refcount++;
ret = ldops;
}
}
spin_unlock_irqrestore(&tty_ldisc_lock, flags);
return ret;
}
static void put_ldops(struct tty_ldisc_ops *ldops)
{
unsigned long flags;
spin_lock_irqsave(&tty_ldisc_lock, flags);
ldops->refcount--;
module_put(ldops->owner);
spin_unlock_irqrestore(&tty_ldisc_lock, flags);
}
static struct tty_ldisc *tty_ldisc_get(int disc)
{
struct tty_ldisc *ld;
struct tty_ldisc_ops *ldops;
if (disc < N_TTY || disc >= NR_LDISCS)
return ERR_PTR(-EINVAL);
ldops = get_ldops(disc);
if (IS_ERR(ldops)) {
request_module("tty-ldisc-%d", disc);
ldops = get_ldops(disc);
if (IS_ERR(ldops))
return ERR_CAST(ldops);
}
ld = kmalloc(sizeof(struct tty_ldisc), GFP_KERNEL);
if (ld == NULL) {
put_ldops(ldops);
return ERR_PTR(-ENOMEM);
}
ld->ops = ldops;
atomic_set(&ld->users, 1);
return ld;
}
static void *tty_ldiscs_seq_start(struct seq_file *m, loff_t *pos)
{
return (*pos < NR_LDISCS) ? pos : NULL;
}
static void *tty_ldiscs_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return (*pos < NR_LDISCS) ? pos : NULL;
}
static void tty_ldiscs_seq_stop(struct seq_file *m, void *v)
{
}
static int tty_ldiscs_seq_show(struct seq_file *m, void *v)
{
int i = *(loff_t *)v;
struct tty_ldisc_ops *ldops;
ldops = get_ldops(i);
if (IS_ERR(ldops))
return 0;
seq_printf(m, "%-10s %2d\n", ldops->name ? ldops->name : "???", i);
put_ldops(ldops);
return 0;
}
static const struct seq_operations tty_ldiscs_seq_ops = {
.start = tty_ldiscs_seq_start,
.next = tty_ldiscs_seq_next,
.stop = tty_ldiscs_seq_stop,
.show = tty_ldiscs_seq_show,
};
static int proc_tty_ldiscs_open(struct inode *inode, struct file *file)
{
return seq_open(file, &tty_ldiscs_seq_ops);
}
const struct file_operations tty_ldiscs_proc_fops = {
.owner = THIS_MODULE,
.open = proc_tty_ldiscs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static void tty_ldisc_assign(struct tty_struct *tty, struct tty_ldisc *ld)
{
tty->ldisc = ld;
}
static struct tty_ldisc *tty_ldisc_try(struct tty_struct *tty)
{
unsigned long flags;
struct tty_ldisc *ld;
spin_lock_irqsave(&tty_ldisc_lock, flags);
ld = NULL;
if (test_bit(TTY_LDISC, &tty->flags))
ld = get_ldisc(tty->ldisc);
spin_unlock_irqrestore(&tty_ldisc_lock, flags);
return ld;
}
struct tty_ldisc *tty_ldisc_ref_wait(struct tty_struct *tty)
{
struct tty_ldisc *ld;
wait_event(tty_ldisc_wait, (ld = tty_ldisc_try(tty)) != NULL);
return ld;
}
EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait);
struct tty_ldisc *tty_ldisc_ref(struct tty_struct *tty)
{
return tty_ldisc_try(tty);
}
EXPORT_SYMBOL_GPL(tty_ldisc_ref);
void tty_ldisc_deref(struct tty_ldisc *ld)
{
put_ldisc(ld);
}
EXPORT_SYMBOL_GPL(tty_ldisc_deref);
static inline void tty_ldisc_put(struct tty_ldisc *ld)
{
put_ldisc(ld);
}
void tty_ldisc_enable(struct tty_struct *tty)
{
set_bit(TTY_LDISC, &tty->flags);
clear_bit(TTY_LDISC_CHANGING, &tty->flags);
wake_up(&tty_ldisc_wait);
}
void tty_ldisc_flush(struct tty_struct *tty)
{
struct tty_ldisc *ld = tty_ldisc_ref(tty);
if (ld) {
if (ld->ops->flush_buffer)
ld->ops->flush_buffer(tty);
tty_ldisc_deref(ld);
}
tty_buffer_flush(tty);
}
EXPORT_SYMBOL_GPL(tty_ldisc_flush);
static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
{
mutex_lock(&tty->termios_mutex);
tty->termios->c_line = num;
mutex_unlock(&tty->termios_mutex);
}
static int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld)
{
WARN_ON(test_and_set_bit(TTY_LDISC_OPEN, &tty->flags));
if (ld->ops->open) {
int ret;
ret = ld->ops->open(tty);
if (ret)
clear_bit(TTY_LDISC_OPEN, &tty->flags);
return ret;
}
return 0;
}
static void tty_ldisc_close(struct tty_struct *tty, struct tty_ldisc *ld)
{
WARN_ON(!test_bit(TTY_LDISC_OPEN, &tty->flags));
clear_bit(TTY_LDISC_OPEN, &tty->flags);
if (ld->ops->close)
ld->ops->close(tty);
}
static void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old)
{
char buf[64];
struct tty_ldisc *new_ldisc;
int r;
old = tty_ldisc_get(old->ops->num);
WARN_ON(IS_ERR(old));
tty_ldisc_assign(tty, old);
tty_set_termios_ldisc(tty, old->ops->num);
if (tty_ldisc_open(tty, old) < 0) {
tty_ldisc_put(old);
new_ldisc = tty_ldisc_get(N_TTY);
if (IS_ERR(new_ldisc))
panic("n_tty: get");
tty_ldisc_assign(tty, new_ldisc);
tty_set_termios_ldisc(tty, N_TTY);
r = tty_ldisc_open(tty, new_ldisc);
if (r < 0)
panic("Couldn't open N_TTY ldisc for "
"%s --- error %d.",
tty_name(tty, buf), r);
}
}
static int tty_ldisc_halt(struct tty_struct *tty)
{
clear_bit(TTY_LDISC, &tty->flags);
return cancel_work_sync(&tty->buf.work);
}
static void tty_ldisc_flush_works(struct tty_struct *tty)
{
flush_work_sync(&tty->hangup_work);
flush_work_sync(&tty->SAK_work);
flush_work_sync(&tty->buf.work);
}
static int tty_ldisc_wait_idle(struct tty_struct *tty, long timeout)
{
long ret;
ret = wait_event_timeout(tty_ldisc_idle,
atomic_read(&tty->ldisc->users) == 1, timeout);
return ret > 0 ? 0 : -EBUSY;
}
int tty_set_ldisc(struct tty_struct *tty, int ldisc)
{
int retval;
struct tty_ldisc *o_ldisc, *new_ldisc;
int work, o_work = 0;
struct tty_struct *o_tty;
new_ldisc = tty_ldisc_get(ldisc);
if (IS_ERR(new_ldisc))
return PTR_ERR(new_ldisc);
tty_lock();
o_tty = tty->link;
if (tty->ldisc->ops->num == ldisc) {
tty_unlock();
tty_ldisc_put(new_ldisc);
return 0;
}
tty_unlock();
tty_wait_until_sent(tty, 0);
tty_lock();
mutex_lock(&tty->ldisc_mutex);
while (test_bit(TTY_LDISC_CHANGING, &tty->flags)) {
mutex_unlock(&tty->ldisc_mutex);
tty_unlock();
wait_event(tty_ldisc_wait,
test_bit(TTY_LDISC_CHANGING, &tty->flags) == 0);
tty_lock();
mutex_lock(&tty->ldisc_mutex);
}
set_bit(TTY_LDISC_CHANGING, &tty->flags);
tty->receive_room = 0;
o_ldisc = tty->ldisc;
tty_unlock();
work = tty_ldisc_halt(tty);
if (o_tty)
o_work = tty_ldisc_halt(o_tty);
mutex_unlock(&tty->ldisc_mutex);
#if defined(CONFIG_MSM_SMD0_WQ)
if (!strcmp(tty->name, "smd0"))
flush_workqueue(tty_wq);
else
#endif
tty_ldisc_flush_works(tty);
retval = tty_ldisc_wait_idle(tty, 5 * HZ);
tty_lock();
mutex_lock(&tty->ldisc_mutex);
if (retval) {
tty_ldisc_put(new_ldisc);
goto enable;
}
if (test_bit(TTY_HUPPED, &tty->flags)) {
clear_bit(TTY_LDISC_CHANGING, &tty->flags);
mutex_unlock(&tty->ldisc_mutex);
tty_ldisc_put(new_ldisc);
tty_unlock();
return -EIO;
}
tty_ldisc_close(tty, o_ldisc);
tty_ldisc_assign(tty, new_ldisc);
tty_set_termios_ldisc(tty, ldisc);
retval = tty_ldisc_open(tty, new_ldisc);
if (retval < 0) {
tty_ldisc_put(new_ldisc);
tty_ldisc_restore(tty, o_ldisc);
}
if (tty->ldisc->ops->num != o_ldisc->ops->num && tty->ops->set_ldisc)
tty->ops->set_ldisc(tty);
tty_ldisc_put(o_ldisc);
enable:
tty_ldisc_enable(tty);
if (o_tty)
tty_ldisc_enable(o_tty);
if (work) {
#if defined(CONFIG_MSM_SMD0_WQ)
if (!strcmp(tty->name, "smd0"))
queue_work(tty_wq, &tty->buf.work);
else
#endif
schedule_work(&tty->buf.work);
}
if (o_work) {
#if defined(CONFIG_MSM_SMD0_WQ)
if (!strcmp(o_tty->name, "smd0"))
queue_work(tty_wq, &tty->buf.work);
else
#endif
schedule_work(&o_tty->buf.work);
}
mutex_unlock(&tty->ldisc_mutex);
tty_unlock();
return retval;
}
static void tty_reset_termios(struct tty_struct *tty)
{
mutex_lock(&tty->termios_mutex);
*tty->termios = tty->driver->init_termios;
tty->termios->c_ispeed = tty_termios_input_baud_rate(tty->termios);
tty->termios->c_ospeed = tty_termios_baud_rate(tty->termios);
mutex_unlock(&tty->termios_mutex);
}
static int tty_ldisc_reinit(struct tty_struct *tty, int ldisc)
{
struct tty_ldisc *ld = tty_ldisc_get(ldisc);
if (IS_ERR(ld))
return -1;
tty_ldisc_close(tty, tty->ldisc);
tty_ldisc_put(tty->ldisc);
tty->ldisc = NULL;
tty_ldisc_assign(tty, ld);
tty_set_termios_ldisc(tty, ldisc);
return 0;
}
void tty_ldisc_hangup(struct tty_struct *tty)
{
struct tty_ldisc *ld;
int reset = tty->driver->flags & TTY_DRIVER_RESET_TERMIOS;
int err = 0;
ld = tty_ldisc_ref(tty);
if (ld != NULL) {
if (ld->ops->flush_buffer)
ld->ops->flush_buffer(tty);
tty_driver_flush_buffer(tty);
if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) &&
ld->ops->write_wakeup)
ld->ops->write_wakeup(tty);
if (ld->ops->hangup)
ld->ops->hangup(tty);
tty_ldisc_deref(ld);
}
wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
wake_up_interruptible_poll(&tty->read_wait, POLLIN);
mutex_lock(&tty->ldisc_mutex);
clear_bit(TTY_LDISC, &tty->flags);
tty_unlock();
cancel_work_sync(&tty->buf.work);
mutex_unlock(&tty->ldisc_mutex);
retry:
tty_lock();
mutex_lock(&tty->ldisc_mutex);
if (tty->ldisc) {
if (atomic_read(&tty->ldisc->users) != 1) {
char cur_n[TASK_COMM_LEN], tty_n[64];
long timeout = 3 * HZ;
tty_unlock();
while (tty_ldisc_wait_idle(tty, timeout) == -EBUSY) {
timeout = MAX_SCHEDULE_TIMEOUT;
printk_ratelimited(KERN_WARNING
"%s: waiting (%s) for %s took too long, but we keep waiting...\n",
__func__, get_task_comm(cur_n, current),
tty_name(tty, tty_n));
}
mutex_unlock(&tty->ldisc_mutex);
goto retry;
}
if (reset == 0) {
if (!tty_ldisc_reinit(tty, tty->termios->c_line))
err = tty_ldisc_open(tty, tty->ldisc);
else
err = 1;
}
if (reset || err) {
BUG_ON(tty_ldisc_reinit(tty, N_TTY));
WARN_ON(tty_ldisc_open(tty, tty->ldisc));
}
tty_ldisc_enable(tty);
}
mutex_unlock(&tty->ldisc_mutex);
if (reset)
tty_reset_termios(tty);
}
int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty)
{
struct tty_ldisc *ld = tty->ldisc;
int retval;
retval = tty_ldisc_open(tty, ld);
if (retval)
return retval;
if (o_tty) {
retval = tty_ldisc_open(o_tty, o_tty->ldisc);
if (retval) {
tty_ldisc_close(tty, ld);
return retval;
}
tty_ldisc_enable(o_tty);
}
tty_ldisc_enable(tty);
return 0;
}
void tty_ldisc_release(struct tty_struct *tty, struct tty_struct *o_tty)
{
tty_unlock();
tty_ldisc_halt(tty);
#if defined(CONFIG_MSM_SMD0_WQ)
if (!strcmp(tty->name, "smd0"))
flush_workqueue(tty_wq);
else
#endif
tty_ldisc_flush_works(tty);
tty_lock();
mutex_lock(&tty->ldisc_mutex);
tty_ldisc_close(tty, tty->ldisc);
tty_ldisc_put(tty->ldisc);
tty->ldisc = NULL;
tty_set_termios_ldisc(tty, N_TTY);
mutex_unlock(&tty->ldisc_mutex);
if (o_tty)
tty_ldisc_release(o_tty, NULL);
}
void tty_ldisc_init(struct tty_struct *tty)
{
struct tty_ldisc *ld = tty_ldisc_get(N_TTY);
if (IS_ERR(ld))
panic("n_tty: init_tty");
tty_ldisc_assign(tty, ld);
}
void tty_ldisc_deinit(struct tty_struct *tty)
{
put_ldisc(tty->ldisc);
tty_ldisc_assign(tty, NULL);
}
void tty_ldisc_begin(void)
{
(void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY);
}
|
/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2000-2002 Maxim Krasnyansky <maxk@qualcomm.com>
* Copyright (C) 2003-2007 Marcel Holtmann <marcel@holtmann.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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "parser.h"
#include "rfcomm.h"
struct parser_t parser;
void init_parser(unsigned long flags, unsigned long filter,
unsigned short defpsm, unsigned short defcompid,
int pppdump_fd, int audio_fd)
{
if ((flags & DUMP_RAW) && !(flags & DUMP_TYPE_MASK))
flags |= DUMP_HEX;
parser.flags = flags;
parser.filter = filter;
parser.defpsm = defpsm;
parser.defcompid = defcompid;
parser.state = 0;
parser.pppdump_fd = pppdump_fd;
parser.audio_fd = audio_fd;
}
#define PROTO_TABLE_SIZE 20
static struct {
uint16_t handle;
uint16_t psm;
uint8_t channel;
uint32_t proto;
} proto_table[PROTO_TABLE_SIZE];
void set_proto(uint16_t handle, uint16_t psm, uint8_t channel, uint32_t proto)
{
int i, pos = -1;
if (psm > 0 && psm < 0x1000 && !channel)
return;
if (!psm && channel)
psm = RFCOMM_PSM;
for (i = 0; i < PROTO_TABLE_SIZE; i++) {
if (proto_table[i].handle == handle && proto_table[i].psm == psm && proto_table[i].channel == channel) {
pos = i;
break;
}
if (pos < 0 && !proto_table[i].handle && !proto_table[i].psm && !proto_table[i].channel)
pos = i;
}
if (pos < 0)
return;
proto_table[pos].handle = handle;
proto_table[pos].psm = psm;
proto_table[pos].channel = channel;
proto_table[pos].proto = proto;
}
uint32_t get_proto(uint16_t handle, uint16_t psm, uint8_t channel)
{
int i, pos = -1;
if (!psm && channel)
psm = RFCOMM_PSM;
for (i = 0; i < PROTO_TABLE_SIZE; i++) {
if (proto_table[i].handle == handle && proto_table[i].psm == psm && proto_table[i].channel == channel)
return proto_table[i].proto;
if (!proto_table[i].handle) {
if (proto_table[i].psm == psm && proto_table[i].channel == channel)
pos = i;
}
}
return (pos < 0) ? 0 : proto_table[pos].proto;
}
#define FRAME_TABLE_SIZE 20
static struct {
uint16_t handle;
uint8_t dlci;
uint8_t opcode;
uint8_t status;
struct frame frm;
} frame_table[FRAME_TABLE_SIZE];
void del_frame(uint16_t handle, uint8_t dlci)
{
int i;
for (i = 0; i < FRAME_TABLE_SIZE; i++)
if (frame_table[i].handle == handle &&
frame_table[i].dlci == dlci) {
frame_table[i].handle = 0;
frame_table[i].dlci = 0;
frame_table[i].opcode = 0;
frame_table[i].status = 0;
if (frame_table[i].frm.data)
free(frame_table[i].frm.data);
memset(&frame_table[i].frm, 0, sizeof(struct frame));
break;
}
}
struct frame *add_frame(struct frame *frm)
{
struct frame *fr;
void *data;
int i, pos = -1;
for (i = 0; i < FRAME_TABLE_SIZE; i++) {
if (frame_table[i].handle == frm->handle &&
frame_table[i].dlci == frm->dlci) {
pos = i;
break;
}
if (pos < 0 && !frame_table[i].handle && !frame_table[i].dlci)
pos = i;
}
if (pos < 0)
return frm;
frame_table[pos].handle = frm->handle;
frame_table[pos].dlci = frm->dlci;
fr = &frame_table[pos].frm;
data = malloc(fr->len + frm->len);
if (!data) {
perror("Can't allocate frame stream buffer");
del_frame(frm->handle, frm->dlci);
return frm;
}
if (fr->len > 0)
memcpy(data, fr->ptr, fr->len);
if (frm->len > 0)
memcpy(data + fr->len, frm->ptr, frm->len);
if (fr->data)
free(fr->data);
fr->data = data;
fr->data_len = fr->len + frm->len;
fr->len = fr->data_len;
fr->ptr = fr->data;
fr->dev_id = frm->dev_id;
fr->in = frm->in;
fr->ts = frm->ts;
fr->handle = frm->handle;
fr->cid = frm->cid;
fr->num = frm->num;
fr->dlci = frm->dlci;
fr->channel = frm->channel;
fr->pppdump_fd = frm->pppdump_fd;
fr->audio_fd = frm->audio_fd;
return fr;
}
uint8_t get_opcode(uint16_t handle, uint8_t dlci)
{
int i;
for (i = 0; i < FRAME_TABLE_SIZE; i++)
if (frame_table[i].handle == handle &&
frame_table[i].dlci == dlci)
return frame_table[i].opcode;
return 0x00;
}
void set_opcode(uint16_t handle, uint8_t dlci, uint8_t opcode)
{
int i;
for (i = 0; i < FRAME_TABLE_SIZE; i++)
if (frame_table[i].handle == handle &&
frame_table[i].dlci == dlci) {
frame_table[i].opcode = opcode;
break;
}
}
uint8_t get_status(uint16_t handle, uint8_t dlci)
{
int i;
for (i = 0; i < FRAME_TABLE_SIZE; i++)
if (frame_table[i].handle == handle &&
frame_table[i].dlci == dlci)
return frame_table[i].status;
return 0x00;
}
void set_status(uint16_t handle, uint8_t dlci, uint8_t status)
{
int i;
for (i = 0; i < FRAME_TABLE_SIZE; i++)
if (frame_table[i].handle == handle &&
frame_table[i].dlci == dlci) {
frame_table[i].status = status;
break;
}
}
void ascii_dump(int level, struct frame *frm, int num)
{
unsigned char *buf = frm->ptr;
register int i, n;
if ((num < 0) || (num > frm->len))
num = frm->len;
for (i = 0, n = 1; i < num; i++, n++) {
if (n == 1)
p_indent(level, frm);
printf("%1c ", isprint(buf[i]) ? buf[i] : '.');
if (n == DUMP_WIDTH) {
printf("\n");
n = 0;
}
}
if (i && n != 1)
printf("\n");
}
void hex_dump(int level, struct frame *frm, int num)
{
unsigned char *buf = frm->ptr;
register int i, n;
if ((num < 0) || (num > frm->len))
num = frm->len;
for (i = 0, n = 1; i < num; i++, n++) {
if (n == 1)
p_indent(level, frm);
printf("%2.2X ", buf[i]);
if (n == DUMP_WIDTH) {
printf("\n");
n = 0;
}
}
if (i && n != 1)
printf("\n");
}
void ext_dump(int level, struct frame *frm, int num)
{
unsigned char *buf = frm->ptr;
register int i, n = 0, size;
if ((num < 0) || (num > frm->len))
num = frm->len;
while (num > 0) {
p_indent(level, frm);
printf("%04x: ", n);
size = num > 16 ? 16 : num;
for (i = 0; i < size; i++)
printf("%02x%s", buf[i], (i + 1) % 8 ? " " : " ");
for (i = size; i < 16; i++)
printf(" %s", (i + 1) % 8 ? " " : " ");
for (i = 0; i < size; i++)
printf("%1c", isprint(buf[i]) ? buf[i] : '.');
printf("\n");
buf += size;
num -= size;
n += size;
}
}
void raw_ndump(int level, struct frame *frm, int num)
{
if (!frm->len)
return;
switch (parser.flags & DUMP_TYPE_MASK) {
case DUMP_ASCII:
ascii_dump(level, frm, num);
break;
case DUMP_HEX:
hex_dump(level, frm, num);
break;
case DUMP_EXT:
ext_dump(level, frm, num);
break;
}
}
void raw_dump(int level, struct frame *frm)
{
raw_ndump(level, frm, -1);
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Tue Feb 16 15:23:08 EST 2016 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.request.json.ObjectUtil (Solr 5.5.0 API)</title>
<meta name="date" content="2016-02-16">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.request.json.ObjectUtil (Solr 5.5.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/request/json/ObjectUtil.html" title="class in org.apache.solr.request.json">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/request/json/class-use/ObjectUtil.html" target="_top">Frames</a></li>
<li><a href="ObjectUtil.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.request.json.ObjectUtil" class="title">Uses of Class<br>org.apache.solr.request.json.ObjectUtil</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.request.json.ObjectUtil</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/request/json/ObjectUtil.html" title="class in org.apache.solr.request.json">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/request/json/class-use/ObjectUtil.html" target="_top">Frames</a></li>
<li><a href="ObjectUtil.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2013 Lennart Poettering
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include "bus-internal.h"
#include "bus-message.h"
#include "bus-signature.h"
#include "bus-util.h"
#include "bus-type.h"
_public_ int sd_bus_emit_signal(
sd_bus *bus,
const char *path,
const char *interface,
const char *member,
const char *types, ...) {
_cleanup_bus_message_unref_ sd_bus_message *m = NULL;
int r;
assert_return(bus, -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_message_new_signal(bus, &m, path, interface, member);
if (r < 0)
return r;
if (!isempty(types)) {
va_list ap;
va_start(ap, types);
r = bus_message_append_ap(m, types, ap);
va_end(ap);
if (r < 0)
return r;
}
return sd_bus_send(bus, m, NULL);
}
_public_ int sd_bus_call_method(
sd_bus *bus,
const char *destination,
const char *path,
const char *interface,
const char *member,
sd_bus_error *error,
sd_bus_message **reply,
const char *types, ...) {
_cleanup_bus_message_unref_ sd_bus_message *m = NULL;
int r;
assert_return(bus, -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_message_new_method_call(bus, &m, destination, path, interface, member);
if (r < 0)
return r;
if (!isempty(types)) {
va_list ap;
va_start(ap, types);
r = bus_message_append_ap(m, types, ap);
va_end(ap);
if (r < 0)
return r;
}
return sd_bus_call(bus, m, 0, error, reply);
}
_public_ int sd_bus_reply_method_return(
sd_bus_message *call,
const char *types, ...) {
_cleanup_bus_message_unref_ sd_bus_message *m = NULL;
int r;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
return 0;
r = sd_bus_message_new_method_return(call, &m);
if (r < 0)
return r;
if (!isempty(types)) {
va_list ap;
va_start(ap, types);
r = bus_message_append_ap(m, types, ap);
va_end(ap);
if (r < 0)
return r;
}
return sd_bus_send(call->bus, m, NULL);
}
_public_ int sd_bus_reply_method_error(
sd_bus_message *call,
const sd_bus_error *e) {
_cleanup_bus_message_unref_ sd_bus_message *m = NULL;
int r;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
assert_return(sd_bus_error_is_set(e), -EINVAL);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
return 0;
r = sd_bus_message_new_method_error(call, &m, e);
if (r < 0)
return r;
return sd_bus_send(call->bus, m, NULL);
}
_public_ int sd_bus_reply_method_errorf(
sd_bus_message *call,
const char *name,
const char *format,
...) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
va_list ap;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
return 0;
va_start(ap, format);
bus_error_setfv(&error, name, format, ap);
va_end(ap);
return sd_bus_reply_method_error(call, &error);
}
_public_ int sd_bus_reply_method_errno(
sd_bus_message *call,
int error,
const sd_bus_error *p) {
_cleanup_bus_error_free_ sd_bus_error berror = SD_BUS_ERROR_NULL;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
return 0;
if (sd_bus_error_is_set(p))
return sd_bus_reply_method_error(call, p);
sd_bus_error_set_errno(&berror, error);
return sd_bus_reply_method_error(call, &berror);
}
_public_ int sd_bus_reply_method_errnof(
sd_bus_message *call,
int error,
const char *format,
...) {
_cleanup_bus_error_free_ sd_bus_error berror = SD_BUS_ERROR_NULL;
va_list ap;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
return 0;
va_start(ap, format);
sd_bus_error_set_errnofv(&berror, error, format, ap);
va_end(ap);
return sd_bus_reply_method_error(call, &berror);
}
_public_ int sd_bus_get_property(
sd_bus *bus,
const char *destination,
const char *path,
const char *interface,
const char *member,
sd_bus_error *error,
sd_bus_message **reply,
const char *type) {
sd_bus_message *rep = NULL;
int r;
assert_return(bus, -EINVAL);
assert_return(isempty(interface) || interface_name_is_valid(interface), -EINVAL);
assert_return(member_name_is_valid(member), -EINVAL);
assert_return(reply, -EINVAL);
assert_return(signature_is_single(type, false), -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_call_method(bus, destination, path, "org.freedesktop.DBus.Properties", "Get", error, &rep, "ss", strempty(interface), member);
if (r < 0)
return r;
r = sd_bus_message_enter_container(rep, 'v', type);
if (r < 0) {
sd_bus_message_unref(rep);
return r;
}
*reply = rep;
return 0;
}
_public_ int sd_bus_get_property_trivial(
sd_bus *bus,
const char *destination,
const char *path,
const char *interface,
const char *member,
sd_bus_error *error,
char type, void *ptr) {
_cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
int r;
assert_return(bus, -EINVAL);
assert_return(isempty(interface) || interface_name_is_valid(interface), -EINVAL);
assert_return(member_name_is_valid(member), -EINVAL);
assert_return(bus_type_is_trivial(type), -EINVAL);
assert_return(ptr, -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_call_method(bus, destination, path, "org.freedesktop.DBus.Properties", "Get", error, &reply, "ss", strempty(interface), member);
if (r < 0)
return r;
r = sd_bus_message_enter_container(reply, 'v', CHAR_TO_STR(type));
if (r < 0)
return r;
r = sd_bus_message_read_basic(reply, type, ptr);
if (r < 0)
return r;
return 0;
}
_public_ int sd_bus_get_property_string(
sd_bus *bus,
const char *destination,
const char *path,
const char *interface,
const char *member,
sd_bus_error *error,
char **ret) {
_cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
const char *s;
char *n;
int r;
assert_return(bus, -EINVAL);
assert_return(isempty(interface) || interface_name_is_valid(interface), -EINVAL);
assert_return(member_name_is_valid(member), -EINVAL);
assert_return(ret, -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_call_method(bus, destination, path, "org.freedesktop.DBus.Properties", "Get", error, &reply, "ss", strempty(interface), member);
if (r < 0)
return r;
r = sd_bus_message_enter_container(reply, 'v', "s");
if (r < 0)
return r;
r = sd_bus_message_read_basic(reply, 's', &s);
if (r < 0)
return r;
n = strdup(s);
if (!n)
return -ENOMEM;
*ret = n;
return 0;
}
_public_ int sd_bus_get_property_strv(
sd_bus *bus,
const char *destination,
const char *path,
const char *interface,
const char *member,
sd_bus_error *error,
char ***ret) {
_cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
int r;
assert_return(bus, -EINVAL);
assert_return(isempty(interface) || interface_name_is_valid(interface), -EINVAL);
assert_return(member_name_is_valid(member), -EINVAL);
assert_return(ret, -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_call_method(bus, destination, path, "org.freedesktop.DBus.Properties", "Get", error, &reply, "ss", strempty(interface), member);
if (r < 0)
return r;
r = sd_bus_message_enter_container(reply, 'v', NULL);
if (r < 0)
return r;
r = sd_bus_message_read_strv(reply, ret);
if (r < 0)
return r;
return 0;
}
_public_ int sd_bus_set_property(
sd_bus *bus,
const char *destination,
const char *path,
const char *interface,
const char *member,
sd_bus_error *error,
const char *type, ...) {
_cleanup_bus_message_unref_ sd_bus_message *m = NULL;
va_list ap;
int r;
assert_return(bus, -EINVAL);
assert_return(isempty(interface) || interface_name_is_valid(interface), -EINVAL);
assert_return(member_name_is_valid(member), -EINVAL);
assert_return(signature_is_single(type, false), -EINVAL);
assert_return(!bus_pid_changed(bus), -ECHILD);
if (!BUS_IS_OPEN(bus->state))
return -ENOTCONN;
r = sd_bus_message_new_method_call(bus, &m, destination, path, "org.freedesktop.DBus.Properties", "Set");
if (r < 0)
return r;
r = sd_bus_message_append(m, "ss", strempty(interface), member);
if (r < 0)
return r;
r = sd_bus_message_open_container(m, 'v', type);
if (r < 0)
return r;
va_start(ap, type);
r = bus_message_append_ap(m, type, ap);
va_end(ap);
if (r < 0)
return r;
r = sd_bus_message_close_container(m);
if (r < 0)
return r;
return sd_bus_call(bus, m, 0, error, NULL);
}
_public_ int sd_bus_query_sender_creds(sd_bus_message *call, uint64_t mask, sd_bus_creds **creds) {
sd_bus_creds *c;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
c = sd_bus_message_get_creds(call);
/* All data we need? */
if (c && (mask & ~c->mask) == 0) {
*creds = sd_bus_creds_ref(c);
return 0;
}
/* No data passed? Or not enough data passed to retrieve the missing bits? */
if (!c || !(c->mask & SD_BUS_CREDS_PID)) {
/* We couldn't read anything from the call, let's try
* to get it from the sender or peer */
if (call->sender)
return sd_bus_get_name_creds(call->bus, call->sender, mask, creds);
else
return sd_bus_get_owner_creds(call->bus, mask, creds);
}
return bus_creds_extend_by_pid(c, mask, creds);
}
_public_ int sd_bus_query_sender_privilege(sd_bus_message *call, int capability) {
_cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
uid_t our_uid;
bool know_caps = false;
int r;
assert_return(call, -EINVAL);
assert_return(call->sealed, -EPERM);
assert_return(call->bus, -EINVAL);
assert_return(!bus_pid_changed(call->bus), -ECHILD);
if (!BUS_IS_OPEN(call->bus->state))
return -ENOTCONN;
if (capability >= 0) {
r = sd_bus_query_sender_creds(call, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS, &creds);
if (r < 0)
return r;
/* Note that not even on kdbus we might have the caps
* field, due to faked identities, or namespace
* translation issues. */
r = sd_bus_creds_has_effective_cap(creds, capability);
if (r > 0)
return 1;
if (r == 0)
know_caps = true;
} else {
r = sd_bus_query_sender_creds(call, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID, &creds);
if (r < 0)
return r;
}
/* Now, check the UID, but only if the capability check wasn't
* sufficient */
our_uid = getuid();
if (our_uid != 0 || !know_caps || capability < 0) {
uid_t sender_uid;
/* Try to use the EUID, if we have it. */
r = sd_bus_creds_get_euid(creds, &sender_uid);
if (r < 0)
r = sd_bus_creds_get_uid(creds, &sender_uid);
if (r >= 0) {
/* Sender has same UID as us, then let's grant access */
if (sender_uid == our_uid)
return 1;
/* Sender is root, we are not root. */
if (our_uid != 0 && sender_uid == 0)
return 1;
}
}
return 0;
}
|
#ifndef _LINUX_SWAPOPS_H
#define _LINUX_SWAPOPS_H
#include <linux/radix-tree.h>
#include <linux/bug.h>
/*
* swapcache pages are stored in the swapper_space radix tree. We want to
* get good packing density in that tree, so the index should be dense in
* the low-order bits.
*
* We arrange the `type' and `offset' fields so that `type' is at the seven
* high-order bits of the swp_entry_t and `offset' is right-aligned in the
* remaining bits. Although `type' itself needs only five bits, we allow for
* shmem/tmpfs to shift it all up a further two bits: see swp_to_radix_entry().
*
* swp_entry_t's are *never* stored anywhere in their arch-dependent format.
*/
#define SWP_TYPE_SHIFT(e) ((sizeof(e.val) * 8) - \
(MAX_SWAPFILES_SHIFT + RADIX_TREE_EXCEPTIONAL_SHIFT))
#define SWP_OFFSET_MASK(e) ((1UL << SWP_TYPE_SHIFT(e)) - 1)
/*
* Store a type+offset into a swp_entry_t in an arch-independent format
*/
static inline swp_entry_t swp_entry(unsigned long type, pgoff_t offset)
{
swp_entry_t ret;
ret.val = (type << SWP_TYPE_SHIFT(ret)) |
(offset & SWP_OFFSET_MASK(ret));
return ret;
}
/*
* Extract the `type' field from a swp_entry_t. The swp_entry_t is in
* arch-independent format
*/
static inline unsigned swp_type(swp_entry_t entry)
{
return (entry.val >> SWP_TYPE_SHIFT(entry));
}
/*
* Extract the `offset' field from a swp_entry_t. The swp_entry_t is in
* arch-independent format
*/
static inline pgoff_t swp_offset(swp_entry_t entry)
{
return entry.val & SWP_OFFSET_MASK(entry);
}
#ifdef CONFIG_MMU
/* check whether a pte points to a swap entry */
static inline int is_swap_pte(pte_t pte)
{
return !pte_none(pte) && !pte_present(pte);
}
#endif
/*
* Convert the arch-dependent pte representation of a swp_entry_t into an
* arch-independent swp_entry_t.
*/
static inline swp_entry_t pte_to_swp_entry(pte_t pte)
{
swp_entry_t arch_entry;
if (pte_swp_soft_dirty(pte))
pte = pte_swp_clear_soft_dirty(pte);
arch_entry = __pte_to_swp_entry(pte);
return swp_entry(__swp_type(arch_entry), __swp_offset(arch_entry));
}
/*
* Convert the arch-independent representation of a swp_entry_t into the
* arch-dependent pte representation.
*/
static inline pte_t swp_entry_to_pte(swp_entry_t entry)
{
swp_entry_t arch_entry;
arch_entry = __swp_entry(swp_type(entry), swp_offset(entry));
return __swp_entry_to_pte(arch_entry);
}
static inline swp_entry_t radix_to_swp_entry(void *arg)
{
swp_entry_t entry;
entry.val = (unsigned long)arg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
return entry;
}
static inline void *swp_to_radix_entry(swp_entry_t entry)
{
unsigned long value;
value = entry.val << RADIX_TREE_EXCEPTIONAL_SHIFT;
return (void *)(value | RADIX_TREE_EXCEPTIONAL_ENTRY);
}
#if IS_ENABLED(CONFIG_DEVICE_PRIVATE)
static inline swp_entry_t make_device_private_entry(struct page *page, bool write)
{
return swp_entry(write ? SWP_DEVICE_WRITE : SWP_DEVICE_READ,
page_to_pfn(page));
}
static inline bool is_device_private_entry(swp_entry_t entry)
{
int type = swp_type(entry);
return type == SWP_DEVICE_READ || type == SWP_DEVICE_WRITE;
}
static inline void make_device_private_entry_read(swp_entry_t *entry)
{
*entry = swp_entry(SWP_DEVICE_READ, swp_offset(*entry));
}
static inline bool is_write_device_private_entry(swp_entry_t entry)
{
return unlikely(swp_type(entry) == SWP_DEVICE_WRITE);
}
static inline struct page *device_private_entry_to_page(swp_entry_t entry)
{
return pfn_to_page(swp_offset(entry));
}
int device_private_entry_fault(struct vm_area_struct *vma,
unsigned long addr,
swp_entry_t entry,
unsigned int flags,
pmd_t *pmdp);
#else /* CONFIG_DEVICE_PRIVATE */
static inline swp_entry_t make_device_private_entry(struct page *page, bool write)
{
return swp_entry(0, 0);
}
static inline void make_device_private_entry_read(swp_entry_t *entry)
{
}
static inline bool is_device_private_entry(swp_entry_t entry)
{
return false;
}
static inline bool is_write_device_private_entry(swp_entry_t entry)
{
return false;
}
static inline struct page *device_private_entry_to_page(swp_entry_t entry)
{
return NULL;
}
static inline int device_private_entry_fault(struct vm_area_struct *vma,
unsigned long addr,
swp_entry_t entry,
unsigned int flags,
pmd_t *pmdp)
{
return VM_FAULT_SIGBUS;
}
#endif /* CONFIG_DEVICE_PRIVATE */
#ifdef CONFIG_MIGRATION
static inline swp_entry_t make_migration_entry(struct page *page, int write)
{
BUG_ON(!PageLocked(compound_head(page)));
return swp_entry(write ? SWP_MIGRATION_WRITE : SWP_MIGRATION_READ,
page_to_pfn(page));
}
static inline int is_migration_entry(swp_entry_t entry)
{
return unlikely(swp_type(entry) == SWP_MIGRATION_READ ||
swp_type(entry) == SWP_MIGRATION_WRITE);
}
static inline int is_write_migration_entry(swp_entry_t entry)
{
return unlikely(swp_type(entry) == SWP_MIGRATION_WRITE);
}
static inline struct page *migration_entry_to_page(swp_entry_t entry)
{
struct page *p = pfn_to_page(swp_offset(entry));
/*
* Any use of migration entries may only occur while the
* corresponding page is locked
*/
BUG_ON(!PageLocked(compound_head(p)));
return p;
}
static inline void make_migration_entry_read(swp_entry_t *entry)
{
*entry = swp_entry(SWP_MIGRATION_READ, swp_offset(*entry));
}
extern void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
spinlock_t *ptl);
extern void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
unsigned long address);
extern void migration_entry_wait_huge(struct vm_area_struct *vma,
struct mm_struct *mm, pte_t *pte);
#else
#define make_migration_entry(page, write) swp_entry(0, 0)
static inline int is_migration_entry(swp_entry_t swp)
{
return 0;
}
static inline struct page *migration_entry_to_page(swp_entry_t entry)
{
return NULL;
}
static inline void make_migration_entry_read(swp_entry_t *entryp) { }
static inline void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
spinlock_t *ptl) { }
static inline void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
unsigned long address) { }
static inline void migration_entry_wait_huge(struct vm_area_struct *vma,
struct mm_struct *mm, pte_t *pte) { }
static inline int is_write_migration_entry(swp_entry_t entry)
{
return 0;
}
#endif
struct page_vma_mapped_walk;
#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
extern void set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
struct page *page);
extern void remove_migration_pmd(struct page_vma_mapped_walk *pvmw,
struct page *new);
extern void pmd_migration_entry_wait(struct mm_struct *mm, pmd_t *pmd);
static inline swp_entry_t pmd_to_swp_entry(pmd_t pmd)
{
swp_entry_t arch_entry;
if (pmd_swp_soft_dirty(pmd))
pmd = pmd_swp_clear_soft_dirty(pmd);
arch_entry = __pmd_to_swp_entry(pmd);
return swp_entry(__swp_type(arch_entry), __swp_offset(arch_entry));
}
static inline pmd_t swp_entry_to_pmd(swp_entry_t entry)
{
swp_entry_t arch_entry;
arch_entry = __swp_entry(swp_type(entry), swp_offset(entry));
return __swp_entry_to_pmd(arch_entry);
}
static inline int is_pmd_migration_entry(pmd_t pmd)
{
return !pmd_present(pmd) && is_migration_entry(pmd_to_swp_entry(pmd));
}
#else
static inline void set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
struct page *page)
{
BUILD_BUG();
}
static inline void remove_migration_pmd(struct page_vma_mapped_walk *pvmw,
struct page *new)
{
BUILD_BUG();
}
static inline void pmd_migration_entry_wait(struct mm_struct *m, pmd_t *p) { }
static inline swp_entry_t pmd_to_swp_entry(pmd_t pmd)
{
return swp_entry(0, 0);
}
static inline pmd_t swp_entry_to_pmd(swp_entry_t entry)
{
return __pmd(0);
}
static inline int is_pmd_migration_entry(pmd_t pmd)
{
return 0;
}
#endif
#ifdef CONFIG_MEMORY_FAILURE
extern atomic_long_t num_poisoned_pages __read_mostly;
/*
* Support for hardware poisoned pages
*/
static inline swp_entry_t make_hwpoison_entry(struct page *page)
{
BUG_ON(!PageLocked(page));
return swp_entry(SWP_HWPOISON, page_to_pfn(page));
}
static inline int is_hwpoison_entry(swp_entry_t entry)
{
return swp_type(entry) == SWP_HWPOISON;
}
static inline bool test_set_page_hwpoison(struct page *page)
{
return TestSetPageHWPoison(page);
}
static inline void num_poisoned_pages_inc(void)
{
atomic_long_inc(&num_poisoned_pages);
}
static inline void num_poisoned_pages_dec(void)
{
atomic_long_dec(&num_poisoned_pages);
}
#else
static inline swp_entry_t make_hwpoison_entry(struct page *page)
{
return swp_entry(0, 0);
}
static inline int is_hwpoison_entry(swp_entry_t swp)
{
return 0;
}
static inline bool test_set_page_hwpoison(struct page *page)
{
return false;
}
static inline void num_poisoned_pages_inc(void)
{
}
#endif
#if defined(CONFIG_MEMORY_FAILURE) || defined(CONFIG_MIGRATION)
static inline int non_swap_entry(swp_entry_t entry)
{
return swp_type(entry) >= MAX_SWAPFILES;
}
#else
static inline int non_swap_entry(swp_entry_t entry)
{
return 0;
}
#endif
#endif /* _LINUX_SWAPOPS_H */
|
/* Collator.java -- Perform locale dependent String comparisons.
Copyright (C) 1998, 1999, 2000, 2001, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.text;
import gnu.java.locale.LocaleHelper;
import java.text.spi.CollatorProvider;
import java.util.Comparator;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.ServiceLoader;
/**
* This class is the abstract superclass of classes which perform
* locale dependent <code>String</code> comparisons. A caller requests
* an instance of <code>Collator</code> for a particular locale using
* the <code>getInstance()</code> static method in this class. That method
* will return a locale specific subclass of <code>Collator</code> which
* can be used to perform <code>String</code> comparisons for that locale.
* If a subclass of <code>Collator</code> cannot be located for a particular
* locale, a default instance for the current locale will be returned.
*
* In addition to setting the correct locale, there are two additional
* settings that can be adjusted to affect <code>String</code> comparisons:
* strength and decomposition. The strength value determines the level
* of signficance of character differences required for them to sort
* differently. (For example, whether or not capital letters are considered
* different from lower case letters). The decomposition value affects how
* variants of the same character are treated for sorting purposes. (For
* example, whether or not an accent is signficant or not). These settings
* are described in detail in the documentation for the methods and values
* that are related to them.
*
* @author Tom Tromey (tromey@cygnus.com)
* @author Aaron M. Renn (arenn@urbanophile.com)
* @date March 18, 1999
*/
public abstract class Collator implements Comparator<Object>, Cloneable
{
/**
* This constant is a strength value which indicates that only primary
* differences between characters will be considered signficant. As an
* example, two completely different English letters such as 'a' and 'b'
* are considered to have a primary difference.
*/
public static final int PRIMARY = 0;
/**
* This constant is a strength value which indicates that only secondary
* or primary differences between characters will be considered
* significant. An example of a secondary difference between characters
* are instances of the same letter with different accented forms.
*/
public static final int SECONDARY = 1;
/**
* This constant is a strength value which indicates that tertiary,
* secondary, and primary differences will be considered during sorting.
* An example of a tertiary difference is capitalization of a given letter.
* This is the default value for the strength setting.
*/
public static final int TERTIARY = 2;
/**
* This constant is a strength value which indicates that any difference
* at all between character values are considered significant.
*/
public static final int IDENTICAL = 3;
/**
* This constant indicates that accented characters won't be decomposed
* when performing comparisons. This will yield the fastest results, but
* will only work correctly in call cases for languages which do not
* use accents such as English.
*/
public static final int NO_DECOMPOSITION = 0;
/**
* This constant indicates that only characters which are canonical variants
* in Unicode 2.0 will be decomposed prior to performing comparisons. This
* will cause accented languages to be sorted correctly. This is the
* default decomposition value.
*/
public static final int CANONICAL_DECOMPOSITION = 1;
/**
* This constant indicates that both canonical variants and compatibility
* variants in Unicode 2.0 will be decomposed prior to performing
* comparisons. This is the slowest mode, but is required to get the
* correct sorting for certain languages with certain special formats.
*/
public static final int FULL_DECOMPOSITION = 2;
/**
* This method initializes a new instance of <code>Collator</code> to have
* the default strength (TERTIARY) and decomposition
* (CANONICAL_DECOMPOSITION) settings. This constructor is protected and
* is for use by subclasses only. Non-subclass callers should use the
* static <code>getInstance()</code> methods of this class to instantiate
* <code>Collation</code> objects for the desired locale.
*/
protected Collator ()
{
strength = TERTIARY;
decmp = CANONICAL_DECOMPOSITION;
}
/**
* This method compares the two <code>String</code>'s and returns an
* integer indicating whether or not the first argument is less than,
* equal to, or greater than the second argument. The comparison is
* performed according to the rules of the locale for this
* <code>Collator</code> and the strength and decomposition rules in
* effect.
*
* @param source The first object to compare
* @param target The second object to compare
*
* @return A negative integer if str1 < str2, 0 if str1 == str2, or
* a positive integer if str1 > str2.
*/
public abstract int compare (String source, String target);
/**
* This method compares the two <code>Object</code>'s and returns an
* integer indicating whether or not the first argument is less than,
* equal to, or greater than the second argument. These two objects
* must be <code>String</code>'s or an exception will be thrown.
*
* @param o1 The first object to compare
* @param o2 The second object to compare
*
* @return A negative integer if obj1 < obj2, 0 if obj1 == obj2, or
* a positive integer if obj1 > obj2.
*
* @exception ClassCastException If the arguments are not instances
* of <code>String</code>.
*/
public int compare (Object o1, Object o2)
{
return compare ((String) o1, (String) o2);
}
/**
* This method tests the specified object for equality against this
* object. This will be true if and only if the following conditions are
* met:
* <ul>
* <li>The specified object is not <code>null</code>.</li>
* <li>The specified object is an instance of <code>Collator</code>.</li>
* <li>The specified object has the same strength and decomposition
* settings as this object.</li>
* </ul>
*
* @param obj The <code>Object</code> to test for equality against
* this object.
*
* @return <code>true</code> if the specified object is equal to
* this one, <code>false</code> otherwise.
*/
public boolean equals (Object obj)
{
if (! (obj instanceof Collator))
return false;
Collator c = (Collator) obj;
return decmp == c.decmp && strength == c.strength;
}
/**
* This method tests whether the specified <code>String</code>'s are equal
* according to the collation rules for the locale of this object and
* the current strength and decomposition settings.
*
* @param source The first <code>String</code> to compare
* @param target The second <code>String</code> to compare
*
* @return <code>true</code> if the two strings are equal,
* <code>false</code> otherwise.
*/
public boolean equals (String source, String target)
{
return compare (source, target) == 0;
}
/**
* This method returns a copy of this <code>Collator</code> object.
*
* @return A duplicate of this object.
*/
public Object clone ()
{
try
{
return super.clone ();
}
catch (CloneNotSupportedException _)
{
return null;
}
}
/**
* This method returns an array of <code>Locale</code> objects which is
* the list of locales for which <code>Collator</code> objects exist.
*
* @return The list of locales for which <code>Collator</code>'s exist.
*/
public static synchronized Locale[] getAvailableLocales ()
{
return LocaleHelper.getCollatorLocales();
}
/**
* This method transforms the specified <code>String</code> into a
* <code>CollationKey</code> for faster comparisons. This is useful when
* comparisons against a string might be performed multiple times, such
* as during a sort operation.
*
* @param source The <code>String</code> to convert.
*
* @return A <code>CollationKey</code> for the specified <code>String</code>.
*/
public abstract CollationKey getCollationKey (String source);
/**
* This method returns the current decomposition setting for this
* object. This * will be one of NO_DECOMPOSITION,
* CANONICAL_DECOMPOSITION, or * FULL_DECOMPOSITION. See the
* documentation for those constants for an * explanation of this
* setting.
*
* @return The current decomposition setting.
*/
public synchronized int getDecomposition ()
{
return decmp;
}
/**
* This method returns an instance of <code>Collator</code> for the
* default locale.
*
* @return A <code>Collator</code> for the default locale.
*/
public static Collator getInstance ()
{
return getInstance (Locale.getDefault());
}
/**
* This method returns an instance of <code>Collator</code> for the
* specified locale. If no <code>Collator</code> exists for the desired
* locale, the fallback procedure described in
* {@link java.util.spi.LocaleServiceProvider} is invoked.
*
* @param loc The desired locale to load a <code>Collator</code> for.
*
* @return A <code>Collator</code> for the requested locale
*/
public static Collator getInstance (Locale loc)
{
String pattern;
try
{
ResourceBundle res =
ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
loc, ClassLoader.getSystemClassLoader());
return new RuleBasedCollator(res.getString("collation_rules"));
}
catch (MissingResourceException x)
{
/* This means runtime support for the locale
* is not available, so we check providers. */
}
catch (ParseException x)
{
throw (InternalError)new InternalError().initCause(x);
}
for (CollatorProvider p : ServiceLoader.load(CollatorProvider.class))
{
for (Locale l : p.getAvailableLocales())
{
if (l.equals(loc))
{
Collator c = p.getInstance(loc);
if (c != null)
return c;
break;
}
}
}
if (loc.equals(Locale.ROOT))
{
try
{
return new RuleBasedCollator("<0<1<2<3<4<5<6<7<8<9<A,a<b,B<c," +
"C<d,D<e,E<f,F<g,G<h,H<i,I<j,J<k,K" +
"<l,L<m,M<n,N<o,O<p,P<q,Q<r,R<s,S<t,"+
"T<u,U<v,V<w,W<x,X<y,Y<z,Z");
}
catch (ParseException x)
{
throw (InternalError)new InternalError().initCause(x);
}
}
return getInstance(LocaleHelper.getFallbackLocale(loc));
}
/**
* This method returns the current strength setting for this object. This
* will be one of PRIMARY, SECONDARY, TERTIARY, or IDENTICAL. See the
* documentation for those constants for an explanation of this setting.
*
* @return The current strength setting.
*/
public synchronized int getStrength ()
{
return strength;
}
/**
* This method returns a hash code value for this object.
*
* @return A hash value for this object.
*/
public abstract int hashCode ();
/**
* This method sets the decomposition setting for this object to the
* specified value. This must be one of NO_DECOMPOSITION,
* CANONICAL_DECOMPOSITION, or FULL_DECOMPOSITION. Otherwise an
* exception will be thrown. See the documentation for those
* contants for an explanation of this setting.
*
* @param mode The new decomposition setting.
*
* @exception IllegalArgumentException If the requested
* decomposition setting is not valid.
*/
public synchronized void setDecomposition (int mode)
{
if (mode != NO_DECOMPOSITION
&& mode != CANONICAL_DECOMPOSITION
&& mode != FULL_DECOMPOSITION)
throw new IllegalArgumentException ();
decmp = mode;
}
/**
* This method sets the strength setting for this object to the specified
* value. This must be one of PRIMARY, SECONDARY, TERTIARY, or IDENTICAL.
* Otherwise an exception is thrown. See the documentation for these
* constants for an explanation of this setting.
*
* @param strength The new strength setting.
*
* @exception IllegalArgumentException If the requested strength
* setting value is not valid.
*/
public synchronized void setStrength (int strength)
{
if (strength != PRIMARY && strength != SECONDARY
&& strength != TERTIARY && strength != IDENTICAL)
throw new IllegalArgumentException ();
this.strength = strength;
}
// Decompose a single character and append results to the buffer.
// FIXME: for libgcj this is a native method which handles
// decomposition. For Classpath, for now, it does nothing.
/*
final void decomposeCharacter (char c, StringBuffer buf)
{
buf.append (c);
}
*/
/**
* This is the current collation decomposition setting.
*/
int decmp;
/**
* This is the current collation strength setting.
*/
int strength;
}
|
# MSM CPU/CODEC DAI Support
snd-soc-msm-dai-objs := msm-dai.o
obj-$(CONFIG_SND_MSM_DAI_SOC) += snd-soc-msm-dai.o
snd-soc-msm7kv2-dai-objs := msm7kv2-dai.o
obj-$(CONFIG_SND_MSM7KV2_DAI_SOC) += snd-soc-msm7kv2-dai.o
# MSM Platform Support
snd-soc-msm-objs := msm-pcm.o msm7k-pcm.o
obj-$(CONFIG_SND_MSM_SOC) += snd-soc-msm.o
snd-soc-msmv2-objs := msm7kv2-dsp.o msm7kv2-pcm.o
obj-$(CONFIG_SND_MSM7KV2_SOC) += snd-soc-msmv2.o
# MSM Machine Support
snd-soc-msm7k-objs := msm7201.o
obj-$(CONFIG_SND_MSM_SOC_MSM7K) += snd-soc-msm7k.o
snd-soc-msm7kv2-objs := msm7x30.o
obj-$(CONFIG_SND_MSM_SOC_MSM7KV2) += snd-soc-msm7kv2.o
# 8660 ALSA Support
snd-soc-msm8x60-dai-objs := msm8x60-dai.o
obj-$(CONFIG_SND_SOC_MSM8X60_DAI) += snd-soc-msm8x60-dai.o
snd-soc-msm8x60-pcm-objs := msm8x60-pcm.o
obj-$(CONFIG_SND_SOC_MSM8X60_PCM) += snd-soc-msm8x60-pcm.o
snd-soc-msm8x60-objs := msm8x60.o
obj-$(CONFIG_SND_SOC_MSM8X60) += snd-soc-msm8x60.o
#MVS Support
snd-soc-msm-mvs-dai-objs := mvs-dai.o
obj-$(CONFIG_SND_MSM_MVS_DAI_SOC) += snd-soc-msm-mvs-dai.o
snd-soc-msm-mvs-objs := msm-mvs.o
obj-$(CONFIG_SND_MVS_SOC) += snd-soc-msm-mvs.o
# 8660 ALSA Support
snd-soc-lpass-objs := lpass-i2s.o lpass-dma.o
obj-$(CONFIG_SND_SOC_MSM8660_LPAIF) += snd-soc-lpass.o
snd-soc-lpass-pcm-objs := lpass-pcm.o
obj-$(CONFIG_SND_SOC_LPASS_PCM) += snd-soc-lpass-pcm.o
#8660 VOIP Driver Support
snd-soc-msm-voip-objs := msm-voip.o
obj-$(CONFIG_SND_VOIP_PCM) += snd-soc-msm-voip.o
snd-soc-lpass-dma-objs := lpass-dma.o
obj-$(CONFIG_SND_SOC_MSM8X60) += snd-soc-lpass-dma.o
# for MSM 8960 sound card driver
obj-$(CONFIG_SND_SOC_MSM_QDSP6_INTF) += qdsp6/
snd-soc-qdsp6-objs := msm-dai-q6.o msm-pcm-q6.o msm-multi-ch-pcm-q6.o msm-lowlatency-pcm-q6.o msm-pcm-loopback.o msm-pcm-routing.o msm-dai-fe.o msm-compr-q6.o msm-dai-stub.o
obj-$(CONFIG_SND_SOC_MSM_QDSP6_HDMI_AUDIO) += msm-dai-q6-hdmi.o
obj-$(CONFIG_SND_SOC_VOICE) += msm-pcm-voice.o msm-pcm-voip.o
snd-soc-qdsp6-objs += msm-pcm-lpa.o msm-pcm-afe.o
obj-$(CONFIG_SND_SOC_QDSP6) += snd-soc-qdsp6.o
ifdef CONFIG_MACH_M2
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_M2_SKT
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_M2_DCM
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_K2_KDI
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_GOGH
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_INFINITE
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_JASPER
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_AEGIS2
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_COMANCHE
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_EXPRESS
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_STRETTO
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_APEXQ
snd-soc-msm8960-objs := msm8960-apexq.o
else ifdef CONFIG_MACH_SUPERIORLTE_SKT
snd-soc-msm8960-objs := msm8960-d2.o
else ifdef CONFIG_MACH_JAGUAR
snd-soc-msm8960-objs := msm8960-jaguar.o
else
snd-soc-msm8960-objs := msm8960-jaguar.o
endif
obj-$(CONFIG_SND_SOC_MSM8960) += snd-soc-msm8960.o
# Generic MSM drivers
snd-soc-hostless-pcm-objs := msm-pcm-hostless.o
obj-$(CONFIG_SND_SOC_MSM_HOSTLESS_PCM) += snd-soc-hostless-pcm.o
snd-soc-msm8660-apq-objs := msm8660-apq-wm8903.o
obj-$(CONFIG_SND_SOC_MSM8660_APQ) += snd-soc-msm8660-apq.o
# for MDM 9615 sound card driver
snd-soc-mdm9615-objs := mdm9615.o
obj-$(CONFIG_SND_SOC_MDM9615) += snd-soc-mdm9615.o
# for MSM 8974 sound card driver
obj-$(CONFIG_SND_SOC_MSM_QDSP6V2_INTF) += qdsp6v2/
snd-soc-msm8974-objs := msm8974.o
obj-$(CONFIG_SND_SOC_MSM8974) += snd-soc-msm8974.o
snd-soc-qdsp6v2-objs := msm-dai-fe.o msm-dai-stub.o
obj-$(CONFIG_SND_SOC_QDSP6V2) += snd-soc-qdsp6v2.o
|
/*
* 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
*
* Clean ups from Moschip version and a few ioctl implementations by:
* Paul B Schroeder <pschroeder "at" uplogix "dot" com>
*
* Originally based on drivers/usb/serial/io_edgeport.c which is:
* Copyright (C) 2000 Inside Out Networks, All rights reserved.
* Copyright (C) 2001-2002 Greg Kroah-Hartman <greg@kroah.com>
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/serial.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/uaccess.h>
/*
* Version Information
*/
#define DRIVER_VERSION "1.3.1"
#define DRIVER_DESC "Moschip 7840/7820 USB Serial Driver"
/*
* 16C50 UART register defines
*/
#define LCR_BITS_5 0x00 /* 5 bits/char */
#define LCR_BITS_6 0x01 /* 6 bits/char */
#define LCR_BITS_7 0x02 /* 7 bits/char */
#define LCR_BITS_8 0x03 /* 8 bits/char */
#define LCR_BITS_MASK 0x03 /* Mask for bits/char field */
#define LCR_STOP_1 0x00 /* 1 stop bit */
#define LCR_STOP_1_5 0x04 /* 1.5 stop bits (if 5 bits/char) */
#define LCR_STOP_2 0x04 /* 2 stop bits (if 6-8 bits/char) */
#define LCR_STOP_MASK 0x04 /* Mask for stop bits field */
#define LCR_PAR_NONE 0x00 /* No parity */
#define LCR_PAR_ODD 0x08 /* Odd parity */
#define LCR_PAR_EVEN 0x18 /* Even parity */
#define LCR_PAR_MARK 0x28 /* Force parity bit to 1 */
#define LCR_PAR_SPACE 0x38 /* Force parity bit to 0 */
#define LCR_PAR_MASK 0x38 /* Mask for parity field */
#define LCR_SET_BREAK 0x40 /* Set Break condition */
#define LCR_DL_ENABLE 0x80 /* Enable access to divisor latch */
#define MCR_DTR 0x01 /* Assert DTR */
#define MCR_RTS 0x02 /* Assert RTS */
#define MCR_OUT1 0x04 /* Loopback only: Sets state of RI */
#define MCR_MASTER_IE 0x08 /* Enable interrupt outputs */
#define MCR_LOOPBACK 0x10 /* Set internal (digital) loopback mode */
#define MCR_XON_ANY 0x20 /* Enable any char to exit XOFF mode */
#define MOS7840_MSR_CTS 0x10 /* Current state of CTS */
#define MOS7840_MSR_DSR 0x20 /* Current state of DSR */
#define MOS7840_MSR_RI 0x40 /* Current state of RI */
#define MOS7840_MSR_CD 0x80 /* Current state of CD */
/*
* Defines used for sending commands to port
*/
#define WAIT_FOR_EVER (HZ * 0) /* timeout urb is wait for ever */
#define MOS_WDR_TIMEOUT (HZ * 5) /* default urb timeout */
#define MOS_PORT1 0x0200
#define MOS_PORT2 0x0300
#define MOS_VENREG 0x0000
#define MOS_MAX_PORT 0x02
#define MOS_WRITE 0x0E
#define MOS_READ 0x0D
/* Requests */
#define MCS_RD_RTYPE 0xC0
#define MCS_WR_RTYPE 0x40
#define MCS_RDREQ 0x0D
#define MCS_WRREQ 0x0E
#define MCS_CTRL_TIMEOUT 500
#define VENDOR_READ_LENGTH (0x01)
#define MAX_NAME_LEN 64
#define ZLP_REG1 0x3A /* Zero_Flag_Reg1 58 */
#define ZLP_REG5 0x3E /* Zero_Flag_Reg5 62 */
/* For higher baud Rates use TIOCEXBAUD */
#define TIOCEXBAUD 0x5462
/* vendor id and device id defines */
/* The native mos7840/7820 component */
#define USB_VENDOR_ID_MOSCHIP 0x9710
#define MOSCHIP_DEVICE_ID_7840 0x7840
#define MOSCHIP_DEVICE_ID_7820 0x7820
/* The native component can have its vendor/device id's overridden
* in vendor-specific implementations. Such devices can be handled
* by making a change here, in moschip_port_id_table, and in
* moschip_id_table_combined
*/
#define USB_VENDOR_ID_BANDB 0x0856
#define BANDB_DEVICE_ID_USOPTL4_4 0xAC44
#define BANDB_DEVICE_ID_USOPTL4_2 0xAC42
/* Interrupt Routine Defines */
#define SERIAL_IIR_RLS 0x06
#define SERIAL_IIR_MS 0x00
/*
* Emulation of the bit mask on the LINE STATUS REGISTER.
*/
#define SERIAL_LSR_DR 0x0001
#define SERIAL_LSR_OE 0x0002
#define SERIAL_LSR_PE 0x0004
#define SERIAL_LSR_FE 0x0008
#define SERIAL_LSR_BI 0x0010
#define MOS_MSR_DELTA_CTS 0x10
#define MOS_MSR_DELTA_DSR 0x20
#define MOS_MSR_DELTA_RI 0x40
#define MOS_MSR_DELTA_CD 0x80
/* Serial Port register Address */
#define INTERRUPT_ENABLE_REGISTER ((__u16)(0x01))
#define FIFO_CONTROL_REGISTER ((__u16)(0x02))
#define LINE_CONTROL_REGISTER ((__u16)(0x03))
#define MODEM_CONTROL_REGISTER ((__u16)(0x04))
#define LINE_STATUS_REGISTER ((__u16)(0x05))
#define MODEM_STATUS_REGISTER ((__u16)(0x06))
#define SCRATCH_PAD_REGISTER ((__u16)(0x07))
#define DIVISOR_LATCH_LSB ((__u16)(0x00))
#define DIVISOR_LATCH_MSB ((__u16)(0x01))
#define CLK_MULTI_REGISTER ((__u16)(0x02))
#define CLK_START_VALUE_REGISTER ((__u16)(0x03))
#define SERIAL_LCR_DLAB ((__u16)(0x0080))
/*
* URB POOL related defines
*/
#define NUM_URBS 16 /* URB Count */
#define URB_TRANSFER_BUFFER_SIZE 32 /* URB Size */
static struct usb_device_id moschip_port_id_table[] = {
{USB_DEVICE(USB_VENDOR_ID_MOSCHIP, MOSCHIP_DEVICE_ID_7840)},
{USB_DEVICE(USB_VENDOR_ID_MOSCHIP, MOSCHIP_DEVICE_ID_7820)},
{USB_DEVICE(USB_VENDOR_ID_BANDB, BANDB_DEVICE_ID_USOPTL4_4)},
{USB_DEVICE(USB_VENDOR_ID_BANDB, BANDB_DEVICE_ID_USOPTL4_2)},
{} /* terminating entry */
};
static __devinitdata struct usb_device_id moschip_id_table_combined[] = {
{USB_DEVICE(USB_VENDOR_ID_MOSCHIP, MOSCHIP_DEVICE_ID_7840)},
{USB_DEVICE(USB_VENDOR_ID_MOSCHIP, MOSCHIP_DEVICE_ID_7820)},
{USB_DEVICE(USB_VENDOR_ID_BANDB, BANDB_DEVICE_ID_USOPTL4_4)},
{USB_DEVICE(USB_VENDOR_ID_BANDB, BANDB_DEVICE_ID_USOPTL4_2)},
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, moschip_id_table_combined);
/* This structure holds all of the local port information */
struct moschip_port {
int port_num; /*Actual port number in the device(1,2,etc) */
struct urb *write_urb; /* write URB for this port */
struct urb *read_urb; /* read URB for this port */
struct urb *int_urb;
__u8 shadowLCR; /* last LCR value received */
__u8 shadowMCR; /* last MCR value received */
char open;
char open_ports;
char zombie;
wait_queue_head_t wait_chase; /* for handling sleeping while waiting for chase to finish */
wait_queue_head_t delta_msr_wait; /* for handling sleeping while waiting for msr change to happen */
int delta_msr_cond;
struct async_icount icount;
struct usb_serial_port *port; /* loop back to the owner of this object */
/* Offsets */
__u8 SpRegOffset;
__u8 ControlRegOffset;
__u8 DcrRegOffset;
/* for processing control URBS in interrupt context */
struct urb *control_urb;
struct usb_ctrlrequest *dr;
char *ctrl_buf;
int MsrLsr;
spinlock_t pool_lock;
struct urb *write_urb_pool[NUM_URBS];
char busy[NUM_URBS];
};
static int debug;
/*
* mos7840_set_reg_sync
* To set the Control register by calling usb_fill_control_urb function
* by passing usb_sndctrlpipe function as parameter.
*/
static int mos7840_set_reg_sync(struct usb_serial_port *port, __u16 reg,
__u16 val)
{
struct usb_device *dev = port->serial->dev;
val = val & 0x00ff;
dbg("mos7840_set_reg_sync offset is %x, value %x\n", reg, val);
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), MCS_WRREQ,
MCS_WR_RTYPE, val, reg, NULL, 0,
MOS_WDR_TIMEOUT);
}
/*
* mos7840_get_reg_sync
* To set the Uart register by calling usb_fill_control_urb function by
* passing usb_rcvctrlpipe function as parameter.
*/
static int mos7840_get_reg_sync(struct usb_serial_port *port, __u16 reg,
__u16 *val)
{
struct usb_device *dev = port->serial->dev;
int ret = 0;
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), MCS_RDREQ,
MCS_RD_RTYPE, 0, reg, val, VENDOR_READ_LENGTH,
MOS_WDR_TIMEOUT);
dbg("mos7840_get_reg_sync offset is %x, return val %x\n", reg, *val);
*val = (*val) & 0x00ff;
return ret;
}
/*
* mos7840_set_uart_reg
* To set the Uart register by calling usb_fill_control_urb function by
* passing usb_sndctrlpipe function as parameter.
*/
static int mos7840_set_uart_reg(struct usb_serial_port *port, __u16 reg,
__u16 val)
{
struct usb_device *dev = port->serial->dev;
val = val & 0x00ff;
/* For the UART control registers, the application number need
to be Or'ed */
if (port->serial->num_ports == 4) {
val |= (((__u16) port->number -
(__u16) (port->serial->minor)) + 1) << 8;
dbg("mos7840_set_uart_reg application number is %x\n", val);
} else {
if (((__u16) port->number - (__u16) (port->serial->minor)) == 0) {
val |= (((__u16) port->number -
(__u16) (port->serial->minor)) + 1) << 8;
dbg("mos7840_set_uart_reg application number is %x\n",
val);
} else {
val |=
(((__u16) port->number -
(__u16) (port->serial->minor)) + 2) << 8;
dbg("mos7840_set_uart_reg application number is %x\n",
val);
}
}
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), MCS_WRREQ,
MCS_WR_RTYPE, val, reg, NULL, 0,
MOS_WDR_TIMEOUT);
}
/*
* mos7840_get_uart_reg
* To set the Control register by calling usb_fill_control_urb function
* by passing usb_rcvctrlpipe function as parameter.
*/
static int mos7840_get_uart_reg(struct usb_serial_port *port, __u16 reg,
__u16 *val)
{
struct usb_device *dev = port->serial->dev;
int ret = 0;
__u16 Wval;
/* dbg("application number is %4x \n",
(((__u16)port->number - (__u16)(port->serial->minor))+1)<<8); */
/* Wval is same as application number */
if (port->serial->num_ports == 4) {
Wval =
(((__u16) port->number - (__u16) (port->serial->minor)) +
1) << 8;
dbg("mos7840_get_uart_reg application number is %x\n", Wval);
} else {
if (((__u16) port->number - (__u16) (port->serial->minor)) == 0) {
Wval = (((__u16) port->number -
(__u16) (port->serial->minor)) + 1) << 8;
dbg("mos7840_get_uart_reg application number is %x\n",
Wval);
} else {
Wval = (((__u16) port->number -
(__u16) (port->serial->minor)) + 2) << 8;
dbg("mos7840_get_uart_reg application number is %x\n",
Wval);
}
}
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), MCS_RDREQ,
MCS_RD_RTYPE, Wval, reg, val, VENDOR_READ_LENGTH,
MOS_WDR_TIMEOUT);
*val = (*val) & 0x00ff;
return ret;
}
static void mos7840_dump_serial_port(struct moschip_port *mos7840_port)
{
dbg("***************************************\n");
dbg("SpRegOffset is %2x\n", mos7840_port->SpRegOffset);
dbg("ControlRegOffset is %2x \n", mos7840_port->ControlRegOffset);
dbg("DCRRegOffset is %2x \n", mos7840_port->DcrRegOffset);
dbg("***************************************\n");
}
/************************************************************************/
/************************************************************************/
/* I N T E R F A C E F U N C T I O N S */
/* I N T E R F A C E F U N C T I O N S */
/************************************************************************/
/************************************************************************/
static inline void mos7840_set_port_private(struct usb_serial_port *port,
struct moschip_port *data)
{
usb_set_serial_port_data(port, (void *)data);
}
static inline struct moschip_port *mos7840_get_port_private(struct
usb_serial_port
*port)
{
return (struct moschip_port *)usb_get_serial_port_data(port);
}
static void mos7840_handle_new_msr(struct moschip_port *port, __u8 new_msr)
{
struct moschip_port *mos7840_port;
struct async_icount *icount;
mos7840_port = port;
icount = &mos7840_port->icount;
if (new_msr &
(MOS_MSR_DELTA_CTS | MOS_MSR_DELTA_DSR | MOS_MSR_DELTA_RI |
MOS_MSR_DELTA_CD)) {
icount = &mos7840_port->icount;
/* update input line counters */
if (new_msr & MOS_MSR_DELTA_CTS) {
icount->cts++;
smp_wmb();
}
if (new_msr & MOS_MSR_DELTA_DSR) {
icount->dsr++;
smp_wmb();
}
if (new_msr & MOS_MSR_DELTA_CD) {
icount->dcd++;
smp_wmb();
}
if (new_msr & MOS_MSR_DELTA_RI) {
icount->rng++;
smp_wmb();
}
}
}
static void mos7840_handle_new_lsr(struct moschip_port *port, __u8 new_lsr)
{
struct async_icount *icount;
dbg("%s - %02x", __func__, new_lsr);
if (new_lsr & SERIAL_LSR_BI) {
/*
* Parity and Framing errors only count if they
* occur exclusive of a break being
* received.
*/
new_lsr &= (__u8) (SERIAL_LSR_OE | SERIAL_LSR_BI);
}
/* update input line counters */
icount = &port->icount;
if (new_lsr & SERIAL_LSR_BI) {
icount->brk++;
smp_wmb();
}
if (new_lsr & SERIAL_LSR_OE) {
icount->overrun++;
smp_wmb();
}
if (new_lsr & SERIAL_LSR_PE) {
icount->parity++;
smp_wmb();
}
if (new_lsr & SERIAL_LSR_FE) {
icount->frame++;
smp_wmb();
}
}
/************************************************************************/
/************************************************************************/
/* U S B C A L L B A C K F U N C T I O N S */
/* U S B C A L L B A C K F U N C T I O N S */
/************************************************************************/
/************************************************************************/
static void mos7840_control_callback(struct urb *urb)
{
unsigned char *data;
struct moschip_port *mos7840_port;
__u8 regval = 0x0;
int result = 0;
int status = urb->status;
mos7840_port = urb->context;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d", __func__,
status);
return;
default:
dbg("%s - nonzero urb status received: %d", __func__,
status);
goto exit;
}
dbg("%s urb buffer size is %d\n", __func__, urb->actual_length);
dbg("%s mos7840_port->MsrLsr is %d port %d\n", __func__,
mos7840_port->MsrLsr, mos7840_port->port_num);
data = urb->transfer_buffer;
regval = (__u8) data[0];
dbg("%s data is %x\n", __func__, regval);
if (mos7840_port->MsrLsr == 0)
mos7840_handle_new_msr(mos7840_port, regval);
else if (mos7840_port->MsrLsr == 1)
mos7840_handle_new_lsr(mos7840_port, regval);
exit:
spin_lock(&mos7840_port->pool_lock);
if (!mos7840_port->zombie)
result = usb_submit_urb(mos7840_port->int_urb, GFP_ATOMIC);
spin_unlock(&mos7840_port->pool_lock);
if (result) {
dev_err(&urb->dev->dev,
"%s - Error %d submitting interrupt urb\n",
__func__, result);
}
}
static int mos7840_get_reg(struct moschip_port *mcs, __u16 Wval, __u16 reg,
__u16 *val)
{
struct usb_device *dev = mcs->port->serial->dev;
struct usb_ctrlrequest *dr = mcs->dr;
unsigned char *buffer = mcs->ctrl_buf;
int ret;
dr->bRequestType = MCS_RD_RTYPE;
dr->bRequest = MCS_RDREQ;
dr->wValue = cpu_to_le16(Wval); /* 0 */
dr->wIndex = cpu_to_le16(reg);
dr->wLength = cpu_to_le16(2);
usb_fill_control_urb(mcs->control_urb, dev, usb_rcvctrlpipe(dev, 0),
(unsigned char *)dr, buffer, 2,
mos7840_control_callback, mcs);
mcs->control_urb->transfer_buffer_length = 2;
ret = usb_submit_urb(mcs->control_urb, GFP_ATOMIC);
return ret;
}
/*****************************************************************************
* mos7840_interrupt_callback
* this is the callback function for when we have received data on the
* interrupt endpoint.
*****************************************************************************/
static void mos7840_interrupt_callback(struct urb *urb)
{
int result;
int length;
struct moschip_port *mos7840_port;
struct usb_serial *serial;
__u16 Data;
unsigned char *data;
__u8 sp[5], st;
int i, rv = 0;
__u16 wval, wreg = 0;
int status = urb->status;
dbg("%s", " : Entering\n");
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d", __func__,
status);
return;
default:
dbg("%s - nonzero urb status received: %d", __func__,
status);
goto exit;
}
length = urb->actual_length;
data = urb->transfer_buffer;
serial = urb->context;
/* Moschip get 5 bytes
* Byte 1 IIR Port 1 (port.number is 0)
* Byte 2 IIR Port 2 (port.number is 1)
* Byte 3 IIR Port 3 (port.number is 2)
* Byte 4 IIR Port 4 (port.number is 3)
* Byte 5 FIFO status for both */
if (length && length > 5) {
dbg("%s \n", "Wrong data !!!");
return;
}
sp[0] = (__u8) data[0];
sp[1] = (__u8) data[1];
sp[2] = (__u8) data[2];
sp[3] = (__u8) data[3];
st = (__u8) data[4];
for (i = 0; i < serial->num_ports; i++) {
mos7840_port = mos7840_get_port_private(serial->port[i]);
wval =
(((__u16) serial->port[i]->number -
(__u16) (serial->minor)) + 1) << 8;
if (mos7840_port->open) {
if (sp[i] & 0x01) {
dbg("SP%d No Interrupt !!!\n", i);
} else {
switch (sp[i] & 0x0f) {
case SERIAL_IIR_RLS:
dbg("Serial Port %d: Receiver status error or ", i);
dbg("address bit detected in 9-bit mode\n");
mos7840_port->MsrLsr = 1;
wreg = LINE_STATUS_REGISTER;
break;
case SERIAL_IIR_MS:
dbg("Serial Port %d: Modem status change\n", i);
mos7840_port->MsrLsr = 0;
wreg = MODEM_STATUS_REGISTER;
break;
}
spin_lock(&mos7840_port->pool_lock);
if (!mos7840_port->zombie) {
rv = mos7840_get_reg(mos7840_port, wval, wreg, &Data);
} else {
spin_unlock(&mos7840_port->pool_lock);
return;
}
spin_unlock(&mos7840_port->pool_lock);
}
}
}
if (!(rv < 0))
/* the completion handler for the control urb will resubmit */
return;
exit:
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result) {
dev_err(&urb->dev->dev,
"%s - Error %d submitting interrupt urb\n",
__func__, result);
}
}
static int mos7840_port_paranoia_check(struct usb_serial_port *port,
const char *function)
{
if (!port) {
dbg("%s - port == NULL", function);
return -1;
}
if (!port->serial) {
dbg("%s - port->serial == NULL", function);
return -1;
}
return 0;
}
/* Inline functions to check the sanity of a pointer that is passed to us */
static int mos7840_serial_paranoia_check(struct usb_serial *serial,
const char *function)
{
if (!serial) {
dbg("%s - serial == NULL", function);
return -1;
}
if (!serial->type) {
dbg("%s - serial->type == NULL!", function);
return -1;
}
return 0;
}
static struct usb_serial *mos7840_get_usb_serial(struct usb_serial_port *port,
const char *function)
{
/* if no port was specified, or it fails a paranoia check */
if (!port ||
mos7840_port_paranoia_check(port, function) ||
mos7840_serial_paranoia_check(port->serial, function)) {
/* then say that we don't have a valid usb_serial thing,
* which will end up genrating -ENODEV return values */
return NULL;
}
return port->serial;
}
/*****************************************************************************
* mos7840_bulk_in_callback
* this is the callback function for when we have received data on the
* bulk in endpoint.
*****************************************************************************/
static void mos7840_bulk_in_callback(struct urb *urb)
{
int retval;
unsigned char *data;
struct usb_serial *serial;
struct usb_serial_port *port;
struct moschip_port *mos7840_port;
struct tty_struct *tty;
int status = urb->status;
if (status) {
dbg("nonzero read bulk status received: %d", status);
return;
}
mos7840_port = urb->context;
if (!mos7840_port) {
dbg("%s", "NULL mos7840_port pointer \n");
return;
}
port = (struct usb_serial_port *)mos7840_port->port;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Port Paranoia failed \n");
return;
}
serial = mos7840_get_usb_serial(port, __func__);
if (!serial) {
dbg("%s\n", "Bad serial pointer ");
return;
}
dbg("%s\n", "Entering... \n");
data = urb->transfer_buffer;
dbg("%s", "Entering ........... \n");
if (urb->actual_length) {
tty = mos7840_port->port->port.tty;
if (tty) {
tty_buffer_request_room(tty, urb->actual_length);
tty_insert_flip_string(tty, data, urb->actual_length);
dbg(" %s \n", data);
tty_flip_buffer_push(tty);
}
mos7840_port->icount.rx += urb->actual_length;
smp_wmb();
dbg("mos7840_port->icount.rx is %d:\n",
mos7840_port->icount.rx);
}
if (!mos7840_port->read_urb) {
dbg("%s", "URB KILLED !!!\n");
return;
}
mos7840_port->read_urb->dev = serial->dev;
retval = usb_submit_urb(mos7840_port->read_urb, GFP_ATOMIC);
if (retval) {
dbg(" usb_submit_urb(read bulk) failed, retval = %d",
retval);
}
}
/*****************************************************************************
* mos7840_bulk_out_data_callback
* this is the callback function for when we have finished sending
* serial data on the bulk out endpoint.
*****************************************************************************/
static void mos7840_bulk_out_data_callback(struct urb *urb)
{
struct moschip_port *mos7840_port;
struct tty_struct *tty;
int status = urb->status;
int i;
mos7840_port = urb->context;
spin_lock(&mos7840_port->pool_lock);
for (i = 0; i < NUM_URBS; i++) {
if (urb == mos7840_port->write_urb_pool[i]) {
mos7840_port->busy[i] = 0;
break;
}
}
spin_unlock(&mos7840_port->pool_lock);
if (status) {
dbg("nonzero write bulk status received:%d\n", status);
return;
}
if (mos7840_port_paranoia_check(mos7840_port->port, __func__)) {
dbg("%s", "Port Paranoia failed \n");
return;
}
dbg("%s \n", "Entering .........");
tty = mos7840_port->port->port.tty;
if (tty && mos7840_port->open)
tty_wakeup(tty);
}
/************************************************************************/
/* D R I V E R T T Y I N T E R F A C E F U N C T I O N S */
/************************************************************************/
#ifdef MCSSerialProbe
static int mos7840_serial_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
/*need to implement the mode_reg reading and updating\
structures usb_serial_ device_type\
(i.e num_ports, num_bulkin,bulkout etc) */
/* Also we can update the changes attach */
return 1;
}
#endif
/*****************************************************************************
* mos7840_open
* this function is called by the tty driver when a port is opened
* If successful, we return 0
* Otherwise we return a negative error number.
*****************************************************************************/
static int mos7840_open(struct tty_struct *tty,
struct usb_serial_port *port, struct file *filp)
{
int response;
int j;
struct usb_serial *serial;
struct urb *urb;
__u16 Data;
int status;
struct moschip_port *mos7840_port;
struct moschip_port *port0;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Port Paranoia failed \n");
return -ENODEV;
}
serial = port->serial;
if (mos7840_serial_paranoia_check(serial, __func__)) {
dbg("%s", "Serial Paranoia failed \n");
return -ENODEV;
}
mos7840_port = mos7840_get_port_private(port);
port0 = mos7840_get_port_private(serial->port[0]);
if (mos7840_port == NULL || port0 == NULL)
return -ENODEV;
usb_clear_halt(serial->dev, port->write_urb->pipe);
usb_clear_halt(serial->dev, port->read_urb->pipe);
port0->open_ports++;
/* Initialising the write urb pool */
for (j = 0; j < NUM_URBS; ++j) {
urb = usb_alloc_urb(0, GFP_KERNEL);
mos7840_port->write_urb_pool[j] = urb;
if (urb == NULL) {
err("No more urbs???");
continue;
}
urb->transfer_buffer = kmalloc(URB_TRANSFER_BUFFER_SIZE,
GFP_KERNEL);
if (!urb->transfer_buffer) {
usb_free_urb(urb);
mos7840_port->write_urb_pool[j] = NULL;
err("%s-out of memory for urb buffers.", __func__);
continue;
}
}
/*****************************************************************************
* Initialize MCS7840 -- Write Init values to corresponding Registers
*
* Register Index
* 1 : IER
* 2 : FCR
* 3 : LCR
* 4 : MCR
*
* 0x08 : SP1/2 Control Reg
*****************************************************************************/
/* NEED to check the following Block */
Data = 0x0;
status = mos7840_get_reg_sync(port, mos7840_port->SpRegOffset, &Data);
if (status < 0) {
dbg("Reading Spreg failed\n");
return -1;
}
Data |= 0x80;
status = mos7840_set_reg_sync(port, mos7840_port->SpRegOffset, Data);
if (status < 0) {
dbg("writing Spreg failed\n");
return -1;
}
Data &= ~0x80;
status = mos7840_set_reg_sync(port, mos7840_port->SpRegOffset, Data);
if (status < 0) {
dbg("writing Spreg failed\n");
return -1;
}
/* End of block to be checked */
Data = 0x0;
status = mos7840_get_reg_sync(port, mos7840_port->ControlRegOffset,
&Data);
if (status < 0) {
dbg("Reading Controlreg failed\n");
return -1;
}
Data |= 0x08; /* Driver done bit */
Data |= 0x20; /* rx_disable */
status = mos7840_set_reg_sync(port,
mos7840_port->ControlRegOffset, Data);
if (status < 0) {
dbg("writing Controlreg failed\n");
return -1;
}
/* do register settings here */
/* Set all regs to the device default values. */
/***********************************
* First Disable all interrupts.
***********************************/
Data = 0x00;
status = mos7840_set_uart_reg(port, INTERRUPT_ENABLE_REGISTER, Data);
if (status < 0) {
dbg("disableing interrupts failed\n");
return -1;
}
/* Set FIFO_CONTROL_REGISTER to the default value */
Data = 0x00;
status = mos7840_set_uart_reg(port, FIFO_CONTROL_REGISTER, Data);
if (status < 0) {
dbg("Writing FIFO_CONTROL_REGISTER failed\n");
return -1;
}
Data = 0xcf;
status = mos7840_set_uart_reg(port, FIFO_CONTROL_REGISTER, Data);
if (status < 0) {
dbg("Writing FIFO_CONTROL_REGISTER failed\n");
return -1;
}
Data = 0x03;
status = mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
mos7840_port->shadowLCR = Data;
Data = 0x0b;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, Data);
mos7840_port->shadowMCR = Data;
Data = 0x00;
status = mos7840_get_uart_reg(port, LINE_CONTROL_REGISTER, &Data);
mos7840_port->shadowLCR = Data;
Data |= SERIAL_LCR_DLAB; /* data latch enable in LCR 0x80 */
status = mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
Data = 0x0c;
status = mos7840_set_uart_reg(port, DIVISOR_LATCH_LSB, Data);
Data = 0x0;
status = mos7840_set_uart_reg(port, DIVISOR_LATCH_MSB, Data);
Data = 0x00;
status = mos7840_get_uart_reg(port, LINE_CONTROL_REGISTER, &Data);
Data = Data & ~SERIAL_LCR_DLAB;
status = mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
mos7840_port->shadowLCR = Data;
/* clearing Bulkin and Bulkout Fifo */
Data = 0x0;
status = mos7840_get_reg_sync(port, mos7840_port->SpRegOffset, &Data);
Data = Data | 0x0c;
status = mos7840_set_reg_sync(port, mos7840_port->SpRegOffset, Data);
Data = Data & ~0x0c;
status = mos7840_set_reg_sync(port, mos7840_port->SpRegOffset, Data);
/* Finally enable all interrupts */
Data = 0x0c;
status = mos7840_set_uart_reg(port, INTERRUPT_ENABLE_REGISTER, Data);
/* clearing rx_disable */
Data = 0x0;
status = mos7840_get_reg_sync(port, mos7840_port->ControlRegOffset,
&Data);
Data = Data & ~0x20;
status = mos7840_set_reg_sync(port, mos7840_port->ControlRegOffset,
Data);
/* rx_negate */
Data = 0x0;
status = mos7840_get_reg_sync(port, mos7840_port->ControlRegOffset,
&Data);
Data = Data | 0x10;
status = mos7840_set_reg_sync(port, mos7840_port->ControlRegOffset,
Data);
/* force low_latency on so that our tty_push actually forces *
* the data through,otherwise it is scheduled, and with *
* high data rates (like with OHCI) data can get lost. */
if (tty)
tty->low_latency = 1;
/* Check to see if we've set up our endpoint info yet *
* (can't set it up in mos7840_startup as the structures *
* were not set up at that time.) */
if (port0->open_ports == 1) {
if (serial->port[0]->interrupt_in_buffer == NULL) {
/* set up interrupt urb */
usb_fill_int_urb(serial->port[0]->interrupt_in_urb,
serial->dev,
usb_rcvintpipe(serial->dev,
serial->port[0]->interrupt_in_endpointAddress),
serial->port[0]->interrupt_in_buffer,
serial->port[0]->interrupt_in_urb->
transfer_buffer_length,
mos7840_interrupt_callback,
serial,
serial->port[0]->interrupt_in_urb->interval);
/* start interrupt read for mos7840 *
* will continue as long as mos7840 is connected */
response =
usb_submit_urb(serial->port[0]->interrupt_in_urb,
GFP_KERNEL);
if (response) {
err("%s - Error %d submitting interrupt urb",
__func__, response);
}
}
}
/* see if we've set up our endpoint info yet *
* (can't set it up in mos7840_startup as the *
* structures were not set up at that time.) */
dbg("port number is %d \n", port->number);
dbg("serial number is %d \n", port->serial->minor);
dbg("Bulkin endpoint is %d \n", port->bulk_in_endpointAddress);
dbg("BulkOut endpoint is %d \n", port->bulk_out_endpointAddress);
dbg("Interrupt endpoint is %d \n", port->interrupt_in_endpointAddress);
dbg("port's number in the device is %d\n", mos7840_port->port_num);
mos7840_port->read_urb = port->read_urb;
/* set up our bulk in urb */
usb_fill_bulk_urb(mos7840_port->read_urb,
serial->dev,
usb_rcvbulkpipe(serial->dev,
port->bulk_in_endpointAddress),
port->bulk_in_buffer,
mos7840_port->read_urb->transfer_buffer_length,
mos7840_bulk_in_callback, mos7840_port);
dbg("mos7840_open: bulkin endpoint is %d\n",
port->bulk_in_endpointAddress);
response = usb_submit_urb(mos7840_port->read_urb, GFP_KERNEL);
if (response) {
err("%s - Error %d submitting control urb", __func__,
response);
}
/* initialize our wait queues */
init_waitqueue_head(&mos7840_port->wait_chase);
init_waitqueue_head(&mos7840_port->delta_msr_wait);
/* initialize our icount structure */
memset(&(mos7840_port->icount), 0x00, sizeof(mos7840_port->icount));
/* initialize our port settings */
/* Must set to enable ints! */
mos7840_port->shadowMCR = MCR_MASTER_IE;
/* send a open port command */
mos7840_port->open = 1;
/* mos7840_change_port_settings(mos7840_port,old_termios); */
mos7840_port->icount.tx = 0;
mos7840_port->icount.rx = 0;
dbg("\n\nusb_serial serial:%p mos7840_port:%p\n usb_serial_port port:%p\n\n",
serial, mos7840_port, port);
return 0;
}
/*****************************************************************************
* mos7840_chars_in_buffer
* this function is called by the tty driver when it wants to know how many
* bytes of data we currently have outstanding in the port (data that has
* been written, but hasn't made it out the port yet)
* If successful, we return the number of bytes left to be written in the
* system,
* Otherwise we return zero.
*****************************************************************************/
static int mos7840_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
int i;
int chars = 0;
unsigned long flags;
struct moschip_port *mos7840_port;
dbg("%s \n", " mos7840_chars_in_buffer:entering ...........");
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return 0;
}
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL) {
dbg("%s \n", "mos7840_break:leaving ...........");
return 0;
}
spin_lock_irqsave(&mos7840_port->pool_lock, flags);
for (i = 0; i < NUM_URBS; ++i)
if (mos7840_port->busy[i])
chars += URB_TRANSFER_BUFFER_SIZE;
spin_unlock_irqrestore(&mos7840_port->pool_lock, flags);
dbg("%s - returns %d", __func__, chars);
return chars;
}
/************************************************************************
*
* mos7840_block_until_tx_empty
*
* This function will block the close until one of the following:
* 1. TX count are 0
* 2. The mos7840 has stopped
* 3. A timeout of 3 seconds without activity has expired
*
************************************************************************/
static void mos7840_block_until_tx_empty(struct tty_struct *tty,
struct moschip_port *mos7840_port)
{
int timeout = HZ / 10;
int wait = 30;
int count;
while (1) {
count = mos7840_chars_in_buffer(tty);
/* Check for Buffer status */
if (count <= 0)
return;
/* Block the thread for a while */
interruptible_sleep_on_timeout(&mos7840_port->wait_chase,
timeout);
/* No activity.. count down section */
wait--;
if (wait == 0) {
dbg("%s - TIMEOUT", __func__);
return;
} else {
/* Reset timeout value back to seconds */
wait = 30;
}
}
}
/*****************************************************************************
* mos7840_close
* this function is called by the tty driver when a port is closed
*****************************************************************************/
static void mos7840_close(struct tty_struct *tty,
struct usb_serial_port *port, struct file *filp)
{
struct usb_serial *serial;
struct moschip_port *mos7840_port;
struct moschip_port *port0;
int j;
__u16 Data;
dbg("%s\n", "mos7840_close:entering...");
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Port Paranoia failed \n");
return;
}
serial = mos7840_get_usb_serial(port, __func__);
if (!serial) {
dbg("%s", "Serial Paranoia failed \n");
return;
}
mos7840_port = mos7840_get_port_private(port);
port0 = mos7840_get_port_private(serial->port[0]);
if (mos7840_port == NULL || port0 == NULL)
return;
for (j = 0; j < NUM_URBS; ++j)
usb_kill_urb(mos7840_port->write_urb_pool[j]);
/* Freeing Write URBs */
for (j = 0; j < NUM_URBS; ++j) {
if (mos7840_port->write_urb_pool[j]) {
if (mos7840_port->write_urb_pool[j]->transfer_buffer)
kfree(mos7840_port->write_urb_pool[j]->
transfer_buffer);
usb_free_urb(mos7840_port->write_urb_pool[j]);
}
}
if (serial->dev)
/* flush and block until tx is empty */
mos7840_block_until_tx_empty(tty, mos7840_port);
/* While closing port, shutdown all bulk read, write *
* and interrupt read if they exists */
if (serial->dev) {
if (mos7840_port->write_urb) {
dbg("%s", "Shutdown bulk write\n");
usb_kill_urb(mos7840_port->write_urb);
}
if (mos7840_port->read_urb) {
dbg("%s", "Shutdown bulk read\n");
usb_kill_urb(mos7840_port->read_urb);
}
if ((&mos7840_port->control_urb)) {
dbg("%s", "Shutdown control read\n");
/*/ usb_kill_urb (mos7840_port->control_urb); */
}
}
/* if(mos7840_port->ctrl_buf != NULL) */
/* kfree(mos7840_port->ctrl_buf); */
port0->open_ports--;
dbg("mos7840_num_open_ports in close%d:in port%d\n",
port0->open_ports, port->number);
if (port0->open_ports == 0) {
if (serial->port[0]->interrupt_in_urb) {
dbg("%s", "Shutdown interrupt_in_urb\n");
usb_kill_urb(serial->port[0]->interrupt_in_urb);
}
}
if (mos7840_port->write_urb) {
/* if this urb had a transfer buffer already (old tx) free it */
if (mos7840_port->write_urb->transfer_buffer != NULL)
kfree(mos7840_port->write_urb->transfer_buffer);
usb_free_urb(mos7840_port->write_urb);
}
Data = 0x0;
mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, Data);
Data = 0x00;
mos7840_set_uart_reg(port, INTERRUPT_ENABLE_REGISTER, Data);
mos7840_port->open = 0;
dbg("%s \n", "Leaving ............");
}
/************************************************************************
*
* mos7840_block_until_chase_response
*
* This function will block the close until one of the following:
* 1. Response to our Chase comes from mos7840
* 2. A timeout of 10 seconds without activity has expired
* (1K of mos7840 data @ 2400 baud ==> 4 sec to empty)
*
************************************************************************/
static void mos7840_block_until_chase_response(struct tty_struct *tty,
struct moschip_port *mos7840_port)
{
int timeout = 1 * HZ;
int wait = 10;
int count;
while (1) {
count = mos7840_chars_in_buffer(tty);
/* Check for Buffer status */
if (count <= 0)
return;
/* Block the thread for a while */
interruptible_sleep_on_timeout(&mos7840_port->wait_chase,
timeout);
/* No activity.. count down section */
wait--;
if (wait == 0) {
dbg("%s - TIMEOUT", __func__);
return;
} else {
/* Reset timeout value back to seconds */
wait = 10;
}
}
}
/*****************************************************************************
* mos7840_break
* this function sends a break to the port
*****************************************************************************/
static void mos7840_break(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
unsigned char data;
struct usb_serial *serial;
struct moschip_port *mos7840_port;
dbg("%s \n", "Entering ...........");
dbg("mos7840_break: Start\n");
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Port Paranoia failed \n");
return;
}
serial = mos7840_get_usb_serial(port, __func__);
if (!serial) {
dbg("%s", "Serial Paranoia failed \n");
return;
}
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL)
return;
if (serial->dev)
/* flush and block until tx is empty */
mos7840_block_until_chase_response(tty, mos7840_port);
if (break_state == -1)
data = mos7840_port->shadowLCR | LCR_SET_BREAK;
else
data = mos7840_port->shadowLCR & ~LCR_SET_BREAK;
mos7840_port->shadowLCR = data;
dbg("mcs7840_break mos7840_port->shadowLCR is %x\n",
mos7840_port->shadowLCR);
mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER,
mos7840_port->shadowLCR);
return;
}
/*****************************************************************************
* mos7840_write_room
* this function is called by the tty driver when it wants to know how many
* bytes of data we can accept for a specific port.
* If successful, we return the amount of room that we have for this port
* Otherwise we return a negative error number.
*****************************************************************************/
static int mos7840_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
int i;
int room = 0;
unsigned long flags;
struct moschip_port *mos7840_port;
dbg("%s \n", " mos7840_write_room:entering ...........");
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
dbg("%s \n", " mos7840_write_room:leaving ...........");
return -1;
}
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL) {
dbg("%s \n", "mos7840_break:leaving ...........");
return -1;
}
spin_lock_irqsave(&mos7840_port->pool_lock, flags);
for (i = 0; i < NUM_URBS; ++i) {
if (!mos7840_port->busy[i])
room += URB_TRANSFER_BUFFER_SIZE;
}
spin_unlock_irqrestore(&mos7840_port->pool_lock, flags);
room = (room == 0) ? 0 : room - URB_TRANSFER_BUFFER_SIZE + 1;
dbg("%s - returns %d", __func__, room);
return room;
}
/*****************************************************************************
* mos7840_write
* this function is called by the tty driver when data should be written to
* the port.
* If successful, we return the number of bytes written, otherwise we
* return a negative error number.
*****************************************************************************/
static int mos7840_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *data, int count)
{
int status;
int i;
int bytes_sent = 0;
int transfer_size;
unsigned long flags;
struct moschip_port *mos7840_port;
struct usb_serial *serial;
struct urb *urb;
/* __u16 Data; */
const unsigned char *current_position = data;
unsigned char *data1;
dbg("%s \n", "entering ...........");
/* dbg("mos7840_write: mos7840_port->shadowLCR is %x\n",
mos7840_port->shadowLCR); */
#ifdef NOTMOS7840
Data = 0x00;
status = mos7840_get_uart_reg(port, LINE_CONTROL_REGISTER, &Data);
mos7840_port->shadowLCR = Data;
dbg("mos7840_write: LINE_CONTROL_REGISTER is %x\n", Data);
dbg("mos7840_write: mos7840_port->shadowLCR is %x\n",
mos7840_port->shadowLCR);
/* Data = 0x03; */
/* status = mos7840_set_uart_reg(port,LINE_CONTROL_REGISTER,Data); */
/* mos7840_port->shadowLCR=Data;//Need to add later */
Data |= SERIAL_LCR_DLAB; /* data latch enable in LCR 0x80 */
status = mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
/* Data = 0x0c; */
/* status = mos7840_set_uart_reg(port,DIVISOR_LATCH_LSB,Data); */
Data = 0x00;
status = mos7840_get_uart_reg(port, DIVISOR_LATCH_LSB, &Data);
dbg("mos7840_write:DLL value is %x\n", Data);
Data = 0x0;
status = mos7840_get_uart_reg(port, DIVISOR_LATCH_MSB, &Data);
dbg("mos7840_write:DLM value is %x\n", Data);
Data = Data & ~SERIAL_LCR_DLAB;
dbg("mos7840_write: mos7840_port->shadowLCR is %x\n",
mos7840_port->shadowLCR);
status = mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
#endif
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Port Paranoia failed \n");
return -1;
}
serial = port->serial;
if (mos7840_serial_paranoia_check(serial, __func__)) {
dbg("%s", "Serial Paranoia failed \n");
return -1;
}
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL) {
dbg("%s", "mos7840_port is NULL\n");
return -1;
}
/* try to find a free urb in the list */
urb = NULL;
spin_lock_irqsave(&mos7840_port->pool_lock, flags);
for (i = 0; i < NUM_URBS; ++i) {
if (!mos7840_port->busy[i]) {
mos7840_port->busy[i] = 1;
urb = mos7840_port->write_urb_pool[i];
dbg("\nURB:%d", i);
break;
}
}
spin_unlock_irqrestore(&mos7840_port->pool_lock, flags);
if (urb == NULL) {
dbg("%s - no more free urbs", __func__);
goto exit;
}
if (urb->transfer_buffer == NULL) {
urb->transfer_buffer =
kmalloc(URB_TRANSFER_BUFFER_SIZE, GFP_KERNEL);
if (urb->transfer_buffer == NULL) {
err("%s no more kernel memory...", __func__);
goto exit;
}
}
transfer_size = min(count, URB_TRANSFER_BUFFER_SIZE);
memcpy(urb->transfer_buffer, current_position, transfer_size);
/* fill urb with data and submit */
usb_fill_bulk_urb(urb,
serial->dev,
usb_sndbulkpipe(serial->dev,
port->bulk_out_endpointAddress),
urb->transfer_buffer,
transfer_size,
mos7840_bulk_out_data_callback, mos7840_port);
data1 = urb->transfer_buffer;
dbg("\nbulkout endpoint is %d", port->bulk_out_endpointAddress);
/* send it down the pipe */
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status) {
mos7840_port->busy[i] = 0;
err("%s - usb_submit_urb(write bulk) failed with status = %d",
__func__, status);
bytes_sent = status;
goto exit;
}
bytes_sent = transfer_size;
mos7840_port->icount.tx += transfer_size;
smp_wmb();
dbg("mos7840_port->icount.tx is %d:\n", mos7840_port->icount.tx);
exit:
return bytes_sent;
}
/*****************************************************************************
* mos7840_throttle
* this function is called by the tty driver when it wants to stop the data
* being read from the port.
*****************************************************************************/
static void mos7840_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7840_port;
int status;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return;
}
dbg("- port %d\n", port->number);
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL)
return;
if (!mos7840_port->open) {
dbg("%s\n", "port not opened");
return;
}
dbg("%s", "Entering .......... \n");
/* if we are implementing XON/XOFF, send the stop character */
if (I_IXOFF(tty)) {
unsigned char stop_char = STOP_CHAR(tty);
status = mos7840_write(tty, port, &stop_char, 1);
if (status <= 0)
return;
}
/* if we are implementing RTS/CTS, toggle that line */
if (tty->termios->c_cflag & CRTSCTS) {
mos7840_port->shadowMCR &= ~MCR_RTS;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER,
mos7840_port->shadowMCR);
if (status < 0)
return;
}
return;
}
/*****************************************************************************
* mos7840_unthrottle
* this function is called by the tty driver when it wants to resume
* the data being read from the port (called after mos7840_throttle is
* called)
*****************************************************************************/
static void mos7840_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
int status;
struct moschip_port *mos7840_port = mos7840_get_port_private(port);
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return;
}
if (mos7840_port == NULL)
return;
if (!mos7840_port->open) {
dbg("%s - port not opened", __func__);
return;
}
dbg("%s", "Entering .......... \n");
/* if we are implementing XON/XOFF, send the start character */
if (I_IXOFF(tty)) {
unsigned char start_char = START_CHAR(tty);
status = mos7840_write(tty, port, &start_char, 1);
if (status <= 0)
return;
}
/* if we are implementing RTS/CTS, toggle that line */
if (tty->termios->c_cflag & CRTSCTS) {
mos7840_port->shadowMCR |= MCR_RTS;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER,
mos7840_port->shadowMCR);
if (status < 0)
return;
}
}
static int mos7840_tiocmget(struct tty_struct *tty, struct file *file)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7840_port;
unsigned int result;
__u16 msr;
__u16 mcr;
int status;
mos7840_port = mos7840_get_port_private(port);
dbg("%s - port %d", __func__, port->number);
if (mos7840_port == NULL)
return -ENODEV;
status = mos7840_get_uart_reg(port, MODEM_STATUS_REGISTER, &msr);
status = mos7840_get_uart_reg(port, MODEM_CONTROL_REGISTER, &mcr);
result = ((mcr & MCR_DTR) ? TIOCM_DTR : 0)
| ((mcr & MCR_RTS) ? TIOCM_RTS : 0)
| ((mcr & MCR_LOOPBACK) ? TIOCM_LOOP : 0)
| ((msr & MOS7840_MSR_CTS) ? TIOCM_CTS : 0)
| ((msr & MOS7840_MSR_CD) ? TIOCM_CAR : 0)
| ((msr & MOS7840_MSR_RI) ? TIOCM_RI : 0)
| ((msr & MOS7840_MSR_DSR) ? TIOCM_DSR : 0);
dbg("%s - 0x%04X", __func__, result);
return result;
}
static int mos7840_tiocmset(struct tty_struct *tty, struct file *file,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7840_port;
unsigned int mcr;
int status;
dbg("%s - port %d", __func__, port->number);
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL)
return -ENODEV;
/* FIXME: What locks the port registers ? */
mcr = mos7840_port->shadowMCR;
if (clear & TIOCM_RTS)
mcr &= ~MCR_RTS;
if (clear & TIOCM_DTR)
mcr &= ~MCR_DTR;
if (clear & TIOCM_LOOP)
mcr &= ~MCR_LOOPBACK;
if (set & TIOCM_RTS)
mcr |= MCR_RTS;
if (set & TIOCM_DTR)
mcr |= MCR_DTR;
if (set & TIOCM_LOOP)
mcr |= MCR_LOOPBACK;
mos7840_port->shadowMCR = mcr;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, mcr);
if (status < 0) {
dbg("setting MODEM_CONTROL_REGISTER Failed\n");
return status;
}
return 0;
}
/*****************************************************************************
* mos7840_calc_baud_rate_divisor
* this function calculates the proper baud rate divisor for the specified
* baud rate.
*****************************************************************************/
static int mos7840_calc_baud_rate_divisor(int baudRate, int *divisor,
__u16 *clk_sel_val)
{
dbg("%s - %d", __func__, baudRate);
if (baudRate <= 115200) {
*divisor = 115200 / baudRate;
*clk_sel_val = 0x0;
}
if ((baudRate > 115200) && (baudRate <= 230400)) {
*divisor = 230400 / baudRate;
*clk_sel_val = 0x10;
} else if ((baudRate > 230400) && (baudRate <= 403200)) {
*divisor = 403200 / baudRate;
*clk_sel_val = 0x20;
} else if ((baudRate > 403200) && (baudRate <= 460800)) {
*divisor = 460800 / baudRate;
*clk_sel_val = 0x30;
} else if ((baudRate > 460800) && (baudRate <= 806400)) {
*divisor = 806400 / baudRate;
*clk_sel_val = 0x40;
} else if ((baudRate > 806400) && (baudRate <= 921600)) {
*divisor = 921600 / baudRate;
*clk_sel_val = 0x50;
} else if ((baudRate > 921600) && (baudRate <= 1572864)) {
*divisor = 1572864 / baudRate;
*clk_sel_val = 0x60;
} else if ((baudRate > 1572864) && (baudRate <= 3145728)) {
*divisor = 3145728 / baudRate;
*clk_sel_val = 0x70;
}
return 0;
#ifdef NOTMCS7840
for (i = 0; i < ARRAY_SIZE(mos7840_divisor_table); i++) {
if (mos7840_divisor_table[i].BaudRate == baudrate) {
*divisor = mos7840_divisor_table[i].Divisor;
return 0;
}
}
/* After trying for all the standard baud rates *
* Try calculating the divisor for this baud rate */
if (baudrate > 75 && baudrate < 230400) {
/* get the divisor */
custom = (__u16) (230400L / baudrate);
/* Check for round off */
round1 = (__u16) (2304000L / baudrate);
round = (__u16) (round1 - (custom * 10));
if (round > 4)
custom++;
*divisor = custom;
dbg(" Baud %d = %d\n", baudrate, custom);
return 0;
}
dbg("%s\n", " Baud calculation Failed...");
return -1;
#endif
}
/*****************************************************************************
* mos7840_send_cmd_write_baud_rate
* this function sends the proper command to change the baud rate of the
* specified port.
*****************************************************************************/
static int mos7840_send_cmd_write_baud_rate(struct moschip_port *mos7840_port,
int baudRate)
{
int divisor = 0;
int status;
__u16 Data;
unsigned char number;
__u16 clk_sel_val;
struct usb_serial_port *port;
if (mos7840_port == NULL)
return -1;
port = (struct usb_serial_port *)mos7840_port->port;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return -1;
}
if (mos7840_serial_paranoia_check(port->serial, __func__)) {
dbg("%s", "Invalid Serial \n");
return -1;
}
dbg("%s", "Entering .......... \n");
number = mos7840_port->port->number - mos7840_port->port->serial->minor;
dbg("%s - port = %d, baud = %d", __func__,
mos7840_port->port->number, baudRate);
/* reset clk_uart_sel in spregOffset */
if (baudRate > 115200) {
#ifdef HW_flow_control
/* NOTE: need to see the pther register to modify */
/* setting h/w flow control bit to 1 */
Data = 0x2b;
mos7840_port->shadowMCR = Data;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER,
Data);
if (status < 0) {
dbg("Writing spreg failed in set_serial_baud\n");
return -1;
}
#endif
} else {
#ifdef HW_flow_control
/ *setting h/w flow control bit to 0 */
Data = 0xb;
mos7840_port->shadowMCR = Data;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER,
Data);
if (status < 0) {
dbg("Writing spreg failed in set_serial_baud\n");
return -1;
}
#endif
}
if (1) { /* baudRate <= 115200) */
clk_sel_val = 0x0;
Data = 0x0;
status = mos7840_calc_baud_rate_divisor(baudRate, &divisor,
&clk_sel_val);
status = mos7840_get_reg_sync(port, mos7840_port->SpRegOffset,
&Data);
if (status < 0) {
dbg("reading spreg failed in set_serial_baud\n");
return -1;
}
Data = (Data & 0x8f) | clk_sel_val;
status = mos7840_set_reg_sync(port, mos7840_port->SpRegOffset,
Data);
if (status < 0) {
dbg("Writing spreg failed in set_serial_baud\n");
return -1;
}
/* Calculate the Divisor */
if (status) {
err("%s - bad baud rate", __func__);
dbg("%s\n", "bad baud rate");
return status;
}
/* Enable access to divisor latch */
Data = mos7840_port->shadowLCR | SERIAL_LCR_DLAB;
mos7840_port->shadowLCR = Data;
mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
/* Write the divisor */
Data = (unsigned char)(divisor & 0xff);
dbg("set_serial_baud Value to write DLL is %x\n", Data);
mos7840_set_uart_reg(port, DIVISOR_LATCH_LSB, Data);
Data = (unsigned char)((divisor & 0xff00) >> 8);
dbg("set_serial_baud Value to write DLM is %x\n", Data);
mos7840_set_uart_reg(port, DIVISOR_LATCH_MSB, Data);
/* Disable access to divisor latch */
Data = mos7840_port->shadowLCR & ~SERIAL_LCR_DLAB;
mos7840_port->shadowLCR = Data;
mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
}
return status;
}
/*****************************************************************************
* mos7840_change_port_settings
* This routine is called to set the UART on the device to match
* the specified new settings.
*****************************************************************************/
static void mos7840_change_port_settings(struct tty_struct *tty,
struct moschip_port *mos7840_port, struct ktermios *old_termios)
{
int baud;
unsigned cflag;
unsigned iflag;
__u8 lData;
__u8 lParity;
__u8 lStop;
int status;
__u16 Data;
struct usb_serial_port *port;
struct usb_serial *serial;
if (mos7840_port == NULL)
return;
port = (struct usb_serial_port *)mos7840_port->port;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return;
}
if (mos7840_serial_paranoia_check(port->serial, __func__)) {
dbg("%s", "Invalid Serial \n");
return;
}
serial = port->serial;
dbg("%s - port %d", __func__, mos7840_port->port->number);
if (!mos7840_port->open) {
dbg("%s - port not opened", __func__);
return;
}
dbg("%s", "Entering .......... \n");
lData = LCR_BITS_8;
lStop = LCR_STOP_1;
lParity = LCR_PAR_NONE;
cflag = tty->termios->c_cflag;
iflag = tty->termios->c_iflag;
/* Change the number of bits */
if (cflag & CSIZE) {
switch (cflag & CSIZE) {
case CS5:
lData = LCR_BITS_5;
break;
case CS6:
lData = LCR_BITS_6;
break;
case CS7:
lData = LCR_BITS_7;
break;
default:
case CS8:
lData = LCR_BITS_8;
break;
}
}
/* Change the Parity bit */
if (cflag & PARENB) {
if (cflag & PARODD) {
lParity = LCR_PAR_ODD;
dbg("%s - parity = odd", __func__);
} else {
lParity = LCR_PAR_EVEN;
dbg("%s - parity = even", __func__);
}
} else {
dbg("%s - parity = none", __func__);
}
if (cflag & CMSPAR)
lParity = lParity | 0x20;
/* Change the Stop bit */
if (cflag & CSTOPB) {
lStop = LCR_STOP_2;
dbg("%s - stop bits = 2", __func__);
} else {
lStop = LCR_STOP_1;
dbg("%s - stop bits = 1", __func__);
}
/* Update the LCR with the correct value */
mos7840_port->shadowLCR &=
~(LCR_BITS_MASK | LCR_STOP_MASK | LCR_PAR_MASK);
mos7840_port->shadowLCR |= (lData | lParity | lStop);
dbg("mos7840_change_port_settings mos7840_port->shadowLCR is %x\n",
mos7840_port->shadowLCR);
/* Disable Interrupts */
Data = 0x00;
mos7840_set_uart_reg(port, INTERRUPT_ENABLE_REGISTER, Data);
Data = 0x00;
mos7840_set_uart_reg(port, FIFO_CONTROL_REGISTER, Data);
Data = 0xcf;
mos7840_set_uart_reg(port, FIFO_CONTROL_REGISTER, Data);
/* Send the updated LCR value to the mos7840 */
Data = mos7840_port->shadowLCR;
mos7840_set_uart_reg(port, LINE_CONTROL_REGISTER, Data);
Data = 0x00b;
mos7840_port->shadowMCR = Data;
mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, Data);
Data = 0x00b;
mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, Data);
/* set up the MCR register and send it to the mos7840 */
mos7840_port->shadowMCR = MCR_MASTER_IE;
if (cflag & CBAUD)
mos7840_port->shadowMCR |= (MCR_DTR | MCR_RTS);
if (cflag & CRTSCTS)
mos7840_port->shadowMCR |= (MCR_XON_ANY);
else
mos7840_port->shadowMCR &= ~(MCR_XON_ANY);
Data = mos7840_port->shadowMCR;
mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, Data);
/* Determine divisor based on baud rate */
baud = tty_get_baud_rate(tty);
if (!baud) {
/* pick a default, any default... */
dbg("%s\n", "Picked default baud...");
baud = 9600;
}
dbg("%s - baud rate = %d", __func__, baud);
status = mos7840_send_cmd_write_baud_rate(mos7840_port, baud);
/* Enable Interrupts */
Data = 0x0c;
mos7840_set_uart_reg(port, INTERRUPT_ENABLE_REGISTER, Data);
if (mos7840_port->read_urb->status != -EINPROGRESS) {
mos7840_port->read_urb->dev = serial->dev;
status = usb_submit_urb(mos7840_port->read_urb, GFP_ATOMIC);
if (status) {
dbg(" usb_submit_urb(read bulk) failed, status = %d",
status);
}
}
wake_up(&mos7840_port->delta_msr_wait);
mos7840_port->delta_msr_cond = 1;
dbg("mos7840_change_port_settings mos7840_port->shadowLCR is End %x\n",
mos7840_port->shadowLCR);
return;
}
/*****************************************************************************
* mos7840_set_termios
* this function is called by the tty driver when it wants to change
* the termios structure
*****************************************************************************/
static void mos7840_set_termios(struct tty_struct *tty,
struct usb_serial_port *port,
struct ktermios *old_termios)
{
int status;
unsigned int cflag;
struct usb_serial *serial;
struct moschip_port *mos7840_port;
dbg("mos7840_set_termios: START\n");
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return;
}
serial = port->serial;
if (mos7840_serial_paranoia_check(serial, __func__)) {
dbg("%s", "Invalid Serial \n");
return;
}
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL)
return;
if (!mos7840_port->open) {
dbg("%s - port not opened", __func__);
return;
}
dbg("%s\n", "setting termios - ");
cflag = tty->termios->c_cflag;
dbg("%s - clfag %08x iflag %08x", __func__,
tty->termios->c_cflag, RELEVANT_IFLAG(tty->termios->c_iflag));
dbg("%s - old clfag %08x old iflag %08x", __func__,
old_termios->c_cflag, RELEVANT_IFLAG(old_termios->c_iflag));
dbg("%s - port %d", __func__, port->number);
/* change the port settings to the new ones specified */
mos7840_change_port_settings(tty, mos7840_port, old_termios);
if (!mos7840_port->read_urb) {
dbg("%s", "URB KILLED !!!!!\n");
return;
}
if (mos7840_port->read_urb->status != -EINPROGRESS) {
mos7840_port->read_urb->dev = serial->dev;
status = usb_submit_urb(mos7840_port->read_urb, GFP_ATOMIC);
if (status) {
dbg(" usb_submit_urb(read bulk) failed, status = %d",
status);
}
}
return;
}
/*****************************************************************************
* mos7840_get_lsr_info - get line status register info
*
* Purpose: Let user call ioctl() to get info when the UART physically
* is emptied. On bus types like RS485, the transmitter must
* release the bus after transmitting. This must be done when
* the transmit shift register is empty, not be done when the
* transmit holding register is empty. This functionality
* allows an RS485 driver to be written in user space.
*****************************************************************************/
static int mos7840_get_lsr_info(struct tty_struct *tty,
unsigned int __user *value)
{
int count;
unsigned int result = 0;
count = mos7840_chars_in_buffer(tty);
if (count == 0) {
dbg("%s -- Empty", __func__);
result = TIOCSER_TEMT;
}
if (copy_to_user(value, &result, sizeof(int)))
return -EFAULT;
return 0;
}
/*****************************************************************************
* mos7840_set_modem_info
* function to set modem info
*****************************************************************************/
/* FIXME: Should be using the model control hooks */
static int mos7840_set_modem_info(struct moschip_port *mos7840_port,
unsigned int cmd, unsigned int __user *value)
{
unsigned int mcr;
unsigned int arg;
__u16 Data;
int status;
struct usb_serial_port *port;
if (mos7840_port == NULL)
return -1;
port = (struct usb_serial_port *)mos7840_port->port;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return -1;
}
mcr = mos7840_port->shadowMCR;
if (copy_from_user(&arg, value, sizeof(int)))
return -EFAULT;
switch (cmd) {
case TIOCMBIS:
if (arg & TIOCM_RTS)
mcr |= MCR_RTS;
if (arg & TIOCM_DTR)
mcr |= MCR_RTS;
if (arg & TIOCM_LOOP)
mcr |= MCR_LOOPBACK;
break;
case TIOCMBIC:
if (arg & TIOCM_RTS)
mcr &= ~MCR_RTS;
if (arg & TIOCM_DTR)
mcr &= ~MCR_RTS;
if (arg & TIOCM_LOOP)
mcr &= ~MCR_LOOPBACK;
break;
case TIOCMSET:
/* turn off the RTS and DTR and LOOPBACK
* and then only turn on what was asked to */
mcr &= ~(MCR_RTS | MCR_DTR | MCR_LOOPBACK);
mcr |= ((arg & TIOCM_RTS) ? MCR_RTS : 0);
mcr |= ((arg & TIOCM_DTR) ? MCR_DTR : 0);
mcr |= ((arg & TIOCM_LOOP) ? MCR_LOOPBACK : 0);
break;
}
mos7840_port->shadowMCR = mcr;
Data = mos7840_port->shadowMCR;
status = mos7840_set_uart_reg(port, MODEM_CONTROL_REGISTER, Data);
if (status < 0) {
dbg("setting MODEM_CONTROL_REGISTER Failed\n");
return -1;
}
return 0;
}
/*****************************************************************************
* mos7840_get_modem_info
* function to get modem info
*****************************************************************************/
static int mos7840_get_modem_info(struct moschip_port *mos7840_port,
unsigned int __user *value)
{
unsigned int result = 0;
__u16 msr;
unsigned int mcr = mos7840_port->shadowMCR;
mos7840_get_uart_reg(mos7840_port->port,
MODEM_STATUS_REGISTER, &msr);
result = ((mcr & MCR_DTR) ? TIOCM_DTR : 0) /* 0x002 */
|((mcr & MCR_RTS) ? TIOCM_RTS : 0) /* 0x004 */
|((msr & MOS7840_MSR_CTS) ? TIOCM_CTS : 0) /* 0x020 */
|((msr & MOS7840_MSR_CD) ? TIOCM_CAR : 0) /* 0x040 */
|((msr & MOS7840_MSR_RI) ? TIOCM_RI : 0) /* 0x080 */
|((msr & MOS7840_MSR_DSR) ? TIOCM_DSR : 0); /* 0x100 */
dbg("%s -- %x", __func__, result);
if (copy_to_user(value, &result, sizeof(int)))
return -EFAULT;
return 0;
}
/*****************************************************************************
* mos7840_get_serial_info
* function to get information about serial port
*****************************************************************************/
static int mos7840_get_serial_info(struct moschip_port *mos7840_port,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp;
if (mos7840_port == NULL)
return -1;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.type = PORT_16550A;
tmp.line = mos7840_port->port->serial->minor;
tmp.port = mos7840_port->port->number;
tmp.irq = 0;
tmp.flags = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ;
tmp.xmit_fifo_size = NUM_URBS * URB_TRANSFER_BUFFER_SIZE;
tmp.baud_base = 9600;
tmp.close_delay = 5 * HZ;
tmp.closing_wait = 30 * HZ;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
/*****************************************************************************
* SerialIoctl
* this function handles any ioctl calls to the driver
*****************************************************************************/
static int mos7840_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
void __user *argp = (void __user *)arg;
struct moschip_port *mos7840_port;
struct async_icount cnow;
struct async_icount cprev;
struct serial_icounter_struct icount;
int mosret = 0;
if (mos7840_port_paranoia_check(port, __func__)) {
dbg("%s", "Invalid port \n");
return -1;
}
mos7840_port = mos7840_get_port_private(port);
if (mos7840_port == NULL)
return -1;
dbg("%s - port %d, cmd = 0x%x", __func__, port->number, cmd);
switch (cmd) {
/* return number of bytes available */
case TIOCSERGETLSR:
dbg("%s (%d) TIOCSERGETLSR", __func__, port->number);
return mos7840_get_lsr_info(tty, argp);
return 0;
/* FIXME: use the modem hooks and remove this */
case TIOCMBIS:
case TIOCMBIC:
case TIOCMSET:
dbg("%s (%d) TIOCMSET/TIOCMBIC/TIOCMSET", __func__,
port->number);
mosret =
mos7840_set_modem_info(mos7840_port, cmd, argp);
return mosret;
case TIOCMGET:
dbg("%s (%d) TIOCMGET", __func__, port->number);
return mos7840_get_modem_info(mos7840_port, argp);
case TIOCGSERIAL:
dbg("%s (%d) TIOCGSERIAL", __func__, port->number);
return mos7840_get_serial_info(mos7840_port, argp);
case TIOCSSERIAL:
dbg("%s (%d) TIOCSSERIAL", __func__, port->number);
break;
case TIOCMIWAIT:
dbg("%s (%d) TIOCMIWAIT", __func__, port->number);
cprev = mos7840_port->icount;
while (1) {
/* interruptible_sleep_on(&mos7840_port->delta_msr_wait); */
mos7840_port->delta_msr_cond = 0;
wait_event_interruptible(mos7840_port->delta_msr_wait,
(mos7840_port->
delta_msr_cond == 1));
/* see if a signal did it */
if (signal_pending(current))
return -ERESTARTSYS;
cnow = mos7840_port->icount;
smp_rmb();
if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
cnow.dcd == cprev.dcd && cnow.cts == cprev.cts)
return -EIO; /* no change => error */
if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||
((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
return 0;
}
cprev = cnow;
}
/* NOTREACHED */
break;
case TIOCGICOUNT:
cnow = mos7840_port->icount;
smp_rmb();
icount.cts = cnow.cts;
icount.dsr = cnow.dsr;
icount.rng = cnow.rng;
icount.dcd = cnow.dcd;
icount.rx = cnow.rx;
icount.tx = cnow.tx;
icount.frame = cnow.frame;
icount.overrun = cnow.overrun;
icount.parity = cnow.parity;
icount.brk = cnow.brk;
icount.buf_overrun = cnow.buf_overrun;
dbg("%s (%d) TIOCGICOUNT RX=%d, TX=%d", __func__,
port->number, icount.rx, icount.tx);
if (copy_to_user(argp, &icount, sizeof(icount)))
return -EFAULT;
return 0;
default:
break;
}
return -ENOIOCTLCMD;
}
static int mos7840_calc_num_ports(struct usb_serial *serial)
{
int mos7840_num_ports = 0;
dbg("numberofendpoints: %d \n",
(int)serial->interface->cur_altsetting->desc.bNumEndpoints);
dbg("numberofendpoints: %d \n",
(int)serial->interface->altsetting->desc.bNumEndpoints);
if (serial->interface->cur_altsetting->desc.bNumEndpoints == 5) {
mos7840_num_ports = serial->num_ports = 2;
} else if (serial->interface->cur_altsetting->desc.bNumEndpoints == 9) {
serial->num_bulk_in = 4;
serial->num_bulk_out = 4;
mos7840_num_ports = serial->num_ports = 4;
}
return mos7840_num_ports;
}
/****************************************************************************
* mos7840_startup
****************************************************************************/
static int mos7840_startup(struct usb_serial *serial)
{
struct moschip_port *mos7840_port;
struct usb_device *dev;
int i, status;
__u16 Data;
dbg("%s \n", " mos7840_startup :entering..........");
if (!serial) {
dbg("%s\n", "Invalid Handler");
return -1;
}
dev = serial->dev;
dbg("%s\n", "Entering...");
/* we set up the pointers to the endpoints in the mos7840_open *
* function, as the structures aren't created yet. */
/* set up port private structures */
for (i = 0; i < serial->num_ports; ++i) {
mos7840_port = kzalloc(sizeof(struct moschip_port), GFP_KERNEL);
if (mos7840_port == NULL) {
err("%s - Out of memory", __func__);
status = -ENOMEM;
i--; /* don't follow NULL pointer cleaning up */
goto error;
}
/* Initialize all port interrupt end point to port 0 int
* endpoint. Our device has only one interrupt end point
* common to all port */
mos7840_port->port = serial->port[i];
mos7840_set_port_private(serial->port[i], mos7840_port);
spin_lock_init(&mos7840_port->pool_lock);
mos7840_port->port_num = ((serial->port[i]->number -
(serial->port[i]->serial->minor)) +
1);
if (mos7840_port->port_num == 1) {
mos7840_port->SpRegOffset = 0x0;
mos7840_port->ControlRegOffset = 0x1;
mos7840_port->DcrRegOffset = 0x4;
} else if ((mos7840_port->port_num == 2)
&& (serial->num_ports == 4)) {
mos7840_port->SpRegOffset = 0x8;
mos7840_port->ControlRegOffset = 0x9;
mos7840_port->DcrRegOffset = 0x16;
} else if ((mos7840_port->port_num == 2)
&& (serial->num_ports == 2)) {
mos7840_port->SpRegOffset = 0xa;
mos7840_port->ControlRegOffset = 0xb;
mos7840_port->DcrRegOffset = 0x19;
} else if ((mos7840_port->port_num == 3)
&& (serial->num_ports == 4)) {
mos7840_port->SpRegOffset = 0xa;
mos7840_port->ControlRegOffset = 0xb;
mos7840_port->DcrRegOffset = 0x19;
} else if ((mos7840_port->port_num == 4)
&& (serial->num_ports == 4)) {
mos7840_port->SpRegOffset = 0xc;
mos7840_port->ControlRegOffset = 0xd;
mos7840_port->DcrRegOffset = 0x1c;
}
mos7840_dump_serial_port(mos7840_port);
mos7840_set_port_private(serial->port[i], mos7840_port);
/* enable rx_disable bit in control register */
status = mos7840_get_reg_sync(serial->port[i],
mos7840_port->ControlRegOffset, &Data);
if (status < 0) {
dbg("Reading ControlReg failed status-0x%x\n", status);
break;
} else
dbg("ControlReg Reading success val is %x, status%d\n",
Data, status);
Data |= 0x08; /* setting driver done bit */
Data |= 0x04; /* sp1_bit to have cts change reflect in
modem status reg */
/* Data |= 0x20; //rx_disable bit */
status = mos7840_set_reg_sync(serial->port[i],
mos7840_port->ControlRegOffset, Data);
if (status < 0) {
dbg("Writing ControlReg failed(rx_disable) status-0x%x\n", status);
break;
} else
dbg("ControlReg Writing success(rx_disable) status%d\n",
status);
/* Write default values in DCR (i.e 0x01 in DCR0, 0x05 in DCR2
and 0x24 in DCR3 */
Data = 0x01;
status = mos7840_set_reg_sync(serial->port[i],
(__u16) (mos7840_port->DcrRegOffset + 0), Data);
if (status < 0) {
dbg("Writing DCR0 failed status-0x%x\n", status);
break;
} else
dbg("DCR0 Writing success status%d\n", status);
Data = 0x05;
status = mos7840_set_reg_sync(serial->port[i],
(__u16) (mos7840_port->DcrRegOffset + 1), Data);
if (status < 0) {
dbg("Writing DCR1 failed status-0x%x\n", status);
break;
} else
dbg("DCR1 Writing success status%d\n", status);
Data = 0x24;
status = mos7840_set_reg_sync(serial->port[i],
(__u16) (mos7840_port->DcrRegOffset + 2), Data);
if (status < 0) {
dbg("Writing DCR2 failed status-0x%x\n", status);
break;
} else
dbg("DCR2 Writing success status%d\n", status);
/* write values in clkstart0x0 and clkmulti 0x20 */
Data = 0x0;
status = mos7840_set_reg_sync(serial->port[i],
CLK_START_VALUE_REGISTER, Data);
if (status < 0) {
dbg("Writing CLK_START_VALUE_REGISTER failed status-0x%x\n", status);
break;
} else
dbg("CLK_START_VALUE_REGISTER Writing success status%d\n", status);
Data = 0x20;
status = mos7840_set_reg_sync(serial->port[i],
CLK_MULTI_REGISTER, Data);
if (status < 0) {
dbg("Writing CLK_MULTI_REGISTER failed status-0x%x\n",
status);
goto error;
} else
dbg("CLK_MULTI_REGISTER Writing success status%d\n",
status);
/* write value 0x0 to scratchpad register */
Data = 0x00;
status = mos7840_set_uart_reg(serial->port[i],
SCRATCH_PAD_REGISTER, Data);
if (status < 0) {
dbg("Writing SCRATCH_PAD_REGISTER failed status-0x%x\n",
status);
break;
} else
dbg("SCRATCH_PAD_REGISTER Writing success status%d\n",
status);
/* Zero Length flag register */
if ((mos7840_port->port_num != 1)
&& (serial->num_ports == 2)) {
Data = 0xff;
status = mos7840_set_reg_sync(serial->port[i],
(__u16) (ZLP_REG1 +
((__u16)mos7840_port->port_num)), Data);
dbg("ZLIP offset%x\n",
(__u16) (ZLP_REG1 +
((__u16) mos7840_port->port_num)));
if (status < 0) {
dbg("Writing ZLP_REG%d failed status-0x%x\n",
i + 2, status);
break;
} else
dbg("ZLP_REG%d Writing success status%d\n",
i + 2, status);
} else {
Data = 0xff;
status = mos7840_set_reg_sync(serial->port[i],
(__u16) (ZLP_REG1 +
((__u16)mos7840_port->port_num) - 0x1), Data);
dbg("ZLIP offset%x\n",
(__u16) (ZLP_REG1 +
((__u16) mos7840_port->port_num) - 0x1));
if (status < 0) {
dbg("Writing ZLP_REG%d failed status-0x%x\n",
i + 1, status);
break;
} else
dbg("ZLP_REG%d Writing success status%d\n",
i + 1, status);
}
mos7840_port->control_urb = usb_alloc_urb(0, GFP_KERNEL);
mos7840_port->ctrl_buf = kmalloc(16, GFP_KERNEL);
mos7840_port->dr = kmalloc(sizeof(struct usb_ctrlrequest),
GFP_KERNEL);
if (!mos7840_port->control_urb || !mos7840_port->ctrl_buf ||
!mos7840_port->dr) {
status = -ENOMEM;
goto error;
}
}
/* Zero Length flag enable */
Data = 0x0f;
status = mos7840_set_reg_sync(serial->port[0], ZLP_REG5, Data);
if (status < 0) {
dbg("Writing ZLP_REG5 failed status-0x%x\n", status);
goto error;
} else
dbg("ZLP_REG5 Writing success status%d\n", status);
/* setting configuration feature to one */
usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
(__u8) 0x03, 0x00, 0x01, 0x00, NULL, 0x00, 5 * HZ);
return 0;
error:
for (/* nothing */; i >= 0; i--) {
mos7840_port = mos7840_get_port_private(serial->port[i]);
kfree(mos7840_port->dr);
kfree(mos7840_port->ctrl_buf);
usb_free_urb(mos7840_port->control_urb);
kfree(mos7840_port);
serial->port[i] = NULL;
}
return status;
}
/****************************************************************************
* mos7840_shutdown
* This function is called whenever the device is removed from the usb bus.
****************************************************************************/
static void mos7840_shutdown(struct usb_serial *serial)
{
int i;
unsigned long flags;
struct moschip_port *mos7840_port;
dbg("%s \n", " shutdown :entering..........");
if (!serial) {
dbg("%s", "Invalid Handler \n");
return;
}
/* check for the ports to be closed,close the ports and disconnect */
/* free private structure allocated for serial port *
* stop reads and writes on all ports */
for (i = 0; i < serial->num_ports; ++i) {
mos7840_port = mos7840_get_port_private(serial->port[i]);
spin_lock_irqsave(&mos7840_port->pool_lock, flags);
mos7840_port->zombie = 1;
spin_unlock_irqrestore(&mos7840_port->pool_lock, flags);
usb_kill_urb(mos7840_port->control_urb);
kfree(mos7840_port->ctrl_buf);
kfree(mos7840_port->dr);
kfree(mos7840_port);
mos7840_set_port_private(serial->port[i], NULL);
}
dbg("%s\n", "Thank u :: ");
}
static struct usb_driver io_driver = {
.name = "mos7840",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = moschip_id_table_combined,
.no_dynamic_id = 1,
};
static struct usb_serial_driver moschip7840_4port_device = {
.driver = {
.owner = THIS_MODULE,
.name = "mos7840",
},
.description = DRIVER_DESC,
.usb_driver = &io_driver,
.id_table = moschip_port_id_table,
.num_ports = 4,
.open = mos7840_open,
.close = mos7840_close,
.write = mos7840_write,
.write_room = mos7840_write_room,
.chars_in_buffer = mos7840_chars_in_buffer,
.throttle = mos7840_throttle,
.unthrottle = mos7840_unthrottle,
.calc_num_ports = mos7840_calc_num_ports,
#ifdef MCSSerialProbe
.probe = mos7840_serial_probe,
#endif
.ioctl = mos7840_ioctl,
.set_termios = mos7840_set_termios,
.break_ctl = mos7840_break,
.tiocmget = mos7840_tiocmget,
.tiocmset = mos7840_tiocmset,
.attach = mos7840_startup,
.shutdown = mos7840_shutdown,
.read_bulk_callback = mos7840_bulk_in_callback,
.read_int_callback = mos7840_interrupt_callback,
};
/****************************************************************************
* moschip7840_init
* This is called by the module subsystem, or on startup to initialize us
****************************************************************************/
static int __init moschip7840_init(void)
{
int retval;
dbg("%s \n", " mos7840_init :entering..........");
/* Register with the usb serial */
retval = usb_serial_register(&moschip7840_4port_device);
if (retval)
goto failed_port_device_register;
dbg("%s\n", "Entring...");
info(DRIVER_DESC " " DRIVER_VERSION);
/* Register with the usb */
retval = usb_register(&io_driver);
if (retval == 0) {
dbg("%s\n", "Leaving...");
return 0;
}
usb_serial_deregister(&moschip7840_4port_device);
failed_port_device_register:
return retval;
}
/****************************************************************************
* moschip7840_exit
* Called when the driver is about to be unloaded.
****************************************************************************/
static void __exit moschip7840_exit(void)
{
dbg("%s \n", " mos7840_exit :entering..........");
usb_deregister(&io_driver);
usb_serial_deregister(&moschip7840_4port_device);
dbg("%s\n", "Entring...");
}
module_init(moschip7840_init);
module_exit(moschip7840_exit);
/* Module information */
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Session
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Abstract.php 24594 2012-01-05 21:27:01Z matthew $
* @since Preview Release 0.2
*/
/**
* Zend_Session_Abstract
*
* @category Zend
* @package Zend_Session
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Session_Abstract
{
/**
* Whether or not session permits writing (modification of $_SESSION[])
*
* @var bool
*/
protected static $_writable = false;
/**
* Whether or not session permits reading (reading data in $_SESSION[])
*
* @var bool
*/
protected static $_readable = false;
/**
* Since expiring data is handled at startup to avoid __destruct difficulties,
* the data that will be expiring at end of this request is held here
*
* @var array
*/
protected static $_expiringData = array();
/**
* Error message thrown when an action requires modification,
* but current Zend_Session has been marked as read-only.
*/
const _THROW_NOT_WRITABLE_MSG = 'Zend_Session is currently marked as read-only.';
/**
* Error message thrown when an action requires reading session data,
* but current Zend_Session is not marked as readable.
*/
const _THROW_NOT_READABLE_MSG = 'Zend_Session is not marked as readable.';
/**
* namespaceIsset() - check to see if a namespace or a variable within a namespace is set
*
* @param string $namespace
* @param string $name
* @return bool
*/
protected static function _namespaceIsset($namespace, $name = null)
{
if (self::$_readable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG);
}
if ($name === null) {
return ( isset($_SESSION[$namespace]) || isset(self::$_expiringData[$namespace]) );
} else {
return ( isset($_SESSION[$namespace][$name]) || isset(self::$_expiringData[$namespace][$name]) );
}
}
/**
* namespaceUnset() - unset a namespace or a variable within a namespace
*
* @param string $namespace
* @param string $name
* @throws Zend_Session_Exception
* @return void
*/
protected static function _namespaceUnset($namespace, $name = null)
{
if (self::$_writable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_WRITABLE_MSG);
}
$name = (string) $name;
// check to see if the api wanted to remove a var from a namespace or a namespace
if ($name === '') {
unset($_SESSION[$namespace]);
unset(self::$_expiringData[$namespace]);
} else {
unset($_SESSION[$namespace][$name]);
unset(self::$_expiringData[$namespace]);
}
// if we remove the last value, remove namespace.
if (empty($_SESSION[$namespace])) {
unset($_SESSION[$namespace]);
}
}
/**
* namespaceGet() - Get $name variable from $namespace, returning by reference.
*
* @param string $namespace
* @param string $name
* @return mixed
*/
protected static function & _namespaceGet($namespace, $name = null)
{
if (self::$_readable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG);
}
if ($name === null) {
if (isset($_SESSION[$namespace])) { // check session first for data requested
return $_SESSION[$namespace];
} elseif (isset(self::$_expiringData[$namespace])) { // check expiring data for data reqeusted
return self::$_expiringData[$namespace];
} else {
return $_SESSION[$namespace]; // satisfy return by reference
}
} else {
if (isset($_SESSION[$namespace][$name])) { // check session first
return $_SESSION[$namespace][$name];
} elseif (isset(self::$_expiringData[$namespace][$name])) { // check expiring data
return self::$_expiringData[$namespace][$name];
} else {
return $_SESSION[$namespace][$name]; // satisfy return by reference
}
}
}
/**
* namespaceGetAll() - Get an array containing $namespace, including expiring data.
*
* @param string $namespace
* @param string $name
* @return mixed
*/
protected static function _namespaceGetAll($namespace)
{
$currentData = (isset($_SESSION[$namespace]) && is_array($_SESSION[$namespace])) ?
$_SESSION[$namespace] : array();
$expiringData = (isset(self::$_expiringData[$namespace]) && is_array(self::$_expiringData[$namespace])) ?
self::$_expiringData[$namespace] : array();
return array_merge($currentData, $expiringData);
}
}
|
#ifndef UART_H
#define UART_H
/************************************************************************
Title: Interrupt UART library with receive/transmit circular buffers
Author: Peter Fleury <pfleury@gmx.ch> http://jump.to/fleury
File: $Id: uart.h,v 1.8.2.1 2007/07/01 11:14:38 peter Exp $
Software: AVR-GCC 4.1, AVR Libc 1.4
Hardware: any AVR with built-in UART, tested on AT90S8515 & ATmega8 at 4 Mhz
License: GNU General Public License
Usage: see Doxygen manual
LICENSE:
Copyright (C) 2006 Peter Fleury
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
any later version.
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.
************************************************************************/
/************************************************************************
uart_available, uart_flush, uart1_available, and uart1_flush functions
were adapted from the Arduino HardwareSerial.h library by Tim Sharpe on
11 Jan 2009. The license info for HardwareSerial.h is as follows:
HardwareSerial.h - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
************************************************************************/
/************************************************************************
Changelog for modifications made by Tim Sharpe, starting with the current
library version on his Web site as of 05/01/2009.
Date Description
=========================================================================
05/12/2009 Added Arduino-style available() and flush() functions for both
supported UARTs. Really wanted to keep them out of the library, so
that it would be as close as possible to Peter Fleury's original
library, but has scoping issues accessing internal variables from
another program. Go C!
************************************************************************/
/**
* @defgroup pfleury_uart UART Library
* @code #include <uart.h> @endcode
*
* @brief Interrupt UART library using the built-in UART with transmit and receive circular buffers.
*
* This library can be used to transmit and receive data through the built in UART.
*
* An interrupt is generated when the UART has finished transmitting or
* receiving a byte. The interrupt handling routines use circular buffers
* for buffering received and transmitted data.
*
* The UART_RX_BUFFER_SIZE and UART_TX_BUFFER_SIZE constants define
* the size of the circular buffers in bytes. Note that these constants must be a power of 2.
* You may need to adapt this constants to your target and your application by adding
* CDEFS += -DUART_RX_BUFFER_SIZE=nn -DUART_RX_BUFFER_SIZE=nn to your Makefile.
*
* @note Based on Atmel Application Note AVR306
* @author Peter Fleury pfleury@gmx.ch http://jump.to/fleury
*/
/**@{*/
#if (__GNUC__ * 100 + __GNUC_MINOR__) < 304
#error "This library requires AVR-GCC 3.4 or later, update to newer AVR-GCC compiler !"
#endif
/*
** constants and macros
*/
/** @brief UART Baudrate Expression
* @param xtalcpu system clock in Mhz, e.g. 4000000L for 4Mhz
* @param baudrate baudrate in bps, e.g. 1200, 2400, 9600
*/
#define UART_BAUD_SELECT(baudRate,xtalCpu) ((xtalCpu)/((baudRate)*16l)-1)
/** @brief UART Baudrate Expression for ATmega double speed mode
* @param xtalcpu system clock in Mhz, e.g. 4000000L for 4Mhz
* @param baudrate baudrate in bps, e.g. 1200, 2400, 9600
*/
#define UART_BAUD_SELECT_DOUBLE_SPEED(baudRate,xtalCpu) (((xtalCpu)/((baudRate)*8l)-1)|0x8000)
/** Size of the circular receive buffer, must be power of 2 */
#ifndef UART_RX_BUFFER_SIZE
#define UART_RX_BUFFER_SIZE 32
#endif
/** Size of the circular transmit buffer, must be power of 2 */
#ifndef UART_TX_BUFFER_SIZE
#define UART_TX_BUFFER_SIZE 32
#endif
/* test if the size of the circular buffers fits into SRAM */
#if ( (UART_RX_BUFFER_SIZE+UART_TX_BUFFER_SIZE) >= (RAMEND-0x60 ) )
#error "size of UART_RX_BUFFER_SIZE + UART_TX_BUFFER_SIZE larger than size of SRAM"
#endif
/*
** high byte error return code of uart_getc()
*/
#define UART_FRAME_ERROR 0x0800 /* Framing Error by UART */
#define UART_OVERRUN_ERROR 0x0400 /* Overrun condition by UART */
#define UART_BUFFER_OVERFLOW 0x0200 /* receive ringbuffer overflow */
#define UART_NO_DATA 0x0100 /* no receive data available */
/*
** function prototypes
*/
/**
@brief Initialize UART and set baudrate
@param baudrate Specify baudrate using macro UART_BAUD_SELECT()
@return none
*/
extern void uart_init(unsigned int baudrate);
/**
* @brief Get received byte from ringbuffer
*
* Returns in the lower byte the received character and in the
* higher byte the last receive error.
* UART_NO_DATA is returned when no data is available.
*
* @param void
* @return lower byte: received byte from ringbuffer
* @return higher byte: last receive status
* - \b 0 successfully received data from UART
* - \b UART_NO_DATA
* <br>no receive data available
* - \b UART_BUFFER_OVERFLOW
* <br>Receive ringbuffer overflow.
* We are not reading the receive buffer fast enough,
* one or more received character have been dropped
* - \b UART_OVERRUN_ERROR
* <br>Overrun condition by UART.
* A character already present in the UART UDR register was
* not read by the interrupt handler before the next character arrived,
* one or more received characters have been dropped.
* - \b UART_FRAME_ERROR
* <br>Framing Error by UART
*/
extern unsigned int uart_getc(void);
/**
* @brief Put byte to ringbuffer for transmitting via UART
* @param data byte to be transmitted
* @return none
*/
extern void uart_putc(unsigned char data);
/**
* @brief Put string to ringbuffer for transmitting via UART
*
* The string is buffered by the uart library in a circular buffer
* and one character at a time is transmitted to the UART using interrupts.
* Blocks if it can not write the whole string into the circular buffer.
*
* @param s string to be transmitted
* @return none
*/
extern void uart_puts(const char *s );
/**
* @brief Put string from program memory to ringbuffer for transmitting via UART.
*
* The string is buffered by the uart library in a circular buffer
* and one character at a time is transmitted to the UART using interrupts.
* Blocks if it can not write the whole string into the circular buffer.
*
* @param s program memory string to be transmitted
* @return none
* @see uart_puts_P
*/
extern void uart_puts_p(const char *s );
/**
* @brief Macro to automatically put a string constant into program memory
*/
#define uart_puts_P(__s) uart_puts_p(PSTR(__s))
/**
* @brief Return number of bytes waiting in the receive buffer
* @param none
* @return bytes waiting in the receive buffer
*/
extern int uart_available(void);
/**
* @brief Flush bytes waiting in receive buffer
* @param none
* @return none
*/
extern void uart_flush(void);
/** @brief Initialize USART1 (only available on selected ATmegas) @see uart_init */
extern void uart1_init(unsigned int baudrate);
/** @brief Get received byte of USART1 from ringbuffer. (only available on selected ATmega) @see uart_getc */
extern unsigned int uart1_getc(void);
/** @brief Put byte to ringbuffer for transmitting via USART1 (only available on selected ATmega) @see uart_putc */
extern void uart1_putc(unsigned char data);
/** @brief Put string to ringbuffer for transmitting via USART1 (only available on selected ATmega) @see uart_puts */
extern void uart1_puts(const char *s );
/** @brief Put string from program memory to ringbuffer for transmitting via USART1 (only available on selected ATmega) @see uart_puts_p */
extern void uart1_puts_p(const char *s );
/** @brief Macro to automatically put a string constant into program memory */
#define uart1_puts_P(__s) uart1_puts_p(PSTR(__s))
/** @brief Return number of bytes waiting in the receive buffer */
extern int uart1_available(void);
/** @brief Flush bytes waiting in receive buffer */
extern void uart1_flush(void);
/**@}*/
#endif // UART_H
|
# -*- test-case-name: twisted.pb.test.test_promise -*-
from twisted.python import util, failure
from twisted.internet import defer
id = util.unsignedID
EVENTUAL, FULFILLED, BROKEN = range(3)
class Promise:
"""I am a promise of a future result. I am a lot like a Deferred, except
that my promised result is usually an instance. I make it possible to
schedule method invocations on this future instance, returning Promises
for the results.
Promises are always in one of three states: Eventual, Fulfilled, and
Broken. (see http://www.erights.org/elib/concurrency/refmech.html for a
pretty picture). They start as Eventual, meaning we do not yet know
whether they will resolve or not. In this state, method invocations are
queued. Eventually the Promise will be 'resolved' into either the
Fulfilled or the Broken state. Fulfilled means that the promise contains
a live object to which methods can be dispatched synchronously. Broken
promises are incapable of invoking methods: they all result in Failure.
Method invocation is always asynchronous: it always returns a Promise.
"""
# all our internal methods are private, to avoid colliding with normal
# method names that users may invoke on our eventual target.
_state = EVENTUAL
_resolution = None
def __init__(self, d):
self._watchers = []
self._pendingMethods = []
d.addCallbacks(self._ready, self._broken)
def _wait_for_resolution(self):
if self._state == EVENTUAL:
d = defer.Deferred()
self._watchers.append(d)
else:
d = defer.succeed(self._resolution)
return d
def _ready(self, resolution):
self._resolution = resolution
self._state = FULFILLED
self._run_methods()
def _broken(self, f):
self._resolution = f
self._state = BROKEN
self._run_methods()
def _invoke_method(self, name, args, kwargs):
if isinstance(self._resolution, failure.Failure):
return self._resolution
method = getattr(self._resolution, name)
res = method(*args, **kwargs)
return res
def _run_methods(self):
for (name, args, kwargs, result_deferred) in self._pendingMethods:
d = defer.maybeDeferred(self._invoke_method, name, args, kwargs)
d.addBoth(result_deferred.callback)
del self._pendingMethods
for d in self._watchers:
d.callback(self._resolution)
del self._watchers
def __repr__(self):
return "<Promise %#x>" % id(self)
def __getattr__(self, name):
if name.startswith("__"):
raise AttributeError
def newmethod(*args, **kwargs):
return self._add_method(name, args, kwargs)
return newmethod
def _add_method(self, name, args, kwargs):
if self._state == EVENTUAL:
d = defer.Deferred()
self._pendingMethods.append((name, args, kwargs, d))
else:
d = defer.maybeDeferred(self._invoke_method, name, args, kwargs)
return Promise(d)
def when(p):
"""Turn a Promise into a Deferred that will fire with the enclosed object
when it is ready. Use this when you actually need to schedule something
to happen in a synchronous fashion. Most of the time, you can just invoke
methods on the Promise as if it were immediately available."""
assert isinstance(p, Promise)
return p._wait_for_resolution()
|
/*
* QLogic Fibre Channel HBA Driver
* Copyright (c) 2003-2014 QLogic Corporation
*
* See LICENSE.qla2xxx for copyright and licensing details.
*/
#include "qla_def.h"
#include "qla_gbl.h"
#include "qla_target.h"
#include <linux/moduleparam.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsicam.h>
#include <linux/delay.h>
void
qla2x00_vp_stop_timer(scsi_qla_host_t *vha)
{
if (vha->vp_idx && vha->timer_active) {
del_timer_sync(&vha->timer);
vha->timer_active = 0;
}
}
static uint32_t
qla24xx_allocate_vp_id(scsi_qla_host_t *vha)
{
uint32_t vp_id;
struct qla_hw_data *ha = vha->hw;
unsigned long flags;
/* Find an empty slot and assign an vp_id */
mutex_lock(&ha->vport_lock);
vp_id = find_first_zero_bit(ha->vp_idx_map, ha->max_npiv_vports + 1);
if (vp_id > ha->max_npiv_vports) {
ql_dbg(ql_dbg_vport, vha, 0xa000,
"vp_id %d is bigger than max-supported %d.\n",
vp_id, ha->max_npiv_vports);
mutex_unlock(&ha->vport_lock);
return vp_id;
}
set_bit(vp_id, ha->vp_idx_map);
ha->num_vhosts++;
vha->vp_idx = vp_id;
spin_lock_irqsave(&ha->vport_slock, flags);
list_add_tail(&vha->list, &ha->vp_list);
spin_unlock_irqrestore(&ha->vport_slock, flags);
spin_lock_irqsave(&ha->hardware_lock, flags);
qlt_update_vp_map(vha, SET_VP_IDX);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
mutex_unlock(&ha->vport_lock);
return vp_id;
}
void
qla24xx_deallocate_vp_id(scsi_qla_host_t *vha)
{
uint16_t vp_id;
struct qla_hw_data *ha = vha->hw;
unsigned long flags = 0;
u8 i;
mutex_lock(&ha->vport_lock);
/*
* Wait for all pending activities to finish before removing vport from
* the list.
* Lock needs to be held for safe removal from the list (it
* ensures no active vp_list traversal while the vport is removed
* from the queue)
*/
for (i = 0; i < 10; i++) {
if (wait_event_timeout(vha->vref_waitq,
!atomic_read(&vha->vref_count), HZ) > 0)
break;
}
spin_lock_irqsave(&ha->vport_slock, flags);
if (atomic_read(&vha->vref_count)) {
ql_dbg(ql_dbg_vport, vha, 0xfffa,
"vha->vref_count=%u timeout\n", vha->vref_count.counter);
vha->vref_count = (atomic_t)ATOMIC_INIT(0);
}
list_del(&vha->list);
qlt_update_vp_map(vha, RESET_VP_IDX);
spin_unlock_irqrestore(&ha->vport_slock, flags);
vp_id = vha->vp_idx;
ha->num_vhosts--;
clear_bit(vp_id, ha->vp_idx_map);
mutex_unlock(&ha->vport_lock);
}
static scsi_qla_host_t *
qla24xx_find_vhost_by_name(struct qla_hw_data *ha, uint8_t *port_name)
{
scsi_qla_host_t *vha;
struct scsi_qla_host *tvha;
unsigned long flags;
spin_lock_irqsave(&ha->vport_slock, flags);
/* Locate matching device in database. */
list_for_each_entry_safe(vha, tvha, &ha->vp_list, list) {
if (!memcmp(port_name, vha->port_name, WWN_SIZE)) {
spin_unlock_irqrestore(&ha->vport_slock, flags);
return vha;
}
}
spin_unlock_irqrestore(&ha->vport_slock, flags);
return NULL;
}
/*
* qla2x00_mark_vp_devices_dead
* Updates fcport state when device goes offline.
*
* Input:
* ha = adapter block pointer.
* fcport = port structure pointer.
*
* Return:
* None.
*
* Context:
*/
static void
qla2x00_mark_vp_devices_dead(scsi_qla_host_t *vha)
{
/*
* !!! NOTE !!!
* This function, if called in contexts other than vp create, disable
* or delete, please make sure this is synchronized with the
* delete thread.
*/
fc_port_t *fcport;
list_for_each_entry(fcport, &vha->vp_fcports, list) {
ql_dbg(ql_dbg_vport, vha, 0xa001,
"Marking port dead, loop_id=0x%04x : %x.\n",
fcport->loop_id, fcport->vha->vp_idx);
qla2x00_mark_device_lost(vha, fcport, 0, 0);
qla2x00_set_fcport_state(fcport, FCS_UNCONFIGURED);
}
}
int
qla24xx_disable_vp(scsi_qla_host_t *vha)
{
unsigned long flags;
int ret = QLA_SUCCESS;
fc_port_t *fcport;
if (vha->hw->flags.fw_started)
ret = qla24xx_control_vp(vha, VCE_COMMAND_DISABLE_VPS_LOGO_ALL);
atomic_set(&vha->loop_state, LOOP_DOWN);
atomic_set(&vha->loop_down_timer, LOOP_DOWN_TIME);
list_for_each_entry(fcport, &vha->vp_fcports, list)
fcport->logout_on_delete = 0;
qla2x00_mark_all_devices_lost(vha, 0);
/* Remove port id from vp target map */
spin_lock_irqsave(&vha->hw->hardware_lock, flags);
qlt_update_vp_map(vha, RESET_AL_PA);
spin_unlock_irqrestore(&vha->hw->hardware_lock, flags);
qla2x00_mark_vp_devices_dead(vha);
atomic_set(&vha->vp_state, VP_FAILED);
vha->flags.management_server_logged_in = 0;
if (ret == QLA_SUCCESS) {
fc_vport_set_state(vha->fc_vport, FC_VPORT_DISABLED);
} else {
fc_vport_set_state(vha->fc_vport, FC_VPORT_FAILED);
return -1;
}
return 0;
}
int
qla24xx_enable_vp(scsi_qla_host_t *vha)
{
int ret;
struct qla_hw_data *ha = vha->hw;
scsi_qla_host_t *base_vha = pci_get_drvdata(ha->pdev);
/* Check if physical ha port is Up */
if (atomic_read(&base_vha->loop_state) == LOOP_DOWN ||
atomic_read(&base_vha->loop_state) == LOOP_DEAD ||
!(ha->current_topology & ISP_CFG_F)) {
vha->vp_err_state = VP_ERR_PORTDWN;
fc_vport_set_state(vha->fc_vport, FC_VPORT_LINKDOWN);
ql_dbg(ql_dbg_taskm, vha, 0x800b,
"%s skip enable. loop_state %x topo %x\n",
__func__, base_vha->loop_state.counter,
ha->current_topology);
goto enable_failed;
}
/* Initialize the new vport unless it is a persistent port */
mutex_lock(&ha->vport_lock);
ret = qla24xx_modify_vp_config(vha);
mutex_unlock(&ha->vport_lock);
if (ret != QLA_SUCCESS) {
fc_vport_set_state(vha->fc_vport, FC_VPORT_FAILED);
goto enable_failed;
}
ql_dbg(ql_dbg_taskm, vha, 0x801a,
"Virtual port with id: %d - Enabled.\n", vha->vp_idx);
return 0;
enable_failed:
ql_dbg(ql_dbg_taskm, vha, 0x801b,
"Virtual port with id: %d - Disabled.\n", vha->vp_idx);
return 1;
}
static void
qla24xx_configure_vp(scsi_qla_host_t *vha)
{
struct fc_vport *fc_vport;
int ret;
fc_vport = vha->fc_vport;
ql_dbg(ql_dbg_vport, vha, 0xa002,
"%s: change request #3.\n", __func__);
ret = qla2x00_send_change_request(vha, 0x3, vha->vp_idx);
if (ret != QLA_SUCCESS) {
ql_dbg(ql_dbg_vport, vha, 0xa003, "Failed to enable "
"receiving of RSCN requests: 0x%x.\n", ret);
return;
} else {
/* Corresponds to SCR enabled */
clear_bit(VP_SCR_NEEDED, &vha->vp_flags);
}
vha->flags.online = 1;
if (qla24xx_configure_vhba(vha))
return;
atomic_set(&vha->vp_state, VP_ACTIVE);
fc_vport_set_state(fc_vport, FC_VPORT_ACTIVE);
}
void
qla2x00_alert_all_vps(struct rsp_que *rsp, uint16_t *mb)
{
scsi_qla_host_t *vha;
struct qla_hw_data *ha = rsp->hw;
int i = 0;
unsigned long flags;
spin_lock_irqsave(&ha->vport_slock, flags);
list_for_each_entry(vha, &ha->vp_list, list) {
if (vha->vp_idx) {
if (test_bit(VPORT_DELETE, &vha->dpc_flags))
continue;
atomic_inc(&vha->vref_count);
spin_unlock_irqrestore(&ha->vport_slock, flags);
switch (mb[0]) {
case MBA_LIP_OCCURRED:
case MBA_LOOP_UP:
case MBA_LOOP_DOWN:
case MBA_LIP_RESET:
case MBA_POINT_TO_POINT:
case MBA_CHG_IN_CONNECTION:
ql_dbg(ql_dbg_async, vha, 0x5024,
"Async_event for VP[%d], mb=0x%x vha=%p.\n",
i, *mb, vha);
qla2x00_async_event(vha, rsp, mb);
break;
case MBA_PORT_UPDATE:
case MBA_RSCN_UPDATE:
if ((mb[3] & 0xff) == vha->vp_idx) {
ql_dbg(ql_dbg_async, vha, 0x5024,
"Async_event for VP[%d], mb=0x%x vha=%p\n",
i, *mb, vha);
qla2x00_async_event(vha, rsp, mb);
}
break;
}
spin_lock_irqsave(&ha->vport_slock, flags);
atomic_dec(&vha->vref_count);
wake_up(&vha->vref_waitq);
}
i++;
}
spin_unlock_irqrestore(&ha->vport_slock, flags);
}
int
qla2x00_vp_abort_isp(scsi_qla_host_t *vha)
{
fc_port_t *fcport;
/*
* To exclusively reset vport, we need to log it out first.
* Note: This control_vp can fail if ISP reset is already
* issued, this is expected, as the vp would be already
* logged out due to ISP reset.
*/
if (!test_bit(ABORT_ISP_ACTIVE, &vha->dpc_flags)) {
qla24xx_control_vp(vha, VCE_COMMAND_DISABLE_VPS_LOGO_ALL);
list_for_each_entry(fcport, &vha->vp_fcports, list)
fcport->logout_on_delete = 0;
}
/*
* Physical port will do most of the abort and recovery work. We can
* just treat it as a loop down
*/
if (atomic_read(&vha->loop_state) != LOOP_DOWN) {
atomic_set(&vha->loop_state, LOOP_DOWN);
qla2x00_mark_all_devices_lost(vha, 0);
} else {
if (!atomic_read(&vha->loop_down_timer))
atomic_set(&vha->loop_down_timer, LOOP_DOWN_TIME);
}
ql_dbg(ql_dbg_taskm, vha, 0x801d,
"Scheduling enable of Vport %d.\n", vha->vp_idx);
return qla24xx_enable_vp(vha);
}
static int
qla2x00_do_dpc_vp(scsi_qla_host_t *vha)
{
struct qla_hw_data *ha = vha->hw;
scsi_qla_host_t *base_vha = pci_get_drvdata(ha->pdev);
ql_dbg(ql_dbg_dpc + ql_dbg_verbose, vha, 0x4012,
"Entering %s vp_flags: 0x%lx.\n", __func__, vha->vp_flags);
/* Check if Fw is ready to configure VP first */
if (test_bit(VP_CONFIG_OK, &base_vha->vp_flags)) {
if (test_and_clear_bit(VP_IDX_ACQUIRED, &vha->vp_flags)) {
/* VP acquired. complete port configuration */
ql_dbg(ql_dbg_dpc, vha, 0x4014,
"Configure VP scheduled.\n");
qla24xx_configure_vp(vha);
ql_dbg(ql_dbg_dpc, vha, 0x4015,
"Configure VP end.\n");
return 0;
}
}
if (test_bit(FCPORT_UPDATE_NEEDED, &vha->dpc_flags)) {
ql_dbg(ql_dbg_dpc, vha, 0x4016,
"FCPort update scheduled.\n");
qla2x00_update_fcports(vha);
clear_bit(FCPORT_UPDATE_NEEDED, &vha->dpc_flags);
ql_dbg(ql_dbg_dpc, vha, 0x4017,
"FCPort update end.\n");
}
if (test_bit(RELOGIN_NEEDED, &vha->dpc_flags) &&
!test_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags) &&
atomic_read(&vha->loop_state) != LOOP_DOWN) {
if (!vha->relogin_jif ||
time_after_eq(jiffies, vha->relogin_jif)) {
vha->relogin_jif = jiffies + HZ;
clear_bit(RELOGIN_NEEDED, &vha->dpc_flags);
ql_dbg(ql_dbg_dpc, vha, 0x4018,
"Relogin needed scheduled.\n");
qla24xx_post_relogin_work(vha);
}
}
if (test_and_clear_bit(RESET_MARKER_NEEDED, &vha->dpc_flags) &&
(!(test_and_set_bit(RESET_ACTIVE, &vha->dpc_flags)))) {
clear_bit(RESET_ACTIVE, &vha->dpc_flags);
}
if (test_and_clear_bit(LOOP_RESYNC_NEEDED, &vha->dpc_flags)) {
if (!(test_and_set_bit(LOOP_RESYNC_ACTIVE, &vha->dpc_flags))) {
ql_dbg(ql_dbg_dpc, vha, 0x401a,
"Loop resync scheduled.\n");
qla2x00_loop_resync(vha);
clear_bit(LOOP_RESYNC_ACTIVE, &vha->dpc_flags);
ql_dbg(ql_dbg_dpc, vha, 0x401b,
"Loop resync end.\n");
}
}
ql_dbg(ql_dbg_dpc + ql_dbg_verbose, vha, 0x401c,
"Exiting %s.\n", __func__);
return 0;
}
void
qla2x00_do_dpc_all_vps(scsi_qla_host_t *vha)
{
struct qla_hw_data *ha = vha->hw;
scsi_qla_host_t *vp;
unsigned long flags = 0;
if (vha->vp_idx)
return;
if (list_empty(&ha->vp_list))
return;
clear_bit(VP_DPC_NEEDED, &vha->dpc_flags);
if (!(ha->current_topology & ISP_CFG_F))
return;
spin_lock_irqsave(&ha->vport_slock, flags);
list_for_each_entry(vp, &ha->vp_list, list) {
if (vp->vp_idx) {
atomic_inc(&vp->vref_count);
spin_unlock_irqrestore(&ha->vport_slock, flags);
qla2x00_do_dpc_vp(vp);
spin_lock_irqsave(&ha->vport_slock, flags);
atomic_dec(&vp->vref_count);
}
}
spin_unlock_irqrestore(&ha->vport_slock, flags);
}
int
qla24xx_vport_create_req_sanity_check(struct fc_vport *fc_vport)
{
scsi_qla_host_t *base_vha = shost_priv(fc_vport->shost);
struct qla_hw_data *ha = base_vha->hw;
scsi_qla_host_t *vha;
uint8_t port_name[WWN_SIZE];
if (fc_vport->roles != FC_PORT_ROLE_FCP_INITIATOR)
return VPCERR_UNSUPPORTED;
/* Check up the F/W and H/W support NPIV */
if (!ha->flags.npiv_supported)
return VPCERR_UNSUPPORTED;
/* Check up whether npiv supported switch presented */
if (!(ha->switch_cap & FLOGI_MID_SUPPORT))
return VPCERR_NO_FABRIC_SUPP;
/* Check up unique WWPN */
u64_to_wwn(fc_vport->port_name, port_name);
if (!memcmp(port_name, base_vha->port_name, WWN_SIZE))
return VPCERR_BAD_WWN;
vha = qla24xx_find_vhost_by_name(ha, port_name);
if (vha)
return VPCERR_BAD_WWN;
/* Check up max-npiv-supports */
if (ha->num_vhosts > ha->max_npiv_vports) {
ql_dbg(ql_dbg_vport, vha, 0xa004,
"num_vhosts %ud is bigger "
"than max_npiv_vports %ud.\n",
ha->num_vhosts, ha->max_npiv_vports);
return VPCERR_UNSUPPORTED;
}
return 0;
}
scsi_qla_host_t *
qla24xx_create_vhost(struct fc_vport *fc_vport)
{
scsi_qla_host_t *base_vha = shost_priv(fc_vport->shost);
struct qla_hw_data *ha = base_vha->hw;
scsi_qla_host_t *vha;
struct scsi_host_template *sht = &qla2xxx_driver_template;
struct Scsi_Host *host;
vha = qla2x00_create_host(sht, ha);
if (!vha) {
ql_log(ql_log_warn, vha, 0xa005,
"scsi_host_alloc() failed for vport.\n");
return(NULL);
}
host = vha->host;
fc_vport->dd_data = vha;
/* New host info */
u64_to_wwn(fc_vport->node_name, vha->node_name);
u64_to_wwn(fc_vport->port_name, vha->port_name);
vha->fc_vport = fc_vport;
vha->device_flags = 0;
vha->vp_idx = qla24xx_allocate_vp_id(vha);
if (vha->vp_idx > ha->max_npiv_vports) {
ql_dbg(ql_dbg_vport, vha, 0xa006,
"Couldn't allocate vp_id.\n");
goto create_vhost_failed;
}
vha->mgmt_svr_loop_id = qla2x00_reserve_mgmt_server_loop_id(vha);
vha->dpc_flags = 0L;
/*
* To fix the issue of processing a parent's RSCN for the vport before
* its SCR is complete.
*/
set_bit(VP_SCR_NEEDED, &vha->vp_flags);
atomic_set(&vha->loop_state, LOOP_DOWN);
atomic_set(&vha->loop_down_timer, LOOP_DOWN_TIME);
qla2x00_start_timer(vha, WATCH_INTERVAL);
vha->req = base_vha->req;
vha->flags.nvme_enabled = base_vha->flags.nvme_enabled;
host->can_queue = base_vha->req->length + 128;
host->cmd_per_lun = 3;
if (IS_T10_PI_CAPABLE(ha) && ql2xenabledif)
host->max_cmd_len = 32;
else
host->max_cmd_len = MAX_CMDSZ;
host->max_channel = MAX_BUSES - 1;
host->max_lun = ql2xmaxlun;
host->unique_id = host->host_no;
host->max_id = ha->max_fibre_devices;
host->transportt = qla2xxx_transport_vport_template;
ql_dbg(ql_dbg_vport, vha, 0xa007,
"Detect vport hba %ld at address = %p.\n",
vha->host_no, vha);
vha->flags.init_done = 1;
mutex_lock(&ha->vport_lock);
set_bit(vha->vp_idx, ha->vp_idx_map);
ha->cur_vport_count++;
mutex_unlock(&ha->vport_lock);
return vha;
create_vhost_failed:
return NULL;
}
static void
qla25xx_free_req_que(struct scsi_qla_host *vha, struct req_que *req)
{
struct qla_hw_data *ha = vha->hw;
uint16_t que_id = req->id;
dma_free_coherent(&ha->pdev->dev, (req->length + 1) *
sizeof(request_t), req->ring, req->dma);
req->ring = NULL;
req->dma = 0;
if (que_id) {
ha->req_q_map[que_id] = NULL;
mutex_lock(&ha->vport_lock);
clear_bit(que_id, ha->req_qid_map);
mutex_unlock(&ha->vport_lock);
}
kfree(req->outstanding_cmds);
kfree(req);
req = NULL;
}
static void
qla25xx_free_rsp_que(struct scsi_qla_host *vha, struct rsp_que *rsp)
{
struct qla_hw_data *ha = vha->hw;
uint16_t que_id = rsp->id;
if (rsp->msix && rsp->msix->have_irq) {
free_irq(rsp->msix->vector, rsp->msix->handle);
rsp->msix->have_irq = 0;
rsp->msix->in_use = 0;
rsp->msix->handle = NULL;
}
dma_free_coherent(&ha->pdev->dev, (rsp->length + 1) *
sizeof(response_t), rsp->ring, rsp->dma);
rsp->ring = NULL;
rsp->dma = 0;
if (que_id) {
ha->rsp_q_map[que_id] = NULL;
mutex_lock(&ha->vport_lock);
clear_bit(que_id, ha->rsp_qid_map);
mutex_unlock(&ha->vport_lock);
}
kfree(rsp);
rsp = NULL;
}
int
qla25xx_delete_req_que(struct scsi_qla_host *vha, struct req_que *req)
{
int ret = QLA_SUCCESS;
if (req && vha->flags.qpairs_req_created) {
req->options |= BIT_0;
ret = qla25xx_init_req_que(vha, req);
if (ret != QLA_SUCCESS)
return QLA_FUNCTION_FAILED;
qla25xx_free_req_que(vha, req);
}
return ret;
}
int
qla25xx_delete_rsp_que(struct scsi_qla_host *vha, struct rsp_que *rsp)
{
int ret = QLA_SUCCESS;
if (rsp && vha->flags.qpairs_rsp_created) {
rsp->options |= BIT_0;
ret = qla25xx_init_rsp_que(vha, rsp);
if (ret != QLA_SUCCESS)
return QLA_FUNCTION_FAILED;
qla25xx_free_rsp_que(vha, rsp);
}
return ret;
}
/* Delete all queues for a given vhost */
int
qla25xx_delete_queues(struct scsi_qla_host *vha)
{
int cnt, ret = 0;
struct req_que *req = NULL;
struct rsp_que *rsp = NULL;
struct qla_hw_data *ha = vha->hw;
struct qla_qpair *qpair, *tqpair;
if (ql2xmqsupport || ql2xnvmeenable) {
list_for_each_entry_safe(qpair, tqpair, &vha->qp_list,
qp_list_elem)
qla2xxx_delete_qpair(vha, qpair);
} else {
/* Delete request queues */
for (cnt = 1; cnt < ha->max_req_queues; cnt++) {
req = ha->req_q_map[cnt];
if (req && test_bit(cnt, ha->req_qid_map)) {
ret = qla25xx_delete_req_que(vha, req);
if (ret != QLA_SUCCESS) {
ql_log(ql_log_warn, vha, 0x00ea,
"Couldn't delete req que %d.\n",
req->id);
return ret;
}
}
}
/* Delete response queues */
for (cnt = 1; cnt < ha->max_rsp_queues; cnt++) {
rsp = ha->rsp_q_map[cnt];
if (rsp && test_bit(cnt, ha->rsp_qid_map)) {
ret = qla25xx_delete_rsp_que(vha, rsp);
if (ret != QLA_SUCCESS) {
ql_log(ql_log_warn, vha, 0x00eb,
"Couldn't delete rsp que %d.\n",
rsp->id);
return ret;
}
}
}
}
return ret;
}
int
qla25xx_create_req_que(struct qla_hw_data *ha, uint16_t options,
uint8_t vp_idx, uint16_t rid, int rsp_que, uint8_t qos, bool startqp)
{
int ret = 0;
struct req_que *req = NULL;
struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
struct scsi_qla_host *vha = pci_get_drvdata(ha->pdev);
uint16_t que_id = 0;
device_reg_t *reg;
uint32_t cnt;
req = kzalloc(sizeof(struct req_que), GFP_KERNEL);
if (req == NULL) {
ql_log(ql_log_fatal, base_vha, 0x00d9,
"Failed to allocate memory for request queue.\n");
goto failed;
}
req->length = REQUEST_ENTRY_CNT_24XX;
req->ring = dma_alloc_coherent(&ha->pdev->dev,
(req->length + 1) * sizeof(request_t),
&req->dma, GFP_KERNEL);
if (req->ring == NULL) {
ql_log(ql_log_fatal, base_vha, 0x00da,
"Failed to allocate memory for request_ring.\n");
goto que_failed;
}
ret = qla2x00_alloc_outstanding_cmds(ha, req);
if (ret != QLA_SUCCESS)
goto que_failed;
mutex_lock(&ha->mq_lock);
que_id = find_first_zero_bit(ha->req_qid_map, ha->max_req_queues);
if (que_id >= ha->max_req_queues) {
mutex_unlock(&ha->mq_lock);
ql_log(ql_log_warn, base_vha, 0x00db,
"No resources to create additional request queue.\n");
goto que_failed;
}
set_bit(que_id, ha->req_qid_map);
ha->req_q_map[que_id] = req;
req->rid = rid;
req->vp_idx = vp_idx;
req->qos = qos;
ql_dbg(ql_dbg_multiq, base_vha, 0xc002,
"queue_id=%d rid=%d vp_idx=%d qos=%d.\n",
que_id, req->rid, req->vp_idx, req->qos);
ql_dbg(ql_dbg_init, base_vha, 0x00dc,
"queue_id=%d rid=%d vp_idx=%d qos=%d.\n",
que_id, req->rid, req->vp_idx, req->qos);
if (rsp_que < 0)
req->rsp = NULL;
else
req->rsp = ha->rsp_q_map[rsp_que];
/* Use alternate PCI bus number */
if (MSB(req->rid))
options |= BIT_4;
/* Use alternate PCI devfn */
if (LSB(req->rid))
options |= BIT_5;
req->options = options;
ql_dbg(ql_dbg_multiq, base_vha, 0xc003,
"options=0x%x.\n", req->options);
ql_dbg(ql_dbg_init, base_vha, 0x00dd,
"options=0x%x.\n", req->options);
for (cnt = 1; cnt < req->num_outstanding_cmds; cnt++)
req->outstanding_cmds[cnt] = NULL;
req->current_outstanding_cmd = 1;
req->ring_ptr = req->ring;
req->ring_index = 0;
req->cnt = req->length;
req->id = que_id;
reg = ISP_QUE_REG(ha, que_id);
req->req_q_in = ®->isp25mq.req_q_in;
req->req_q_out = ®->isp25mq.req_q_out;
req->max_q_depth = ha->req_q_map[0]->max_q_depth;
req->out_ptr = (void *)(req->ring + req->length);
mutex_unlock(&ha->mq_lock);
ql_dbg(ql_dbg_multiq, base_vha, 0xc004,
"ring_ptr=%p ring_index=%d, "
"cnt=%d id=%d max_q_depth=%d.\n",
req->ring_ptr, req->ring_index,
req->cnt, req->id, req->max_q_depth);
ql_dbg(ql_dbg_init, base_vha, 0x00de,
"ring_ptr=%p ring_index=%d, "
"cnt=%d id=%d max_q_depth=%d.\n",
req->ring_ptr, req->ring_index, req->cnt,
req->id, req->max_q_depth);
if (startqp) {
ret = qla25xx_init_req_que(base_vha, req);
if (ret != QLA_SUCCESS) {
ql_log(ql_log_fatal, base_vha, 0x00df,
"%s failed.\n", __func__);
mutex_lock(&ha->mq_lock);
clear_bit(que_id, ha->req_qid_map);
mutex_unlock(&ha->mq_lock);
goto que_failed;
}
vha->flags.qpairs_req_created = 1;
}
return req->id;
que_failed:
qla25xx_free_req_que(base_vha, req);
failed:
return 0;
}
static void qla_do_work(struct work_struct *work)
{
unsigned long flags;
struct qla_qpair *qpair = container_of(work, struct qla_qpair, q_work);
struct scsi_qla_host *vha;
struct qla_hw_data *ha = qpair->hw;
spin_lock_irqsave(&qpair->qp_lock, flags);
vha = pci_get_drvdata(ha->pdev);
qla24xx_process_response_queue(vha, qpair->rsp);
spin_unlock_irqrestore(&qpair->qp_lock, flags);
}
/* create response queue */
int
qla25xx_create_rsp_que(struct qla_hw_data *ha, uint16_t options,
uint8_t vp_idx, uint16_t rid, struct qla_qpair *qpair, bool startqp)
{
int ret = 0;
struct rsp_que *rsp = NULL;
struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
struct scsi_qla_host *vha = pci_get_drvdata(ha->pdev);
uint16_t que_id = 0;
device_reg_t *reg;
rsp = kzalloc(sizeof(struct rsp_que), GFP_KERNEL);
if (rsp == NULL) {
ql_log(ql_log_warn, base_vha, 0x0066,
"Failed to allocate memory for response queue.\n");
goto failed;
}
rsp->length = RESPONSE_ENTRY_CNT_MQ;
rsp->ring = dma_alloc_coherent(&ha->pdev->dev,
(rsp->length + 1) * sizeof(response_t),
&rsp->dma, GFP_KERNEL);
if (rsp->ring == NULL) {
ql_log(ql_log_warn, base_vha, 0x00e1,
"Failed to allocate memory for response ring.\n");
goto que_failed;
}
mutex_lock(&ha->mq_lock);
que_id = find_first_zero_bit(ha->rsp_qid_map, ha->max_rsp_queues);
if (que_id >= ha->max_rsp_queues) {
mutex_unlock(&ha->mq_lock);
ql_log(ql_log_warn, base_vha, 0x00e2,
"No resources to create additional request queue.\n");
goto que_failed;
}
set_bit(que_id, ha->rsp_qid_map);
rsp->msix = qpair->msix;
ha->rsp_q_map[que_id] = rsp;
rsp->rid = rid;
rsp->vp_idx = vp_idx;
rsp->hw = ha;
ql_dbg(ql_dbg_init, base_vha, 0x00e4,
"rsp queue_id=%d rid=%d vp_idx=%d hw=%p.\n",
que_id, rsp->rid, rsp->vp_idx, rsp->hw);
/* Use alternate PCI bus number */
if (MSB(rsp->rid))
options |= BIT_4;
/* Use alternate PCI devfn */
if (LSB(rsp->rid))
options |= BIT_5;
/* Enable MSIX handshake mode on for uncapable adapters */
if (!IS_MSIX_NACK_CAPABLE(ha))
options |= BIT_6;
/* Set option to indicate response queue creation */
options |= BIT_1;
rsp->options = options;
rsp->id = que_id;
reg = ISP_QUE_REG(ha, que_id);
rsp->rsp_q_in = ®->isp25mq.rsp_q_in;
rsp->rsp_q_out = ®->isp25mq.rsp_q_out;
rsp->in_ptr = (void *)(rsp->ring + rsp->length);
mutex_unlock(&ha->mq_lock);
ql_dbg(ql_dbg_multiq, base_vha, 0xc00b,
"options=%x id=%d rsp_q_in=%p rsp_q_out=%p\n",
rsp->options, rsp->id, rsp->rsp_q_in,
rsp->rsp_q_out);
ql_dbg(ql_dbg_init, base_vha, 0x00e5,
"options=%x id=%d rsp_q_in=%p rsp_q_out=%p\n",
rsp->options, rsp->id, rsp->rsp_q_in,
rsp->rsp_q_out);
ret = qla25xx_request_irq(ha, qpair, qpair->msix,
QLA_MSIX_QPAIR_MULTIQ_RSP_Q);
if (ret)
goto que_failed;
if (startqp) {
ret = qla25xx_init_rsp_que(base_vha, rsp);
if (ret != QLA_SUCCESS) {
ql_log(ql_log_fatal, base_vha, 0x00e7,
"%s failed.\n", __func__);
mutex_lock(&ha->mq_lock);
clear_bit(que_id, ha->rsp_qid_map);
mutex_unlock(&ha->mq_lock);
goto que_failed;
}
vha->flags.qpairs_rsp_created = 1;
}
rsp->req = NULL;
qla2x00_init_response_q_entries(rsp);
if (qpair->hw->wq)
INIT_WORK(&qpair->q_work, qla_do_work);
return rsp->id;
que_failed:
qla25xx_free_rsp_que(base_vha, rsp);
failed:
return 0;
}
static void qla_ctrlvp_sp_done(srb_t *sp, int res)
{
if (sp->comp)
complete(sp->comp);
/* don't free sp here. Let the caller do the free */
}
/**
* qla24xx_control_vp() - Enable a virtual port for given host
* @vha: adapter block pointer
* @cmd: command type to be sent for enable virtual port
*
* Return: qla2xxx local function return status code.
*/
int qla24xx_control_vp(scsi_qla_host_t *vha, int cmd)
{
int rval = QLA_MEMORY_ALLOC_FAILED;
struct qla_hw_data *ha = vha->hw;
int vp_index = vha->vp_idx;
struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
DECLARE_COMPLETION_ONSTACK(comp);
srb_t *sp;
ql_dbg(ql_dbg_vport, vha, 0x10c1,
"Entered %s cmd %x index %d.\n", __func__, cmd, vp_index);
if (vp_index == 0 || vp_index >= ha->max_npiv_vports)
return QLA_PARAMETER_ERROR;
sp = qla2x00_get_sp(base_vha, NULL, GFP_KERNEL);
if (!sp)
return rval;
sp->type = SRB_CTRL_VP;
sp->name = "ctrl_vp";
sp->comp = ∁
sp->done = qla_ctrlvp_sp_done;
sp->u.iocb_cmd.timeout = qla2x00_async_iocb_timeout;
qla2x00_init_timer(sp, qla2x00_get_async_timeout(vha) + 2);
sp->u.iocb_cmd.u.ctrlvp.cmd = cmd;
sp->u.iocb_cmd.u.ctrlvp.vp_index = vp_index;
rval = qla2x00_start_sp(sp);
if (rval != QLA_SUCCESS) {
ql_dbg(ql_dbg_async, vha, 0xffff,
"%s: %s Failed submission. %x.\n",
__func__, sp->name, rval);
goto done;
}
ql_dbg(ql_dbg_vport, vha, 0x113f, "%s hndl %x submitted\n",
sp->name, sp->handle);
wait_for_completion(&comp);
sp->comp = NULL;
rval = sp->rc;
switch (rval) {
case QLA_FUNCTION_TIMEOUT:
ql_dbg(ql_dbg_vport, vha, 0xffff, "%s: %s Timeout. %x.\n",
__func__, sp->name, rval);
break;
case QLA_SUCCESS:
ql_dbg(ql_dbg_vport, vha, 0xffff, "%s: %s done.\n",
__func__, sp->name);
break;
default:
ql_dbg(ql_dbg_vport, vha, 0xffff, "%s: %s Failed. %x.\n",
__func__, sp->name, rval);
break;
}
done:
sp->free(sp);
return rval;
}
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_GiftMessage
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Product attribute for allowing of gift messages per item
*
* @deprecated after 1.4.2.0
*
* @category Mage
* @package Mage_GiftMessage
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_GiftMessage_Model_Entity_Attribute_Backend_Boolean_Config extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
/**
* Set attribute default value if value empty
*
* @param Varien_Object $object
*/
public function afterLoad($object)
{
if(!$object->hasData($this->getAttribute()->getAttributeCode())) {
$object->setData($this->getAttribute()->getAttributeCode(), $this->getDefaultValue());
}
}
/**
* Set attribute default value if value empty
*
* @param Varien_Object $object
*/
public function beforeSave($object)
{
if($object->hasData($this->getAttribute()->getAttributeCode())
&& $object->getData($this->getAttribute()->getAttributeCode()) == $this->getDefaultValue()) {
$object->unsData($this->getAttribute()->getAttributeCode());
}
}
/**
* Validate attribute data
*
* @param Varien_Object $object
* @return boolean
*/
public function validate($object)
{
// all attribute's options
$optionsAllowed = array('0', '1', '2');
$value = $object->getData($this->getAttribute()->getAttributeCode());
return in_array($value, $optionsAllowed)? true : false;
}
}
|
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
#ifndef _UAPI_ASM_X86_PROCESSOR_FLAGS_H
#define _UAPI_ASM_X86_PROCESSOR_FLAGS_H
/* Various flags defined: can be included from assembler. */
#include <linux/const.h>
/*
* EFLAGS bits
*/
#define X86_EFLAGS_CF_BIT 0 /* Carry Flag */
#define X86_EFLAGS_CF _BITUL(X86_EFLAGS_CF_BIT)
#define X86_EFLAGS_FIXED_BIT 1 /* Bit 1 - always on */
#define X86_EFLAGS_FIXED _BITUL(X86_EFLAGS_FIXED_BIT)
#define X86_EFLAGS_PF_BIT 2 /* Parity Flag */
#define X86_EFLAGS_PF _BITUL(X86_EFLAGS_PF_BIT)
#define X86_EFLAGS_AF_BIT 4 /* Auxiliary carry Flag */
#define X86_EFLAGS_AF _BITUL(X86_EFLAGS_AF_BIT)
#define X86_EFLAGS_ZF_BIT 6 /* Zero Flag */
#define X86_EFLAGS_ZF _BITUL(X86_EFLAGS_ZF_BIT)
#define X86_EFLAGS_SF_BIT 7 /* Sign Flag */
#define X86_EFLAGS_SF _BITUL(X86_EFLAGS_SF_BIT)
#define X86_EFLAGS_TF_BIT 8 /* Trap Flag */
#define X86_EFLAGS_TF _BITUL(X86_EFLAGS_TF_BIT)
#define X86_EFLAGS_IF_BIT 9 /* Interrupt Flag */
#define X86_EFLAGS_IF _BITUL(X86_EFLAGS_IF_BIT)
#define X86_EFLAGS_DF_BIT 10 /* Direction Flag */
#define X86_EFLAGS_DF _BITUL(X86_EFLAGS_DF_BIT)
#define X86_EFLAGS_OF_BIT 11 /* Overflow Flag */
#define X86_EFLAGS_OF _BITUL(X86_EFLAGS_OF_BIT)
#define X86_EFLAGS_IOPL_BIT 12 /* I/O Privilege Level (2 bits) */
#define X86_EFLAGS_IOPL (_AC(3,UL) << X86_EFLAGS_IOPL_BIT)
#define X86_EFLAGS_NT_BIT 14 /* Nested Task */
#define X86_EFLAGS_NT _BITUL(X86_EFLAGS_NT_BIT)
#define X86_EFLAGS_RF_BIT 16 /* Resume Flag */
#define X86_EFLAGS_RF _BITUL(X86_EFLAGS_RF_BIT)
#define X86_EFLAGS_VM_BIT 17 /* Virtual Mode */
#define X86_EFLAGS_VM _BITUL(X86_EFLAGS_VM_BIT)
#define X86_EFLAGS_AC_BIT 18 /* Alignment Check/Access Control */
#define X86_EFLAGS_AC _BITUL(X86_EFLAGS_AC_BIT)
#define X86_EFLAGS_VIF_BIT 19 /* Virtual Interrupt Flag */
#define X86_EFLAGS_VIF _BITUL(X86_EFLAGS_VIF_BIT)
#define X86_EFLAGS_VIP_BIT 20 /* Virtual Interrupt Pending */
#define X86_EFLAGS_VIP _BITUL(X86_EFLAGS_VIP_BIT)
#define X86_EFLAGS_ID_BIT 21 /* CPUID detection */
#define X86_EFLAGS_ID _BITUL(X86_EFLAGS_ID_BIT)
/*
* Basic CPU control in CR0
*/
#define X86_CR0_PE_BIT 0 /* Protection Enable */
#define X86_CR0_PE _BITUL(X86_CR0_PE_BIT)
#define X86_CR0_MP_BIT 1 /* Monitor Coprocessor */
#define X86_CR0_MP _BITUL(X86_CR0_MP_BIT)
#define X86_CR0_EM_BIT 2 /* Emulation */
#define X86_CR0_EM _BITUL(X86_CR0_EM_BIT)
#define X86_CR0_TS_BIT 3 /* Task Switched */
#define X86_CR0_TS _BITUL(X86_CR0_TS_BIT)
#define X86_CR0_ET_BIT 4 /* Extension Type */
#define X86_CR0_ET _BITUL(X86_CR0_ET_BIT)
#define X86_CR0_NE_BIT 5 /* Numeric Error */
#define X86_CR0_NE _BITUL(X86_CR0_NE_BIT)
#define X86_CR0_WP_BIT 16 /* Write Protect */
#define X86_CR0_WP _BITUL(X86_CR0_WP_BIT)
#define X86_CR0_AM_BIT 18 /* Alignment Mask */
#define X86_CR0_AM _BITUL(X86_CR0_AM_BIT)
#define X86_CR0_NW_BIT 29 /* Not Write-through */
#define X86_CR0_NW _BITUL(X86_CR0_NW_BIT)
#define X86_CR0_CD_BIT 30 /* Cache Disable */
#define X86_CR0_CD _BITUL(X86_CR0_CD_BIT)
#define X86_CR0_PG_BIT 31 /* Paging */
#define X86_CR0_PG _BITUL(X86_CR0_PG_BIT)
/*
* Paging options in CR3
*/
#define X86_CR3_PWT_BIT 3 /* Page Write Through */
#define X86_CR3_PWT _BITUL(X86_CR3_PWT_BIT)
#define X86_CR3_PCD_BIT 4 /* Page Cache Disable */
#define X86_CR3_PCD _BITUL(X86_CR3_PCD_BIT)
#define X86_CR3_PCID_MASK _AC(0x00000fff,UL) /* PCID Mask */
/*
* Intel CPU features in CR4
*/
#define X86_CR4_VME_BIT 0 /* enable vm86 extensions */
#define X86_CR4_VME _BITUL(X86_CR4_VME_BIT)
#define X86_CR4_PVI_BIT 1 /* virtual interrupts flag enable */
#define X86_CR4_PVI _BITUL(X86_CR4_PVI_BIT)
#define X86_CR4_TSD_BIT 2 /* disable time stamp at ipl 3 */
#define X86_CR4_TSD _BITUL(X86_CR4_TSD_BIT)
#define X86_CR4_DE_BIT 3 /* enable debugging extensions */
#define X86_CR4_DE _BITUL(X86_CR4_DE_BIT)
#define X86_CR4_PSE_BIT 4 /* enable page size extensions */
#define X86_CR4_PSE _BITUL(X86_CR4_PSE_BIT)
#define X86_CR4_PAE_BIT 5 /* enable physical address extensions */
#define X86_CR4_PAE _BITUL(X86_CR4_PAE_BIT)
#define X86_CR4_MCE_BIT 6 /* Machine check enable */
#define X86_CR4_MCE _BITUL(X86_CR4_MCE_BIT)
#define X86_CR4_PGE_BIT 7 /* enable global pages */
#define X86_CR4_PGE _BITUL(X86_CR4_PGE_BIT)
#define X86_CR4_PCE_BIT 8 /* enable performance counters at ipl 3 */
#define X86_CR4_PCE _BITUL(X86_CR4_PCE_BIT)
#define X86_CR4_OSFXSR_BIT 9 /* enable fast FPU save and restore */
#define X86_CR4_OSFXSR _BITUL(X86_CR4_OSFXSR_BIT)
#define X86_CR4_OSXMMEXCPT_BIT 10 /* enable unmasked SSE exceptions */
#define X86_CR4_OSXMMEXCPT _BITUL(X86_CR4_OSXMMEXCPT_BIT)
#define X86_CR4_LA57_BIT 12 /* enable 5-level page tables */
#define X86_CR4_LA57 _BITUL(X86_CR4_LA57_BIT)
#define X86_CR4_VMXE_BIT 13 /* enable VMX virtualization */
#define X86_CR4_VMXE _BITUL(X86_CR4_VMXE_BIT)
#define X86_CR4_SMXE_BIT 14 /* enable safer mode (TXT) */
#define X86_CR4_SMXE _BITUL(X86_CR4_SMXE_BIT)
#define X86_CR4_FSGSBASE_BIT 16 /* enable RDWRFSGS support */
#define X86_CR4_FSGSBASE _BITUL(X86_CR4_FSGSBASE_BIT)
#define X86_CR4_PCIDE_BIT 17 /* enable PCID support */
#define X86_CR4_PCIDE _BITUL(X86_CR4_PCIDE_BIT)
#define X86_CR4_OSXSAVE_BIT 18 /* enable xsave and xrestore */
#define X86_CR4_OSXSAVE _BITUL(X86_CR4_OSXSAVE_BIT)
#define X86_CR4_SMEP_BIT 20 /* enable SMEP support */
#define X86_CR4_SMEP _BITUL(X86_CR4_SMEP_BIT)
#define X86_CR4_SMAP_BIT 21 /* enable SMAP support */
#define X86_CR4_SMAP _BITUL(X86_CR4_SMAP_BIT)
#define X86_CR4_PKE_BIT 22 /* enable Protection Keys support */
#define X86_CR4_PKE _BITUL(X86_CR4_PKE_BIT)
/*
* x86-64 Task Priority Register, CR8
*/
#define X86_CR8_TPR _AC(0x0000000f,UL) /* task priority register */
/*
* AMD and Transmeta use MSRs for configuration; see <asm/msr-index.h>
*/
/*
* NSC/Cyrix CPU configuration register indexes
*/
#define CX86_PCR0 0x20
#define CX86_GCR 0xb8
#define CX86_CCR0 0xc0
#define CX86_CCR1 0xc1
#define CX86_CCR2 0xc2
#define CX86_CCR3 0xc3
#define CX86_CCR4 0xe8
#define CX86_CCR5 0xe9
#define CX86_CCR6 0xea
#define CX86_CCR7 0xeb
#define CX86_PCR1 0xf0
#define CX86_DIR0 0xfe
#define CX86_DIR1 0xff
#define CX86_ARR_BASE 0xc4
#define CX86_RCR_BASE 0xdc
#endif /* _UAPI_ASM_X86_PROCESSOR_FLAGS_H */
|
local inspect ={
_VERSION = 'inspect.lua 3.0.2',
_URL = 'http://github.com/kikito/inspect.lua',
_DESCRIPTION = 'human-readable representations of tables',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 Enrique García Cota
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.
]]
}
inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
-- returns the length of a table, ignoring __len (if it exists)
local rawlen = _G.rawlen or function(t) return #t end
-- Apostrophizes the string if it has quotes, but not aphostrophes
-- Otherwise, it returns a regular quoted string
local function smartQuote(str)
if str:match('"') and not str:match("'") then
return "'" .. str .. "'"
end
return '"' .. str:gsub('"', '\\"') .. '"'
end
local controlCharsTranslation = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
}
local function escape(str)
local result = str:gsub("\\", "\\\\"):gsub("(%c)", controlCharsTranslation)
return result
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
end
local function isSequenceKey(k, length)
return type(k) == 'number'
and 1 <= k
and k <= length
and math.floor(k) == k
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
-- strings and numbers are sorted numerically/alphabetically
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
-- Two default types are compared according to the defaultTypeOrders table
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then return true -- default types before custom ones
elseif dtb then return false -- custom types after default ones
end
-- custom types are sorted out alphabetically
return ta < tb
end
local function getNonSequentialKeys(t)
local keys, length = {}, rawlen(t)
for k,_ in pairs(t) do
if not isSequenceKey(k, length) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys
end
local function getToStringResultSafely(t, mt)
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local str, ok
if type(__tostring) == 'function' then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
end
local maxIdsMetaTable = {
__index = function(self, typeName)
rawset(self, typeName, 0)
return 0
end
}
local idsMetaTable = {
__index = function (self, typeName)
local col = {}
rawset(self, typeName, col)
return col
end
}
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or {}
if type(t) == 'table' then
if not tableAppearances[t] then
tableAppearances[t] = 1
for k,v in pairs(t) do
countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances)
end
countTableAppearances(getmetatable(t), tableAppearances)
else
tableAppearances[t] = tableAppearances[t] + 1
end
end
return tableAppearances
end
local copySequence = function(s)
local copy, len = {}, #s
for i=1, len do copy[i] = s[i] end
return copy, len
end
local function makePath(path, ...)
local keys = {...}
local newPath, len = copySequence(path)
for i=1, #keys do
newPath[len + i] = keys[i]
end
return newPath
end
local function processRecursive(process, item, path)
if item == nil then return nil end
local processed = process(item, path)
if type(processed) == 'table' then
local processedCopy = {}
local processedKey
for k,v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY))
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey))
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE))
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
end
-------------------------------------------------------------------
local Inspector = {}
local Inspector_mt = {__index = Inspector}
function Inspector:puts(...)
local args = {...}
local buffer = self.buffer
local len = #buffer
for i=1, #args do
len = len + 1
buffer[len] = tostring(args[i])
end
end
function Inspector:down(f)
self.level = self.level + 1
f()
self.level = self.level - 1
end
function Inspector:tabify()
self:puts(self.newline, string.rep(self.indent, self.level))
end
function Inspector:alreadyVisited(v)
return self.ids[type(v)][v] ~= nil
end
function Inspector:getId(v)
local tv = type(v)
local id = self.ids[tv][v]
if not id then
id = self.maxIds[tv] + 1
self.maxIds[tv] = id
self.ids[tv][v] = id
end
return id
end
function Inspector:putKey(k)
if isIdentifier(k) then return self:puts(k) end
self:puts("[")
self:putValue(k)
self:puts("]")
end
function Inspector:putTable(t)
if t == inspect.KEY or t == inspect.METATABLE then
self:puts(tostring(t))
elseif self:alreadyVisited(t) then
self:puts('<table ', self:getId(t), '>')
elseif self.level >= self.depth then
self:puts('{...}')
else
if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
local nonSequentialKeys = getNonSequentialKeys(t)
local length = rawlen(t)
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
self:puts('{')
self:down(function()
if toStringResult then
self:puts(' -- ', escape(toStringResult))
if length >= 1 then self:tabify() end
end
local count = 0
for i=1, length do
if count > 0 then self:puts(',') end
self:puts(' ')
self:putValue(t[i])
count = count + 1
end
for _,k in ipairs(nonSequentialKeys) do
if count > 0 then self:puts(',') end
self:tabify()
self:putKey(k)
self:puts(' = ')
self:putValue(t[k])
count = count + 1
end
if mt then
if count > 0 then self:puts(',') end
self:tabify()
self:puts('<metatable> = ')
self:putValue(mt)
end
end)
if #nonSequentialKeys > 0 or mt then -- result is multi-lined. Justify closing }
self:tabify()
elseif length > 0 then -- array tables have one extra space before closing }
self:puts(' ')
end
self:puts('}')
end
end
function Inspector:putValue(v)
local tv = type(v)
if tv == 'string' then
self:puts(smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' then
self:puts(tostring(v))
elseif tv == 'table' then
self:putTable(v)
else
self:puts('<',tv,' ',self:getId(v),'>')
end
end
-------------------------------------------------------------------
function inspect.inspect(root, options)
options = options or {}
local depth = options.depth or math.huge
local newline = options.newline or '\n'
local indent = options.indent or ' '
local process = options.process
if process then
root = processRecursive(process, root, {})
end
local inspector = setmetatable({
depth = depth,
buffer = {},
level = 0,
ids = setmetatable({}, idsMetaTable),
maxIds = setmetatable({}, maxIdsMetaTable),
newline = newline,
indent = indent,
tableAppearances = countTableAppearances(root)
}, Inspector_mt)
inspector:putValue(root)
return table.concat(inspector.buffer)
end
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
return inspect
|
/*
* Common LSM logging functions
* Heavily borrowed from selinux/avc.h
*
* Author : Etienne BASSET <etienne.basset@ensta.org>
*
* All credits to : Stephen Smalley, <sds@tycho.nsa.gov>
* All BUGS to : Etienne BASSET <etienne.basset@ensta.org>
*/
#ifndef _LSM_COMMON_LOGGING_
#define _LSM_COMMON_LOGGING_
#include <linux/stddef.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/kdev_t.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/audit.h>
#include <linux/in6.h>
#include <linux/path.h>
#include <linux/key.h>
#include <linux/skbuff.h>
#include <rdma/ib_verbs.h>
struct lsm_network_audit {
int netif;
struct sock *sk;
u16 family;
__be16 dport;
__be16 sport;
union {
struct {
__be32 daddr;
__be32 saddr;
} v4;
struct {
struct in6_addr daddr;
struct in6_addr saddr;
} v6;
} fam;
};
struct lsm_ioctlop_audit {
struct path path;
u16 cmd;
};
struct lsm_ibpkey_audit {
u64 subnet_prefix;
u16 pkey;
};
struct lsm_ibendport_audit {
char dev_name[IB_DEVICE_NAME_MAX];
u8 port;
};
/* Auxiliary data to use in generating the audit record. */
struct common_audit_data {
char type;
#define LSM_AUDIT_DATA_PATH 1
#define LSM_AUDIT_DATA_NET 2
#define LSM_AUDIT_DATA_CAP 3
#define LSM_AUDIT_DATA_IPC 4
#define LSM_AUDIT_DATA_TASK 5
#define LSM_AUDIT_DATA_KEY 6
#define LSM_AUDIT_DATA_NONE 7
#define LSM_AUDIT_DATA_KMOD 8
#define LSM_AUDIT_DATA_INODE 9
#define LSM_AUDIT_DATA_DENTRY 10
#define LSM_AUDIT_DATA_IOCTL_OP 11
#define LSM_AUDIT_DATA_FILE 12
#define LSM_AUDIT_DATA_IBPKEY 13
#define LSM_AUDIT_DATA_IBENDPORT 14
union {
struct path path;
struct dentry *dentry;
struct inode *inode;
struct lsm_network_audit *net;
int cap;
int ipc_id;
struct task_struct *tsk;
#ifdef CONFIG_KEYS
struct {
key_serial_t key;
char *key_desc;
} key_struct;
#endif
char *kmod_name;
struct lsm_ioctlop_audit *op;
struct file *file;
struct lsm_ibpkey_audit *ibpkey;
struct lsm_ibendport_audit *ibendport;
} u;
/* this union contains LSM specific data */
union {
#ifdef CONFIG_SECURITY_SMACK
struct smack_audit_data *smack_audit_data;
#endif
#ifdef CONFIG_SECURITY_SELINUX
struct selinux_audit_data *selinux_audit_data;
#endif
#ifdef CONFIG_SECURITY_APPARMOR
struct apparmor_audit_data *apparmor_audit_data;
#endif
}; /* per LSM data pointer union */
};
#define v4info fam.v4
#define v6info fam.v6
int ipv4_skb_to_auditdata(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto);
int ipv6_skb_to_auditdata(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto);
void common_lsm_audit(struct common_audit_data *a,
void (*pre_audit)(struct audit_buffer *, void *),
void (*post_audit)(struct audit_buffer *, void *));
#endif
|
<?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/>.
/**
* @package moodlecore
* @subpackage backup-dbops
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Non instantiable helper class providing DB support to the @restore_controller
*
* This class contains various static methods available for all the DB operations
* performed by the restore_controller class
*
* TODO: Finish phpdocs
*/
abstract class restore_controller_dbops extends restore_dbops {
/**
* Send one restore controller to DB
*
* @param restore_controller $controller controller to send to DB
* @param string $checksum hash of the controller to be checked
* @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
* @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
* @return int id of the controller record in the DB
* @throws backup_controller_exception|restore_dbops_exception
*/
public static function save_controller($controller, $checksum, $includeobj = true, $cleanobj = false) {
global $DB;
// Check we are going to save one backup_controller
if (! $controller instanceof restore_controller) {
throw new backup_controller_exception('restore_controller_expected');
}
// Check checksum is ok. Only if we are including object info. Sounds silly but it isn't ;-).
if ($includeobj and !$controller->is_checksum_correct($checksum)) {
throw new restore_dbops_exception('restore_controller_dbops_saving_checksum_mismatch');
}
// Cannot request to $includeobj and $cleanobj at the same time.
if ($includeobj and $cleanobj) {
throw new restore_dbops_exception('restore_controller_dbops_saving_cannot_include_and_delete');
}
// Get all the columns
$rec = new stdclass();
$rec->backupid = $controller->get_restoreid();
$rec->operation = $controller->get_operation();
$rec->type = $controller->get_type();
$rec->itemid = $controller->get_courseid();
$rec->format = $controller->get_format();
$rec->interactive = $controller->get_interactive();
$rec->purpose = $controller->get_mode();
$rec->userid = $controller->get_userid();
$rec->status = $controller->get_status();
$rec->execution = $controller->get_execution();
$rec->executiontime= $controller->get_executiontime();
$rec->checksum = $checksum;
// Serialize information
if ($includeobj) {
$rec->controller = base64_encode(serialize($controller));
} else if ($cleanobj) {
$rec->controller = '';
}
// Send it to DB
if ($recexists = $DB->get_record('backup_controllers', array('backupid' => $rec->backupid))) {
$rec->id = $recexists->id;
$rec->timemodified = time();
$DB->update_record('backup_controllers', $rec);
} else {
$rec->timecreated = time();
$rec->timemodified = 0;
$rec->id = $DB->insert_record('backup_controllers', $rec);
}
return $rec->id;
}
public static function load_controller($restoreid) {
global $DB;
if (! $controllerrec = $DB->get_record('backup_controllers', array('backupid' => $restoreid))) {
throw new backup_dbops_exception('restore_controller_dbops_nonexisting');
}
$controller = unserialize(base64_decode($controllerrec->controller));
if (!is_object($controller)) {
// The controller field of the table did not contain a serialized object.
// It is made empty after it has been used successfully, it is likely that
// the user has pressed the browser back button at some point.
throw new backup_dbops_exception('restore_controller_dbops_loading_invalid_controller');
}
// Check checksum is ok. Sounds silly but it isn't ;-)
if (!$controller->is_checksum_correct($controllerrec->checksum)) {
throw new backup_dbops_exception('restore_controller_dbops_loading_checksum_mismatch');
}
return $controller;
}
public static function create_restore_temp_tables($restoreid) {
global $CFG, $DB;
$dbman = $DB->get_manager(); // We are going to use database_manager services
if ($dbman->table_exists('backup_ids_temp')) { // Table exists, from restore prechecks
// TODO: Improve this by inserting/selecting some record to see there is restoreid match
// TODO: If not match, exception, table corresponds to another backup/restore operation
return true;
}
backup_controller_dbops::create_backup_ids_temp_table($restoreid);
backup_controller_dbops::create_backup_files_temp_table($restoreid);
return false;
}
public static function drop_restore_temp_tables($backupid) {
global $DB;
$dbman = $DB->get_manager(); // We are going to use database_manager services
$targettablenames = array('backup_ids_temp', 'backup_files_temp');
foreach ($targettablenames as $targettablename) {
$table = new xmldb_table($targettablename);
$dbman->drop_table($table); // And drop it
}
// Invalidate the backup_ids caches.
restore_dbops::reset_backup_ids_cached();
}
/**
* Sets the default values for the settings in a restore operation
*
* @param restore_controller $controller
*/
public static function apply_config_defaults(restore_controller $controller) {
$settings = array(
'restore_general_users' => 'users',
'restore_general_enrolments' => 'enrolments',
'restore_general_role_assignments' => 'role_assignments',
'restore_general_activities' => 'activities',
'restore_general_blocks' => 'blocks',
'restore_general_filters' => 'filters',
'restore_general_comments' => 'comments',
'restore_general_badges' => 'badges',
'restore_general_calendarevents' => 'calendarevents',
'restore_general_userscompletion' => 'userscompletion',
'restore_general_logs' => 'logs',
'restore_general_histories' => 'grade_histories',
'restore_general_questionbank' => 'questionbank',
'restore_general_groups' => 'groups',
'restore_general_competencies' => 'competencies'
);
self::apply_admin_config_defaults($controller, $settings, true);
$target = $controller->get_target();
if ($target == backup::TARGET_EXISTING_ADDING || $target == backup::TARGET_CURRENT_ADDING) {
$settings = array(
'restore_merge_overwrite_conf' => 'overwrite_conf',
'restore_merge_course_fullname' => 'course_fullname',
'restore_merge_course_shortname' => 'course_shortname',
'restore_merge_course_startdate' => 'course_startdate',
);
self::apply_admin_config_defaults($controller, $settings, true);
}
if ($target == backup::TARGET_EXISTING_DELETING || $target == backup::TARGET_CURRENT_DELETING) {
$settings = array(
'restore_replace_overwrite_conf' => 'overwrite_conf',
'restore_replace_course_fullname' => 'course_fullname',
'restore_replace_course_shortname' => 'course_shortname',
'restore_replace_course_startdate' => 'course_startdate',
'restore_replace_keep_roles_and_enrolments' => 'keep_roles_and_enrolments',
'restore_replace_keep_groups_and_groupings' => 'keep_groups_and_groupings',
);
self::apply_admin_config_defaults($controller, $settings, true);
}
if ($controller->get_mode() == backup::MODE_IMPORT &&
(!$controller->get_interactive()) &&
$controller->get_type() == backup::TYPE_1ACTIVITY) {
// This is duplicate - there is no concept of defaults - these settings must be on.
$settings = array(
'activities',
'blocks',
'filters',
'questionbank'
);
self::force_enable_settings($controller, $settings);
};
// Add some dependencies.
$plan = $controller->get_plan();
if ($plan->setting_exists('overwrite_conf')) {
/** @var restore_course_overwrite_conf_setting $overwriteconf */
$overwriteconf = $plan->get_setting('overwrite_conf');
if ($overwriteconf->get_visibility()) {
foreach (['course_fullname', 'course_shortname', 'course_startdate'] as $settingname) {
if ($plan->setting_exists($settingname)) {
$setting = $plan->get_setting($settingname);
$overwriteconf->add_dependency($setting, setting_dependency::DISABLED_FALSE,
array('defaultvalue' => $setting->get_value()));
}
}
}
}
}
/**
* Returns the default value to be used for a setting from the admin restore config
*
* @param string $config
* @param backup_setting $setting
* @return mixed
*/
private static function get_setting_default($config, $setting) {
$value = get_config('restore', $config);
if (in_array($setting->get_name(), ['course_fullname', 'course_shortname', 'course_startdate']) &&
$setting->get_ui() instanceof backup_setting_ui_defaultcustom) {
// Special case - admin config settings course_fullname, etc. are boolean and the restore settings are strings.
$value = (bool)$value;
if ($value) {
$attributes = $setting->get_ui()->get_attributes();
$value = $attributes['customvalue'];
}
}
if ($setting->get_ui() instanceof backup_setting_ui_select) {
// Make sure the value is a valid option in the select element, otherwise just pick the first from the options list.
// Example: enrolments dropdown may not have the "enrol_withusers" option because users info can not be restored.
$options = array_keys($setting->get_ui()->get_values());
if (!in_array($value, $options)) {
$value = reset($options);
}
}
return $value;
}
/**
* Turn these settings on. No defaults from admin settings.
*
* @param restore_controller $controller
* @param array $settings a map from admin config names to setting names (Config name => Setting name)
*/
private static function force_enable_settings(restore_controller $controller, array $settings) {
$plan = $controller->get_plan();
foreach ($settings as $config => $settingname) {
$value = true;
if ($plan->setting_exists($settingname)) {
$setting = $plan->get_setting($settingname);
// We do not allow this setting to be locked for a duplicate function.
if ($setting->get_status() !== base_setting::NOT_LOCKED) {
$setting->set_status(base_setting::NOT_LOCKED);
}
$setting->set_value($value);
$setting->set_status(base_setting::LOCKED_BY_CONFIG);
} else {
$controller->log('Unknown setting: ' . $settingname, BACKUP::LOG_DEBUG);
}
}
}
/**
* Sets the controller settings default values from the admin config.
*
* @param restore_controller $controller
* @param array $settings a map from admin config names to setting names (Config name => Setting name)
* @param boolean $uselocks whether "locked" admin settings should be honoured
*/
private static function apply_admin_config_defaults(restore_controller $controller, array $settings, $uselocks) {
$plan = $controller->get_plan();
foreach ($settings as $config => $settingname) {
if ($plan->setting_exists($settingname)) {
$setting = $plan->get_setting($settingname);
$value = self::get_setting_default($config, $setting);
$locked = (get_config('restore', $config . '_locked') == true);
// We can only update the setting if it isn't already locked by config or permission.
if ($setting->get_status() != base_setting::LOCKED_BY_CONFIG
&& $setting->get_status() != base_setting::LOCKED_BY_PERMISSION
&& $setting->get_ui()->is_changeable()) {
$setting->set_value($value);
if ($uselocks && $locked) {
$setting->set_status(base_setting::LOCKED_BY_CONFIG);
}
}
} else {
$controller->log('Unknown setting: ' . $settingname, BACKUP::LOG_DEBUG);
}
}
}
}
|
<!DOCTYPE HTML>
<title>CSS Test Reference: breaking of a multicolumn</title>
<meta charset="utf-8">
<link rel="author" title="L. David Baron" href="https://dbaron.org/">
<link rel="author" title="Ting-Yu Lin" href="tlin@mozilla.com">
<link rel="author" title="Mozilla" href="https://mozilla.org/">
<style>
.outer {
height: 200px;
width: 800px;
background: rgba(0, 0, 255, 0.3);
position: relative;
}
.blueborders {
position: absolute;
top: 0;
left: 262px; /* 256px first column + (16px gap - 4px rule) / 2 */
width: 268px; /* 256px second column + (16px gap - 4px rule) */
height: 200px;
border-right: blue solid 4px;
border-left: blue solid 4px;
}
.innerbg {
height: 100px;
width: 256px;
background: rgba(255, 0, 255, 0.3);
position: absolute;
top: 0;
}
.inner {
height: 100px;
width: 120px;
font: 16px/1.25 sans-serif;
position: absolute;
top: 0;
}
.lefthalf {
border-right: 2px solid fuchsia;
padding-right: 7px;
}
.righthalf {
padding-left: 7px;
}
</style>
<div class="outer">
<div class="blueborders"></div>
<div class="innerbg" style="left: 0"></div>
<div class="inner lefthalf" style="left: 0">
AAAAA<br>
BBBBB<br>
CCCCC<br>
DDDDD<br>
EEEEE
</div>
<div class="inner righthalf" style="left: 129px">
FFFFF<br>
GGGGG<br>
HHHHH<br>
IIIII<br>
JJJJJ
</div>
<div class="innerbg" style="left: 272px"></div>
<div class="inner lefthalf" style="left: 272px">
KKKKK<br>
LLLLL<br>
MMMMM<br>
NNNNN<br>
OOOOO
</div>
<div class="inner righthalf" style="left: 401px">
PPPPP<br>
QQQQQ<br>
RRRRR<br>
SSSSS<br>
TTTTT
</div>
<div class="innerbg" style="left: 544px"></div>
<div class="inner lefthalf" style="left: 544px">
UUUUU<br>
VVVVV<br>
WWWWW<br>
XXXXX<br>
YYYYY
</div>
<div class="inner righthalf" style="left: 673px">
ZZZZZ<br>
aaaaa<br>
bbbbb<br>
ccccc<br>
ddddd
</div>
</div>
|
package com.temenos.interaction.core.rim;
/*
* #%L
* interaction-core
* %%
* Copyright (C) 2012 - 2013 Temenos Holdings N.V.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import java.util.Collection;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.temenos.interaction.core.hypermedia.ResourceState;
public interface ResourceInteractionModel {
/**
* The current application state.
* @return
*/
public ResourceState getCurrentState();
/**
* The path to this resource
* @return
*/
public String getResourcePath();
/**
* The path to this resource with all ancestors
* @return
*/
public String getFQResourcePath();
public ResourceInteractionModel getParent();
public Collection<ResourceInteractionModel> getChildren();
@OPTIONS
public Response options( @Context HttpHeaders headers, @PathParam("id") String id, @Context UriInfo uriInfo );
}
|
/*
* Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
*
* Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
*/
#include <dirent.h>
#include <errno.h>
#define __need_NULL
#include <stddef.h>
#include "dirstream.h"
#ifndef __READDIR
# define __READDIR readdir
# define __DIRENT_TYPE struct dirent
# define __GETDENTS __getdents
#endif
__DIRENT_TYPE *__READDIR(DIR * dir)
{
ssize_t bytes;
__DIRENT_TYPE *de;
if (!dir) {
__set_errno(EBADF);
return NULL;
}
__UCLIBC_MUTEX_LOCK(dir->dd_lock);
do {
if (dir->dd_size <= dir->dd_nextloc) {
/* read dir->dd_max bytes of directory entries. */
bytes = __GETDENTS(dir->dd_fd, dir->dd_buf, dir->dd_max);
if (bytes <= 0) {
de = NULL;
goto all_done;
}
dir->dd_size = bytes;
dir->dd_nextloc = 0;
}
de = (__DIRENT_TYPE *) (((char *) dir->dd_buf) + dir->dd_nextloc);
/* Am I right? H.J. */
dir->dd_nextloc += de->d_reclen;
/* We have to save the next offset here. */
dir->dd_nextoff = de->d_off;
/* Skip deleted files. */
} while (de->d_ino == 0);
all_done:
__UCLIBC_MUTEX_UNLOCK(dir->dd_lock);
return de;
}
libc_hidden_def(__READDIR)
#if defined __UCLIBC_HAS_LFS__ && __WORDSIZE == 64
strong_alias_untyped(readdir,readdir64)
libc_hidden_def(readdir64)
#endif
|
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#pragma once
#include "RichardsSeff.h"
#include "RichardsSeffVG.h"
/**
* van-Genuchten water effective saturation as a function of (Pwater, Pgas),
* and its derivs wrt to those pressures. Note that the water pressure appears
* first in the tuple (Pwater, Pgas)
*/
class RichardsSeff2waterVG : public RichardsSeff
{
public:
static InputParameters validParams();
RichardsSeff2waterVG(const InputParameters & parameters);
/**
* water effective saturation
* @param p porepressures. Here (*p[0])[qp] is the water pressure at quadpoint qp, and
* (*p[1])[qp] is the gas porepressure
* @param qp the quadpoint to evaluate effective saturation at
*/
Real seff(std::vector<const VariableValue *> p, unsigned int qp) const;
/**
* derivative of effective saturation as a function of porepressure
* @param p porepressure in the element. Note that (*p[0])[qp] is the porepressure at quadpoint
* qp
* @param qp the quad point to evaluate effective saturation at
* @param result the derivtives will be placed in this array
*/
void
dseff(std::vector<const VariableValue *> p, unsigned int qp, std::vector<Real> & result) const;
/**
* second derivative of effective saturation as a function of porepressure
* @param p porepressure in the element. Note that (*p[0])[qp] is the porepressure at quadpoint
* qp
* @param qp the quad point to evaluate effective saturation at
* @param result the derivtives will be placed in this array
*/
void d2seff(std::vector<const VariableValue *> p,
unsigned int qp,
std::vector<std::vector<Real>> & result) const;
protected:
/// van Genuchten alpha parameter
Real _al;
/// van Genuchten m parameter
Real _m;
};
|
# Compute Plane Small Strain
!syntax description /Materials/ADComputePlaneSmallStrain
## Description
The material `ADComputePlaneSmallStrain` calculates the small total
strain for 2D plane strain problems. It can be used for classical
[plane strain or plane stress](https://en.wikipedia.org/wiki/Plane_stress)
problems, or in
[Generalized Plane Strain](tensor_mechanics/generalized_plane_strain.md) simulations.
## Out of Plane Strain
In the classical plane strain problem, it is assumed that the front and back
surfaces of the body are constrained in the out-of-plane direction, and that
the displacements in that direction on those surfaces are zero. As a
result, the strain and deformation gradient components in the out-of-plane
direction are held constant at zero:
\begin{equation}
\label{eqn:classical_dop_deform_grad}
\epsilon|^{dop} = 0
\end{equation}
$\epsilon|^{dop}$ is the strain tensor diagonal component for the
direction of the out-of-plane strain.
### Plane Stress and Generalized Plane Strain
In the cases of the plane stress and generalized plane strain assumptions, the
component of strain and the deformation gradient in the out-of-plane direction
is non-zero. To solve for this out-of-plane strain, we use the out-of-plane
strain variable as the strain tensor component
\begin{equation}
\label{eqn:dop_deform_grad}
\epsilon|^{dop} = \epsilon|^{op}
\end{equation}
where $\epsilon|^{dop}$ is the strain tensor diagonal component for
the direction of the out-of-plane strain and $\epsilon|^{op}$ is a
prescribed out-of-plane strain value: this strain value can be
given either as a scalar variable or a nonlinear field variable.
The [Generalized Plane Strain](tensor_mechanics/generalized_plane_strain.md)
problems use scalar variables. Multiple scalar variables can be provided such
that one strain calculator is needed for multiple generalized plane strain
models on different subdomains.
For the case of plane stress, the [ADWeakPlaneStress](ADWeakPlaneStress.md) kernel
is used to integrate the out-of-plane component of the stress over the area of
each element, and assemble that integral to the residual of the out-of-plane
strain field variable. This results in a weak enforcement of the condition that
the out-of-plane stress is zero, which allows for re-use of the same constitutive
models for models of all dimensionality.
## Strain and Deformation Gradient Formulation
The definition of a small total linearized strain is
\begin{equation}
\label{eqn:def_small_total_strain}
\epsilon_{ij} = \frac{1}{2} \left( u_{i,j} + u_{j,i} \right)
\end{equation}
The values of each of the strain tensor components depends on the direction
selected by the user as the out-of-plane direction.
#### $Z$-Direction of Out-of-Plane Strain (Default)
The default out-of-plane direction is along the $z$-axis. For this direction
the strain tensor, [eqn:def_small_total_strain], is given as
\begin{equation}
\label{eqn:strain_tensor}
\boldsymbol{\epsilon} = \begin{bmatrix}
u_{x,x} & \frac{1}{2} \left(u_{x,y} + u_{y,x} \right) & 0 \\
\frac{1}{2} \left(u_{x,y} + u_{y,x} \right) & u_{y,y} & 0 \\
0 & 0 & \epsilon|^{dop}
\end{bmatrix}
\end{equation}
where $\epsilon|^{dop}$ is defined in [eqn:dop_deform_grad].
As in the classical presentation of the strain tensor in plane
strain problems, the components of the strain tensor associated
with the $z$-direction are zero; these zero components indicate no
coupling between the in-plane and the out-of-plane strains.
#### $X$-Direction of Out-of-Plane Strain
If the user selects the out-of-plane direction as along the
$x$-direction, the strain tensor from [eqn:def_small_total_strain]
is given as
\begin{equation}
\label{eqn:deform_grads_xdirs}
\boldsymbol{\epsilon} = \begin{bmatrix}
\epsilon|^{dop} & 0 & 0 \\
0 & u_{y,y} & \frac{1}{2} \left(u_{y,z} + u_{z,y} \right) \\
0 & \frac{1}{2} \left(u_{y,z} + u_{z,y} \right) & u_{z,z}
\end{bmatrix}
\end{equation}
so that the off-diagonal components of the strain tensor associated
with the $x$-direction are zeros.
#### $Y$-Direction of Out-of-Plane Strain
If the user selects the out-of-plane direction as along the
$y$-direction, the strain tensor from [eqn:def_small_total_strain]
is given as
\begin{equation}
\label{eqn:deform_grads_ydirs}
\boldsymbol{\epsilon} = \begin{bmatrix}
u_{x,x} & 0 & \frac{1}{2} \left(u_{x,z} + u_{z,x} \right) \\
0 & \epsilon|^{dop} & 0 \\
\frac{1}{2} \left(u_{x,z} + u_{z,x} \right) & 0 & u_{z,z}
\end{bmatrix}
\end{equation}
so that the off-diagonal components of the strain tensor associated
with the $y$-direction are zeros.
### Volumetric Locking Correction for Strain Tensor
If selected by the user, the strain tensor is conditioned with
a $\bar{B}$ formulation to mitigate volumetric locking of the elements.
The volumetric locking correction is applied to the total strain
\begin{equation}
\label{eqn:vlc_strain}
\boldsymbol{\epsilon}|_{vlc} = \boldsymbol{\epsilon} + \frac{\left( \boldsymbol{\epsilon}_V - tr(\boldsymbol{\epsilon}) \right)}{3} \cdot \boldsymbol{I}
\end{equation}
where $\boldsymbol{\epsilon}_V$ is the volumetric strain and $\boldsymbol{I}$
is the Rank-2 identity tensor. For more details about the theory
behind [eqn:vlc_strain] see the
[Volumetric Locking Correction](/tensor_mechanics/VolumetricLocking.md)
documentation.
## Example Input Files
### Plane Stress
The tensor mechanics [Master action](/Modules/TensorMechanics/Master/index.md)
can be used to create the `ADComputePlaneSmallStrain` class by setting
`planar_formulation = WEAK_PLANE_STRESS` and `strain = SMALL` in the
`Master` action block.
!listing modules/tensor_mechanics/test/tests/plane_stress/weak_plane_stress_small.i block=Modules/TensorMechanics/Master
Note that for plane stress analysis, the `out_of_plane_strain` parameter must be
defined, and is the name of the out-of-plane strain field variable.
!listing modules/tensor_mechanics/test/tests/plane_stress/weak_plane_stress_small.i block=Variables/strain_zz
In the case of this example, `out_of_plane_strain` is defined in the `GlobalParams` block.
### Generalized Plane Strain
The use of this plane strain class for
[Generalized Plane Strain](tensor_mechanics/generalized_plane_strain.md)
simulations uses the scalar out-of-plane strains. The tensor mechanics
[Master action](/Modules/TensorMechanics/Master/index.md) is used to create the
`ADComputePlaneSmallStrain` class with the `planar_formulation = GENERALIZED_PLANE_STRAIN`
and `strain = SMALL` settings.
!listing modules/tensor_mechanics/test/tests/generalized_plane_strain/generalized_plane_strain_small.i block=Modules/TensorMechanics/Master/all
Note that the argument for the `scalar_out_of_plane_strain` parameter is the
name of the scalar strain variable
!listing modules/tensor_mechanics/test/tests/generalized_plane_strain/generalized_plane_strain_small.i block=Variables/scalar_strain_zz
### $Y$-Direction of Out-of-Plane Strain
This plane strain class is used to model plane strain with an out-of-plane strain
in directions other than in the $z$-direction. As an example, the tensor mechanics
[Master action](/Modules/TensorMechanics/Master/index.md) can be used to create
the `ComputePlaneFiniteStrain` class for a $y$-direction out-of-plane strain with
the `planar_formulation = PLANE_STRAIN` and the `out_of_plane_direction = y`
settings.
!listing modules/tensor_mechanics/test/tests/2D_different_planes/planestrain_xz.i block=Modules/TensorMechanics/Master/plane_strain
!syntax parameters /Materials/ADComputePlaneSmallStrain
!syntax inputs /Materials/ADComputePlaneSmallStrain
!syntax children /Materials/ADComputePlaneSmallStrain
!bibtex bibliography
|
dnl AMD64 mpn_addmul_1 and mpn_submul_1.
dnl Copyright 2003-2005, 2007, 2008, 2011, 2012 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C AMD K8,K9 2.52
C AMD K10 2.51
C AMD bd1 4.43
C AMD bd2 5.03 5.63
C AMD bd3 ?
C AMD bd4 ?
C AMD zen ?
C AMD bobcat 6.20
C AMD jaguar 5.57 6.56
C Intel P4 14.9 17.1
C Intel core2 5.15
C Intel NHM 4.93
C Intel SBR 3.95
C Intel IBR 3.75
C Intel HWL 3.62
C Intel BWL 2.53
C Intel SKL 2.53
C Intel atom 21.3
C Intel SLM 9.0
C VIA nano 5.0
C The loop of this code is the result of running a code generation and
C optimization tool suite written by David Harvey and Torbjorn Granlund.
C TODO
C * The loop is great, but the prologue and epilogue code was quickly written.
C Tune it!
define(`rp', `%rdi') C rcx
define(`up', `%rsi') C rdx
define(`n_param', `%rdx') C r8
define(`vl', `%rcx') C r9
define(`n', `%r11')
ifdef(`OPERATION_addmul_1',`
define(`ADDSUB', `add')
define(`func', `mpn_addmul_1')
')
ifdef(`OPERATION_submul_1',`
define(`ADDSUB', `sub')
define(`func', `mpn_submul_1')
')
ABI_SUPPORT(DOS64)
ABI_SUPPORT(STD64)
MULFUNC_PROLOGUE(mpn_addmul_1 mpn_submul_1)
IFDOS(` define(`up', ``%rsi'') ') dnl
IFDOS(` define(`rp', ``%rcx'') ') dnl
IFDOS(` define(`vl', ``%r9'') ') dnl
IFDOS(` define(`r9', ``rdi'') ') dnl
IFDOS(` define(`n', ``%r8'') ') dnl
IFDOS(` define(`r8', ``r11'') ') dnl
ASM_START()
TEXT
ALIGN(16)
PROLOGUE(func)
IFDOS(``push %rsi '')
IFDOS(``push %rdi '')
IFDOS(``mov %rdx, %rsi '')
mov (up), %rax C read first u limb early
push %rbx
IFSTD(` mov n_param, %rbx ') C move away n from rdx, mul uses it
IFDOS(` mov n, %rbx ')
mul vl
IFSTD(` mov %rbx, n ')
and $3, R32(%rbx)
jz L(b0)
cmp $2, R32(%rbx)
jz L(b2)
jg L(b3)
L(b1): dec n
jne L(gt1)
ADDSUB %rax, (rp)
jmp L(ret)
L(gt1): lea 8(up,n,8), up
lea -8(rp,n,8), rp
neg n
xor %r10, %r10
xor R32(%rbx), R32(%rbx)
mov %rax, %r9
mov (up,n,8), %rax
mov %rdx, %r8
jmp L(L1)
L(b0): lea (up,n,8), up
lea -16(rp,n,8), rp
neg n
xor %r10, %r10
mov %rax, %r8
mov %rdx, %rbx
jmp L(L0)
L(b3): lea -8(up,n,8), up
lea -24(rp,n,8), rp
neg n
mov %rax, %rbx
mov %rdx, %r10
jmp L(L3)
L(b2): lea -16(up,n,8), up
lea -32(rp,n,8), rp
neg n
xor %r8, %r8
xor R32(%rbx), R32(%rbx)
mov %rax, %r10
mov 24(up,n,8), %rax
mov %rdx, %r9
jmp L(L2)
ALIGN(16)
L(top): ADDSUB %r10, (rp,n,8)
adc %rax, %r9
mov (up,n,8), %rax
adc %rdx, %r8
mov $0, R32(%r10)
L(L1): mul vl
ADDSUB %r9, 8(rp,n,8)
adc %rax, %r8
adc %rdx, %rbx
L(L0): mov 8(up,n,8), %rax
mul vl
ADDSUB %r8, 16(rp,n,8)
adc %rax, %rbx
adc %rdx, %r10
L(L3): mov 16(up,n,8), %rax
mul vl
ADDSUB %rbx, 24(rp,n,8)
mov $0, R32(%r8) C zero
mov %r8, %rbx C zero
adc %rax, %r10
mov 24(up,n,8), %rax
mov %r8, %r9 C zero
adc %rdx, %r9
L(L2): mul vl
add $4, n
js L(top)
ADDSUB %r10, (rp,n,8)
adc %rax, %r9
adc %r8, %rdx
ADDSUB %r9, 8(rp,n,8)
L(ret): adc $0, %rdx
mov %rdx, %rax
pop %rbx
IFDOS(``pop %rdi '')
IFDOS(``pop %rsi '')
ret
EPILOGUE()
|
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.inject.client.multibindings;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* A very simple multimap implementation that supports conversion to unmodifiable map.
*/
class SimpleMultimap<K, V> extends LinkedHashMap<K, Set<V>> {
public void putItem(K key, V value) {
Set<V> set = get(key);
if (set == null) {
set = new LinkedHashSet<V>();
put(key, set);
}
set.add(value);
}
public Map<K, Set<V>> toUnmodifiable() {
for (Entry<K, Set<V>> entry : entrySet()) {
entry.setValue(Collections.unmodifiableSet(entry.getValue()));
}
return Collections.unmodifiableMap(this);
}
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Operator --x uses [[Default Value]]
*
* @path ch11/11.4/11.4.5/S11.4.5_A2.2_T1.js
* @description If Type(value) is Object, evaluate ToPrimitive(value, Number)
*/
//CHECK#1
var object = {valueOf: function() {return 1}};
if (--object !== 1 - 1) {
$ERROR('#1: var object = {valueOf: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#1: var object = {valueOf: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#2
var object = {valueOf: function() {return 1}, toString: function() {return 0}};
if (--object !== 1 - 1) {
$ERROR('#2: var object = {valueOf: function() {return 1}, toString: function() {return 0}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#2: var object = {valueOf: function() {return 1}, toString: function() {return 0}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#3
var object = {valueOf: function() {return 1}, toString: function() {return {}}};
if (--object !== 1 - 1) {
$ERROR('#3: var object = {valueOf: function() {return 1}, toString: function() {return {}}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#3: var object = {valueOf: function() {return 1}, toString: function() {return {}}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#4
try {
var object = {valueOf: function() {return 1}, toString: function() {throw "error"}};
if (--object !== 1 - 1) {
$ERROR('#4.1: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#4.1: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
}
catch (e) {
if (e === "error") {
$ERROR('#4.2: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object not throw "error"');
} else {
$ERROR('#4.3: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object not throw Error. Actual: ' + (e));
}
}
//CHECK#5
var object = {toString: function() {return 1}};
if (--object !== 1 - 1) {
$ERROR('#5.1: var object = {toString: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#5.2: var object = {toString: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#6
var object = {valueOf: function() {return {}}, toString: function() {return 1}}
if (--object !== 1 - 1) {
$ERROR('#6.1: var object = {valueOf: function() {return {}}, toString: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#6.2: var object = {valueOf: function() {return {}}, toString: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#7
try {
var object = {valueOf: function() {throw "error"}, toString: function() {return 1}};
--object;
$ERROR('#7.1: var object = {valueOf: function() {throw "error"}, toString: function() {return 1}}; --object throw "error". Actual: ' + (--object));
}
catch (e) {
if (e !== "error") {
$ERROR('#7.2: var object = {valueOf: function() {throw "error"}, toString: function() {return 1}}; --object throw "error". Actual: ' + (e));
}
}
//CHECK#8
try {
var object = {valueOf: function() {return {}}, toString: function() {return {}}};
--object;
$ERROR('#8.1: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; --object throw TypeError. Actual: ' + (--object));
}
catch (e) {
if ((e instanceof TypeError) !== true) {
$ERROR('#8.2: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; --object throw TypeError. Actual: ' + (e));
}
}
|
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
/// <reference path="../../../ZumoE2ETestAppJs/ZumoE2ETestAppJs/js/MobileServices.js" />
/// <reference path="/LiveSDKHTML/js/wl.js" />
/// <reference path="../testFramework.js" />
function defineLoginTestsNamespace() {
var tests = [];
var i;
var TABLE_PERMISSION_PUBLIC = 1;
var TABLE_PERMISSION_APPLICATION = 2;
var TABLE_PERMISSION_USER = 3;
var TABLE_PERMISSION_ADMIN = 4;
var TABLE_NAME_PUBLIC = 'public';
var TABLE_NAME_APPLICATION = 'application';
var TABLE_NAME_AUTHENTICATED = 'authenticated';
var TABLE_NAME_ADMIN = 'admin';
var tables = [
{ name: TABLE_NAME_PUBLIC, permission: TABLE_PERMISSION_PUBLIC },
{ name: TABLE_NAME_APPLICATION, permission: TABLE_PERMISSION_APPLICATION },
{ name: TABLE_NAME_AUTHENTICATED, permission: TABLE_PERMISSION_USER },
{ name: TABLE_NAME_ADMIN, permission: TABLE_PERMISSION_ADMIN }];
var supportRecycledToken = {
facebook: true,
google: false, // Known bug - Drop login via Google token until Google client flow is reintroduced
twitter: false,
microsoftaccount: false
};
tests.push(createLogoutTest());
var index, table;
for (index = 0; index < tables.length; index++) {
table = tables[index];
tests.push(createCRUDTest(table.name, null, table.permission, false));
}
var indexOfTestsWithAuthentication = 0;
var lastUserIdentityObject = null;
var providers = ['facebook', 'google', 'twitter', 'microsoftaccount'];
for (i = 0; i < providers.length; i++) {
var provider = providers[i];
tests.push(createLogoutTest());
tests.push(createLoginTest(provider));
for (index = 0; index < tables.length; index++) {
table = tables[index];
if (table.permission !== TABLE_PERMISSION_PUBLIC) {
tests.push(createCRUDTest(table.name, provider, table.permission, true));
}
}
if (supportRecycledToken[provider]) {
tests.push(createLogoutTest());
tests.push(createClientSideLoginTest(provider));
tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
}
}
if (!testPlatform.IsHTMLApplication) {
//In Browser, default is single signon and LIVE SDK is not supported
tests.push(createLogoutTest());
tests.push(createLiveSDKLoginTest());
tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, 'microsoftaccount', TABLE_PERMISSION_USER, true));
providers.forEach(function (provider) {
if (provider === 'microsoftaccount') {
// Known issue - SSO for MS account does not work in application which also uses the Live SDK
} else {
tests.push(createLogoutTest());
tests.push(createLoginTest(provider, true));
tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
}
});
}
for (var i = indexOfTestsWithAuthentication; i < tests.length; i++) {
tests[i].canRunUnattended = false;
}
function createLiveSDKLoginTest() {
var liveSDKInitialized = false;
return new zumo.Test('Login via token with the Live SDK', function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var client = zumo.getClient();
if (!liveSDKInitialized) {
WL.init({ redirect_uri: client.applicationUrl });
liveSDKInitialized = true;
test.addLog('Initialized the WL object');
}
WL.login({ scope: 'wl.basic' }).then(function (wlLoginResult) {
test.addLog('Logged in via Live SDK: ', wlLoginResult);
WL.api({ path: 'me', method: 'GET' }).then(function (wlMeResult) {
test.addLog('My information: ', wlMeResult);
var token = { authenticationToken: wlLoginResult.session.authentication_token };
client.login('microsoftaccount', token).done(function (user) {
test.addLog('Logged in as ', user);
done(true);
}, function (err) {
test.addLog('Error logging into the mobile service: ', err);
done(false);
});
}, function (err) {
test.addLog('Error calling WL.api: ', err);
done(false);
});
}, function (err) {
test.addLog('Error logging in via Live SDK: ', err);
done(false);
});
});
}
function createClientSideLoginTest(provider) {
/// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
/// the client. Currently only 'facebook' and 'google' are supported for this test.</param>
return new zumo.Test('Login via token for ' + provider, function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var client = zumo.getClient();
var lastIdentity = lastUserIdentityObject;
if (!lastIdentity) {
test.addLog('Last identity object is null. Cannot run this test.');
done(false);
} else {
var token = {};
if (provider === 'facebook' || provider === 'google') {
token.access_token = lastIdentity[provider].accessToken;
client.login(provider, token).done(function (user) {
test.addLog('Logged in as ', user);
done(true);
}, function (err) {
test.addLog('Error on login: ', err);
done(false);
});
} else {
test.addLog('Client-side login for ' + provider + ' is not implemented or not supported.');
done(false);
}
}
});
}
function createCRUDTest(tableName, provider, tablePermission, userIsAuthenticated) {
/// <param name="tableName" type="String">The name of the table to attempt the CRUD operations for.</param>
/// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
/// the client.</param>
/// <param name="tablePermission" type="Number" mayBeNull="false">The permission required to access the
/// table. One of the constants defined in the scope.</param>
/// <param name="userIsAuthenticated" type="Boolean" mayBeNull="false">The name of the table to attempt
/// the CRUD operations for.</param>
/// <return type="zumo.Test"/>
var testName = 'CRUD, ' + (userIsAuthenticated ? ('auth by ' + provider) : 'unauthenticated');
testName = testName + ', table with ';
testName = testName + ['public', 'application', 'user', 'admin'][tablePermission - 1];
testName = testName + ' permission.';
return new zumo.Test(testName, function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var crudShouldWork = tablePermission === TABLE_PERMISSION_PUBLIC ||
tablePermission === TABLE_PERMISSION_APPLICATION ||
(tablePermission === TABLE_PERMISSION_USER && userIsAuthenticated);
var client = zumo.getClient();
var table = client.getTable(tableName);
var currentUser = client.currentUser;
var item = { name: 'hello' };
var insertedItem;
var validateCRUDResult = function (operation, error) {
var result = false;
if (crudShouldWork) {
if (error) {
test.addLog(operation + ' should have succeeded, but got error: ', error);
} else {
test.addLog(operation + ' succeeded as expected.');
result = true;
}
} else {
if (error) {
var xhr = error.request;
if (xhr) {
var isInternetExplorer10 = testPlatform.IsHTMLApplication && window.ActiveXObject && window.navigator.userAgent.toLowerCase().match(/msie ([\d.]+)/)[1] == "10.0";
// IE 10 has a bug in which it doesn't set the status code correctly - https://connect.microsoft.com/IE/feedback/details/785990
// so we cannot validate the status code if this is the case.
if (isInternetExplorer10) {
result = true;
} else {
if (xhr.status == 401) {
test.addLog('Got expected response code (401) for ', operation);
result = true;
} else {
zumo.util.traceResponse(test, xhr);
test.addLog('Error, incorrect response.');
}
}
} else {
test.addLog('Error, error object does not have a \'request\' (for the XMLHttpRequest object) property.');
}
} else {
test.addLog(operation + ' should not have succeeded, but the success callback was called.');
}
}
if (!result) {
done(false);
}
return result;
}
// The last of the callbacks, which will call 'done(true);' if validation succeeds.
// called by readCallback
function deleteCallback(error) {
if (validateCRUDResult('delete', error)) {
test.addLog('Validation succeeded for all operations');
done(true);
}
}
// called by updateCallback
function readCallback(error) {
if (validateCRUDResult('read', error)) {
//table.del({ id: insertedItem.id || 1 }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
table.del({ id: insertedItem.id }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
}
}
// called by insertCallback
function updateCallback(error) {
if (validateCRUDResult('update', error)) {
item.id = insertedItem.id || 1;
table.where({ id: item.id }).read().done(function (items) {
test.addLog('Read items: ', items);
if (items.length !== 1) {
test.addLog('Error, query should have returned exactly one item');
done(false);
} else {
var retrievedItem = items[0];
var usersFeatureEnabled = retrievedItem.UsersEnabled;
if (retrievedItem.Identities) {
lastUserIdentityObject = JSON.parse(items[0].Identities);
test.addLog('Identities object: ', lastUserIdentityObject);
var providerName = provider;
if (providerName.toLowerCase() === 'microsoftaccount') {
providerName = 'microsoft';
}
var providerIdentity = lastUserIdentityObject[providerName];
if (!providerIdentity) {
test.addLog('Error, cannot fetch the identity for provider ', providerName);
done(false);
return;
}
if (usersFeatureEnabled) {
var userName = providerIdentity.name || providerIdentity.screen_name;
if (userName) {
test.addLog('Found user name: ', userName);
} else {
test.addLog('Could not find user name!');
done(false);
return;
}
}
}
readCallback();
}
}, function (err) {
readCallback(err);
});
}
}
// called by the callback for insert.
function insertCallback(error) {
if (validateCRUDResult('insert', error)) {
if (tablePermission === TABLE_PERMISSION_PUBLIC) {
// No need for app key anymore
client = new WindowsAzure.MobileServiceClient(client.applicationUrl);
table = client.getTable(tableName);
}
item.id = insertedItem.id || 1;
item.text = 'world';
table.update(item).done(function (newItem) {
test.addLog('Updated item: ', newItem);
updateCallback();
}, function (err) {
updateCallback(err);
});
}
}
table.insert(item).done(function (newItem) {
insertedItem = newItem;
test.addLog('Inserted item: ', newItem);
if (tablePermission === TABLE_PERMISSION_USER) {
var currentUser = client.currentUser.userId;
if (currentUser === newItem.userId) {
test.addLog('User id correctly added by the server script');
} else {
test.addLog('Error, user id not set by the server script');
done(false);
return;
}
}
insertCallback();
}, function (err) {
insertedItem = item;
insertedItem.id = item.id || 1;
insertCallback(err);
});
});
}
function createLoginTest(provider, useSingleSignOn) {
/// <param name="provider" type="String">The authentication provider to use.</param>
/// <param name="useSingleSignOn" type="Boolean">Whether to use the single sign-on parameter for login.</param>
/// <return type="zumo.Test" />
return new zumo.Test('Login with ' + provider + (useSingleSignOn ? ' (using single sign-on)' : ''), function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var client = zumo.getClient();
var successFunction = function (user) {
test.addLog('Logged in: ', user);
done(true);
};
var errorFunction = function (err) {
test.addLog('Error during login: ', err);
done(false);
};
if (useSingleSignOn) {
client.login(provider, true).done(successFunction, errorFunction);
} else {
client.login(provider).done(successFunction, errorFunction);
}
});
}
function createLogoutTest() {
return new zumo.Test('Log out', function (test, done) {
var client = zumo.getClient();
client.logout();
test.addLog('Logged out');
done(true);
});
}
return {
name: 'Login',
tests: tests
};
}
zumo.tests.login = defineLoginTestsNamespace();
|
/****************************************************************
* @nolint
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
/* Please send bug reports to David M. Gay (dmg at acm dot org,
* with " at " changed at "@" and " dot " changed to "."). */
/* On a machine with IEEE extended-precision registers, it is
* necessary to specify double-precision (53-bit) rounding precision
* before invoking strtod or dtoa. If the machine uses (the equivalent
* of) Intel 80x87 arithmetic, the call
* _control87(PC_53, MCW_PC);
* does this with many compilers. Whether this or another call is
* appropriate depends on the compiler; for this to work, it may be
* necessary to #include "float.h" or another system-dependent header
* file.
*/
/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
* (Note that IEEE arithmetic is disabled by gcc's -ffast-math flag.)
*
* This strtod returns a nearest machine number to the input decimal
* string (or sets errno to ERANGE). With IEEE arithmetic, ties are
* broken by the IEEE round-even rule. Otherwise ties are broken by
* biased rounding (add half and chop).
*
* Inspired loosely by William D. Clinger's paper "How to Read Floating
* Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
*
* Modifications:
*
* 1. We only require IEEE, IBM, or VAX double-precision
* arithmetic (not IEEE double-extended).
* 2. We get by with floating-point arithmetic in a case that
* Clinger missed -- when we're computing d * 10^n
* for a small integer d and the integer n is not too
* much larger than 22 (the maximum integer k for which
* we can represent 10^k exactly), we may be able to
* compute (d*10^k) * 10^(e-k) with just one roundoff.
* 3. Rather than a bit-at-a-time adjustment of the binary
* result in the hard case, we use floating-point
* arithmetic to determine the adjustment to within
* one bit; only in really hard cases do we need to
* compute a second residual.
* 4. Because of 3., we don't need a large table of powers of 10
* for ten-to-e (just some small tables, e.g. of 10^k
* for 0 <= k <= 22).
*/
/*
* #define IEEE_8087 for IEEE-arithmetic machines where the least
* significant byte has the lowest address.
* #define IEEE_MC68k for IEEE-arithmetic machines where the most
* significant byte has the lowest address.
* #define Long int on machines with 32-bit ints and 64-bit longs.
* #define IBM for IBM mainframe-style floating-point arithmetic.
* #define VAX for VAX-style floating-point arithmetic (D_floating).
* #define No_leftright to omit left-right logic in fast floating-point
* computation of dtoa. This will cause dtoa modes 4 and 5 to be
* treated the same as modes 2 and 3 for some inputs.
* #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
* and strtod and dtoa should round accordingly. Unless Trust_FLT_ROUNDS
* is also #defined, fegetround() will be queried for the rounding mode.
* Note that both FLT_ROUNDS and fegetround() are specified by the C99
* standard (and are specified to be consistent, with fesetround()
* affecting the value of FLT_ROUNDS), but that some (Linux) systems
* do not work correctly in this regard, so using fegetround() is more
* portable than using FLT_ROUNDS directly.
* #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
* and Honor_FLT_ROUNDS is not #defined.
* #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
* that use extended-precision instructions to compute rounded
* products and quotients) with IBM.
* #define ROUND_BIASED for IEEE-format with biased rounding and arithmetic
* that rounds toward +Infinity.
* #define ROUND_BIASED_without_Round_Up for IEEE-format with biased
* rounding when the underlying floating-point arithmetic uses
* unbiased rounding. This prevent using ordinary floating-point
* arithmetic when the result could be computed with one rounding error.
* #define Inaccurate_Divide for IEEE-format with correctly rounded
* products but inaccurate quotients, e.g., for Intel i860.
* #define NO_LONG_LONG on machines that do not have a "long long"
* integer type (of >= 64 bits). On such machines, you can
* #define Just_16 to store 16 bits per 32-bit Long when doing
* high-precision integer arithmetic. Whether this speeds things
* up or slows things down depends on the machine and the number
* being converted. If long long is available and the name is
* something other than "long long", #define Llong to be the name,
* and if "unsigned Llong" does not work as an unsigned version of
* Llong, #define #ULLong to be the corresponding unsigned type.
* #define KR_headers for old-style C function headers.
* #define Bad_float_h if your system lacks a float.h or if it does not
* define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
* FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
* #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
* if memory is available and otherwise does something you deem
* appropriate. If MALLOC is undefined, malloc will be invoked
* directly -- and assumed always to succeed. Similarly, if you
* want something other than the system's free() to be called to
* recycle memory acquired from MALLOC, #define FREE to be the
* name of the alternate routine. (FREE or free is only called in
* pathological cases, e.g., in a dtoa call after a dtoa return in
* mode 3 with thousands of digits requested.)
* #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
* memory allocations from a private pool of memory when possible.
* When used, the private pool is PRIVATE_MEM bytes long: 2304 bytes,
* unless #defined to be a different length. This default length
* suffices to get rid of MALLOC calls except for unusual cases,
* such as decimal-to-binary conversion of a very long string of
* digits. The longest string dtoa can return is about 751 bytes
* long. For conversions by strtod of strings of 800 digits and
* all dtoa conversions in single-threaded executions with 8-byte
* pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
* pointers, PRIVATE_MEM >= 7112 appears adequate.
* #define NO_INFNAN_CHECK if you do not wish to have INFNAN_CHECK
* #defined automatically on IEEE systems. On such systems,
* when INFNAN_CHECK is #defined, strtod checks
* for Infinity and NaN (case insensitively). On some systems
* (e.g., some HP systems), it may be necessary to #define NAN_WORD0
* appropriately -- to the most significant word of a quiet NaN.
* (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
* When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
* strtod also accepts (case insensitively) strings of the form
* NaN(x), where x is a string of hexadecimal digits and spaces;
* if there is only one string of hexadecimal digits, it is taken
* for the 52 fraction bits of the resulting NaN; if there are two
* or more strings of hex digits, the first is for the high 20 bits,
* the second and subsequent for the low 32 bits, with intervening
* white space ignored; but if this results in none of the 52
* fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
* and NAN_WORD1 are used instead.
* #define MULTIPLE_THREADS if the system offers preemptively scheduled
* multiple threads. In this case, you must provide (or suitably
* #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
* by FREE_DTOA_LOCK(n) for n = 0 or 1. (The second lock, accessed
* in pow5mult, ensures lazy evaluation of only one copy of high
* powers of 5; omitting this lock would introduce a small
* probability of wasting memory, but would otherwise be harmless.)
* You must also invoke freedtoa(s) to free the value s returned by
* dtoa. You may do so whether or not MULTIPLE_THREADS is #defined.
* #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
* avoids underflows on inputs whose result does not underflow.
* If you #define NO_IEEE_Scale on a machine that uses IEEE-format
* floating-point numbers and flushes underflows to zero rather
* than implementing gradual underflow, then you must also #define
* Sudden_Underflow.
* #define USE_LOCALE to use the current locale's decimal_point value.
* #define SET_INEXACT if IEEE arithmetic is being used and extra
* computation should be done to set the inexact flag when the
* result is inexact and avoid setting inexact when the result
* is exact. In this case, dtoa.c must be compiled in
* an environment, perhaps provided by #include "dtoa.c" in a
* suitable wrapper, that defines two functions,
* int get_inexact(void);
* void clear_inexact(void);
* such that get_inexact() returns a nonzero value if the
* inexact bit is already set, and clear_inexact() sets the
* inexact bit to 0. When SET_INEXACT is #defined, strtod
* also does extra computations to set the underflow and overflow
* flags when appropriate (i.e., when the result is tiny and
* inexact or when it is a numeric value rounded to +-infinity).
* #define NO_ERRNO if strtod should not assign errno = ERANGE when
* the result overflows to +-Infinity or underflows to 0.
* #define NO_HEX_FP to omit recognition of hexadecimal floating-point
* values by strtod.
* #define NO_STRTOD_BIGCOMP (on IEEE-arithmetic systems only for now)
* to disable logic for "fast" testing of very long input strings
* to strtod. This testing proceeds by initially truncating the
* input string, then if necessary comparing the whole string with
* a decimal expansion to decide close cases. This logic is only
* used for input more than STRTOD_DIGLIM digits long (default 40).
*/
#include "phenom/defs.h"
#include "phenom/sysutil.h"
/* --- configuration for phenom --- */
#ifdef WORDS_BIGENDIAN
# define IEEE_MC68k
#else
# define IEEE_8087
#endif
#define MULTIPLE_THREADS
//#define Omit_Private_Memory
static pthread_mutex_t lock[2] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
#define ACQUIRE_DTOA_LOCK(n) pthread_mutex_lock(&lock[n])
#define FREE_DTOA_LOCK(n) pthread_mutex_unlock(&lock[n])
#define Long int32_t
#define ULong uint32_t
/* --- */
#ifndef Long
#define Long long
#endif
#ifndef ULong
typedef unsigned Long ULong;
#endif
#ifdef DEBUG
#define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
#endif
#ifdef Honor_FLT_ROUNDS
#ifndef Trust_FLT_ROUNDS
#include <fenv.h>
#endif
#endif
#ifdef MALLOC
#ifdef KR_headers
extern char *MALLOC();
#else
extern void *MALLOC(size_t);
#endif
#else
#define MALLOC malloc
#endif
#ifndef Omit_Private_Memory
#ifndef PRIVATE_MEM
#define PRIVATE_MEM 2304
#endif
#define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
#endif
#undef IEEE_Arith
#undef Avoid_Underflow
#ifdef IEEE_MC68k
#define IEEE_Arith
#endif
#ifdef IEEE_8087
#define IEEE_Arith
#endif
#ifdef IEEE_Arith
#ifndef NO_INFNAN_CHECK
#undef INFNAN_CHECK
#define INFNAN_CHECK
#endif
#else
#undef INFNAN_CHECK
#define NO_STRTOD_BIGCOMP
#endif
#ifdef Bad_float_h
#ifdef IEEE_Arith
#define DBL_DIG 15
#define DBL_MAX_10_EXP 308
#define DBL_MAX_EXP 1024
#define FLT_RADIX 2
#endif /*IEEE_Arith*/
#ifdef IBM
#define DBL_DIG 16
#define DBL_MAX_10_EXP 75
#define DBL_MAX_EXP 63
#define FLT_RADIX 16
#define DBL_MAX 7.2370055773322621e+75
#endif
#ifdef VAX
#define DBL_DIG 16
#define DBL_MAX_10_EXP 38
#define DBL_MAX_EXP 127
#define FLT_RADIX 2
#define DBL_MAX 1.7014118346046923e+38
#endif
#ifndef LONG_MAX
#define LONG_MAX 2147483647
#endif
#else /* ifndef Bad_float_h */
#include "float.h"
#endif /* Bad_float_h */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef CONST
#ifdef KR_headers
#define CONST /* blank */
#else
#define CONST const
#endif
#endif
#if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
#endif
typedef union { double d; ULong L[2]; } U;
#ifdef IEEE_8087
#define word0(x) (x)->L[1]
#define word1(x) (x)->L[0]
#else
#define word0(x) (x)->L[0]
#define word1(x) (x)->L[1]
#endif
#define dval(x) (x)->d
#ifndef STRTOD_DIGLIM
#define STRTOD_DIGLIM 40
#endif
#ifdef DIGLIM_DEBUG
extern int strtod_diglim;
#else
#define strtod_diglim STRTOD_DIGLIM
#endif
/* The following definition of Storeinc is appropriate for MIPS processors.
* An alternative that might be better on some machines is
* #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
*/
#if defined(IEEE_8087) + defined(VAX)
#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
((unsigned short *)a)[0] = (unsigned short)c, a++)
#else
#define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
((unsigned short *)a)[1] = (unsigned short)c, a++)
#endif
/* #define P DBL_MANT_DIG */
/* Ten_pmax = floor(P*log(2)/log(5)) */
/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
#ifdef IEEE_Arith
#define Exp_shift 20
#define Exp_shift1 20
#define Exp_msk1 0x100000
#define Exp_msk11 0x100000
#define Exp_mask 0x7ff00000
#define P 53
#define Nbits 53
#define Bias 1023
#define Emax 1023
#define Emin (-1022)
#define Exp_1 0x3ff00000
#define Exp_11 0x3ff00000
#define Ebits 11
#define Frac_mask 0xfffff
#define Frac_mask1 0xfffff
#define Ten_pmax 22
#define Bletch 0x10
#define Bndry_mask 0xfffff
#define Bndry_mask1 0xfffff
#define LSB 1
#define Sign_bit 0x80000000
#define Log2P 1
#define Tiny0 0
#define Tiny1 1
#define Quick_max 14
#define Int_max 14
#ifndef NO_IEEE_Scale
#define Avoid_Underflow
#ifdef Flush_Denorm /* debugging option */
#undef Sudden_Underflow
#endif
#endif
#ifndef Flt_Rounds
#ifdef FLT_ROUNDS
#define Flt_Rounds FLT_ROUNDS
#else
#define Flt_Rounds 1
#endif
#endif /*Flt_Rounds*/
#ifdef Honor_FLT_ROUNDS
#undef Check_FLT_ROUNDS
#define Check_FLT_ROUNDS
#else
#define Rounding Flt_Rounds
#endif
#else /* ifndef IEEE_Arith */
#undef Check_FLT_ROUNDS
#undef Honor_FLT_ROUNDS
#undef SET_INEXACT
#undef Sudden_Underflow
#define Sudden_Underflow
#ifdef IBM
#undef Flt_Rounds
#define Flt_Rounds 0
#define Exp_shift 24
#define Exp_shift1 24
#define Exp_msk1 0x1000000
#define Exp_msk11 0x1000000
#define Exp_mask 0x7f000000
#define P 14
#define Nbits 56
#define Bias 65
#define Emax 248
#define Emin (-260)
#define Exp_1 0x41000000
#define Exp_11 0x41000000
#define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
#define Frac_mask 0xffffff
#define Frac_mask1 0xffffff
#define Bletch 4
#define Ten_pmax 22
#define Bndry_mask 0xefffff
#define Bndry_mask1 0xffffff
#define LSB 1
#define Sign_bit 0x80000000
#define Log2P 4
#define Tiny0 0x100000
#define Tiny1 0
#define Quick_max 14
#define Int_max 15
#else /* VAX */
#undef Flt_Rounds
#define Flt_Rounds 1
#define Exp_shift 23
#define Exp_shift1 7
#define Exp_msk1 0x80
#define Exp_msk11 0x800000
#define Exp_mask 0x7f80
#define P 56
#define Nbits 56
#define Bias 129
#define Emax 126
#define Emin (-129)
#define Exp_1 0x40800000
#define Exp_11 0x4080
#define Ebits 8
#define Frac_mask 0x7fffff
#define Frac_mask1 0xffff007f
#define Ten_pmax 24
#define Bletch 2
#define Bndry_mask 0xffff007f
#define Bndry_mask1 0xffff007f
#define LSB 0x10000
#define Sign_bit 0x8000
#define Log2P 1
#define Tiny0 0x80
#define Tiny1 0
#define Quick_max 15
#define Int_max 15
#endif /* IBM, VAX */
#endif /* IEEE_Arith */
#ifndef IEEE_Arith
#define ROUND_BIASED
#else
#ifdef ROUND_BIASED_without_Round_Up
#undef ROUND_BIASED
#define ROUND_BIASED
#endif
#endif
#ifdef RND_PRODQUOT
#define rounded_product(a,b) a = rnd_prod(a, b)
#define rounded_quotient(a,b) a = rnd_quot(a, b)
#ifdef KR_headers
extern double rnd_prod(), rnd_quot();
#else
extern double rnd_prod(double, double), rnd_quot(double, double);
#endif
#else
#define rounded_product(a,b) a *= b
#define rounded_quotient(a,b) a /= b
#endif
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
#define Big1 0xffffffff
#ifndef Pack_32
#define Pack_32
#endif
typedef struct BCinfo BCinfo;
struct
BCinfo {
int dp0, dp1, dplen, dsign, e0,
inexact, nd, nd0, rounding, scale, uflchk;
};
#ifdef KR_headers
#define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
#else
#define FFFFFFFF 0xffffffffUL
#endif
#ifdef NO_LONG_LONG
#undef ULLong
#ifdef Just_16
#undef Pack_32
/* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
* This makes some inner loops simpler and sometimes saves work
* during multiplications, but it often seems to make things slightly
* slower. Hence the default is now to store 32 bits per Long.
*/
#endif
#else /* long long available */
#ifndef Llong
#define Llong long long
#endif
#ifndef ULLong
#define ULLong unsigned Llong
#endif
#endif /* NO_LONG_LONG */
#ifndef MULTIPLE_THREADS
#define ACQUIRE_DTOA_LOCK(n) /*nothing*/
#define FREE_DTOA_LOCK(n) /*nothing*/
#endif
#define Kmax 7
struct
Bigint {
struct Bigint *next;
int k, maxwds, sign, wds;
ULong x[1];
};
typedef struct Bigint Bigint;
static Bigint *freelist[Kmax+1];
static Bigint *
Balloc
#ifdef KR_headers
(k) int k;
#else
(int k)
#endif
{
int x;
Bigint *rv;
#ifndef Omit_Private_Memory
unsigned int len;
#endif
ACQUIRE_DTOA_LOCK(0);
/* The k > Kmax case does not need ACQUIRE_DTOA_LOCK(0), */
/* but this case seems very unlikely. */
if (k <= Kmax && (rv = freelist[k]))
freelist[k] = rv->next;
else {
x = 1 << k;
#ifdef Omit_Private_Memory
rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
#else
len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
/sizeof(double);
if (k <= Kmax && (uint32_t)(pmem_next - private_mem + len) <= PRIVATE_mem) {
rv = (Bigint*)pmem_next;
pmem_next += len;
}
else
rv = (Bigint*)MALLOC(len*sizeof(double));
#endif
rv->k = k;
rv->maxwds = x;
}
FREE_DTOA_LOCK(0);
rv->sign = rv->wds = 0;
return rv;
}
static void
Bfree
#ifdef KR_headers
(v) Bigint *v;
#else
(Bigint *v)
#endif
{
if (v) {
if (v->k > Kmax)
#ifdef FREE
FREE((void*)v);
#else
free((void*)v);
#endif
else {
ACQUIRE_DTOA_LOCK(0);
v->next = freelist[v->k];
freelist[v->k] = v;
FREE_DTOA_LOCK(0);
}
}
}
#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
y->wds*sizeof(Long) + 2*sizeof(int))
static Bigint *
multadd
#ifdef KR_headers
(b, m, a) Bigint *b; int m, a;
#else
(Bigint *b, int m, int a) /* multiply by m and add a */
#endif
{
int i, wds;
#ifdef ULLong
ULong *x;
ULLong carry, y;
#else
ULong carry, *x, y;
#ifdef Pack_32
ULong xi, z;
#endif
#endif
Bigint *b1;
wds = b->wds;
x = b->x;
i = 0;
carry = a;
do {
#ifdef ULLong
y = *x * (ULLong)m + carry;
carry = y >> 32;
*x++ = y & FFFFFFFF;
#else
#ifdef Pack_32
xi = *x;
y = (xi & 0xffff) * m + carry;
z = (xi >> 16) * m + (y >> 16);
carry = z >> 16;
*x++ = (z << 16) + (y & 0xffff);
#else
y = *x * m + carry;
carry = y >> 16;
*x++ = y & 0xffff;
#endif
#endif
}
while(++i < wds);
if (carry) {
if (wds >= b->maxwds) {
b1 = Balloc(b->k+1);
Bcopy(b1, b);
Bfree(b);
b = b1;
}
b->x[wds++] = carry;
b->wds = wds;
}
return b;
}
static Bigint *
s2b
#ifdef KR_headers
(s, nd0, nd, y9, dplen) CONST char *s; int nd0, nd, dplen; ULong y9;
#else
(const char *s, int nd0, int nd, ULong y9, int dplen)
#endif
{
Bigint *b;
int i, k;
Long x, y;
x = (nd + 8) / 9;
for(k = 0, y = 1; x > y; y <<= 1, k++) ;
#ifdef Pack_32
b = Balloc(k);
b->x[0] = y9;
b->wds = 1;
#else
b = Balloc(k+1);
b->x[0] = y9 & 0xffff;
b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
#endif
i = 9;
if (9 < nd0) {
s += 9;
do b = multadd(b, 10, *s++ - '0');
while(++i < nd0);
s += dplen;
}
else
s += dplen + 9;
for(; i < nd; i++)
b = multadd(b, 10, *s++ - '0');
return b;
}
static int
hi0bits
#ifdef KR_headers
(x) ULong x;
#else
(ULong x)
#endif
{
int k = 0;
if (!(x & 0xffff0000)) {
k = 16;
x <<= 16;
}
if (!(x & 0xff000000)) {
k += 8;
x <<= 8;
}
if (!(x & 0xf0000000)) {
k += 4;
x <<= 4;
}
if (!(x & 0xc0000000)) {
k += 2;
x <<= 2;
}
if (!(x & 0x80000000)) {
k++;
if (!(x & 0x40000000))
return 32;
}
return k;
}
static int
lo0bits
#ifdef KR_headers
(y) ULong *y;
#else
(ULong *y)
#endif
{
int k;
ULong x = *y;
if (x & 7) {
if (x & 1)
return 0;
if (x & 2) {
*y = x >> 1;
return 1;
}
*y = x >> 2;
return 2;
}
k = 0;
if (!(x & 0xffff)) {
k = 16;
x >>= 16;
}
if (!(x & 0xff)) {
k += 8;
x >>= 8;
}
if (!(x & 0xf)) {
k += 4;
x >>= 4;
}
if (!(x & 0x3)) {
k += 2;
x >>= 2;
}
if (!(x & 1)) {
k++;
x >>= 1;
if (!x)
return 32;
}
*y = x;
return k;
}
static Bigint *
i2b
#ifdef KR_headers
(i) int i;
#else
(int i)
#endif
{
Bigint *b;
b = Balloc(1);
b->x[0] = i;
b->wds = 1;
return b;
}
static Bigint *
mult
#ifdef KR_headers
(a, b) Bigint *a, *b;
#else
(Bigint *a, Bigint *b)
#endif
{
Bigint *c;
int k, wa, wb, wc;
ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
ULong y;
#ifdef ULLong
ULLong carry, z;
#else
ULong carry, z;
#ifdef Pack_32
ULong z2;
#endif
#endif
if (a->wds < b->wds) {
c = a;
a = b;
b = c;
}
k = a->k;
wa = a->wds;
wb = b->wds;
wc = wa + wb;
if (wc > a->maxwds)
k++;
c = Balloc(k);
for(x = c->x, xa = x + wc; x < xa; x++)
*x = 0;
xa = a->x;
xae = xa + wa;
xb = b->x;
xbe = xb + wb;
xc0 = c->x;
#ifdef ULLong
for(; xb < xbe; xc0++) {
if ((y = *xb++)) {
x = xa;
xc = xc0;
carry = 0;
do {
z = *x++ * (ULLong)y + *xc + carry;
carry = z >> 32;
*xc++ = z & FFFFFFFF;
}
while(x < xae);
*xc = carry;
}
}
#else
#ifdef Pack_32
for(; xb < xbe; xb++, xc0++) {
if (y = *xb & 0xffff) {
x = xa;
xc = xc0;
carry = 0;
do {
z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
carry = z >> 16;
z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
carry = z2 >> 16;
Storeinc(xc, z2, z);
}
while(x < xae);
*xc = carry;
}
if (y = *xb >> 16) {
x = xa;
xc = xc0;
carry = 0;
z2 = *xc;
do {
z = (*x & 0xffff) * y + (*xc >> 16) + carry;
carry = z >> 16;
Storeinc(xc, z, z2);
z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
carry = z2 >> 16;
}
while(x < xae);
*xc = z2;
}
}
#else
for(; xb < xbe; xc0++) {
if (y = *xb++) {
x = xa;
xc = xc0;
carry = 0;
do {
z = *x++ * y + *xc + carry;
carry = z >> 16;
*xc++ = z & 0xffff;
}
while(x < xae);
*xc = carry;
}
}
#endif
#endif
for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
c->wds = wc;
return c;
}
static Bigint *p5s;
static Bigint *
pow5mult
#ifdef KR_headers
(b, k) Bigint *b; int k;
#else
(Bigint *b, int k)
#endif
{
Bigint *b1, *p5, *p51;
int i;
static int p05[3] = { 5, 25, 125 };
if ((i = k & 3))
b = multadd(b, p05[i-1], 0);
if (!(k >>= 2))
return b;
if (!(p5 = p5s)) {
/* first time */
#ifdef MULTIPLE_THREADS
ACQUIRE_DTOA_LOCK(1);
if (!(p5 = p5s)) {
p5 = p5s = i2b(625);
p5->next = 0;
}
FREE_DTOA_LOCK(1);
#else
p5 = p5s = i2b(625);
p5->next = 0;
#endif
}
for(;;) {
if (k & 1) {
b1 = mult(b, p5);
Bfree(b);
b = b1;
}
if (!(k >>= 1))
break;
if (!(p51 = p5->next)) {
#ifdef MULTIPLE_THREADS
ACQUIRE_DTOA_LOCK(1);
if (!(p51 = p5->next)) {
p51 = p5->next = mult(p5,p5);
p51->next = 0;
}
FREE_DTOA_LOCK(1);
#else
p51 = p5->next = mult(p5,p5);
p51->next = 0;
#endif
}
p5 = p51;
}
return b;
}
static Bigint *
lshift
#ifdef KR_headers
(b, k) Bigint *b; int k;
#else
(Bigint *b, int k)
#endif
{
int i, k1, n, n1;
Bigint *b1;
ULong *x, *x1, *xe, z;
#ifdef Pack_32
n = k >> 5;
#else
n = k >> 4;
#endif
k1 = b->k;
n1 = n + b->wds + 1;
for(i = b->maxwds; n1 > i; i <<= 1)
k1++;
b1 = Balloc(k1);
x1 = b1->x;
for(i = 0; i < n; i++)
*x1++ = 0;
x = b->x;
xe = x + b->wds;
#ifdef Pack_32
if (k &= 0x1f) {
k1 = 32 - k;
z = 0;
do {
*x1++ = *x << k | z;
z = *x++ >> k1;
}
while(x < xe);
if ((*x1 = z))
++n1;
}
#else
if (k &= 0xf) {
k1 = 16 - k;
z = 0;
do {
*x1++ = *x << k & 0xffff | z;
z = *x++ >> k1;
}
while(x < xe);
if (*x1 = z)
++n1;
}
#endif
else do
*x1++ = *x++;
while(x < xe);
b1->wds = n1 - 1;
Bfree(b);
return b1;
}
static int
cmp
#ifdef KR_headers
(a, b) Bigint *a, *b;
#else
(Bigint *a, Bigint *b)
#endif
{
ULong *xa, *xa0, *xb, *xb0;
int i, j;
i = a->wds;
j = b->wds;
#ifdef DEBUG
if (i > 1 && !a->x[i-1])
Bug("cmp called with a->x[a->wds-1] == 0");
if (j > 1 && !b->x[j-1])
Bug("cmp called with b->x[b->wds-1] == 0");
#endif
if (i -= j)
return i;
xa0 = a->x;
xa = xa0 + j;
xb0 = b->x;
xb = xb0 + j;
for(;;) {
if (*--xa != *--xb)
return *xa < *xb ? -1 : 1;
if (xa <= xa0)
break;
}
return 0;
}
static Bigint *
diff
#ifdef KR_headers
(a, b) Bigint *a, *b;
#else
(Bigint *a, Bigint *b)
#endif
{
Bigint *c;
int i, wa, wb;
ULong *xa, *xae, *xb, *xbe, *xc;
#ifdef ULLong
ULLong borrow, y;
#else
ULong borrow, y;
#ifdef Pack_32
ULong z;
#endif
#endif
i = cmp(a,b);
if (!i) {
c = Balloc(0);
c->wds = 1;
c->x[0] = 0;
return c;
}
if (i < 0) {
c = a;
a = b;
b = c;
i = 1;
}
else
i = 0;
c = Balloc(a->k);
c->sign = i;
wa = a->wds;
xa = a->x;
xae = xa + wa;
wb = b->wds;
xb = b->x;
xbe = xb + wb;
xc = c->x;
borrow = 0;
#ifdef ULLong
do {
y = (ULLong)*xa++ - *xb++ - borrow;
borrow = y >> 32 & (ULong)1;
*xc++ = y & FFFFFFFF;
}
while(xb < xbe);
while(xa < xae) {
y = *xa++ - borrow;
borrow = y >> 32 & (ULong)1;
*xc++ = y & FFFFFFFF;
}
#else
#ifdef Pack_32
do {
y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
borrow = (y & 0x10000) >> 16;
z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
borrow = (z & 0x10000) >> 16;
Storeinc(xc, z, y);
}
while(xb < xbe);
while(xa < xae) {
y = (*xa & 0xffff) - borrow;
borrow = (y & 0x10000) >> 16;
z = (*xa++ >> 16) - borrow;
borrow = (z & 0x10000) >> 16;
Storeinc(xc, z, y);
}
#else
do {
y = *xa++ - *xb++ - borrow;
borrow = (y & 0x10000) >> 16;
*xc++ = y & 0xffff;
}
while(xb < xbe);
while(xa < xae) {
y = *xa++ - borrow;
borrow = (y & 0x10000) >> 16;
*xc++ = y & 0xffff;
}
#endif
#endif
while(!*--xc)
wa--;
c->wds = wa;
return c;
}
static double
ulp
#ifdef KR_headers
(x) U *x;
#else
(U *x)
#endif
{
Long L;
U u;
L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
#ifndef Avoid_Underflow
#ifndef Sudden_Underflow
if (L > 0) {
#endif
#endif
#ifdef IBM
L |= Exp_msk1 >> 4;
#endif
word0(&u) = L;
word1(&u) = 0;
#ifndef Avoid_Underflow
#ifndef Sudden_Underflow
}
else {
L = -L >> Exp_shift;
if (L < Exp_shift) {
word0(&u) = 0x80000 >> L;
word1(&u) = 0;
}
else {
word0(&u) = 0;
L -= Exp_shift;
word1(&u) = L >= 31 ? 1 : 1 << 31 - L;
}
}
#endif
#endif
return dval(&u);
}
static double
b2d
#ifdef KR_headers
(a, e) Bigint *a; int *e;
#else
(Bigint *a, int *e)
#endif
{
ULong *xa, *xa0, w, y, z;
int k;
U d;
#ifdef VAX
ULong d0, d1;
#else
#define d0 word0(&d)
#define d1 word1(&d)
#endif
xa0 = a->x;
xa = xa0 + a->wds;
y = *--xa;
#ifdef DEBUG
if (!y) Bug("zero y in b2d");
#endif
k = hi0bits(y);
*e = 32 - k;
#ifdef Pack_32
if (k < Ebits) {
d0 = Exp_1 | y >> (Ebits - k);
w = xa > xa0 ? *--xa : 0;
d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
goto ret_d;
}
z = xa > xa0 ? *--xa : 0;
if (k -= Ebits) {
d0 = Exp_1 | y << k | z >> (32 - k);
y = xa > xa0 ? *--xa : 0;
d1 = z << k | y >> (32 - k);
}
else {
d0 = Exp_1 | y;
d1 = z;
}
#else
if (k < Ebits + 16) {
z = xa > xa0 ? *--xa : 0;
d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
w = xa > xa0 ? *--xa : 0;
y = xa > xa0 ? *--xa : 0;
d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
goto ret_d;
}
z = xa > xa0 ? *--xa : 0;
w = xa > xa0 ? *--xa : 0;
k -= Ebits + 16;
d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
y = xa > xa0 ? *--xa : 0;
d1 = w << k + 16 | y << k;
#endif
ret_d:
#ifdef VAX
word0(&d) = d0 >> 16 | d0 << 16;
word1(&d) = d1 >> 16 | d1 << 16;
#else
#undef d0
#undef d1
#endif
return dval(&d);
}
static Bigint *
d2b
#ifdef KR_headers
(d, e, bits) U *d; int *e, *bits;
#else
(U *d, int *e, int *bits)
#endif
{
Bigint *b;
int de = 0, k;
ULong *x, y, z;
#ifndef Sudden_Underflow
int i;
#endif
#ifdef VAX
ULong d0, d1;
d0 = word0(d) >> 16 | word0(d) << 16;
d1 = word1(d) >> 16 | word1(d) << 16;
#else
#define d0 word0(d)
#define d1 word1(d)
#endif
#ifdef Pack_32
b = Balloc(1);
#else
b = Balloc(2);
#endif
x = b->x;
z = d0 & Frac_mask;
d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
#ifdef Sudden_Underflow
de = (int)(d0 >> Exp_shift);
#ifndef IBM
z |= Exp_msk11;
#endif
#else
if ((de = (int)(d0 >> Exp_shift)))
z |= Exp_msk1;
#endif
#ifdef Pack_32
if ((y = d1)) {
if ((k = lo0bits(&y))) {
x[0] = y | z << (32 - k);
z >>= k;
}
else
x[0] = y;
#ifndef Sudden_Underflow
i =
#endif
b->wds = (x[1] = z) ? 2 : 1;
}
else {
k = lo0bits(&z);
x[0] = z;
#ifndef Sudden_Underflow
i =
#endif
b->wds = 1;
k += 32;
}
#else
if (y = d1) {
if (k = lo0bits(&y))
if (k >= 16) {
x[0] = y | z << 32 - k & 0xffff;
x[1] = z >> k - 16 & 0xffff;
x[2] = z >> k;
i = 2;
}
else {
x[0] = y & 0xffff;
x[1] = y >> 16 | z << 16 - k & 0xffff;
x[2] = z >> k & 0xffff;
x[3] = z >> k+16;
i = 3;
}
else {
x[0] = y & 0xffff;
x[1] = y >> 16;
x[2] = z & 0xffff;
x[3] = z >> 16;
i = 3;
}
}
else {
#ifdef DEBUG
if (!z)
Bug("Zero passed to d2b");
#endif
k = lo0bits(&z);
if (k >= 16) {
x[0] = z;
i = 0;
}
else {
x[0] = z & 0xffff;
x[1] = z >> 16;
i = 1;
}
k += 32;
}
while(!x[i])
--i;
b->wds = i + 1;
#endif
#ifndef Sudden_Underflow
if (de) {
#endif
#ifdef IBM
*e = (de - Bias - (P-1) << 2) + k;
*bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
#else
*e = de - Bias - (P-1) + k;
*bits = P - k;
#endif
#ifndef Sudden_Underflow
}
else {
*e = de - Bias - (P-1) + 1 + k;
#ifdef Pack_32
*bits = 32*i - hi0bits(x[i-1]);
#else
*bits = (i+2)*16 - hi0bits(x[i]);
#endif
}
#endif
return b;
}
#undef d0
#undef d1
static double
ratio
#ifdef KR_headers
(a, b) Bigint *a, *b;
#else
(Bigint *a, Bigint *b)
#endif
{
U da, db;
int k, ka, kb;
dval(&da) = b2d(a, &ka);
dval(&db) = b2d(b, &kb);
#ifdef Pack_32
k = ka - kb + 32*(a->wds - b->wds);
#else
k = ka - kb + 16*(a->wds - b->wds);
#endif
#ifdef IBM
if (k > 0) {
word0(&da) += (k >> 2)*Exp_msk1;
if (k &= 3)
dval(&da) *= 1 << k;
}
else {
k = -k;
word0(&db) += (k >> 2)*Exp_msk1;
if (k &= 3)
dval(&db) *= 1 << k;
}
#else
if (k > 0)
word0(&da) += k*Exp_msk1;
else {
k = -k;
word0(&db) += k*Exp_msk1;
}
#endif
return dval(&da) / dval(&db);
}
static CONST double
tens[] = {
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1e20, 1e21, 1e22
#ifdef VAX
, 1e23, 1e24
#endif
};
static CONST double
#ifdef IEEE_Arith
bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
#ifdef Avoid_Underflow
9007199254740992.*9007199254740992.e-256
/* = 2^106 * 1e-256 */
#else
1e-256
#endif
};
/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
/* flag unnecessarily. It leads to a song and dance at the end of strtod. */
#define Scale_Bit 0x10
#define n_bigtens 5
#else
#ifdef IBM
bigtens[] = { 1e16, 1e32, 1e64 };
static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
#define n_bigtens 3
#else
bigtens[] = { 1e16, 1e32 };
static CONST double tinytens[] = { 1e-16, 1e-32 };
#define n_bigtens 2
#endif
#endif
#undef Need_Hexdig
#ifdef INFNAN_CHECK
#ifndef No_Hex_NaN
#define Need_Hexdig
#endif
#endif
#ifndef Need_Hexdig
#ifndef NO_HEX_FP
#define Need_Hexdig
#endif
#endif
#ifdef Need_Hexdig /*{*/
#if 0
static unsigned char hexdig[256];
static void
htinit(unsigned char *h, unsigned char *s, int inc)
{
int i, j;
for(i = 0; (j = s[i]) !=0; i++)
h[j] = i + inc;
}
static void
hexdig_init(void) /* Use of hexdig_init omitted 20121220 to avoid a */
/* race condition when multiple threads are used. */
{
#define USC (unsigned char *)
htinit(hexdig, USC "0123456789", 0x10);
htinit(hexdig, USC "abcdef", 0x10 + 10);
htinit(hexdig, USC "ABCDEF", 0x10 + 10);
}
#else
static unsigned char hexdig[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,
0,26,27,28,29,30,31,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,26,27,28,29,30,31,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
#endif
#endif /* } Need_Hexdig */
#ifdef INFNAN_CHECK
#ifndef NAN_WORD0
#define NAN_WORD0 0x7ff80000
#endif
#ifndef NAN_WORD1
#define NAN_WORD1 0
#endif
static int
match
#ifdef KR_headers
(sp, t) char **sp, *t;
#else
(const char **sp, const char *t)
#endif
{
int c, d;
CONST char *s = *sp;
while((d = *t++)) {
if ((c = *++s) >= 'A' && c <= 'Z')
c += 'a' - 'A';
if (c != d)
return 0;
}
*sp = s + 1;
return 1;
}
#ifndef No_Hex_NaN
static void
hexnan
#ifdef KR_headers
(rvp, sp) U *rvp; CONST char **sp;
#else
(U *rvp, const char **sp)
#endif
{
ULong c, x[2];
CONST char *s;
int c1, havedig, udx0, xshift;
/**** if (!hexdig['0']) hexdig_init(); ****/
x[0] = x[1] = 0;
havedig = xshift = 0;
udx0 = 1;
s = *sp;
/* allow optional initial 0x or 0X */
while((c = *(CONST unsigned char*)(s+1)) && c <= ' ')
++s;
if (s[1] == '0' && (s[2] == 'x' || s[2] == 'X'))
s += 2;
while((c = *(CONST unsigned char*)++s)) {
if ((c1 = hexdig[c]))
c = c1 & 0xf;
else if (c <= ' ') {
if (udx0 && havedig) {
udx0 = 0;
xshift = 1;
}
continue;
}
#ifdef GDTOA_NON_PEDANTIC_NANCHECK
else if (/*(*/ c == ')' && havedig) {
*sp = s + 1;
break;
}
else
return; /* invalid form: don't change *sp */
#else
else {
do {
if (/*(*/ c == ')') {
*sp = s + 1;
break;
}
} while((c = *++s));
break;
}
#endif
havedig = 1;
if (xshift) {
xshift = 0;
x[0] = x[1];
x[1] = 0;
}
if (udx0)
x[0] = (x[0] << 4) | (x[1] >> 28);
x[1] = (x[1] << 4) | c;
}
if ((x[0] &= 0xfffff) || x[1]) {
word0(rvp) = Exp_mask | x[0];
word1(rvp) = x[1];
}
}
#endif /*No_Hex_NaN*/
#endif /* INFNAN_CHECK */
#ifdef Pack_32
#define ULbits 32
#define kshift 5
#define kmask 31
#else
#define ULbits 16
#define kshift 4
#define kmask 15
#endif
#if !defined(NO_HEX_FP) || defined(Honor_FLT_ROUNDS) /*{*/
static Bigint *
#ifdef KR_headers
increment(b) Bigint *b;
#else
increment(Bigint *b)
#endif
{
ULong *x, *xe;
Bigint *b1;
x = b->x;
xe = x + b->wds;
do {
if (*x < (ULong)0xffffffffL) {
++*x;
return b;
}
*x++ = 0;
} while(x < xe);
{
if (b->wds >= b->maxwds) {
b1 = Balloc(b->k+1);
Bcopy(b1,b);
Bfree(b);
b = b1;
}
b->x[b->wds++] = 1;
}
return b;
}
#endif /*}*/
#ifndef NO_HEX_FP /*{*/
static void
#ifdef KR_headers
rshift(b, k) Bigint *b; int k;
#else
rshift(Bigint *b, int k)
#endif
{
ULong *x, *x1, *xe, y;
int n;
x = x1 = b->x;
n = k >> kshift;
if (n < b->wds) {
xe = x + b->wds;
x += n;
if (k &= kmask) {
n = 32 - k;
y = *x++ >> k;
while(x < xe) {
*x1++ = (y | (*x << n)) & 0xffffffff;
y = *x++ >> k;
}
if ((*x1 = y) !=0)
x1++;
}
else
while(x < xe)
*x1++ = *x++;
}
if ((b->wds = x1 - b->x) == 0)
b->x[0] = 0;
}
static ULong
#ifdef KR_headers
any_on(b, k) Bigint *b; int k;
#else
any_on(Bigint *b, int k)
#endif
{
int n, nwds;
ULong *x, *x0, x1, x2;
x = b->x;
nwds = b->wds;
n = k >> kshift;
if (n > nwds)
n = nwds;
else if (n < nwds && (k &= kmask)) {
x1 = x2 = x[n];
x1 >>= k;
x1 <<= k;
if (x1 != x2)
return 1;
}
x0 = x;
x += n;
while(x > x0)
if (*--x)
return 1;
return 0;
}
enum { /* rounding values: same as FLT_ROUNDS */
Round_zero = 0,
Round_near = 1,
Round_up = 2,
Round_down = 3
};
static void
#ifdef KR_headers
gethex(sp, rvp, rounding, sign)
CONST char **sp; U *rvp; int rounding, sign;
#else
gethex( CONST char **sp, U *rvp, int rounding, int sign)
#endif
{
Bigint *b;
CONST unsigned char *decpt, *s0, *s, *s1;
Long e, e1;
ULong L, lostbits, *x;
int big, denorm, esign, havedig, k, n, nbits, up, zret;
#ifdef IBM
int j;
#endif
enum {
#ifdef IEEE_Arith /*{{*/
emax = 0x7fe - Bias - P + 1,
emin = Emin - P + 1
#else /*}{*/
emin = Emin - P,
#ifdef VAX
emax = 0x7ff - Bias - P + 1
#endif
#ifdef IBM
emax = 0x7f - Bias - P
#endif
#endif /*}}*/
};
#ifdef USE_LOCALE
int i;
#ifdef NO_LOCALE_CACHE
const unsigned char *decimalpoint = (unsigned char*)
localeconv()->decimal_point;
#else
const unsigned char *decimalpoint;
static unsigned char *decimalpoint_cache;
if (!(s0 = decimalpoint_cache)) {
s0 = (unsigned char*)localeconv()->decimal_point;
if ((decimalpoint_cache = (unsigned char*)
MALLOC(strlen((CONST char*)s0) + 1))) {
strcpy((char*)decimalpoint_cache, (CONST char*)s0);
s0 = decimalpoint_cache;
}
}
decimalpoint = s0;
#endif
#endif
/**** if (!hexdig['0']) hexdig_init(); ****/
havedig = 0;
s0 = *(CONST unsigned char **)sp + 2;
while(s0[havedig] == '0')
havedig++;
s0 += havedig;
s = s0;
decpt = 0;
zret = 0;
e = 0;
if (hexdig[*s])
havedig++;
else {
zret = 1;
#ifdef USE_LOCALE
for(i = 0; decimalpoint[i]; ++i) {
if (s[i] != decimalpoint[i])
goto pcheck;
}
decpt = s += i;
#else
if (*s != '.')
goto pcheck;
decpt = ++s;
#endif
if (!hexdig[*s])
goto pcheck;
while(*s == '0')
s++;
if (hexdig[*s])
zret = 0;
havedig = 1;
s0 = s;
}
while(hexdig[*s])
s++;
#ifdef USE_LOCALE
if (*s == *decimalpoint && !decpt) {
for(i = 1; decimalpoint[i]; ++i) {
if (s[i] != decimalpoint[i])
goto pcheck;
}
decpt = s += i;
#else
if (*s == '.' && !decpt) {
decpt = ++s;
#endif
while(hexdig[*s])
s++;
}/*}*/
if (decpt)
e = -(((Long)(s-decpt)) << 2);
pcheck:
s1 = s;
big = esign = 0;
switch(*s) {
case 'p':
case 'P':
switch(*++s) {
case '-':
esign = 1;
/* no break */
case '+':
s++;
}
if ((n = hexdig[*s]) == 0 || n > 0x19) {
s = s1;
break;
}
e1 = n - 0x10;
while((n = hexdig[*++s]) !=0 && n <= 0x19) {
if (e1 & 0xf8000000)
big = 1;
e1 = 10*e1 + n - 0x10;
}
if (esign)
e1 = -e1;
e += e1;
}
*sp = (char*)s;
if (!havedig)
*sp = (char*)s0 - 1;
if (zret)
goto retz1;
if (big) {
if (esign) {
#ifdef IEEE_Arith
switch(rounding) {
case Round_up:
if (sign)
break;
goto ret_tiny;
case Round_down:
if (!sign)
break;
goto ret_tiny;
}
#endif
goto retz;
#ifdef IEEE_Arith
ret_tiny:
#ifndef NO_ERRNO
errno = ERANGE;
#endif
word0(rvp) = 0;
word1(rvp) = 1;
return;
#endif /* IEEE_Arith */
}
switch(rounding) {
case Round_near:
goto ovfl1;
case Round_up:
if (!sign)
goto ovfl1;
goto ret_big;
case Round_down:
if (sign)
goto ovfl1;
goto ret_big;
}
ret_big:
word0(rvp) = Big0;
word1(rvp) = Big1;
return;
}
n = s1 - s0 - 1;
for(k = 0; n > (1 << (kshift-2)) - 1; n >>= 1)
k++;
b = Balloc(k);
x = b->x;
n = 0;
L = 0;
#ifdef USE_LOCALE
for(i = 0; decimalpoint[i+1]; ++i);
#endif
while(s1 > s0) {
#ifdef USE_LOCALE
if (*--s1 == decimalpoint[i]) {
s1 -= i;
continue;
}
#else
if (*--s1 == '.')
continue;
#endif
if (n == ULbits) {
*x++ = L;
L = 0;
n = 0;
}
L |= (hexdig[*s1] & 0x0f) << n;
n += 4;
}
*x++ = L;
b->wds = n = x - b->x;
n = ULbits*n - hi0bits(L);
nbits = Nbits;
lostbits = 0;
x = b->x;
if (n > nbits) {
n -= nbits;
if (any_on(b,n)) {
lostbits = 1;
k = n - 1;
if (x[k>>kshift] & 1 << (k & kmask)) {
lostbits = 2;
if (k > 0 && any_on(b,k))
lostbits = 3;
}
}
rshift(b, n);
e += n;
}
else if (n < nbits) {
n = nbits - n;
b = lshift(b, n);
e -= n;
x = b->x;
}
if (e > Emax) {
ovfl:
Bfree(b);
ovfl1:
#ifndef NO_ERRNO
errno = ERANGE;
#endif
word0(rvp) = Exp_mask;
word1(rvp) = 0;
return;
}
denorm = 0;
if (e < emin) {
denorm = 1;
n = emin - e;
if (n >= nbits) {
#ifdef IEEE_Arith /*{*/
switch (rounding) {
case Round_near:
if (n == nbits && (n < 2 || any_on(b,n-1)))
goto ret_tiny;
break;
case Round_up:
if (!sign)
goto ret_tiny;
break;
case Round_down:
if (sign)
goto ret_tiny;
}
#endif /* } IEEE_Arith */
Bfree(b);
retz:
#ifndef NO_ERRNO
errno = ERANGE;
#endif
retz1:
rvp->d = 0.;
return;
}
k = n - 1;
if (lostbits)
lostbits = 1;
else if (k > 0)
lostbits = any_on(b,k);
if (x[k>>kshift] & 1 << (k & kmask))
lostbits |= 2;
nbits -= n;
rshift(b,n);
e = emin;
}
if (lostbits) {
up = 0;
switch(rounding) {
case Round_zero:
break;
case Round_near:
if (lostbits & 2
&& (lostbits & 1) | (x[0] & 1))
up = 1;
break;
case Round_up:
up = 1 - sign;
break;
case Round_down:
up = sign;
}
if (up) {
k = b->wds;
b = increment(b);
x = b->x;
if (denorm) {
#if 0
if (nbits == Nbits - 1
&& x[nbits >> kshift] & 1 << (nbits & kmask))
denorm = 0; /* not currently used */
#endif
}
else if (b->wds > k
|| ((n = nbits & kmask) !=0
&& hi0bits(x[k-1]) < 32-n)) {
rshift(b,1);
if (++e > Emax)
goto ovfl;
}
}
}
#ifdef IEEE_Arith
if (denorm)
word0(rvp) = b->wds > 1 ? b->x[1] & ~0x100000 : 0;
else
word0(rvp) = (b->x[1] & ~0x100000) | ((e + 0x3ff + 52) << 20);
word1(rvp) = b->x[0];
#endif
#ifdef IBM
if ((j = e & 3)) {
k = b->x[0] & ((1 << j) - 1);
rshift(b,j);
if (k) {
switch(rounding) {
case Round_up:
if (!sign)
increment(b);
break;
case Round_down:
if (sign)
increment(b);
break;
case Round_near:
j = 1 << (j-1);
if (k & j && ((k & (j-1)) | lostbits))
increment(b);
}
}
}
e >>= 2;
word0(rvp) = b->x[1] | ((e + 65 + 13) << 24);
word1(rvp) = b->x[0];
#endif
#ifdef VAX
/* The next two lines ignore swap of low- and high-order 2 bytes. */
/* word0(rvp) = (b->x[1] & ~0x800000) | ((e + 129 + 55) << 23); */
/* word1(rvp) = b->x[0]; */
word0(rvp) = ((b->x[1] & ~0x800000) >> 16) |
((e + 129 + 55) << 7) | (b->x[1] << 16);
word1(rvp) = (b->x[0] >> 16) | (b->x[0] << 16);
#endif
Bfree(b);
}
#endif /*!NO_HEX_FP}*/
static int
#ifdef KR_headers
dshift(b, p2) Bigint *b; int p2;
#else
dshift(Bigint *b, int p2)
#endif
{
int rv = hi0bits(b->x[b->wds-1]) - 4;
if (p2 > 0)
rv -= p2;
return rv & kmask;
}
static int
quorem
#ifdef KR_headers
(b, S) Bigint *b, *S;
#else
(Bigint *b, Bigint *S)
#endif
{
int n;
ULong *bx, *bxe, q, *sx, *sxe;
#ifdef ULLong
ULLong borrow, carry, y, ys;
#else
ULong borrow, carry, y, ys;
#ifdef Pack_32
ULong si, z, zs;
#endif
#endif
n = S->wds;
#ifdef DEBUG
/*debug*/ if (b->wds > n)
/*debug*/ Bug("oversize b in quorem");
#endif
if (b->wds < n)
return 0;
sx = S->x;
sxe = sx + --n;
bx = b->x;
bxe = bx + n;
q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
#ifdef DEBUG
#ifdef NO_STRTOD_BIGCOMP
/*debug*/ if (q > 9)
#else
/* An oversized q is possible when quorem is called from bigcomp and */
/* the input is near, e.g., twice the smallest denormalized number. */
/*debug*/ if (q > 15)
#endif
/*debug*/ Bug("oversized quotient in quorem");
#endif
if (q) {
borrow = 0;
carry = 0;
do {
#ifdef ULLong
ys = *sx++ * (ULLong)q + carry;
carry = ys >> 32;
y = *bx - (ys & FFFFFFFF) - borrow;
borrow = y >> 32 & (ULong)1;
*bx++ = y & FFFFFFFF;
#else
#ifdef Pack_32
si = *sx++;
ys = (si & 0xffff) * q + carry;
zs = (si >> 16) * q + (ys >> 16);
carry = zs >> 16;
y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
borrow = (y & 0x10000) >> 16;
z = (*bx >> 16) - (zs & 0xffff) - borrow;
borrow = (z & 0x10000) >> 16;
Storeinc(bx, z, y);
#else
ys = *sx++ * q + carry;
carry = ys >> 16;
y = *bx - (ys & 0xffff) - borrow;
borrow = (y & 0x10000) >> 16;
*bx++ = y & 0xffff;
#endif
#endif
}
while(sx <= sxe);
if (!*bxe) {
bx = b->x;
while(--bxe > bx && !*bxe)
--n;
b->wds = n;
}
}
if (cmp(b, S) >= 0) {
q++;
borrow = 0;
carry = 0;
bx = b->x;
sx = S->x;
do {
#ifdef ULLong
ys = *sx++ + carry;
carry = ys >> 32;
y = *bx - (ys & FFFFFFFF) - borrow;
borrow = y >> 32 & (ULong)1;
*bx++ = y & FFFFFFFF;
#else
#ifdef Pack_32
si = *sx++;
ys = (si & 0xffff) + carry;
zs = (si >> 16) + (ys >> 16);
carry = zs >> 16;
y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
borrow = (y & 0x10000) >> 16;
z = (*bx >> 16) - (zs & 0xffff) - borrow;
borrow = (z & 0x10000) >> 16;
Storeinc(bx, z, y);
#else
ys = *sx++ + carry;
carry = ys >> 16;
y = *bx - (ys & 0xffff) - borrow;
borrow = (y & 0x10000) >> 16;
*bx++ = y & 0xffff;
#endif
#endif
}
while(sx <= sxe);
bx = b->x;
bxe = bx + n;
if (!*bxe) {
while(--bxe > bx && !*bxe)
--n;
b->wds = n;
}
}
return q;
}
#if defined(Avoid_Underflow) || !defined(NO_STRTOD_BIGCOMP) /*{*/
static double
sulp
#ifdef KR_headers
(x, bc) U *x; BCinfo *bc;
#else
(U *x, BCinfo *bc)
#endif
{
U u;
double rv;
int i;
rv = ulp(x);
if (!bc->scale || (i = 2*P + 1 - ((word0(x) & Exp_mask) >> Exp_shift)) <= 0)
return rv; /* Is there an example where i <= 0 ? */
word0(&u) = Exp_1 + (i << Exp_shift);
word1(&u) = 0;
return rv * u.d;
}
#endif /*}*/
#ifndef NO_STRTOD_BIGCOMP
static void
bigcomp
#ifdef KR_headers
(rv, s0, bc)
U *rv; CONST char *s0; BCinfo *bc;
#else
(U *rv, const char *s0, BCinfo *bc)
#endif
{
Bigint *b, *d;
int b2, bbits, d2, dd = 0, dig, dsign, i, j, nd, nd0, p2, p5, speccase;
dsign = bc->dsign;
nd = bc->nd;
nd0 = bc->nd0;
p5 = nd + bc->e0 - 1;
speccase = 0;
#ifndef Sudden_Underflow
if (rv->d == 0.) { /* special case: value near underflow-to-zero */
/* threshold was rounded to zero */
b = i2b(1);
p2 = Emin - P + 1;
bbits = 1;
#ifdef Avoid_Underflow
word0(rv) = (P+2) << Exp_shift;
#else
word1(rv) = 1;
#endif
i = 0;
#ifdef Honor_FLT_ROUNDS
if (bc->rounding == 1)
#endif
{
speccase = 1;
--p2;
dsign = 0;
goto have_i;
}
}
else
#endif
b = d2b(rv, &p2, &bbits);
#ifdef Avoid_Underflow
p2 -= bc->scale;
#endif
/* floor(log2(rv)) == bbits - 1 + p2 */
/* Check for denormal case. */
i = P - bbits;
if (i > (j = P - Emin - 1 + p2)) {
#ifdef Sudden_Underflow
Bfree(b);
b = i2b(1);
p2 = Emin;
i = P - 1;
#ifdef Avoid_Underflow
word0(rv) = (1 + bc->scale) << Exp_shift;
#else
word0(rv) = Exp_msk1;
#endif
word1(rv) = 0;
#else
i = j;
#endif
}
#ifdef Honor_FLT_ROUNDS
if (bc->rounding != 1) {
if (i > 0)
b = lshift(b, i);
if (dsign)
b = increment(b);
}
else
#endif
{
b = lshift(b, ++i);
b->x[0] |= 1;
}
#ifndef Sudden_Underflow
have_i:
#endif
p2 -= p5 + i;
d = i2b(1);
/* Arrange for convenient computation of quotients:
* shift left if necessary so divisor has 4 leading 0 bits.
*/
if (p5 > 0)
d = pow5mult(d, p5);
else if (p5 < 0)
b = pow5mult(b, -p5);
if (p2 > 0) {
b2 = p2;
d2 = 0;
}
else {
b2 = 0;
d2 = -p2;
}
i = dshift(d, d2);
if ((b2 += i) > 0)
b = lshift(b, b2);
if ((d2 += i) > 0)
d = lshift(d, d2);
/* Now b/d = exactly half-way between the two floating-point values */
/* on either side of the input string. Compute first digit of b/d. */
if (!(dig = quorem(b,d))) {
b = multadd(b, 10, 0); /* very unlikely */
dig = quorem(b,d);
}
/* Compare b/d with s0 */
for(i = 0; i < nd0; ) {
if ((dd = s0[i++] - '0' - dig))
goto ret;
if (!b->x[0] && b->wds == 1) {
if (i < nd)
dd = 1;
goto ret;
}
b = multadd(b, 10, 0);
dig = quorem(b,d);
}
for(j = bc->dp1; i++ < nd;) {
if ((dd = s0[j++] - '0' - dig))
goto ret;
if (!b->x[0] && b->wds == 1) {
if (i < nd)
dd = 1;
goto ret;
}
b = multadd(b, 10, 0);
dig = quorem(b,d);
}
if (dig > 0 || b->x[0] || b->wds > 1)
dd = -1;
ret:
Bfree(b);
Bfree(d);
#ifdef Honor_FLT_ROUNDS
if (bc->rounding != 1) {
if (dd < 0) {
if (bc->rounding == 0) {
if (!dsign)
goto retlow1;
}
else if (dsign)
goto rethi1;
}
else if (dd > 0) {
if (bc->rounding == 0) {
if (dsign)
goto rethi1;
goto ret1;
}
if (!dsign)
goto rethi1;
dval(rv) += 2.*sulp(rv,bc);
}
else {
bc->inexact = 0;
if (dsign)
goto rethi1;
}
}
else
#endif
if (speccase) {
if (dd <= 0)
rv->d = 0.;
}
else if (dd < 0) {
if (!dsign) /* does not happen for round-near */
retlow1:
dval(rv) -= sulp(rv,bc);
}
else if (dd > 0) {
if (dsign) {
rethi1:
dval(rv) += sulp(rv,bc);
}
}
else {
/* Exact half-way case: apply round-even rule. */
if ((j = ((word0(rv) & Exp_mask) >> Exp_shift) - bc->scale) <= 0) {
i = 1 - j;
if (i <= 31) {
if (word1(rv) & (0x1 << i))
goto odd;
}
else if (word0(rv) & (0x1 << (i-32)))
goto odd;
}
else if (word1(rv) & 1) {
odd:
if (dsign)
goto rethi1;
goto retlow1;
}
}
#ifdef Honor_FLT_ROUNDS
ret1:
#endif
return;
}
#endif /* NO_STRTOD_BIGCOMP */
double
ph_strtod
#ifdef KR_headers
(s00, se) CONST char *s00; char **se;
#else
(const char *s00, const char **se)
#endif
{
int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, e, e1;
int esign, i, j, k, nd, nd0, nf, nz, nz0, nz1, sign;
CONST char *s, *s0, *s1;
double aadj, aadj1;
Long L;
U aadj2, adj, rv, rv0 = {0};
ULong y, z;
BCinfo bc;
Bigint *bb = 0, *bb1 = 0, *bd = 0, *bd0 = 0, *bs = 0, *delta = 0;
#ifdef Avoid_Underflow
ULong Lsb, Lsb1;
#endif
#ifdef SET_INEXACT
int oldinexact;
#endif
#ifndef NO_STRTOD_BIGCOMP
int req_bigcomp = 0;
#endif
#ifdef Honor_FLT_ROUNDS /*{*/
#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
bc.rounding = Flt_Rounds;
#else /*}{*/
bc.rounding = 1;
switch(fegetround()) {
case FE_TOWARDZERO: bc.rounding = 0; break;
case FE_UPWARD: bc.rounding = 2; break;
case FE_DOWNWARD: bc.rounding = 3;
}
#endif /*}}*/
#endif /*}*/
#ifdef USE_LOCALE
CONST char *s2;
#endif
sign = nz0 = nz1 = nz = bc.dplen = bc.uflchk = 0;
dval(&rv) = 0.;
for(s = s00;;s++) switch(*s) {
case '-':
sign = 1;
/* no break */
case '+':
if (*++s)
goto break2;
/* no break */
case 0:
goto ret0;
case '\t':
case '\n':
case '\v':
case '\f':
case '\r':
case ' ':
continue;
default:
goto break2;
}
break2:
if (*s == '0') {
#ifndef NO_HEX_FP /*{*/
switch(s[1]) {
case 'x':
case 'X':
#ifdef Honor_FLT_ROUNDS
gethex(&s, &rv, bc.rounding, sign);
#else
gethex(&s, &rv, 1, sign);
#endif
goto ret;
}
#endif /*}*/
nz0 = 1;
while(*++s == '0') ;
if (!*s)
goto ret;
}
s0 = s;
y = z = 0;
for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
if (nd < 9)
y = 10*y + c - '0';
else if (nd < 16)
z = 10*z + c - '0';
nd0 = nd;
bc.dp0 = bc.dp1 = s - s0;
for(s1 = s; s1 > s0 && *--s1 == '0'; )
++nz1;
#ifdef USE_LOCALE
s1 = localeconv()->decimal_point;
if (c == *s1) {
c = '.';
if (*++s1) {
s2 = s;
for(;;) {
if (*++s2 != *s1) {
c = 0;
break;
}
if (!*++s1) {
s = s2;
break;
}
}
}
}
#endif
if (c == '.') {
c = *++s;
bc.dp1 = s - s0;
bc.dplen = bc.dp1 - bc.dp0;
if (!nd) {
for(; c == '0'; c = *++s)
nz++;
if (c > '0' && c <= '9') {
bc.dp0 = s0 - s;
bc.dp1 = bc.dp0 + bc.dplen;
s0 = s;
nf += nz;
nz = 0;
goto have_dig;
}
goto dig_done;
}
for(; c >= '0' && c <= '9'; c = *++s) {
have_dig:
nz++;
if (c -= '0') {
nf += nz;
for(i = 1; i < nz; i++)
if (nd++ < 9)
y *= 10;
else if (nd <= DBL_DIG + 1)
z *= 10;
if (nd++ < 9)
y = 10*y + c;
else if (nd <= DBL_DIG + 1)
z = 10*z + c;
nz = nz1 = 0;
}
}
}
dig_done:
e = 0;
if (c == 'e' || c == 'E') {
if (!nd && !nz && !nz0) {
goto ret0;
}
s00 = s;
esign = 0;
switch(c = *++s) {
case '-':
esign = 1;
case '+':
c = *++s;
}
if (c >= '0' && c <= '9') {
while(c == '0')
c = *++s;
if (c > '0' && c <= '9') {
L = c - '0';
s1 = s;
while((c = *++s) >= '0' && c <= '9')
L = 10*L + c - '0';
if (s - s1 > 8 || L > 19999)
/* Avoid confusion from exponents
* so large that e might overflow.
*/
e = 19999; /* safe for 16 bit ints */
else
e = (int)L;
if (esign)
e = -e;
}
else
e = 0;
}
else
s = s00;
}
if (!nd) {
if (!nz && !nz0) {
#ifdef INFNAN_CHECK
/* Check for Nan and Infinity */
if (!bc.dplen)
switch(c) {
case 'i':
case 'I':
if (match(&s,"nf")) {
--s;
if (!match(&s,"inity"))
++s;
word0(&rv) = 0x7ff00000;
word1(&rv) = 0;
goto ret;
}
break;
case 'n':
case 'N':
if (match(&s, "an")) {
word0(&rv) = NAN_WORD0;
word1(&rv) = NAN_WORD1;
#ifndef No_Hex_NaN
if (*s == '(') /*)*/
hexnan(&rv, &s);
#endif
goto ret;
}
}
#endif /* INFNAN_CHECK */
ret0:
s = s00;
sign = 0;
}
goto ret;
}
bc.e0 = e1 = e -= nf;
/* Now we have nd0 digits, starting at s0, followed by a
* decimal point, followed by nd-nd0 digits. The number we're
* after is the integer represented by those digits times
* 10**e */
if (!nd0)
nd0 = nd;
k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
dval(&rv) = y;
if (k > 9) {
#ifdef SET_INEXACT
if (k > DBL_DIG)
oldinexact = get_inexact();
#endif
dval(&rv) = tens[k - 9] * dval(&rv) + z;
}
bd0 = 0;
if (nd <= DBL_DIG
#ifndef RND_PRODQUOT
#ifndef Honor_FLT_ROUNDS
&& Flt_Rounds == 1
#endif
#endif
) {
if (!e)
goto ret;
#ifndef ROUND_BIASED_without_Round_Up
if (e > 0) {
if (e <= Ten_pmax) {
#ifdef VAX
goto vax_ovfl_check;
#else
#ifdef Honor_FLT_ROUNDS
/* round correctly FLT_ROUNDS = 2 or 3 */
if (sign) {
rv.d = -rv.d;
sign = 0;
}
#endif
/* rv = */ rounded_product(dval(&rv), tens[e]);
goto ret;
#endif
}
i = DBL_DIG - nd;
if (e <= Ten_pmax + i) {
/* A fancier test would sometimes let us do
* this for larger i values.
*/
#ifdef Honor_FLT_ROUNDS
/* round correctly FLT_ROUNDS = 2 or 3 */
if (sign) {
rv.d = -rv.d;
sign = 0;
}
#endif
e -= i;
dval(&rv) *= tens[i];
#ifdef VAX
/* VAX exponent range is so narrow we must
* worry about overflow here...
*/
vax_ovfl_check:
word0(&rv) -= P*Exp_msk1;
/* rv = */ rounded_product(dval(&rv), tens[e]);
if ((word0(&rv) & Exp_mask)
> Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
goto ovfl;
word0(&rv) += P*Exp_msk1;
#else
/* rv = */ rounded_product(dval(&rv), tens[e]);
#endif
goto ret;
}
}
#ifndef Inaccurate_Divide
else if (e >= -Ten_pmax) {
#ifdef Honor_FLT_ROUNDS
/* round correctly FLT_ROUNDS = 2 or 3 */
if (sign) {
rv.d = -rv.d;
sign = 0;
}
#endif
/* rv = */ rounded_quotient(dval(&rv), tens[-e]);
goto ret;
}
#endif
#endif /* ROUND_BIASED_without_Round_Up */
}
e1 += nd - k;
#ifdef IEEE_Arith
#ifdef SET_INEXACT
bc.inexact = 1;
if (k <= DBL_DIG)
oldinexact = get_inexact();
#endif
#ifdef Avoid_Underflow
bc.scale = 0;
#endif
#ifdef Honor_FLT_ROUNDS
if (bc.rounding >= 2) {
if (sign)
bc.rounding = bc.rounding == 2 ? 0 : 2;
else
if (bc.rounding != 2)
bc.rounding = 0;
}
#endif
#endif /*IEEE_Arith*/
/* Get starting approximation = rv * 10**e1 */
if (e1 > 0) {
if ((i = e1 & 15))
dval(&rv) *= tens[i];
if (e1 &= ~15) {
if (e1 > DBL_MAX_10_EXP) {
ovfl:
/* Can't trust HUGE_VAL */
#ifdef IEEE_Arith
#ifdef Honor_FLT_ROUNDS
switch(bc.rounding) {
case 0: /* toward 0 */
case 3: /* toward -infinity */
word0(&rv) = Big0;
word1(&rv) = Big1;
break;
default:
word0(&rv) = Exp_mask;
word1(&rv) = 0;
}
#else /*Honor_FLT_ROUNDS*/
word0(&rv) = Exp_mask;
word1(&rv) = 0;
#endif /*Honor_FLT_ROUNDS*/
#ifdef SET_INEXACT
/* set overflow bit */
dval(&rv0) = 1e300;
dval(&rv0) *= dval(&rv0);
#endif
#else /*IEEE_Arith*/
word0(&rv) = Big0;
word1(&rv) = Big1;
#endif /*IEEE_Arith*/
range_err:
if (bd0) {
Bfree(bb);
Bfree(bd);
Bfree(bs);
Bfree(bd0);
Bfree(delta);
}
#ifndef NO_ERRNO
errno = ERANGE;
#endif
goto ret;
}
e1 >>= 4;
for(j = 0; e1 > 1; j++, e1 >>= 1)
if (e1 & 1)
dval(&rv) *= bigtens[j];
/* The last multiplication could overflow. */
word0(&rv) -= P*Exp_msk1;
dval(&rv) *= bigtens[j];
if ((z = word0(&rv) & Exp_mask)
> Exp_msk1*(DBL_MAX_EXP+Bias-P))
goto ovfl;
if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
/* set to largest number */
/* (Can't trust DBL_MAX) */
word0(&rv) = Big0;
word1(&rv) = Big1;
}
else
word0(&rv) += P*Exp_msk1;
}
}
else if (e1 < 0) {
e1 = -e1;
if ((i = e1 & 15))
dval(&rv) /= tens[i];
if (e1 >>= 4) {
if (e1 >= 1 << n_bigtens)
goto undfl;
#ifdef Avoid_Underflow
if (e1 & Scale_Bit)
bc.scale = 2*P;
for(j = 0; e1 > 0; j++, e1 >>= 1)
if (e1 & 1)
dval(&rv) *= tinytens[j];
if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
>> Exp_shift)) > 0) {
/* scaled rv is denormal; clear j low bits */
if (j >= 32) {
if (j > 54)
goto undfl;
word1(&rv) = 0;
if (j >= 53)
word0(&rv) = (P+2)*Exp_msk1;
else
word0(&rv) &= 0xffffffff << (j-32);
}
else
word1(&rv) &= 0xffffffff << j;
}
#else
for(j = 0; e1 > 1; j++, e1 >>= 1)
if (e1 & 1)
dval(&rv) *= tinytens[j];
/* The last multiplication could underflow. */
dval(&rv0) = dval(&rv);
dval(&rv) *= tinytens[j];
if (!dval(&rv)) {
dval(&rv) = 2.*dval(&rv0);
dval(&rv) *= tinytens[j];
#endif
if (!dval(&rv)) {
undfl:
dval(&rv) = 0.;
goto range_err;
}
#ifndef Avoid_Underflow
word0(&rv) = Tiny0;
word1(&rv) = Tiny1;
/* The refinement below will clean
* this approximation up.
*/
}
#endif
}
}
/* Now the hard part -- adjusting rv to the correct value.*/
/* Put digits into bd: true value = bd * 10^e */
bc.nd = nd - nz1;
#ifndef NO_STRTOD_BIGCOMP
bc.nd0 = nd0; /* Only needed if nd > strtod_diglim, but done here */
/* to silence an erroneous warning about bc.nd0 */
/* possibly not being initialized. */
if (nd > strtod_diglim) {
/* ASSERT(strtod_diglim >= 18); 18 == one more than the */
/* minimum number of decimal digits to distinguish double values */
/* in IEEE arithmetic. */
i = j = 18;
if (i > nd0)
j += bc.dplen;
for(;;) {
if (--j < bc.dp1 && j >= bc.dp0)
j = bc.dp0 - 1;
if (s0[j] != '0')
break;
--i;
}
e += nd - i;
nd = i;
if (nd0 > nd)
nd0 = nd;
if (nd < 9) { /* must recompute y */
y = 0;
for(i = 0; i < nd0; ++i)
y = 10*y + s0[i] - '0';
for(j = bc.dp1; i < nd; ++i)
y = 10*y + s0[j++] - '0';
}
}
#endif
bd0 = s2b(s0, nd0, nd, y, bc.dplen);
for(;;) {
bd = Balloc(bd0->k);
Bcopy(bd, bd0);
bb = d2b(&rv, &bbe, &bbbits); /* rv = bb * 2^bbe */
bs = i2b(1);
if (e >= 0) {
bb2 = bb5 = 0;
bd2 = bd5 = e;
}
else {
bb2 = bb5 = -e;
bd2 = bd5 = 0;
}
if (bbe >= 0)
bb2 += bbe;
else
bd2 -= bbe;
bs2 = bb2;
#ifdef Honor_FLT_ROUNDS
if (bc.rounding != 1)
bs2++;
#endif
#ifdef Avoid_Underflow
Lsb = LSB;
Lsb1 = 0;
j = bbe - bc.scale;
i = j + bbbits - 1; /* logb(rv) */
j = P + 1 - bbbits;
if (i < Emin) { /* denormal */
i = Emin - i;
j -= i;
if (i < 32)
Lsb <<= i;
else if (i < 52)
Lsb1 = Lsb << (i-32);
else
Lsb1 = Exp_mask;
}
#else /*Avoid_Underflow*/
#ifdef Sudden_Underflow
#ifdef IBM
j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
#else
j = P + 1 - bbbits;
#endif
#else /*Sudden_Underflow*/
j = bbe;
i = j + bbbits - 1; /* logb(rv) */
if (i < Emin) /* denormal */
j += P - Emin;
else
j = P + 1 - bbbits;
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow*/
bb2 += j;
bd2 += j;
#ifdef Avoid_Underflow
bd2 += bc.scale;
#endif
i = bb2 < bd2 ? bb2 : bd2;
if (i > bs2)
i = bs2;
if (i > 0) {
bb2 -= i;
bd2 -= i;
bs2 -= i;
}
if (bb5 > 0) {
bs = pow5mult(bs, bb5);
bb1 = mult(bs, bb);
Bfree(bb);
bb = bb1;
}
if (bb2 > 0)
bb = lshift(bb, bb2);
if (bd5 > 0)
bd = pow5mult(bd, bd5);
if (bd2 > 0)
bd = lshift(bd, bd2);
if (bs2 > 0)
bs = lshift(bs, bs2);
delta = diff(bb, bd);
bc.dsign = delta->sign;
delta->sign = 0;
i = cmp(delta, bs);
#ifndef NO_STRTOD_BIGCOMP /*{*/
if (bc.nd > nd && i <= 0) {
if (bc.dsign) {
/* Must use bigcomp(). */
req_bigcomp = 1;
break;
}
#ifdef Honor_FLT_ROUNDS
if (bc.rounding != 1) {
if (i < 0) {
req_bigcomp = 1;
break;
}
}
else
#endif
i = -1; /* Discarded digits make delta smaller. */
}
#endif /*}*/
#ifdef Honor_FLT_ROUNDS /*{*/
if (bc.rounding != 1) {
if (i < 0) {
/* Error is less than an ulp */
if (!delta->x[0] && delta->wds <= 1) {
/* exact */
#ifdef SET_INEXACT
bc.inexact = 0;
#endif
break;
}
if (bc.rounding) {
if (bc.dsign) {
adj.d = 1.;
goto apply_adj;
}
}
else if (!bc.dsign) {
adj.d = -1.;
if (!word1(&rv)
&& !(word0(&rv) & Frac_mask)) {
y = word0(&rv) & Exp_mask;
#ifdef Avoid_Underflow
if (!bc.scale || y > 2*P*Exp_msk1)
#else
if (y)
#endif
{
delta = lshift(delta,Log2P);
if (cmp(delta, bs) <= 0)
adj.d = -0.5;
}
}
apply_adj:
#ifdef Avoid_Underflow /*{*/
if (bc.scale && (y = word0(&rv) & Exp_mask)
<= 2*P*Exp_msk1)
word0(&adj) += (2*P+1)*Exp_msk1 - y;
#else
#ifdef Sudden_Underflow
if ((word0(&rv) & Exp_mask) <=
P*Exp_msk1) {
word0(&rv) += P*Exp_msk1;
dval(&rv) += adj.d*ulp(dval(&rv));
word0(&rv) -= P*Exp_msk1;
}
else
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow}*/
dval(&rv) += adj.d*ulp(&rv);
}
break;
}
adj.d = ratio(delta, bs);
if (adj.d < 1.)
adj.d = 1.;
if (adj.d <= 0x7ffffffe) {
/* adj = rounding ? ceil(adj) : floor(adj); */
y = adj.d;
if (y != adj.d) {
if (!((bc.rounding>>1) ^ bc.dsign))
y++;
adj.d = y;
}
}
#ifdef Avoid_Underflow /*{*/
if (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1)
word0(&adj) += (2*P+1)*Exp_msk1 - y;
#else
#ifdef Sudden_Underflow
if ((word0(&rv) & Exp_mask) <= P*Exp_msk1) {
word0(&rv) += P*Exp_msk1;
adj.d *= ulp(dval(&rv));
if (bc.dsign)
dval(&rv) += adj.d;
else
dval(&rv) -= adj.d;
word0(&rv) -= P*Exp_msk1;
goto cont;
}
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow}*/
adj.d *= ulp(&rv);
if (bc.dsign) {
if (word0(&rv) == Big0 && word1(&rv) == Big1)
goto ovfl;
dval(&rv) += adj.d;
}
else
dval(&rv) -= adj.d;
goto cont;
}
#endif /*}Honor_FLT_ROUNDS*/
if (i < 0) {
/* Error is less than half an ulp -- check for
* special case of mantissa a power of two.
*/
if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask
#ifdef IEEE_Arith /*{*/
#ifdef Avoid_Underflow
|| (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
#else
|| (word0(&rv) & Exp_mask) <= Exp_msk1
#endif
#endif /*}*/
) {
#ifdef SET_INEXACT
if (!delta->x[0] && delta->wds <= 1)
bc.inexact = 0;
#endif
break;
}
if (!delta->x[0] && delta->wds <= 1) {
/* exact result */
#ifdef SET_INEXACT
bc.inexact = 0;
#endif
break;
}
delta = lshift(delta,Log2P);
if (cmp(delta, bs) > 0)
goto drop_down;
break;
}
if (i == 0) {
/* exactly half-way between */
if (bc.dsign) {
if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
&& word1(&rv) == (
#ifdef Avoid_Underflow
(bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1)
? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
#endif
0xffffffff)) {
/*boundary case -- increment exponent*/
if (word0(&rv) == Big0 && word1(&rv) == Big1)
goto ovfl;
word0(&rv) = (word0(&rv) & Exp_mask)
+ Exp_msk1
#ifdef IBM
| Exp_msk1 >> 4
#endif
;
word1(&rv) = 0;
#ifdef Avoid_Underflow
bc.dsign = 0;
#endif
break;
}
}
else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
drop_down:
/* boundary case -- decrement exponent */
#ifdef Sudden_Underflow /*{{*/
L = word0(&rv) & Exp_mask;
#ifdef IBM
if (L < Exp_msk1)
#else
#ifdef Avoid_Underflow
if (L <= (bc.scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
#else
if (L <= Exp_msk1)
#endif /*Avoid_Underflow*/
#endif /*IBM*/
{
if (bc.nd >nd) {
bc.uflchk = 1;
break;
}
goto undfl;
}
L -= Exp_msk1;
#else /*Sudden_Underflow}{*/
#ifdef Avoid_Underflow
if (bc.scale) {
L = word0(&rv) & Exp_mask;
if (L <= (2*P+1)*Exp_msk1) {
if (L > (P+2)*Exp_msk1)
/* round even ==> */
/* accept rv */
break;
/* rv = smallest denormal */
if (bc.nd >nd) {
bc.uflchk = 1;
break;
}
goto undfl;
}
}
#endif /*Avoid_Underflow*/
L = (word0(&rv) & Exp_mask) - Exp_msk1;
#endif /*Sudden_Underflow}}*/
word0(&rv) = L | Bndry_mask1;
word1(&rv) = 0xffffffff;
#ifdef IBM
goto cont;
#else
#ifndef NO_STRTOD_BIGCOMP
if (bc.nd > nd)
goto cont;
#endif
break;
#endif
}
#ifndef ROUND_BIASED
#ifdef Avoid_Underflow
if (Lsb1) {
if (!(word0(&rv) & Lsb1))
break;
}
else if (!(word1(&rv) & Lsb))
break;
#else
if (!(word1(&rv) & LSB))
break;
#endif
#endif
if (bc.dsign)
#ifdef Avoid_Underflow
dval(&rv) += sulp(&rv, &bc);
#else
dval(&rv) += ulp(&rv);
#endif
#ifndef ROUND_BIASED
else {
#ifdef Avoid_Underflow
dval(&rv) -= sulp(&rv, &bc);
#else
dval(&rv) -= ulp(&rv);
#endif
#ifndef Sudden_Underflow
if (!dval(&rv)) {
if (bc.nd >nd) {
bc.uflchk = 1;
break;
}
goto undfl;
}
#endif
}
#ifdef Avoid_Underflow
bc.dsign = 1 - bc.dsign;
#endif
#endif
break;
}
if ((aadj = ratio(delta, bs)) <= 2.) {
if (bc.dsign)
aadj = aadj1 = 1.;
else if (word1(&rv) || word0(&rv) & Bndry_mask) {
#ifndef Sudden_Underflow
if (word1(&rv) == Tiny1 && !word0(&rv)) {
if (bc.nd >nd) {
bc.uflchk = 1;
break;
}
goto undfl;
}
#endif
aadj = 1.;
aadj1 = -1.;
}
else {
/* special case -- power of FLT_RADIX to be */
/* rounded down... */
if (aadj < 2./FLT_RADIX)
aadj = 1./FLT_RADIX;
else
aadj *= 0.5;
aadj1 = -aadj;
}
}
else {
aadj *= 0.5;
aadj1 = bc.dsign ? aadj : -aadj;
#ifdef Check_FLT_ROUNDS
switch(bc.rounding) {
case 2: /* towards +infinity */
aadj1 -= 0.5;
break;
case 0: /* towards 0 */
case 3: /* towards -infinity */
aadj1 += 0.5;
}
#else
if (Flt_Rounds == 0)
aadj1 += 0.5;
#endif /*Check_FLT_ROUNDS*/
}
y = word0(&rv) & Exp_mask;
/* Check for overflow */
if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
dval(&rv0) = dval(&rv);
word0(&rv) -= P*Exp_msk1;
adj.d = aadj1 * ulp(&rv);
dval(&rv) += adj.d;
if ((word0(&rv) & Exp_mask) >=
Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
if (word0(&rv0) == Big0 && word1(&rv0) == Big1)
goto ovfl;
word0(&rv) = Big0;
word1(&rv) = Big1;
goto cont;
}
else
word0(&rv) += P*Exp_msk1;
}
else {
#ifdef Avoid_Underflow
if (bc.scale && y <= 2*P*Exp_msk1) {
if (aadj <= 0x7fffffff) {
if ((z = aadj) <= 0)
z = 1;
aadj = z;
aadj1 = bc.dsign ? aadj : -aadj;
}
dval(&aadj2) = aadj1;
word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
aadj1 = dval(&aadj2);
adj.d = aadj1 * ulp(&rv);
dval(&rv) += adj.d;
if (rv.d == 0.)
#ifdef NO_STRTOD_BIGCOMP
goto undfl;
#else
{
if (bc.nd > nd)
bc.dsign = 1;
break;
}
#endif
}
else {
adj.d = aadj1 * ulp(&rv);
dval(&rv) += adj.d;
}
#else
#ifdef Sudden_Underflow
if ((word0(&rv) & Exp_mask) <= P*Exp_msk1) {
dval(&rv0) = dval(&rv);
word0(&rv) += P*Exp_msk1;
adj.d = aadj1 * ulp(&rv);
dval(&rv) += adj.d;
#ifdef IBM
if ((word0(&rv) & Exp_mask) < P*Exp_msk1)
#else
if ((word0(&rv) & Exp_mask) <= P*Exp_msk1)
#endif
{
if (word0(&rv0) == Tiny0
&& word1(&rv0) == Tiny1) {
if (bc.nd >nd) {
bc.uflchk = 1;
break;
}
goto undfl;
}
word0(&rv) = Tiny0;
word1(&rv) = Tiny1;
goto cont;
}
else
word0(&rv) -= P*Exp_msk1;
}
else {
adj.d = aadj1 * ulp(&rv);
dval(&rv) += adj.d;
}
#else /*Sudden_Underflow*/
/* Compute adj so that the IEEE rounding rules will
* correctly round rv + adj in some half-way cases.
* If rv * ulp(rv) is denormalized (i.e.,
* y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
* trouble from bits lost to denormalization;
* example: 1.2e-307 .
*/
if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
aadj1 = (double)(int)(aadj + 0.5);
if (!bc.dsign)
aadj1 = -aadj1;
}
adj.d = aadj1 * ulp(&rv);
dval(&rv) += adj.d;
#endif /*Sudden_Underflow*/
#endif /*Avoid_Underflow*/
}
z = word0(&rv) & Exp_mask;
#ifndef SET_INEXACT
if (bc.nd == nd) {
#ifdef Avoid_Underflow
if (!bc.scale)
#endif
if (y == z) {
/* Can we stop now? */
L = (Long)aadj;
aadj -= L;
/* The tolerances below are conservative. */
if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
if (aadj < .4999999 || aadj > .5000001)
break;
}
else if (aadj < .4999999/FLT_RADIX)
break;
}
}
#endif
cont:
Bfree(bb);
Bfree(bd);
Bfree(bs);
Bfree(delta);
}
Bfree(bb);
Bfree(bd);
Bfree(bs);
Bfree(bd0);
Bfree(delta);
#ifndef NO_STRTOD_BIGCOMP
if (req_bigcomp) {
bd0 = 0;
bc.e0 += nz1;
bigcomp(&rv, s0, &bc);
y = word0(&rv) & Exp_mask;
if (y == Exp_mask)
goto ovfl;
if (y == 0 && rv.d == 0.)
goto undfl;
}
#endif
#ifdef SET_INEXACT
if (bc.inexact) {
if (!oldinexact) {
word0(&rv0) = Exp_1 + (70 << Exp_shift);
word1(&rv0) = 0;
dval(&rv0) += 1.;
}
}
else if (!oldinexact)
clear_inexact();
#endif
#ifdef Avoid_Underflow
if (bc.scale) {
word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
word1(&rv0) = 0;
dval(&rv) *= dval(&rv0);
#ifndef NO_ERRNO
/* try to avoid the bug of testing an 8087 register value */
#ifdef IEEE_Arith
if (!(word0(&rv) & Exp_mask))
#else
if (word0(&rv) == 0 && word1(&rv) == 0)
#endif
errno = ERANGE;
#endif
}
#endif /* Avoid_Underflow */
#ifdef SET_INEXACT
if (bc.inexact && !(word0(&rv) & Exp_mask)) {
/* set underflow bit */
dval(&rv0) = 1e-300;
dval(&rv0) *= dval(&rv0);
}
#endif
ret:
if (se)
*se = (char *)s;
return sign ? -dval(&rv) : dval(&rv);
}
#ifndef MULTIPLE_THREADS
static char *dtoa_result;
#endif
static char *
#ifdef KR_headers
rv_alloc(i) int i;
#else
rv_alloc(int i)
#endif
{
int j, k, *r;
j = sizeof(ULong);
for(k = 0;
sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
j <<= 1)
k++;
r = (int*)Balloc(k);
*r = k;
return
#ifndef MULTIPLE_THREADS
dtoa_result =
#endif
(char *)(r+1);
}
static char *
#ifdef KR_headers
nrv_alloc(s, rve, n) char *s, **rve; int n;
#else
nrv_alloc(const char *s, char **rve, int n)
#endif
{
char *rv, *t;
t = rv = rv_alloc(n);
while((*t = *s++)) t++;
if (rve)
*rve = t;
return rv;
}
/* freedtoa(s) must be used to free values s returned by dtoa
* when MULTIPLE_THREADS is #defined. It should be used in all cases,
* but for consistency with earlier versions of dtoa, it is optional
* when MULTIPLE_THREADS is not defined.
*/
void
#ifdef KR_headers
ph_freedtoa(s) char *s;
#else
ph_freedtoa(char *s)
#endif
{
Bigint *b = (Bigint *)(void*)((int *)(void*)s - 1);
b->maxwds = 1 << (b->k = *(int*)b);
Bfree(b);
#ifndef MULTIPLE_THREADS
if (s == dtoa_result)
dtoa_result = 0;
#endif
}
/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
*
* Inspired by "How to Print Floating-Point Numbers Accurately" by
* Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
*
* Modifications:
* 1. Rather than iterating, we use a simple numeric overestimate
* to determine k = floor(log10(d)). We scale relevant
* quantities using O(log2(k)) rather than O(k) multiplications.
* 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
* try to generate digits strictly left to right. Instead, we
* compute with fewer bits and propagate the carry if necessary
* when rounding the final digit up. This is often faster.
* 3. Under the assumption that input will be rounded nearest,
* mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
* That is, we allow equality in stopping tests when the
* round-nearest rule will give the same floating-point value
* as would satisfaction of the stopping test with strict
* inequality.
* 4. We remove common factors of powers of 2 from relevant
* quantities.
* 5. When converting floating-point integers less than 1e16,
* we use floating-point arithmetic rather than resorting
* to multiple-precision integers.
* 6. When asked to produce fewer than 15 digits, we first try
* to get by with floating-point arithmetic; we resort to
* multiple-precision integer arithmetic only if we cannot
* guarantee that the floating-point calculation has given
* the correctly rounded result. For k requested digits and
* "uniformly" distributed input, the probability is
* something like 10^(k-15) that we must resort to the Long
* calculation.
*/
char *
ph_dtoa
#ifdef KR_headers
(dd, mode, ndigits, decpt, sign, rve)
double dd; int mode, ndigits, *decpt, *sign; char **rve;
#else
(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve)
#endif
{
/* Arguments ndigits, decpt, sign are similar to those
of ecvt and fcvt; trailing zeros are suppressed from
the returned string. If not null, *rve is set to point
to the end of the return value. If d is +-Infinity or NaN,
then *decpt is set to 9999.
mode:
0 ==> shortest string that yields d when read in
and rounded to nearest.
1 ==> like 0, but with Steele & White stopping rule;
e.g. with IEEE P754 arithmetic , mode 0 gives
1e23 whereas mode 1 gives 9.999999999999999e22.
2 ==> max(1,ndigits) significant digits. This gives a
return value similar to that of ecvt, except
that trailing zeros are suppressed.
3 ==> through ndigits past the decimal point. This
gives a return value similar to that from fcvt,
except that trailing zeros are suppressed, and
ndigits can be negative.
4,5 ==> similar to 2 and 3, respectively, but (in
round-nearest mode) with the tests of mode 0 to
possibly return a shorter string that rounds to d.
With IEEE arithmetic and compilation with
-DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
as modes 2 and 3 when FLT_ROUNDS != 1.
6-9 ==> Debugging modes similar to mode - 4: don't try
fast floating-point estimate (if applicable).
Values of mode other than 0-9 are treated as mode 0.
Sufficient space is allocated to the return value
to hold the suppressed trailing zeros.
*/
int bbits, b2, b5, be, dig, i, ieps, ilim = 0, ilim0, ilim1,
j, j1v = 0, k, k0, k_check, leftright, m2, m5, s2, s5,
spec_case = 0, try_quick;
Long L;
#ifndef Sudden_Underflow
int denorm;
ULong x;
#endif
Bigint *b, *b1, *delta, *mlo, *mhi, *S;
U d2, eps, u;
double ds;
char *s, *s0;
#ifndef No_leftright
#ifdef IEEE_Arith
U eps1;
#endif
#endif
#ifdef SET_INEXACT
int inexact, oldinexact;
#endif
#ifdef Honor_FLT_ROUNDS /*{*/
int Rounding;
#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
Rounding = Flt_Rounds;
#else /*}{*/
Rounding = 1;
switch(fegetround()) {
case FE_TOWARDZERO: Rounding = 0; break;
case FE_UPWARD: Rounding = 2; break;
case FE_DOWNWARD: Rounding = 3;
}
#endif /*}}*/
#endif /*}*/
#ifndef MULTIPLE_THREADS
if (dtoa_result) {
ph_freedtoa(dtoa_result);
dtoa_result = 0;
}
#endif
u.d = dd;
if (word0(&u) & Sign_bit) {
/* set sign for everything, including 0's and NaNs */
*sign = 1;
word0(&u) &= ~Sign_bit; /* clear sign bit */
}
else
*sign = 0;
#if defined(IEEE_Arith) + defined(VAX)
#ifdef IEEE_Arith
if ((word0(&u) & Exp_mask) == Exp_mask)
#else
if (word0(&u) == 0x8000)
#endif
{
/* Infinity or NaN */
*decpt = 9999;
#ifdef IEEE_Arith
if (!word1(&u) && !(word0(&u) & 0xfffff))
return nrv_alloc("Infinity", rve, 8);
#endif
return nrv_alloc("NaN", rve, 3);
}
#endif
#ifdef IBM
dval(&u) += 0; /* normalize */
#endif
if (!dval(&u)) {
*decpt = 1;
return nrv_alloc("0", rve, 1);
}
#ifdef SET_INEXACT
try_quick = oldinexact = get_inexact();
inexact = 1;
#endif
#ifdef Honor_FLT_ROUNDS
if (Rounding >= 2) {
if (*sign)
Rounding = Rounding == 2 ? 0 : 2;
else
if (Rounding != 2)
Rounding = 0;
}
#endif
b = d2b(&u, &be, &bbits);
#ifdef Sudden_Underflow
i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
#else
if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
#endif
dval(&d2) = dval(&u);
word0(&d2) &= Frac_mask1;
word0(&d2) |= Exp_11;
#ifdef IBM
if (j = 11 - hi0bits(word0(&d2) & Frac_mask))
dval(&d2) /= 1 << j;
#endif
/* log(x) ~=~ log(1.5) + (x-1.5)/1.5
* log10(x) = log(x) / log(10)
* ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
* log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
*
* This suggests computing an approximation k to log10(d) by
*
* k = (i - Bias)*0.301029995663981
* + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
*
* We want k to be too large rather than too small.
* The error in the first-order Taylor series approximation
* is in our favor, so we just round up the constant enough
* to compensate for any error in the multiplication of
* (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
* and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
* adding 1e-13 to the constant term more than suffices.
* Hence we adjust the constant term to 0.1760912590558.
* (We could get a more accurate k by invoking log10,
* but this is probably not worthwhile.)
*/
i -= Bias;
#ifdef IBM
i <<= 2;
i += j;
#endif
#ifndef Sudden_Underflow
denorm = 0;
}
else {
/* d is denormalized */
i = bbits + be + (Bias + (P-1) - 1);
x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
: word1(&u) << (32 - i);
dval(&d2) = x;
word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
i -= (Bias + (P-1) - 1) + 1;
denorm = 1;
}
#endif
ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558
+ i*0.301029995663981;
k = (int)ds;
if (ds < 0. && ds != k)
k--; /* want k = floor(ds) */
k_check = 1;
if (k >= 0 && k <= Ten_pmax) {
if (dval(&u) < tens[k])
k--;
k_check = 0;
}
j = bbits - i - 1;
if (j >= 0) {
b2 = 0;
s2 = j;
}
else {
b2 = -j;
s2 = 0;
}
if (k >= 0) {
b5 = 0;
s5 = k;
s2 += k;
}
else {
b2 -= k;
b5 = -k;
s5 = 0;
}
if (mode < 0 || mode > 9)
mode = 0;
#ifndef SET_INEXACT
#ifdef Check_FLT_ROUNDS
try_quick = Rounding == 1;
#else
try_quick = 1;
#endif
#endif /*SET_INEXACT*/
if (mode > 5) {
mode -= 4;
try_quick = 0;
}
leftright = 1;
ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
/* silence erroneous "gcc -Wall" warning. */
switch(mode) {
case 0:
case 1:
i = 18;
ndigits = 0;
break;
case 2:
leftright = 0;
/* no break */
case 4:
if (ndigits <= 0)
ndigits = 1;
ilim = ilim1 = i = ndigits;
break;
case 3:
leftright = 0;
/* no break */
case 5:
i = ndigits + k + 1;
ilim = i;
ilim1 = i - 1;
if (i <= 0)
i = 1;
}
s = s0 = rv_alloc(i);
#ifdef Honor_FLT_ROUNDS
if (mode > 1 && Rounding != 1)
leftright = 0;
#endif
if (ilim >= 0 && ilim <= Quick_max && try_quick) {
/* Try to get by with floating-point arithmetic. */
i = 0;
dval(&d2) = dval(&u);
k0 = k;
ilim0 = ilim;
ieps = 2; /* conservative */
if (k > 0) {
ds = tens[k&0xf];
j = k >> 4;
if (j & Bletch) {
/* prevent overflows */
j &= Bletch - 1;
dval(&u) /= bigtens[n_bigtens-1];
ieps++;
}
for(; j; j >>= 1, i++)
if (j & 1) {
ieps++;
ds *= bigtens[i];
}
dval(&u) /= ds;
}
else if ((j1v = -k)) {
dval(&u) *= tens[j1v & 0xf];
for(j = j1v >> 4; j; j >>= 1, i++)
if (j & 1) {
ieps++;
dval(&u) *= bigtens[i];
}
}
if (k_check && dval(&u) < 1. && ilim > 0) {
if (ilim1 <= 0)
goto fast_failed;
ilim = ilim1;
k--;
dval(&u) *= 10.;
ieps++;
}
dval(&eps) = ieps*dval(&u) + 7.;
word0(&eps) -= (P-1)*Exp_msk1;
if (ilim == 0) {
S = mhi = 0;
dval(&u) -= 5.;
if (dval(&u) > dval(&eps))
goto one_digit;
if (dval(&u) < -dval(&eps))
goto no_digits;
goto fast_failed;
}
#ifndef No_leftright
if (leftright) {
/* Use Steele & White method of only
* generating digits needed.
*/
dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
#ifdef IEEE_Arith
if (k0 < 0 && j1v >= 307) {
eps1.d = 1.01e256; /* 1.01 allows roundoff in the next few lines */
word0(&eps1) -= Exp_msk1 * (Bias+P-1);
dval(&eps1) *= tens[j1v & 0xf];
for(i = 0, j = (j1v-256) >> 4; j; j >>= 1, i++)
if (j & 1)
dval(&eps1) *= bigtens[i];
if (eps.d < eps1.d)
eps.d = eps1.d;
}
#endif
for(i = 0;;) {
L = dval(&u);
dval(&u) -= L;
*s++ = '0' + (int)L;
if (1. - dval(&u) < dval(&eps))
goto bump_up;
if (dval(&u) < dval(&eps))
goto ret1;
if (++i >= ilim)
break;
dval(&eps) *= 10.;
dval(&u) *= 10.;
}
}
else {
#endif
/* Generate ilim digits, then fix them up. */
dval(&eps) *= tens[ilim-1];
for(i = 1;; i++, dval(&u) *= 10.) {
L = (Long)(dval(&u));
if (!(dval(&u) -= L))
ilim = i;
*s++ = '0' + (int)L;
if (i == ilim) {
if (dval(&u) > 0.5 + dval(&eps))
goto bump_up;
else if (dval(&u) < 0.5 - dval(&eps)) {
while(*--s == '0');
s++;
goto ret1;
}
break;
}
}
#ifndef No_leftright
}
#endif
fast_failed:
s = s0;
dval(&u) = dval(&d2);
k = k0;
ilim = ilim0;
}
/* Do we have a "small" integer? */
if (be >= 0 && k <= Int_max) {
/* Yes. */
ds = tens[k];
if (ndigits < 0 && ilim <= 0) {
S = mhi = 0;
if (ilim < 0 || dval(&u) <= 5*ds)
goto no_digits;
goto one_digit;
}
for(i = 1;; i++, dval(&u) *= 10.) {
L = (Long)(dval(&u) / ds);
dval(&u) -= L*ds;
#ifdef Check_FLT_ROUNDS
/* If FLT_ROUNDS == 2, L will usually be high by 1 */
if (dval(&u) < 0) {
L--;
dval(&u) += ds;
}
#endif
*s++ = '0' + (int)L;
if (!dval(&u)) {
#ifdef SET_INEXACT
inexact = 0;
#endif
break;
}
if (i == ilim) {
#ifdef Honor_FLT_ROUNDS
if (mode > 1)
switch(Rounding) {
case 0: goto ret1;
case 2: goto bump_up;
}
#endif
dval(&u) += dval(&u);
#ifdef ROUND_BIASED
if (dval(&u) >= ds)
#else
if (dval(&u) > ds || (dval(&u) == ds && L & 1))
#endif
{
bump_up:
while(*--s == '9')
if (s == s0) {
k++;
*s = '0';
break;
}
++*s++;
}
break;
}
}
goto ret1;
}
m2 = b2;
m5 = b5;
mhi = mlo = 0;
if (leftright) {
i =
#ifndef Sudden_Underflow
denorm ? be + (Bias + (P-1) - 1 + 1) :
#endif
#ifdef IBM
1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
#else
1 + P - bbits;
#endif
b2 += i;
s2 += i;
mhi = i2b(1);
}
if (m2 > 0 && s2 > 0) {
i = m2 < s2 ? m2 : s2;
b2 -= i;
m2 -= i;
s2 -= i;
}
if (b5 > 0) {
if (leftright) {
if (m5 > 0) {
mhi = pow5mult(mhi, m5);
b1 = mult(mhi, b);
Bfree(b);
b = b1;
}
if ((j = b5 - m5))
b = pow5mult(b, j);
}
else
b = pow5mult(b, b5);
}
S = i2b(1);
if (s5 > 0)
S = pow5mult(S, s5);
/* Check for special case that d is a normalized power of 2. */
spec_case = 0;
if ((mode < 2 || leftright)
#ifdef Honor_FLT_ROUNDS
&& Rounding == 1
#endif
) {
if (!word1(&u) && !(word0(&u) & Bndry_mask)
#ifndef Sudden_Underflow
&& word0(&u) & (Exp_mask & ~Exp_msk1)
#endif
) {
/* The special case */
b2 += Log2P;
s2 += Log2P;
spec_case = 1;
}
}
/* Arrange for convenient computation of quotients:
* shift left if necessary so divisor has 4 leading 0 bits.
*
* Perhaps we should just compute leading 28 bits of S once
* and for all and pass them and a shift to quorem, so it
* can do shifts and ors to compute the numerator for q.
*/
i = dshift(S, s2);
b2 += i;
m2 += i;
s2 += i;
if (b2 > 0)
b = lshift(b, b2);
if (s2 > 0)
S = lshift(S, s2);
if (k_check) {
if (cmp(b,S) < 0) {
k--;
b = multadd(b, 10, 0); /* we botched the k estimate */
if (leftright)
mhi = multadd(mhi, 10, 0);
ilim = ilim1;
}
}
if (ilim <= 0 && (mode == 3 || mode == 5)) {
if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
/* no digits, fcvt style */
no_digits:
k = -1 - ndigits;
goto ret;
}
one_digit:
*s++ = '1';
k++;
goto ret;
}
if (leftright) {
if (m2 > 0)
mhi = lshift(mhi, m2);
/* Compute mlo -- check for special case
* that d is a normalized power of 2.
*/
mlo = mhi;
if (spec_case) {
mhi = Balloc(mhi->k);
Bcopy(mhi, mlo);
mhi = lshift(mhi, Log2P);
}
for(i = 1;;i++) {
dig = quorem(b,S) + '0';
/* Do we yet have the shortest decimal string
* that will round to d?
*/
j = cmp(b, mlo);
delta = diff(S, mhi);
j1v = delta->sign ? 1 : cmp(b, delta);
Bfree(delta);
#ifndef ROUND_BIASED
if (j1v == 0 && mode != 1 && !(word1(&u) & 1)
#ifdef Honor_FLT_ROUNDS
&& Rounding >= 1
#endif
) {
if (dig == '9')
goto round_9_up;
if (j > 0)
dig++;
#ifdef SET_INEXACT
else if (!b->x[0] && b->wds <= 1)
inexact = 0;
#endif
*s++ = dig;
goto ret;
}
#endif
if (j < 0 || (j == 0 && mode != 1
#ifndef ROUND_BIASED
&& !(word1(&u) & 1)
#endif
)) {
if (!b->x[0] && b->wds <= 1) {
#ifdef SET_INEXACT
inexact = 0;
#endif
goto accept_dig;
}
#ifdef Honor_FLT_ROUNDS
if (mode > 1)
switch(Rounding) {
case 0: goto accept_dig;
case 2: goto keep_dig;
}
#endif /*Honor_FLT_ROUNDS*/
if (j1v > 0) {
b = lshift(b, 1);
j1v = cmp(b, S);
#ifdef ROUND_BIASED
if (j1v >= 0 /*)*/
#else
if ((j1v > 0 || (j1v == 0 && dig & 1))
#endif
&& dig++ == '9')
goto round_9_up;
}
accept_dig:
*s++ = dig;
goto ret;
}
if (j1v > 0) {
#ifdef Honor_FLT_ROUNDS
if (!Rounding)
goto accept_dig;
#endif
if (dig == '9') { /* possible if i == 1 */
round_9_up:
*s++ = '9';
goto roundoff;
}
*s++ = dig + 1;
goto ret;
}
#ifdef Honor_FLT_ROUNDS
keep_dig:
#endif
*s++ = dig;
if (i == ilim)
break;
b = multadd(b, 10, 0);
if (mlo == mhi)
mlo = mhi = multadd(mhi, 10, 0);
else {
mlo = multadd(mlo, 10, 0);
mhi = multadd(mhi, 10, 0);
}
}
}
else
for(i = 1;; i++) {
*s++ = dig = quorem(b,S) + '0';
if (!b->x[0] && b->wds <= 1) {
#ifdef SET_INEXACT
inexact = 0;
#endif
goto ret;
}
if (i >= ilim)
break;
b = multadd(b, 10, 0);
}
/* Round off last digit */
#ifdef Honor_FLT_ROUNDS
switch(Rounding) {
case 0: goto trimzeros;
case 2: goto roundoff;
}
#endif
b = lshift(b, 1);
j = cmp(b, S);
#ifdef ROUND_BIASED
if (j >= 0)
#else
if (j > 0 || (j == 0 && dig & 1))
#endif
{
roundoff:
while(*--s == '9')
if (s == s0) {
k++;
*s++ = '1';
goto ret;
}
++*s++;
}
else {
#ifdef Honor_FLT_ROUNDS
trimzeros:
#endif
while(*--s == '0');
s++;
}
ret:
Bfree(S);
if (mhi) {
if (mlo && mlo != mhi)
Bfree(mlo);
Bfree(mhi);
}
ret1:
#ifdef SET_INEXACT
if (inexact) {
if (!oldinexact) {
word0(&u) = Exp_1 + (70 << Exp_shift);
word1(&u) = 0;
dval(&u) += 1.;
}
}
else if (!oldinexact)
clear_inexact();
#endif
Bfree(b);
*s = 0;
*decpt = k + 1;
if (rve)
*rve = s;
return s0;
}
#ifdef __cplusplus
}
#endif
|
//////////////////////////////////////////////////////////////////////
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (C) 2003 Microsoft Corporation. All rights reserved.
//
// PreComp.cpp
//
// Stub for vc precompiled header.
//
//////////////////////////////////////////////////////////////////////
#include "globals.h"
|
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"> <style>
.KEYW {color: #933;}
.COMM {color: #bbb; font-style: italic;}
.NUMB {color: #393;}
.STRN {color: #393;}
.REGX {color: #339;}
.line {border-right: 1px dotted #666; color: #666; font-style: normal;}
</style></head><body><pre><span class='line'> 1</span> <span class="COMM">/*
<span class='line'> 2</span> * Copyright (C) 2013 Glyptodon LLC
<span class='line'> 3</span> *
<span class='line'> 4</span> * Permission is hereby granted, free of charge, to any person obtaining a copy
<span class='line'> 5</span> * of this software and associated documentation files (the "Software"), to deal
<span class='line'> 6</span> * in the Software without restriction, including without limitation the rights
<span class='line'> 7</span> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<span class='line'> 8</span> * copies of the Software, and to permit persons to whom the Software is
<span class='line'> 9</span> * furnished to do so, subject to the following conditions:
<span class='line'> 10</span> *
<span class='line'> 11</span> * The above copyright notice and this permission notice shall be included in
<span class='line'> 12</span> * all copies or substantial portions of the Software.
<span class='line'> 13</span> *
<span class='line'> 14</span> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<span class='line'> 15</span> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<span class='line'> 16</span> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<span class='line'> 17</span> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<span class='line'> 18</span> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<span class='line'> 19</span> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
<span class='line'> 20</span> * THE SOFTWARE.
<span class='line'> 21</span> */</span><span class="WHIT">
<span class='line'> 22</span>
<span class='line'> 23</span> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">Guacamole</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">Guacamole</span><span class="WHIT"> </span><span class="PUNC">||</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="PUNC">}</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 24</span>
<span class='line'> 25</span> </span><span class="COMM">/**
<span class='line'> 26</span> * A writer which automatically writes to the given output stream with text
<span class='line'> 27</span> * data.
<span class='line'> 28</span> *
<span class='line'> 29</span> * @constructor
<span class='line'> 30</span> * @param {Guacamole.OutputStream} stream The stream that data will be written
<span class='line'> 31</span> * to.
<span class='line'> 32</span> */</span><span class="WHIT">
<span class='line'> 33</span> </span><span class="NAME">Guacamole.StringWriter</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">function</span><span class="PUNC">(</span><span class="NAME">stream</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'> 34</span>
<span class='line'> 35</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'> 36</span> * Reference to this Guacamole.StringWriter.
<span class='line'> 37</span> * @private
<span class='line'> 38</span> */</span><span class="WHIT">
<span class='line'> 39</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">guac_writer</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">this</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 40</span>
<span class='line'> 41</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'> 42</span> * Wrapped Guacamole.ArrayBufferWriter.
<span class='line'> 43</span> * @private
<span class='line'> 44</span> * @type Guacamole.ArrayBufferWriter
<span class='line'> 45</span> */</span><span class="WHIT">
<span class='line'> 46</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">array_writer</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">new</span><span class="WHIT"> </span><span class="NAME">Guacamole.ArrayBufferWriter</span><span class="PUNC">(</span><span class="NAME">stream</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 47</span>
<span class='line'> 48</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'> 49</span> * Internal buffer for UTF-8 output.
<span class='line'> 50</span> * @private
<span class='line'> 51</span> */</span><span class="WHIT">
<span class='line'> 52</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">buffer</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">new</span><span class="WHIT"> </span><span class="NAME">Uint8Array</span><span class="PUNC">(</span><span class="NUMB">8192</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 53</span>
<span class='line'> 54</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'> 55</span> * The number of bytes currently in the buffer.
<span class='line'> 56</span> * @private
<span class='line'> 57</span> */</span><span class="WHIT">
<span class='line'> 58</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">length</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 59</span>
<span class='line'> 60</span> </span><span class="WHIT"> </span><span class="COMM">// Simply call onack for acknowledgements</span><span class="WHIT">
<span class='line'> 61</span> </span><span class="WHIT"> </span><span class="NAME">array_writer.onack</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">function</span><span class="PUNC">(</span><span class="NAME">status</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'> 62</span> </span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">guac_writer.onack</span><span class="PUNC">)</span><span class="WHIT">
<span class='line'> 63</span> </span><span class="WHIT"> </span><span class="NAME">guac_writer.onack</span><span class="PUNC">(</span><span class="NAME">status</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 64</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 65</span>
<span class='line'> 66</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'> 67</span> * Expands the size of the underlying buffer by the given number of bytes,
<span class='line'> 68</span> * updating the length appropriately.
<span class='line'> 69</span> *
<span class='line'> 70</span> * @private
<span class='line'> 71</span> * @param {Number} bytes The number of bytes to add to the underlying
<span class='line'> 72</span> * buffer.
<span class='line'> 73</span> */</span><span class="WHIT">
<span class='line'> 74</span> </span><span class="WHIT"> </span><span class="KEYW">function</span><span class="WHIT"> </span><span class="NAME">__expand</span><span class="PUNC">(</span><span class="NAME">bytes</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'> 75</span>
<span class='line'> 76</span> </span><span class="WHIT"> </span><span class="COMM">// Resize buffer if more space needed</span><span class="WHIT">
<span class='line'> 77</span> </span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">length</span><span class="PUNC">+</span><span class="NAME">bytes</span><span class="WHIT"> </span><span class="PUNC">>=</span><span class="WHIT"> </span><span class="NAME">buffer.length</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'> 78</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">new_buffer</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">new</span><span class="WHIT"> </span><span class="NAME">Uint8Array</span><span class="PUNC">(</span><span class="PUNC">(</span><span class="NAME">length</span><span class="PUNC">+</span><span class="NAME">bytes</span><span class="PUNC">)</span><span class="PUNC">*</span><span class="NUMB">2</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 79</span> </span><span class="WHIT"> </span><span class="NAME">new_buffer.set</span><span class="PUNC">(</span><span class="NAME">buffer</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 80</span> </span><span class="WHIT"> </span><span class="NAME">buffer</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">new_buffer</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 81</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'> 82</span>
<span class='line'> 83</span> </span><span class="WHIT"> </span><span class="NAME">length</span><span class="WHIT"> </span><span class="PUNC">+</span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">bytes</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 84</span>
<span class='line'> 85</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'> 86</span>
<span class='line'> 87</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'> 88</span> * Appends a single Unicode character to the current buffer, resizing the
<span class='line'> 89</span> * buffer if necessary. The character will be encoded as UTF-8.
<span class='line'> 90</span> *
<span class='line'> 91</span> * @private
<span class='line'> 92</span> * @param {Number} codepoint The codepoint of the Unicode character to
<span class='line'> 93</span> * append.
<span class='line'> 94</span> */</span><span class="WHIT">
<span class='line'> 95</span> </span><span class="WHIT"> </span><span class="KEYW">function</span><span class="WHIT"> </span><span class="NAME">__append_utf8</span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'> 96</span>
<span class='line'> 97</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">mask</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 98</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">bytes</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'> 99</span>
<span class='line'>100</span> </span><span class="WHIT"> </span><span class="COMM">// 1 byte</span><span class="WHIT">
<span class='line'>101</span> </span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC"><=</span><span class="WHIT"> </span><span class="NUMB">0x7F</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>102</span> </span><span class="WHIT"> </span><span class="NAME">mask</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0x00</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>103</span> </span><span class="WHIT"> </span><span class="NAME">bytes</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">1</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>104</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>105</span>
<span class='line'>106</span> </span><span class="WHIT"> </span><span class="COMM">// 2 byte</span><span class="WHIT">
<span class='line'>107</span> </span><span class="WHIT"> </span><span class="KEYW">else</span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC"><=</span><span class="WHIT"> </span><span class="NUMB">0x7FF</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>108</span> </span><span class="WHIT"> </span><span class="NAME">mask</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0xC0</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>109</span> </span><span class="WHIT"> </span><span class="NAME">bytes</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">2</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>110</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>111</span>
<span class='line'>112</span> </span><span class="WHIT"> </span><span class="COMM">// 3 byte</span><span class="WHIT">
<span class='line'>113</span> </span><span class="WHIT"> </span><span class="KEYW">else</span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC"><=</span><span class="WHIT"> </span><span class="NUMB">0xFFFF</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>114</span> </span><span class="WHIT"> </span><span class="NAME">mask</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0xE0</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>115</span> </span><span class="WHIT"> </span><span class="NAME">bytes</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">3</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>116</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>117</span>
<span class='line'>118</span> </span><span class="WHIT"> </span><span class="COMM">// 4 byte</span><span class="WHIT">
<span class='line'>119</span> </span><span class="WHIT"> </span><span class="KEYW">else</span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC"><=</span><span class="WHIT"> </span><span class="NUMB">0x1FFFFF</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>120</span> </span><span class="WHIT"> </span><span class="NAME">mask</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0xF0</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>121</span> </span><span class="WHIT"> </span><span class="NAME">bytes</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">4</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>122</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>123</span>
<span class='line'>124</span> </span><span class="WHIT"> </span><span class="COMM">// If invalid codepoint, append replacement character</span><span class="WHIT">
<span class='line'>125</span> </span><span class="WHIT"> </span><span class="KEYW">else</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>126</span> </span><span class="WHIT"> </span><span class="NAME">__append_utf8</span><span class="PUNC">(</span><span class="NUMB">0xFFFD</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>127</span> </span><span class="WHIT"> </span><span class="KEYW">return</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>128</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>129</span>
<span class='line'>130</span> </span><span class="WHIT"> </span><span class="COMM">// Offset buffer by size</span><span class="WHIT">
<span class='line'>131</span> </span><span class="WHIT"> </span><span class="NAME">__expand</span><span class="PUNC">(</span><span class="NAME">bytes</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>132</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">offset</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">length</span><span class="WHIT"> </span><span class="PUNC">-</span><span class="WHIT"> </span><span class="NUMB">1</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>133</span>
<span class='line'>134</span> </span><span class="WHIT"> </span><span class="COMM">// Add trailing bytes, if any</span><span class="WHIT">
<span class='line'>135</span> </span><span class="WHIT"> </span><span class="KEYW">for</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">i</span><span class="PUNC">=</span><span class="NUMB">1</span><span class="PUNC">;</span><span class="WHIT"> </span><span class="NAME">i</span><span class="PUNC"><</span><span class="NAME">bytes</span><span class="PUNC">;</span><span class="WHIT"> </span><span class="NAME">i</span><span class="PUNC">++</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>136</span> </span><span class="WHIT"> </span><span class="NAME">buffer</span><span class="PUNC">[</span><span class="NAME">offset</span><span class="PUNC">--</span><span class="PUNC">]</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0x80</span><span class="WHIT"> </span><span class="PUNC">|</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC">&</span><span class="WHIT"> </span><span class="NUMB">0x3F</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>137</span> </span><span class="WHIT"> </span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC">>></span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">6</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>138</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>139</span>
<span class='line'>140</span> </span><span class="WHIT"> </span><span class="COMM">// Set initial byte</span><span class="WHIT">
<span class='line'>141</span> </span><span class="WHIT"> </span><span class="NAME">buffer</span><span class="PUNC">[</span><span class="NAME">offset</span><span class="PUNC">]</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">mask</span><span class="WHIT"> </span><span class="PUNC">|</span><span class="WHIT"> </span><span class="NAME">codepoint</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>142</span>
<span class='line'>143</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>144</span>
<span class='line'>145</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'>146</span> * Encodes the given string as UTF-8, returning an ArrayBuffer containing
<span class='line'>147</span> * the resulting bytes.
<span class='line'>148</span> *
<span class='line'>149</span> * @private
<span class='line'>150</span> * @param {String} text The string to encode as UTF-8.
<span class='line'>151</span> * @return {Uint8Array} The encoded UTF-8 data.
<span class='line'>152</span> */</span><span class="WHIT">
<span class='line'>153</span> </span><span class="WHIT"> </span><span class="KEYW">function</span><span class="WHIT"> </span><span class="NAME">__encode_utf8</span><span class="PUNC">(</span><span class="NAME">text</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>154</span>
<span class='line'>155</span> </span><span class="WHIT"> </span><span class="COMM">// Fill buffer with UTF-8</span><span class="WHIT">
<span class='line'>156</span> </span><span class="WHIT"> </span><span class="KEYW">for</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">i</span><span class="PUNC">=</span><span class="NUMB">0</span><span class="PUNC">;</span><span class="WHIT"> </span><span class="NAME">i</span><span class="PUNC"><</span><span class="NAME">text.length</span><span class="PUNC">;</span><span class="WHIT"> </span><span class="NAME">i</span><span class="PUNC">++</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>157</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">codepoint</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">text.charCodeAt</span><span class="PUNC">(</span><span class="NAME">i</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>158</span> </span><span class="WHIT"> </span><span class="NAME">__append_utf8</span><span class="PUNC">(</span><span class="NAME">codepoint</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>159</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>160</span>
<span class='line'>161</span> </span><span class="WHIT"> </span><span class="COMM">// Flush buffer</span><span class="WHIT">
<span class='line'>162</span> </span><span class="WHIT"> </span><span class="KEYW">if</span><span class="WHIT"> </span><span class="PUNC">(</span><span class="NAME">length</span><span class="WHIT"> </span><span class="PUNC">></span><span class="WHIT"> </span><span class="NUMB">0</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>163</span> </span><span class="WHIT"> </span><span class="KEYW">var</span><span class="WHIT"> </span><span class="NAME">out_buffer</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NAME">buffer.subarray</span><span class="PUNC">(</span><span class="NUMB">0</span><span class="PUNC">,</span><span class="WHIT"> </span><span class="NAME">length</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>164</span> </span><span class="WHIT"> </span><span class="NAME">length</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="NUMB">0</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>165</span> </span><span class="WHIT"> </span><span class="KEYW">return</span><span class="WHIT"> </span><span class="NAME">out_buffer</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>166</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>167</span>
<span class='line'>168</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="WHIT">
<span class='line'>169</span>
<span class='line'>170</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'>171</span> * Sends the given text.
<span class='line'>172</span> *
<span class='line'>173</span> * @param {String} text The text to send.
<span class='line'>174</span> */</span><span class="WHIT">
<span class='line'>175</span> </span><span class="WHIT"> </span><span class="NAME">this.sendText</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">function</span><span class="PUNC">(</span><span class="NAME">text</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>176</span> </span><span class="WHIT"> </span><span class="NAME">array_writer.sendData</span><span class="PUNC">(</span><span class="NAME">__encode_utf8</span><span class="PUNC">(</span><span class="NAME">text</span><span class="PUNC">)</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>177</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>178</span>
<span class='line'>179</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'>180</span> * Signals that no further text will be sent, effectively closing the
<span class='line'>181</span> * stream.
<span class='line'>182</span> */</span><span class="WHIT">
<span class='line'>183</span> </span><span class="WHIT"> </span><span class="NAME">this.sendEnd</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">function</span><span class="PUNC">(</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT">
<span class='line'>184</span> </span><span class="WHIT"> </span><span class="NAME">array_writer.sendEnd</span><span class="PUNC">(</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>185</span> </span><span class="WHIT"> </span><span class="PUNC">}</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>186</span>
<span class='line'>187</span> </span><span class="WHIT"> </span><span class="COMM">/**
<span class='line'>188</span> * Fired for received data, if acknowledged by the server.
<span class='line'>189</span> * @event
<span class='line'>190</span> * @param {Guacamole.Status} status The status of the operation.
<span class='line'>191</span> */</span><span class="WHIT">
<span class='line'>192</span> </span><span class="WHIT"> </span><span class="NAME">this.onack</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">null</span><span class="PUNC">;</span><span class="WHIT">
<span class='line'>193</span>
<span class='line'>194</span> </span><span class="PUNC">}</span><span class="PUNC">;</span></pre>
<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-75289145-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
</body></html> |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production x *= y is the same as the production x = x * y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.1_T2.6.js
* @description Type(x) is different from Type(y) and both types vary between primitive String (primitive or object) and Undefined
*/
//CHECK#1
x = "1";
x *= undefined;
if (isNaN(x) !== true) {
$ERROR('#1: x = "1"; x *= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x *= "1";
if (isNaN(x) !== true) {
$ERROR('#2: x = undefined; x *= "1"; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#3
x = new String("1");
x *= undefined;
if (isNaN(x) !== true) {
$ERROR('#3: x = new String("1"); x *= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x *= new String("1");
if (isNaN(x) !== true) {
$ERROR('#4: x = undefined; x *= new String("1"); x === Not-a-Number. Actual: ' + (x));
}
|
/*
* Copyright (C) 2013 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tests;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
/**
* @author Gregory Kick
*/
final class MixedDepsImplementingInterfaces {
@AutoFactory(implementing = {FromInt.class, MarkerA.class})
MixedDepsImplementingInterfaces(@Provided String s, int i) {}
@AutoFactory(implementing = {FromObject.class, MarkerB.class})
MixedDepsImplementingInterfaces(Object o) {}
interface FromInt {
MixedDepsImplementingInterfaces fromInt(int i);
}
interface FromObject {
MixedDepsImplementingInterfaces fromObject(Object o);
}
interface MarkerA {}
interface MarkerB {}
}
|
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =================================================================================================
package com.twitter.common.text.token;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.util.AttributeSource;
import com.twitter.common.text.example.TokenizerUsageExample;
import com.twitter.common.text.token.attribute.CharSequenceTermAttribute;
import com.twitter.common.text.token.attribute.TokenType;
import com.twitter.common.text.token.attribute.TokenTypeAttribute;
/**
* Abstraction to enumerate a sequence of tokens. This class represents the central abstraction in
* Twitter's text processing library, and is similar to Lucene's TokenStream, with the following
* exceptions:
*
* <ul>
* <li>This class assumes that the input text is a {@link CharSequence}.
* <li>Calls support chaining.
* <li>Instances are reusable.
* </ul>
*
* For an annotated example of how this class is used in practice, refer to
* {@link TokenizerUsageExample}.
*/
public abstract class TwitterTokenStream extends TokenStream {
private final CharSequenceTermAttribute termAttribute = addAttribute(CharSequenceTermAttribute.class);
private final TokenTypeAttribute typeAttribute = addAttribute(TokenTypeAttribute.class);
/**
* Constructs a {@code TwitterTokenStream} using the default attribute factory.
*/
public TwitterTokenStream() {
super();
}
/**
* Constructs a {@code TwitterTokenStream} using the supplied {@code AttributeFactory} for creating new
* {@code Attribute} instances.
*
* @param factory attribute factory
*/
protected TwitterTokenStream(AttributeSource.AttributeFactory factory) {
super(factory);
}
/**
* Constructs a {@code TwitterTokenStream} that uses the same attributes as the supplied one.
*
* @param input attribute source
*/
protected TwitterTokenStream(AttributeSource input) {
super(input);
}
/**
* Consumers call this method to advance the stream to the next token.
*
* @return false for end of stream; true otherwise
*/
public abstract boolean incrementToken();
/**
* Resets this {@code TwitterTokenStream} (and also downstream tokens if they exist) to parse a new
* input.
*/
public void reset(CharSequence input) {
updateInputCharSequence(input);
reset();
};
/**
* Subclasses should implement reset() to reinitiate the processing.
* Input CharSequence is available as inputCharSequence().
*/
public abstract void reset();
/**
* Converts this token stream into a list of {@code Strings}.
*
* @return the contents of the token stream as a list of {@code Strings}.
*/
public List<String> toStringList() {
List<String> tokens = Lists.newArrayList();
while (incrementToken()) {
tokens.add(term().toString());
}
return tokens;
}
/**
* Searches and returns an instance of a specified class in this TwitterTokenStream chain.
*
* @param cls class to search for
* @return instance of the class {@code cls} if found or {@code null} if not found
*/
public <T extends TwitterTokenStream> T getInstanceOf(Class<T> cls) {
Preconditions.checkNotNull(cls);
if (cls.isInstance(this)) {
return cls.cast(this);
}
return null;
}
/**
* Returns the offset of the current token.
*
* @return offset of the current token.
*/
public int offset() {
return termAttribute.getOffset();
}
/**
* Returns the length of the current token.
*
* @return length of the current token.
*/
public int length() {
return termAttribute.getLength();
}
/**
* Returns the {@code CharSequence} of the current token.
*
* @return {@code CharSequence} of the current token
*/
public CharSequence term() {
return termAttribute.getTermCharSequence();
}
/**
* Returns the input {@code CharSequence}.
*
* @return input {@code CharSequence}
*/
public CharSequence inputCharSequence() {
return termAttribute.getCharSequence();
}
/**
* Returns the type of the current token.
*
* @return type of the current token.
*/
public TokenType type() {
return typeAttribute.getType();
}
/**
* Sets the input {@code CharSequence}.
*
* @param inputCharSequence {@code CharSequence} analyzed by this
* {@code TwitterTokenStream}
*/
protected void updateInputCharSequence(CharSequence inputCharSequence) {
termAttribute.setCharSequence(inputCharSequence);
}
/**
* Updates the offset and length of the current token.
*
* @param offset new offset
* @param length new length
*/
protected void updateOffsetAndLength(int offset, int length) {
termAttribute.setOffset(offset);
termAttribute.setLength(length);
}
/**
* Updates the type of the current token.
*
* @param type new type
*/
protected void updateType(TokenType type) {
typeAttribute.setType(type);
}
@Override
public boolean equals(Object target) {
// Lucene's AttributeSource.equals() returns true if this has the same
// set of attributes as the target one. Let's make it more strict.
return this == target;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
}
|
/**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.zeppelin.interpreter.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemoteInterpreterResult implements org.apache.thrift.TBase<RemoteInterpreterResult, RemoteInterpreterResult._Fields>, java.io.Serializable, Cloneable {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RemoteInterpreterResult");
private static final org.apache.thrift.protocol.TField CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("code", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("type", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField MSG_FIELD_DESC = new org.apache.thrift.protocol.TField("msg", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.protocol.TField CONFIG_FIELD_DESC = new org.apache.thrift.protocol.TField("config", org.apache.thrift.protocol.TType.STRING, (short)4);
private static final org.apache.thrift.protocol.TField GUI_FIELD_DESC = new org.apache.thrift.protocol.TField("gui", org.apache.thrift.protocol.TType.STRING, (short)5);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new RemoteInterpreterResultStandardSchemeFactory());
schemes.put(TupleScheme.class, new RemoteInterpreterResultTupleSchemeFactory());
}
public String code; // required
public String type; // required
public String msg; // required
public String config; // required
public String gui; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
CODE((short)1, "code"),
TYPE((short)2, "type"),
MSG((short)3, "msg"),
CONFIG((short)4, "config"),
GUI((short)5, "gui");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // CODE
return CODE;
case 2: // TYPE
return TYPE;
case 3: // MSG
return MSG;
case 4: // CONFIG
return CONFIG;
case 5: // GUI
return GUI;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.CODE, new org.apache.thrift.meta_data.FieldMetaData("code", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TYPE, new org.apache.thrift.meta_data.FieldMetaData("type", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.MSG, new org.apache.thrift.meta_data.FieldMetaData("msg", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.CONFIG, new org.apache.thrift.meta_data.FieldMetaData("config", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.GUI, new org.apache.thrift.meta_data.FieldMetaData("gui", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(RemoteInterpreterResult.class, metaDataMap);
}
public RemoteInterpreterResult() {
}
public RemoteInterpreterResult(
String code,
String type,
String msg,
String config,
String gui)
{
this();
this.code = code;
this.type = type;
this.msg = msg;
this.config = config;
this.gui = gui;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public RemoteInterpreterResult(RemoteInterpreterResult other) {
if (other.isSetCode()) {
this.code = other.code;
}
if (other.isSetType()) {
this.type = other.type;
}
if (other.isSetMsg()) {
this.msg = other.msg;
}
if (other.isSetConfig()) {
this.config = other.config;
}
if (other.isSetGui()) {
this.gui = other.gui;
}
}
public RemoteInterpreterResult deepCopy() {
return new RemoteInterpreterResult(this);
}
@Override
public void clear() {
this.code = null;
this.type = null;
this.msg = null;
this.config = null;
this.gui = null;
}
public String getCode() {
return this.code;
}
public RemoteInterpreterResult setCode(String code) {
this.code = code;
return this;
}
public void unsetCode() {
this.code = null;
}
/** Returns true if field code is set (has been assigned a value) and false otherwise */
public boolean isSetCode() {
return this.code != null;
}
public void setCodeIsSet(boolean value) {
if (!value) {
this.code = null;
}
}
public String getType() {
return this.type;
}
public RemoteInterpreterResult setType(String type) {
this.type = type;
return this;
}
public void unsetType() {
this.type = null;
}
/** Returns true if field type is set (has been assigned a value) and false otherwise */
public boolean isSetType() {
return this.type != null;
}
public void setTypeIsSet(boolean value) {
if (!value) {
this.type = null;
}
}
public String getMsg() {
return this.msg;
}
public RemoteInterpreterResult setMsg(String msg) {
this.msg = msg;
return this;
}
public void unsetMsg() {
this.msg = null;
}
/** Returns true if field msg is set (has been assigned a value) and false otherwise */
public boolean isSetMsg() {
return this.msg != null;
}
public void setMsgIsSet(boolean value) {
if (!value) {
this.msg = null;
}
}
public String getConfig() {
return this.config;
}
public RemoteInterpreterResult setConfig(String config) {
this.config = config;
return this;
}
public void unsetConfig() {
this.config = null;
}
/** Returns true if field config is set (has been assigned a value) and false otherwise */
public boolean isSetConfig() {
return this.config != null;
}
public void setConfigIsSet(boolean value) {
if (!value) {
this.config = null;
}
}
public String getGui() {
return this.gui;
}
public RemoteInterpreterResult setGui(String gui) {
this.gui = gui;
return this;
}
public void unsetGui() {
this.gui = null;
}
/** Returns true if field gui is set (has been assigned a value) and false otherwise */
public boolean isSetGui() {
return this.gui != null;
}
public void setGuiIsSet(boolean value) {
if (!value) {
this.gui = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case CODE:
if (value == null) {
unsetCode();
} else {
setCode((String)value);
}
break;
case TYPE:
if (value == null) {
unsetType();
} else {
setType((String)value);
}
break;
case MSG:
if (value == null) {
unsetMsg();
} else {
setMsg((String)value);
}
break;
case CONFIG:
if (value == null) {
unsetConfig();
} else {
setConfig((String)value);
}
break;
case GUI:
if (value == null) {
unsetGui();
} else {
setGui((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case CODE:
return getCode();
case TYPE:
return getType();
case MSG:
return getMsg();
case CONFIG:
return getConfig();
case GUI:
return getGui();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case CODE:
return isSetCode();
case TYPE:
return isSetType();
case MSG:
return isSetMsg();
case CONFIG:
return isSetConfig();
case GUI:
return isSetGui();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof RemoteInterpreterResult)
return this.equals((RemoteInterpreterResult)that);
return false;
}
public boolean equals(RemoteInterpreterResult that) {
if (that == null)
return false;
boolean this_present_code = true && this.isSetCode();
boolean that_present_code = true && that.isSetCode();
if (this_present_code || that_present_code) {
if (!(this_present_code && that_present_code))
return false;
if (!this.code.equals(that.code))
return false;
}
boolean this_present_type = true && this.isSetType();
boolean that_present_type = true && that.isSetType();
if (this_present_type || that_present_type) {
if (!(this_present_type && that_present_type))
return false;
if (!this.type.equals(that.type))
return false;
}
boolean this_present_msg = true && this.isSetMsg();
boolean that_present_msg = true && that.isSetMsg();
if (this_present_msg || that_present_msg) {
if (!(this_present_msg && that_present_msg))
return false;
if (!this.msg.equals(that.msg))
return false;
}
boolean this_present_config = true && this.isSetConfig();
boolean that_present_config = true && that.isSetConfig();
if (this_present_config || that_present_config) {
if (!(this_present_config && that_present_config))
return false;
if (!this.config.equals(that.config))
return false;
}
boolean this_present_gui = true && this.isSetGui();
boolean that_present_gui = true && that.isSetGui();
if (this_present_gui || that_present_gui) {
if (!(this_present_gui && that_present_gui))
return false;
if (!this.gui.equals(that.gui))
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
public int compareTo(RemoteInterpreterResult other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
RemoteInterpreterResult typedOther = (RemoteInterpreterResult)other;
lastComparison = Boolean.valueOf(isSetCode()).compareTo(typedOther.isSetCode());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCode()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.code, typedOther.code);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetType()).compareTo(typedOther.isSetType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.type, typedOther.type);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMsg()).compareTo(typedOther.isSetMsg());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMsg()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.msg, typedOther.msg);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetConfig()).compareTo(typedOther.isSetConfig());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetConfig()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.config, typedOther.config);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetGui()).compareTo(typedOther.isSetGui());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGui()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.gui, typedOther.gui);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RemoteInterpreterResult(");
boolean first = true;
sb.append("code:");
if (this.code == null) {
sb.append("null");
} else {
sb.append(this.code);
}
first = false;
if (!first) sb.append(", ");
sb.append("type:");
if (this.type == null) {
sb.append("null");
} else {
sb.append(this.type);
}
first = false;
if (!first) sb.append(", ");
sb.append("msg:");
if (this.msg == null) {
sb.append("null");
} else {
sb.append(this.msg);
}
first = false;
if (!first) sb.append(", ");
sb.append("config:");
if (this.config == null) {
sb.append("null");
} else {
sb.append(this.config);
}
first = false;
if (!first) sb.append(", ");
sb.append("gui:");
if (this.gui == null) {
sb.append("null");
} else {
sb.append(this.gui);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class RemoteInterpreterResultStandardSchemeFactory implements SchemeFactory {
public RemoteInterpreterResultStandardScheme getScheme() {
return new RemoteInterpreterResultStandardScheme();
}
}
private static class RemoteInterpreterResultStandardScheme extends StandardScheme<RemoteInterpreterResult> {
public void read(org.apache.thrift.protocol.TProtocol iprot, RemoteInterpreterResult struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // CODE
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.code = iprot.readString();
struct.setCodeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.type = iprot.readString();
struct.setTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // MSG
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.msg = iprot.readString();
struct.setMsgIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // CONFIG
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.config = iprot.readString();
struct.setConfigIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // GUI
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.gui = iprot.readString();
struct.setGuiIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, RemoteInterpreterResult struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.code != null) {
oprot.writeFieldBegin(CODE_FIELD_DESC);
oprot.writeString(struct.code);
oprot.writeFieldEnd();
}
if (struct.type != null) {
oprot.writeFieldBegin(TYPE_FIELD_DESC);
oprot.writeString(struct.type);
oprot.writeFieldEnd();
}
if (struct.msg != null) {
oprot.writeFieldBegin(MSG_FIELD_DESC);
oprot.writeString(struct.msg);
oprot.writeFieldEnd();
}
if (struct.config != null) {
oprot.writeFieldBegin(CONFIG_FIELD_DESC);
oprot.writeString(struct.config);
oprot.writeFieldEnd();
}
if (struct.gui != null) {
oprot.writeFieldBegin(GUI_FIELD_DESC);
oprot.writeString(struct.gui);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class RemoteInterpreterResultTupleSchemeFactory implements SchemeFactory {
public RemoteInterpreterResultTupleScheme getScheme() {
return new RemoteInterpreterResultTupleScheme();
}
}
private static class RemoteInterpreterResultTupleScheme extends TupleScheme<RemoteInterpreterResult> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, RemoteInterpreterResult struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetCode()) {
optionals.set(0);
}
if (struct.isSetType()) {
optionals.set(1);
}
if (struct.isSetMsg()) {
optionals.set(2);
}
if (struct.isSetConfig()) {
optionals.set(3);
}
if (struct.isSetGui()) {
optionals.set(4);
}
oprot.writeBitSet(optionals, 5);
if (struct.isSetCode()) {
oprot.writeString(struct.code);
}
if (struct.isSetType()) {
oprot.writeString(struct.type);
}
if (struct.isSetMsg()) {
oprot.writeString(struct.msg);
}
if (struct.isSetConfig()) {
oprot.writeString(struct.config);
}
if (struct.isSetGui()) {
oprot.writeString(struct.gui);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, RemoteInterpreterResult struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(5);
if (incoming.get(0)) {
struct.code = iprot.readString();
struct.setCodeIsSet(true);
}
if (incoming.get(1)) {
struct.type = iprot.readString();
struct.setTypeIsSet(true);
}
if (incoming.get(2)) {
struct.msg = iprot.readString();
struct.setMsgIsSet(true);
}
if (incoming.get(3)) {
struct.config = iprot.readString();
struct.setConfigIsSet(true);
}
if (incoming.get(4)) {
struct.gui = iprot.readString();
struct.setGuiIsSet(true);
}
}
}
}
|
/*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.rpc.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Author Taejin Koo
*/
public class LoggingStreamChannelStateChangeEventHandler implements StreamChannelStateChangeEventHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void eventPerformed(StreamChannel streamChannel, StreamChannelStateCode updatedStateCode) throws Exception {
logger.info("eventPerformed streamChannel:{}, stateCode:{}", streamChannel, updatedStateCode);
}
@Override
public void exceptionCaught(StreamChannel streamChannel, StreamChannelStateCode updatedStateCode, Throwable e) {
logger.warn("exceptionCaught message:{}, streamChannel:{}, stateCode:{}", e.getMessage(), streamChannel, updatedStateCode, e);
}
}
|
This ModeShape BOM makes it easy for your applications and libraries to connect to a remote ModeShape repository, using either ModeShape's REST API or JDBC driver.
== Usage ==
Include the following in your POM file:
<project>
...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.modeshape.bom</groupId>
<artifactId>modeshape-bom-remote-client</artifactId>
<version>${version.modeshape}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
...
</project>
Obviously, you'll need to specify the correct ModeShape version. But note that this is the only place you'll need to specify a version, because the BOM provides a completely valid and consistent set of versions.
This works like all other Maven BOMs by adding into the `dependencyManagement` section all of the dependency defaults for the ModeShape components and dependencies that your module _might_ need. Then, all you have to do is add an explicit dependency to your POM's `dependencies` section for each of ModeShape's components that your module _does_ use.
For example, if your module _explicitly_ uses ModeShape's REST client library, then simply define these dependencies:
<project>
...
<dependencies>
...
<dependency>
<groupId>org.modeshape</groupId>
<artifactId>modeshape-jdbc</artifactId>
</dependency>
...
</dependencies>
...
</project>
There are quite a few other transitive dependencies of these components.
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.datafrominternet;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import com.example.android.datafrominternet.utilities.NetworkUtils;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText mSearchBoxEditText;
private TextView mUrlDisplayTextView;
private TextView mSearchResultsTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);
mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);
mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);
}
/**
* This method retrieves the search text from the EditText, constructs
* the URL (using {@link NetworkUtils}) for the github repository you'd like to find, displays
* that URL in a TextView, and finally fires off an AsyncTask to perform the GET request using
* our (not yet created) {@link GithubQueryTask}
*/
private void makeGithubSearchQuery() {
String githubQuery = mSearchBoxEditText.getText().toString();
URL githubSearchUrl = NetworkUtils.buildUrl(githubQuery);
mUrlDisplayTextView.setText(githubSearchUrl.toString());
// TODO (2) Call getResponseFromHttpUrl and display the results in mSearchResultsTextView
// TODO (3) Surround the call to getResponseFromHttpUrl with a try / catch block to catch an IOException
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemThatWasClickedId = item.getItemId();
if (itemThatWasClickedId == R.id.action_search) {
makeGithubSearchQuery();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
/*
* 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.spark.ml.feature
import java.util.Locale
import org.apache.spark.annotation.Since
import org.apache.spark.ml.Transformer
import org.apache.spark.ml.param._
import org.apache.spark.ml.param.shared.{HasInputCol, HasInputCols, HasOutputCol, HasOutputCols}
import org.apache.spark.ml.util._
import org.apache.spark.sql.{DataFrame, Dataset}
import org.apache.spark.sql.functions.{col, udf}
import org.apache.spark.sql.types.{ArrayType, StringType, StructField, StructType}
/**
* A feature transformer that filters out stop words from input.
*
* Since 3.0.0, `StopWordsRemover` can filter out multiple columns at once by setting the
* `inputCols` parameter. Note that when both the `inputCol` and `inputCols` parameters are set,
* an Exception will be thrown.
*
* @note null values from input array are preserved unless adding null to stopWords
* explicitly.
*
* @see <a href="http://en.wikipedia.org/wiki/Stop_words">Stop words (Wikipedia)</a>
*/
@Since("1.5.0")
class StopWordsRemover @Since("1.5.0") (@Since("1.5.0") override val uid: String)
extends Transformer with HasInputCol with HasOutputCol with HasInputCols with HasOutputCols
with DefaultParamsWritable {
@Since("1.5.0")
def this() = this(Identifiable.randomUID("stopWords"))
/** @group setParam */
@Since("1.5.0")
def setInputCol(value: String): this.type = set(inputCol, value)
/** @group setParam */
@Since("1.5.0")
def setOutputCol(value: String): this.type = set(outputCol, value)
/** @group setParam */
@Since("3.0.0")
def setInputCols(value: Array[String]): this.type = set(inputCols, value)
/** @group setParam */
@Since("3.0.0")
def setOutputCols(value: Array[String]): this.type = set(outputCols, value)
/**
* The words to be filtered out.
* Default: English stop words
* @see `StopWordsRemover.loadDefaultStopWords()`
* @group param
*/
@Since("1.5.0")
val stopWords: StringArrayParam =
new StringArrayParam(this, "stopWords", "the words to be filtered out")
/** @group setParam */
@Since("1.5.0")
def setStopWords(value: Array[String]): this.type = set(stopWords, value)
/** @group getParam */
@Since("1.5.0")
def getStopWords: Array[String] = $(stopWords)
/**
* Whether to do a case sensitive comparison over the stop words.
* Default: false
* @group param
*/
@Since("1.5.0")
val caseSensitive: BooleanParam = new BooleanParam(this, "caseSensitive",
"whether to do a case-sensitive comparison over the stop words")
/** @group setParam */
@Since("1.5.0")
def setCaseSensitive(value: Boolean): this.type = set(caseSensitive, value)
/** @group getParam */
@Since("1.5.0")
def getCaseSensitive: Boolean = $(caseSensitive)
/**
* Locale of the input for case insensitive matching. Ignored when [[caseSensitive]]
* is true.
* Default: the string of default locale (`Locale.getDefault`), or `Locale.US` if default locale
* is not in available locales in JVM.
* @group param
*/
@Since("2.4.0")
val locale: Param[String] = new Param[String](this, "locale",
"Locale of the input for case insensitive matching. Ignored when caseSensitive is true.",
ParamValidators.inArray[String](Locale.getAvailableLocales.map(_.toString)))
/** @group setParam */
@Since("2.4.0")
def setLocale(value: String): this.type = set(locale, value)
/** @group getParam */
@Since("2.4.0")
def getLocale: String = $(locale)
/**
* Returns system default locale, or `Locale.US` if the default locale is not in available locales
* in JVM.
*/
private val getDefaultOrUS: Locale = {
if (Locale.getAvailableLocales.contains(Locale.getDefault)) {
Locale.getDefault
} else {
logWarning(s"Default locale set was [${Locale.getDefault.toString}]; however, it was " +
"not found in available locales in JVM, falling back to en_US locale. Set param `locale` " +
"in order to respect another locale.")
Locale.US
}
}
/** Returns the input and output column names corresponding in pair. */
private[feature] def getInOutCols(): (Array[String], Array[String]) = {
if (isSet(inputCol)) {
(Array($(inputCol)), Array($(outputCol)))
} else {
($(inputCols), $(outputCols))
}
}
setDefault(stopWords -> StopWordsRemover.loadDefaultStopWords("english"),
caseSensitive -> false, locale -> getDefaultOrUS.toString)
@Since("2.0.0")
override def transform(dataset: Dataset[_]): DataFrame = {
val outputSchema = transformSchema(dataset.schema)
val t = if ($(caseSensitive)) {
val stopWordsSet = $(stopWords).toSet
udf { terms: Seq[String] =>
terms.filter(s => !stopWordsSet.contains(s))
}
} else {
val lc = new Locale($(locale))
// scalastyle:off caselocale
val toLower = (s: String) => if (s != null) s.toLowerCase(lc) else s
// scalastyle:on caselocale
val lowerStopWords = $(stopWords).map(toLower(_)).toSet
udf { terms: Seq[String] =>
terms.filter(s => !lowerStopWords.contains(toLower(s)))
}
}
val (inputColNames, outputColNames) = getInOutCols()
val ouputCols = inputColNames.map { inputColName =>
t(col(inputColName))
}
val ouputMetadata = outputColNames.map(outputSchema(_).metadata)
dataset.withColumns(outputColNames, ouputCols, ouputMetadata)
}
@Since("1.5.0")
override def transformSchema(schema: StructType): StructType = {
ParamValidators.checkSingleVsMultiColumnParams(this, Seq(outputCol),
Seq(outputCols))
if (isSet(inputCols)) {
require(getInputCols.length == getOutputCols.length,
s"StopWordsRemover $this has mismatched Params " +
s"for multi-column transform. Params ($inputCols, $outputCols) should have " +
"equal lengths, but they have different lengths: " +
s"(${getInputCols.length}, ${getOutputCols.length}).")
}
val (inputColNames, outputColNames) = getInOutCols()
val newCols = inputColNames.zip(outputColNames).map { case (inputColName, outputColName) =>
require(!schema.fieldNames.contains(outputColName),
s"Output Column $outputColName already exists.")
val inputType = schema(inputColName).dataType
require(inputType.sameType(ArrayType(StringType)), "Input type must be " +
s"${ArrayType(StringType).catalogString} but got ${inputType.catalogString}.")
StructField(outputColName, inputType, schema(inputColName).nullable)
}
StructType(schema.fields ++ newCols)
}
@Since("1.5.0")
override def copy(extra: ParamMap): StopWordsRemover = defaultCopy(extra)
@Since("3.0.0")
override def toString: String = {
s"StopWordsRemover: uid=$uid, numStopWords=${$(stopWords).length}, locale=${$(locale)}, " +
s"caseSensitive=${$(caseSensitive)}"
}
}
@Since("1.6.0")
object StopWordsRemover extends DefaultParamsReadable[StopWordsRemover] {
private[feature]
val supportedLanguages = Set("danish", "dutch", "english", "finnish", "french", "german",
"hungarian", "italian", "norwegian", "portuguese", "russian", "spanish", "swedish", "turkish")
@Since("1.6.0")
override def load(path: String): StopWordsRemover = super.load(path)
/**
* Loads the default stop words for the given language.
* Supported languages: danish, dutch, english, finnish, french, german, hungarian,
* italian, norwegian, portuguese, russian, spanish, swedish, turkish
* @see <a href="http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/src/backend/snowball/stopwords/">
* here</a>
*/
@Since("2.0.0")
def loadDefaultStopWords(language: String): Array[String] = {
require(supportedLanguages.contains(language),
s"$language is not in the supported language list: ${supportedLanguages.mkString(", ")}.")
val is = getClass.getResourceAsStream(s"/org/apache/spark/ml/feature/stopwords/$language.txt")
scala.io.Source.fromInputStream(is)(scala.io.Codec.UTF8).getLines().toArray
}
}
|
package org.bouncycastle.cert.selector;
import java.io.IOException;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.util.Pack;
class MSOutlookKeyIdCalculator
{
// This is less than ideal, but it seems to be the best way of supporting this without exposing SHA-1
// as the class is only used to workout the MSOutlook Key ID, you can think of the fact it's SHA-1 as
// a coincidence...
static byte[] calculateKeyId(SubjectPublicKeyInfo info)
{
SHA1Digest dig = new SHA1Digest();
byte[] hash = new byte[dig.getDigestSize()];
byte[] spkiEnc = new byte[0];
try
{
spkiEnc = info.getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
return new byte[0];
}
// try the outlook 2010 calculation
dig.update(spkiEnc, 0, spkiEnc.length);
dig.doFinal(hash, 0);
return hash;
}
private static abstract class GeneralDigest
{
private static final int BYTE_LENGTH = 64;
private byte[] xBuf;
private int xBufOff;
private long byteCount;
/**
* Standard constructor
*/
protected GeneralDigest()
{
xBuf = new byte[4];
xBufOff = 0;
}
/**
* Copy constructor. We are using copy constructors in place
* of the Object.clone() interface as this interface is not
* supported by J2ME.
*/
protected GeneralDigest(GeneralDigest t)
{
xBuf = new byte[t.xBuf.length];
copyIn(t);
}
protected void copyIn(GeneralDigest t)
{
System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
xBufOff = t.xBufOff;
byteCount = t.byteCount;
}
public void update(
byte in)
{
xBuf[xBufOff++] = in;
if (xBufOff == xBuf.length)
{
processWord(xBuf, 0);
xBufOff = 0;
}
byteCount++;
}
public void update(
byte[] in,
int inOff,
int len)
{
//
// fill the current word
//
while ((xBufOff != 0) && (len > 0))
{
update(in[inOff]);
inOff++;
len--;
}
//
// process whole words.
//
while (len > xBuf.length)
{
processWord(in, inOff);
inOff += xBuf.length;
len -= xBuf.length;
byteCount += xBuf.length;
}
//
// load in the remainder.
//
while (len > 0)
{
update(in[inOff]);
inOff++;
len--;
}
}
public void finish()
{
long bitLength = (byteCount << 3);
//
// add the pad bytes.
//
update((byte)128);
while (xBufOff != 0)
{
update((byte)0);
}
processLength(bitLength);
processBlock();
}
public void reset()
{
byteCount = 0;
xBufOff = 0;
for (int i = 0; i < xBuf.length; i++)
{
xBuf[i] = 0;
}
}
protected abstract void processWord(byte[] in, int inOff);
protected abstract void processLength(long bitLength);
protected abstract void processBlock();
}
private static class SHA1Digest
extends GeneralDigest
{
private static final int DIGEST_LENGTH = 20;
private int H1, H2, H3, H4, H5;
private int[] X = new int[80];
private int xOff;
/**
* Standard constructor
*/
public SHA1Digest()
{
reset();
}
public String getAlgorithmName()
{
return "SHA-1";
}
public int getDigestSize()
{
return DIGEST_LENGTH;
}
protected void processWord(
byte[] in,
int inOff)
{
// Note: Inlined for performance
// X[xOff] = Pack.bigEndianToInt(in, inOff);
int n = in[ inOff] << 24;
n |= (in[++inOff] & 0xff) << 16;
n |= (in[++inOff] & 0xff) << 8;
n |= (in[++inOff] & 0xff);
X[xOff] = n;
if (++xOff == 16)
{
processBlock();
}
}
protected void processLength(
long bitLength)
{
if (xOff > 14)
{
processBlock();
}
X[14] = (int)(bitLength >>> 32);
X[15] = (int)(bitLength & 0xffffffff);
}
public int doFinal(
byte[] out,
int outOff)
{
finish();
Pack.intToBigEndian(H1, out, outOff);
Pack.intToBigEndian(H2, out, outOff + 4);
Pack.intToBigEndian(H3, out, outOff + 8);
Pack.intToBigEndian(H4, out, outOff + 12);
Pack.intToBigEndian(H5, out, outOff + 16);
reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables
*/
public void reset()
{
super.reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
//
// Additive constants
//
private static final int Y1 = 0x5a827999;
private static final int Y2 = 0x6ed9eba1;
private static final int Y3 = 0x8f1bbcdc;
private static final int Y4 = 0xca62c1d6;
private int f(
int u,
int v,
int w)
{
return ((u & v) | ((~u) & w));
}
private int h(
int u,
int v,
int w)
{
return (u ^ v ^ w);
}
private int g(
int u,
int v,
int w)
{
return ((u & v) | (u & w) | (v & w));
}
protected void processBlock()
{
//
// expand 16 word block into 80 word block.
//
for (int i = 16; i < 80; i++)
{
int t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >>> 31;
}
//
// set up working variables.
//
int A = H1;
int B = H2;
int C = H3;
int D = H4;
int E = H5;
//
// round 1
//
int idx = 0;
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + f(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + f(B, C, D) + X[idx++] + Y1;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + f(A, B, C) + X[idx++] + Y1;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + f(E, A, B) + X[idx++] + Y1;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + f(D, E, A) + X[idx++] + Y1;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + f(C, D, E) + X[idx++] + Y1;
C = C << 30 | C >>> 2;
}
//
// round 2
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y2;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y2;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y2;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y2;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y2;
C = C << 30 | C >>> 2;
}
//
// round 3
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + g(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + g(B, C, D) + X[idx++] + Y3;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + g(A, B, C) + X[idx++] + Y3;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + g(E, A, B) + X[idx++] + Y3;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + g(D, E, A) + X[idx++] + Y3;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + g(C, D, E) + X[idx++] + Y3;
C = C << 30 | C >>> 2;
}
//
// round 4
//
for (int j = 0; j <= 3; j++)
{
// E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y4;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y4;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y4;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y4;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y4;
C = C << 30 | C >>> 2;
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
for (int i = 0; i < 16; i++)
{
X[i] = 0;
}
}
}
}
|
---
title: "ORDER BY 语句"
weight: 12
type: docs
---
<!--
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.
-->
# ORDER BY 语句
{{< label Batch >}} {{< label Streaming >}}
The `ORDER BY` clause causes the result rows to be sorted according to the specified expression(s). If two rows are equal according to the leftmost expression, they are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in an implementation-dependent order.
When running in streaming mode, the primary sort order of a table must be ascending on a [time attribute]({{< ref "docs/dev/table/concepts/time_attributes" >}}). All subsequent orders can be freely chosen. But there is no this limitation in batch mode.
```sql
SELECT *
FROM Orders
ORDER BY order_time, order_id
```
{{< top >}}
|
/* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.173
ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
Available from http://www.3gpp.org
(C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
------------------------------------------------------------------------------
Filename: pit_shrp.cpp
Date: 05/08/2007
------------------------------------------------------------------------------
REVISION HISTORY
Description:
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
int16 * x, in/out: impulse response (or algebraic code)
int16 pit_lag, input : pitch lag
int16 sharp, input : pitch sharpening factor (Q15)
int16 L_subfr input : subframe size
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
Performs Pitch sharpening routine
------------------------------------------------------------------------------
REQUIREMENTS
------------------------------------------------------------------------------
REFERENCES
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "pv_amr_wb_type_defs.h"
#include "pvamrwbdecoder_basic_op.h"
#include "pvamrwbdecoder_acelp.h"
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
void Pit_shrp(
int16 * x, /* in/out: impulse response (or algebraic code) */
int16 pit_lag, /* input : pitch lag */
int16 sharp, /* input : pitch sharpening factor (Q15) */
int16 L_subfr /* input : subframe size */
)
{
int16 i;
int32 L_tmp;
for (i = pit_lag; i < L_subfr; i++)
{
L_tmp = mac_16by16_to_int32((int32)x[i] << 16, x[i - pit_lag], sharp);
x[i] = amr_wb_round(L_tmp);
}
return;
}
|
WITH
x
AS (SELECT
a1
FROM
t1)
SELECT x.a1
FROM x
ORDER BY
x.a1;
|
<!DOCTYPE html>
<html>
<canvas id='c' width='400' height='400'></canvas>
<script src='webgl-utils.js'></script>
<script id="vshader" type="text/plain">
attribute vec2 aVertexPosition;
varying vec2 vTexCoord;
uniform vec2 uOffset;
void main() {
vTexCoord = aVertexPosition + uOffset;
gl_Position = vec4(aVertexPosition, 0, 1);
}
</script>
<script id="fshader" type="text/plain">
precision mediump float;
varying vec2 vTexCoord;
void main() {
gl_FragColor = vec4(vTexCoord, 0, 1);
}
</script>
<script>
var c = document.getElementById('c');
var gl = c.getContext('experimental-webgl');
var offset = [1,1];
var vertexPosBuffer = screenQuad();
var vs = document.getElementById('vshader').textContent;
var fs = document.getElementById('fshader').textContent;
var program = createProgram(vs,fs);
gl.useProgram(program);
program.vertexPosAttrib = gl.getAttribLocation(program, 'aVertexPosition');
program.offsetUniform = gl.getUniformLocation(program, 'uOffset');
gl.enableVertexAttribArray(program.vertexPosArray);
gl.vertexAttribPointer(program.vertexPosAttrib, vertexPosBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.uniform2f(program.offsetUniform, offset[0], offset[1]);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexPosBuffer.numItems);
</script>
</html> |
package org.apache.lucene.analysis.util;
/*
* 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.
*/
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.ServiceConfigurationError;
import org.apache.lucene.util.SPIClassIterator;
/**
* Helper class for loading named SPIs from classpath (e.g. Tokenizers, TokenStreams).
* @lucene.internal
*/
final class AnalysisSPILoader<S extends AbstractAnalysisFactory> {
private volatile Map<String,Class<? extends S>> services = Collections.emptyMap();
private final Class<S> clazz;
private final String[] suffixes;
public AnalysisSPILoader(Class<S> clazz) {
this(clazz, new String[] { clazz.getSimpleName() });
}
public AnalysisSPILoader(Class<S> clazz, ClassLoader loader) {
this(clazz, new String[] { clazz.getSimpleName() }, loader);
}
public AnalysisSPILoader(Class<S> clazz, String[] suffixes) {
this(clazz, suffixes, Thread.currentThread().getContextClassLoader());
}
public AnalysisSPILoader(Class<S> clazz, String[] suffixes, ClassLoader classloader) {
this.clazz = clazz;
this.suffixes = suffixes;
// if clazz' classloader is not a parent of the given one, we scan clazz's classloader, too:
final ClassLoader clazzClassloader = clazz.getClassLoader();
if (clazzClassloader != null && !SPIClassIterator.isParentClassLoader(clazzClassloader, classloader)) {
reload(clazzClassloader);
}
reload(classloader);
}
/**
* Reloads the internal SPI list from the given {@link ClassLoader}.
* Changes to the service list are visible after the method ends, all
* iterators (e.g., from {@link #availableServices()},...) stay consistent.
*
* <p><b>NOTE:</b> Only new service providers are added, existing ones are
* never removed or replaced.
*
* <p><em>This method is expensive and should only be called for discovery
* of new service providers on the given classpath/classloader!</em>
*/
public synchronized void reload(ClassLoader classloader) {
final LinkedHashMap<String,Class<? extends S>> services =
new LinkedHashMap<>(this.services);
final SPIClassIterator<S> loader = SPIClassIterator.get(clazz, classloader);
while (loader.hasNext()) {
final Class<? extends S> service = loader.next();
final String clazzName = service.getSimpleName();
String name = null;
for (String suffix : suffixes) {
if (clazzName.endsWith(suffix)) {
name = clazzName.substring(0, clazzName.length() - suffix.length()).toLowerCase(Locale.ROOT);
break;
}
}
if (name == null) {
throw new ServiceConfigurationError("The class name " + service.getName() +
" has wrong suffix, allowed are: " + Arrays.toString(suffixes));
}
// only add the first one for each name, later services will be ignored
// this allows to place services before others in classpath to make
// them used instead of others
//
// TODO: Should we disallow duplicate names here?
// Allowing it may get confusing on collisions, as different packages
// could contain same factory class, which is a naming bug!
// When changing this be careful to allow reload()!
if (!services.containsKey(name)) {
services.put(name, service);
}
}
this.services = Collections.unmodifiableMap(services);
}
public S newInstance(String name, Map<String,String> args) {
final Class<? extends S> service = lookupClass(name);
try {
return service.getConstructor(Map.class).newInstance(args);
} catch (Exception e) {
throw new IllegalArgumentException("SPI class of type "+clazz.getName()+" with name '"+name+"' cannot be instantiated. " +
"This is likely due to a misconfiguration of the java class '" + service.getName() + "': ", e);
}
}
public Class<? extends S> lookupClass(String name) {
final Class<? extends S> service = services.get(name.toLowerCase(Locale.ROOT));
if (service != null) {
return service;
} else {
throw new IllegalArgumentException("A SPI class of type "+clazz.getName()+" with name '"+name+"' does not exist. "+
"You need to add the corresponding JAR file supporting this SPI to your classpath. "+
"The current classpath supports the following names: "+availableServices());
}
}
public Set<String> availableServices() {
return services.keySet();
}
}
|
<!DOCTYPE html>
<!--
Copyright (c) 2015 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original 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 work 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.
Authors:
Zhu, YongyongX <yongyongx.zhu@intel.com>
-->
<meta charset='utf-8'>
<title>Secure Data Test: AppSecurityApi_open_bad_url</title>
<link rel="author" title="Intel" href="http://www.intel.com/">
<link rel="help" href="https://software.intel.com/en-us/app-security-api/api">
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="../../../cordova.js"></script>
<script src="js/appSecurityApi.js"></script>
<script src="js/q.js"></script>
<div id="log"></div>
<script type="text/javascript">
setTimeout(function() { test(); }, 500);
var error_code_bad_url = 29
function test() {
async_test(function(t) {
intel.security.secureTransport.open({'url': '123', 'method': 'GET', 'serverKey': '', 'timeout': 1000})
.then(function(instanceID) {
t.step(function() {
assert_unreached("open should fail");
});
t.done();
})
.catch(function (errorObj) {
t.step(function() {
assert_equals(errorObj.code, error_code_bad_url);
});
t.done();
});
}, document.title);
}
</script>
|
C_SOURCES := main.c
DYLIB_NAME := a
DYLIB_C_SOURCES := a.c
include Makefile.rules
|
<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
</head>
<body>
<script>
description("This tests the constructor for the MediaKeyMessageEvent DOM class.");
var arrayBuffer = new ArrayBuffer(1);
// Default values for bubbles and cancelable.
shouldBe("new MediaKeyMessageEvent('eventType', { messageType: 'license-request', message: arrayBuffer }).bubbles", "false");
shouldBe("new MediaKeyMessageEvent('eventType', { messageType: 'license-request', message: arrayBuffer }).cancelable", "false");
// bubbles is passed.
shouldBe("new MediaKeyMessageEvent('eventType', { bubbles: false, messageType: 'license-request', message: arrayBuffer }).bubbles", "false");
shouldBe("new MediaKeyMessageEvent('eventType', { bubbles: true, messageType: 'license-request', message: arrayBuffer }).bubbles", "true");
// cancelable is passed.
shouldBe("new MediaKeyMessageEvent('eventType', { cancelable: false, messageType: 'license-request', message: arrayBuffer }).cancelable", "false");
shouldBe("new MediaKeyMessageEvent('eventType', { cancelable: true, messageType: 'license-request', message: arrayBuffer }).cancelable", "true");
// message is passed.
shouldBe("new MediaKeyMessageEvent('eventType', { messageType: 'license-request', message: arrayBuffer }).message", "arrayBuffer");
// messageType is passed.
shouldBeEqualToString("new MediaKeyMessageEvent('eventType', { messageType: 'license-request', message: arrayBuffer }).messageType", "license-request");
shouldBeEqualToString("new MediaKeyMessageEvent('eventType', { messageType: 'license-renewal', message: arrayBuffer }).messageType", "license-renewal");
shouldBeEqualToString("new MediaKeyMessageEvent('eventType', { messageType: 'license-release', message: arrayBuffer }).messageType", "license-release");
</script>
</body>
</html>
|
<!DOCTYPE html>
<!--
Copyright (c) 2015 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original 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 work 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.
Authors:
Zhu, YongyongX <yongyongx.zhu@intel.com>
-->
<meta charset='utf-8'>
<title>Secure Data Test: AppSecurityApi_destroy_invalid_instance</title>
<link rel="author" title="Intel" href="http://www.intel.com/">
<link rel="help" href="https://software.intel.com/en-us/app-security-api/api">
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="../../../cordova.js"></script>
<script src="js/appSecurityApi.js"></script>
<script src="js/q.js"></script>
<div id="log"></div>
<script type="text/javascript">
var error_code_invalid_instance = 9
setTimeout(function() { test(); }, 500);
function test() {
async_test(function(t) {
intel.security.secureData.destroy(1234)
.then(function() {
t.step(function() {
assert_true(false, 'fail:code = '+ errorObj.code + ', message = ' + errorObj.message);
});
t.done();
})
.catch(function (errorObj) {
t.step(function() {
assert_equals(errorObj.code, error_code_invalid_instance);
});
t.done();
});
}, document.title);
}
</script>
|
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
// here you can set theme used for your frontend application
// - template comes with: 'default', 'slate', 'spacelab' and 'cerulean'
'view' => [
'theme' => [
'pathMap' => ['@app/views' => '@webroot/themes/slate/views'],
'baseUrl' => '@web/themes/slate',
],
],
'user' => [
'identityClass' => 'common\models\UserIdentity',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Jeff Walden
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 465980;
var summary = 'Do not crash @ InitArrayElements';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
function describe(name, startLength, pushArgs, expectThrow, expectLength)
{
return name + "(" + startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")";
}
var push = Array.prototype.push;
var unshift = Array.prototype.unshift;
function testArrayPush(startLength, pushArgs, expectThrow, expectLength)
{
print("running testArrayPush(" +
startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")...");
var a = new Array(startLength);
try
{
push.apply(a, pushArgs);
if (expectThrow)
{
throw "expected to throw for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
}
catch (e)
{
if (!(e instanceof RangeError))
{
throw "unexpected exception type thrown: " + e + " for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
if (!expectThrow)
{
throw "unexpected exception " + e + " for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
}
if (a.length !== expectLength)
{
throw "unexpected modified-array length for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
for (var i = 0, sz = pushArgs.length; i < sz; i++)
{
var index = i + startLength;
if (a[index] !== pushArgs[i])
{
throw "unexpected value " + a[index] +
" at index " + index + " (" + i + ") during " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength) + ", expected " + pushArgs[i];
}
}
}
function testArrayUnshift(startLength, unshiftArgs, expectThrow, expectLength)
{
print("running testArrayUnshift(" +
startLength + ", " +
"[" + unshiftArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")...");
var a = new Array(startLength);
try
{
unshift.apply(a, unshiftArgs);
if (expectThrow)
{
throw "expected to throw for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
catch (e)
{
if (!(e instanceof RangeError))
{
throw "unexpected exception type thrown: " + e + " for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
if (!expectThrow)
{
throw "unexpected exception " + e + " for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
if (a.length !== expectLength)
{
throw "unexpected modified-array length for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
for (var i = 0, sz = unshiftArgs.length; i < sz; i++)
{
if (a[i] !== unshiftArgs[i])
{
throw "unexpected value at index " + i + " during " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
}
var failed = true;
try
{
var foo = "foo", bar = "bar", baz = "baz";
testArrayPush(4294967294, [foo], false, 4294967295);
testArrayPush(4294967294, [foo, bar], true, 4294967295);
testArrayPush(4294967294, [foo, bar, baz], true, 4294967295);
testArrayPush(4294967295, [foo], true, 4294967295);
testArrayPush(4294967295, [foo, bar], true, 4294967295);
testArrayPush(4294967295, [foo, bar, baz], true, 4294967295);
testArrayUnshift(4294967294, [foo], false, 4294967295);
testArrayUnshift(4294967294, [foo, bar], true, 4294967294);
testArrayUnshift(4294967294, [foo, bar, baz], true, 4294967294);
testArrayUnshift(4294967295, [foo], true, 4294967295);
testArrayUnshift(4294967295, [foo, bar], true, 4294967295);
testArrayUnshift(4294967295, [foo, bar, baz], true, 4294967295);
}
catch (e)
{
actual = e + '';
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
|
/* Recreated Espressif libpp lmac.o contents.
Copyright (C) 2015 Espressif Systems. Derived from MIT Licensed SDK libraries.
BSD Licensed as described in the file LICENSE
*/
#include "open_esplibs.h"
#if OPEN_LIBPP_LMAC
// The contents of this file are only built if OPEN_LIBPHY_PHY_CHIP_SLEEP is set to true
#endif /* OPEN_LIBPP_LMAC */
|
// Type definitions for node-hook 1.0
// Project: https://github.com/bahmutov/node-hook#readme
// Definitions by: Nathan Hardy <https://github.com/nhardy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Options {
verbose?: boolean | undefined;
}
type Transform = (source: string, filename: string) => string;
interface NodeHook {
hook: {
(extension: string, transform: Transform, options?: Options): void;
(transform: Transform, _?: undefined, options?: Options): void;
};
unhook(extension?: string): void;
}
declare const hook: NodeHook;
export = hook;
|
//------------------------------------------------------------------------------
// <copyright file="XmlSchemaDocumentation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System.Collections;
using System.ComponentModel;
using System.Xml.Serialization;
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSchemaDocumentation : XmlSchemaObject {
string source;
string language;
XmlNode[] markup;
static XmlSchemaSimpleType languageType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName("language",XmlReservedNs.NsXs));
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation.Source"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("source", DataType="anyURI")]
public string Source {
get { return source; }
set { source = value; }
}
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation.Language"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("xml:lang")]
public string Language {
get { return language; }
set { language = (string)languageType.Datatype.ParseValue(value, (XmlNameTable) null, (IXmlNamespaceResolver) null); }
}
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation.Markup"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlText(), XmlAnyElement]
public XmlNode[] Markup {
get { return markup; }
set { markup = value; }
}
}
}
|
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../_references.ts"/>
module powerbi.visuals {
export interface BasicShapeDataViewObjects extends DataViewObjects {
general: BasicShapeDataViewObject;
line: LineObject;
fill: FillObject;
lockAspect: LockAspectObject;
rotation: RotationObject;
}
export interface LineObject extends DataViewObject {
lineColor: Fill;
roundEdge: number;
weight: number;
transparency: number;
}
export interface FillObject extends DataViewObject {
transparency: number;
fillColor: Fill;
show: boolean;
}
export interface LockAspectObject extends DataViewObject {
show: boolean;
}
export interface RotationObject extends DataViewObject {
angle: number;
}
export interface BasicShapeDataViewObject extends DataViewObject {
shapeType: string;
shapeSvg: string;
}
export interface BasicShapeData {
shapeType: string;
lineColor: string;
lineTransparency: number;
lineWeight: number;
showFill: boolean;
fillColor: string;
shapeTransparency: number;
lockAspectRatio: boolean;
roundEdge: number;
angle: number;
}
export class BasicShapeVisual implements IVisual {
private currentViewport: IViewport;
private element: JQuery;
private data: BasicShapeData;
private selection: D3.Selection;
public static DefaultShape: string = powerbi.basicShapeType.rectangle;
public static DefaultStrokeColor: string = '#00B8AA';
public static DefaultFillColor: string = '#E6E6E6';
public static DefaultFillTransValue: number = 100;
public static DefaultWeightValue: number = 3;
public static DefaultLineTransValue: number = 100;
public static DefaultRoundEdgeValue: number = 0;
public static DefaultAngle: number = 0;
/**property for the shape line color */
get shapeType(): string {
return this.data ? this.data.shapeType : BasicShapeVisual.DefaultShape;
}
set shapeType(shapeType: string) {
this.data.shapeType = shapeType;
}
/**property for the shape line color */
get lineColor(): string {
return this.data ? this.data.lineColor : BasicShapeVisual.DefaultStrokeColor;
}
set lineColor(color: string) {
this.data.lineColor = color;
}
/**property for the shape line transparency */
get lineTransparency(): number {
return this.data ? this.data.lineTransparency : BasicShapeVisual.DefaultLineTransValue;
}
set lineTransparency(trans: number) {
this.data.lineTransparency = trans;
}
/**property for the shape line weight */
get lineWeight(): number {
return this.data ? this.data.lineWeight : BasicShapeVisual.DefaultWeightValue;
}
set lineWeight(weight: number) {
this.data.lineWeight = weight;
}
/**property for the shape round edge */
get roundEdge(): number {
return this.data ? this.data.roundEdge : BasicShapeVisual.DefaultRoundEdgeValue;
}
set roundEdge(roundEdge: number) {
this.data.roundEdge = roundEdge;
}
/**property for showing the fill properties */
get showFill(): boolean {
return this.data ? this.data.showFill : true;
}
set showFill(show: boolean) {
this.data.showFill = show;
}
/**property for the shape line color */
get fillColor(): string {
return this.data ? this.data.fillColor : BasicShapeVisual.DefaultFillColor;
}
set fillColor(color: string) {
this.data.fillColor = color;
}
/**property for the shape fill transparency */
get shapeTransparency(): number {
return this.data ? this.data.shapeTransparency : BasicShapeVisual.DefaultFillTransValue;
}
set shapeTransparency(trans: number) {
this.data.shapeTransparency = trans;
}
/**property for showing the lock aspect ratio */
get lockAspectRatio(): boolean {
return this.data ? this.data.lockAspectRatio : false;
}
set lockAspectRatio(show: boolean) {
this.data.lockAspectRatio = show;
}
/**property for the shape angle */
get angle(): number {
return this.data ? this.data.angle : BasicShapeVisual.DefaultAngle;
}
set angle(angle: number) {
this.data.angle = angle;
}
public init(options: VisualInitOptions) {
this.element = options.element;
this.selection = d3.select(this.element.context);
this.currentViewport = options.viewport;
}
public constructor(options?: VisualInitOptions) {
}
public update(options: VisualUpdateOptions): void {
debug.assertValue(options, 'options');
this.currentViewport = options.viewport;
let dataViews = options.dataViews;
if (!_.isEmpty(dataViews)) {
let dataView = options.dataViews[0];
if (dataView.metadata && dataView.metadata.objects) {
let dataViewObject = <BasicShapeDataViewObjects>options.dataViews[0].metadata.objects;
this.data = this.getDataFromDataView(dataViewObject);
}
}
this.render();
}
private getDataFromDataView(dataViewObject: BasicShapeDataViewObjects): BasicShapeData {
if (dataViewObject) {
return {
shapeType: dataViewObject.general !== undefined && dataViewObject.general.shapeType !== undefined ? dataViewObject.general.shapeType : this.shapeType,
lineColor: dataViewObject.line !== undefined && dataViewObject.line.lineColor !== undefined ? dataViewObject.line.lineColor.solid.color : this.lineColor,
lineTransparency: dataViewObject.line !== undefined && dataViewObject.line.transparency !== undefined ? dataViewObject.line.transparency : this.lineTransparency,
lineWeight: dataViewObject.line !== undefined && dataViewObject.line.weight !== undefined ? dataViewObject.line.weight : this.lineWeight,
roundEdge: dataViewObject.line !== undefined && dataViewObject.line.roundEdge !== undefined ? dataViewObject.line.roundEdge : this.roundEdge,
shapeTransparency: dataViewObject.fill !== undefined && dataViewObject.fill.transparency !== undefined ? dataViewObject.fill.transparency : this.shapeTransparency,
fillColor: dataViewObject.fill !== undefined && dataViewObject.fill.fillColor !== undefined ? dataViewObject.fill.fillColor.solid.color : this.fillColor,
showFill: dataViewObject.fill !== undefined && dataViewObject.fill.show !== undefined ? dataViewObject.fill.show : this.showFill,
lockAspectRatio: dataViewObject.lockAspect !== undefined && dataViewObject.lockAspect.show !== undefined ? dataViewObject.lockAspect.show : this.lockAspectRatio,
angle: dataViewObject.rotation !== undefined && dataViewObject.rotation.angle !== undefined ? dataViewObject.rotation.angle : this.angle
};
}
return null;
}
public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] {
let objectInstances: VisualObjectInstance[] = [];
switch (options.objectName) {
case 'line':
let instance: VisualObjectInstance = {
selector: null,
properties: {
lineColor: this.lineColor,
transparency: this.lineTransparency,
weight: this.lineWeight
},
objectName: options.objectName
};
if (this.data.shapeType === powerbi.basicShapeType.rectangle) {
instance.properties['roundEdge'] = this.roundEdge;
}
objectInstances.push(instance);
return objectInstances;
case 'fill':
objectInstances.push({
selector: null,
properties: {
show: this.showFill,
fillColor: this.fillColor,
transparency: this.shapeTransparency
},
objectName: options.objectName
});
return objectInstances;
case 'lockAspect':
objectInstances.push({
selector: null,
properties: {
show: this.lockAspectRatio
},
objectName: options.objectName
});
return objectInstances;
case 'rotation':
objectInstances.push({
selector: null,
properties: {
angle: this.angle
},
objectName: options.objectName
});
return objectInstances;
}
return null;
}
public render(): void {
this.selection.html('');
switch (this.shapeType) {
case powerbi.basicShapeType.rectangle:
shapeFactory.createRectangle(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.oval:
shapeFactory.createOval(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.line:
shapeFactory.createLine(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.arrow:
shapeFactory.createUpArrow(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.triangle:
shapeFactory.createTriangle(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
default:
break;
}
}
}
}
|
// Type definitions for @webpack-blocks/assets 2.0
// Project: https://github.com/andywer/webpack-blocks/tree/master/packages/assets
// Definitions by: Max Boguslavskiy <https://github.com/maxbogus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.7
import { Block } from 'webpack-blocks';
export namespace css {
type UrlFilter = (url: string, resourcePath: string) => boolean;
type ImportFilter = (parseImport: ParseImportOptions, resourcePath: string) => boolean;
type GetLocalIdent = (context: any, localIdentName: any, localName: any, options: any) => string;
type NameFunction = (file: string) => any;
type PathFunction = (url: string, resourcePath: string, context: string) => any;
interface ParseImportOptions {
url: string;
media: string;
}
interface ModuleOptions {
mode?: string | undefined;
localIdentName?: string | undefined;
context?: string | undefined;
hashPrefix?: string | undefined;
getLocalIdent?: GetLocalIdent | undefined;
localIdentRegExp?: string | RegExp | undefined;
/**
* 0 => no loaders (default);
* 1 => postcss-loader;
* 2 => postcss-loader, sass-loader
*/
importLoaders?: 0 | 1 | 2 | undefined;
localsConvention?: 'asIs' | 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | undefined;
onlyLocals?: boolean | undefined;
}
interface CssOptions {
url?: boolean | UrlFilter | undefined;
import?: boolean | ImportFilter | undefined;
modules?: boolean | string | ModuleOptions | undefined;
sourceMap?: boolean | undefined;
}
interface FileOptions {
name?: string | NameFunction | undefined;
outputPath?: string | PathFunction | undefined;
publicPath?: string | PathFunction | undefined;
postTransformPublicPath?: ((p: string) => string) | undefined;
context?: string | undefined;
emitFile?: boolean | undefined;
regExp?: RegExp | undefined;
}
interface UrlOptions {
fallback?: string | undefined;
limit?: number | boolean | string | undefined;
mimetype?: string | undefined;
}
function modules(options?: ModuleOptions): any;
}
export function css(options?: css.CssOptions): Block;
export function file(options?: css.FileOptions): Block;
export function url(options?: css.UrlOptions): Block;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Thelia\Model\ProductDocument | </title>
<link rel="stylesheet" type="text/css" href="../../stylesheet.css">
</head>
<body id="class">
<div class="header">
<ul>
<li><a href="../../classes.html">Classes</a></li>
<li><a href="../../namespaces.html">Namespaces</a></li>
<li><a href="../../interfaces.html">Interfaces</a></li>
<li><a href="../../traits.html">Traits</a></li>
<li><a href="../../doc-index.html">Index</a></li>
</ul>
<div id="title"></div>
<div class="type">Class</div>
<h1><a href="../../Thelia/Model.html">Thelia\Model</a>\ProductDocument</h1>
</div>
<div class="content">
<p> class
<strong>ProductDocument</strong> extends <a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></p>
<h2>Constants</h2>
<table>
<tr>
<td>TABLE_MAP</td>
<td class="last">
<p><em>TableMap class name</em></p>
<p>
</p>
</td>
</tr>
</table>
<h2>Methods</h2>
<table>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method___construct">__construct</a>()
<p>Initializes internal state of Thelia\Model\Base\ProductDocument object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method___construct"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_isModified">isModified</a>()
<p>Returns whether the object has been modified.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_isModified"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_isColumnModified">isColumnModified</a>(string $col)
<p>Has specified column been modified?</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_isColumnModified"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="#method_getModifiedColumns">getModifiedColumns</a>()
<p>Get the columns that have been modified in this object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getModifiedColumns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_isNew">isNew</a>()
<p>Returns whether the object has ever been saved.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_isNew"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_setNew">setNew</a>(boolean $b)
<p>Setter for the isNew attribute.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setNew"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_isDeleted">isDeleted</a>()
<p>Whether this object has been deleted.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_isDeleted"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_setDeleted">setDeleted</a>(boolean $b)
<p>Specify whether this object has been deleted.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setDeleted"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_resetModified">resetModified</a>(string $col = null)
<p>Sets the modified state for the object to be false.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_resetModified"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_equals">equals</a>(mixed $obj)
<p>Compares this with another <code>ProductDocument</code> instance.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_equals"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_hashCode">hashCode</a>()
<p>If the primary key is not null, return the hashcode of the primary key.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_hashCode"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="#method_getVirtualColumns">getVirtualColumns</a>()
<p>Get the associative array of the virtual columns in this object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getVirtualColumns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_hasVirtualColumn">hasVirtualColumn</a>(string $name)
<p>Checks the existence of a virtual column in this object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_hasVirtualColumn"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
mixed
</td>
<td class="last">
<a href="#method_getVirtualColumn">getVirtualColumn</a>(string $name)
<p>Get the value of a virtual column in this object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getVirtualColumn"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setVirtualColumn">setVirtualColumn</a>(string $name, mixed $value)
<p>Set the value of a virtual column in this object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setVirtualColumn"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_importFrom">importFrom</a>(mixed $parser, string $data)
<p>Populate the current object from a string, using a given parser format <code> $book = new Book(); $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); </code></p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_importFrom"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_exportTo">exportTo</a>(mixed $parser, boolean $includeLazyLoadColumns = true)
<p>Export the current object properties to a string, using a given parser format <code> $book = BookQuery::create()->findPk(9012); echo $book->exportTo('JSON'); => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); </code></p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_exportTo"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method___sleep">__sleep</a>()
<p>Clean up internal collections prior to serializing Avoids recursive loops that turn into segmentation faults when serializing</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method___sleep"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_getId">getId</a>()
<p>Get the [id] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_getProductId">getProductId</a>()
<p>Get the [product_id] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getProductId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_getFile">getFile</a>()
<p>Get the [file] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getFile"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_getPosition">getPosition</a>()
<p>Get the [position] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
mixed
</td>
<td class="last">
<a href="#method_getCreatedAt">getCreatedAt</a>(string $format = NULL)
<p>Get the [optionally formatted] temporal [created_at] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getCreatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
mixed
</td>
<td class="last">
<a href="#method_getUpdatedAt">getUpdatedAt</a>(string $format = NULL)
<p>Get the [optionally formatted] temporal [updated_at] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getUpdatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setId">setId</a>(int $v)
<p>Set the value of [id] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setProductId">setProductId</a>(int $v)
<p>Set the value of [product_id] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setProductId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setFile">setFile</a>(string $v)
<p>Set the value of [file] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setFile"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setPosition">setPosition</a>(int $v)
<p>Set the value of [position] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setCreatedAt">setCreatedAt</a>(mixed $v)
<p>Sets the value of [created_at] column to a normalized version of the date/time value specified.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setCreatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setUpdatedAt">setUpdatedAt</a>(mixed $v)
<p>Sets the value of [updated_at] column to a normalized version of the date/time value specified.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setUpdatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_hasOnlyDefaultValues">hasOnlyDefaultValues</a>()
<p>Indicates whether the columns in this object are only set to default values.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_hasOnlyDefaultValues"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_hydrate">hydrate</a>(array $row, int $startcol, boolean $rehydrate = false, string $indexType = TableMap::TYPE_NUM)
<p>Hydrates (populates) the object variables with values from the database resultset.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_hydrate"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_ensureConsistency">ensureConsistency</a>()
<p>Checks and repairs the internal consistency of the object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_ensureConsistency"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_reload">reload</a>(boolean $deep = false, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Reloads this object from datastore based on primary key and (optionally) resets all associated objects.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_reload"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_delete">delete</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Removes this object from datastore and sets delete attribute.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_delete"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_save">save</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Persists this object to the database.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_save"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
mixed
</td>
<td class="last">
<a href="#method_getByName">getByName</a>(string $name, string $type = TableMap::TYPE_PHPNAME)
<p>Retrieves a field from the object by name passed in as a string.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getByName"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
mixed
</td>
<td class="last">
<a href="#method_getByPosition">getByPosition</a>(int $pos)
<p>Retrieves a field from the object by Position as specified in the xml schema.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getByPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="#method_toArray">toArray</a>(string $keyType = TableMap::TYPE_PHPNAME, boolean $includeLazyLoadColumns = true, array $alreadyDumpedObjects = array(), boolean $includeForeignObjects = false)
<p>Exports the object as an array.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_toArray"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_setByName">setByName</a>(string $name, mixed $value, string $type = TableMap::TYPE_PHPNAME)
<p>Sets a field from the object by name passed in as a string.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setByName"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_setByPosition">setByPosition</a>(int $pos, mixed $value)
<p>Sets a field from the object by Position as specified in the xml schema.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setByPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_fromArray">fromArray</a>(array $arr, string $keyType = TableMap::TYPE_PHPNAME)
<p>Populates the object using an array.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_fromArray"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
</td>
<td class="last">
<a href="#method_buildCriteria">buildCriteria</a>()
<p>Build a Criteria object containing the values of all modified columns in this object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_buildCriteria"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
</td>
<td class="last">
<a href="#method_buildPkeyCriteria">buildPkeyCriteria</a>()
<p>Builds a Criteria object containing the primary key for this object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_buildPkeyCriteria"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_getPrimaryKey">getPrimaryKey</a>()
<p>Returns the primary key for this object (row).</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getPrimaryKey"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_setPrimaryKey">setPrimaryKey</a>(int $key)
<p>Generic method to set the primary key (id column).</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setPrimaryKey"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_isPrimaryKeyNull">isPrimaryKeyNull</a>()
<p>Returns true if the primary key for this object is null.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_isPrimaryKeyNull"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_copyInto">copyInto</a>(object $copyObj, boolean $deepCopy = false, boolean $makeNew = true)
<p>Sets contents of passed object to values from current object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_copyInto"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_copy">copy</a>(boolean $deepCopy = false)
<p>Makes a copy of this object that will be inserted as a new row in table when saved.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_copy"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setProduct">setProduct</a>(<a href="../../Thelia/Model/Product.html"><abbr title="Thelia\Model\Product">Product</abbr></a> $v = null)
<p>Declares an association between this object and a ChildProduct object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setProduct"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/Product.html"><abbr title="Thelia\Model\Product">Product</abbr></a>
</td>
<td class="last">
<a href="#method_getProduct">getProduct</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Get the associated ChildProduct object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getProduct"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_initRelation">initRelation</a>(string $relationName)
<p>Initializes a collection based on the name of a relation.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_initRelation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_clearProductDocumentI18ns">clearProductDocumentI18ns</a>()
<p>Clears out the collProductDocumentI18ns collection</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_clearProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_resetPartialProductDocumentI18ns">resetPartialProductDocumentI18ns</a>($v = true)
<p>Reset is the collProductDocumentI18ns collection loaded partially.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_resetPartialProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
void
</td>
<td class="last">
<a href="#method_initProductDocumentI18ns">initProductDocumentI18ns</a>(boolean $overrideExisting = true)
<p>Initializes the collProductDocumentI18ns collection.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_initProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>[]
</td>
<td class="last">
<a href="#method_getProductDocumentI18ns">getProductDocumentI18ns</a>(<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Gets an array of ChildProductDocumentI18n objects which contain a foreign key that references this object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setProductDocumentI18ns">setProductDocumentI18ns</a>(<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr> $productDocumentI18ns, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Sets a collection of ProductDocumentI18n objects related by a one-to-many relationship to the current object.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_countProductDocumentI18ns">countProductDocumentI18ns</a>(<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null, boolean $distinct = false, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Returns the number of related ProductDocumentI18n objects.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_countProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_addProductDocumentI18n">addProductDocumentI18n</a>(<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a> $l)
<p>Method called to associate a ChildProductDocumentI18n object to this object through the ChildProductDocumentI18n foreign key attribute.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_addProductDocumentI18n"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_removeProductDocumentI18n">removeProductDocumentI18n</a>(<a href="../../Thelia/Model/Base/ProductDocumentI18n.html"><abbr title="Thelia\Model\Base\ProductDocumentI18n">ProductDocumentI18n</abbr></a> $productDocumentI18n)
<p>
</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_removeProductDocumentI18n"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_clear">clear</a>()
<p>Clears the current object and sets all attributes to their default values</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_clear"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_clearAllReferences">clearAllReferences</a>(boolean $deep = false)
<p>Resets all references to other model objects or collections of model objects.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_clearAllReferences"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method___toString">__toString</a>()
<p>Return the string representation of this object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method___toString"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_keepUpdateDateUnchanged">keepUpdateDateUnchanged</a>()
<p>Mark the current object so that the update date doesn't get updated during next save</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_keepUpdateDateUnchanged"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_setLocale">setLocale</a>(string $locale = 'en_US')
<p>Sets the locale for translations</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setLocale"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_getLocale">getLocale</a>()
<p>Gets the locale for translations</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getLocale"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
</td>
<td class="last">
<a href="#method_getTranslation">getTranslation</a>(string $locale = 'en_US', <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Returns the current translation for a given locale</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getTranslation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
</td>
<td class="last">
<a href="#method_removeTranslation">removeTranslation</a>(string $locale = 'en_US', <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Remove the translation for a given locale</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_removeTranslation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
</td>
<td class="last">
<a href="#method_getCurrentTranslation">getCurrentTranslation</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Returns the current translation</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getCurrentTranslation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_getTitle">getTitle</a>()
<p>Get the [title] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getTitle"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
</td>
<td class="last">
<a href="#method_setTitle">setTitle</a>(string $v)
<p>Set the value of [title] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setTitle"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_getDescription">getDescription</a>()
<p>Get the [description] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getDescription"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
</td>
<td class="last">
<a href="#method_setDescription">setDescription</a>(string $v)
<p>Set the value of [description] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setDescription"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_getChapo">getChapo</a>()
<p>Get the [chapo] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getChapo"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
</td>
<td class="last">
<a href="#method_setChapo">setChapo</a>(string $v)
<p>Set the value of [chapo] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setChapo"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
string
</td>
<td class="last">
<a href="#method_getPostscriptum">getPostscriptum</a>()
<p>Get the [postscriptum] column value.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_getPostscriptum"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
</td>
<td class="last">
<a href="#method_setPostscriptum">setPostscriptum</a>(string $v)
<p>Set the value of [postscriptum] column.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_setPostscriptum"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_preSave">preSave</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before persisting the object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_preSave"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_postSave">postSave</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after persisting the object</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_postSave"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_preInsert">preInsert</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before inserting to database</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_postInsert">postInsert</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after inserting to database</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_postInsert"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_preUpdate">preUpdate</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before updating the object in database</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_preUpdate"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_postUpdate">postUpdate</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after updating the object in database</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_postUpdate"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
boolean
</td>
<td class="last">
<a href="#method_preDelete">preDelete</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run before deleting the object in database</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_postDelete">postDelete</a>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)
<p>Code to be run after deleting the object in database</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method_postDelete"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
array|string
</td>
<td class="last">
<a href="#method___call">__call</a>(string $name, mixed $params)
<p>Derived method to catches calls to undefined methods.</p>
</td>
<td><small>from <a href="../../Thelia/Model/Base/ProductDocument.html#method___call"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<abbr title="Thelia\Model\$this">$this</abbr>
</td>
<td class="last">
<a href="#method_setParentId">setParentId</a>(int $parentId)
<p>Set Document parent id</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
int
</td>
<td class="last">
<a href="#method_getParentId">getParentId</a>()
<p>Get Document parent id</p>
</td>
<td></td>
</tr>
</table>
<h2>Details</h2>
<h3 id="method___construct">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method___construct"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 140</div>
<code> public
<strong>__construct</strong>()</code>
</h3>
<div class="details">
<p>Initializes internal state of Thelia\Model\Base\ProductDocument object.</p>
<p>
</p>
<div class="tags">
</div>
</div>
<h3 id="method_isModified">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_isModified"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 149</div>
<code> public boolean
<strong>isModified</strong>()</code>
</h3>
<div class="details">
<p>Returns whether the object has been modified.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>True if the object has been modified.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_isColumnModified">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_isColumnModified"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 160</div>
<code> public boolean
<strong>isColumnModified</strong>(string $col)</code>
</h3>
<div class="details">
<p>Has specified column been modified?</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$col</td>
<td>column fully qualified name (TableMap::TYPE<em>COLNAME), e.g. Book::AUTHOR</em>ID</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>True if $col has been modified.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getModifiedColumns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getModifiedColumns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 169</div>
<code> public array
<strong>getModifiedColumns</strong>()</code>
</h3>
<div class="details">
<p>Get the columns that have been modified in this object.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A unique list of the modified column names for this object.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_isNew">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_isNew"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 181</div>
<code> public boolean
<strong>isNew</strong>()</code>
</h3>
<div class="details">
<p>Returns whether the object has ever been saved.</p>
<p>This will
be false, if the object was retrieved from storage or was created
and then saved.</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>true, if the object has never been persisted.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setNew">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setNew"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 192</div>
<code> public
<strong>setNew</strong>(boolean $b)</code>
</h3>
<div class="details">
<p>Setter for the isNew attribute.</p>
<p>This method will be called
by Propel-generated children and objects.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>boolean</td>
<td>$b</td>
<td>the state of the object.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_isDeleted">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_isDeleted"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 201</div>
<code> public boolean
<strong>isDeleted</strong>()</code>
</h3>
<div class="details">
<p>Whether this object has been deleted.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>The deleted state of this object.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setDeleted">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setDeleted"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 211</div>
<code> public void
<strong>setDeleted</strong>(boolean $b)</code>
</h3>
<div class="details">
<p>Specify whether this object has been deleted.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>boolean</td>
<td>$b</td>
<td>The deleted state of this object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_resetModified">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_resetModified"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 221</div>
<code> public void
<strong>resetModified</strong>(string $col = null)</code>
</h3>
<div class="details">
<p>Sets the modified state for the object to be false.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$col</td>
<td>If supplied, only the specified column is reset.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_equals">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_equals"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 240</div>
<code> public boolean
<strong>equals</strong>(mixed $obj)</code>
</h3>
<div class="details">
<p>Compares this with another <code>ProductDocument</code> instance.</p>
<p>If
<code>obj</code> is an instance of <code>ProductDocument</code>, delegates to
<code>equals(ProductDocument)</code>. Otherwise, returns <code>false</code>.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>mixed</td>
<td>$obj</td>
<td>The object to compare to.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>Whether equal to the object specified.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_hashCode">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_hashCode"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 265</div>
<code> public int
<strong>hashCode</strong>()</code>
</h3>
<div class="details">
<p>If the primary key is not null, return the hashcode of the primary key.</p>
<p>Otherwise, return the hash code of the object.</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>Hashcode</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getVirtualColumns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getVirtualColumns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 279</div>
<code> public array
<strong>getVirtualColumns</strong>()</code>
</h3>
<div class="details">
<p>Get the associative array of the virtual columns in this object</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_hasVirtualColumn">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_hasVirtualColumn"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 290</div>
<code> public boolean
<strong>hasVirtualColumn</strong>(string $name)</code>
</h3>
<div class="details">
<p>Checks the existence of a virtual column in this object</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$name</td>
<td>The virtual column name</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getVirtualColumn">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getVirtualColumn"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 303</div>
<code> public mixed
<strong>getVirtualColumn</strong>(string $name)</code>
</h3>
<div class="details">
<p>Get the value of a virtual column in this object</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$name</td>
<td>The virtual column name</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>mixed</td>
<td>
</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setVirtualColumn">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setVirtualColumn"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 320</div>
<code> public <a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a>
<strong>setVirtualColumn</strong>(string $name, mixed $value)</code>
</h3>
<div class="details">
<p>Set the value of a virtual column in this object</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$name</td>
<td>The virtual column name</td>
</tr>
<tr>
<td>mixed</td>
<td>$value</td>
<td>The value to give to the virtual column</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object, for fluid interface</td>
</tr>
</table>
</div>
</div>
<h3 id="method_importFrom">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_importFrom"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 352</div>
<code> public <a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a>
<strong>importFrom</strong>(mixed $parser, string $data)</code>
</h3>
<div class="details">
<p>Populate the current object from a string, using a given parser format <code> $book = new Book(); $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); </code></p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>mixed</td>
<td>$parser</td>
<td>A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV')</td>
</tr>
<tr>
<td>string</td>
<td>$data</td>
<td>The source data to import from</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/Base/ProductDocument.html"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object, for fluid interface</td>
</tr>
</table>
</div>
</div>
<h3 id="method_exportTo">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_exportTo"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 375</div>
<code> public string
<strong>exportTo</strong>(mixed $parser, boolean $includeLazyLoadColumns = true)</code>
</h3>
<div class="details">
<p>Export the current object properties to a string, using a given parser format <code> $book = BookQuery::create()->findPk(9012); echo $book->exportTo('JSON'); => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); </code></p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>mixed</td>
<td>$parser</td>
<td>A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV')</td>
</tr>
<tr>
<td>boolean</td>
<td>$includeLazyLoadColumns</td>
<td>(optional) Whether to include lazy load(ed) columns. Defaults to TRUE.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>The exported data</td>
</tr>
</table>
</div>
</div>
<h3 id="method___sleep">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method___sleep"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 388</div>
<code> public
<strong>__sleep</strong>()</code>
</h3>
<div class="details">
<p>Clean up internal collections prior to serializing Avoids recursive loops that turn into segmentation faults when serializing</p>
<p>
</p>
<div class="tags">
</div>
</div>
<h3 id="method_getId">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 400</div>
<code> public int
<strong>getId</strong>()</code>
</h3>
<div class="details">
<p>Get the [id] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getProductId">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getProductId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 411</div>
<code> public int
<strong>getProductId</strong>()</code>
</h3>
<div class="details">
<p>Get the [product_id] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getFile">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getFile"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 422</div>
<code> public string
<strong>getFile</strong>()</code>
</h3>
<div class="details">
<p>Get the [file] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getPosition">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 433</div>
<code> public int
<strong>getPosition</strong>()</code>
</h3>
<div class="details">
<p>Get the [position] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getCreatedAt">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getCreatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 450</div>
<code> public mixed
<strong>getCreatedAt</strong>(string $format = NULL)</code>
</h3>
<div class="details">
<p>Get the [optionally formatted] temporal [created_at] column value.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$format</td>
<td>The date/time format string (either date()-style or strftime()-style). If format is NULL, then the raw \DateTime object will be returned.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>mixed</td>
<td>Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td><ul>
<li>if unable to parse/validate the date/time value.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getUpdatedAt">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getUpdatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 470</div>
<code> public mixed
<strong>getUpdatedAt</strong>(string $format = NULL)</code>
</h3>
<div class="details">
<p>Get the [optionally formatted] temporal [updated_at] column value.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$format</td>
<td>The date/time format string (either date()-style or strftime()-style). If format is NULL, then the raw \DateTime object will be returned.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>mixed</td>
<td>Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td><ul>
<li>if unable to parse/validate the date/time value.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setId">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 485</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setId</strong>(int $v)</code>
</h3>
<div class="details">
<p>Set the value of [id] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setProductId">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setProductId"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 506</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setProductId</strong>(int $v)</code>
</h3>
<div class="details">
<p>Set the value of [product_id] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setFile">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setFile"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 531</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setFile</strong>(string $v)</code>
</h3>
<div class="details">
<p>Set the value of [file] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setPosition">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 552</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setPosition</strong>(int $v)</code>
</h3>
<div class="details">
<p>Set the value of [position] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setCreatedAt">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setCreatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 574</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setCreatedAt</strong>(mixed $v)</code>
</h3>
<div class="details">
<p>Sets the value of [created_at] column to a normalized version of the date/time value specified.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>mixed</td>
<td>$v</td>
<td>string, integer (timestamp), or \DateTime value. Empty strings are treated as NULL.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setUpdatedAt">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setUpdatedAt"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 595</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setUpdatedAt</strong>(mixed $v)</code>
</h3>
<div class="details">
<p>Sets the value of [updated_at] column to a normalized version of the date/time value specified.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>mixed</td>
<td>$v</td>
<td>string, integer (timestamp), or \DateTime value. Empty strings are treated as NULL.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_hasOnlyDefaultValues">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_hasOnlyDefaultValues"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 617</div>
<code> public boolean
<strong>hasOnlyDefaultValues</strong>()</code>
</h3>
<div class="details">
<p>Indicates whether the columns in this object are only set to default values.</p>
<p>This method can be used in conjunction with isModified() to indicate whether an object is both
modified <em>and</em> has some values set which are non-default.</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>Whether the columns in this object are only been set with default values.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_hydrate">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_hydrate"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 641</div>
<code> public int
<strong>hydrate</strong>(array $row, int $startcol, boolean $rehydrate = false, string $indexType = TableMap::TYPE_NUM)</code>
</h3>
<div class="details">
<p>Hydrates (populates) the object variables with values from the database resultset.</p>
<p>An offset (0-based "start column") is specified so that objects can be hydrated
with a subset of the columns in the resultset rows. This is needed, for example,
for results of JOIN queries where the resultset row includes columns from two or
more tables.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$row</td>
<td>The row returned by DataFetcher->fetch().</td>
</tr>
<tr>
<td>int</td>
<td>$startcol</td>
<td>0-based offset column which indicates which restultset column to start with.</td>
</tr>
<tr>
<td>boolean</td>
<td>$rehydrate</td>
<td>Whether this object is being re-hydrated from the database.</td>
</tr>
<tr>
<td>string</td>
<td>$indexType</td>
<td>The index type of $row. Mostly DataFetcher->getIndexType(). One of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE_NUM.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>next starting column</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td><ul>
<li>Any caught Exception will be rewrapped as a PropelException.</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_ensureConsistency">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_ensureConsistency"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 697</div>
<code> public
<strong>ensureConsistency</strong>()</code>
</h3>
<div class="details">
<p>Checks and repairs the internal consistency of the object.</p>
<p>This method is executed after an already-instantiated object is re-hydrated
from the database. It exists to check any foreign keys to make sure that
the objects related to the current object are correct based on foreign key.</p>
<p>You can override this method in the stub class, but you should always invoke
the base method from the overridden method (i.e. parent::ensureConsistency()),
in case your model changes.</p>
<div class="tags">
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_reload">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_reload"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 714</div>
<code> public void
<strong>reload</strong>(boolean $deep = false, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Reloads this object from datastore based on primary key and (optionally) resets all associated objects.</p>
<p>This will only work if the object has been saved and has a valid primary key set.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>boolean</td>
<td>$deep</td>
<td>(optional) Whether to also de-associated any related objects.</td>
</tr>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>(optional) The ConnectionInterface connection to use.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td><ul>
<li>if this object is deleted, unsaved or doesn't have pk match in db</li>
</ul>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_delete">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_delete"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 756</div>
<code> public void
<strong>delete</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Removes this object from datastore and sets delete attribute.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>ProductDocument::setDeleted()</td>
<td></td>
</tr>
<tr>
<td>ProductDocument::isDeleted()</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_save">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_save"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 798</div>
<code> public int
<strong>save</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Persists this object to the database.</p>
<p>If the object is new, it inserts it; otherwise an update is performed.
All modified related objects will also be persisted in the doSave()
method. This method wraps all precipitate database operations in a
single transaction.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>The number of rows affected by this insert/update and any referring fk objects' save() operations.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>doSave()</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getByName">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getByName"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1023</div>
<code> public mixed
<strong>getByName</strong>(string $name, string $type = TableMap::TYPE_PHPNAME)</code>
</h3>
<div class="details">
<p>Retrieves a field from the object by name passed in as a string.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$name</td>
<td>name</td>
</tr>
<tr>
<td>string</td>
<td>$type</td>
<td>The type of fieldname the $name is of: one of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM. Defaults to TableMap::TYPE</em>PHPNAME.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>mixed</td>
<td>Value of field.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getByPosition">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getByPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1038</div>
<code> public mixed
<strong>getByPosition</strong>(int $pos)</code>
</h3>
<div class="details">
<p>Retrieves a field from the object by Position as specified in the xml schema.</p>
<p>Zero-based.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$pos</td>
<td>position in xml schema</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>mixed</td>
<td>Value of field at $pos</td>
</tr>
</table>
</div>
</div>
<h3 id="method_toArray">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_toArray"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1080</div>
<code> public array
<strong>toArray</strong>(string $keyType = TableMap::TYPE_PHPNAME, boolean $includeLazyLoadColumns = true, array $alreadyDumpedObjects = array(), boolean $includeForeignObjects = false)</code>
</h3>
<div class="details">
<p>Exports the object as an array.</p>
<p>You can specify the key type of the array by passing one of the class
type constants.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$keyType</td>
<td>(optional) One of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME, TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM. Defaults to TableMap::TYPE</em>PHPNAME.</td>
</tr>
<tr>
<td>boolean</td>
<td>$includeLazyLoadColumns</td>
<td>(optional) Whether to include lazy loaded columns. Defaults to TRUE.</td>
</tr>
<tr>
<td>array</td>
<td>$alreadyDumpedObjects</td>
<td>List of objects to skip to avoid recursion</td>
</tr>
<tr>
<td>boolean</td>
<td>$includeForeignObjects</td>
<td>(optional) Whether to include hydrated related objects. Default to FALSE.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>an associative array containing the field names (as keys) and field values</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setByName">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setByName"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1123</div>
<code> public void
<strong>setByName</strong>(string $name, mixed $value, string $type = TableMap::TYPE_PHPNAME)</code>
</h3>
<div class="details">
<p>Sets a field from the object by name passed in as a string.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$name</td>
<td>
</td>
</tr>
<tr>
<td>mixed</td>
<td>$value</td>
<td>field value</td>
</tr>
<tr>
<td>string</td>
<td>$type</td>
<td>The type of fieldname the $name is of: one of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM. Defaults to TableMap::TYPE</em>PHPNAME.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setByPosition">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setByPosition"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1138</div>
<code> public void
<strong>setByPosition</strong>(int $pos, mixed $value)</code>
</h3>
<div class="details">
<p>Sets a field from the object by Position as specified in the xml schema.</p>
<p>Zero-based.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$pos</td>
<td>position in xml schema</td>
</tr>
<tr>
<td>mixed</td>
<td>$value</td>
<td>field value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_fromArray">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_fromArray"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1179</div>
<code> public void
<strong>fromArray</strong>(array $arr, string $keyType = TableMap::TYPE_PHPNAME)</code>
</h3>
<div class="details">
<p>Populates the object using an array.</p>
<p>This is particularly useful when populating an object from one of the
request arrays (e.g. $_POST). This method goes through the column
names, checking to see whether a matching key exists in populated
array. If so the setByName() method is called for that column.</p>
<p>You can specify the key type of the array by additionally passing one
of the class type constants TableMap::TYPE<em>PHPNAME, TableMap::TYPE</em>STUDLYPHPNAME,
TableMap::TYPE<em>COLNAME, TableMap::TYPE</em>FIELDNAME, TableMap::TYPE<em>NUM.
The default key type is the column's TableMap::TYPE</em>PHPNAME.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$arr</td>
<td>An array to populate the object from.</td>
</tr>
<tr>
<td>string</td>
<td>$keyType</td>
<td>The type of keys the array uses.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_buildCriteria">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_buildCriteria"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1196</div>
<code> public <abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
<strong>buildCriteria</strong>()</code>
</h3>
<div class="details">
<p>Build a Criteria object containing the values of all modified columns in this object.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>The Criteria object containing all modified values.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_buildPkeyCriteria">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_buildPkeyCriteria"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1218</div>
<code> public <abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr>
<strong>buildPkeyCriteria</strong>()</code>
</h3>
<div class="details">
<p>Builds a Criteria object containing the primary key for this object.</p>
<p>Unlike buildCriteria() this method includes the primary key values regardless
of whether or not they have been modified.</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>The Criteria object containing value(s) for primary key(s).</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getPrimaryKey">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getPrimaryKey"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1230</div>
<code> public int
<strong>getPrimaryKey</strong>()</code>
</h3>
<div class="details">
<p>Returns the primary key for this object (row).</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setPrimaryKey">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setPrimaryKey"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1241</div>
<code> public void
<strong>setPrimaryKey</strong>(int $key)</code>
</h3>
<div class="details">
<p>Generic method to set the primary key (id column).</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$key</td>
<td>Primary key.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_isPrimaryKeyNull">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_isPrimaryKeyNull"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1250</div>
<code> public boolean
<strong>isPrimaryKeyNull</strong>()</code>
</h3>
<div class="details">
<p>Returns true if the primary key for this object is null.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_copyInto">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_copyInto"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1267</div>
<code> public
<strong>copyInto</strong>(object $copyObj, boolean $deepCopy = false, boolean $makeNew = true)</code>
</h3>
<div class="details">
<p>Sets contents of passed object to values from current object.</p>
<p>If desired, this method can also make copies of all associated (fkey referrers)
objects.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>object</td>
<td>$copyObj</td>
<td>An object of \Thelia\Model\ProductDocument (or compatible) type.</td>
</tr>
<tr>
<td>boolean</td>
<td>$deepCopy</td>
<td>Whether to also copy all rows that refer (by fkey) to the current row.</td>
</tr>
<tr>
<td>boolean</td>
<td>$makeNew</td>
<td>Whether to reset autoincrement PKs and make the object new.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_copy">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_copy"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1306</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>copy</strong>(boolean $deepCopy = false)</code>
</h3>
<div class="details">
<p>Makes a copy of this object that will be inserted as a new row in table when saved.</p>
<p>It creates a new object filling in the simple attributes, but skipping any primary
keys that are defined for the table.</p>
<p>If desired, this method can also make copies of all associated (fkey referrers)
objects.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>boolean</td>
<td>$deepCopy</td>
<td>Whether to also copy all rows that refer (by fkey) to the current row.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>Clone of current object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setProduct">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setProduct"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1323</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setProduct</strong>(<a href="../../Thelia/Model/Product.html"><abbr title="Thelia\Model\Product">Product</abbr></a> $v = null)</code>
</h3>
<div class="details">
<p>Declares an association between this object and a ChildProduct object.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/Product.html"><abbr title="Thelia\Model\Product">Product</abbr></a></td>
<td>$v</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getProduct">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getProduct"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1351</div>
<code> public <a href="../../Thelia/Model/Product.html"><abbr title="Thelia\Model\Product">Product</abbr></a>
<strong>getProduct</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Get the associated ChildProduct object</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional Connection object.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/Product.html"><abbr title="Thelia\Model\Product">Product</abbr></a></td>
<td>The associated ChildProduct object.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_initRelation">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_initRelation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1376</div>
<code> public void
<strong>initRelation</strong>(string $relationName)</code>
</h3>
<div class="details">
<p>Initializes a collection based on the name of a relation.</p>
<p>Avoids crafting an 'init[$relationName]s' method name
that wouldn't work when StandardEnglishPluralizer is used.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$relationName</td>
<td>The name of the relation to initialize</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_clearProductDocumentI18ns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_clearProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1392</div>
<code> public void
<strong>clearProductDocumentI18ns</strong>()</code>
</h3>
<div class="details">
<p>Clears out the collProductDocumentI18ns collection</p>
<p>This does not modify the database; however, it will remove any associated objects, causing
them to be refetched by subsequent calls to accessor method.</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>addProductDocumentI18ns()</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_resetPartialProductDocumentI18ns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_resetPartialProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1400</div>
<code> public
<strong>resetPartialProductDocumentI18ns</strong>($v = true)</code>
</h3>
<div class="details">
<p>Reset is the collProductDocumentI18ns collection loaded partially.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td></td>
<td>$v</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_initProductDocumentI18ns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_initProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1417</div>
<code> public void
<strong>initProductDocumentI18ns</strong>(boolean $overrideExisting = true)</code>
</h3>
<div class="details">
<p>Initializes the collProductDocumentI18ns collection.</p>
<p>By default this just sets the collProductDocumentI18ns collection to an empty array (like clearcollProductDocumentI18ns());
however, you may wish to override this method in your stub class to provide setting appropriate
to your application -- for example, setting the initial array to the values stored in database.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>boolean</td>
<td>$overrideExisting</td>
<td>If set to true, the method call initializes the collection even if it is not empty</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>void</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getProductDocumentI18ns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1440</div>
<code> public <abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>[]
<strong>getProductDocumentI18ns</strong>(<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Gets an array of ChildProductDocumentI18n objects which contain a foreign key that references this object.</p>
<p>If the $criteria is not null, it is used to always fetch the results from the database.
Otherwise the results are fetched from the database the first time, then cached.
Next time the same method is called without $criteria, the cached collection is returned.
If this ChildProductDocument is new, it will return
an empty collection or the current collection; the criteria is ignored on a new object.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td>optional Criteria object to narrow the query</td>
</tr>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Collection\Collection">Collection</abbr>|<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>[]</td>
<td>List of ChildProductDocumentI18n objects</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setProductDocumentI18ns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1496</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setProductDocumentI18ns</strong>(<abbr title="Propel\Runtime\Collection\Collection">Collection</abbr> $productDocumentI18ns, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Sets a collection of ProductDocumentI18n objects related by a one-to-many relationship to the current object.</p>
<p>It will also schedule objects for deletion based on a diff between old objects (aka persisted)
and new objects from the given Propel collection.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Collection\Collection">Collection</abbr></td>
<td>$productDocumentI18ns</td>
<td>A Propel collection.</td>
</tr>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>Optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_countProductDocumentI18ns">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_countProductDocumentI18ns"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1530</div>
<code> public int
<strong>countProductDocumentI18ns</strong>(<abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr> $criteria = null, boolean $distinct = false, <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Returns the number of related ProductDocumentI18n objects.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\ActiveQuery\Criteria">Criteria</abbr></td>
<td>$criteria</td>
<td>
</td>
</tr>
<tr>
<td>boolean</td>
<td>$distinct</td>
<td>
</td>
</tr>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>Count of related ProductDocumentI18n objects.</td>
</tr>
</table>
<h4>Exceptions</h4>
<table>
<tr>
<td><abbr title="PropelException">PropelException</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_addProductDocumentI18n">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_addProductDocumentI18n"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1562</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>addProductDocumentI18n</strong>(<a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a> $l)</code>
</h3>
<div class="details">
<p>Method called to associate a ChildProductDocumentI18n object to this object through the ChildProductDocumentI18n foreign key attribute.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>$l</td>
<td>ChildProductDocumentI18n</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_removeProductDocumentI18n">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_removeProductDocumentI18n"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1593</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>removeProductDocumentI18n</strong>(<a href="../../Thelia/Model/Base/ProductDocumentI18n.html"><abbr title="Thelia\Model\Base\ProductDocumentI18n">ProductDocumentI18n</abbr></a> $productDocumentI18n)</code>
</h3>
<div class="details">
<p>
</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/Base/ProductDocumentI18n.html"><abbr title="Thelia\Model\Base\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>$productDocumentI18n</td>
<td>The productDocumentI18n object to remove.</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_clear">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_clear"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1611</div>
<code> public
<strong>clear</strong>()</code>
</h3>
<div class="details">
<p>Clears the current object and sets all attributes to their default values</p>
<p>
</p>
<div class="tags">
</div>
</div>
<h3 id="method_clearAllReferences">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_clearAllReferences"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1635</div>
<code> public
<strong>clearAllReferences</strong>(boolean $deep = false)</code>
</h3>
<div class="details">
<p>Resets all references to other model objects or collections of model objects.</p>
<p>This method is a user-space workaround for PHP's inability to garbage collect
objects with circular references (even in PHP 5.3). This is currently necessary
when using Propel in certain daemon or large-volume/high-memory operations.</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>boolean</td>
<td>$deep</td>
<td>Whether to also clear the references on all referrer objects.</td>
</tr>
</table>
</div>
</div>
<h3 id="method___toString">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method___toString"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1661</div>
<code> public string
<strong>__toString</strong>()</code>
</h3>
<div class="details">
<p>Return the string representation of this object</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_keepUpdateDateUnchanged">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_keepUpdateDateUnchanged"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1673</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>keepUpdateDateUnchanged</strong>()</code>
</h3>
<div class="details">
<p>Mark the current object so that the update date doesn't get updated during next save</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setLocale">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setLocale"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1689</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>setLocale</strong>(string $locale = 'en_US')</code>
</h3>
<div class="details">
<p>Sets the locale for translations</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$locale</td>
<td>Locale to use for the translation, e.g. 'fr_FR'</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getLocale">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getLocale"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1701</div>
<code> public string
<strong>getLocale</strong>()</code>
</h3>
<div class="details">
<p>Gets the locale for translations</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>$locale Locale to use for the translation, e.g. 'fr_FR'</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getTranslation">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getTranslation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1713</div>
<code> public <a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
<strong>getTranslation</strong>(string $locale = 'en_US', <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Returns the current translation for a given locale</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$locale</td>
<td>Locale to use for the translation, e.g. 'fr_FR'</td>
</tr>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>an optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_removeTranslation">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_removeTranslation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1748</div>
<code> public <a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a>
<strong>removeTranslation</strong>(string $locale = 'en_US', <abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Remove the translation for a given locale</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$locale</td>
<td>Locale to use for the translation, e.g. 'fr_FR'</td>
</tr>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>an optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocument.html"><abbr title="Thelia\Model\ProductDocument">ProductDocument</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getCurrentTranslation">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getCurrentTranslation"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1774</div>
<code> public <a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
<strong>getCurrentTranslation</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Returns the current translation</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>an optional connection object</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getTitle">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getTitle"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1785</div>
<code> public string
<strong>getTitle</strong>()</code>
</h3>
<div class="details">
<p>Get the [title] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setTitle">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setTitle"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1797</div>
<code> public <a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
<strong>setTitle</strong>(string $v)</code>
</h3>
<div class="details">
<p>Set the value of [title] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getDescription">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getDescription"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1809</div>
<code> public string
<strong>getDescription</strong>()</code>
</h3>
<div class="details">
<p>Get the [description] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setDescription">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setDescription"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1821</div>
<code> public <a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
<strong>setDescription</strong>(string $v)</code>
</h3>
<div class="details">
<p>Set the value of [description] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getChapo">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getChapo"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1833</div>
<code> public string
<strong>getChapo</strong>()</code>
</h3>
<div class="details">
<p>Get the [chapo] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setChapo">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setChapo"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1845</div>
<code> public <a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
<strong>setChapo</strong>(string $v)</code>
</h3>
<div class="details">
<p>Set the value of [chapo] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getPostscriptum">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_getPostscriptum"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1857</div>
<code> public string
<strong>getPostscriptum</strong>()</code>
</h3>
<div class="details">
<p>Get the [postscriptum] column value.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setPostscriptum">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_setPostscriptum"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1869</div>
<code> public <a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a>
<strong>setPostscriptum</strong>(string $v)</code>
</h3>
<div class="details">
<p>Set the value of [postscriptum] column.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$v</td>
<td>new value</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../Thelia/Model/ProductDocumentI18n.html"><abbr title="Thelia\Model\ProductDocumentI18n">ProductDocumentI18n</abbr></a></td>
<td>The current object (for fluent API support)</td>
</tr>
</table>
</div>
</div>
<h3 id="method_preSave">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_preSave"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1880</div>
<code> public boolean
<strong>preSave</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run before persisting the object</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_postSave">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_postSave"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1889</div>
<code> public
<strong>postSave</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run after persisting the object</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_preInsert">
<div class="location">at line 23</div>
<code> public boolean
<strong>preInsert</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run before inserting to database</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_postInsert">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_postInsert"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1908</div>
<code> public
<strong>postInsert</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run after inserting to database</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_preUpdate">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_preUpdate"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1918</div>
<code> public boolean
<strong>preUpdate</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run before updating the object in database</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_postUpdate">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_postUpdate"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1927</div>
<code> public
<strong>postUpdate</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run after updating the object in database</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_preDelete">
<div class="location">at line 54</div>
<code> public boolean
<strong>preDelete</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run before deleting the object in database</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>boolean</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_postDelete">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method_postDelete"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1946</div>
<code> public
<strong>postDelete</strong>(<abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr> $con = null)</code>
</h3>
<div class="details">
<p>Code to be run after deleting the object in database</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Propel\Runtime\Connection\ConnectionInterface">ConnectionInterface</abbr></td>
<td>$con</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method___call">
<div class="location">in <a href="../../Thelia/Model/Base/ProductDocument.html#method___call"><abbr title="Thelia\Model\Base\ProductDocument">ProductDocument</abbr></a> at line 1963</div>
<code> public array|string
<strong>__call</strong>(string $name, mixed $params)</code>
</h3>
<div class="details">
<p>Derived method to catches calls to undefined methods.</p>
<p>Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.).
Allows to define default __call() behavior if you overwrite __call()</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$name</td>
<td>
</td>
</tr>
<tr>
<td>mixed</td>
<td>$params</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array|string</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_setParentId">
<div class="location">at line 37</div>
<code> public <abbr title="Thelia\Model\$this">$this</abbr>
<strong>setParentId</strong>(int $parentId)</code>
</h3>
<div class="details">
<p>Set Document parent id</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$parentId</td>
<td>parent id</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><abbr title="Thelia\Model\$this">$this</abbr></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getParentId">
<div class="location">at line 49</div>
<code> public int
<strong>getParentId</strong>()</code>
</h3>
<div class="details">
<p>Get Document parent id</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>int</td>
<td>parent id</td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>.
</div>
</body>
</html>
|
import * as moment from 'moment';
export const dateFormat = 'DD/MM/YYYY';
export const datePickerFormat = 'dd/mm/yy';
export const minDate = moment('1900-01-01').toDate();
|
/* Boost.MultiIndex test for iterators.
*
* Copyright 2003-2008 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/multi_index for library home page.
*/
#include <boost/test/included/test_exec_monitor.hpp>
#include "test_iterators.hpp"
int test_main(int,char *[])
{
test_iterators();
return 0;
}
|
// MiniPieFrame.h : interface of the CMiniPieFrame class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#define ID_TITLE 0 // Document title uses StatusBar pane 0
#define ID_BROWSER 1 // DispEvent ID
class CMiniPieFrame :
public CFrameWindowImpl<CMiniPieFrame>,
public CUpdateUI<CMiniPieFrame>,
public CAppWindow<CMiniPieFrame>,
public CFullScreenFrame<CMiniPieFrame>,
public CMessageFilter, public CIdleHandler,
public IDispEventImpl<ID_BROWSER, CMiniPieFrame>
{
public:
DECLARE_APP_FRAME_CLASS(NULL, IDR_MAINFRAME, L"Software\\WTL\\MiniPie")
// Data members
CAxWindow m_browser;
CComPtr<IWebBrowser2> m_spIWebBrowser2;
// Message filter
virtual BOOL PreTranslateMessage(MSG* pMsg);
// CAppWindow operations
bool AppNewInstance( LPCTSTR lpstrCmdLine);
void AppSave();
// Implementation
void UpdateLayout(BOOL bResizeBars = TRUE);
BOOL SetCommandButton(INT iID, bool bRight = false);
void Navigate(LPCTSTR sUrl);
// Idle handler and UI map
virtual BOOL OnIdle();
BEGIN_UPDATE_UI_MAP(CMiniPieFrame)
UPDATE_ELEMENT(ID_TITLE, UPDUI_STATUSBAR)
UPDATE_ELEMENT(ID_VIEW_FULLSCREEN, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_VIEW_STATUS_BAR, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(ID_VIEW_ADDRESSBAR, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(IDM_BACK, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(IDM_FORWARD, UPDUI_MENUPOPUP)
UPDATE_ELEMENT(IDM_STOP, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
UPDATE_ELEMENT(IDM_REFRESH, UPDUI_MENUPOPUP | UPDUI_TOOLBAR)
END_UPDATE_UI_MAP()
// Message map and handlers
BEGIN_MSG_MAP(CMiniPieFrame)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit)
COMMAND_ID_HANDLER(ID_VIEW_FULLSCREEN, OnFullScreen)
COMMAND_ID_HANDLER(ID_VIEW_STATUS_BAR, OnViewStatusBar)
#ifdef WIN32_PLATFORM_PSPC
COMMAND_ID_HANDLER(ID_VIEW_ADDRESSBAR, OnViewAddressBar)
#endif
COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
COMMAND_RANGE_HANDLER(IDM_FORWARD, IDM_STOP, OnBrowserCmd)
COMMAND_ID_HANDLER(IDM_OPENURL, OnOpenURL)
CHAIN_MSG_MAP(CAppWindow<CMiniPieFrame>)
CHAIN_MSG_MAP(CFullScreenFrame<CMiniPieFrame>)
CHAIN_MSG_MAP(CUpdateUI<CMiniPieFrame>)
CHAIN_MSG_MAP(CFrameWindowImpl<CMiniPieFrame>)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnFullScreen(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
#ifdef WIN32_PLATFORM_PSPC
LRESULT OnViewAddressBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
#endif
LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnBrowserCmd(WORD /*wNotifyCode*/, WORD wID/**/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnOpenURL(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
// IWebBrowser2 event map and handlers
BEGIN_SINK_MAP(CMiniPieFrame)
SINK_ENTRY(ID_BROWSER, DISPID_BEFORENAVIGATE2, OnBeforeNavigate2)
SINK_ENTRY(ID_BROWSER, DISPID_TITLECHANGE, OnBrowserTitleChange)
SINK_ENTRY(ID_BROWSER, DISPID_NAVIGATECOMPLETE2, OnNavigateComplete2)
SINK_ENTRY(ID_BROWSER, DISPID_DOCUMENTCOMPLETE, OnDocumentComplete)
SINK_ENTRY(ID_BROWSER, DISPID_COMMANDSTATECHANGE, OnCommandStateChange)
END_SINK_MAP()
private:
void __stdcall OnBeforeNavigate2(IDispatch* pDisp, VARIANT * pvtURL,
VARIANT * /*pvtFlags*/, VARIANT * pvtTargetFrameName,
VARIANT * /*pvtPostData*/, VARIANT * /*pvtHeaders*/,
VARIANT_BOOL * /*pvbCancel*/);
void __stdcall OnBrowserTitleChange(BSTR bstrTitleText);
void __stdcall OnNavigateComplete2(IDispatch* pDisp, VARIANT * pvtURL);
void __stdcall OnDocumentComplete(IDispatch* pDisp, VARIANT * pvtURL);
void __stdcall OnCommandStateChange(long lCommand, BOOL bEnable);
};
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# MicroPython documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 21 11:42:03 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
#master_doc = 'index'
# General information about the project.
project = 'MicroPython'
copyright = '2014, Damien P. George'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.4'
# The full version, including alpha/beta/rc tags.
release = '1.4.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.']
except:
html_theme = 'default'
html_theme_path = ['.']
else:
html_theme_path = ['.']
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = ['.']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = '../../logo/trans-logo.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%d %b %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {"index": "topindex.html"}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'MicroPythondoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'MicroPython.tex', 'MicroPython Documentation',
'Damien P. George', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'micropython', 'MicroPython Documentation',
['Damien P. George'], 1),
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'MicroPython', 'MicroPython Documentation',
'Damien P. George', 'MicroPython', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
# Work out the port to generate the docs for
from collections import OrderedDict
micropy_port = os.getenv('MICROPY_PORT') or 'pyboard'
tags.add('port_' + micropy_port)
ports = OrderedDict((
("unix", "unix"),
("pyboard", "the pyboard"),
("wipy", "the WiPy"),
("esp8266", "esp8266"),
))
# The members of the html_context dict are available inside topindex.html
url_prefix = os.getenv('MICROPY_URL_PREFIX') or '/'
html_context = {
'port':micropy_port,
'port_name':ports[micropy_port],
'all_ports':[(n, url_prefix + p) for p, n in ports.items()],
}
# Append the other ports' specific folders/files to the exclude pattern
exclude_patterns.extend([port + '*' for port in ports if port != micropy_port])
# Specify a custom master document based on the port name
master_doc = micropy_port + '_' + 'index'
|
<!DOCTYPE html>
<html>
<!--
Copyright 2010 The Closure Library Authors. All Rights Reserved.
Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
Author: nicksantos@google.com (Nick Santos)
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8" />
<title>JsUnit tests for goog.graphics.paths</title>
<script src="../base.js"></script>
</head>
<body>
<div id="root"></div>
<script type='text/javascript'>
goog.require('goog.graphics.pathsTest');
</script>
</body>
</html>
|
'use strict';
// There's an example D script here to showcase a "slow" handler where it's
// wildcard'd by the route name. In "real life" you'd probably start with a
// d script that breaks down the route -start and -done, and then you'd want
// to see which handler is taking longest from there.
//
// $ node demo.js
// $ curl localhost:9080/foo/bar
// $ sudo ./handler-timing.d
// ^C
//
// handler-6
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseAccept
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseAuthorization
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseDate
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseQueryString
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseUrlEncodedBody
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// sendResult
// value ------------- Distribution ------------- count
// 1 | 0
// 2 |@@@@ 1
// 4 | 0
// 8 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 16 | 0
//
// slowHandler
// value ------------- Distribution ------------- count
// 64 | 0
// 128 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 256 |@@@@ 1
// 512 | 0
//
// getfoo
// value ------------- Distribution ------------- count
// 64 | 0
// 128 |@@@@ 1
// 256 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 512 | 0
var restify = require('../../lib');
var Logger = require('bunyan');
///--- Globals
var NAME = 'exampleapp';
///--- Mainline
var log = new Logger({
name: NAME,
level: 'trace',
service: NAME,
serializers: restify.bunyan.serializers
});
var server = restify.createServer({
name: NAME,
Logger: log,
formatters: {
'application/foo': function (req, res, body, cb) {
if (body instanceof Error) {
body = body.stack;
} else if (Buffer.isBuffer(body)) {
body = body.toString('base64');
} else {
switch (typeof body) {
case 'boolean':
case 'number':
case 'string':
body = body.toString();
break;
case 'undefined':
body = '';
break;
default:
body = body === null ? '' :
'Demoing application/foo formatter; ' +
JSON.stringify(body);
break;
}
}
return cb(null, body);
}
}
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.urlEncodedBodyParser());
server.use(function slowHandler(req, res, next) {
setTimeout(function () {
next();
}, 250);
});
server.get({url: '/foo/:id', name: 'GetFoo'}, function (req, res, next) {
next();
}, function sendResult(req, res, next) {
res.contentType = 'application/foo';
res.send({
hello: req.params.id
});
next();
});
server.head('/foo/:id', function (req, res, next) {
res.send({
hello: req.params.id
});
next();
});
server.put('/foo/:id', function (req, res, next) {
res.send({
hello: req.params.id
});
next();
});
server.post('/foo/:id', function (req, res, next) {
res.json(201, req.params);
next();
});
server.del('/foo/:id', function (req, res, next) {
res.send(204);
next();
});
server.on('after', function (req, res, name) {
req.log.info('%s just finished: %d.', name, res.code);
});
server.on('NotFound', function (req, res) {
res.send(404, req.url + ' was not found');
});
server.listen(9080, function () {
log.info('listening: %s', server.url);
});
|
// Type definitions for parallel.js
// Project: https://github.com/parallel-js/parallel.js#readme
// Definitions by: Josh Baldwin <https://github.com/jbaldwin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/*
Copyright(c) 2013 Josh Baldwin https://github.com/jbaldwin/parallel.d.ts
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.
*/
interface ParallelOptions {
/**
* This is the path to the file eval.js. This is required when running in node, and required for some browsers (IE 10) in order to work around cross-domain restrictions for web workers. Defaults to the same location as parallel.js in node environments, and null in the browser.
**/
evalPath?: string | undefined;
/**
* The maximum number of permitted worker threads. This will default to 4, or the number of cpus on your computer if you're running node.
**/
maxWorkers?: number | undefined;
/**
* If webworkers are not available, whether or not to fall back to synchronous processing using setTimeout. Defaults to true.
**/
synchronous?: boolean | undefined;
}
declare class Parallel<T> {
/**
* This is the constructor. Use it to new up any parallel jobs. The constructor takes an array of data you want to operate on. This data will be held in memory until you finish your job, and can be accessed via the .data attribute of your job.
* The object returned by the Parallel constructor is meant to be chained, so you can produce a chain of operations on the provided data.
* @param data This is the data you wish to operate on. Will often be an array, but the only restrictions are that your values are serializable as JSON.
* @param opts Some options for your job.
**/
constructor(data: T, opts?: ParallelOptions);
/**
* Data
**/
public data: T;
/**
* This function will spawn a new process on a worker thread. Pass it the function you want to call. Your function will receive one argument, which is the current data. The value returned from your spawned function will update the current data.
* @param fn A function to execute on a worker thread. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data.
* @return Parallel instance.
**/
public spawn(fn: (data: T) => T): Parallel<T>;
/**
* Map will apply the supplied function to every element in the wrapped data. Parallel will spawn one worker for each array element in the data, or the supplied maxWorkers argument. The values returned will be stored for further processing.
* @param fn A function to apply. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data.
* @return Parallel instance.
**/
public map<N>(fn: (data: N) => N): Parallel<T>;
/**
* Reduce applies an operation to every member of the wrapped data, and returns a scalar value produced by the operation. Use it for combining the results of a map operation, by summing numbers for example. This takes a reducing function, which gets an argument, data, an array of the stored value, and the current element.
* @param fn A function to apply. Receives the stored value and current element as argument. The value returned will be stored as the current value for the next iteration. Finally, the current value will be assigned to current data.
* @return Parallel instance.
**/
public reduce<N>(fn: (data: N[]) => N): Parallel<T>;
/**
* The functions given to then are called after the last requested operation has finished. success receives the resulting data object, while fail will receive an error object.
* @param success A function that gets called upon successful completion. Receives the wrapped data as an argument.
* @param fail A function that gets called if the job fails. The function is passed an error object.
* @return Parallel instance.
**/
public then(success: (data: T) => void, fail?: (e: Error) => void): Parallel<T>;
/**
* If you have state that you want to share between your main thread and worker threads, this is how. Require takes either a string or a function. A string should point to a file name. NOte that in order to use require with a file name as an argument, you have to provide the evalPath property in the options object.
* @param state Shared state function or js file.
* @return Parallel instance.
**/
public require(file: string): Parallel<T>;
/**
* @see require
**/
public require(fn: Function): Parallel<T>;
}
/* commonjs binding for npm use */
declare module "paralleljs" {
export = Parallel;
}
|
//---------------------------------------------------------------------
// <copyright file="Perspective.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Diagnostics;
using System.Linq;
namespace System.Data.Metadata.Edm
{
using System.Collections.Generic;
/// <summary>
/// Internal helper class for query
/// </summary>
internal abstract class Perspective
{
#region Constructors
/// <summary>
/// Creates a new instance of perspective class so that query can work
/// ignorant of all spaces
/// </summary>
/// <param name="metadataWorkspace">runtime metadata container</param>
/// <param name="targetDataspace">target dataspace for the perspective</param>
internal Perspective(MetadataWorkspace metadataWorkspace,
DataSpace targetDataspace)
{
EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace");
m_metadataWorkspace = metadataWorkspace;
m_targetDataspace = targetDataspace;
}
#endregion
#region Fields
private MetadataWorkspace m_metadataWorkspace;
private DataSpace m_targetDataspace;
#endregion
#region Methods
/// <summary>
/// Given the type in the target space and the member name in the source space,
/// get the corresponding member in the target space
/// For e.g. consider a Conceptual Type 'Foo' with a member 'Bar' and a CLR type
/// 'XFoo' with a member 'YBar'. If one has a reference to Foo one can
/// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar
/// </summary>
/// <param name="type">The type in the target perspective</param>
/// <param name="memberName">the name of the member in the source perspective</param>
/// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param>
/// <param name="outMember">returns the member in target space, if a match is found</param>
internal virtual bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember)
{
EntityUtil.CheckArgumentNull(type, "type");
EntityUtil.CheckStringArgument(memberName, "memberName");
outMember = null;
return type.Members.TryGetValue(memberName, ignoreCase, out outMember);
}
internal bool TryGetEnumMember(EnumType type, String memberName, bool ignoreCase, out EnumMember outMember)
{
EntityUtil.CheckArgumentNull(type, "type");
EntityUtil.CheckStringArgument(memberName, "memberName");
outMember = null;
return type.Members.TryGetValue(memberName, ignoreCase, out outMember);
}
/// <summary>
/// Returns the extent in the target space, for the given entity container.
/// </summary>
/// <param name="entityContainer">name of the entity container in target space</param>
/// <param name="extentName">name of the extent</param>
/// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param>
/// <param name="outSet">extent in target space, if a match is found</param>
/// <returns>returns true, if a match is found otherwise returns false</returns>
internal bool TryGetExtent(EntityContainer entityContainer, String extentName, bool ignoreCase, out EntitySetBase outSet)
{
// There are no entity containers in the OSpace. So there is no mapping involved.
// Hence the name should be a valid name in the CSpace.
return entityContainer.BaseEntitySets.TryGetValue(extentName, ignoreCase, out outSet);
}
/// <summary>
/// Returns the function import in the target space, for the given entity container.
/// </summary>
internal bool TryGetFunctionImport(EntityContainer entityContainer, String functionImportName, bool ignoreCase, out EdmFunction functionImport)
{
// There are no entity containers in the OSpace. So there is no mapping involved.
// Hence the name should be a valid name in the CSpace.
functionImport = null;
if (ignoreCase)
{
functionImport = entityContainer.FunctionImports.Where(fi => String.Equals(fi.Name, functionImportName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
}
else
{
functionImport = entityContainer.FunctionImports.Where(fi => fi.Name == functionImportName).SingleOrDefault();
}
return functionImport != null;
}
/// <summary>
/// Get the default entity container
/// returns null for any perspective other
/// than the CLR perspective
/// </summary>
/// <returns>The default container</returns>
internal virtual EntityContainer GetDefaultContainer()
{
return null;
}
/// <summary>
/// Get an entity container based upon the strong name of the container
/// If no entity container is found, returns null, else returns the first one/// </summary>
/// <param name="name">name of the entity container</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="entityContainer">returns the entity container if a match is found</param>
/// <returns>returns true if a match is found, otherwise false</returns>
internal virtual bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer)
{
return MetadataWorkspace.TryGetEntityContainer(name, ignoreCase, TargetDataspace, out entityContainer);
}
/// <summary>
/// Gets a type with the given name in the target space.
/// </summary>
/// <param name="fullName">full name of the type</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="typeUsage">TypeUsage for the type</param>
/// <returns>returns true if a match was found, otherwise false</returns>
internal abstract bool TryGetTypeByName(string fullName, bool ignoreCase, out TypeUsage typeUsage);
/// <summary>
/// Returns overloads of a function with the given name in the target space.
/// </summary>
/// <param name="namespaceName">namespace of the function</param>
/// <param name="functionName">name of the function</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="functionOverloads">function overloads</param>
/// <returns>returns true if a match was found, otherwise false</returns>
internal bool TryGetFunctionByName(string namespaceName, string functionName, bool ignoreCase, out IList<EdmFunction> functionOverloads)
{
EntityUtil.CheckStringArgument(namespaceName, "namespaceName");
EntityUtil.CheckStringArgument(functionName, "functionName");
var fullName = namespaceName + "." + functionName;
// First look for a model-defined function in the target space.
ItemCollection itemCollection = m_metadataWorkspace.GetItemCollection(m_targetDataspace);
IList<EdmFunction> overloads =
m_targetDataspace == DataSpace.SSpace ?
((StoreItemCollection)itemCollection).GetCTypeFunctions(fullName, ignoreCase) :
itemCollection.GetFunctions(fullName, ignoreCase);
if (m_targetDataspace == DataSpace.CSpace)
{
// Then look for a function import.
if (overloads == null || overloads.Count == 0)
{
EntityContainer entityContainer;
if (this.TryGetEntityContainer(namespaceName, /*ignoreCase:*/ false, out entityContainer))
{
EdmFunction functionImport;
if (this.TryGetFunctionImport(entityContainer, functionName, /*ignoreCase:*/ false, out functionImport))
{
overloads = new EdmFunction[] { functionImport };
}
}
}
// Last, look in SSpace.
if (overloads == null || overloads.Count == 0)
{
ItemCollection storeItemCollection;
if (m_metadataWorkspace.TryGetItemCollection(DataSpace.SSpace, out storeItemCollection))
{
overloads = ((StoreItemCollection)storeItemCollection).GetCTypeFunctions(fullName, ignoreCase);
}
}
}
functionOverloads = (overloads != null && overloads.Count > 0) ? overloads : null;
return functionOverloads != null;
}
/// <summary>
/// Return the metadata workspace
/// </summary>
internal MetadataWorkspace MetadataWorkspace
{
get
{
return m_metadataWorkspace;
}
}
/// <summary>
/// returns the primitive type for a given primitive type kind.
/// </summary>
/// <param name="primitiveTypeKind"></param>
/// <param name="primitiveType"></param>
/// <returns></returns>
internal virtual bool TryGetMappedPrimitiveType(PrimitiveTypeKind primitiveTypeKind, out PrimitiveType primitiveType)
{
primitiveType = m_metadataWorkspace.GetMappedPrimitiveType(primitiveTypeKind, DataSpace.CSpace);
return (null != primitiveType);
}
//
// This property will be needed to construct keys for transient types
//
/// <summary>
/// Returns the target dataspace for this perspective
/// </summary>
internal DataSpace TargetDataspace
{
get
{
return m_targetDataspace;
}
}
#endregion
}
}
|
<div id="modelsBuilder" ng-controller="Umbraco.Dashboard.ModelsBuilderManagementController as vm">
<umb-box>
<umb-box-content>
<div ng-show="!vm.loading" class="pull-right">
<button type="button" class="btn" ng-click="vm.reload()"><span>Reload</span></button>
</div>
<h3 class="bold">Models Builder</h3>
<umb-load-indicator ng-show="vm.loading"></umb-load-indicator>
<div ng-show="!vm.loading && vm.dashboard">
<div ng-bind-html="vm.dashboard.text"></div>
<div ng-if="vm.dashboard.outOfDateModels">
<p>Models are <strong>out-of-date</strong>.</p>
</div>
<div ng-if="vm.dashboard.canGenerate">
<div ng-if="vm.dashboard.generateCausesRestart">
<p style="color: red; font-weight: bold;">Generating models will restart the application.</p>
</div>
<div ng-show="!vm.generating">
<button type="button" ng-click="vm.generate()" class="btn btn-danger">
<span>Generate models</span>
</button>
</div>
<div class="umb-loader-wrapper" ng-show="vm.generating">
<div class="umb-loader"></div>
</div>
</div>
<div ng-if="vm.dashboard.lastError" style="margin-top: 32px;" ng-show="!vm.generating">
<span style="color: red; font-weight: bold;">Last generation failed with the following error:</span>
<pre style="width: 80%; white-space: pre-line; background: #f8f8f8; padding: 4px; font-size: small;">{{vm.dashboard.lastError}}</pre>
</div>
</div>
</umb-box-content>
</umb-box>
</div>
|
/**
* 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.powermax.internal;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
/**
* The {@link PowermaxBinding} class defines common constants, which are
* used across the whole binding.
*
* @author Laurent Garnier - Initial contribution
*/
public class PowermaxBindingConstants {
public static final String BINDING_ID = "powermax";
// List of all Thing Type UIDs
public static final ThingTypeUID BRIDGE_TYPE_SERIAL = new ThingTypeUID(BINDING_ID, "serial");
public static final ThingTypeUID BRIDGE_TYPE_IP = new ThingTypeUID(BINDING_ID, "ip");
public static final ThingTypeUID THING_TYPE_ZONE = new ThingTypeUID(BINDING_ID, "zone");
public static final ThingTypeUID THING_TYPE_X10 = new ThingTypeUID(BINDING_ID, "x10");
// All supported Bridge types
public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Collections
.unmodifiableSet(Stream.of(BRIDGE_TYPE_SERIAL, BRIDGE_TYPE_IP).collect(Collectors.toSet()));
// All supported Thing types
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
.unmodifiableSet(Stream.of(THING_TYPE_ZONE, THING_TYPE_X10).collect(Collectors.toSet()));
// List of all Channel ids
public static final String MODE = "mode";
public static final String TROUBLE = "trouble";
public static final String ALERT_IN_MEMORY = "alert_in_memory";
public static final String SYSTEM_STATUS = "system_status";
public static final String READY = "ready";
public static final String WITH_ZONES_BYPASSED = "with_zones_bypassed";
public static final String ALARM_ACTIVE = "alarm_active";
public static final String SYSTEM_ARMED = "system_armed";
public static final String ARM_MODE = "arm_mode";
public static final String TRIPPED = "tripped";
public static final String LAST_TRIP = "last_trip";
public static final String BYPASSED = "bypassed";
public static final String ARMED = "armed";
public static final String LOW_BATTERY = "low_battery";
public static final String PGM_STATUS = "pgm_status";
public static final String X10_STATUS = "x10_status";
public static final String EVENT_LOG = "event_log_%s";
public static final String UPDATE_EVENT_LOGS = "update_event_logs";
public static final String DOWNLOAD_SETUP = "download_setup";
}
|
/**
* 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.lifx.internal.protocol;
import java.nio.ByteBuffer;
import org.openhab.binding.lifx.internal.fields.Field;
import org.openhab.binding.lifx.internal.fields.UInt16Field;
import org.openhab.binding.lifx.internal.fields.UInt32Field;
/**
* @author Tim Buckley - Initial Contribution
* @author Karel Goderis - Enhancement for the V2 LIFX Firmware and LAN Protocol Specification
*/
public class SetDimAbsoluteRequest extends Packet {
public static final int TYPE = 0x68;
public static final Field<Integer> FIELD_DIM = new UInt16Field().little();
public static final Field<Long> FIELD_DURATION = new UInt32Field().little();
private int dim;
private long duration;
public int getDim() {
return dim;
}
public long getDuration() {
return duration;
}
public SetDimAbsoluteRequest() {
}
public SetDimAbsoluteRequest(int dim, long duration) {
this.dim = dim;
this.duration = duration;
}
@Override
public int packetType() {
return TYPE;
}
@Override
protected int packetLength() {
return 6;
}
@Override
protected void parsePacket(ByteBuffer bytes) {
dim = FIELD_DIM.value(bytes);
duration = FIELD_DURATION.value(bytes);
}
@Override
protected ByteBuffer packetBytes() {
return ByteBuffer.allocate(packetLength()).put(FIELD_DIM.bytes(dim)).put(FIELD_DURATION.bytes(duration));
}
@Override
public int[] expectedResponses() {
return new int[] {};
}
}
|
/***************************************************************************
qgsattributeformeditorwidget.cpp
-------------------------------
Date : March 2016
Copyright : (C) 2016 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. *
* *
***************************************************************************/
#include "qgsattributeformeditorwidget.h"
#include "qgsattributeform.h"
#include "qgsmultiedittoolbutton.h"
#include "qgssearchwidgettoolbutton.h"
#include "qgseditorwidgetwrapper.h"
#include "qgssearchwidgetwrapper.h"
#include "qgsattributeeditorcontext.h"
#include "qgseditorwidgetregistry.h"
#include "qgsaggregatetoolbutton.h"
#include "qgsgui.h"
#include "qgsvectorlayerjoinbuffer.h"
#include "qgsvectorlayerutils.h"
#include <QLayout>
#include <QLabel>
#include <QStackedWidget>
QgsAttributeFormEditorWidget::QgsAttributeFormEditorWidget( QgsEditorWidgetWrapper *editorWidget, const QString &widgetType, QgsAttributeForm *form )
: QgsAttributeFormWidget( editorWidget, form )
, mWidgetType( widgetType )
, mEditorWidget( editorWidget )
, mForm( form )
, mMultiEditButton( new QgsMultiEditToolButton() )
, mBlockValueUpdate( false )
, mIsMixed( false )
, mIsChanged( false )
{
mConstraintResultLabel = new QLabel( this );
mConstraintResultLabel->setObjectName( QStringLiteral( "ConstraintStatus" ) );
mConstraintResultLabel->setSizePolicy( QSizePolicy::Fixed, mConstraintResultLabel->sizePolicy().verticalPolicy() );
mMultiEditButton->setField( mEditorWidget->field() );
mAggregateButton = new QgsAggregateToolButton();
mAggregateButton->setType( editorWidget->field().type() );
connect( mAggregateButton, &QgsAggregateToolButton::aggregateChanged, this, &QgsAttributeFormEditorWidget::onAggregateChanged );
if ( mEditorWidget->widget() )
{
mEditorWidget->widget()->setObjectName( mEditorWidget->field().name() );
}
connect( mEditorWidget, &QgsEditorWidgetWrapper::valuesChanged, this, &QgsAttributeFormEditorWidget::editorWidgetValuesChanged );
connect( mMultiEditButton, &QgsMultiEditToolButton::resetFieldValueTriggered, this, &QgsAttributeFormEditorWidget::resetValue );
connect( mMultiEditButton, &QgsMultiEditToolButton::setFieldValueTriggered, this, &QgsAttributeFormEditorWidget::setFieldTriggered );
mMultiEditButton->setField( mEditorWidget->field() );
updateWidgets();
}
QgsAttributeFormEditorWidget::~QgsAttributeFormEditorWidget()
{
//there's a chance these widgets are not currently added to the layout, so have no parent set
delete mMultiEditButton;
}
void QgsAttributeFormEditorWidget::createSearchWidgetWrappers( const QgsAttributeEditorContext &context )
{
Q_ASSERT( !mWidgetType.isEmpty() );
const QVariantMap config = mEditorWidget->config();
const int fieldIdx = mEditorWidget->fieldIdx();
QgsSearchWidgetWrapper *sww = QgsGui::editorWidgetRegistry()->createSearchWidget( mWidgetType, layer(), fieldIdx, config,
searchWidgetFrame(), context );
setSearchWidgetWrapper( sww );
searchWidgetFrame()->layout()->addWidget( mAggregateButton );
if ( sww->supportedFlags() & QgsSearchWidgetWrapper::Between ||
sww->supportedFlags() & QgsSearchWidgetWrapper::IsNotBetween )
{
// create secondary widget for between type searches
QgsSearchWidgetWrapper *sww2 = QgsGui::editorWidgetRegistry()->createSearchWidget( mWidgetType, layer(), fieldIdx, config,
searchWidgetFrame(), context );
addAdditionalSearchWidgetWrapper( sww2 );
}
}
void QgsAttributeFormEditorWidget::setConstraintStatus( const QString &constraint, const QString &description, const QString &err, QgsEditorWidgetWrapper::ConstraintResult result )
{
switch ( result )
{
case QgsEditorWidgetWrapper::ConstraintResultFailHard:
mConstraintResultLabel->setText( QStringLiteral( "<font color=\"#FF9800\">%1</font>" ).arg( QChar( 0x2718 ) ) );
mConstraintResultLabel->setToolTip( description.isEmpty() ? QStringLiteral( "<b>%1</b>: %2" ).arg( constraint, err ) : description );
break;
case QgsEditorWidgetWrapper::ConstraintResultFailSoft:
mConstraintResultLabel->setText( QStringLiteral( "<font color=\"#FFC107\">%1</font>" ).arg( QChar( 0x2718 ) ) );
mConstraintResultLabel->setToolTip( description.isEmpty() ? QStringLiteral( "<b>%1</b>: %2" ).arg( constraint, err ) : description );
break;
case QgsEditorWidgetWrapper::ConstraintResultPass:
mConstraintResultLabel->setText( QStringLiteral( "<font color=\"#259B24\">%1</font>" ).arg( QChar( 0x2714 ) ) );
mConstraintResultLabel->setToolTip( description );
break;
}
}
void QgsAttributeFormEditorWidget::setConstraintResultVisible( bool editable )
{
mConstraintResultLabel->setHidden( !editable );
}
QgsEditorWidgetWrapper *QgsAttributeFormEditorWidget::editorWidget() const
{
return mEditorWidget;
}
void QgsAttributeFormEditorWidget::setIsMixed( bool mixed )
{
if ( mEditorWidget && mixed )
mEditorWidget->showIndeterminateState();
mMultiEditButton->setIsMixed( mixed );
mIsMixed = mixed;
}
void QgsAttributeFormEditorWidget::changesCommitted()
{
if ( mEditorWidget )
{
mPreviousValue = mEditorWidget->value();
mPreviousAdditionalValues = mEditorWidget->additionalFieldValues();
}
setIsMixed( false );
mMultiEditButton->changesCommitted();
mIsChanged = false;
}
void QgsAttributeFormEditorWidget::initialize( const QVariant &initialValue, bool mixedValues, const QVariantList &additionalFieldValues )
{
if ( mEditorWidget )
{
mBlockValueUpdate = true;
mEditorWidget->setValues( initialValue, additionalFieldValues );
mBlockValueUpdate = false;
}
mPreviousValue = initialValue;
mPreviousAdditionalValues = additionalFieldValues;
setIsMixed( mixedValues );
mMultiEditButton->setIsChanged( false );
mIsChanged = false;
updateWidgets();
}
QVariant QgsAttributeFormEditorWidget::currentValue() const
{
return mEditorWidget->value();
}
void QgsAttributeFormEditorWidget::editorWidgetValuesChanged( const QVariant &value, const QVariantList &additionalFieldValues )
{
if ( mBlockValueUpdate )
return;
mIsChanged = true;
switch ( mode() )
{
case DefaultMode:
case SearchMode:
case AggregateSearchMode:
break;
case MultiEditMode:
mMultiEditButton->setIsChanged( true );
}
Q_NOWARN_DEPRECATED_PUSH
emit valueChanged( value );
Q_NOWARN_DEPRECATED_POP
emit valuesChanged( value, additionalFieldValues );
}
void QgsAttributeFormEditorWidget::resetValue()
{
mIsChanged = false;
mBlockValueUpdate = true;
if ( mEditorWidget )
mEditorWidget->setValues( mPreviousValue, mPreviousAdditionalValues );
mBlockValueUpdate = false;
switch ( mode() )
{
case DefaultMode:
case SearchMode:
case AggregateSearchMode:
break;
case MultiEditMode:
{
mMultiEditButton->setIsChanged( false );
if ( mEditorWidget && mIsMixed )
mEditorWidget->showIndeterminateState();
break;
}
}
}
void QgsAttributeFormEditorWidget::setFieldTriggered()
{
mIsChanged = true;
}
void QgsAttributeFormEditorWidget::onAggregateChanged()
{
for ( QgsSearchWidgetWrapper *searchWidget : searchWidgetWrappers() )
searchWidget->setAggregate( mAggregateButton->aggregate() );
}
void QgsAttributeFormEditorWidget::updateWidgets()
{
//first update the tool buttons
bool hasMultiEditButton = ( editPage()->layout()->indexOf( mMultiEditButton ) >= 0 );
const int fieldIndex = mEditorWidget->fieldIdx();
bool fieldReadOnly = false;
QgsFeature feature;
auto it = layer()->getSelectedFeatures();
while ( it.nextFeature( feature ) )
{
fieldReadOnly |= !QgsVectorLayerUtils::fieldIsEditable( layer(), fieldIndex, feature );
}
if ( hasMultiEditButton )
{
if ( mode() != MultiEditMode || fieldReadOnly )
{
editPage()->layout()->removeWidget( mMultiEditButton );
mMultiEditButton->setParent( nullptr );
}
}
else
{
if ( mode() == MultiEditMode && !fieldReadOnly )
{
editPage()->layout()->addWidget( mMultiEditButton );
}
}
switch ( mode() )
{
case DefaultMode:
case MultiEditMode:
{
stack()->setCurrentWidget( editPage() );
editPage()->layout()->addWidget( mConstraintResultLabel );
break;
}
case AggregateSearchMode:
{
mAggregateButton->setVisible( true );
stack()->setCurrentWidget( searchPage() );
break;
}
case SearchMode:
{
mAggregateButton->setVisible( false );
stack()->setCurrentWidget( searchPage() );
break;
}
}
}
|
/*
* File : dc.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2006 - 2009, RT-Thread Development Team
*
* The license and distribution terms for this file may be
* found in the file LICENSE in this distribution or at
* http://www.rt-thread.org/license/LICENSE
*
* Change Logs:
* Date Author Notes
* 2009-10-16 Bernard first version
* 2010-09-20 richard modified rtgui_dc_draw_round_rect
* 2010-09-27 Bernard fix draw_mono_bmp issue
* 2011-04-25 Bernard fix fill polygon issue, which found by loveic
*/
#include <rtgui/dc.h>
#include <rtgui/rtgui_system.h>
#include <string.h> /* for strlen */
#include <stdlib.h> /* fir qsort */
/* for sin/cos etc */
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static int _int_compare(const void *a, const void *b)
{
return (*(const int *) a) - (*(const int *) b);
}
void rtgui_dc_destory(struct rtgui_dc* dc)
{
if (dc == RT_NULL) return;
dc->engine->fini(dc);
rtgui_free(dc);
}
RTM_EXPORT(rtgui_dc_destory);
void rtgui_dc_draw_line (struct rtgui_dc* dc, int x1, int y1, int x2, int y2)
{
if (dc == RT_NULL) return;
if (y1 == y2)
{
rtgui_dc_draw_hline(dc, x1, x2, y1);
}
else if (x1 == x2)
{
rtgui_dc_draw_vline(dc, x1, y1, y2);
}
else
{
int dx, dy, sdx, sdy, dxabs, dyabs, x, y, px, py;
register rt_base_t i;
/* rtgui_rect_t rect; */
dx = x2 - x1; /* the horizontal distance of the line */
dy = y2 - y1; /* the vertical distance of the line */
#define rtgui_sgn(x) ((x<0)?-1:((x>0)?1:0)) /* macro to return the sign of a number */
#define rtgui_abs(x) ((x)>=0? (x):-(x)) /* macro to return the absolute value */
dxabs = rtgui_abs(dx);
dyabs = rtgui_abs(dy);
sdx = rtgui_sgn(dx);
sdy = rtgui_sgn(dy);
x = dyabs >> 1;
y = dxabs >> 1;
px = x1;
py = y1;
if(dxabs >= dyabs) /* the line is more horizontal than vertical */
{
for(i = 0; i < dxabs; i++)
{
y += dyabs;
if(y >= dxabs)
{
y -= dxabs;
py += sdy;
}
px += sdx;
/* draw this point */
rtgui_dc_draw_point(dc, px, py);
}
}
else /* the line is more vertical than horizontal */
{
for(i = 0; i < dyabs; i++)
{
x += dxabs;
if(x >= dyabs)
{
x -= dyabs;
px += sdx;
}
py += sdy;
/* draw this point */
rtgui_dc_draw_point(dc, px, py);
}
}
}
}
RTM_EXPORT(rtgui_dc_draw_line);
void rtgui_dc_draw_horizontal_line(struct rtgui_dc* dc, int x1, int x2, int y)
{
rtgui_color_t color;
if (dc == RT_NULL) return ;
/* save old color */
color = RTGUI_DC_FC(dc);
RTGUI_DC_FC(dc) = dark_grey;
rtgui_dc_draw_hline(dc, x1, x2, y);
y ++;
RTGUI_DC_FC(dc) = high_light;
rtgui_dc_draw_hline(dc, x1, x2, y);
/* restore color */
RTGUI_DC_FC(dc) = color;
}
RTM_EXPORT(rtgui_dc_draw_horizontal_line);
void rtgui_dc_draw_vertical_line(struct rtgui_dc* dc, int x, int y1, int y2)
{
rtgui_color_t color;
if (dc == RT_NULL) return ;
/* save old color */
color = RTGUI_DC_FC(dc);
RTGUI_DC_FC(dc) = dark_grey;
rtgui_dc_draw_vline(dc, x, y1, y2);
x ++;
RTGUI_DC_FC(dc) = high_light;
rtgui_dc_draw_vline(dc, x, y1, y2);
/* restore color */
RTGUI_DC_FC(dc) = color;
}
RTM_EXPORT(rtgui_dc_draw_vertical_line);
void rtgui_dc_draw_rect (struct rtgui_dc* dc, struct rtgui_rect* rect)
{
rtgui_dc_draw_hline(dc, rect->x1, rect->x2, rect->y1);
rtgui_dc_draw_hline(dc, rect->x1, rect->x2, rect->y2 - 1);
rtgui_dc_draw_vline(dc, rect->x1, rect->y1, rect->y2);
rtgui_dc_draw_vline(dc, rect->x2 - 1, rect->y1, rect->y2);
}
RTM_EXPORT(rtgui_dc_draw_rect);
void rtgui_dc_fill_rect_forecolor(struct rtgui_dc* dc, struct rtgui_rect* rect)
{
int i = 0;
rtgui_dc_draw_rect(dc, rect);
do
{
rtgui_dc_draw_hline(dc, rect->x1+1, rect->x2-1, rect->y1+i);
i++;
}while(!(rect->y1+i == rect->y2));
}
RTM_EXPORT(rtgui_dc_fill_rect_forecolor);
void rtgui_dc_draw_round_rect(struct rtgui_dc* dc, struct rtgui_rect* rect, int r)
{
RT_ASSERT(((rect->x2 - rect->x1)/2 >= r)&&((rect->y2-rect->y1)/2 >= r));
if(r < 0)
{
return;
}
if(r == 0)
{
rtgui_dc_draw_rect(dc, rect);
return;
}
if(((rect->x2 - rect->x1)/2 >= r)&&((rect->y2-rect->y1)/2 >= r))
{
rtgui_dc_draw_arc(dc, rect->x1 + r, rect->y1 + r, r, 180, 270);
rtgui_dc_draw_arc(dc, rect->x2 - r, rect->y1 + r, r, 270, 360);
rtgui_dc_draw_arc(dc, rect->x1 + r, rect->y2 - r, r, 90, 180);
rtgui_dc_draw_arc(dc, rect->x2 - r, rect->y2 - r, r, 0, 90);
rtgui_dc_draw_hline(dc, rect->x1 + r, rect->x2 - r, rect->y1);
rtgui_dc_draw_hline(dc, rect->x1 + r, rect->x2 - r, rect->y2);
rtgui_dc_draw_vline(dc, rect->x1, rect->y1 + r, rect->y2 - r);
rtgui_dc_draw_vline(dc, rect->x2, rect->y1 + r, rect->y2 - r);
}
}
RTM_EXPORT(rtgui_dc_draw_round_rect);
void rtgui_dc_fill_round_rect(struct rtgui_dc* dc, struct rtgui_rect* rect, int r)
{
struct rtgui_rect rect_temp;
RT_ASSERT(((rect->x2 - rect->x1)/2 >= r)&&((rect->y2-rect->y1)/2 >= r));
if(((rect->x2 - rect->x1)/2 >= r)&&((rect->y2-rect->y1)/2 >= r))
{
rect_temp.x1 = rect->x1 + r;
rect_temp.y1 = rect->y1;
rect_temp.x2 = rect->x2 - r;
rect_temp.y2 = rect->y2;
rtgui_dc_fill_rect_forecolor(dc, &rect_temp);//fill rect with foreground
rect_temp.x1 = rect->x1;
rect_temp.y1 = rect->y1 + r;
rect_temp.x2 = rect->x1 + r;
rect_temp.y2 = rect->y2 - r;
rtgui_dc_fill_rect_forecolor(dc, &rect_temp);//fill rect with foreground
rect_temp.x1 = rect->x2 - r;
rect_temp.y1 = rect->y1 + r;
rect_temp.x2 = rect->x2;
rect_temp.y2 = rect->y2 - r;
rtgui_dc_fill_rect_forecolor(dc, &rect_temp);//fill rect with foreground
rtgui_dc_fill_circle(dc, rect->x1 + r, rect->y1 + r, r);
rtgui_dc_fill_circle(dc, rect->x2 - r, rect->y2 - r, r);
rtgui_dc_fill_circle(dc, rect->x2 - r, rect->y1 + r, r);
rtgui_dc_fill_circle(dc, rect->x1 + r, rect->y2 - r, r);
}
}
RTM_EXPORT(rtgui_dc_fill_round_rect);
void rtgui_dc_draw_shaded_rect(struct rtgui_dc* dc, rtgui_rect_t* rect,
rtgui_color_t c1, rtgui_color_t c2)
{
RT_ASSERT(dc != RT_NULL);
RTGUI_DC_FC(dc) = c1;
rtgui_dc_draw_vline(dc, rect->x1, rect->y1, rect->y2);
rtgui_dc_draw_hline(dc, rect->x1 + 1, rect->x2, rect->y1);
RTGUI_DC_FC(dc) = c2;
rtgui_dc_draw_vline(dc, rect->x2 - 1, rect->y1, rect->y2);
rtgui_dc_draw_hline(dc, rect->x1, rect->x2, rect->y2 - 1);
}
RTM_EXPORT(rtgui_dc_draw_shaded_rect);
void rtgui_dc_draw_focus_rect(struct rtgui_dc* dc, rtgui_rect_t* rect)
{
int x,y;
for (x=rect->x1; x<rect->x2-1; x++)
{
if ((x+rect->y1)&0x01)
rtgui_dc_draw_point(dc, x, rect->y1);
if ((x+rect->y2-1)&0x01)
rtgui_dc_draw_point(dc, x, rect->y2-1);
}
for (y=rect->y1; y<rect->y2; y++)
{
if ((rect->x1+y)&0x01)
rtgui_dc_draw_point(dc, rect->x1, y);
if ((rect->x2-1+y)&0x01)
rtgui_dc_draw_point(dc, rect->x2-1, y);
}
}
RTM_EXPORT(rtgui_dc_draw_focus_rect);
void rtgui_dc_draw_text (struct rtgui_dc* dc, const char* text, struct rtgui_rect* rect)
{
rt_uint32_t len;
struct rtgui_font *font;
struct rtgui_rect text_rect;
RT_ASSERT(dc != RT_NULL);
font = RTGUI_DC_FONT(dc);
if (font == RT_NULL)
{
/* use system default font */
font = rtgui_font_default();
}
/* text align */
rtgui_font_get_metrics(font, text, &text_rect);
rtgui_rect_moveto_align(rect, &text_rect, RTGUI_DC_TEXTALIGN(dc));
len = strlen((const char*)text);
rtgui_font_draw(font, dc, text, len, &text_rect);
}
RTM_EXPORT(rtgui_dc_draw_text);
void rtgui_dc_draw_text_stroke (struct rtgui_dc* dc, const char* text, struct rtgui_rect* rect,
rtgui_color_t color_stroke, rtgui_color_t color_core)
{
int x, y;
rtgui_rect_t r;
rtgui_color_t fc;
RT_ASSERT(dc != RT_NULL);
fc = RTGUI_DC_FC(dc);
RTGUI_DC_FC(dc) = color_stroke;
for(x=-1; x<2; x++)
{
for(y=-1; y<2; y++)
{
r = *rect;
rtgui_rect_moveto(&r, x, y);
rtgui_dc_draw_text(dc, text, &r);
}
}
RTGUI_DC_FC(dc) = color_core;
rtgui_dc_draw_text(dc, text, rect);
RTGUI_DC_FC(dc) = fc;
}
RTM_EXPORT(rtgui_dc_draw_text_stroke);
/*
* draw a monochrome color bitmap data
*/
void rtgui_dc_draw_mono_bmp(struct rtgui_dc* dc, int x, int y, int w, int h, const rt_uint8_t* data)
{
int i, j, k;
/* get word bytes */
w = (w + 7)/8;
/* draw mono bitmap data */
for (i = 0; i < h; i ++)
for (j = 0; j < w; j++)
for (k = 0; k < 8; k++)
if ( ((data[i*w + j] >> (7-k)) & 0x01) != 0)
rtgui_dc_draw_point(dc, x + 8*j + k, y + i);
}
RTM_EXPORT(rtgui_dc_draw_mono_bmp);
void rtgui_dc_draw_byte(struct rtgui_dc*dc, int x, int y, int h, const rt_uint8_t* data)
{
rtgui_dc_draw_mono_bmp(dc, x, y, 8, h, data);
}
RTM_EXPORT(rtgui_dc_draw_byte);
void rtgui_dc_draw_word(struct rtgui_dc*dc, int x, int y, int h, const rt_uint8_t* data)
{
rtgui_dc_draw_mono_bmp(dc, x, y, 16, h, data);
}
RTM_EXPORT(rtgui_dc_draw_word);
void rtgui_dc_draw_border(struct rtgui_dc* dc, rtgui_rect_t* rect, int flag)
{
rtgui_rect_t r;
rtgui_color_t color;
if (dc == RT_NULL) return ;
/* save old color */
color = RTGUI_DC_FC(dc);
r = *rect;
switch (flag)
{
case RTGUI_BORDER_RAISE:
rtgui_dc_draw_shaded_rect(dc, &r, high_light, black);
rtgui_rect_inflate(&r, -1);
rtgui_dc_draw_shaded_rect(dc, &r, light_grey, dark_grey);
break;
case RTGUI_BORDER_SUNKEN:
rtgui_dc_draw_shaded_rect(dc, &r, dark_grey, high_light);
rtgui_rect_inflate(&r, -1);
rtgui_dc_draw_shaded_rect(dc, &r, black, light_grey);
break;
case RTGUI_BORDER_BOX:
rtgui_dc_draw_shaded_rect(dc, &r, dark_grey, high_light);
rtgui_rect_inflate(&r, -1);
rtgui_dc_draw_shaded_rect(dc, &r, high_light, dark_grey);
break;
case RTGUI_BORDER_STATIC:
rtgui_dc_draw_shaded_rect(dc, &r, dark_grey, high_light);
break;
case RTGUI_BORDER_EXTRA:
RTGUI_DC_FC(dc) = light_grey;
rtgui_dc_draw_rect(dc, &r);
break;
case RTGUI_BORDER_SIMPLE:
RTGUI_DC_FC(dc) = black;
rtgui_dc_draw_rect(dc, &r);
break;
default:
break;
}
/* restore color */
RTGUI_DC_FC(dc) = color;
}
RTM_EXPORT(rtgui_dc_draw_border);
void rtgui_dc_draw_polygon(struct rtgui_dc* dc, const int *vx, const int *vy, int count)
{
int i;
const int *x1, *y1, *x2, *y2;
/*
* Sanity check
*/
if (count < 3) return;
/*
* Pointer setup
*/
x1 = x2 = vx;
y1 = y2 = vy;
x2++;
y2++;
/*
* Draw
*/
for (i = 1; i < count; i++)
{
rtgui_dc_draw_line(dc, *x1, *y1, *x2, *y2);
x1 = x2;
y1 = y2;
x2++;
y2++;
}
rtgui_dc_draw_line(dc, *x1, *y1, *vx, *vy);
}
RTM_EXPORT(rtgui_dc_draw_polygon);
void rtgui_dc_draw_regular_polygon(struct rtgui_dc* dc, int x, int y, int r, int count, rt_uint16_t angle)
{
int i, temp_val;
double temp;
float angle_interval;
int *xx;
int *x_head;
int *yy;
int *y_head;
/*
* Sanity check
*/
if (count < 3) return;
angle_interval = 360.0 / count;
/*
* Pointer setup
*/
x_head = xx = (int *)rtgui_malloc(sizeof(int) * count);
y_head = yy = (int *)rtgui_malloc(sizeof(int) * count);
for(i = 0; i < count; i++)
{
temp = cos(((angle_interval * i) + angle) * M_PI / 180);
temp *= r;
temp_val = (int)temp;
*xx = temp_val + x;
temp = sin(((angle_interval * i) + angle) * M_PI / 180);
temp *= r;
temp_val = (int)temp;
*yy = temp_val + y;
xx++;
yy++;
}
rtgui_dc_draw_polygon(dc, (const int *)x_head, (const int *)y_head, count);
rtgui_free(x_head);
rtgui_free(y_head);
}
RTM_EXPORT(rtgui_dc_draw_regular_polygon);
void rtgui_dc_fill_polygon(struct rtgui_dc* dc, const int* vx, const int* vy, int count)
{
int i;
int y, xa, xb;
int miny, maxy;
int x1, y1;
int x2, y2;
int ind1, ind2;
int ints;
int *poly_ints = RT_NULL;
/*
* Sanity check number of edges
*/
if (count < 3) return;
/*
* Allocate temp array, only grow array
*/
poly_ints = (int *) rtgui_malloc(sizeof(int) * count);
if (poly_ints == RT_NULL) return ; /* no memory, failed */
/*
* Determine Y maximal
*/
miny = vy[0];
maxy = vy[0];
for (i = 1; (i < count); i++)
{
if (vy[i] < miny) miny = vy[i];
else if (vy[i] > maxy) maxy = vy[i];
}
/*
* Draw, scanning y
*/
for (y = miny; (y <= maxy); y++) {
ints = 0;
for (i = 0; (i < count); i++) {
if (!i) {
ind1 = count - 1;
ind2 = 0;
} else {
ind1 = i - 1;
ind2 = i;
}
y1 = vy[ind1];
y2 = vy[ind2];
if (y1 < y2) {
x1 = vx[ind1];
x2 = vx[ind2];
} else if (y1 > y2) {
y2 = vy[ind1];
y1 = vy[ind2];
x2 = vx[ind1];
x1 = vx[ind2];
} else {
continue;
}
if ( ((y >= y1) && (y < y2)) || ((y == maxy) && (y > y1) && (y <= y2)) )
{
poly_ints[ints++] = ((65536 * (y - y1)) / (y2 - y1)) * (x2 - x1) + (65536 * x1);
}
}
qsort(poly_ints, ints, sizeof(int), _int_compare);
for (i = 0; (i < ints); i += 2)
{
xa = poly_ints[i] + 1;
xa = (xa >> 16) + ((xa & 32768) >> 15);
xb = poly_ints[i+1] - 1;
xb = (xb >> 16) + ((xb & 32768) >> 15);
rtgui_dc_draw_hline(dc, xa, xb, y);
}
}
/* release memory */
rtgui_free(poly_ints);
}
RTM_EXPORT(rtgui_dc_fill_polygon);
void rtgui_dc_draw_circle(struct rtgui_dc* dc, int x, int y, int r)
{
rt_int16_t cx = 0;
rt_int16_t cy = r;
rt_int16_t df = 1 - r;
rt_int16_t d_e = 3;
rt_int16_t d_se = -2 * r + 5;
rt_int16_t xpcx, xmcx, xpcy, xmcy;
rt_int16_t ypcy, ymcy, ypcx, ymcx;
/*
* sanity check radius
*/
if (r < 0) return ;
/* special case for r=0 - draw a point */
if (r == 0) rtgui_dc_draw_point(dc, x, y);
/*
* draw circle
*/
do
{
ypcy = y + cy;
ymcy = y - cy;
if (cx > 0)
{
xpcx = x + cx;
xmcx = x - cx;
rtgui_dc_draw_point(dc, xmcx, ypcy);
rtgui_dc_draw_point(dc, xpcx, ypcy);
rtgui_dc_draw_point(dc, xmcx, ymcy);
rtgui_dc_draw_point(dc, xpcx, ymcy);
}
else
{
rtgui_dc_draw_point(dc, x, ymcy);
rtgui_dc_draw_point(dc, x, ypcy);
}
xpcy = x + cy;
xmcy = x - cy;
if ((cx > 0) && (cx != cy))
{
ypcx = y + cx;
ymcx = y - cx;
rtgui_dc_draw_point(dc, xmcy, ypcx);
rtgui_dc_draw_point(dc, xpcy, ypcx);
rtgui_dc_draw_point(dc, xmcy, ymcx);
rtgui_dc_draw_point(dc, xpcy, ymcx);
}
else if (cx == 0)
{
rtgui_dc_draw_point(dc, xmcy, y);
rtgui_dc_draw_point(dc, xpcy, y);
}
/*
* Update
*/
if (df < 0)
{
df += d_e;
d_e += 2;
d_se += 2;
}
else
{
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
}while (cx <= cy);
}
RTM_EXPORT(rtgui_dc_draw_circle);
void rtgui_dc_fill_circle(struct rtgui_dc* dc, rt_int16_t x, rt_int16_t y, rt_int16_t r)
{
rt_int16_t cx = 0;
rt_int16_t cy = r;
rt_int16_t ocx = (rt_int16_t) 0xffff;
rt_int16_t ocy = (rt_int16_t) 0xffff;
rt_int16_t df = 1 - r;
rt_int16_t d_e = 3;
rt_int16_t d_se = -2 * r + 5;
rt_int16_t xpcx, xmcx, xpcy, xmcy;
rt_int16_t ypcy, ymcy, ypcx, ymcx;
/*
* Sanity check radius
*/
if (r < 0) return;
/*
* Special case for r=0 - draw a point
*/
if (r == 0)
{
rtgui_dc_draw_point(dc, x, y);
return ;
}
/*
* Draw
*/
do {
xpcx = x + cx;
xmcx = x - cx;
xpcy = x + cy;
xmcy = x - cy;
if (ocy != cy) {
if (cy > 0) {
ypcy = y + cy;
ymcy = y - cy;
rtgui_dc_draw_hline(dc, xmcx, xpcx, ypcy);
rtgui_dc_draw_hline(dc, xmcx, xpcx, ymcy);
} else {
rtgui_dc_draw_hline(dc, xmcx, xpcx, y);
}
ocy = cy;
}
if (ocx != cx) {
if (cx != cy) {
if (cx > 0) {
ypcx = y + cx;
ymcx = y - cx;
rtgui_dc_draw_hline(dc, xmcy, xpcy, ymcx);
rtgui_dc_draw_hline(dc, xmcy, xpcy, ypcx);
} else {
rtgui_dc_draw_hline(dc, xmcy, xpcy, y);
}
}
ocx = cx;
}
/*
* Update
*/
if (df < 0) {
df += d_e;
d_e += 2;
d_se += 2;
} else {
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
} while (cx <= cy);
}
RTM_EXPORT(rtgui_dc_fill_circle);
void rtgui_dc_draw_arc(struct rtgui_dc *dc, rt_int16_t x, rt_int16_t y, rt_int16_t r, rt_int16_t start, rt_int16_t end)
{
rt_int16_t cx = 0;
rt_int16_t cy = r;
rt_int16_t df = 1 - r;
rt_int16_t d_e = 3;
rt_int16_t d_se = -2 * r + 5;
rt_int16_t xpcx, xmcx, xpcy, xmcy;
rt_int16_t ypcy, ymcy, ypcx, ymcx;
rt_uint8_t drawoct;
int startoct, endoct, oct, stopval_start, stopval_end;
double temp;
stopval_start = 0;
stopval_end = 0;
temp = 0;
/* Sanity check radius */
if (r < 0) return ;
/* Special case for r=0 - draw a point */
if (r == 0)
{
rtgui_dc_draw_point(dc, x, y);
return;
}
/*
* Draw arc
*/
// Octant labelling
//
// \ 5 | 6 /
// \ | /
// 4 \ | / 7
// \|/
//------+------ +x
// /|\
// 3 / | \ 0
// / | \
// / 2 | 1 \
// +y
drawoct = 0; // 0x00000000
// whether or not to keep drawing a given octant.
// For example: 0x00111100 means we're drawing in octants 2-5
// 0 <= start & end < 360; note that sometimes start > end - if so, arc goes back through 0.
while (start < 0) start += 360;
while (end < 0) end += 360;
/* Fixup angles */
start = start % 360;
end = end % 360;
// now, we find which octants we're drawing in.
startoct = start / 45;
endoct = end / 45;
oct = startoct - 1; // we increment as first step in loop
//stopval_start, stopval_end; // what values of cx to stop at.
do {
oct = (oct + 1) % 8;
if (oct == startoct)
{
// need to compute stopval_start for this octant. Look at picture above if this is unclear
switch (oct)
{
case 0:
case 3:
temp = sin(start * M_PI / 180);
break;
case 1:
case 6:
temp = cos(start * M_PI / 180);
break;
case 2:
case 5:
temp = -cos(start * M_PI / 180);
break;
case 4:
case 7:
temp = -sin(start * M_PI / 180);
break;
}
temp *= r;
stopval_start = (int)temp; // always round down.
// This isn't arbitrary, but requires graph paper to explain well.
// The basic idea is that we're always changing drawoct after we draw, so we
// stop immediately after we render the last sensible pixel at x = ((int)temp).
// and whether to draw in this octant initially
if (oct % 2) drawoct |= (1 << oct); // this is basically like saying drawoct[oct] = true, if drawoct were a bool array
else drawoct &= 255 - (1 << oct); // this is basically like saying drawoct[oct] = false
}
if (oct == endoct)
{
// need to compute stopval_end for this octant
switch (oct)
{
case 0:
case 3:
temp = sin(end * M_PI / 180);
break;
case 1:
case 6:
temp = cos(end * M_PI / 180);
break;
case 2:
case 5:
temp = -cos(end * M_PI / 180);
break;
case 4:
case 7:
temp = -sin(end * M_PI / 180);
break;
}
temp *= r;
stopval_end = (int)temp;
// and whether to draw in this octant initially
if (startoct == endoct)
{
// note: we start drawing, stop, then start again in this case
// otherwise: we only draw in this octant, so initialize it to false, it will get set back to true
if (start > end)
{
// unfortunately, if we're in the same octant and need to draw over the whole circle,
// we need to set the rest to true, because the while loop will end at the bottom.
drawoct = 255;
}
else
{
drawoct &= 255 - (1 << oct);
}
}
else if (oct % 2) drawoct &= 255 - (1 << oct);
else drawoct |= (1 << oct);
} else if (oct != startoct) { // already verified that it's != endoct
drawoct |= (1 << oct); // draw this entire segment
}
} while (oct != endoct);
// so now we have what octants to draw and when to draw them. all that's left is the actual raster code.
do
{
ypcy = y + cy;
ymcy = y - cy;
if (cx > 0)
{
xpcx = x + cx;
xmcx = x - cx;
// always check if we're drawing a certain octant before adding a pixel to that octant.
if (drawoct & 4) rtgui_dc_draw_point(dc, xmcx, ypcy); // drawoct & 4 = 22; drawoct[2]
if (drawoct & 2) rtgui_dc_draw_point(dc, xpcx, ypcy);
if (drawoct & 32) rtgui_dc_draw_point(dc, xmcx, ymcy);
if (drawoct & 64) rtgui_dc_draw_point(dc, xpcx, ymcy);
}
else
{
if (drawoct & 6) rtgui_dc_draw_point(dc, x, ypcy); // 4 + 2; drawoct[2] || drawoct[1]
if (drawoct & 96) rtgui_dc_draw_point(dc, x, ymcy); // 32 + 64
}
xpcy = x + cy;
xmcy = x - cy;
if (cx > 0 && cx != cy)
{
ypcx = y + cx;
ymcx = y - cx;
if (drawoct & 8) rtgui_dc_draw_point(dc, xmcy, ypcx);
if (drawoct & 1) rtgui_dc_draw_point(dc, xpcy, ypcx);
if (drawoct & 16) rtgui_dc_draw_point(dc, xmcy, ymcx);
if (drawoct & 128) rtgui_dc_draw_point(dc, xpcy, ymcx);
}
else if (cx == 0)
{
if (drawoct & 24) rtgui_dc_draw_point(dc, xmcy, y); // 8 + 16
if (drawoct & 129) rtgui_dc_draw_point(dc, xpcy, y); // 1 + 128
}
/*
* Update whether we're drawing an octant
*/
if (stopval_start == cx)
{
// works like an on-off switch because start & end may be in the same octant.
if (drawoct & (1 << startoct)) drawoct &= 255 - (1 << startoct);
else drawoct |= (1 << startoct);
}
if (stopval_end == cx)
{
if (drawoct & (1 << endoct)) drawoct &= 255 - (1 << endoct);
else drawoct |= (1 << endoct);
}
/*
* Update pixels
*/
if (df < 0)
{
df += d_e;
d_e += 2;
d_se += 2;
}
else
{
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
} while (cx <= cy);
}
RTM_EXPORT(rtgui_dc_draw_arc);
void rtgui_dc_draw_annulus(struct rtgui_dc *dc, rt_int16_t x, rt_int16_t y, rt_int16_t r1, rt_int16_t r2, rt_int16_t start, rt_int16_t end)
{
rt_int16_t start_x, start_y;
rt_int16_t end_x, end_y;
double temp;
rt_int16_t temp_val = 0;
/* Sanity check radius */
if ((r1 < 0) || (r2 < 0)) return ;
/* Special case for r=0 - draw a point */
if ((r1 == 0) && (r2 == 0))
{
rtgui_dc_draw_point(dc, x, y);
return;
}
while (start < 0) start += 360;
while (end < 0) end += 360;
rtgui_dc_draw_arc(dc, x, y, r1, start, end);
rtgui_dc_draw_arc(dc, x, y, r2, start, end);
temp = cos(start * M_PI / 180);
temp_val = (int)(temp * r1);
start_x = x + temp_val;
temp_val = (int)(temp * r2);
end_x = x + temp_val;
temp = sin(start * M_PI / 180);
temp_val = (int)(temp * r1);
start_y = y + temp_val;
temp_val = (int)(temp * r2);
end_y = y + temp_val;
rtgui_dc_draw_line(dc, start_x, start_y, end_x, end_y);
temp = cos(end * M_PI / 180);
temp_val = (int)(temp * r1);
start_x = x + temp_val;
temp_val = (int)(temp * r2);
end_x = x + temp_val;
temp = sin(end * M_PI / 180);
temp_val = (int)(temp * r1);
start_y = y + temp_val;
temp_val = (int)(temp * r2);
end_y = y + temp_val;
rtgui_dc_draw_line(dc, start_x, start_y, end_x, end_y);
}
RTM_EXPORT(rtgui_dc_draw_annulus);
void rtgui_dc_draw_sector(struct rtgui_dc *dc, rt_int16_t x, rt_int16_t y, rt_int16_t r, rt_int16_t start, rt_int16_t end)
{
int start_x, start_y;
int end_x, end_y;
/* Sanity check radius */
if (r < 0) return ;
/* Special case for r=0 - draw a point */
if (r == 0)
{
rtgui_dc_draw_point(dc, x, y);
return;
}
while (start < 0) start += 360;
while (end < 0) end += 360;
/* Fixup angles */
start = start % 360;
end = end % 360;
rtgui_dc_draw_arc(dc, x, y, r, start, end);
start_x = x + r * cos(start * M_PI / 180);
start_y = y + r * sin(start * M_PI / 180);
end_x = x + r * cos(end * M_PI / 180);
end_y = y + r * sin(end * M_PI / 180);
rtgui_dc_draw_line(dc, x, y, start_x, start_y);
rtgui_dc_draw_line(dc, x, y, end_x, end_y);
}
RTM_EXPORT(rtgui_dc_draw_sector);
void rtgui_dc_fill_sector(struct rtgui_dc *dc, rt_int16_t x, rt_int16_t y, rt_int16_t r, rt_int16_t start, rt_int16_t end)
{
int start_x, start_y;
int end_x, end_y;
/* Sanity check radius */
if (r < 0) return ;
/* Special case for r=0 - draw a point */
if (r == 0)
{
rtgui_dc_draw_point(dc, x, y);
return;
}
while (start < 0) start += 360;
while (end < 0) end += 360;
/* Fixup angles */
start = start % 360;
end = end % 360;
end_x = x + r * cos(end * M_PI / 180);
end_y = y + r * sin(end * M_PI / 180);
do
{
start_x = x + r * cos(start * M_PI / 180);
start_y = y + r * sin(start * M_PI / 180);
start ++;
rtgui_dc_draw_line(dc, x, y, start_x, start_y);
}while(!((start_x == end_x) && (start_y == end_y)));
}
RTM_EXPORT(rtgui_dc_fill_sector);
void rtgui_dc_draw_ellipse(struct rtgui_dc* dc, rt_int16_t x, rt_int16_t y, rt_int16_t rx, rt_int16_t ry)
{
int ix, iy;
int h, i, j, k;
int oh, oi, oj, ok;
int xmh, xph, ypk, ymk;
int xmi, xpi, ymj, ypj;
int xmj, xpj, ymi, ypi;
int xmk, xpk, ymh, yph;
/*
* Sanity check radii
*/
if ((rx < 0) || (ry < 0)) return;
/*
* Special case for rx=0 - draw a vline
*/
if (rx == 0)
{
rtgui_dc_draw_vline(dc, x, y - ry, y + ry);
return;
}
/*
* Special case for ry=0 - draw a hline
*/
if (ry == 0)
{
rtgui_dc_draw_hline(dc, x - rx, x + rx, y);
return;
}
/*
* Init vars
*/
oh = oi = oj = ok = 0xFFFF;
if (rx > ry)
{
ix = 0;
iy = rx * 64;
do
{
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * ry) / rx;
k = (i * ry) / rx;
if (((ok != k) && (oj != k)) || ((oj != j) && (ok != j)) || (k != j))
{
xph = x + h;
xmh = x - h;
if (k > 0)
{
ypk = y + k;
ymk = y - k;
rtgui_dc_draw_point(dc, xmh, ypk);
rtgui_dc_draw_point(dc, xph, ypk);
rtgui_dc_draw_point(dc, xmh, ymk);
rtgui_dc_draw_point(dc, xph, ymk);
}
else
{
rtgui_dc_draw_point(dc, xmh, y);
rtgui_dc_draw_point(dc, xph, y);
}
ok = k;
xpi = x + i;
xmi = x - i;
if (j > 0)
{
ypj = y + j;
ymj = y - j;
rtgui_dc_draw_point(dc, xmi, ypj);
rtgui_dc_draw_point(dc, xpi, ypj);
rtgui_dc_draw_point(dc, xmi, ymj);
rtgui_dc_draw_point(dc, xpi, ymj);
}
else
{
rtgui_dc_draw_point(dc, xmi, y);
rtgui_dc_draw_point(dc, xpi, y);
}
oj = j;
}
ix = ix + iy / rx;
iy = iy - ix / rx;
} while (i > h);
}
else
{
ix = 0;
iy = ry * 64;
do
{
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * rx) / ry;
k = (i * rx) / ry;
if (((oi != i) && (oh != i)) || ((oh != h) && (oi != h) && (i != h)))
{
xmj = x - j;
xpj = x + j;
if (i > 0)
{
ypi = y + i;
ymi = y - i;
rtgui_dc_draw_point(dc, xmj, ypi);
rtgui_dc_draw_point(dc, xpj, ypi);
rtgui_dc_draw_point(dc, xmj, ymi);
rtgui_dc_draw_point(dc, xpj, ymi);
}
else
{
rtgui_dc_draw_point(dc, xmj, y);
rtgui_dc_draw_point(dc, xpj, y);
}
oi = i;
xmk = x - k;
xpk = x + k;
if (h > 0)
{
yph = y + h;
ymh = y - h;
rtgui_dc_draw_point(dc, xmk, yph);
rtgui_dc_draw_point(dc, xpk, yph);
rtgui_dc_draw_point(dc, xmk, ymh);
rtgui_dc_draw_point(dc, xpk, ymh);
}
else
{
rtgui_dc_draw_point(dc, xmk, y);
rtgui_dc_draw_point(dc, xpk, y);
}
oh = h;
}
ix = ix + iy / ry;
iy = iy - ix / ry;
} while (i > h);
}
}
RTM_EXPORT(rtgui_dc_draw_ellipse);
void rtgui_dc_fill_ellipse(struct rtgui_dc *dc, rt_int16_t x, rt_int16_t y, rt_int16_t rx, rt_int16_t ry)
{
int ix, iy;
int h, i, j, k;
int oh, oi, oj, ok;
int xmh, xph;
int xmi, xpi;
int xmj, xpj;
int xmk, xpk;
/*
* Special case for rx=0 - draw a vline
*/
if (rx == 0)
{
rtgui_dc_draw_vline(dc, x, y - ry, y + ry);
return;
}
/* special case for ry=0 - draw a hline */
if (ry == 0) {
rtgui_dc_draw_hline(dc, x - rx, x + rx, y);
return;
}
/*
* Init vars
*/
oh = oi = oj = ok = 0xFFFF;
/*
* Draw
*/
if (rx > ry) {
ix = 0;
iy = rx * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * ry) / rx;
k = (i * ry) / rx;
if ((ok != k) && (oj != k)) {
xph = x + h;
xmh = x - h;
if (k > 0) {
rtgui_dc_draw_hline(dc, xmh, xph, y + k);
rtgui_dc_draw_hline(dc, xmh, xph, y - k);
} else {
rtgui_dc_draw_hline(dc, xmh, xph, y);
}
ok = k;
}
if ((oj != j) && (ok != j) && (k != j)) {
xmi = x - i;
xpi = x + i;
if (j > 0) {
rtgui_dc_draw_hline(dc, xmi, xpi, y + j);
rtgui_dc_draw_hline(dc, xmi, xpi, y - j);
} else {
rtgui_dc_draw_hline(dc, xmi, xpi, y);
}
oj = j;
}
ix = ix + iy / rx;
iy = iy - ix / rx;
} while (i > h);
} else {
ix = 0;
iy = ry * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * rx) / ry;
k = (i * rx) / ry;
if ((oi != i) && (oh != i)) {
xmj = x - j;
xpj = x + j;
if (i > 0) {
rtgui_dc_draw_hline(dc, xmj, xpj, y + i);
rtgui_dc_draw_hline(dc, xmj, xpj, y - i);
} else {
rtgui_dc_draw_hline(dc, xmj, xpj, y);
}
oi = i;
}
if ((oh != h) && (oi != h) && (i != h)) {
xmk = x - k;
xpk = x + k;
if (h > 0) {
rtgui_dc_draw_hline(dc, xmk, xpk, y + h);
rtgui_dc_draw_hline(dc, xmk, xpk, y - h);
} else {
rtgui_dc_draw_hline(dc, xmk, xpk, y);
}
oh = h;
}
ix = ix + iy / ry;
iy = iy - ix / ry;
} while (i > h);
}
}
RTM_EXPORT(rtgui_dc_fill_ellipse);
|
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Definitions for the IP module.
*
* Version: @(#)ip.h 1.0.2 05/07/93
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
*
* Changes:
* Mike McLagan : Routing by source
*
* 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 _IP_H
#define _IP_H
#include <linux/types.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/skbuff.h>
#include <net/inet_sock.h>
#include <net/route.h>
#include <net/snmp.h>
#include <net/flow.h>
#include <net/flow_dissector.h>
struct sock;
struct inet_skb_parm {
struct ip_options opt; /* Compiled IP options */
unsigned char flags;
#define IPSKB_FORWARDED BIT(0)
#define IPSKB_XFRM_TUNNEL_SIZE BIT(1)
#define IPSKB_XFRM_TRANSFORMED BIT(2)
#define IPSKB_FRAG_COMPLETE BIT(3)
#define IPSKB_REROUTED BIT(4)
#define IPSKB_DOREDIRECT BIT(5)
#define IPSKB_FRAG_PMTU BIT(6)
u16 frag_max_size;
};
static inline unsigned int ip_hdrlen(const struct sk_buff *skb)
{
return ip_hdr(skb)->ihl * 4;
}
struct ipcm_cookie {
__be32 addr;
int oif;
struct ip_options_rcu *opt;
__u8 tx_flags;
__u8 ttl;
__s16 tos;
char priority;
};
#define IPCB(skb) ((struct inet_skb_parm*)((skb)->cb))
#define PKTINFO_SKB_CB(skb) ((struct in_pktinfo *)((skb)->cb))
struct ip_ra_chain {
struct ip_ra_chain __rcu *next;
struct sock *sk;
union {
void (*destructor)(struct sock *);
struct sock *saved_sk;
};
struct rcu_head rcu;
};
extern struct ip_ra_chain __rcu *ip_ra_chain;
/* IP flags. */
#define IP_CE 0x8000 /* Flag: "Congestion" */
#define IP_DF 0x4000 /* Flag: "Don't Fragment" */
#define IP_MF 0x2000 /* Flag: "More Fragments" */
#define IP_OFFSET 0x1FFF /* "Fragment Offset" part */
#define IP_FRAG_TIME (30 * HZ) /* fragment lifetime */
struct msghdr;
struct net_device;
struct packet_type;
struct rtable;
struct sockaddr;
int igmp_mc_init(void);
/*
* Functions provided by ip.c
*/
int ip_build_and_send_pkt(struct sk_buff *skb, const struct sock *sk,
__be32 saddr, __be32 daddr,
struct ip_options_rcu *opt);
int ip_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt,
struct net_device *orig_dev);
int ip_local_deliver(struct sk_buff *skb);
int ip_mr_input(struct sk_buff *skb);
int ip_output(struct net *net, struct sock *sk, struct sk_buff *skb);
int ip_mc_output(struct net *net, struct sock *sk, struct sk_buff *skb);
int ip_do_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
int (*output)(struct net *, struct sock *, struct sk_buff *));
void ip_send_check(struct iphdr *ip);
int __ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb);
int ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb);
int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl);
void ip_init(void);
int ip_append_data(struct sock *sk, struct flowi4 *fl4,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int len, int protolen,
struct ipcm_cookie *ipc,
struct rtable **rt,
unsigned int flags);
int ip_generic_getfrag(void *from, char *to, int offset, int len, int odd,
struct sk_buff *skb);
ssize_t ip_append_page(struct sock *sk, struct flowi4 *fl4, struct page *page,
int offset, size_t size, int flags);
struct sk_buff *__ip_make_skb(struct sock *sk, struct flowi4 *fl4,
struct sk_buff_head *queue,
struct inet_cork *cork);
int ip_send_skb(struct net *net, struct sk_buff *skb);
int ip_push_pending_frames(struct sock *sk, struct flowi4 *fl4);
void ip_flush_pending_frames(struct sock *sk);
struct sk_buff *ip_make_skb(struct sock *sk, struct flowi4 *fl4,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
struct ipcm_cookie *ipc, struct rtable **rtp,
unsigned int flags);
static inline struct sk_buff *ip_finish_skb(struct sock *sk, struct flowi4 *fl4)
{
return __ip_make_skb(sk, fl4, &sk->sk_write_queue, &inet_sk(sk)->cork.base);
}
static inline __u8 get_rttos(struct ipcm_cookie* ipc, struct inet_sock *inet)
{
return (ipc->tos != -1) ? RT_TOS(ipc->tos) : RT_TOS(inet->tos);
}
static inline __u8 get_rtconn_flags(struct ipcm_cookie* ipc, struct sock* sk)
{
return (ipc->tos != -1) ? RT_CONN_FLAGS_TOS(sk, ipc->tos) : RT_CONN_FLAGS(sk);
}
/* datagram.c */
int __ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len);
int ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len);
void ip4_datagram_release_cb(struct sock *sk);
struct ip_reply_arg {
struct kvec iov[1];
int flags;
__wsum csum;
int csumoffset; /* u16 offset of csum in iov[0].iov_base */
/* -1 if not needed */
int bound_dev_if;
u8 tos;
};
#define IP_REPLY_ARG_NOSRCCHECK 1
static inline __u8 ip_reply_arg_flowi_flags(const struct ip_reply_arg *arg)
{
return (arg->flags & IP_REPLY_ARG_NOSRCCHECK) ? FLOWI_FLAG_ANYSRC : 0;
}
void ip_send_unicast_reply(struct sock *sk, struct sk_buff *skb,
const struct ip_options *sopt,
__be32 daddr, __be32 saddr,
const struct ip_reply_arg *arg,
unsigned int len);
#define IP_INC_STATS(net, field) SNMP_INC_STATS64((net)->mib.ip_statistics, field)
#define IP_INC_STATS_BH(net, field) SNMP_INC_STATS64_BH((net)->mib.ip_statistics, field)
#define IP_ADD_STATS(net, field, val) SNMP_ADD_STATS64((net)->mib.ip_statistics, field, val)
#define IP_ADD_STATS_BH(net, field, val) SNMP_ADD_STATS64_BH((net)->mib.ip_statistics, field, val)
#define IP_UPD_PO_STATS(net, field, val) SNMP_UPD_PO_STATS64((net)->mib.ip_statistics, field, val)
#define IP_UPD_PO_STATS_BH(net, field, val) SNMP_UPD_PO_STATS64_BH((net)->mib.ip_statistics, field, val)
#define NET_INC_STATS(net, field) SNMP_INC_STATS((net)->mib.net_statistics, field)
#define NET_INC_STATS_BH(net, field) SNMP_INC_STATS_BH((net)->mib.net_statistics, field)
#define NET_INC_STATS_USER(net, field) SNMP_INC_STATS_USER((net)->mib.net_statistics, field)
#define NET_ADD_STATS(net, field, adnd) SNMP_ADD_STATS((net)->mib.net_statistics, field, adnd)
#define NET_ADD_STATS_BH(net, field, adnd) SNMP_ADD_STATS_BH((net)->mib.net_statistics, field, adnd)
#define NET_ADD_STATS_USER(net, field, adnd) SNMP_ADD_STATS_USER((net)->mib.net_statistics, field, adnd)
u64 snmp_get_cpu_field(void __percpu *mib, int cpu, int offct);
unsigned long snmp_fold_field(void __percpu *mib, int offt);
#if BITS_PER_LONG==32
u64 snmp_get_cpu_field64(void __percpu *mib, int cpu, int offct,
size_t syncp_offset);
u64 snmp_fold_field64(void __percpu *mib, int offt, size_t sync_off);
#else
static inline u64 snmp_get_cpu_field64(void __percpu *mib, int cpu, int offct,
size_t syncp_offset)
{
return snmp_get_cpu_field(mib, cpu, offct);
}
static inline u64 snmp_fold_field64(void __percpu *mib, int offt, size_t syncp_off)
{
return snmp_fold_field(mib, offt);
}
#endif
void inet_get_local_port_range(struct net *net, int *low, int *high);
#ifdef CONFIG_SYSCTL
static inline int inet_is_local_reserved_port(struct net *net, int port)
{
if (!net->ipv4.sysctl_local_reserved_ports)
return 0;
return test_bit(port, net->ipv4.sysctl_local_reserved_ports);
}
static inline bool sysctl_dev_name_is_allowed(const char *name)
{
return strcmp(name, "default") != 0 && strcmp(name, "all") != 0;
}
#else
static inline int inet_is_local_reserved_port(struct net *net, int port)
{
return 0;
}
#endif
/* From inetpeer.c */
extern int inet_peer_threshold;
extern int inet_peer_minttl;
extern int inet_peer_maxttl;
/* From ip_input.c */
extern int sysctl_ip_early_demux;
/* From ip_output.c */
extern int sysctl_ip_dynaddr;
void ipfrag_init(void);
void ip_static_sysctl_init(void);
#define IP4_REPLY_MARK(net, mark) \
((net)->ipv4.sysctl_fwmark_reflect ? (mark) : 0)
static inline bool ip_is_fragment(const struct iphdr *iph)
{
return (iph->frag_off & htons(IP_MF | IP_OFFSET)) != 0;
}
#ifdef CONFIG_INET
#include <net/dst.h>
/* The function in 2.2 was invalid, producing wrong result for
* check=0xFEFF. It was noticed by Arthur Skawina _year_ ago. --ANK(000625) */
static inline
int ip_decrease_ttl(struct iphdr *iph)
{
u32 check = (__force u32)iph->check;
check += (__force u32)htons(0x0100);
iph->check = (__force __sum16)(check + (check>=0xFFFF));
return --iph->ttl;
}
static inline
int ip_dont_fragment(const struct sock *sk, const struct dst_entry *dst)
{
u8 pmtudisc = READ_ONCE(inet_sk(sk)->pmtudisc);
return pmtudisc == IP_PMTUDISC_DO ||
(pmtudisc == IP_PMTUDISC_WANT &&
!(dst_metric_locked(dst, RTAX_MTU)));
}
static inline bool ip_sk_accept_pmtu(const struct sock *sk)
{
return inet_sk(sk)->pmtudisc != IP_PMTUDISC_INTERFACE &&
inet_sk(sk)->pmtudisc != IP_PMTUDISC_OMIT;
}
static inline bool ip_sk_use_pmtu(const struct sock *sk)
{
return inet_sk(sk)->pmtudisc < IP_PMTUDISC_PROBE;
}
static inline bool ip_sk_ignore_df(const struct sock *sk)
{
return inet_sk(sk)->pmtudisc < IP_PMTUDISC_DO ||
inet_sk(sk)->pmtudisc == IP_PMTUDISC_OMIT;
}
static inline unsigned int ip_dst_mtu_maybe_forward(const struct dst_entry *dst,
bool forwarding)
{
struct net *net = dev_net(dst->dev);
if (net->ipv4.sysctl_ip_fwd_use_pmtu ||
dst_metric_locked(dst, RTAX_MTU) ||
!forwarding)
return dst_mtu(dst);
return min(dst->dev->mtu, IP_MAX_MTU);
}
static inline unsigned int ip_skb_dst_mtu(const struct sk_buff *skb)
{
struct sock *sk = skb->sk;
if (!sk || !sk_fullsock(sk) || ip_sk_use_pmtu(sk)) {
bool forwarding = IPCB(skb)->flags & IPSKB_FORWARDED;
return ip_dst_mtu_maybe_forward(skb_dst(skb), forwarding);
}
return min(skb_dst(skb)->dev->mtu, IP_MAX_MTU);
}
u32 ip_idents_reserve(u32 hash, int segs);
void __ip_select_ident(struct net *net, struct iphdr *iph, int segs);
static inline void ip_select_ident_segs(struct net *net, struct sk_buff *skb,
struct sock *sk, int segs)
{
struct iphdr *iph = ip_hdr(skb);
if ((iph->frag_off & htons(IP_DF)) && !skb->ignore_df) {
/* This is only to work around buggy Windows95/2000
* VJ compression implementations. If the ID field
* does not change, they drop every other packet in
* a TCP stream using header compression.
*/
if (sk && inet_sk(sk)->inet_daddr) {
iph->id = htons(inet_sk(sk)->inet_id);
inet_sk(sk)->inet_id += segs;
} else {
iph->id = 0;
}
} else {
__ip_select_ident(net, iph, segs);
}
}
static inline void ip_select_ident(struct net *net, struct sk_buff *skb,
struct sock *sk)
{
ip_select_ident_segs(net, skb, sk, 1);
}
static inline __wsum inet_compute_pseudo(struct sk_buff *skb, int proto)
{
return csum_tcpudp_nofold(ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
skb->len, proto, 0);
}
/* copy IPv4 saddr & daddr to flow_keys, possibly using 64bit load/store
* Equivalent to : flow->v4addrs.src = iph->saddr;
* flow->v4addrs.dst = iph->daddr;
*/
static inline void iph_to_flow_copy_v4addrs(struct flow_keys *flow,
const struct iphdr *iph)
{
BUILD_BUG_ON(offsetof(typeof(flow->addrs), v4addrs.dst) !=
offsetof(typeof(flow->addrs), v4addrs.src) +
sizeof(flow->addrs.v4addrs.src));
memcpy(&flow->addrs.v4addrs, &iph->saddr, sizeof(flow->addrs.v4addrs));
flow->control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
}
static inline __wsum inet_gro_compute_pseudo(struct sk_buff *skb, int proto)
{
const struct iphdr *iph = skb_gro_network_header(skb);
return csum_tcpudp_nofold(iph->saddr, iph->daddr,
skb_gro_len(skb), proto, 0);
}
/*
* Map a multicast IP onto multicast MAC for type ethernet.
*/
static inline void ip_eth_mc_map(__be32 naddr, char *buf)
{
__u32 addr=ntohl(naddr);
buf[0]=0x01;
buf[1]=0x00;
buf[2]=0x5e;
buf[5]=addr&0xFF;
addr>>=8;
buf[4]=addr&0xFF;
addr>>=8;
buf[3]=addr&0x7F;
}
/*
* Map a multicast IP onto multicast MAC for type IP-over-InfiniBand.
* Leave P_Key as 0 to be filled in by driver.
*/
static inline void ip_ib_mc_map(__be32 naddr, const unsigned char *broadcast, char *buf)
{
__u32 addr;
unsigned char scope = broadcast[5] & 0xF;
buf[0] = 0; /* Reserved */
buf[1] = 0xff; /* Multicast QPN */
buf[2] = 0xff;
buf[3] = 0xff;
addr = ntohl(naddr);
buf[4] = 0xff;
buf[5] = 0x10 | scope; /* scope from broadcast address */
buf[6] = 0x40; /* IPv4 signature */
buf[7] = 0x1b;
buf[8] = broadcast[8]; /* P_Key */
buf[9] = broadcast[9];
buf[10] = 0;
buf[11] = 0;
buf[12] = 0;
buf[13] = 0;
buf[14] = 0;
buf[15] = 0;
buf[19] = addr & 0xff;
addr >>= 8;
buf[18] = addr & 0xff;
addr >>= 8;
buf[17] = addr & 0xff;
addr >>= 8;
buf[16] = addr & 0x0f;
}
static inline void ip_ipgre_mc_map(__be32 naddr, const unsigned char *broadcast, char *buf)
{
if ((broadcast[0] | broadcast[1] | broadcast[2] | broadcast[3]) != 0)
memcpy(buf, broadcast, 4);
else
memcpy(buf, &naddr, sizeof(naddr));
}
#if IS_ENABLED(CONFIG_IPV6)
#include <linux/ipv6.h>
#endif
static __inline__ void inet_reset_saddr(struct sock *sk)
{
inet_sk(sk)->inet_rcv_saddr = inet_sk(sk)->inet_saddr = 0;
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == PF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
memset(&np->saddr, 0, sizeof(np->saddr));
memset(&sk->sk_v6_rcv_saddr, 0, sizeof(sk->sk_v6_rcv_saddr));
}
#endif
}
#endif
static inline unsigned int ipv4_addr_hash(__be32 ip)
{
return (__force unsigned int) ip;
}
bool ip_call_ra_chain(struct sk_buff *skb);
/*
* Functions provided by ip_fragment.c
*/
enum ip_defrag_users {
IP_DEFRAG_LOCAL_DELIVER,
IP_DEFRAG_CALL_RA_CHAIN,
IP_DEFRAG_CONNTRACK_IN,
__IP_DEFRAG_CONNTRACK_IN_END = IP_DEFRAG_CONNTRACK_IN + USHRT_MAX,
IP_DEFRAG_CONNTRACK_OUT,
__IP_DEFRAG_CONNTRACK_OUT_END = IP_DEFRAG_CONNTRACK_OUT + USHRT_MAX,
IP_DEFRAG_CONNTRACK_BRIDGE_IN,
__IP_DEFRAG_CONNTRACK_BRIDGE_IN = IP_DEFRAG_CONNTRACK_BRIDGE_IN + USHRT_MAX,
IP_DEFRAG_VS_IN,
IP_DEFRAG_VS_OUT,
IP_DEFRAG_VS_FWD,
IP_DEFRAG_AF_PACKET,
IP_DEFRAG_MACVLAN,
};
/* Return true if the value of 'user' is between 'lower_bond'
* and 'upper_bond' inclusively.
*/
static inline bool ip_defrag_user_in_between(u32 user,
enum ip_defrag_users lower_bond,
enum ip_defrag_users upper_bond)
{
return user >= lower_bond && user <= upper_bond;
}
int ip_defrag(struct net *net, struct sk_buff *skb, u32 user);
#ifdef CONFIG_INET
struct sk_buff *ip_check_defrag(struct net *net, struct sk_buff *skb, u32 user);
#else
static inline struct sk_buff *ip_check_defrag(struct net *net, struct sk_buff *skb, u32 user)
{
return skb;
}
#endif
int ip_frag_mem(struct net *net);
/*
* Functions provided by ip_forward.c
*/
int ip_forward(struct sk_buff *skb);
/*
* Functions provided by ip_options.c
*/
void ip_options_build(struct sk_buff *skb, struct ip_options *opt,
__be32 daddr, struct rtable *rt, int is_frag);
int __ip_options_echo(struct ip_options *dopt, struct sk_buff *skb,
const struct ip_options *sopt);
static inline int ip_options_echo(struct ip_options *dopt, struct sk_buff *skb)
{
return __ip_options_echo(dopt, skb, &IPCB(skb)->opt);
}
void ip_options_fragment(struct sk_buff *skb);
int ip_options_compile(struct net *net, struct ip_options *opt,
struct sk_buff *skb);
int ip_options_get(struct net *net, struct ip_options_rcu **optp,
unsigned char *data, int optlen);
int ip_options_get_from_user(struct net *net, struct ip_options_rcu **optp,
unsigned char __user *data, int optlen);
void ip_options_undo(struct ip_options *opt);
void ip_forward_options(struct sk_buff *skb);
int ip_options_rcv_srr(struct sk_buff *skb);
/*
* Functions provided by ip_sockglue.c
*/
void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb);
void ip_cmsg_recv_offset(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset);
int ip_cmsg_send(struct net *net, struct msghdr *msg,
struct ipcm_cookie *ipc, bool allow_ipv6);
int ip_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
unsigned int optlen);
int ip_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
int __user *optlen);
int compat_ip_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen);
int compat_ip_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen);
int ip_ra_control(struct sock *sk, unsigned char on,
void (*destructor)(struct sock *));
int ip_recv_error(struct sock *sk, struct msghdr *msg, int len, int *addr_len);
void ip_icmp_error(struct sock *sk, struct sk_buff *skb, int err, __be16 port,
u32 info, u8 *payload);
void ip_local_error(struct sock *sk, int err, __be32 daddr, __be16 dport,
u32 info);
static inline void ip_cmsg_recv(struct msghdr *msg, struct sk_buff *skb)
{
ip_cmsg_recv_offset(msg, skb, 0, 0);
}
bool icmp_global_allow(void);
extern int sysctl_icmp_msgs_per_sec;
extern int sysctl_icmp_msgs_burst;
#ifdef CONFIG_PROC_FS
int ip_misc_proc_init(void);
#endif
#endif /* _IP_H */
|
#
# Makefile for the kernel character device drivers.
#
#
# This file contains the font map for the default (hardware) font
#
FONTMAPFILE = cp437.uni
ifeq ($(CONFIG_ARM),y)
# This warning will never go away until a keyboard is defined for this target.
CFLAGS_REMOVE_keyboard.o = -Werror
endif
obj-y += mem.o random.o tty_io.o n_tty.o tty_ioctl.o tty_ldisc.o tty_buffer.o tty_port.o
obj-$(CONFIG_LEGACY_PTYS) += pty.o
obj-$(CONFIG_UNIX98_PTYS) += pty.o
obj-y += misc.o
obj-$(CONFIG_VT) += vt_ioctl.o vc_screen.o selection.o keyboard.o
obj-$(CONFIG_BFIN_JTAG_COMM) += bfin_jtag_comm.o
obj-$(CONFIG_CONSOLE_TRANSLATIONS) += consolemap.o consolemap_deftbl.o
obj-$(CONFIG_HW_CONSOLE) += vt.o defkeymap.o
obj-$(CONFIG_AUDIT) += tty_audit.o
obj-$(CONFIG_MAGIC_SYSRQ) += sysrq.o
obj-$(CONFIG_ESPSERIAL) += esp.o
obj-$(CONFIG_MVME147_SCC) += generic_serial.o vme_scc.o
obj-$(CONFIG_MVME162_SCC) += generic_serial.o vme_scc.o
obj-$(CONFIG_BVME6000_SCC) += generic_serial.o vme_scc.o
obj-$(CONFIG_ROCKETPORT) += rocket.o
obj-$(CONFIG_SERIAL167) += serial167.o
obj-$(CONFIG_CYCLADES) += cyclades.o
obj-$(CONFIG_STALLION) += stallion.o
obj-$(CONFIG_ISTALLION) += istallion.o
obj-$(CONFIG_NOZOMI) += nozomi.o
obj-$(CONFIG_DIGIEPCA) += epca.o
obj-$(CONFIG_SPECIALIX) += specialix.o
obj-$(CONFIG_MOXA_INTELLIO) += moxa.o
obj-$(CONFIG_A2232) += ser_a2232.o generic_serial.o
obj-$(CONFIG_ATARI_DSP56K) += dsp56k.o
obj-$(CONFIG_MOXA_SMARTIO) += mxser.o
obj-$(CONFIG_COMPUTONE) += ip2/
obj-$(CONFIG_RISCOM8) += riscom8.o
obj-$(CONFIG_ISI) += isicom.o
obj-$(CONFIG_SYNCLINK) += synclink.o
obj-$(CONFIG_SYNCLINKMP) += synclinkmp.o
obj-$(CONFIG_SYNCLINK_GT) += synclink_gt.o
obj-$(CONFIG_N_HDLC) += n_hdlc.o
obj-$(CONFIG_AMIGA_BUILTIN_SERIAL) += amiserial.o
obj-$(CONFIG_SX) += sx.o generic_serial.o
obj-$(CONFIG_RIO) += rio/ generic_serial.o
obj-$(CONFIG_HVC_CONSOLE) += hvc_vio.o hvsi.o
obj-$(CONFIG_HVC_ISERIES) += hvc_iseries.o
obj-$(CONFIG_HVC_RTAS) += hvc_rtas.o
obj-$(CONFIG_HVC_BEAT) += hvc_beat.o
obj-$(CONFIG_HVC_DRIVER) += hvc_console.o
obj-$(CONFIG_HVC_IRQ) += hvc_irq.o
obj-$(CONFIG_HVC_XEN) += hvc_xen.o
obj-$(CONFIG_HVC_IUCV) += hvc_iucv.o
obj-$(CONFIG_HVC_UDBG) += hvc_udbg.o
obj-$(CONFIG_VIRTIO_CONSOLE) += virtio_console.o
obj-$(CONFIG_RAW_DRIVER) += raw.o
obj-$(CONFIG_SGI_SNSC) += snsc.o snsc_event.o
obj-$(CONFIG_MSPEC) += mspec.o
obj-$(CONFIG_MMTIMER) += mmtimer.o
obj-$(CONFIG_UV_MMTIMER) += uv_mmtimer.o
obj-$(CONFIG_VIOTAPE) += viotape.o
obj-$(CONFIG_HVCS) += hvcs.o
obj-$(CONFIG_IBM_BSR) += bsr.o
obj-$(CONFIG_SGI_MBCS) += mbcs.o
obj-$(CONFIG_BRIQ_PANEL) += briq_panel.o
obj-$(CONFIG_BFIN_OTP) += bfin-otp.o
obj-$(CONFIG_PRINTER) += lp.o
obj-$(CONFIG_APM_EMULATION) += apm-emulation.o
obj-$(CONFIG_DIAG_CHAR) += diag/
obj-$(CONFIG_DTLK) += dtlk.o
obj-$(CONFIG_R3964) += n_r3964.o
obj-$(CONFIG_APPLICOM) += applicom.o
obj-$(CONFIG_SONYPI) += sonypi.o
obj-$(CONFIG_RTC) += rtc.o
obj-$(CONFIG_HPET) += hpet.o
obj-$(CONFIG_GEN_RTC) += genrtc.o
obj-$(CONFIG_EFI_RTC) += efirtc.o
obj-$(CONFIG_DS1302) += ds1302.o
obj-$(CONFIG_XILINX_HWICAP) += xilinx_hwicap/
ifeq ($(CONFIG_GENERIC_NVRAM),y)
obj-$(CONFIG_NVRAM) += generic_nvram.o
else
obj-$(CONFIG_NVRAM) += nvram.o
endif
obj-$(CONFIG_TOSHIBA) += toshiba.o
obj-$(CONFIG_I8K) += i8k.o
obj-$(CONFIG_DS1620) += ds1620.o
obj-$(CONFIG_HW_RANDOM) += hw_random/
obj-$(CONFIG_PPDEV) += ppdev.o
obj-$(CONFIG_NWBUTTON) += nwbutton.o
obj-$(CONFIG_NWFLASH) += nwflash.o
obj-$(CONFIG_SCx200_GPIO) += scx200_gpio.o
obj-$(CONFIG_PC8736x_GPIO) += pc8736x_gpio.o
obj-$(CONFIG_NSC_GPIO) += nsc_gpio.o
obj-$(CONFIG_CS5535_GPIO) += cs5535_gpio.o
obj-$(CONFIG_GPIO_TB0219) += tb0219.o
obj-$(CONFIG_TELCLOCK) += tlclk.o
obj-$(CONFIG_MWAVE) += mwave/
obj-$(CONFIG_AGP) += agp/
obj-$(CONFIG_PCMCIA) += pcmcia/
obj-$(CONFIG_IPMI_HANDLER) += ipmi/
obj-$(CONFIG_HANGCHECK_TIMER) += hangcheck-timer.o
obj-$(CONFIG_TCG_TPM) += tpm/
obj-$(CONFIG_DCC_TTY) += dcc_tty.o
obj-$(CONFIG_PS3_FLASH) += ps3flash.o
obj-$(CONFIG_JS_RTC) += js-rtc.o
js-rtc-y = rtc.o
obj-$(CONFIG_MSM_ROTATOR) += msm_rotator.o
obj-$(CONFIG_MMC_GENERIC_CSDIO) += csdio.o
#---------------------------------------------
# Provide a char type driver of smd for FTM to communicate with modem.
# Added by Lo, Chien Chung (Paul Lo). 2009/06/16
obj-$(CONFIG_FTM_SMD) += ftm_smd/
#--------------------------------------------
# Added by CHHsieh, porting from 2030
obj-y += ftmgpio.o
# Files generated that shall be removed upon make clean
clean-files := consolemap_deftbl.c defkeymap.c
quiet_cmd_conmk = CONMK $@
cmd_conmk = scripts/conmakehash $< > $@
$(obj)/consolemap_deftbl.c: $(src)/$(FONTMAPFILE)
$(call cmd,conmk)
$(obj)/defkeymap.o: $(obj)/defkeymap.c
# Uncomment if you're changing the keymap and have an appropriate
# loadkeys version for the map. By default, we'll use the shipped
# versions.
# GENERATE_KEYMAP := 1
ifdef GENERATE_KEYMAP
$(obj)/defkeymap.c: $(obj)/%.c: $(src)/%.map
loadkeys --mktable $< > $@.tmp
sed -e 's/^static *//' $@.tmp > $@
rm $@.tmp
endif
|
using System;
using System.Collections.Generic;
using Server.Items;
namespace Server.Mobiles
{
public class SBWeaver: SBInfo
{
private List<GenericBuyInfo> m_BuyInfo = new InternalBuyInfo();
private IShopSellInfo m_SellInfo = new InternalSellInfo();
public SBWeaver()
{
}
public override IShopSellInfo SellInfo { get { return m_SellInfo; } }
public override List<GenericBuyInfo> BuyInfo { get { return m_BuyInfo; } }
public class InternalBuyInfo : List<GenericBuyInfo>
{
public InternalBuyInfo()
{
Add( new GenericBuyInfo( typeof( Dyes ), 8, 20, 0xFA9, 0 ) );
Add( new GenericBuyInfo( typeof( DyeTub ), 8, 20, 0xFAB, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1761, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1762, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1763, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1764, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf9B, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf9C, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf96, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf97, 0 ) );
Add( new GenericBuyInfo( typeof( DarkYarn ), 18, 20, 0xE1D, 0 ) );
Add( new GenericBuyInfo( typeof( LightYarn ), 18, 20, 0xE1E, 0 ) );
Add( new GenericBuyInfo( typeof( LightYarnUnraveled ), 18, 20, 0xE1F, 0 ) );
Add( new GenericBuyInfo( typeof( Scissors ), 11, 20, 0xF9F, 0 ) );
}
}
public class InternalSellInfo : GenericSellInfo
{
public InternalSellInfo()
{
Add( typeof( Scissors ), 6 );
Add( typeof( Dyes ), 4 );
Add( typeof( DyeTub ), 4 );
Add( typeof( UncutCloth ), 1 );
Add( typeof( BoltOfCloth ), 50 );
Add( typeof( LightYarnUnraveled ), 9 );
Add( typeof( LightYarn ), 9 );
Add( typeof( DarkYarn ), 9 );
}
}
}
} |
/*
* This file is part of the Chelsio T4 Ethernet driver for Linux.
*
* Copyright (c) 2003-2016 Chelsio Communications, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/delay.h>
#include "cxgb4.h"
#include "t4_regs.h"
#include "t4_values.h"
#include "t4fw_api.h"
#include "t4fw_version.h"
/**
* t4_wait_op_done_val - wait until an operation is completed
* @adapter: the adapter performing the operation
* @reg: the register to check for completion
* @mask: a single-bit field within @reg that indicates completion
* @polarity: the value of the field when the operation is completed
* @attempts: number of check iterations
* @delay: delay in usecs between iterations
* @valp: where to store the value of the register at completion time
*
* Wait until an operation is completed by checking a bit in a register
* up to @attempts times. If @valp is not NULL the value of the register
* at the time it indicated completion is stored there. Returns 0 if the
* operation completes and -EAGAIN otherwise.
*/
static int t4_wait_op_done_val(struct adapter *adapter, int reg, u32 mask,
int polarity, int attempts, int delay, u32 *valp)
{
while (1) {
u32 val = t4_read_reg(adapter, reg);
if (!!(val & mask) == polarity) {
if (valp)
*valp = val;
return 0;
}
if (--attempts == 0)
return -EAGAIN;
if (delay)
udelay(delay);
}
}
static inline int t4_wait_op_done(struct adapter *adapter, int reg, u32 mask,
int polarity, int attempts, int delay)
{
return t4_wait_op_done_val(adapter, reg, mask, polarity, attempts,
delay, NULL);
}
/**
* t4_set_reg_field - set a register field to a value
* @adapter: the adapter to program
* @addr: the register address
* @mask: specifies the portion of the register to modify
* @val: the new value for the register field
*
* Sets a register field specified by the supplied mask to the
* given value.
*/
void t4_set_reg_field(struct adapter *adapter, unsigned int addr, u32 mask,
u32 val)
{
u32 v = t4_read_reg(adapter, addr) & ~mask;
t4_write_reg(adapter, addr, v | val);
(void) t4_read_reg(adapter, addr); /* flush */
}
/**
* t4_read_indirect - read indirectly addressed registers
* @adap: the adapter
* @addr_reg: register holding the indirect address
* @data_reg: register holding the value of the indirect register
* @vals: where the read register values are stored
* @nregs: how many indirect registers to read
* @start_idx: index of first indirect register to read
*
* Reads registers that are accessed indirectly through an address/data
* register pair.
*/
void t4_read_indirect(struct adapter *adap, unsigned int addr_reg,
unsigned int data_reg, u32 *vals,
unsigned int nregs, unsigned int start_idx)
{
while (nregs--) {
t4_write_reg(adap, addr_reg, start_idx);
*vals++ = t4_read_reg(adap, data_reg);
start_idx++;
}
}
/**
* t4_write_indirect - write indirectly addressed registers
* @adap: the adapter
* @addr_reg: register holding the indirect addresses
* @data_reg: register holding the value for the indirect registers
* @vals: values to write
* @nregs: how many indirect registers to write
* @start_idx: address of first indirect register to write
*
* Writes a sequential block of registers that are accessed indirectly
* through an address/data register pair.
*/
void t4_write_indirect(struct adapter *adap, unsigned int addr_reg,
unsigned int data_reg, const u32 *vals,
unsigned int nregs, unsigned int start_idx)
{
while (nregs--) {
t4_write_reg(adap, addr_reg, start_idx++);
t4_write_reg(adap, data_reg, *vals++);
}
}
/*
* Read a 32-bit PCI Configuration Space register via the PCI-E backdoor
* mechanism. This guarantees that we get the real value even if we're
* operating within a Virtual Machine and the Hypervisor is trapping our
* Configuration Space accesses.
*/
void t4_hw_pci_read_cfg4(struct adapter *adap, int reg, u32 *val)
{
u32 req = FUNCTION_V(adap->pf) | REGISTER_V(reg);
if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
req |= ENABLE_F;
else
req |= T6_ENABLE_F;
if (is_t4(adap->params.chip))
req |= LOCALCFG_F;
t4_write_reg(adap, PCIE_CFG_SPACE_REQ_A, req);
*val = t4_read_reg(adap, PCIE_CFG_SPACE_DATA_A);
/* Reset ENABLE to 0 so reads of PCIE_CFG_SPACE_DATA won't cause a
* Configuration Space read. (None of the other fields matter when
* ENABLE is 0 so a simple register write is easier than a
* read-modify-write via t4_set_reg_field().)
*/
t4_write_reg(adap, PCIE_CFG_SPACE_REQ_A, 0);
}
/*
* t4_report_fw_error - report firmware error
* @adap: the adapter
*
* The adapter firmware can indicate error conditions to the host.
* If the firmware has indicated an error, print out the reason for
* the firmware error.
*/
static void t4_report_fw_error(struct adapter *adap)
{
static const char *const reason[] = {
"Crash", /* PCIE_FW_EVAL_CRASH */
"During Device Preparation", /* PCIE_FW_EVAL_PREP */
"During Device Configuration", /* PCIE_FW_EVAL_CONF */
"During Device Initialization", /* PCIE_FW_EVAL_INIT */
"Unexpected Event", /* PCIE_FW_EVAL_UNEXPECTEDEVENT */
"Insufficient Airflow", /* PCIE_FW_EVAL_OVERHEAT */
"Device Shutdown", /* PCIE_FW_EVAL_DEVICESHUTDOWN */
"Reserved", /* reserved */
};
u32 pcie_fw;
pcie_fw = t4_read_reg(adap, PCIE_FW_A);
if (pcie_fw & PCIE_FW_ERR_F) {
dev_err(adap->pdev_dev, "Firmware reports adapter error: %s\n",
reason[PCIE_FW_EVAL_G(pcie_fw)]);
adap->flags &= ~CXGB4_FW_OK;
}
}
/*
* Get the reply to a mailbox command and store it in @rpl in big-endian order.
*/
static void get_mbox_rpl(struct adapter *adap, __be64 *rpl, int nflit,
u32 mbox_addr)
{
for ( ; nflit; nflit--, mbox_addr += 8)
*rpl++ = cpu_to_be64(t4_read_reg64(adap, mbox_addr));
}
/*
* Handle a FW assertion reported in a mailbox.
*/
static void fw_asrt(struct adapter *adap, u32 mbox_addr)
{
struct fw_debug_cmd asrt;
get_mbox_rpl(adap, (__be64 *)&asrt, sizeof(asrt) / 8, mbox_addr);
dev_alert(adap->pdev_dev,
"FW assertion at %.16s:%u, val0 %#x, val1 %#x\n",
asrt.u.assert.filename_0_7, be32_to_cpu(asrt.u.assert.line),
be32_to_cpu(asrt.u.assert.x), be32_to_cpu(asrt.u.assert.y));
}
/**
* t4_record_mbox - record a Firmware Mailbox Command/Reply in the log
* @adapter: the adapter
* @cmd: the Firmware Mailbox Command or Reply
* @size: command length in bytes
* @access: the time (ms) needed to access the Firmware Mailbox
* @execute: the time (ms) the command spent being executed
*/
static void t4_record_mbox(struct adapter *adapter,
const __be64 *cmd, unsigned int size,
int access, int execute)
{
struct mbox_cmd_log *log = adapter->mbox_log;
struct mbox_cmd *entry;
int i;
entry = mbox_cmd_log_entry(log, log->cursor++);
if (log->cursor == log->size)
log->cursor = 0;
for (i = 0; i < size / 8; i++)
entry->cmd[i] = be64_to_cpu(cmd[i]);
while (i < MBOX_LEN / 8)
entry->cmd[i++] = 0;
entry->timestamp = jiffies;
entry->seqno = log->seqno++;
entry->access = access;
entry->execute = execute;
}
/**
* t4_wr_mbox_meat_timeout - send a command to FW through the given mailbox
* @adap: the adapter
* @mbox: index of the mailbox to use
* @cmd: the command to write
* @size: command length in bytes
* @rpl: where to optionally store the reply
* @sleep_ok: if true we may sleep while awaiting command completion
* @timeout: time to wait for command to finish before timing out
*
* Sends the given command to FW through the selected mailbox and waits
* for the FW to execute the command. If @rpl is not %NULL it is used to
* store the FW's reply to the command. The command and its optional
* reply are of the same length. FW can take up to %FW_CMD_MAX_TIMEOUT ms
* to respond. @sleep_ok determines whether we may sleep while awaiting
* the response. If sleeping is allowed we use progressive backoff
* otherwise we spin.
*
* The return value is 0 on success or a negative errno on failure. A
* failure can happen either because we are not able to execute the
* command or FW executes it but signals an error. In the latter case
* the return value is the error code indicated by FW (negated).
*/
int t4_wr_mbox_meat_timeout(struct adapter *adap, int mbox, const void *cmd,
int size, void *rpl, bool sleep_ok, int timeout)
{
static const int delay[] = {
1, 1, 3, 5, 10, 10, 20, 50, 100, 200
};
struct mbox_list entry;
u16 access = 0;
u16 execute = 0;
u32 v;
u64 res;
int i, ms, delay_idx, ret;
const __be64 *p = cmd;
u32 data_reg = PF_REG(mbox, CIM_PF_MAILBOX_DATA_A);
u32 ctl_reg = PF_REG(mbox, CIM_PF_MAILBOX_CTRL_A);
__be64 cmd_rpl[MBOX_LEN / 8];
u32 pcie_fw;
if ((size & 15) || size > MBOX_LEN)
return -EINVAL;
/*
* If the device is off-line, as in EEH, commands will time out.
* Fail them early so we don't waste time waiting.
*/
if (adap->pdev->error_state != pci_channel_io_normal)
return -EIO;
/* If we have a negative timeout, that implies that we can't sleep. */
if (timeout < 0) {
sleep_ok = false;
timeout = -timeout;
}
/* Queue ourselves onto the mailbox access list. When our entry is at
* the front of the list, we have rights to access the mailbox. So we
* wait [for a while] till we're at the front [or bail out with an
* EBUSY] ...
*/
spin_lock_bh(&adap->mbox_lock);
list_add_tail(&entry.list, &adap->mlist.list);
spin_unlock_bh(&adap->mbox_lock);
delay_idx = 0;
ms = delay[0];
for (i = 0; ; i += ms) {
/* If we've waited too long, return a busy indication. This
* really ought to be based on our initial position in the
* mailbox access list but this is a start. We very rarely
* contend on access to the mailbox ...
*/
pcie_fw = t4_read_reg(adap, PCIE_FW_A);
if (i > FW_CMD_MAX_TIMEOUT || (pcie_fw & PCIE_FW_ERR_F)) {
spin_lock_bh(&adap->mbox_lock);
list_del(&entry.list);
spin_unlock_bh(&adap->mbox_lock);
ret = (pcie_fw & PCIE_FW_ERR_F) ? -ENXIO : -EBUSY;
t4_record_mbox(adap, cmd, size, access, ret);
return ret;
}
/* If we're at the head, break out and start the mailbox
* protocol.
*/
if (list_first_entry(&adap->mlist.list, struct mbox_list,
list) == &entry)
break;
/* Delay for a bit before checking again ... */
if (sleep_ok) {
ms = delay[delay_idx]; /* last element may repeat */
if (delay_idx < ARRAY_SIZE(delay) - 1)
delay_idx++;
msleep(ms);
} else {
mdelay(ms);
}
}
/* Loop trying to get ownership of the mailbox. Return an error
* if we can't gain ownership.
*/
v = MBOWNER_G(t4_read_reg(adap, ctl_reg));
for (i = 0; v == MBOX_OWNER_NONE && i < 3; i++)
v = MBOWNER_G(t4_read_reg(adap, ctl_reg));
if (v != MBOX_OWNER_DRV) {
spin_lock_bh(&adap->mbox_lock);
list_del(&entry.list);
spin_unlock_bh(&adap->mbox_lock);
ret = (v == MBOX_OWNER_FW) ? -EBUSY : -ETIMEDOUT;
t4_record_mbox(adap, cmd, size, access, ret);
return ret;
}
/* Copy in the new mailbox command and send it on its way ... */
t4_record_mbox(adap, cmd, size, access, 0);
for (i = 0; i < size; i += 8)
t4_write_reg64(adap, data_reg + i, be64_to_cpu(*p++));
t4_write_reg(adap, ctl_reg, MBMSGVALID_F | MBOWNER_V(MBOX_OWNER_FW));
t4_read_reg(adap, ctl_reg); /* flush write */
delay_idx = 0;
ms = delay[0];
for (i = 0;
!((pcie_fw = t4_read_reg(adap, PCIE_FW_A)) & PCIE_FW_ERR_F) &&
i < timeout;
i += ms) {
if (sleep_ok) {
ms = delay[delay_idx]; /* last element may repeat */
if (delay_idx < ARRAY_SIZE(delay) - 1)
delay_idx++;
msleep(ms);
} else
mdelay(ms);
v = t4_read_reg(adap, ctl_reg);
if (MBOWNER_G(v) == MBOX_OWNER_DRV) {
if (!(v & MBMSGVALID_F)) {
t4_write_reg(adap, ctl_reg, 0);
continue;
}
get_mbox_rpl(adap, cmd_rpl, MBOX_LEN / 8, data_reg);
res = be64_to_cpu(cmd_rpl[0]);
if (FW_CMD_OP_G(res >> 32) == FW_DEBUG_CMD) {
fw_asrt(adap, data_reg);
res = FW_CMD_RETVAL_V(EIO);
} else if (rpl) {
memcpy(rpl, cmd_rpl, size);
}
t4_write_reg(adap, ctl_reg, 0);
execute = i + ms;
t4_record_mbox(adap, cmd_rpl,
MBOX_LEN, access, execute);
spin_lock_bh(&adap->mbox_lock);
list_del(&entry.list);
spin_unlock_bh(&adap->mbox_lock);
return -FW_CMD_RETVAL_G((int)res);
}
}
ret = (pcie_fw & PCIE_FW_ERR_F) ? -ENXIO : -ETIMEDOUT;
t4_record_mbox(adap, cmd, size, access, ret);
dev_err(adap->pdev_dev, "command %#x in mailbox %d timed out\n",
*(const u8 *)cmd, mbox);
t4_report_fw_error(adap);
spin_lock_bh(&adap->mbox_lock);
list_del(&entry.list);
spin_unlock_bh(&adap->mbox_lock);
t4_fatal_err(adap);
return ret;
}
int t4_wr_mbox_meat(struct adapter *adap, int mbox, const void *cmd, int size,
void *rpl, bool sleep_ok)
{
return t4_wr_mbox_meat_timeout(adap, mbox, cmd, size, rpl, sleep_ok,
FW_CMD_MAX_TIMEOUT);
}
static int t4_edc_err_read(struct adapter *adap, int idx)
{
u32 edc_ecc_err_addr_reg;
u32 rdata_reg;
if (is_t4(adap->params.chip)) {
CH_WARN(adap, "%s: T4 NOT supported.\n", __func__);
return 0;
}
if (idx != 0 && idx != 1) {
CH_WARN(adap, "%s: idx %d NOT supported.\n", __func__, idx);
return 0;
}
edc_ecc_err_addr_reg = EDC_T5_REG(EDC_H_ECC_ERR_ADDR_A, idx);
rdata_reg = EDC_T5_REG(EDC_H_BIST_STATUS_RDATA_A, idx);
CH_WARN(adap,
"edc%d err addr 0x%x: 0x%x.\n",
idx, edc_ecc_err_addr_reg,
t4_read_reg(adap, edc_ecc_err_addr_reg));
CH_WARN(adap,
"bist: 0x%x, status %llx %llx %llx %llx %llx %llx %llx %llx %llx.\n",
rdata_reg,
(unsigned long long)t4_read_reg64(adap, rdata_reg),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 8),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 16),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 24),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 32),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 40),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 48),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 56),
(unsigned long long)t4_read_reg64(adap, rdata_reg + 64));
return 0;
}
/**
* t4_memory_rw_init - Get memory window relative offset, base, and size.
* @adap: the adapter
* @win: PCI-E Memory Window to use
* @mtype: memory type: MEM_EDC0, MEM_EDC1, MEM_HMA or MEM_MC
* @mem_off: memory relative offset with respect to @mtype.
* @mem_base: configured memory base address.
* @mem_aperture: configured memory window aperture.
*
* Get the configured memory window's relative offset, base, and size.
*/
int t4_memory_rw_init(struct adapter *adap, int win, int mtype, u32 *mem_off,
u32 *mem_base, u32 *mem_aperture)
{
u32 edc_size, mc_size, mem_reg;
/* Offset into the region of memory which is being accessed
* MEM_EDC0 = 0
* MEM_EDC1 = 1
* MEM_MC = 2 -- MEM_MC for chips with only 1 memory controller
* MEM_MC1 = 3 -- for chips with 2 memory controllers (e.g. T5)
* MEM_HMA = 4
*/
edc_size = EDRAM0_SIZE_G(t4_read_reg(adap, MA_EDRAM0_BAR_A));
if (mtype == MEM_HMA) {
*mem_off = 2 * (edc_size * 1024 * 1024);
} else if (mtype != MEM_MC1) {
*mem_off = (mtype * (edc_size * 1024 * 1024));
} else {
mc_size = EXT_MEM0_SIZE_G(t4_read_reg(adap,
MA_EXT_MEMORY0_BAR_A));
*mem_off = (MEM_MC0 * edc_size + mc_size) * 1024 * 1024;
}
/* Each PCI-E Memory Window is programmed with a window size -- or
* "aperture" -- which controls the granularity of its mapping onto
* adapter memory. We need to grab that aperture in order to know
* how to use the specified window. The window is also programmed
* with the base address of the Memory Window in BAR0's address
* space. For T4 this is an absolute PCI-E Bus Address. For T5
* the address is relative to BAR0.
*/
mem_reg = t4_read_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN_A,
win));
/* a dead adapter will return 0xffffffff for PIO reads */
if (mem_reg == 0xffffffff)
return -ENXIO;
*mem_aperture = 1 << (WINDOW_G(mem_reg) + WINDOW_SHIFT_X);
*mem_base = PCIEOFST_G(mem_reg) << PCIEOFST_SHIFT_X;
if (is_t4(adap->params.chip))
*mem_base -= adap->t4_bar0;
return 0;
}
/**
* t4_memory_update_win - Move memory window to specified address.
* @adap: the adapter
* @win: PCI-E Memory Window to use
* @addr: location to move.
*
* Move memory window to specified address.
*/
void t4_memory_update_win(struct adapter *adap, int win, u32 addr)
{
t4_write_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_OFFSET_A, win),
addr);
/* Read it back to ensure that changes propagate before we
* attempt to use the new value.
*/
t4_read_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_OFFSET_A, win));
}
/**
* t4_memory_rw_residual - Read/Write residual data.
* @adap: the adapter
* @off: relative offset within residual to start read/write.
* @addr: address within indicated memory type.
* @buf: host memory buffer
* @dir: direction of transfer T4_MEMORY_READ (1) or T4_MEMORY_WRITE (0)
*
* Read/Write residual data less than 32-bits.
*/
void t4_memory_rw_residual(struct adapter *adap, u32 off, u32 addr, u8 *buf,
int dir)
{
union {
u32 word;
char byte[4];
} last;
unsigned char *bp;
int i;
if (dir == T4_MEMORY_READ) {
last.word = le32_to_cpu((__force __le32)
t4_read_reg(adap, addr));
for (bp = (unsigned char *)buf, i = off; i < 4; i++)
bp[i] = last.byte[i];
} else {
last.word = *buf;
for (i = off; i < 4; i++)
last.byte[i] = 0;
t4_write_reg(adap, addr,
(__force u32)cpu_to_le32(last.word));
}
}
/**
* t4_memory_rw - read/write EDC 0, EDC 1 or MC via PCIE memory window
* @adap: the adapter
* @win: PCI-E Memory Window to use
* @mtype: memory type: MEM_EDC0, MEM_EDC1 or MEM_MC
* @addr: address within indicated memory type
* @len: amount of memory to transfer
* @hbuf: host memory buffer
* @dir: direction of transfer T4_MEMORY_READ (1) or T4_MEMORY_WRITE (0)
*
* Reads/writes an [almost] arbitrary memory region in the firmware: the
* firmware memory address and host buffer must be aligned on 32-bit
* boundaries; the length may be arbitrary. The memory is transferred as
* a raw byte sequence from/to the firmware's memory. If this memory
* contains data structures which contain multi-byte integers, it's the
* caller's responsibility to perform appropriate byte order conversions.
*/
int t4_memory_rw(struct adapter *adap, int win, int mtype, u32 addr,
u32 len, void *hbuf, int dir)
{
u32 pos, offset, resid, memoffset;
u32 win_pf, mem_aperture, mem_base;
u32 *buf;
int ret;
/* Argument sanity checks ...
*/
if (addr & 0x3 || (uintptr_t)hbuf & 0x3)
return -EINVAL;
buf = (u32 *)hbuf;
/* It's convenient to be able to handle lengths which aren't a
* multiple of 32-bits because we often end up transferring files to
* the firmware. So we'll handle that by normalizing the length here
* and then handling any residual transfer at the end.
*/
resid = len & 0x3;
len -= resid;
ret = t4_memory_rw_init(adap, win, mtype, &memoffset, &mem_base,
&mem_aperture);
if (ret)
return ret;
/* Determine the PCIE_MEM_ACCESS_OFFSET */
addr = addr + memoffset;
win_pf = is_t4(adap->params.chip) ? 0 : PFNUM_V(adap->pf);
/* Calculate our initial PCI-E Memory Window Position and Offset into
* that Window.
*/
pos = addr & ~(mem_aperture - 1);
offset = addr - pos;
/* Set up initial PCI-E Memory Window to cover the start of our
* transfer.
*/
t4_memory_update_win(adap, win, pos | win_pf);
/* Transfer data to/from the adapter as long as there's an integral
* number of 32-bit transfers to complete.
*
* A note on Endianness issues:
*
* The "register" reads and writes below from/to the PCI-E Memory
* Window invoke the standard adapter Big-Endian to PCI-E Link
* Little-Endian "swizzel." As a result, if we have the following
* data in adapter memory:
*
* Memory: ... | b0 | b1 | b2 | b3 | ...
* Address: i+0 i+1 i+2 i+3
*
* Then a read of the adapter memory via the PCI-E Memory Window
* will yield:
*
* x = readl(i)
* 31 0
* [ b3 | b2 | b1 | b0 ]
*
* If this value is stored into local memory on a Little-Endian system
* it will show up correctly in local memory as:
*
* ( ..., b0, b1, b2, b3, ... )
*
* But on a Big-Endian system, the store will show up in memory
* incorrectly swizzled as:
*
* ( ..., b3, b2, b1, b0, ... )
*
* So we need to account for this in the reads and writes to the
* PCI-E Memory Window below by undoing the register read/write
* swizzels.
*/
while (len > 0) {
if (dir == T4_MEMORY_READ)
*buf++ = le32_to_cpu((__force __le32)t4_read_reg(adap,
mem_base + offset));
else
t4_write_reg(adap, mem_base + offset,
(__force u32)cpu_to_le32(*buf++));
offset += sizeof(__be32);
len -= sizeof(__be32);
/* If we've reached the end of our current window aperture,
* move the PCI-E Memory Window on to the next. Note that
* doing this here after "len" may be 0 allows us to set up
* the PCI-E Memory Window for a possible final residual
* transfer below ...
*/
if (offset == mem_aperture) {
pos += mem_aperture;
offset = 0;
t4_memory_update_win(adap, win, pos | win_pf);
}
}
/* If the original transfer had a length which wasn't a multiple of
* 32-bits, now's where we need to finish off the transfer of the
* residual amount. The PCI-E Memory Window has already been moved
* above (if necessary) to cover this final transfer.
*/
if (resid)
t4_memory_rw_residual(adap, resid, mem_base + offset,
(u8 *)buf, dir);
return 0;
}
/* Return the specified PCI-E Configuration Space register from our Physical
* Function. We try first via a Firmware LDST Command since we prefer to let
* the firmware own all of these registers, but if that fails we go for it
* directly ourselves.
*/
u32 t4_read_pcie_cfg4(struct adapter *adap, int reg)
{
u32 val, ldst_addrspace;
/* If fw_attach != 0, construct and send the Firmware LDST Command to
* retrieve the specified PCI-E Configuration Space register.
*/
struct fw_ldst_cmd ldst_cmd;
int ret;
memset(&ldst_cmd, 0, sizeof(ldst_cmd));
ldst_addrspace = FW_LDST_CMD_ADDRSPACE_V(FW_LDST_ADDRSPC_FUNC_PCIE);
ldst_cmd.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_READ_F |
ldst_addrspace);
ldst_cmd.cycles_to_len16 = cpu_to_be32(FW_LEN16(ldst_cmd));
ldst_cmd.u.pcie.select_naccess = FW_LDST_CMD_NACCESS_V(1);
ldst_cmd.u.pcie.ctrl_to_fn =
(FW_LDST_CMD_LC_F | FW_LDST_CMD_FN_V(adap->pf));
ldst_cmd.u.pcie.r = reg;
/* If the LDST Command succeeds, return the result, otherwise
* fall through to reading it directly ourselves ...
*/
ret = t4_wr_mbox(adap, adap->mbox, &ldst_cmd, sizeof(ldst_cmd),
&ldst_cmd);
if (ret == 0)
val = be32_to_cpu(ldst_cmd.u.pcie.data[0]);
else
/* Read the desired Configuration Space register via the PCI-E
* Backdoor mechanism.
*/
t4_hw_pci_read_cfg4(adap, reg, &val);
return val;
}
/* Get the window based on base passed to it.
* Window aperture is currently unhandled, but there is no use case for it
* right now
*/
static u32 t4_get_window(struct adapter *adap, u32 pci_base, u64 pci_mask,
u32 memwin_base)
{
u32 ret;
if (is_t4(adap->params.chip)) {
u32 bar0;
/* Truncation intentional: we only read the bottom 32-bits of
* the 64-bit BAR0/BAR1 ... We use the hardware backdoor
* mechanism to read BAR0 instead of using
* pci_resource_start() because we could be operating from
* within a Virtual Machine which is trapping our accesses to
* our Configuration Space and we need to set up the PCI-E
* Memory Window decoders with the actual addresses which will
* be coming across the PCI-E link.
*/
bar0 = t4_read_pcie_cfg4(adap, pci_base);
bar0 &= pci_mask;
adap->t4_bar0 = bar0;
ret = bar0 + memwin_base;
} else {
/* For T5, only relative offset inside the PCIe BAR is passed */
ret = memwin_base;
}
return ret;
}
/* Get the default utility window (win0) used by everyone */
u32 t4_get_util_window(struct adapter *adap)
{
return t4_get_window(adap, PCI_BASE_ADDRESS_0,
PCI_BASE_ADDRESS_MEM_MASK, MEMWIN0_BASE);
}
/* Set up memory window for accessing adapter memory ranges. (Read
* back MA register to ensure that changes propagate before we attempt
* to use the new values.)
*/
void t4_setup_memwin(struct adapter *adap, u32 memwin_base, u32 window)
{
t4_write_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN_A, window),
memwin_base | BIR_V(0) |
WINDOW_V(ilog2(MEMWIN0_APERTURE) - WINDOW_SHIFT_X));
t4_read_reg(adap,
PCIE_MEM_ACCESS_REG(PCIE_MEM_ACCESS_BASE_WIN_A, window));
}
/**
* t4_get_regs_len - return the size of the chips register set
* @adapter: the adapter
*
* Returns the size of the chip's BAR0 register space.
*/
unsigned int t4_get_regs_len(struct adapter *adapter)
{
unsigned int chip_version = CHELSIO_CHIP_VERSION(adapter->params.chip);
switch (chip_version) {
case CHELSIO_T4:
return T4_REGMAP_SIZE;
case CHELSIO_T5:
case CHELSIO_T6:
return T5_REGMAP_SIZE;
}
dev_err(adapter->pdev_dev,
"Unsupported chip version %d\n", chip_version);
return 0;
}
/**
* t4_get_regs - read chip registers into provided buffer
* @adap: the adapter
* @buf: register buffer
* @buf_size: size (in bytes) of register buffer
*
* If the provided register buffer isn't large enough for the chip's
* full register range, the register dump will be truncated to the
* register buffer's size.
*/
void t4_get_regs(struct adapter *adap, void *buf, size_t buf_size)
{
static const unsigned int t4_reg_ranges[] = {
0x1008, 0x1108,
0x1180, 0x1184,
0x1190, 0x1194,
0x11a0, 0x11a4,
0x11b0, 0x11b4,
0x11fc, 0x123c,
0x1300, 0x173c,
0x1800, 0x18fc,
0x3000, 0x30d8,
0x30e0, 0x30e4,
0x30ec, 0x5910,
0x5920, 0x5924,
0x5960, 0x5960,
0x5968, 0x5968,
0x5970, 0x5970,
0x5978, 0x5978,
0x5980, 0x5980,
0x5988, 0x5988,
0x5990, 0x5990,
0x5998, 0x5998,
0x59a0, 0x59d4,
0x5a00, 0x5ae0,
0x5ae8, 0x5ae8,
0x5af0, 0x5af0,
0x5af8, 0x5af8,
0x6000, 0x6098,
0x6100, 0x6150,
0x6200, 0x6208,
0x6240, 0x6248,
0x6280, 0x62b0,
0x62c0, 0x6338,
0x6370, 0x638c,
0x6400, 0x643c,
0x6500, 0x6524,
0x6a00, 0x6a04,
0x6a14, 0x6a38,
0x6a60, 0x6a70,
0x6a78, 0x6a78,
0x6b00, 0x6b0c,
0x6b1c, 0x6b84,
0x6bf0, 0x6bf8,
0x6c00, 0x6c0c,
0x6c1c, 0x6c84,
0x6cf0, 0x6cf8,
0x6d00, 0x6d0c,
0x6d1c, 0x6d84,
0x6df0, 0x6df8,
0x6e00, 0x6e0c,
0x6e1c, 0x6e84,
0x6ef0, 0x6ef8,
0x6f00, 0x6f0c,
0x6f1c, 0x6f84,
0x6ff0, 0x6ff8,
0x7000, 0x700c,
0x701c, 0x7084,
0x70f0, 0x70f8,
0x7100, 0x710c,
0x711c, 0x7184,
0x71f0, 0x71f8,
0x7200, 0x720c,
0x721c, 0x7284,
0x72f0, 0x72f8,
0x7300, 0x730c,
0x731c, 0x7384,
0x73f0, 0x73f8,
0x7400, 0x7450,
0x7500, 0x7530,
0x7600, 0x760c,
0x7614, 0x761c,
0x7680, 0x76cc,
0x7700, 0x7798,
0x77c0, 0x77fc,
0x7900, 0x79fc,
0x7b00, 0x7b58,
0x7b60, 0x7b84,
0x7b8c, 0x7c38,
0x7d00, 0x7d38,
0x7d40, 0x7d80,
0x7d8c, 0x7ddc,
0x7de4, 0x7e04,
0x7e10, 0x7e1c,
0x7e24, 0x7e38,
0x7e40, 0x7e44,
0x7e4c, 0x7e78,
0x7e80, 0x7ea4,
0x7eac, 0x7edc,
0x7ee8, 0x7efc,
0x8dc0, 0x8e04,
0x8e10, 0x8e1c,
0x8e30, 0x8e78,
0x8ea0, 0x8eb8,
0x8ec0, 0x8f6c,
0x8fc0, 0x9008,
0x9010, 0x9058,
0x9060, 0x9060,
0x9068, 0x9074,
0x90fc, 0x90fc,
0x9400, 0x9408,
0x9410, 0x9458,
0x9600, 0x9600,
0x9608, 0x9638,
0x9640, 0x96bc,
0x9800, 0x9808,
0x9820, 0x983c,
0x9850, 0x9864,
0x9c00, 0x9c6c,
0x9c80, 0x9cec,
0x9d00, 0x9d6c,
0x9d80, 0x9dec,
0x9e00, 0x9e6c,
0x9e80, 0x9eec,
0x9f00, 0x9f6c,
0x9f80, 0x9fec,
0xd004, 0xd004,
0xd010, 0xd03c,
0xdfc0, 0xdfe0,
0xe000, 0xea7c,
0xf000, 0x11110,
0x11118, 0x11190,
0x19040, 0x1906c,
0x19078, 0x19080,
0x1908c, 0x190e4,
0x190f0, 0x190f8,
0x19100, 0x19110,
0x19120, 0x19124,
0x19150, 0x19194,
0x1919c, 0x191b0,
0x191d0, 0x191e8,
0x19238, 0x1924c,
0x193f8, 0x1943c,
0x1944c, 0x19474,
0x19490, 0x194e0,
0x194f0, 0x194f8,
0x19800, 0x19c08,
0x19c10, 0x19c90,
0x19ca0, 0x19ce4,
0x19cf0, 0x19d40,
0x19d50, 0x19d94,
0x19da0, 0x19de8,
0x19df0, 0x19e40,
0x19e50, 0x19e90,
0x19ea0, 0x19f4c,
0x1a000, 0x1a004,
0x1a010, 0x1a06c,
0x1a0b0, 0x1a0e4,
0x1a0ec, 0x1a0f4,
0x1a100, 0x1a108,
0x1a114, 0x1a120,
0x1a128, 0x1a130,
0x1a138, 0x1a138,
0x1a190, 0x1a1c4,
0x1a1fc, 0x1a1fc,
0x1e040, 0x1e04c,
0x1e284, 0x1e28c,
0x1e2c0, 0x1e2c0,
0x1e2e0, 0x1e2e0,
0x1e300, 0x1e384,
0x1e3c0, 0x1e3c8,
0x1e440, 0x1e44c,
0x1e684, 0x1e68c,
0x1e6c0, 0x1e6c0,
0x1e6e0, 0x1e6e0,
0x1e700, 0x1e784,
0x1e7c0, 0x1e7c8,
0x1e840, 0x1e84c,
0x1ea84, 0x1ea8c,
0x1eac0, 0x1eac0,
0x1eae0, 0x1eae0,
0x1eb00, 0x1eb84,
0x1ebc0, 0x1ebc8,
0x1ec40, 0x1ec4c,
0x1ee84, 0x1ee8c,
0x1eec0, 0x1eec0,
0x1eee0, 0x1eee0,
0x1ef00, 0x1ef84,
0x1efc0, 0x1efc8,
0x1f040, 0x1f04c,
0x1f284, 0x1f28c,
0x1f2c0, 0x1f2c0,
0x1f2e0, 0x1f2e0,
0x1f300, 0x1f384,
0x1f3c0, 0x1f3c8,
0x1f440, 0x1f44c,
0x1f684, 0x1f68c,
0x1f6c0, 0x1f6c0,
0x1f6e0, 0x1f6e0,
0x1f700, 0x1f784,
0x1f7c0, 0x1f7c8,
0x1f840, 0x1f84c,
0x1fa84, 0x1fa8c,
0x1fac0, 0x1fac0,
0x1fae0, 0x1fae0,
0x1fb00, 0x1fb84,
0x1fbc0, 0x1fbc8,
0x1fc40, 0x1fc4c,
0x1fe84, 0x1fe8c,
0x1fec0, 0x1fec0,
0x1fee0, 0x1fee0,
0x1ff00, 0x1ff84,
0x1ffc0, 0x1ffc8,
0x20000, 0x2002c,
0x20100, 0x2013c,
0x20190, 0x201a0,
0x201a8, 0x201b8,
0x201c4, 0x201c8,
0x20200, 0x20318,
0x20400, 0x204b4,
0x204c0, 0x20528,
0x20540, 0x20614,
0x21000, 0x21040,
0x2104c, 0x21060,
0x210c0, 0x210ec,
0x21200, 0x21268,
0x21270, 0x21284,
0x212fc, 0x21388,
0x21400, 0x21404,
0x21500, 0x21500,
0x21510, 0x21518,
0x2152c, 0x21530,
0x2153c, 0x2153c,
0x21550, 0x21554,
0x21600, 0x21600,
0x21608, 0x2161c,
0x21624, 0x21628,
0x21630, 0x21634,
0x2163c, 0x2163c,
0x21700, 0x2171c,
0x21780, 0x2178c,
0x21800, 0x21818,
0x21820, 0x21828,
0x21830, 0x21848,
0x21850, 0x21854,
0x21860, 0x21868,
0x21870, 0x21870,
0x21878, 0x21898,
0x218a0, 0x218a8,
0x218b0, 0x218c8,
0x218d0, 0x218d4,
0x218e0, 0x218e8,
0x218f0, 0x218f0,
0x218f8, 0x21a18,
0x21a20, 0x21a28,
0x21a30, 0x21a48,
0x21a50, 0x21a54,
0x21a60, 0x21a68,
0x21a70, 0x21a70,
0x21a78, 0x21a98,
0x21aa0, 0x21aa8,
0x21ab0, 0x21ac8,
0x21ad0, 0x21ad4,
0x21ae0, 0x21ae8,
0x21af0, 0x21af0,
0x21af8, 0x21c18,
0x21c20, 0x21c20,
0x21c28, 0x21c30,
0x21c38, 0x21c38,
0x21c80, 0x21c98,
0x21ca0, 0x21ca8,
0x21cb0, 0x21cc8,
0x21cd0, 0x21cd4,
0x21ce0, 0x21ce8,
0x21cf0, 0x21cf0,
0x21cf8, 0x21d7c,
0x21e00, 0x21e04,
0x22000, 0x2202c,
0x22100, 0x2213c,
0x22190, 0x221a0,
0x221a8, 0x221b8,
0x221c4, 0x221c8,
0x22200, 0x22318,
0x22400, 0x224b4,
0x224c0, 0x22528,
0x22540, 0x22614,
0x23000, 0x23040,
0x2304c, 0x23060,
0x230c0, 0x230ec,
0x23200, 0x23268,
0x23270, 0x23284,
0x232fc, 0x23388,
0x23400, 0x23404,
0x23500, 0x23500,
0x23510, 0x23518,
0x2352c, 0x23530,
0x2353c, 0x2353c,
0x23550, 0x23554,
0x23600, 0x23600,
0x23608, 0x2361c,
0x23624, 0x23628,
0x23630, 0x23634,
0x2363c, 0x2363c,
0x23700, 0x2371c,
0x23780, 0x2378c,
0x23800, 0x23818,
0x23820, 0x23828,
0x23830, 0x23848,
0x23850, 0x23854,
0x23860, 0x23868,
0x23870, 0x23870,
0x23878, 0x23898,
0x238a0, 0x238a8,
0x238b0, 0x238c8,
0x238d0, 0x238d4,
0x238e0, 0x238e8,
0x238f0, 0x238f0,
0x238f8, 0x23a18,
0x23a20, 0x23a28,
0x23a30, 0x23a48,
0x23a50, 0x23a54,
0x23a60, 0x23a68,
0x23a70, 0x23a70,
0x23a78, 0x23a98,
0x23aa0, 0x23aa8,
0x23ab0, 0x23ac8,
0x23ad0, 0x23ad4,
0x23ae0, 0x23ae8,
0x23af0, 0x23af0,
0x23af8, 0x23c18,
0x23c20, 0x23c20,
0x23c28, 0x23c30,
0x23c38, 0x23c38,
0x23c80, 0x23c98,
0x23ca0, 0x23ca8,
0x23cb0, 0x23cc8,
0x23cd0, 0x23cd4,
0x23ce0, 0x23ce8,
0x23cf0, 0x23cf0,
0x23cf8, 0x23d7c,
0x23e00, 0x23e04,
0x24000, 0x2402c,
0x24100, 0x2413c,
0x24190, 0x241a0,
0x241a8, 0x241b8,
0x241c4, 0x241c8,
0x24200, 0x24318,
0x24400, 0x244b4,
0x244c0, 0x24528,
0x24540, 0x24614,
0x25000, 0x25040,
0x2504c, 0x25060,
0x250c0, 0x250ec,
0x25200, 0x25268,
0x25270, 0x25284,
0x252fc, 0x25388,
0x25400, 0x25404,
0x25500, 0x25500,
0x25510, 0x25518,
0x2552c, 0x25530,
0x2553c, 0x2553c,
0x25550, 0x25554,
0x25600, 0x25600,
0x25608, 0x2561c,
0x25624, 0x25628,
0x25630, 0x25634,
0x2563c, 0x2563c,
0x25700, 0x2571c,
0x25780, 0x2578c,
0x25800, 0x25818,
0x25820, 0x25828,
0x25830, 0x25848,
0x25850, 0x25854,
0x25860, 0x25868,
0x25870, 0x25870,
0x25878, 0x25898,
0x258a0, 0x258a8,
0x258b0, 0x258c8,
0x258d0, 0x258d4,
0x258e0, 0x258e8,
0x258f0, 0x258f0,
0x258f8, 0x25a18,
0x25a20, 0x25a28,
0x25a30, 0x25a48,
0x25a50, 0x25a54,
0x25a60, 0x25a68,
0x25a70, 0x25a70,
0x25a78, 0x25a98,
0x25aa0, 0x25aa8,
0x25ab0, 0x25ac8,
0x25ad0, 0x25ad4,
0x25ae0, 0x25ae8,
0x25af0, 0x25af0,
0x25af8, 0x25c18,
0x25c20, 0x25c20,
0x25c28, 0x25c30,
0x25c38, 0x25c38,
0x25c80, 0x25c98,
0x25ca0, 0x25ca8,
0x25cb0, 0x25cc8,
0x25cd0, 0x25cd4,
0x25ce0, 0x25ce8,
0x25cf0, 0x25cf0,
0x25cf8, 0x25d7c,
0x25e00, 0x25e04,
0x26000, 0x2602c,
0x26100, 0x2613c,
0x26190, 0x261a0,
0x261a8, 0x261b8,
0x261c4, 0x261c8,
0x26200, 0x26318,
0x26400, 0x264b4,
0x264c0, 0x26528,
0x26540, 0x26614,
0x27000, 0x27040,
0x2704c, 0x27060,
0x270c0, 0x270ec,
0x27200, 0x27268,
0x27270, 0x27284,
0x272fc, 0x27388,
0x27400, 0x27404,
0x27500, 0x27500,
0x27510, 0x27518,
0x2752c, 0x27530,
0x2753c, 0x2753c,
0x27550, 0x27554,
0x27600, 0x27600,
0x27608, 0x2761c,
0x27624, 0x27628,
0x27630, 0x27634,
0x2763c, 0x2763c,
0x27700, 0x2771c,
0x27780, 0x2778c,
0x27800, 0x27818,
0x27820, 0x27828,
0x27830, 0x27848,
0x27850, 0x27854,
0x27860, 0x27868,
0x27870, 0x27870,
0x27878, 0x27898,
0x278a0, 0x278a8,
0x278b0, 0x278c8,
0x278d0, 0x278d4,
0x278e0, 0x278e8,
0x278f0, 0x278f0,
0x278f8, 0x27a18,
0x27a20, 0x27a28,
0x27a30, 0x27a48,
0x27a50, 0x27a54,
0x27a60, 0x27a68,
0x27a70, 0x27a70,
0x27a78, 0x27a98,
0x27aa0, 0x27aa8,
0x27ab0, 0x27ac8,
0x27ad0, 0x27ad4,
0x27ae0, 0x27ae8,
0x27af0, 0x27af0,
0x27af8, 0x27c18,
0x27c20, 0x27c20,
0x27c28, 0x27c30,
0x27c38, 0x27c38,
0x27c80, 0x27c98,
0x27ca0, 0x27ca8,
0x27cb0, 0x27cc8,
0x27cd0, 0x27cd4,
0x27ce0, 0x27ce8,
0x27cf0, 0x27cf0,
0x27cf8, 0x27d7c,
0x27e00, 0x27e04,
};
static const unsigned int t5_reg_ranges[] = {
0x1008, 0x10c0,
0x10cc, 0x10f8,
0x1100, 0x1100,
0x110c, 0x1148,
0x1180, 0x1184,
0x1190, 0x1194,
0x11a0, 0x11a4,
0x11b0, 0x11b4,
0x11fc, 0x123c,
0x1280, 0x173c,
0x1800, 0x18fc,
0x3000, 0x3028,
0x3060, 0x30b0,
0x30b8, 0x30d8,
0x30e0, 0x30fc,
0x3140, 0x357c,
0x35a8, 0x35cc,
0x35ec, 0x35ec,
0x3600, 0x5624,
0x56cc, 0x56ec,
0x56f4, 0x5720,
0x5728, 0x575c,
0x580c, 0x5814,
0x5890, 0x589c,
0x58a4, 0x58ac,
0x58b8, 0x58bc,
0x5940, 0x59c8,
0x59d0, 0x59dc,
0x59fc, 0x5a18,
0x5a60, 0x5a70,
0x5a80, 0x5a9c,
0x5b94, 0x5bfc,
0x6000, 0x6020,
0x6028, 0x6040,
0x6058, 0x609c,
0x60a8, 0x614c,
0x7700, 0x7798,
0x77c0, 0x78fc,
0x7b00, 0x7b58,
0x7b60, 0x7b84,
0x7b8c, 0x7c54,
0x7d00, 0x7d38,
0x7d40, 0x7d80,
0x7d8c, 0x7ddc,
0x7de4, 0x7e04,
0x7e10, 0x7e1c,
0x7e24, 0x7e38,
0x7e40, 0x7e44,
0x7e4c, 0x7e78,
0x7e80, 0x7edc,
0x7ee8, 0x7efc,
0x8dc0, 0x8de0,
0x8df8, 0x8e04,
0x8e10, 0x8e84,
0x8ea0, 0x8f84,
0x8fc0, 0x9058,
0x9060, 0x9060,
0x9068, 0x90f8,
0x9400, 0x9408,
0x9410, 0x9470,
0x9600, 0x9600,
0x9608, 0x9638,
0x9640, 0x96f4,
0x9800, 0x9808,
0x9810, 0x9864,
0x9c00, 0x9c6c,
0x9c80, 0x9cec,
0x9d00, 0x9d6c,
0x9d80, 0x9dec,
0x9e00, 0x9e6c,
0x9e80, 0x9eec,
0x9f00, 0x9f6c,
0x9f80, 0xa020,
0xd000, 0xd004,
0xd010, 0xd03c,
0xdfc0, 0xdfe0,
0xe000, 0x1106c,
0x11074, 0x11088,
0x1109c, 0x1117c,
0x11190, 0x11204,
0x19040, 0x1906c,
0x19078, 0x19080,
0x1908c, 0x190e8,
0x190f0, 0x190f8,
0x19100, 0x19110,
0x19120, 0x19124,
0x19150, 0x19194,
0x1919c, 0x191b0,
0x191d0, 0x191e8,
0x19238, 0x19290,
0x193f8, 0x19428,
0x19430, 0x19444,
0x1944c, 0x1946c,
0x19474, 0x19474,
0x19490, 0x194cc,
0x194f0, 0x194f8,
0x19c00, 0x19c08,
0x19c10, 0x19c60,
0x19c94, 0x19ce4,
0x19cf0, 0x19d40,
0x19d50, 0x19d94,
0x19da0, 0x19de8,
0x19df0, 0x19e10,
0x19e50, 0x19e90,
0x19ea0, 0x19f24,
0x19f34, 0x19f34,
0x19f40, 0x19f50,
0x19f90, 0x19fb4,
0x19fc4, 0x19fe4,
0x1a000, 0x1a004,
0x1a010, 0x1a06c,
0x1a0b0, 0x1a0e4,
0x1a0ec, 0x1a0f8,
0x1a100, 0x1a108,
0x1a114, 0x1a130,
0x1a138, 0x1a1c4,
0x1a1fc, 0x1a1fc,
0x1e008, 0x1e00c,
0x1e040, 0x1e044,
0x1e04c, 0x1e04c,
0x1e284, 0x1e290,
0x1e2c0, 0x1e2c0,
0x1e2e0, 0x1e2e0,
0x1e300, 0x1e384,
0x1e3c0, 0x1e3c8,
0x1e408, 0x1e40c,
0x1e440, 0x1e444,
0x1e44c, 0x1e44c,
0x1e684, 0x1e690,
0x1e6c0, 0x1e6c0,
0x1e6e0, 0x1e6e0,
0x1e700, 0x1e784,
0x1e7c0, 0x1e7c8,
0x1e808, 0x1e80c,
0x1e840, 0x1e844,
0x1e84c, 0x1e84c,
0x1ea84, 0x1ea90,
0x1eac0, 0x1eac0,
0x1eae0, 0x1eae0,
0x1eb00, 0x1eb84,
0x1ebc0, 0x1ebc8,
0x1ec08, 0x1ec0c,
0x1ec40, 0x1ec44,
0x1ec4c, 0x1ec4c,
0x1ee84, 0x1ee90,
0x1eec0, 0x1eec0,
0x1eee0, 0x1eee0,
0x1ef00, 0x1ef84,
0x1efc0, 0x1efc8,
0x1f008, 0x1f00c,
0x1f040, 0x1f044,
0x1f04c, 0x1f04c,
0x1f284, 0x1f290,
0x1f2c0, 0x1f2c0,
0x1f2e0, 0x1f2e0,
0x1f300, 0x1f384,
0x1f3c0, 0x1f3c8,
0x1f408, 0x1f40c,
0x1f440, 0x1f444,
0x1f44c, 0x1f44c,
0x1f684, 0x1f690,
0x1f6c0, 0x1f6c0,
0x1f6e0, 0x1f6e0,
0x1f700, 0x1f784,
0x1f7c0, 0x1f7c8,
0x1f808, 0x1f80c,
0x1f840, 0x1f844,
0x1f84c, 0x1f84c,
0x1fa84, 0x1fa90,
0x1fac0, 0x1fac0,
0x1fae0, 0x1fae0,
0x1fb00, 0x1fb84,
0x1fbc0, 0x1fbc8,
0x1fc08, 0x1fc0c,
0x1fc40, 0x1fc44,
0x1fc4c, 0x1fc4c,
0x1fe84, 0x1fe90,
0x1fec0, 0x1fec0,
0x1fee0, 0x1fee0,
0x1ff00, 0x1ff84,
0x1ffc0, 0x1ffc8,
0x30000, 0x30030,
0x30100, 0x30144,
0x30190, 0x301a0,
0x301a8, 0x301b8,
0x301c4, 0x301c8,
0x301d0, 0x301d0,
0x30200, 0x30318,
0x30400, 0x304b4,
0x304c0, 0x3052c,
0x30540, 0x3061c,
0x30800, 0x30828,
0x30834, 0x30834,
0x308c0, 0x30908,
0x30910, 0x309ac,
0x30a00, 0x30a14,
0x30a1c, 0x30a2c,
0x30a44, 0x30a50,
0x30a74, 0x30a74,
0x30a7c, 0x30afc,
0x30b08, 0x30c24,
0x30d00, 0x30d00,
0x30d08, 0x30d14,
0x30d1c, 0x30d20,
0x30d3c, 0x30d3c,
0x30d48, 0x30d50,
0x31200, 0x3120c,
0x31220, 0x31220,
0x31240, 0x31240,
0x31600, 0x3160c,
0x31a00, 0x31a1c,
0x31e00, 0x31e20,
0x31e38, 0x31e3c,
0x31e80, 0x31e80,
0x31e88, 0x31ea8,
0x31eb0, 0x31eb4,
0x31ec8, 0x31ed4,
0x31fb8, 0x32004,
0x32200, 0x32200,
0x32208, 0x32240,
0x32248, 0x32280,
0x32288, 0x322c0,
0x322c8, 0x322fc,
0x32600, 0x32630,
0x32a00, 0x32abc,
0x32b00, 0x32b10,
0x32b20, 0x32b30,
0x32b40, 0x32b50,
0x32b60, 0x32b70,
0x33000, 0x33028,
0x33030, 0x33048,
0x33060, 0x33068,
0x33070, 0x3309c,
0x330f0, 0x33128,
0x33130, 0x33148,
0x33160, 0x33168,
0x33170, 0x3319c,
0x331f0, 0x33238,
0x33240, 0x33240,
0x33248, 0x33250,
0x3325c, 0x33264,
0x33270, 0x332b8,
0x332c0, 0x332e4,
0x332f8, 0x33338,
0x33340, 0x33340,
0x33348, 0x33350,
0x3335c, 0x33364,
0x33370, 0x333b8,
0x333c0, 0x333e4,
0x333f8, 0x33428,
0x33430, 0x33448,
0x33460, 0x33468,
0x33470, 0x3349c,
0x334f0, 0x33528,
0x33530, 0x33548,
0x33560, 0x33568,
0x33570, 0x3359c,
0x335f0, 0x33638,
0x33640, 0x33640,
0x33648, 0x33650,
0x3365c, 0x33664,
0x33670, 0x336b8,
0x336c0, 0x336e4,
0x336f8, 0x33738,
0x33740, 0x33740,
0x33748, 0x33750,
0x3375c, 0x33764,
0x33770, 0x337b8,
0x337c0, 0x337e4,
0x337f8, 0x337fc,
0x33814, 0x33814,
0x3382c, 0x3382c,
0x33880, 0x3388c,
0x338e8, 0x338ec,
0x33900, 0x33928,
0x33930, 0x33948,
0x33960, 0x33968,
0x33970, 0x3399c,
0x339f0, 0x33a38,
0x33a40, 0x33a40,
0x33a48, 0x33a50,
0x33a5c, 0x33a64,
0x33a70, 0x33ab8,
0x33ac0, 0x33ae4,
0x33af8, 0x33b10,
0x33b28, 0x33b28,
0x33b3c, 0x33b50,
0x33bf0, 0x33c10,
0x33c28, 0x33c28,
0x33c3c, 0x33c50,
0x33cf0, 0x33cfc,
0x34000, 0x34030,
0x34100, 0x34144,
0x34190, 0x341a0,
0x341a8, 0x341b8,
0x341c4, 0x341c8,
0x341d0, 0x341d0,
0x34200, 0x34318,
0x34400, 0x344b4,
0x344c0, 0x3452c,
0x34540, 0x3461c,
0x34800, 0x34828,
0x34834, 0x34834,
0x348c0, 0x34908,
0x34910, 0x349ac,
0x34a00, 0x34a14,
0x34a1c, 0x34a2c,
0x34a44, 0x34a50,
0x34a74, 0x34a74,
0x34a7c, 0x34afc,
0x34b08, 0x34c24,
0x34d00, 0x34d00,
0x34d08, 0x34d14,
0x34d1c, 0x34d20,
0x34d3c, 0x34d3c,
0x34d48, 0x34d50,
0x35200, 0x3520c,
0x35220, 0x35220,
0x35240, 0x35240,
0x35600, 0x3560c,
0x35a00, 0x35a1c,
0x35e00, 0x35e20,
0x35e38, 0x35e3c,
0x35e80, 0x35e80,
0x35e88, 0x35ea8,
0x35eb0, 0x35eb4,
0x35ec8, 0x35ed4,
0x35fb8, 0x36004,
0x36200, 0x36200,
0x36208, 0x36240,
0x36248, 0x36280,
0x36288, 0x362c0,
0x362c8, 0x362fc,
0x36600, 0x36630,
0x36a00, 0x36abc,
0x36b00, 0x36b10,
0x36b20, 0x36b30,
0x36b40, 0x36b50,
0x36b60, 0x36b70,
0x37000, 0x37028,
0x37030, 0x37048,
0x37060, 0x37068,
0x37070, 0x3709c,
0x370f0, 0x37128,
0x37130, 0x37148,
0x37160, 0x37168,
0x37170, 0x3719c,
0x371f0, 0x37238,
0x37240, 0x37240,
0x37248, 0x37250,
0x3725c, 0x37264,
0x37270, 0x372b8,
0x372c0, 0x372e4,
0x372f8, 0x37338,
0x37340, 0x37340,
0x37348, 0x37350,
0x3735c, 0x37364,
0x37370, 0x373b8,
0x373c0, 0x373e4,
0x373f8, 0x37428,
0x37430, 0x37448,
0x37460, 0x37468,
0x37470, 0x3749c,
0x374f0, 0x37528,
0x37530, 0x37548,
0x37560, 0x37568,
0x37570, 0x3759c,
0x375f0, 0x37638,
0x37640, 0x37640,
0x37648, 0x37650,
0x3765c, 0x37664,
0x37670, 0x376b8,
0x376c0, 0x376e4,
0x376f8, 0x37738,
0x37740, 0x37740,
0x37748, 0x37750,
0x3775c, 0x37764,
0x37770, 0x377b8,
0x377c0, 0x377e4,
0x377f8, 0x377fc,
0x37814, 0x37814,
0x3782c, 0x3782c,
0x37880, 0x3788c,
0x378e8, 0x378ec,
0x37900, 0x37928,
0x37930, 0x37948,
0x37960, 0x37968,
0x37970, 0x3799c,
0x379f0, 0x37a38,
0x37a40, 0x37a40,
0x37a48, 0x37a50,
0x37a5c, 0x37a64,
0x37a70, 0x37ab8,
0x37ac0, 0x37ae4,
0x37af8, 0x37b10,
0x37b28, 0x37b28,
0x37b3c, 0x37b50,
0x37bf0, 0x37c10,
0x37c28, 0x37c28,
0x37c3c, 0x37c50,
0x37cf0, 0x37cfc,
0x38000, 0x38030,
0x38100, 0x38144,
0x38190, 0x381a0,
0x381a8, 0x381b8,
0x381c4, 0x381c8,
0x381d0, 0x381d0,
0x38200, 0x38318,
0x38400, 0x384b4,
0x384c0, 0x3852c,
0x38540, 0x3861c,
0x38800, 0x38828,
0x38834, 0x38834,
0x388c0, 0x38908,
0x38910, 0x389ac,
0x38a00, 0x38a14,
0x38a1c, 0x38a2c,
0x38a44, 0x38a50,
0x38a74, 0x38a74,
0x38a7c, 0x38afc,
0x38b08, 0x38c24,
0x38d00, 0x38d00,
0x38d08, 0x38d14,
0x38d1c, 0x38d20,
0x38d3c, 0x38d3c,
0x38d48, 0x38d50,
0x39200, 0x3920c,
0x39220, 0x39220,
0x39240, 0x39240,
0x39600, 0x3960c,
0x39a00, 0x39a1c,
0x39e00, 0x39e20,
0x39e38, 0x39e3c,
0x39e80, 0x39e80,
0x39e88, 0x39ea8,
0x39eb0, 0x39eb4,
0x39ec8, 0x39ed4,
0x39fb8, 0x3a004,
0x3a200, 0x3a200,
0x3a208, 0x3a240,
0x3a248, 0x3a280,
0x3a288, 0x3a2c0,
0x3a2c8, 0x3a2fc,
0x3a600, 0x3a630,
0x3aa00, 0x3aabc,
0x3ab00, 0x3ab10,
0x3ab20, 0x3ab30,
0x3ab40, 0x3ab50,
0x3ab60, 0x3ab70,
0x3b000, 0x3b028,
0x3b030, 0x3b048,
0x3b060, 0x3b068,
0x3b070, 0x3b09c,
0x3b0f0, 0x3b128,
0x3b130, 0x3b148,
0x3b160, 0x3b168,
0x3b170, 0x3b19c,
0x3b1f0, 0x3b238,
0x3b240, 0x3b240,
0x3b248, 0x3b250,
0x3b25c, 0x3b264,
0x3b270, 0x3b2b8,
0x3b2c0, 0x3b2e4,
0x3b2f8, 0x3b338,
0x3b340, 0x3b340,
0x3b348, 0x3b350,
0x3b35c, 0x3b364,
0x3b370, 0x3b3b8,
0x3b3c0, 0x3b3e4,
0x3b3f8, 0x3b428,
0x3b430, 0x3b448,
0x3b460, 0x3b468,
0x3b470, 0x3b49c,
0x3b4f0, 0x3b528,
0x3b530, 0x3b548,
0x3b560, 0x3b568,
0x3b570, 0x3b59c,
0x3b5f0, 0x3b638,
0x3b640, 0x3b640,
0x3b648, 0x3b650,
0x3b65c, 0x3b664,
0x3b670, 0x3b6b8,
0x3b6c0, 0x3b6e4,
0x3b6f8, 0x3b738,
0x3b740, 0x3b740,
0x3b748, 0x3b750,
0x3b75c, 0x3b764,
0x3b770, 0x3b7b8,
0x3b7c0, 0x3b7e4,
0x3b7f8, 0x3b7fc,
0x3b814, 0x3b814,
0x3b82c, 0x3b82c,
0x3b880, 0x3b88c,
0x3b8e8, 0x3b8ec,
0x3b900, 0x3b928,
0x3b930, 0x3b948,
0x3b960, 0x3b968,
0x3b970, 0x3b99c,
0x3b9f0, 0x3ba38,
0x3ba40, 0x3ba40,
0x3ba48, 0x3ba50,
0x3ba5c, 0x3ba64,
0x3ba70, 0x3bab8,
0x3bac0, 0x3bae4,
0x3baf8, 0x3bb10,
0x3bb28, 0x3bb28,
0x3bb3c, 0x3bb50,
0x3bbf0, 0x3bc10,
0x3bc28, 0x3bc28,
0x3bc3c, 0x3bc50,
0x3bcf0, 0x3bcfc,
0x3c000, 0x3c030,
0x3c100, 0x3c144,
0x3c190, 0x3c1a0,
0x3c1a8, 0x3c1b8,
0x3c1c4, 0x3c1c8,
0x3c1d0, 0x3c1d0,
0x3c200, 0x3c318,
0x3c400, 0x3c4b4,
0x3c4c0, 0x3c52c,
0x3c540, 0x3c61c,
0x3c800, 0x3c828,
0x3c834, 0x3c834,
0x3c8c0, 0x3c908,
0x3c910, 0x3c9ac,
0x3ca00, 0x3ca14,
0x3ca1c, 0x3ca2c,
0x3ca44, 0x3ca50,
0x3ca74, 0x3ca74,
0x3ca7c, 0x3cafc,
0x3cb08, 0x3cc24,
0x3cd00, 0x3cd00,
0x3cd08, 0x3cd14,
0x3cd1c, 0x3cd20,
0x3cd3c, 0x3cd3c,
0x3cd48, 0x3cd50,
0x3d200, 0x3d20c,
0x3d220, 0x3d220,
0x3d240, 0x3d240,
0x3d600, 0x3d60c,
0x3da00, 0x3da1c,
0x3de00, 0x3de20,
0x3de38, 0x3de3c,
0x3de80, 0x3de80,
0x3de88, 0x3dea8,
0x3deb0, 0x3deb4,
0x3dec8, 0x3ded4,
0x3dfb8, 0x3e004,
0x3e200, 0x3e200,
0x3e208, 0x3e240,
0x3e248, 0x3e280,
0x3e288, 0x3e2c0,
0x3e2c8, 0x3e2fc,
0x3e600, 0x3e630,
0x3ea00, 0x3eabc,
0x3eb00, 0x3eb10,
0x3eb20, 0x3eb30,
0x3eb40, 0x3eb50,
0x3eb60, 0x3eb70,
0x3f000, 0x3f028,
0x3f030, 0x3f048,
0x3f060, 0x3f068,
0x3f070, 0x3f09c,
0x3f0f0, 0x3f128,
0x3f130, 0x3f148,
0x3f160, 0x3f168,
0x3f170, 0x3f19c,
0x3f1f0, 0x3f238,
0x3f240, 0x3f240,
0x3f248, 0x3f250,
0x3f25c, 0x3f264,
0x3f270, 0x3f2b8,
0x3f2c0, 0x3f2e4,
0x3f2f8, 0x3f338,
0x3f340, 0x3f340,
0x3f348, 0x3f350,
0x3f35c, 0x3f364,
0x3f370, 0x3f3b8,
0x3f3c0, 0x3f3e4,
0x3f3f8, 0x3f428,
0x3f430, 0x3f448,
0x3f460, 0x3f468,
0x3f470, 0x3f49c,
0x3f4f0, 0x3f528,
0x3f530, 0x3f548,
0x3f560, 0x3f568,
0x3f570, 0x3f59c,
0x3f5f0, 0x3f638,
0x3f640, 0x3f640,
0x3f648, 0x3f650,
0x3f65c, 0x3f664,
0x3f670, 0x3f6b8,
0x3f6c0, 0x3f6e4,
0x3f6f8, 0x3f738,
0x3f740, 0x3f740,
0x3f748, 0x3f750,
0x3f75c, 0x3f764,
0x3f770, 0x3f7b8,
0x3f7c0, 0x3f7e4,
0x3f7f8, 0x3f7fc,
0x3f814, 0x3f814,
0x3f82c, 0x3f82c,
0x3f880, 0x3f88c,
0x3f8e8, 0x3f8ec,
0x3f900, 0x3f928,
0x3f930, 0x3f948,
0x3f960, 0x3f968,
0x3f970, 0x3f99c,
0x3f9f0, 0x3fa38,
0x3fa40, 0x3fa40,
0x3fa48, 0x3fa50,
0x3fa5c, 0x3fa64,
0x3fa70, 0x3fab8,
0x3fac0, 0x3fae4,
0x3faf8, 0x3fb10,
0x3fb28, 0x3fb28,
0x3fb3c, 0x3fb50,
0x3fbf0, 0x3fc10,
0x3fc28, 0x3fc28,
0x3fc3c, 0x3fc50,
0x3fcf0, 0x3fcfc,
0x40000, 0x4000c,
0x40040, 0x40050,
0x40060, 0x40068,
0x4007c, 0x4008c,
0x40094, 0x400b0,
0x400c0, 0x40144,
0x40180, 0x4018c,
0x40200, 0x40254,
0x40260, 0x40264,
0x40270, 0x40288,
0x40290, 0x40298,
0x402ac, 0x402c8,
0x402d0, 0x402e0,
0x402f0, 0x402f0,
0x40300, 0x4033c,
0x403f8, 0x403fc,
0x41304, 0x413c4,
0x41400, 0x4140c,
0x41414, 0x4141c,
0x41480, 0x414d0,
0x44000, 0x44054,
0x4405c, 0x44078,
0x440c0, 0x44174,
0x44180, 0x441ac,
0x441b4, 0x441b8,
0x441c0, 0x44254,
0x4425c, 0x44278,
0x442c0, 0x44374,
0x44380, 0x443ac,
0x443b4, 0x443b8,
0x443c0, 0x44454,
0x4445c, 0x44478,
0x444c0, 0x44574,
0x44580, 0x445ac,
0x445b4, 0x445b8,
0x445c0, 0x44654,
0x4465c, 0x44678,
0x446c0, 0x44774,
0x44780, 0x447ac,
0x447b4, 0x447b8,
0x447c0, 0x44854,
0x4485c, 0x44878,
0x448c0, 0x44974,
0x44980, 0x449ac,
0x449b4, 0x449b8,
0x449c0, 0x449fc,
0x45000, 0x45004,
0x45010, 0x45030,
0x45040, 0x45060,
0x45068, 0x45068,
0x45080, 0x45084,
0x450a0, 0x450b0,
0x45200, 0x45204,
0x45210, 0x45230,
0x45240, 0x45260,
0x45268, 0x45268,
0x45280, 0x45284,
0x452a0, 0x452b0,
0x460c0, 0x460e4,
0x47000, 0x4703c,
0x47044, 0x4708c,
0x47200, 0x47250,
0x47400, 0x47408,
0x47414, 0x47420,
0x47600, 0x47618,
0x47800, 0x47814,
0x48000, 0x4800c,
0x48040, 0x48050,
0x48060, 0x48068,
0x4807c, 0x4808c,
0x48094, 0x480b0,
0x480c0, 0x48144,
0x48180, 0x4818c,
0x48200, 0x48254,
0x48260, 0x48264,
0x48270, 0x48288,
0x48290, 0x48298,
0x482ac, 0x482c8,
0x482d0, 0x482e0,
0x482f0, 0x482f0,
0x48300, 0x4833c,
0x483f8, 0x483fc,
0x49304, 0x493c4,
0x49400, 0x4940c,
0x49414, 0x4941c,
0x49480, 0x494d0,
0x4c000, 0x4c054,
0x4c05c, 0x4c078,
0x4c0c0, 0x4c174,
0x4c180, 0x4c1ac,
0x4c1b4, 0x4c1b8,
0x4c1c0, 0x4c254,
0x4c25c, 0x4c278,
0x4c2c0, 0x4c374,
0x4c380, 0x4c3ac,
0x4c3b4, 0x4c3b8,
0x4c3c0, 0x4c454,
0x4c45c, 0x4c478,
0x4c4c0, 0x4c574,
0x4c580, 0x4c5ac,
0x4c5b4, 0x4c5b8,
0x4c5c0, 0x4c654,
0x4c65c, 0x4c678,
0x4c6c0, 0x4c774,
0x4c780, 0x4c7ac,
0x4c7b4, 0x4c7b8,
0x4c7c0, 0x4c854,
0x4c85c, 0x4c878,
0x4c8c0, 0x4c974,
0x4c980, 0x4c9ac,
0x4c9b4, 0x4c9b8,
0x4c9c0, 0x4c9fc,
0x4d000, 0x4d004,
0x4d010, 0x4d030,
0x4d040, 0x4d060,
0x4d068, 0x4d068,
0x4d080, 0x4d084,
0x4d0a0, 0x4d0b0,
0x4d200, 0x4d204,
0x4d210, 0x4d230,
0x4d240, 0x4d260,
0x4d268, 0x4d268,
0x4d280, 0x4d284,
0x4d2a0, 0x4d2b0,
0x4e0c0, 0x4e0e4,
0x4f000, 0x4f03c,
0x4f044, 0x4f08c,
0x4f200, 0x4f250,
0x4f400, 0x4f408,
0x4f414, 0x4f420,
0x4f600, 0x4f618,
0x4f800, 0x4f814,
0x50000, 0x50084,
0x50090, 0x500cc,
0x50400, 0x50400,
0x50800, 0x50884,
0x50890, 0x508cc,
0x50c00, 0x50c00,
0x51000, 0x5101c,
0x51300, 0x51308,
};
static const unsigned int t6_reg_ranges[] = {
0x1008, 0x101c,
0x1024, 0x10a8,
0x10b4, 0x10f8,
0x1100, 0x1114,
0x111c, 0x112c,
0x1138, 0x113c,
0x1144, 0x114c,
0x1180, 0x1184,
0x1190, 0x1194,
0x11a0, 0x11a4,
0x11b0, 0x11b4,
0x11fc, 0x1274,
0x1280, 0x133c,
0x1800, 0x18fc,
0x3000, 0x302c,
0x3060, 0x30b0,
0x30b8, 0x30d8,
0x30e0, 0x30fc,
0x3140, 0x357c,
0x35a8, 0x35cc,
0x35ec, 0x35ec,
0x3600, 0x5624,
0x56cc, 0x56ec,
0x56f4, 0x5720,
0x5728, 0x575c,
0x580c, 0x5814,
0x5890, 0x589c,
0x58a4, 0x58ac,
0x58b8, 0x58bc,
0x5940, 0x595c,
0x5980, 0x598c,
0x59b0, 0x59c8,
0x59d0, 0x59dc,
0x59fc, 0x5a18,
0x5a60, 0x5a6c,
0x5a80, 0x5a8c,
0x5a94, 0x5a9c,
0x5b94, 0x5bfc,
0x5c10, 0x5e48,
0x5e50, 0x5e94,
0x5ea0, 0x5eb0,
0x5ec0, 0x5ec0,
0x5ec8, 0x5ed0,
0x5ee0, 0x5ee0,
0x5ef0, 0x5ef0,
0x5f00, 0x5f00,
0x6000, 0x6020,
0x6028, 0x6040,
0x6058, 0x609c,
0x60a8, 0x619c,
0x7700, 0x7798,
0x77c0, 0x7880,
0x78cc, 0x78fc,
0x7b00, 0x7b58,
0x7b60, 0x7b84,
0x7b8c, 0x7c54,
0x7d00, 0x7d38,
0x7d40, 0x7d84,
0x7d8c, 0x7ddc,
0x7de4, 0x7e04,
0x7e10, 0x7e1c,
0x7e24, 0x7e38,
0x7e40, 0x7e44,
0x7e4c, 0x7e78,
0x7e80, 0x7edc,
0x7ee8, 0x7efc,
0x8dc0, 0x8de4,
0x8df8, 0x8e04,
0x8e10, 0x8e84,
0x8ea0, 0x8f88,
0x8fb8, 0x9058,
0x9060, 0x9060,
0x9068, 0x90f8,
0x9100, 0x9124,
0x9400, 0x9470,
0x9600, 0x9600,
0x9608, 0x9638,
0x9640, 0x9704,
0x9710, 0x971c,
0x9800, 0x9808,
0x9810, 0x9864,
0x9c00, 0x9c6c,
0x9c80, 0x9cec,
0x9d00, 0x9d6c,
0x9d80, 0x9dec,
0x9e00, 0x9e6c,
0x9e80, 0x9eec,
0x9f00, 0x9f6c,
0x9f80, 0xa020,
0xd000, 0xd03c,
0xd100, 0xd118,
0xd200, 0xd214,
0xd220, 0xd234,
0xd240, 0xd254,
0xd260, 0xd274,
0xd280, 0xd294,
0xd2a0, 0xd2b4,
0xd2c0, 0xd2d4,
0xd2e0, 0xd2f4,
0xd300, 0xd31c,
0xdfc0, 0xdfe0,
0xe000, 0xf008,
0xf010, 0xf018,
0xf020, 0xf028,
0x11000, 0x11014,
0x11048, 0x1106c,
0x11074, 0x11088,
0x11098, 0x11120,
0x1112c, 0x1117c,
0x11190, 0x112e0,
0x11300, 0x1130c,
0x12000, 0x1206c,
0x19040, 0x1906c,
0x19078, 0x19080,
0x1908c, 0x190e8,
0x190f0, 0x190f8,
0x19100, 0x19110,
0x19120, 0x19124,
0x19150, 0x19194,
0x1919c, 0x191b0,
0x191d0, 0x191e8,
0x19238, 0x19290,
0x192a4, 0x192b0,
0x192bc, 0x192bc,
0x19348, 0x1934c,
0x193f8, 0x19418,
0x19420, 0x19428,
0x19430, 0x19444,
0x1944c, 0x1946c,
0x19474, 0x19474,
0x19490, 0x194cc,
0x194f0, 0x194f8,
0x19c00, 0x19c48,
0x19c50, 0x19c80,
0x19c94, 0x19c98,
0x19ca0, 0x19cbc,
0x19ce4, 0x19ce4,
0x19cf0, 0x19cf8,
0x19d00, 0x19d28,
0x19d50, 0x19d78,
0x19d94, 0x19d98,
0x19da0, 0x19dc8,
0x19df0, 0x19e10,
0x19e50, 0x19e6c,
0x19ea0, 0x19ebc,
0x19ec4, 0x19ef4,
0x19f04, 0x19f2c,
0x19f34, 0x19f34,
0x19f40, 0x19f50,
0x19f90, 0x19fac,
0x19fc4, 0x19fc8,
0x19fd0, 0x19fe4,
0x1a000, 0x1a004,
0x1a010, 0x1a06c,
0x1a0b0, 0x1a0e4,
0x1a0ec, 0x1a0f8,
0x1a100, 0x1a108,
0x1a114, 0x1a130,
0x1a138, 0x1a1c4,
0x1a1fc, 0x1a1fc,
0x1e008, 0x1e00c,
0x1e040, 0x1e044,
0x1e04c, 0x1e04c,
0x1e284, 0x1e290,
0x1e2c0, 0x1e2c0,
0x1e2e0, 0x1e2e0,
0x1e300, 0x1e384,
0x1e3c0, 0x1e3c8,
0x1e408, 0x1e40c,
0x1e440, 0x1e444,
0x1e44c, 0x1e44c,
0x1e684, 0x1e690,
0x1e6c0, 0x1e6c0,
0x1e6e0, 0x1e6e0,
0x1e700, 0x1e784,
0x1e7c0, 0x1e7c8,
0x1e808, 0x1e80c,
0x1e840, 0x1e844,
0x1e84c, 0x1e84c,
0x1ea84, 0x1ea90,
0x1eac0, 0x1eac0,
0x1eae0, 0x1eae0,
0x1eb00, 0x1eb84,
0x1ebc0, 0x1ebc8,
0x1ec08, 0x1ec0c,
0x1ec40, 0x1ec44,
0x1ec4c, 0x1ec4c,
0x1ee84, 0x1ee90,
0x1eec0, 0x1eec0,
0x1eee0, 0x1eee0,
0x1ef00, 0x1ef84,
0x1efc0, 0x1efc8,
0x1f008, 0x1f00c,
0x1f040, 0x1f044,
0x1f04c, 0x1f04c,
0x1f284, 0x1f290,
0x1f2c0, 0x1f2c0,
0x1f2e0, 0x1f2e0,
0x1f300, 0x1f384,
0x1f3c0, 0x1f3c8,
0x1f408, 0x1f40c,
0x1f440, 0x1f444,
0x1f44c, 0x1f44c,
0x1f684, 0x1f690,
0x1f6c0, 0x1f6c0,
0x1f6e0, 0x1f6e0,
0x1f700, 0x1f784,
0x1f7c0, 0x1f7c8,
0x1f808, 0x1f80c,
0x1f840, 0x1f844,
0x1f84c, 0x1f84c,
0x1fa84, 0x1fa90,
0x1fac0, 0x1fac0,
0x1fae0, 0x1fae0,
0x1fb00, 0x1fb84,
0x1fbc0, 0x1fbc8,
0x1fc08, 0x1fc0c,
0x1fc40, 0x1fc44,
0x1fc4c, 0x1fc4c,
0x1fe84, 0x1fe90,
0x1fec0, 0x1fec0,
0x1fee0, 0x1fee0,
0x1ff00, 0x1ff84,
0x1ffc0, 0x1ffc8,
0x30000, 0x30030,
0x30100, 0x30168,
0x30190, 0x301a0,
0x301a8, 0x301b8,
0x301c4, 0x301c8,
0x301d0, 0x301d0,
0x30200, 0x30320,
0x30400, 0x304b4,
0x304c0, 0x3052c,
0x30540, 0x3061c,
0x30800, 0x308a0,
0x308c0, 0x30908,
0x30910, 0x309b8,
0x30a00, 0x30a04,
0x30a0c, 0x30a14,
0x30a1c, 0x30a2c,
0x30a44, 0x30a50,
0x30a74, 0x30a74,
0x30a7c, 0x30afc,
0x30b08, 0x30c24,
0x30d00, 0x30d14,
0x30d1c, 0x30d3c,
0x30d44, 0x30d4c,
0x30d54, 0x30d74,
0x30d7c, 0x30d7c,
0x30de0, 0x30de0,
0x30e00, 0x30ed4,
0x30f00, 0x30fa4,
0x30fc0, 0x30fc4,
0x31000, 0x31004,
0x31080, 0x310fc,
0x31208, 0x31220,
0x3123c, 0x31254,
0x31300, 0x31300,
0x31308, 0x3131c,
0x31338, 0x3133c,
0x31380, 0x31380,
0x31388, 0x313a8,
0x313b4, 0x313b4,
0x31400, 0x31420,
0x31438, 0x3143c,
0x31480, 0x31480,
0x314a8, 0x314a8,
0x314b0, 0x314b4,
0x314c8, 0x314d4,
0x31a40, 0x31a4c,
0x31af0, 0x31b20,
0x31b38, 0x31b3c,
0x31b80, 0x31b80,
0x31ba8, 0x31ba8,
0x31bb0, 0x31bb4,
0x31bc8, 0x31bd4,
0x32140, 0x3218c,
0x321f0, 0x321f4,
0x32200, 0x32200,
0x32218, 0x32218,
0x32400, 0x32400,
0x32408, 0x3241c,
0x32618, 0x32620,
0x32664, 0x32664,
0x326a8, 0x326a8,
0x326ec, 0x326ec,
0x32a00, 0x32abc,
0x32b00, 0x32b18,
0x32b20, 0x32b38,
0x32b40, 0x32b58,
0x32b60, 0x32b78,
0x32c00, 0x32c00,
0x32c08, 0x32c3c,
0x33000, 0x3302c,
0x33034, 0x33050,
0x33058, 0x33058,
0x33060, 0x3308c,
0x3309c, 0x330ac,
0x330c0, 0x330c0,
0x330c8, 0x330d0,
0x330d8, 0x330e0,
0x330ec, 0x3312c,
0x33134, 0x33150,
0x33158, 0x33158,
0x33160, 0x3318c,
0x3319c, 0x331ac,
0x331c0, 0x331c0,
0x331c8, 0x331d0,
0x331d8, 0x331e0,
0x331ec, 0x33290,
0x33298, 0x332c4,
0x332e4, 0x33390,
0x33398, 0x333c4,
0x333e4, 0x3342c,
0x33434, 0x33450,
0x33458, 0x33458,
0x33460, 0x3348c,
0x3349c, 0x334ac,
0x334c0, 0x334c0,
0x334c8, 0x334d0,
0x334d8, 0x334e0,
0x334ec, 0x3352c,
0x33534, 0x33550,
0x33558, 0x33558,
0x33560, 0x3358c,
0x3359c, 0x335ac,
0x335c0, 0x335c0,
0x335c8, 0x335d0,
0x335d8, 0x335e0,
0x335ec, 0x33690,
0x33698, 0x336c4,
0x336e4, 0x33790,
0x33798, 0x337c4,
0x337e4, 0x337fc,
0x33814, 0x33814,
0x33854, 0x33868,
0x33880, 0x3388c,
0x338c0, 0x338d0,
0x338e8, 0x338ec,
0x33900, 0x3392c,
0x33934, 0x33950,
0x33958, 0x33958,
0x33960, 0x3398c,
0x3399c, 0x339ac,
0x339c0, 0x339c0,
0x339c8, 0x339d0,
0x339d8, 0x339e0,
0x339ec, 0x33a90,
0x33a98, 0x33ac4,
0x33ae4, 0x33b10,
0x33b24, 0x33b28,
0x33b38, 0x33b50,
0x33bf0, 0x33c10,
0x33c24, 0x33c28,
0x33c38, 0x33c50,
0x33cf0, 0x33cfc,
0x34000, 0x34030,
0x34100, 0x34168,
0x34190, 0x341a0,
0x341a8, 0x341b8,
0x341c4, 0x341c8,
0x341d0, 0x341d0,
0x34200, 0x34320,
0x34400, 0x344b4,
0x344c0, 0x3452c,
0x34540, 0x3461c,
0x34800, 0x348a0,
0x348c0, 0x34908,
0x34910, 0x349b8,
0x34a00, 0x34a04,
0x34a0c, 0x34a14,
0x34a1c, 0x34a2c,
0x34a44, 0x34a50,
0x34a74, 0x34a74,
0x34a7c, 0x34afc,
0x34b08, 0x34c24,
0x34d00, 0x34d14,
0x34d1c, 0x34d3c,
0x34d44, 0x34d4c,
0x34d54, 0x34d74,
0x34d7c, 0x34d7c,
0x34de0, 0x34de0,
0x34e00, 0x34ed4,
0x34f00, 0x34fa4,
0x34fc0, 0x34fc4,
0x35000, 0x35004,
0x35080, 0x350fc,
0x35208, 0x35220,
0x3523c, 0x35254,
0x35300, 0x35300,
0x35308, 0x3531c,
0x35338, 0x3533c,
0x35380, 0x35380,
0x35388, 0x353a8,
0x353b4, 0x353b4,
0x35400, 0x35420,
0x35438, 0x3543c,
0x35480, 0x35480,
0x354a8, 0x354a8,
0x354b0, 0x354b4,
0x354c8, 0x354d4,
0x35a40, 0x35a4c,
0x35af0, 0x35b20,
0x35b38, 0x35b3c,
0x35b80, 0x35b80,
0x35ba8, 0x35ba8,
0x35bb0, 0x35bb4,
0x35bc8, 0x35bd4,
0x36140, 0x3618c,
0x361f0, 0x361f4,
0x36200, 0x36200,
0x36218, 0x36218,
0x36400, 0x36400,
0x36408, 0x3641c,
0x36618, 0x36620,
0x36664, 0x36664,
0x366a8, 0x366a8,
0x366ec, 0x366ec,
0x36a00, 0x36abc,
0x36b00, 0x36b18,
0x36b20, 0x36b38,
0x36b40, 0x36b58,
0x36b60, 0x36b78,
0x36c00, 0x36c00,
0x36c08, 0x36c3c,
0x37000, 0x3702c,
0x37034, 0x37050,
0x37058, 0x37058,
0x37060, 0x3708c,
0x3709c, 0x370ac,
0x370c0, 0x370c0,
0x370c8, 0x370d0,
0x370d8, 0x370e0,
0x370ec, 0x3712c,
0x37134, 0x37150,
0x37158, 0x37158,
0x37160, 0x3718c,
0x3719c, 0x371ac,
0x371c0, 0x371c0,
0x371c8, 0x371d0,
0x371d8, 0x371e0,
0x371ec, 0x37290,
0x37298, 0x372c4,
0x372e4, 0x37390,
0x37398, 0x373c4,
0x373e4, 0x3742c,
0x37434, 0x37450,
0x37458, 0x37458,
0x37460, 0x3748c,
0x3749c, 0x374ac,
0x374c0, 0x374c0,
0x374c8, 0x374d0,
0x374d8, 0x374e0,
0x374ec, 0x3752c,
0x37534, 0x37550,
0x37558, 0x37558,
0x37560, 0x3758c,
0x3759c, 0x375ac,
0x375c0, 0x375c0,
0x375c8, 0x375d0,
0x375d8, 0x375e0,
0x375ec, 0x37690,
0x37698, 0x376c4,
0x376e4, 0x37790,
0x37798, 0x377c4,
0x377e4, 0x377fc,
0x37814, 0x37814,
0x37854, 0x37868,
0x37880, 0x3788c,
0x378c0, 0x378d0,
0x378e8, 0x378ec,
0x37900, 0x3792c,
0x37934, 0x37950,
0x37958, 0x37958,
0x37960, 0x3798c,
0x3799c, 0x379ac,
0x379c0, 0x379c0,
0x379c8, 0x379d0,
0x379d8, 0x379e0,
0x379ec, 0x37a90,
0x37a98, 0x37ac4,
0x37ae4, 0x37b10,
0x37b24, 0x37b28,
0x37b38, 0x37b50,
0x37bf0, 0x37c10,
0x37c24, 0x37c28,
0x37c38, 0x37c50,
0x37cf0, 0x37cfc,
0x40040, 0x40040,
0x40080, 0x40084,
0x40100, 0x40100,
0x40140, 0x401bc,
0x40200, 0x40214,
0x40228, 0x40228,
0x40240, 0x40258,
0x40280, 0x40280,
0x40304, 0x40304,
0x40330, 0x4033c,
0x41304, 0x413c8,
0x413d0, 0x413dc,
0x413f0, 0x413f0,
0x41400, 0x4140c,
0x41414, 0x4141c,
0x41480, 0x414d0,
0x44000, 0x4407c,
0x440c0, 0x441ac,
0x441b4, 0x4427c,
0x442c0, 0x443ac,
0x443b4, 0x4447c,
0x444c0, 0x445ac,
0x445b4, 0x4467c,
0x446c0, 0x447ac,
0x447b4, 0x4487c,
0x448c0, 0x449ac,
0x449b4, 0x44a7c,
0x44ac0, 0x44bac,
0x44bb4, 0x44c7c,
0x44cc0, 0x44dac,
0x44db4, 0x44e7c,
0x44ec0, 0x44fac,
0x44fb4, 0x4507c,
0x450c0, 0x451ac,
0x451b4, 0x451fc,
0x45800, 0x45804,
0x45810, 0x45830,
0x45840, 0x45860,
0x45868, 0x45868,
0x45880, 0x45884,
0x458a0, 0x458b0,
0x45a00, 0x45a04,
0x45a10, 0x45a30,
0x45a40, 0x45a60,
0x45a68, 0x45a68,
0x45a80, 0x45a84,
0x45aa0, 0x45ab0,
0x460c0, 0x460e4,
0x47000, 0x4703c,
0x47044, 0x4708c,
0x47200, 0x47250,
0x47400, 0x47408,
0x47414, 0x47420,
0x47600, 0x47618,
0x47800, 0x47814,
0x47820, 0x4782c,
0x50000, 0x50084,
0x50090, 0x500cc,
0x50300, 0x50384,
0x50400, 0x50400,
0x50800, 0x50884,
0x50890, 0x508cc,
0x50b00, 0x50b84,
0x50c00, 0x50c00,
0x51000, 0x51020,
0x51028, 0x510b0,
0x51300, 0x51324,
};
u32 *buf_end = (u32 *)((char *)buf + buf_size);
const unsigned int *reg_ranges;
int reg_ranges_size, range;
unsigned int chip_version = CHELSIO_CHIP_VERSION(adap->params.chip);
/* Select the right set of register ranges to dump depending on the
* adapter chip type.
*/
switch (chip_version) {
case CHELSIO_T4:
reg_ranges = t4_reg_ranges;
reg_ranges_size = ARRAY_SIZE(t4_reg_ranges);
break;
case CHELSIO_T5:
reg_ranges = t5_reg_ranges;
reg_ranges_size = ARRAY_SIZE(t5_reg_ranges);
break;
case CHELSIO_T6:
reg_ranges = t6_reg_ranges;
reg_ranges_size = ARRAY_SIZE(t6_reg_ranges);
break;
default:
dev_err(adap->pdev_dev,
"Unsupported chip version %d\n", chip_version);
return;
}
/* Clear the register buffer and insert the appropriate register
* values selected by the above register ranges.
*/
memset(buf, 0, buf_size);
for (range = 0; range < reg_ranges_size; range += 2) {
unsigned int reg = reg_ranges[range];
unsigned int last_reg = reg_ranges[range + 1];
u32 *bufp = (u32 *)((char *)buf + reg);
/* Iterate across the register range filling in the register
* buffer but don't write past the end of the register buffer.
*/
while (reg <= last_reg && bufp < buf_end) {
*bufp++ = t4_read_reg(adap, reg);
reg += sizeof(u32);
}
}
}
#define EEPROM_STAT_ADDR 0x7bfc
#define VPD_BASE 0x400
#define VPD_BASE_OLD 0
#define VPD_LEN 1024
#define CHELSIO_VPD_UNIQUE_ID 0x82
/**
* t4_eeprom_ptov - translate a physical EEPROM address to virtual
* @phys_addr: the physical EEPROM address
* @fn: the PCI function number
* @sz: size of function-specific area
*
* Translate a physical EEPROM address to virtual. The first 1K is
* accessed through virtual addresses starting at 31K, the rest is
* accessed through virtual addresses starting at 0.
*
* The mapping is as follows:
* [0..1K) -> [31K..32K)
* [1K..1K+A) -> [31K-A..31K)
* [1K+A..ES) -> [0..ES-A-1K)
*
* where A = @fn * @sz, and ES = EEPROM size.
*/
int t4_eeprom_ptov(unsigned int phys_addr, unsigned int fn, unsigned int sz)
{
fn *= sz;
if (phys_addr < 1024)
return phys_addr + (31 << 10);
if (phys_addr < 1024 + fn)
return 31744 - fn + phys_addr - 1024;
if (phys_addr < EEPROMSIZE)
return phys_addr - 1024 - fn;
return -EINVAL;
}
/**
* t4_seeprom_wp - enable/disable EEPROM write protection
* @adapter: the adapter
* @enable: whether to enable or disable write protection
*
* Enables or disables write protection on the serial EEPROM.
*/
int t4_seeprom_wp(struct adapter *adapter, bool enable)
{
unsigned int v = enable ? 0xc : 0;
int ret = pci_write_vpd(adapter->pdev, EEPROM_STAT_ADDR, 4, &v);
return ret < 0 ? ret : 0;
}
/**
* t4_get_raw_vpd_params - read VPD parameters from VPD EEPROM
* @adapter: adapter to read
* @p: where to store the parameters
*
* Reads card parameters stored in VPD EEPROM.
*/
int t4_get_raw_vpd_params(struct adapter *adapter, struct vpd_params *p)
{
int i, ret = 0, addr;
int ec, sn, pn, na;
u8 *vpd, csum;
unsigned int vpdr_len, kw_offset, id_len;
vpd = vmalloc(VPD_LEN);
if (!vpd)
return -ENOMEM;
/* Card information normally starts at VPD_BASE but early cards had
* it at 0.
*/
ret = pci_read_vpd(adapter->pdev, VPD_BASE, sizeof(u32), vpd);
if (ret < 0)
goto out;
/* The VPD shall have a unique identifier specified by the PCI SIG.
* For chelsio adapters, the identifier is 0x82. The first byte of a VPD
* shall be CHELSIO_VPD_UNIQUE_ID (0x82). The VPD programming software
* is expected to automatically put this entry at the
* beginning of the VPD.
*/
addr = *vpd == CHELSIO_VPD_UNIQUE_ID ? VPD_BASE : VPD_BASE_OLD;
ret = pci_read_vpd(adapter->pdev, addr, VPD_LEN, vpd);
if (ret < 0)
goto out;
if (vpd[0] != PCI_VPD_LRDT_ID_STRING) {
dev_err(adapter->pdev_dev, "missing VPD ID string\n");
ret = -EINVAL;
goto out;
}
id_len = pci_vpd_lrdt_size(vpd);
if (id_len > ID_LEN)
id_len = ID_LEN;
i = pci_vpd_find_tag(vpd, 0, VPD_LEN, PCI_VPD_LRDT_RO_DATA);
if (i < 0) {
dev_err(adapter->pdev_dev, "missing VPD-R section\n");
ret = -EINVAL;
goto out;
}
vpdr_len = pci_vpd_lrdt_size(&vpd[i]);
kw_offset = i + PCI_VPD_LRDT_TAG_SIZE;
if (vpdr_len + kw_offset > VPD_LEN) {
dev_err(adapter->pdev_dev, "bad VPD-R length %u\n", vpdr_len);
ret = -EINVAL;
goto out;
}
#define FIND_VPD_KW(var, name) do { \
var = pci_vpd_find_info_keyword(vpd, kw_offset, vpdr_len, name); \
if (var < 0) { \
dev_err(adapter->pdev_dev, "missing VPD keyword " name "\n"); \
ret = -EINVAL; \
goto out; \
} \
var += PCI_VPD_INFO_FLD_HDR_SIZE; \
} while (0)
FIND_VPD_KW(i, "RV");
for (csum = 0; i >= 0; i--)
csum += vpd[i];
if (csum) {
dev_err(adapter->pdev_dev,
"corrupted VPD EEPROM, actual csum %u\n", csum);
ret = -EINVAL;
goto out;
}
FIND_VPD_KW(ec, "EC");
FIND_VPD_KW(sn, "SN");
FIND_VPD_KW(pn, "PN");
FIND_VPD_KW(na, "NA");
#undef FIND_VPD_KW
memcpy(p->id, vpd + PCI_VPD_LRDT_TAG_SIZE, id_len);
strim(p->id);
memcpy(p->ec, vpd + ec, EC_LEN);
strim(p->ec);
i = pci_vpd_info_field_size(vpd + sn - PCI_VPD_INFO_FLD_HDR_SIZE);
memcpy(p->sn, vpd + sn, min(i, SERNUM_LEN));
strim(p->sn);
i = pci_vpd_info_field_size(vpd + pn - PCI_VPD_INFO_FLD_HDR_SIZE);
memcpy(p->pn, vpd + pn, min(i, PN_LEN));
strim(p->pn);
memcpy(p->na, vpd + na, min(i, MACADDR_LEN));
strim((char *)p->na);
out:
vfree(vpd);
return ret < 0 ? ret : 0;
}
/**
* t4_get_vpd_params - read VPD parameters & retrieve Core Clock
* @adapter: adapter to read
* @p: where to store the parameters
*
* Reads card parameters stored in VPD EEPROM and retrieves the Core
* Clock. This can only be called after a connection to the firmware
* is established.
*/
int t4_get_vpd_params(struct adapter *adapter, struct vpd_params *p)
{
u32 cclk_param, cclk_val;
int ret;
/* Grab the raw VPD parameters.
*/
ret = t4_get_raw_vpd_params(adapter, p);
if (ret)
return ret;
/* Ask firmware for the Core Clock since it knows how to translate the
* Reference Clock ('V2') VPD field into a Core Clock value ...
*/
cclk_param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_CCLK));
ret = t4_query_params(adapter, adapter->mbox, adapter->pf, 0,
1, &cclk_param, &cclk_val);
if (ret)
return ret;
p->cclk = cclk_val;
return 0;
}
/**
* t4_get_pfres - retrieve VF resource limits
* @adapter: the adapter
*
* Retrieves configured resource limits and capabilities for a physical
* function. The results are stored in @adapter->pfres.
*/
int t4_get_pfres(struct adapter *adapter)
{
struct pf_resources *pfres = &adapter->params.pfres;
struct fw_pfvf_cmd cmd, rpl;
int v;
u32 word;
/* Execute PFVF Read command to get VF resource limits; bail out early
* with error on command failure.
*/
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_PFVF_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_READ_F |
FW_PFVF_CMD_PFN_V(adapter->pf) |
FW_PFVF_CMD_VFN_V(0));
cmd.retval_len16 = cpu_to_be32(FW_LEN16(cmd));
v = t4_wr_mbox(adapter, adapter->mbox, &cmd, sizeof(cmd), &rpl);
if (v != FW_SUCCESS)
return v;
/* Extract PF resource limits and return success.
*/
word = be32_to_cpu(rpl.niqflint_niq);
pfres->niqflint = FW_PFVF_CMD_NIQFLINT_G(word);
pfres->niq = FW_PFVF_CMD_NIQ_G(word);
word = be32_to_cpu(rpl.type_to_neq);
pfres->neq = FW_PFVF_CMD_NEQ_G(word);
pfres->pmask = FW_PFVF_CMD_PMASK_G(word);
word = be32_to_cpu(rpl.tc_to_nexactf);
pfres->tc = FW_PFVF_CMD_TC_G(word);
pfres->nvi = FW_PFVF_CMD_NVI_G(word);
pfres->nexactf = FW_PFVF_CMD_NEXACTF_G(word);
word = be32_to_cpu(rpl.r_caps_to_nethctrl);
pfres->r_caps = FW_PFVF_CMD_R_CAPS_G(word);
pfres->wx_caps = FW_PFVF_CMD_WX_CAPS_G(word);
pfres->nethctrl = FW_PFVF_CMD_NETHCTRL_G(word);
return 0;
}
/* serial flash and firmware constants */
enum {
SF_ATTEMPTS = 10, /* max retries for SF operations */
/* flash command opcodes */
SF_PROG_PAGE = 2, /* program page */
SF_WR_DISABLE = 4, /* disable writes */
SF_RD_STATUS = 5, /* read status register */
SF_WR_ENABLE = 6, /* enable writes */
SF_RD_DATA_FAST = 0xb, /* read flash */
SF_RD_ID = 0x9f, /* read ID */
SF_ERASE_SECTOR = 0xd8, /* erase sector */
};
/**
* sf1_read - read data from the serial flash
* @adapter: the adapter
* @byte_cnt: number of bytes to read
* @cont: whether another operation will be chained
* @lock: whether to lock SF for PL access only
* @valp: where to store the read data
*
* Reads up to 4 bytes of data from the serial flash. The location of
* the read needs to be specified prior to calling this by issuing the
* appropriate commands to the serial flash.
*/
static int sf1_read(struct adapter *adapter, unsigned int byte_cnt, int cont,
int lock, u32 *valp)
{
int ret;
if (!byte_cnt || byte_cnt > 4)
return -EINVAL;
if (t4_read_reg(adapter, SF_OP_A) & SF_BUSY_F)
return -EBUSY;
t4_write_reg(adapter, SF_OP_A, SF_LOCK_V(lock) |
SF_CONT_V(cont) | BYTECNT_V(byte_cnt - 1));
ret = t4_wait_op_done(adapter, SF_OP_A, SF_BUSY_F, 0, SF_ATTEMPTS, 5);
if (!ret)
*valp = t4_read_reg(adapter, SF_DATA_A);
return ret;
}
/**
* sf1_write - write data to the serial flash
* @adapter: the adapter
* @byte_cnt: number of bytes to write
* @cont: whether another operation will be chained
* @lock: whether to lock SF for PL access only
* @val: value to write
*
* Writes up to 4 bytes of data to the serial flash. The location of
* the write needs to be specified prior to calling this by issuing the
* appropriate commands to the serial flash.
*/
static int sf1_write(struct adapter *adapter, unsigned int byte_cnt, int cont,
int lock, u32 val)
{
if (!byte_cnt || byte_cnt > 4)
return -EINVAL;
if (t4_read_reg(adapter, SF_OP_A) & SF_BUSY_F)
return -EBUSY;
t4_write_reg(adapter, SF_DATA_A, val);
t4_write_reg(adapter, SF_OP_A, SF_LOCK_V(lock) |
SF_CONT_V(cont) | BYTECNT_V(byte_cnt - 1) | OP_V(1));
return t4_wait_op_done(adapter, SF_OP_A, SF_BUSY_F, 0, SF_ATTEMPTS, 5);
}
/**
* flash_wait_op - wait for a flash operation to complete
* @adapter: the adapter
* @attempts: max number of polls of the status register
* @delay: delay between polls in ms
*
* Wait for a flash operation to complete by polling the status register.
*/
static int flash_wait_op(struct adapter *adapter, int attempts, int delay)
{
int ret;
u32 status;
while (1) {
if ((ret = sf1_write(adapter, 1, 1, 1, SF_RD_STATUS)) != 0 ||
(ret = sf1_read(adapter, 1, 0, 1, &status)) != 0)
return ret;
if (!(status & 1))
return 0;
if (--attempts == 0)
return -EAGAIN;
if (delay)
msleep(delay);
}
}
/**
* t4_read_flash - read words from serial flash
* @adapter: the adapter
* @addr: the start address for the read
* @nwords: how many 32-bit words to read
* @data: where to store the read data
* @byte_oriented: whether to store data as bytes or as words
*
* Read the specified number of 32-bit words from the serial flash.
* If @byte_oriented is set the read data is stored as a byte array
* (i.e., big-endian), otherwise as 32-bit words in the platform's
* natural endianness.
*/
int t4_read_flash(struct adapter *adapter, unsigned int addr,
unsigned int nwords, u32 *data, int byte_oriented)
{
int ret;
if (addr + nwords * sizeof(u32) > adapter->params.sf_size || (addr & 3))
return -EINVAL;
addr = swab32(addr) | SF_RD_DATA_FAST;
if ((ret = sf1_write(adapter, 4, 1, 0, addr)) != 0 ||
(ret = sf1_read(adapter, 1, 1, 0, data)) != 0)
return ret;
for ( ; nwords; nwords--, data++) {
ret = sf1_read(adapter, 4, nwords > 1, nwords == 1, data);
if (nwords == 1)
t4_write_reg(adapter, SF_OP_A, 0); /* unlock SF */
if (ret)
return ret;
if (byte_oriented)
*data = (__force __u32)(cpu_to_be32(*data));
}
return 0;
}
/**
* t4_write_flash - write up to a page of data to the serial flash
* @adapter: the adapter
* @addr: the start address to write
* @n: length of data to write in bytes
* @data: the data to write
*
* Writes up to a page of data (256 bytes) to the serial flash starting
* at the given address. All the data must be written to the same page.
*/
static int t4_write_flash(struct adapter *adapter, unsigned int addr,
unsigned int n, const u8 *data)
{
int ret;
u32 buf[64];
unsigned int i, c, left, val, offset = addr & 0xff;
if (addr >= adapter->params.sf_size || offset + n > SF_PAGE_SIZE)
return -EINVAL;
val = swab32(addr) | SF_PROG_PAGE;
if ((ret = sf1_write(adapter, 1, 0, 1, SF_WR_ENABLE)) != 0 ||
(ret = sf1_write(adapter, 4, 1, 1, val)) != 0)
goto unlock;
for (left = n; left; left -= c) {
c = min(left, 4U);
for (val = 0, i = 0; i < c; ++i)
val = (val << 8) + *data++;
ret = sf1_write(adapter, c, c != left, 1, val);
if (ret)
goto unlock;
}
ret = flash_wait_op(adapter, 8, 1);
if (ret)
goto unlock;
t4_write_reg(adapter, SF_OP_A, 0); /* unlock SF */
/* Read the page to verify the write succeeded */
ret = t4_read_flash(adapter, addr & ~0xff, ARRAY_SIZE(buf), buf, 1);
if (ret)
return ret;
if (memcmp(data - n, (u8 *)buf + offset, n)) {
dev_err(adapter->pdev_dev,
"failed to correctly write the flash page at %#x\n",
addr);
return -EIO;
}
return 0;
unlock:
t4_write_reg(adapter, SF_OP_A, 0); /* unlock SF */
return ret;
}
/**
* t4_get_fw_version - read the firmware version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the FW version from flash.
*/
int t4_get_fw_version(struct adapter *adapter, u32 *vers)
{
return t4_read_flash(adapter, FLASH_FW_START +
offsetof(struct fw_hdr, fw_ver), 1,
vers, 0);
}
/**
* t4_get_bs_version - read the firmware bootstrap version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the FW Bootstrap version from flash.
*/
int t4_get_bs_version(struct adapter *adapter, u32 *vers)
{
return t4_read_flash(adapter, FLASH_FWBOOTSTRAP_START +
offsetof(struct fw_hdr, fw_ver), 1,
vers, 0);
}
/**
* t4_get_tp_version - read the TP microcode version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the TP microcode version from flash.
*/
int t4_get_tp_version(struct adapter *adapter, u32 *vers)
{
return t4_read_flash(adapter, FLASH_FW_START +
offsetof(struct fw_hdr, tp_microcode_ver),
1, vers, 0);
}
/**
* t4_get_exprom_version - return the Expansion ROM version (if any)
* @adap: the adapter
* @vers: where to place the version
*
* Reads the Expansion ROM header from FLASH and returns the version
* number (if present) through the @vers return value pointer. We return
* this in the Firmware Version Format since it's convenient. Return
* 0 on success, -ENOENT if no Expansion ROM is present.
*/
int t4_get_exprom_version(struct adapter *adap, u32 *vers)
{
struct exprom_header {
unsigned char hdr_arr[16]; /* must start with 0x55aa */
unsigned char hdr_ver[4]; /* Expansion ROM version */
} *hdr;
u32 exprom_header_buf[DIV_ROUND_UP(sizeof(struct exprom_header),
sizeof(u32))];
int ret;
ret = t4_read_flash(adap, FLASH_EXP_ROM_START,
ARRAY_SIZE(exprom_header_buf), exprom_header_buf,
0);
if (ret)
return ret;
hdr = (struct exprom_header *)exprom_header_buf;
if (hdr->hdr_arr[0] != 0x55 || hdr->hdr_arr[1] != 0xaa)
return -ENOENT;
*vers = (FW_HDR_FW_VER_MAJOR_V(hdr->hdr_ver[0]) |
FW_HDR_FW_VER_MINOR_V(hdr->hdr_ver[1]) |
FW_HDR_FW_VER_MICRO_V(hdr->hdr_ver[2]) |
FW_HDR_FW_VER_BUILD_V(hdr->hdr_ver[3]));
return 0;
}
/**
* t4_get_vpd_version - return the VPD version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the VPD via the Firmware interface (thus this can only be called
* once we're ready to issue Firmware commands). The format of the
* VPD version is adapter specific. Returns 0 on success, an error on
* failure.
*
* Note that early versions of the Firmware didn't include the ability
* to retrieve the VPD version, so we zero-out the return-value parameter
* in that case to avoid leaving it with garbage in it.
*
* Also note that the Firmware will return its cached copy of the VPD
* Revision ID, not the actual Revision ID as written in the Serial
* EEPROM. This is only an issue if a new VPD has been written and the
* Firmware/Chip haven't yet gone through a RESET sequence. So it's best
* to defer calling this routine till after a FW_RESET_CMD has been issued
* if the Host Driver will be performing a full adapter initialization.
*/
int t4_get_vpd_version(struct adapter *adapter, u32 *vers)
{
u32 vpdrev_param;
int ret;
vpdrev_param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_VPDREV));
ret = t4_query_params(adapter, adapter->mbox, adapter->pf, 0,
1, &vpdrev_param, vers);
if (ret)
*vers = 0;
return ret;
}
/**
* t4_get_scfg_version - return the Serial Configuration version
* @adapter: the adapter
* @vers: where to place the version
*
* Reads the Serial Configuration Version via the Firmware interface
* (thus this can only be called once we're ready to issue Firmware
* commands). The format of the Serial Configuration version is
* adapter specific. Returns 0 on success, an error on failure.
*
* Note that early versions of the Firmware didn't include the ability
* to retrieve the Serial Configuration version, so we zero-out the
* return-value parameter in that case to avoid leaving it with
* garbage in it.
*
* Also note that the Firmware will return its cached copy of the Serial
* Initialization Revision ID, not the actual Revision ID as written in
* the Serial EEPROM. This is only an issue if a new VPD has been written
* and the Firmware/Chip haven't yet gone through a RESET sequence. So
* it's best to defer calling this routine till after a FW_RESET_CMD has
* been issued if the Host Driver will be performing a full adapter
* initialization.
*/
int t4_get_scfg_version(struct adapter *adapter, u32 *vers)
{
u32 scfgrev_param;
int ret;
scfgrev_param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_SCFGREV));
ret = t4_query_params(adapter, adapter->mbox, adapter->pf, 0,
1, &scfgrev_param, vers);
if (ret)
*vers = 0;
return ret;
}
/**
* t4_get_version_info - extract various chip/firmware version information
* @adapter: the adapter
*
* Reads various chip/firmware version numbers and stores them into the
* adapter Adapter Parameters structure. If any of the efforts fails
* the first failure will be returned, but all of the version numbers
* will be read.
*/
int t4_get_version_info(struct adapter *adapter)
{
int ret = 0;
#define FIRST_RET(__getvinfo) \
do { \
int __ret = __getvinfo; \
if (__ret && !ret) \
ret = __ret; \
} while (0)
FIRST_RET(t4_get_fw_version(adapter, &adapter->params.fw_vers));
FIRST_RET(t4_get_bs_version(adapter, &adapter->params.bs_vers));
FIRST_RET(t4_get_tp_version(adapter, &adapter->params.tp_vers));
FIRST_RET(t4_get_exprom_version(adapter, &adapter->params.er_vers));
FIRST_RET(t4_get_scfg_version(adapter, &adapter->params.scfg_vers));
FIRST_RET(t4_get_vpd_version(adapter, &adapter->params.vpd_vers));
#undef FIRST_RET
return ret;
}
/**
* t4_dump_version_info - dump all of the adapter configuration IDs
* @adapter: the adapter
*
* Dumps all of the various bits of adapter configuration version/revision
* IDs information. This is typically called at some point after
* t4_get_version_info() has been called.
*/
void t4_dump_version_info(struct adapter *adapter)
{
/* Device information */
dev_info(adapter->pdev_dev, "Chelsio %s rev %d\n",
adapter->params.vpd.id,
CHELSIO_CHIP_RELEASE(adapter->params.chip));
dev_info(adapter->pdev_dev, "S/N: %s, P/N: %s\n",
adapter->params.vpd.sn, adapter->params.vpd.pn);
/* Firmware Version */
if (!adapter->params.fw_vers)
dev_warn(adapter->pdev_dev, "No firmware loaded\n");
else
dev_info(adapter->pdev_dev, "Firmware version: %u.%u.%u.%u\n",
FW_HDR_FW_VER_MAJOR_G(adapter->params.fw_vers),
FW_HDR_FW_VER_MINOR_G(adapter->params.fw_vers),
FW_HDR_FW_VER_MICRO_G(adapter->params.fw_vers),
FW_HDR_FW_VER_BUILD_G(adapter->params.fw_vers));
/* Bootstrap Firmware Version. (Some adapters don't have Bootstrap
* Firmware, so dev_info() is more appropriate here.)
*/
if (!adapter->params.bs_vers)
dev_info(adapter->pdev_dev, "No bootstrap loaded\n");
else
dev_info(adapter->pdev_dev, "Bootstrap version: %u.%u.%u.%u\n",
FW_HDR_FW_VER_MAJOR_G(adapter->params.bs_vers),
FW_HDR_FW_VER_MINOR_G(adapter->params.bs_vers),
FW_HDR_FW_VER_MICRO_G(adapter->params.bs_vers),
FW_HDR_FW_VER_BUILD_G(adapter->params.bs_vers));
/* TP Microcode Version */
if (!adapter->params.tp_vers)
dev_warn(adapter->pdev_dev, "No TP Microcode loaded\n");
else
dev_info(adapter->pdev_dev,
"TP Microcode version: %u.%u.%u.%u\n",
FW_HDR_FW_VER_MAJOR_G(adapter->params.tp_vers),
FW_HDR_FW_VER_MINOR_G(adapter->params.tp_vers),
FW_HDR_FW_VER_MICRO_G(adapter->params.tp_vers),
FW_HDR_FW_VER_BUILD_G(adapter->params.tp_vers));
/* Expansion ROM version */
if (!adapter->params.er_vers)
dev_info(adapter->pdev_dev, "No Expansion ROM loaded\n");
else
dev_info(adapter->pdev_dev,
"Expansion ROM version: %u.%u.%u.%u\n",
FW_HDR_FW_VER_MAJOR_G(adapter->params.er_vers),
FW_HDR_FW_VER_MINOR_G(adapter->params.er_vers),
FW_HDR_FW_VER_MICRO_G(adapter->params.er_vers),
FW_HDR_FW_VER_BUILD_G(adapter->params.er_vers));
/* Serial Configuration version */
dev_info(adapter->pdev_dev, "Serial Configuration version: %#x\n",
adapter->params.scfg_vers);
/* VPD Version */
dev_info(adapter->pdev_dev, "VPD version: %#x\n",
adapter->params.vpd_vers);
}
/**
* t4_check_fw_version - check if the FW is supported with this driver
* @adap: the adapter
*
* Checks if an adapter's FW is compatible with the driver. Returns 0
* if there's exact match, a negative error if the version could not be
* read or there's a major version mismatch
*/
int t4_check_fw_version(struct adapter *adap)
{
int i, ret, major, minor, micro;
int exp_major, exp_minor, exp_micro;
unsigned int chip_version = CHELSIO_CHIP_VERSION(adap->params.chip);
ret = t4_get_fw_version(adap, &adap->params.fw_vers);
/* Try multiple times before returning error */
for (i = 0; (ret == -EBUSY || ret == -EAGAIN) && i < 3; i++)
ret = t4_get_fw_version(adap, &adap->params.fw_vers);
if (ret)
return ret;
major = FW_HDR_FW_VER_MAJOR_G(adap->params.fw_vers);
minor = FW_HDR_FW_VER_MINOR_G(adap->params.fw_vers);
micro = FW_HDR_FW_VER_MICRO_G(adap->params.fw_vers);
switch (chip_version) {
case CHELSIO_T4:
exp_major = T4FW_MIN_VERSION_MAJOR;
exp_minor = T4FW_MIN_VERSION_MINOR;
exp_micro = T4FW_MIN_VERSION_MICRO;
break;
case CHELSIO_T5:
exp_major = T5FW_MIN_VERSION_MAJOR;
exp_minor = T5FW_MIN_VERSION_MINOR;
exp_micro = T5FW_MIN_VERSION_MICRO;
break;
case CHELSIO_T6:
exp_major = T6FW_MIN_VERSION_MAJOR;
exp_minor = T6FW_MIN_VERSION_MINOR;
exp_micro = T6FW_MIN_VERSION_MICRO;
break;
default:
dev_err(adap->pdev_dev, "Unsupported chip type, %x\n",
adap->chip);
return -EINVAL;
}
if (major < exp_major || (major == exp_major && minor < exp_minor) ||
(major == exp_major && minor == exp_minor && micro < exp_micro)) {
dev_err(adap->pdev_dev,
"Card has firmware version %u.%u.%u, minimum "
"supported firmware is %u.%u.%u.\n", major, minor,
micro, exp_major, exp_minor, exp_micro);
return -EFAULT;
}
return 0;
}
/* Is the given firmware API compatible with the one the driver was compiled
* with?
*/
static int fw_compatible(const struct fw_hdr *hdr1, const struct fw_hdr *hdr2)
{
/* short circuit if it's the exact same firmware version */
if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
return 1;
#define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
SAME_INTF(ri) && SAME_INTF(iscsi) && SAME_INTF(fcoe))
return 1;
#undef SAME_INTF
return 0;
}
/* The firmware in the filesystem is usable, but should it be installed?
* This routine explains itself in detail if it indicates the filesystem
* firmware should be installed.
*/
static int should_install_fs_fw(struct adapter *adap, int card_fw_usable,
int k, int c)
{
const char *reason;
if (!card_fw_usable) {
reason = "incompatible or unusable";
goto install;
}
if (k > c) {
reason = "older than the version supported with this driver";
goto install;
}
return 0;
install:
dev_err(adap->pdev_dev, "firmware on card (%u.%u.%u.%u) is %s, "
"installing firmware %u.%u.%u.%u on card.\n",
FW_HDR_FW_VER_MAJOR_G(c), FW_HDR_FW_VER_MINOR_G(c),
FW_HDR_FW_VER_MICRO_G(c), FW_HDR_FW_VER_BUILD_G(c), reason,
FW_HDR_FW_VER_MAJOR_G(k), FW_HDR_FW_VER_MINOR_G(k),
FW_HDR_FW_VER_MICRO_G(k), FW_HDR_FW_VER_BUILD_G(k));
return 1;
}
int t4_prep_fw(struct adapter *adap, struct fw_info *fw_info,
const u8 *fw_data, unsigned int fw_size,
struct fw_hdr *card_fw, enum dev_state state,
int *reset)
{
int ret, card_fw_usable, fs_fw_usable;
const struct fw_hdr *fs_fw;
const struct fw_hdr *drv_fw;
drv_fw = &fw_info->fw_hdr;
/* Read the header of the firmware on the card */
ret = t4_read_flash(adap, FLASH_FW_START,
sizeof(*card_fw) / sizeof(uint32_t),
(uint32_t *)card_fw, 1);
if (ret == 0) {
card_fw_usable = fw_compatible(drv_fw, (const void *)card_fw);
} else {
dev_err(adap->pdev_dev,
"Unable to read card's firmware header: %d\n", ret);
card_fw_usable = 0;
}
if (fw_data != NULL) {
fs_fw = (const void *)fw_data;
fs_fw_usable = fw_compatible(drv_fw, fs_fw);
} else {
fs_fw = NULL;
fs_fw_usable = 0;
}
if (card_fw_usable && card_fw->fw_ver == drv_fw->fw_ver &&
(!fs_fw_usable || fs_fw->fw_ver == drv_fw->fw_ver)) {
/* Common case: the firmware on the card is an exact match and
* the filesystem one is an exact match too, or the filesystem
* one is absent/incompatible.
*/
} else if (fs_fw_usable && state == DEV_STATE_UNINIT &&
should_install_fs_fw(adap, card_fw_usable,
be32_to_cpu(fs_fw->fw_ver),
be32_to_cpu(card_fw->fw_ver))) {
ret = t4_fw_upgrade(adap, adap->mbox, fw_data,
fw_size, 0);
if (ret != 0) {
dev_err(adap->pdev_dev,
"failed to install firmware: %d\n", ret);
goto bye;
}
/* Installed successfully, update the cached header too. */
*card_fw = *fs_fw;
card_fw_usable = 1;
*reset = 0; /* already reset as part of load_fw */
}
if (!card_fw_usable) {
uint32_t d, c, k;
d = be32_to_cpu(drv_fw->fw_ver);
c = be32_to_cpu(card_fw->fw_ver);
k = fs_fw ? be32_to_cpu(fs_fw->fw_ver) : 0;
dev_err(adap->pdev_dev, "Cannot find a usable firmware: "
"chip state %d, "
"driver compiled with %d.%d.%d.%d, "
"card has %d.%d.%d.%d, filesystem has %d.%d.%d.%d\n",
state,
FW_HDR_FW_VER_MAJOR_G(d), FW_HDR_FW_VER_MINOR_G(d),
FW_HDR_FW_VER_MICRO_G(d), FW_HDR_FW_VER_BUILD_G(d),
FW_HDR_FW_VER_MAJOR_G(c), FW_HDR_FW_VER_MINOR_G(c),
FW_HDR_FW_VER_MICRO_G(c), FW_HDR_FW_VER_BUILD_G(c),
FW_HDR_FW_VER_MAJOR_G(k), FW_HDR_FW_VER_MINOR_G(k),
FW_HDR_FW_VER_MICRO_G(k), FW_HDR_FW_VER_BUILD_G(k));
ret = -EINVAL;
goto bye;
}
/* We're using whatever's on the card and it's known to be good. */
adap->params.fw_vers = be32_to_cpu(card_fw->fw_ver);
adap->params.tp_vers = be32_to_cpu(card_fw->tp_microcode_ver);
bye:
return ret;
}
/**
* t4_flash_erase_sectors - erase a range of flash sectors
* @adapter: the adapter
* @start: the first sector to erase
* @end: the last sector to erase
*
* Erases the sectors in the given inclusive range.
*/
static int t4_flash_erase_sectors(struct adapter *adapter, int start, int end)
{
int ret = 0;
if (end >= adapter->params.sf_nsec)
return -EINVAL;
while (start <= end) {
if ((ret = sf1_write(adapter, 1, 0, 1, SF_WR_ENABLE)) != 0 ||
(ret = sf1_write(adapter, 4, 0, 1,
SF_ERASE_SECTOR | (start << 8))) != 0 ||
(ret = flash_wait_op(adapter, 14, 500)) != 0) {
dev_err(adapter->pdev_dev,
"erase of flash sector %d failed, error %d\n",
start, ret);
break;
}
start++;
}
t4_write_reg(adapter, SF_OP_A, 0); /* unlock SF */
return ret;
}
/**
* t4_flash_cfg_addr - return the address of the flash configuration file
* @adapter: the adapter
*
* Return the address within the flash where the Firmware Configuration
* File is stored.
*/
unsigned int t4_flash_cfg_addr(struct adapter *adapter)
{
if (adapter->params.sf_size == 0x100000)
return FLASH_FPGA_CFG_START;
else
return FLASH_CFG_START;
}
/* Return TRUE if the specified firmware matches the adapter. I.e. T4
* firmware for T4 adapters, T5 firmware for T5 adapters, etc. We go ahead
* and emit an error message for mismatched firmware to save our caller the
* effort ...
*/
static bool t4_fw_matches_chip(const struct adapter *adap,
const struct fw_hdr *hdr)
{
/* The expression below will return FALSE for any unsupported adapter
* which will keep us "honest" in the future ...
*/
if ((is_t4(adap->params.chip) && hdr->chip == FW_HDR_CHIP_T4) ||
(is_t5(adap->params.chip) && hdr->chip == FW_HDR_CHIP_T5) ||
(is_t6(adap->params.chip) && hdr->chip == FW_HDR_CHIP_T6))
return true;
dev_err(adap->pdev_dev,
"FW image (%d) is not suitable for this adapter (%d)\n",
hdr->chip, CHELSIO_CHIP_VERSION(adap->params.chip));
return false;
}
/**
* t4_load_fw - download firmware
* @adap: the adapter
* @fw_data: the firmware image to write
* @size: image size
*
* Write the supplied firmware image to the card's serial flash.
*/
int t4_load_fw(struct adapter *adap, const u8 *fw_data, unsigned int size)
{
u32 csum;
int ret, addr;
unsigned int i;
u8 first_page[SF_PAGE_SIZE];
const __be32 *p = (const __be32 *)fw_data;
const struct fw_hdr *hdr = (const struct fw_hdr *)fw_data;
unsigned int sf_sec_size = adap->params.sf_size / adap->params.sf_nsec;
unsigned int fw_start_sec = FLASH_FW_START_SEC;
unsigned int fw_size = FLASH_FW_MAX_SIZE;
unsigned int fw_start = FLASH_FW_START;
if (!size) {
dev_err(adap->pdev_dev, "FW image has no data\n");
return -EINVAL;
}
if (size & 511) {
dev_err(adap->pdev_dev,
"FW image size not multiple of 512 bytes\n");
return -EINVAL;
}
if ((unsigned int)be16_to_cpu(hdr->len512) * 512 != size) {
dev_err(adap->pdev_dev,
"FW image size differs from size in FW header\n");
return -EINVAL;
}
if (size > fw_size) {
dev_err(adap->pdev_dev, "FW image too large, max is %u bytes\n",
fw_size);
return -EFBIG;
}
if (!t4_fw_matches_chip(adap, hdr))
return -EINVAL;
for (csum = 0, i = 0; i < size / sizeof(csum); i++)
csum += be32_to_cpu(p[i]);
if (csum != 0xffffffff) {
dev_err(adap->pdev_dev,
"corrupted firmware image, checksum %#x\n", csum);
return -EINVAL;
}
i = DIV_ROUND_UP(size, sf_sec_size); /* # of sectors spanned */
ret = t4_flash_erase_sectors(adap, fw_start_sec, fw_start_sec + i - 1);
if (ret)
goto out;
/*
* We write the correct version at the end so the driver can see a bad
* version if the FW write fails. Start by writing a copy of the
* first page with a bad version.
*/
memcpy(first_page, fw_data, SF_PAGE_SIZE);
((struct fw_hdr *)first_page)->fw_ver = cpu_to_be32(0xffffffff);
ret = t4_write_flash(adap, fw_start, SF_PAGE_SIZE, first_page);
if (ret)
goto out;
addr = fw_start;
for (size -= SF_PAGE_SIZE; size; size -= SF_PAGE_SIZE) {
addr += SF_PAGE_SIZE;
fw_data += SF_PAGE_SIZE;
ret = t4_write_flash(adap, addr, SF_PAGE_SIZE, fw_data);
if (ret)
goto out;
}
ret = t4_write_flash(adap,
fw_start + offsetof(struct fw_hdr, fw_ver),
sizeof(hdr->fw_ver), (const u8 *)&hdr->fw_ver);
out:
if (ret)
dev_err(adap->pdev_dev, "firmware download failed, error %d\n",
ret);
else
ret = t4_get_fw_version(adap, &adap->params.fw_vers);
return ret;
}
/**
* t4_phy_fw_ver - return current PHY firmware version
* @adap: the adapter
* @phy_fw_ver: return value buffer for PHY firmware version
*
* Returns the current version of external PHY firmware on the
* adapter.
*/
int t4_phy_fw_ver(struct adapter *adap, int *phy_fw_ver)
{
u32 param, val;
int ret;
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_PHYFW) |
FW_PARAMS_PARAM_Y_V(adap->params.portvec) |
FW_PARAMS_PARAM_Z_V(FW_PARAMS_PARAM_DEV_PHYFW_VERSION));
ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 1,
¶m, &val);
if (ret)
return ret;
*phy_fw_ver = val;
return 0;
}
/**
* t4_load_phy_fw - download port PHY firmware
* @adap: the adapter
* @win: the PCI-E Memory Window index to use for t4_memory_rw()
* @win_lock: the lock to use to guard the memory copy
* @phy_fw_version: function to check PHY firmware versions
* @phy_fw_data: the PHY firmware image to write
* @phy_fw_size: image size
*
* Transfer the specified PHY firmware to the adapter. If a non-NULL
* @phy_fw_version is supplied, then it will be used to determine if
* it's necessary to perform the transfer by comparing the version
* of any existing adapter PHY firmware with that of the passed in
* PHY firmware image. If @win_lock is non-NULL then it will be used
* around the call to t4_memory_rw() which transfers the PHY firmware
* to the adapter.
*
* A negative error number will be returned if an error occurs. If
* version number support is available and there's no need to upgrade
* the firmware, 0 will be returned. If firmware is successfully
* transferred to the adapter, 1 will be returned.
*
* NOTE: some adapters only have local RAM to store the PHY firmware. As
* a result, a RESET of the adapter would cause that RAM to lose its
* contents. Thus, loading PHY firmware on such adapters must happen
* after any FW_RESET_CMDs ...
*/
int t4_load_phy_fw(struct adapter *adap,
int win, spinlock_t *win_lock,
int (*phy_fw_version)(const u8 *, size_t),
const u8 *phy_fw_data, size_t phy_fw_size)
{
unsigned long mtype = 0, maddr = 0;
u32 param, val;
int cur_phy_fw_ver = 0, new_phy_fw_vers = 0;
int ret;
/* If we have version number support, then check to see if the adapter
* already has up-to-date PHY firmware loaded.
*/
if (phy_fw_version) {
new_phy_fw_vers = phy_fw_version(phy_fw_data, phy_fw_size);
ret = t4_phy_fw_ver(adap, &cur_phy_fw_ver);
if (ret < 0)
return ret;
if (cur_phy_fw_ver >= new_phy_fw_vers) {
CH_WARN(adap, "PHY Firmware already up-to-date, "
"version %#x\n", cur_phy_fw_ver);
return 0;
}
}
/* Ask the firmware where it wants us to copy the PHY firmware image.
* The size of the file requires a special version of the READ command
* which will pass the file size via the values field in PARAMS_CMD and
* retrieve the return value from firmware and place it in the same
* buffer values
*/
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_PHYFW) |
FW_PARAMS_PARAM_Y_V(adap->params.portvec) |
FW_PARAMS_PARAM_Z_V(FW_PARAMS_PARAM_DEV_PHYFW_DOWNLOAD));
val = phy_fw_size;
ret = t4_query_params_rw(adap, adap->mbox, adap->pf, 0, 1,
¶m, &val, 1, true);
if (ret < 0)
return ret;
mtype = val >> 8;
maddr = (val & 0xff) << 16;
/* Copy the supplied PHY Firmware image to the adapter memory location
* allocated by the adapter firmware.
*/
if (win_lock)
spin_lock_bh(win_lock);
ret = t4_memory_rw(adap, win, mtype, maddr,
phy_fw_size, (__be32 *)phy_fw_data,
T4_MEMORY_WRITE);
if (win_lock)
spin_unlock_bh(win_lock);
if (ret)
return ret;
/* Tell the firmware that the PHY firmware image has been written to
* RAM and it can now start copying it over to the PHYs. The chip
* firmware will RESET the affected PHYs as part of this operation
* leaving them running the new PHY firmware image.
*/
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_PHYFW) |
FW_PARAMS_PARAM_Y_V(adap->params.portvec) |
FW_PARAMS_PARAM_Z_V(FW_PARAMS_PARAM_DEV_PHYFW_DOWNLOAD));
ret = t4_set_params_timeout(adap, adap->mbox, adap->pf, 0, 1,
¶m, &val, 30000);
/* If we have version number support, then check to see that the new
* firmware got loaded properly.
*/
if (phy_fw_version) {
ret = t4_phy_fw_ver(adap, &cur_phy_fw_ver);
if (ret < 0)
return ret;
if (cur_phy_fw_ver != new_phy_fw_vers) {
CH_WARN(adap, "PHY Firmware did not update: "
"version on adapter %#x, "
"version flashed %#x\n",
cur_phy_fw_ver, new_phy_fw_vers);
return -ENXIO;
}
}
return 1;
}
/**
* t4_fwcache - firmware cache operation
* @adap: the adapter
* @op : the operation (flush or flush and invalidate)
*/
int t4_fwcache(struct adapter *adap, enum fw_params_param_dev_fwcache op)
{
struct fw_params_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn =
cpu_to_be32(FW_CMD_OP_V(FW_PARAMS_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_PARAMS_CMD_PFN_V(adap->pf) |
FW_PARAMS_CMD_VFN_V(0));
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
c.param[0].mnem =
cpu_to_be32(FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_FWCACHE));
c.param[0].val = cpu_to_be32(op);
return t4_wr_mbox(adap, adap->mbox, &c, sizeof(c), NULL);
}
void t4_cim_read_pif_la(struct adapter *adap, u32 *pif_req, u32 *pif_rsp,
unsigned int *pif_req_wrptr,
unsigned int *pif_rsp_wrptr)
{
int i, j;
u32 cfg, val, req, rsp;
cfg = t4_read_reg(adap, CIM_DEBUGCFG_A);
if (cfg & LADBGEN_F)
t4_write_reg(adap, CIM_DEBUGCFG_A, cfg ^ LADBGEN_F);
val = t4_read_reg(adap, CIM_DEBUGSTS_A);
req = POLADBGWRPTR_G(val);
rsp = PILADBGWRPTR_G(val);
if (pif_req_wrptr)
*pif_req_wrptr = req;
if (pif_rsp_wrptr)
*pif_rsp_wrptr = rsp;
for (i = 0; i < CIM_PIFLA_SIZE; i++) {
for (j = 0; j < 6; j++) {
t4_write_reg(adap, CIM_DEBUGCFG_A, POLADBGRDPTR_V(req) |
PILADBGRDPTR_V(rsp));
*pif_req++ = t4_read_reg(adap, CIM_PO_LA_DEBUGDATA_A);
*pif_rsp++ = t4_read_reg(adap, CIM_PI_LA_DEBUGDATA_A);
req++;
rsp++;
}
req = (req + 2) & POLADBGRDPTR_M;
rsp = (rsp + 2) & PILADBGRDPTR_M;
}
t4_write_reg(adap, CIM_DEBUGCFG_A, cfg);
}
void t4_cim_read_ma_la(struct adapter *adap, u32 *ma_req, u32 *ma_rsp)
{
u32 cfg;
int i, j, idx;
cfg = t4_read_reg(adap, CIM_DEBUGCFG_A);
if (cfg & LADBGEN_F)
t4_write_reg(adap, CIM_DEBUGCFG_A, cfg ^ LADBGEN_F);
for (i = 0; i < CIM_MALA_SIZE; i++) {
for (j = 0; j < 5; j++) {
idx = 8 * i + j;
t4_write_reg(adap, CIM_DEBUGCFG_A, POLADBGRDPTR_V(idx) |
PILADBGRDPTR_V(idx));
*ma_req++ = t4_read_reg(adap, CIM_PO_LA_MADEBUGDATA_A);
*ma_rsp++ = t4_read_reg(adap, CIM_PI_LA_MADEBUGDATA_A);
}
}
t4_write_reg(adap, CIM_DEBUGCFG_A, cfg);
}
void t4_ulprx_read_la(struct adapter *adap, u32 *la_buf)
{
unsigned int i, j;
for (i = 0; i < 8; i++) {
u32 *p = la_buf + i;
t4_write_reg(adap, ULP_RX_LA_CTL_A, i);
j = t4_read_reg(adap, ULP_RX_LA_WRPTR_A);
t4_write_reg(adap, ULP_RX_LA_RDPTR_A, j);
for (j = 0; j < ULPRX_LA_SIZE; j++, p += 8)
*p = t4_read_reg(adap, ULP_RX_LA_RDDATA_A);
}
}
/* The ADVERT_MASK is used to mask out all of the Advertised Firmware Port
* Capabilities which we control with separate controls -- see, for instance,
* Pause Frames and Forward Error Correction. In order to determine what the
* full set of Advertised Port Capabilities are, the base Advertised Port
* Capabilities (masked by ADVERT_MASK) must be combined with the Advertised
* Port Capabilities associated with those other controls. See
* t4_link_acaps() for how this is done.
*/
#define ADVERT_MASK (FW_PORT_CAP32_SPEED_V(FW_PORT_CAP32_SPEED_M) | \
FW_PORT_CAP32_ANEG)
/**
* fwcaps16_to_caps32 - convert 16-bit Port Capabilities to 32-bits
* @caps16: a 16-bit Port Capabilities value
*
* Returns the equivalent 32-bit Port Capabilities value.
*/
static fw_port_cap32_t fwcaps16_to_caps32(fw_port_cap16_t caps16)
{
fw_port_cap32_t caps32 = 0;
#define CAP16_TO_CAP32(__cap) \
do { \
if (caps16 & FW_PORT_CAP_##__cap) \
caps32 |= FW_PORT_CAP32_##__cap; \
} while (0)
CAP16_TO_CAP32(SPEED_100M);
CAP16_TO_CAP32(SPEED_1G);
CAP16_TO_CAP32(SPEED_25G);
CAP16_TO_CAP32(SPEED_10G);
CAP16_TO_CAP32(SPEED_40G);
CAP16_TO_CAP32(SPEED_100G);
CAP16_TO_CAP32(FC_RX);
CAP16_TO_CAP32(FC_TX);
CAP16_TO_CAP32(ANEG);
CAP16_TO_CAP32(FORCE_PAUSE);
CAP16_TO_CAP32(MDIAUTO);
CAP16_TO_CAP32(MDISTRAIGHT);
CAP16_TO_CAP32(FEC_RS);
CAP16_TO_CAP32(FEC_BASER_RS);
CAP16_TO_CAP32(802_3_PAUSE);
CAP16_TO_CAP32(802_3_ASM_DIR);
#undef CAP16_TO_CAP32
return caps32;
}
/**
* fwcaps32_to_caps16 - convert 32-bit Port Capabilities to 16-bits
* @caps32: a 32-bit Port Capabilities value
*
* Returns the equivalent 16-bit Port Capabilities value. Note that
* not all 32-bit Port Capabilities can be represented in the 16-bit
* Port Capabilities and some fields/values may not make it.
*/
static fw_port_cap16_t fwcaps32_to_caps16(fw_port_cap32_t caps32)
{
fw_port_cap16_t caps16 = 0;
#define CAP32_TO_CAP16(__cap) \
do { \
if (caps32 & FW_PORT_CAP32_##__cap) \
caps16 |= FW_PORT_CAP_##__cap; \
} while (0)
CAP32_TO_CAP16(SPEED_100M);
CAP32_TO_CAP16(SPEED_1G);
CAP32_TO_CAP16(SPEED_10G);
CAP32_TO_CAP16(SPEED_25G);
CAP32_TO_CAP16(SPEED_40G);
CAP32_TO_CAP16(SPEED_100G);
CAP32_TO_CAP16(FC_RX);
CAP32_TO_CAP16(FC_TX);
CAP32_TO_CAP16(802_3_PAUSE);
CAP32_TO_CAP16(802_3_ASM_DIR);
CAP32_TO_CAP16(ANEG);
CAP32_TO_CAP16(FORCE_PAUSE);
CAP32_TO_CAP16(MDIAUTO);
CAP32_TO_CAP16(MDISTRAIGHT);
CAP32_TO_CAP16(FEC_RS);
CAP32_TO_CAP16(FEC_BASER_RS);
#undef CAP32_TO_CAP16
return caps16;
}
/* Translate Firmware Port Capabilities Pause specification to Common Code */
static inline enum cc_pause fwcap_to_cc_pause(fw_port_cap32_t fw_pause)
{
enum cc_pause cc_pause = 0;
if (fw_pause & FW_PORT_CAP32_FC_RX)
cc_pause |= PAUSE_RX;
if (fw_pause & FW_PORT_CAP32_FC_TX)
cc_pause |= PAUSE_TX;
return cc_pause;
}
/* Translate Common Code Pause specification into Firmware Port Capabilities */
static inline fw_port_cap32_t cc_to_fwcap_pause(enum cc_pause cc_pause)
{
/* Translate orthogonal RX/TX Pause Controls for L1 Configure
* commands, etc.
*/
fw_port_cap32_t fw_pause = 0;
if (cc_pause & PAUSE_RX)
fw_pause |= FW_PORT_CAP32_FC_RX;
if (cc_pause & PAUSE_TX)
fw_pause |= FW_PORT_CAP32_FC_TX;
if (!(cc_pause & PAUSE_AUTONEG))
fw_pause |= FW_PORT_CAP32_FORCE_PAUSE;
/* Translate orthogonal Pause controls into IEEE 802.3 Pause,
* Asymmetrical Pause for use in reporting to upper layer OS code, etc.
* Note that these bits are ignored in L1 Configure commands.
*/
if (cc_pause & PAUSE_RX) {
if (cc_pause & PAUSE_TX)
fw_pause |= FW_PORT_CAP32_802_3_PAUSE;
else
fw_pause |= FW_PORT_CAP32_802_3_ASM_DIR |
FW_PORT_CAP32_802_3_PAUSE;
} else if (cc_pause & PAUSE_TX) {
fw_pause |= FW_PORT_CAP32_802_3_ASM_DIR;
}
return fw_pause;
}
/* Translate Firmware Forward Error Correction specification to Common Code */
static inline enum cc_fec fwcap_to_cc_fec(fw_port_cap32_t fw_fec)
{
enum cc_fec cc_fec = 0;
if (fw_fec & FW_PORT_CAP32_FEC_RS)
cc_fec |= FEC_RS;
if (fw_fec & FW_PORT_CAP32_FEC_BASER_RS)
cc_fec |= FEC_BASER_RS;
return cc_fec;
}
/* Translate Common Code Forward Error Correction specification to Firmware */
static inline fw_port_cap32_t cc_to_fwcap_fec(enum cc_fec cc_fec)
{
fw_port_cap32_t fw_fec = 0;
if (cc_fec & FEC_RS)
fw_fec |= FW_PORT_CAP32_FEC_RS;
if (cc_fec & FEC_BASER_RS)
fw_fec |= FW_PORT_CAP32_FEC_BASER_RS;
return fw_fec;
}
/**
* t4_link_acaps - compute Link Advertised Port Capabilities
* @adapter: the adapter
* @port: the Port ID
* @lc: the Port's Link Configuration
*
* Synthesize the Advertised Port Capabilities we'll be using based on
* the base Advertised Port Capabilities (which have been filtered by
* ADVERT_MASK) plus the individual controls for things like Pause
* Frames, Forward Error Correction, MDI, etc.
*/
fw_port_cap32_t t4_link_acaps(struct adapter *adapter, unsigned int port,
struct link_config *lc)
{
fw_port_cap32_t fw_fc, fw_fec, acaps;
unsigned int fw_mdi;
char cc_fec;
fw_mdi = (FW_PORT_CAP32_MDI_V(FW_PORT_CAP32_MDI_AUTO) & lc->pcaps);
/* Convert driver coding of Pause Frame Flow Control settings into the
* Firmware's API.
*/
fw_fc = cc_to_fwcap_pause(lc->requested_fc);
/* Convert Common Code Forward Error Control settings into the
* Firmware's API. If the current Requested FEC has "Automatic"
* (IEEE 802.3) specified, then we use whatever the Firmware
* sent us as part of its IEEE 802.3-based interpretation of
* the Transceiver Module EPROM FEC parameters. Otherwise we
* use whatever is in the current Requested FEC settings.
*/
if (lc->requested_fec & FEC_AUTO)
cc_fec = fwcap_to_cc_fec(lc->def_acaps);
else
cc_fec = lc->requested_fec;
fw_fec = cc_to_fwcap_fec(cc_fec);
/* Figure out what our Requested Port Capabilities are going to be.
* Note parallel structure in t4_handle_get_port_info() and
* init_link_config().
*/
if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
acaps = lc->acaps | fw_fc | fw_fec;
lc->fc = lc->requested_fc & ~PAUSE_AUTONEG;
lc->fec = cc_fec;
} else if (lc->autoneg == AUTONEG_DISABLE) {
acaps = lc->speed_caps | fw_fc | fw_fec | fw_mdi;
lc->fc = lc->requested_fc & ~PAUSE_AUTONEG;
lc->fec = cc_fec;
} else {
acaps = lc->acaps | fw_fc | fw_fec | fw_mdi;
}
/* Some Requested Port Capabilities are trivially wrong if they exceed
* the Physical Port Capabilities. We can check that here and provide
* moderately useful feedback in the system log.
*
* Note that older Firmware doesn't have FW_PORT_CAP32_FORCE_PAUSE, so
* we need to exclude this from this check in order to maintain
* compatibility ...
*/
if ((acaps & ~lc->pcaps) & ~FW_PORT_CAP32_FORCE_PAUSE) {
dev_err(adapter->pdev_dev, "Requested Port Capabilities %#x exceed Physical Port Capabilities %#x\n",
acaps, lc->pcaps);
return -EINVAL;
}
return acaps;
}
/**
* t4_link_l1cfg_core - apply link configuration to MAC/PHY
* @adapter: the adapter
* @mbox: the Firmware Mailbox to use
* @port: the Port ID
* @lc: the Port's Link Configuration
* @sleep_ok: if true we may sleep while awaiting command completion
* @timeout: time to wait for command to finish before timing out
* (negative implies @sleep_ok=false)
*
* Set up a port's MAC and PHY according to a desired link configuration.
* - If the PHY can auto-negotiate first decide what to advertise, then
* enable/disable auto-negotiation as desired, and reset.
* - If the PHY does not auto-negotiate just reset it.
* - If auto-negotiation is off set the MAC to the proper speed/duplex/FC,
* otherwise do it later based on the outcome of auto-negotiation.
*/
int t4_link_l1cfg_core(struct adapter *adapter, unsigned int mbox,
unsigned int port, struct link_config *lc,
u8 sleep_ok, int timeout)
{
unsigned int fw_caps = adapter->params.fw_caps_support;
struct fw_port_cmd cmd;
fw_port_cap32_t rcap;
int ret;
if (!(lc->pcaps & FW_PORT_CAP32_ANEG) &&
lc->autoneg == AUTONEG_ENABLE) {
return -EINVAL;
}
/* Compute our Requested Port Capabilities and send that on to the
* Firmware.
*/
rcap = t4_link_acaps(adapter, port, lc);
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_portid = cpu_to_be32(FW_CMD_OP_V(FW_PORT_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_PORT_CMD_PORTID_V(port));
cmd.action_to_len16 =
cpu_to_be32(FW_PORT_CMD_ACTION_V(fw_caps == FW_CAPS16
? FW_PORT_ACTION_L1_CFG
: FW_PORT_ACTION_L1_CFG32) |
FW_LEN16(cmd));
if (fw_caps == FW_CAPS16)
cmd.u.l1cfg.rcap = cpu_to_be32(fwcaps32_to_caps16(rcap));
else
cmd.u.l1cfg32.rcap32 = cpu_to_be32(rcap);
ret = t4_wr_mbox_meat_timeout(adapter, mbox, &cmd, sizeof(cmd), NULL,
sleep_ok, timeout);
/* Unfortunately, even if the Requested Port Capabilities "fit" within
* the Physical Port Capabilities, some combinations of features may
* still not be legal. For example, 40Gb/s and Reed-Solomon Forward
* Error Correction. So if the Firmware rejects the L1 Configure
* request, flag that here.
*/
if (ret) {
dev_err(adapter->pdev_dev,
"Requested Port Capabilities %#x rejected, error %d\n",
rcap, -ret);
return ret;
}
return 0;
}
/**
* t4_restart_aneg - restart autonegotiation
* @adap: the adapter
* @mbox: mbox to use for the FW command
* @port: the port id
*
* Restarts autonegotiation for the selected port.
*/
int t4_restart_aneg(struct adapter *adap, unsigned int mbox, unsigned int port)
{
unsigned int fw_caps = adap->params.fw_caps_support;
struct fw_port_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_portid = cpu_to_be32(FW_CMD_OP_V(FW_PORT_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_PORT_CMD_PORTID_V(port));
c.action_to_len16 =
cpu_to_be32(FW_PORT_CMD_ACTION_V(fw_caps == FW_CAPS16
? FW_PORT_ACTION_L1_CFG
: FW_PORT_ACTION_L1_CFG32) |
FW_LEN16(c));
if (fw_caps == FW_CAPS16)
c.u.l1cfg.rcap = cpu_to_be32(FW_PORT_CAP_ANEG);
else
c.u.l1cfg32.rcap32 = cpu_to_be32(FW_PORT_CAP32_ANEG);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
typedef void (*int_handler_t)(struct adapter *adap);
struct intr_info {
unsigned int mask; /* bits to check in interrupt status */
const char *msg; /* message to print or NULL */
short stat_idx; /* stat counter to increment or -1 */
unsigned short fatal; /* whether the condition reported is fatal */
int_handler_t int_handler; /* platform-specific int handler */
};
/**
* t4_handle_intr_status - table driven interrupt handler
* @adapter: the adapter that generated the interrupt
* @reg: the interrupt status register to process
* @acts: table of interrupt actions
*
* A table driven interrupt handler that applies a set of masks to an
* interrupt status word and performs the corresponding actions if the
* interrupts described by the mask have occurred. The actions include
* optionally emitting a warning or alert message. The table is terminated
* by an entry specifying mask 0. Returns the number of fatal interrupt
* conditions.
*/
static int t4_handle_intr_status(struct adapter *adapter, unsigned int reg,
const struct intr_info *acts)
{
int fatal = 0;
unsigned int mask = 0;
unsigned int status = t4_read_reg(adapter, reg);
for ( ; acts->mask; ++acts) {
if (!(status & acts->mask))
continue;
if (acts->fatal) {
fatal++;
dev_alert(adapter->pdev_dev, "%s (0x%x)\n", acts->msg,
status & acts->mask);
} else if (acts->msg && printk_ratelimit())
dev_warn(adapter->pdev_dev, "%s (0x%x)\n", acts->msg,
status & acts->mask);
if (acts->int_handler)
acts->int_handler(adapter);
mask |= acts->mask;
}
status &= mask;
if (status) /* clear processed interrupts */
t4_write_reg(adapter, reg, status);
return fatal;
}
/*
* Interrupt handler for the PCIE module.
*/
static void pcie_intr_handler(struct adapter *adapter)
{
static const struct intr_info sysbus_intr_info[] = {
{ RNPP_F, "RXNP array parity error", -1, 1 },
{ RPCP_F, "RXPC array parity error", -1, 1 },
{ RCIP_F, "RXCIF array parity error", -1, 1 },
{ RCCP_F, "Rx completions control array parity error", -1, 1 },
{ RFTP_F, "RXFT array parity error", -1, 1 },
{ 0 }
};
static const struct intr_info pcie_port_intr_info[] = {
{ TPCP_F, "TXPC array parity error", -1, 1 },
{ TNPP_F, "TXNP array parity error", -1, 1 },
{ TFTP_F, "TXFT array parity error", -1, 1 },
{ TCAP_F, "TXCA array parity error", -1, 1 },
{ TCIP_F, "TXCIF array parity error", -1, 1 },
{ RCAP_F, "RXCA array parity error", -1, 1 },
{ OTDD_F, "outbound request TLP discarded", -1, 1 },
{ RDPE_F, "Rx data parity error", -1, 1 },
{ TDUE_F, "Tx uncorrectable data error", -1, 1 },
{ 0 }
};
static const struct intr_info pcie_intr_info[] = {
{ MSIADDRLPERR_F, "MSI AddrL parity error", -1, 1 },
{ MSIADDRHPERR_F, "MSI AddrH parity error", -1, 1 },
{ MSIDATAPERR_F, "MSI data parity error", -1, 1 },
{ MSIXADDRLPERR_F, "MSI-X AddrL parity error", -1, 1 },
{ MSIXADDRHPERR_F, "MSI-X AddrH parity error", -1, 1 },
{ MSIXDATAPERR_F, "MSI-X data parity error", -1, 1 },
{ MSIXDIPERR_F, "MSI-X DI parity error", -1, 1 },
{ PIOCPLPERR_F, "PCI PIO completion FIFO parity error", -1, 1 },
{ PIOREQPERR_F, "PCI PIO request FIFO parity error", -1, 1 },
{ TARTAGPERR_F, "PCI PCI target tag FIFO parity error", -1, 1 },
{ CCNTPERR_F, "PCI CMD channel count parity error", -1, 1 },
{ CREQPERR_F, "PCI CMD channel request parity error", -1, 1 },
{ CRSPPERR_F, "PCI CMD channel response parity error", -1, 1 },
{ DCNTPERR_F, "PCI DMA channel count parity error", -1, 1 },
{ DREQPERR_F, "PCI DMA channel request parity error", -1, 1 },
{ DRSPPERR_F, "PCI DMA channel response parity error", -1, 1 },
{ HCNTPERR_F, "PCI HMA channel count parity error", -1, 1 },
{ HREQPERR_F, "PCI HMA channel request parity error", -1, 1 },
{ HRSPPERR_F, "PCI HMA channel response parity error", -1, 1 },
{ CFGSNPPERR_F, "PCI config snoop FIFO parity error", -1, 1 },
{ FIDPERR_F, "PCI FID parity error", -1, 1 },
{ INTXCLRPERR_F, "PCI INTx clear parity error", -1, 1 },
{ MATAGPERR_F, "PCI MA tag parity error", -1, 1 },
{ PIOTAGPERR_F, "PCI PIO tag parity error", -1, 1 },
{ RXCPLPERR_F, "PCI Rx completion parity error", -1, 1 },
{ RXWRPERR_F, "PCI Rx write parity error", -1, 1 },
{ RPLPERR_F, "PCI replay buffer parity error", -1, 1 },
{ PCIESINT_F, "PCI core secondary fault", -1, 1 },
{ PCIEPINT_F, "PCI core primary fault", -1, 1 },
{ UNXSPLCPLERR_F, "PCI unexpected split completion error",
-1, 0 },
{ 0 }
};
static struct intr_info t5_pcie_intr_info[] = {
{ MSTGRPPERR_F, "Master Response Read Queue parity error",
-1, 1 },
{ MSTTIMEOUTPERR_F, "Master Timeout FIFO parity error", -1, 1 },
{ MSIXSTIPERR_F, "MSI-X STI SRAM parity error", -1, 1 },
{ MSIXADDRLPERR_F, "MSI-X AddrL parity error", -1, 1 },
{ MSIXADDRHPERR_F, "MSI-X AddrH parity error", -1, 1 },
{ MSIXDATAPERR_F, "MSI-X data parity error", -1, 1 },
{ MSIXDIPERR_F, "MSI-X DI parity error", -1, 1 },
{ PIOCPLGRPPERR_F, "PCI PIO completion Group FIFO parity error",
-1, 1 },
{ PIOREQGRPPERR_F, "PCI PIO request Group FIFO parity error",
-1, 1 },
{ TARTAGPERR_F, "PCI PCI target tag FIFO parity error", -1, 1 },
{ MSTTAGQPERR_F, "PCI master tag queue parity error", -1, 1 },
{ CREQPERR_F, "PCI CMD channel request parity error", -1, 1 },
{ CRSPPERR_F, "PCI CMD channel response parity error", -1, 1 },
{ DREQWRPERR_F, "PCI DMA channel write request parity error",
-1, 1 },
{ DREQPERR_F, "PCI DMA channel request parity error", -1, 1 },
{ DRSPPERR_F, "PCI DMA channel response parity error", -1, 1 },
{ HREQWRPERR_F, "PCI HMA channel count parity error", -1, 1 },
{ HREQPERR_F, "PCI HMA channel request parity error", -1, 1 },
{ HRSPPERR_F, "PCI HMA channel response parity error", -1, 1 },
{ CFGSNPPERR_F, "PCI config snoop FIFO parity error", -1, 1 },
{ FIDPERR_F, "PCI FID parity error", -1, 1 },
{ VFIDPERR_F, "PCI INTx clear parity error", -1, 1 },
{ MAGRPPERR_F, "PCI MA group FIFO parity error", -1, 1 },
{ PIOTAGPERR_F, "PCI PIO tag parity error", -1, 1 },
{ IPRXHDRGRPPERR_F, "PCI IP Rx header group parity error",
-1, 1 },
{ IPRXDATAGRPPERR_F, "PCI IP Rx data group parity error",
-1, 1 },
{ RPLPERR_F, "PCI IP replay buffer parity error", -1, 1 },
{ IPSOTPERR_F, "PCI IP SOT buffer parity error", -1, 1 },
{ TRGT1GRPPERR_F, "PCI TRGT1 group FIFOs parity error", -1, 1 },
{ READRSPERR_F, "Outbound read error", -1, 0 },
{ 0 }
};
int fat;
if (is_t4(adapter->params.chip))
fat = t4_handle_intr_status(adapter,
PCIE_CORE_UTL_SYSTEM_BUS_AGENT_STATUS_A,
sysbus_intr_info) +
t4_handle_intr_status(adapter,
PCIE_CORE_UTL_PCI_EXPRESS_PORT_STATUS_A,
pcie_port_intr_info) +
t4_handle_intr_status(adapter, PCIE_INT_CAUSE_A,
pcie_intr_info);
else
fat = t4_handle_intr_status(adapter, PCIE_INT_CAUSE_A,
t5_pcie_intr_info);
if (fat)
t4_fatal_err(adapter);
}
/*
* TP interrupt handler.
*/
static void tp_intr_handler(struct adapter *adapter)
{
static const struct intr_info tp_intr_info[] = {
{ 0x3fffffff, "TP parity error", -1, 1 },
{ FLMTXFLSTEMPTY_F, "TP out of Tx pages", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, TP_INT_CAUSE_A, tp_intr_info))
t4_fatal_err(adapter);
}
/*
* SGE interrupt handler.
*/
static void sge_intr_handler(struct adapter *adapter)
{
u32 v = 0, perr;
u32 err;
static const struct intr_info sge_intr_info[] = {
{ ERR_CPL_EXCEED_IQE_SIZE_F,
"SGE received CPL exceeding IQE size", -1, 1 },
{ ERR_INVALID_CIDX_INC_F,
"SGE GTS CIDX increment too large", -1, 0 },
{ ERR_CPL_OPCODE_0_F, "SGE received 0-length CPL", -1, 0 },
{ DBFIFO_LP_INT_F, NULL, -1, 0, t4_db_full },
{ ERR_DATA_CPL_ON_HIGH_QID1_F | ERR_DATA_CPL_ON_HIGH_QID0_F,
"SGE IQID > 1023 received CPL for FL", -1, 0 },
{ ERR_BAD_DB_PIDX3_F, "SGE DBP 3 pidx increment too large", -1,
0 },
{ ERR_BAD_DB_PIDX2_F, "SGE DBP 2 pidx increment too large", -1,
0 },
{ ERR_BAD_DB_PIDX1_F, "SGE DBP 1 pidx increment too large", -1,
0 },
{ ERR_BAD_DB_PIDX0_F, "SGE DBP 0 pidx increment too large", -1,
0 },
{ ERR_ING_CTXT_PRIO_F,
"SGE too many priority ingress contexts", -1, 0 },
{ INGRESS_SIZE_ERR_F, "SGE illegal ingress QID", -1, 0 },
{ EGRESS_SIZE_ERR_F, "SGE illegal egress QID", -1, 0 },
{ 0 }
};
static struct intr_info t4t5_sge_intr_info[] = {
{ ERR_DROPPED_DB_F, NULL, -1, 0, t4_db_dropped },
{ DBFIFO_HP_INT_F, NULL, -1, 0, t4_db_full },
{ ERR_EGR_CTXT_PRIO_F,
"SGE too many priority egress contexts", -1, 0 },
{ 0 }
};
perr = t4_read_reg(adapter, SGE_INT_CAUSE1_A);
if (perr) {
v |= perr;
dev_alert(adapter->pdev_dev, "SGE Cause1 Parity Error %#x\n",
perr);
}
perr = t4_read_reg(adapter, SGE_INT_CAUSE2_A);
if (perr) {
v |= perr;
dev_alert(adapter->pdev_dev, "SGE Cause2 Parity Error %#x\n",
perr);
}
if (CHELSIO_CHIP_VERSION(adapter->params.chip) >= CHELSIO_T5) {
perr = t4_read_reg(adapter, SGE_INT_CAUSE5_A);
/* Parity error (CRC) for err_T_RxCRC is trivial, ignore it */
perr &= ~ERR_T_RXCRC_F;
if (perr) {
v |= perr;
dev_alert(adapter->pdev_dev,
"SGE Cause5 Parity Error %#x\n", perr);
}
}
v |= t4_handle_intr_status(adapter, SGE_INT_CAUSE3_A, sge_intr_info);
if (CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5)
v |= t4_handle_intr_status(adapter, SGE_INT_CAUSE3_A,
t4t5_sge_intr_info);
err = t4_read_reg(adapter, SGE_ERROR_STATS_A);
if (err & ERROR_QID_VALID_F) {
dev_err(adapter->pdev_dev, "SGE error for queue %u\n",
ERROR_QID_G(err));
if (err & UNCAPTURED_ERROR_F)
dev_err(adapter->pdev_dev,
"SGE UNCAPTURED_ERROR set (clearing)\n");
t4_write_reg(adapter, SGE_ERROR_STATS_A, ERROR_QID_VALID_F |
UNCAPTURED_ERROR_F);
}
if (v != 0)
t4_fatal_err(adapter);
}
#define CIM_OBQ_INTR (OBQULP0PARERR_F | OBQULP1PARERR_F | OBQULP2PARERR_F |\
OBQULP3PARERR_F | OBQSGEPARERR_F | OBQNCSIPARERR_F)
#define CIM_IBQ_INTR (IBQTP0PARERR_F | IBQTP1PARERR_F | IBQULPPARERR_F |\
IBQSGEHIPARERR_F | IBQSGELOPARERR_F | IBQNCSIPARERR_F)
/*
* CIM interrupt handler.
*/
static void cim_intr_handler(struct adapter *adapter)
{
static const struct intr_info cim_intr_info[] = {
{ PREFDROPINT_F, "CIM control register prefetch drop", -1, 1 },
{ CIM_OBQ_INTR, "CIM OBQ parity error", -1, 1 },
{ CIM_IBQ_INTR, "CIM IBQ parity error", -1, 1 },
{ MBUPPARERR_F, "CIM mailbox uP parity error", -1, 1 },
{ MBHOSTPARERR_F, "CIM mailbox host parity error", -1, 1 },
{ TIEQINPARERRINT_F, "CIM TIEQ outgoing parity error", -1, 1 },
{ TIEQOUTPARERRINT_F, "CIM TIEQ incoming parity error", -1, 1 },
{ TIMER0INT_F, "CIM TIMER0 interrupt", -1, 1 },
{ 0 }
};
static const struct intr_info cim_upintr_info[] = {
{ RSVDSPACEINT_F, "CIM reserved space access", -1, 1 },
{ ILLTRANSINT_F, "CIM illegal transaction", -1, 1 },
{ ILLWRINT_F, "CIM illegal write", -1, 1 },
{ ILLRDINT_F, "CIM illegal read", -1, 1 },
{ ILLRDBEINT_F, "CIM illegal read BE", -1, 1 },
{ ILLWRBEINT_F, "CIM illegal write BE", -1, 1 },
{ SGLRDBOOTINT_F, "CIM single read from boot space", -1, 1 },
{ SGLWRBOOTINT_F, "CIM single write to boot space", -1, 1 },
{ BLKWRBOOTINT_F, "CIM block write to boot space", -1, 1 },
{ SGLRDFLASHINT_F, "CIM single read from flash space", -1, 1 },
{ SGLWRFLASHINT_F, "CIM single write to flash space", -1, 1 },
{ BLKWRFLASHINT_F, "CIM block write to flash space", -1, 1 },
{ SGLRDEEPROMINT_F, "CIM single EEPROM read", -1, 1 },
{ SGLWREEPROMINT_F, "CIM single EEPROM write", -1, 1 },
{ BLKRDEEPROMINT_F, "CIM block EEPROM read", -1, 1 },
{ BLKWREEPROMINT_F, "CIM block EEPROM write", -1, 1 },
{ SGLRDCTLINT_F, "CIM single read from CTL space", -1, 1 },
{ SGLWRCTLINT_F, "CIM single write to CTL space", -1, 1 },
{ BLKRDCTLINT_F, "CIM block read from CTL space", -1, 1 },
{ BLKWRCTLINT_F, "CIM block write to CTL space", -1, 1 },
{ SGLRDPLINT_F, "CIM single read from PL space", -1, 1 },
{ SGLWRPLINT_F, "CIM single write to PL space", -1, 1 },
{ BLKRDPLINT_F, "CIM block read from PL space", -1, 1 },
{ BLKWRPLINT_F, "CIM block write to PL space", -1, 1 },
{ REQOVRLOOKUPINT_F, "CIM request FIFO overwrite", -1, 1 },
{ RSPOVRLOOKUPINT_F, "CIM response FIFO overwrite", -1, 1 },
{ TIMEOUTINT_F, "CIM PIF timeout", -1, 1 },
{ TIMEOUTMAINT_F, "CIM PIF MA timeout", -1, 1 },
{ 0 }
};
u32 val, fw_err;
int fat;
fw_err = t4_read_reg(adapter, PCIE_FW_A);
if (fw_err & PCIE_FW_ERR_F)
t4_report_fw_error(adapter);
/* When the Firmware detects an internal error which normally
* wouldn't raise a Host Interrupt, it forces a CIM Timer0 interrupt
* in order to make sure the Host sees the Firmware Crash. So
* if we have a Timer0 interrupt and don't see a Firmware Crash,
* ignore the Timer0 interrupt.
*/
val = t4_read_reg(adapter, CIM_HOST_INT_CAUSE_A);
if (val & TIMER0INT_F)
if (!(fw_err & PCIE_FW_ERR_F) ||
(PCIE_FW_EVAL_G(fw_err) != PCIE_FW_EVAL_CRASH))
t4_write_reg(adapter, CIM_HOST_INT_CAUSE_A,
TIMER0INT_F);
fat = t4_handle_intr_status(adapter, CIM_HOST_INT_CAUSE_A,
cim_intr_info) +
t4_handle_intr_status(adapter, CIM_HOST_UPACC_INT_CAUSE_A,
cim_upintr_info);
if (fat)
t4_fatal_err(adapter);
}
/*
* ULP RX interrupt handler.
*/
static void ulprx_intr_handler(struct adapter *adapter)
{
static const struct intr_info ulprx_intr_info[] = {
{ 0x1800000, "ULPRX context error", -1, 1 },
{ 0x7fffff, "ULPRX parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, ULP_RX_INT_CAUSE_A, ulprx_intr_info))
t4_fatal_err(adapter);
}
/*
* ULP TX interrupt handler.
*/
static void ulptx_intr_handler(struct adapter *adapter)
{
static const struct intr_info ulptx_intr_info[] = {
{ PBL_BOUND_ERR_CH3_F, "ULPTX channel 3 PBL out of bounds", -1,
0 },
{ PBL_BOUND_ERR_CH2_F, "ULPTX channel 2 PBL out of bounds", -1,
0 },
{ PBL_BOUND_ERR_CH1_F, "ULPTX channel 1 PBL out of bounds", -1,
0 },
{ PBL_BOUND_ERR_CH0_F, "ULPTX channel 0 PBL out of bounds", -1,
0 },
{ 0xfffffff, "ULPTX parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, ULP_TX_INT_CAUSE_A, ulptx_intr_info))
t4_fatal_err(adapter);
}
/*
* PM TX interrupt handler.
*/
static void pmtx_intr_handler(struct adapter *adapter)
{
static const struct intr_info pmtx_intr_info[] = {
{ PCMD_LEN_OVFL0_F, "PMTX channel 0 pcmd too large", -1, 1 },
{ PCMD_LEN_OVFL1_F, "PMTX channel 1 pcmd too large", -1, 1 },
{ PCMD_LEN_OVFL2_F, "PMTX channel 2 pcmd too large", -1, 1 },
{ ZERO_C_CMD_ERROR_F, "PMTX 0-length pcmd", -1, 1 },
{ PMTX_FRAMING_ERROR_F, "PMTX framing error", -1, 1 },
{ OESPI_PAR_ERROR_F, "PMTX oespi parity error", -1, 1 },
{ DB_OPTIONS_PAR_ERROR_F, "PMTX db_options parity error",
-1, 1 },
{ ICSPI_PAR_ERROR_F, "PMTX icspi parity error", -1, 1 },
{ PMTX_C_PCMD_PAR_ERROR_F, "PMTX c_pcmd parity error", -1, 1},
{ 0 }
};
if (t4_handle_intr_status(adapter, PM_TX_INT_CAUSE_A, pmtx_intr_info))
t4_fatal_err(adapter);
}
/*
* PM RX interrupt handler.
*/
static void pmrx_intr_handler(struct adapter *adapter)
{
static const struct intr_info pmrx_intr_info[] = {
{ ZERO_E_CMD_ERROR_F, "PMRX 0-length pcmd", -1, 1 },
{ PMRX_FRAMING_ERROR_F, "PMRX framing error", -1, 1 },
{ OCSPI_PAR_ERROR_F, "PMRX ocspi parity error", -1, 1 },
{ DB_OPTIONS_PAR_ERROR_F, "PMRX db_options parity error",
-1, 1 },
{ IESPI_PAR_ERROR_F, "PMRX iespi parity error", -1, 1 },
{ PMRX_E_PCMD_PAR_ERROR_F, "PMRX e_pcmd parity error", -1, 1},
{ 0 }
};
if (t4_handle_intr_status(adapter, PM_RX_INT_CAUSE_A, pmrx_intr_info))
t4_fatal_err(adapter);
}
/*
* CPL switch interrupt handler.
*/
static void cplsw_intr_handler(struct adapter *adapter)
{
static const struct intr_info cplsw_intr_info[] = {
{ CIM_OP_MAP_PERR_F, "CPLSW CIM op_map parity error", -1, 1 },
{ CIM_OVFL_ERROR_F, "CPLSW CIM overflow", -1, 1 },
{ TP_FRAMING_ERROR_F, "CPLSW TP framing error", -1, 1 },
{ SGE_FRAMING_ERROR_F, "CPLSW SGE framing error", -1, 1 },
{ CIM_FRAMING_ERROR_F, "CPLSW CIM framing error", -1, 1 },
{ ZERO_SWITCH_ERROR_F, "CPLSW no-switch error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adapter, CPL_INTR_CAUSE_A, cplsw_intr_info))
t4_fatal_err(adapter);
}
/*
* LE interrupt handler.
*/
static void le_intr_handler(struct adapter *adap)
{
enum chip_type chip = CHELSIO_CHIP_VERSION(adap->params.chip);
static const struct intr_info le_intr_info[] = {
{ LIPMISS_F, "LE LIP miss", -1, 0 },
{ LIP0_F, "LE 0 LIP error", -1, 0 },
{ PARITYERR_F, "LE parity error", -1, 1 },
{ UNKNOWNCMD_F, "LE unknown command", -1, 1 },
{ REQQPARERR_F, "LE request queue parity error", -1, 1 },
{ 0 }
};
static struct intr_info t6_le_intr_info[] = {
{ T6_LIPMISS_F, "LE LIP miss", -1, 0 },
{ T6_LIP0_F, "LE 0 LIP error", -1, 0 },
{ TCAMINTPERR_F, "LE parity error", -1, 1 },
{ T6_UNKNOWNCMD_F, "LE unknown command", -1, 1 },
{ SSRAMINTPERR_F, "LE request queue parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, LE_DB_INT_CAUSE_A,
(chip <= CHELSIO_T5) ?
le_intr_info : t6_le_intr_info))
t4_fatal_err(adap);
}
/*
* MPS interrupt handler.
*/
static void mps_intr_handler(struct adapter *adapter)
{
static const struct intr_info mps_rx_intr_info[] = {
{ 0xffffff, "MPS Rx parity error", -1, 1 },
{ 0 }
};
static const struct intr_info mps_tx_intr_info[] = {
{ TPFIFO_V(TPFIFO_M), "MPS Tx TP FIFO parity error", -1, 1 },
{ NCSIFIFO_F, "MPS Tx NC-SI FIFO parity error", -1, 1 },
{ TXDATAFIFO_V(TXDATAFIFO_M), "MPS Tx data FIFO parity error",
-1, 1 },
{ TXDESCFIFO_V(TXDESCFIFO_M), "MPS Tx desc FIFO parity error",
-1, 1 },
{ BUBBLE_F, "MPS Tx underflow", -1, 1 },
{ SECNTERR_F, "MPS Tx SOP/EOP error", -1, 1 },
{ FRMERR_F, "MPS Tx framing error", -1, 1 },
{ 0 }
};
static const struct intr_info t6_mps_tx_intr_info[] = {
{ TPFIFO_V(TPFIFO_M), "MPS Tx TP FIFO parity error", -1, 1 },
{ NCSIFIFO_F, "MPS Tx NC-SI FIFO parity error", -1, 1 },
{ TXDATAFIFO_V(TXDATAFIFO_M), "MPS Tx data FIFO parity error",
-1, 1 },
{ TXDESCFIFO_V(TXDESCFIFO_M), "MPS Tx desc FIFO parity error",
-1, 1 },
/* MPS Tx Bubble is normal for T6 */
{ SECNTERR_F, "MPS Tx SOP/EOP error", -1, 1 },
{ FRMERR_F, "MPS Tx framing error", -1, 1 },
{ 0 }
};
static const struct intr_info mps_trc_intr_info[] = {
{ FILTMEM_V(FILTMEM_M), "MPS TRC filter parity error", -1, 1 },
{ PKTFIFO_V(PKTFIFO_M), "MPS TRC packet FIFO parity error",
-1, 1 },
{ MISCPERR_F, "MPS TRC misc parity error", -1, 1 },
{ 0 }
};
static const struct intr_info mps_stat_sram_intr_info[] = {
{ 0x1fffff, "MPS statistics SRAM parity error", -1, 1 },
{ 0 }
};
static const struct intr_info mps_stat_tx_intr_info[] = {
{ 0xfffff, "MPS statistics Tx FIFO parity error", -1, 1 },
{ 0 }
};
static const struct intr_info mps_stat_rx_intr_info[] = {
{ 0xffffff, "MPS statistics Rx FIFO parity error", -1, 1 },
{ 0 }
};
static const struct intr_info mps_cls_intr_info[] = {
{ MATCHSRAM_F, "MPS match SRAM parity error", -1, 1 },
{ MATCHTCAM_F, "MPS match TCAM parity error", -1, 1 },
{ HASHSRAM_F, "MPS hash SRAM parity error", -1, 1 },
{ 0 }
};
int fat;
fat = t4_handle_intr_status(adapter, MPS_RX_PERR_INT_CAUSE_A,
mps_rx_intr_info) +
t4_handle_intr_status(adapter, MPS_TX_INT_CAUSE_A,
is_t6(adapter->params.chip)
? t6_mps_tx_intr_info
: mps_tx_intr_info) +
t4_handle_intr_status(adapter, MPS_TRC_INT_CAUSE_A,
mps_trc_intr_info) +
t4_handle_intr_status(adapter, MPS_STAT_PERR_INT_CAUSE_SRAM_A,
mps_stat_sram_intr_info) +
t4_handle_intr_status(adapter, MPS_STAT_PERR_INT_CAUSE_TX_FIFO_A,
mps_stat_tx_intr_info) +
t4_handle_intr_status(adapter, MPS_STAT_PERR_INT_CAUSE_RX_FIFO_A,
mps_stat_rx_intr_info) +
t4_handle_intr_status(adapter, MPS_CLS_INT_CAUSE_A,
mps_cls_intr_info);
t4_write_reg(adapter, MPS_INT_CAUSE_A, 0);
t4_read_reg(adapter, MPS_INT_CAUSE_A); /* flush */
if (fat)
t4_fatal_err(adapter);
}
#define MEM_INT_MASK (PERR_INT_CAUSE_F | ECC_CE_INT_CAUSE_F | \
ECC_UE_INT_CAUSE_F)
/*
* EDC/MC interrupt handler.
*/
static void mem_intr_handler(struct adapter *adapter, int idx)
{
static const char name[4][7] = { "EDC0", "EDC1", "MC/MC0", "MC1" };
unsigned int addr, cnt_addr, v;
if (idx <= MEM_EDC1) {
addr = EDC_REG(EDC_INT_CAUSE_A, idx);
cnt_addr = EDC_REG(EDC_ECC_STATUS_A, idx);
} else if (idx == MEM_MC) {
if (is_t4(adapter->params.chip)) {
addr = MC_INT_CAUSE_A;
cnt_addr = MC_ECC_STATUS_A;
} else {
addr = MC_P_INT_CAUSE_A;
cnt_addr = MC_P_ECC_STATUS_A;
}
} else {
addr = MC_REG(MC_P_INT_CAUSE_A, 1);
cnt_addr = MC_REG(MC_P_ECC_STATUS_A, 1);
}
v = t4_read_reg(adapter, addr) & MEM_INT_MASK;
if (v & PERR_INT_CAUSE_F)
dev_alert(adapter->pdev_dev, "%s FIFO parity error\n",
name[idx]);
if (v & ECC_CE_INT_CAUSE_F) {
u32 cnt = ECC_CECNT_G(t4_read_reg(adapter, cnt_addr));
t4_edc_err_read(adapter, idx);
t4_write_reg(adapter, cnt_addr, ECC_CECNT_V(ECC_CECNT_M));
if (printk_ratelimit())
dev_warn(adapter->pdev_dev,
"%u %s correctable ECC data error%s\n",
cnt, name[idx], cnt > 1 ? "s" : "");
}
if (v & ECC_UE_INT_CAUSE_F)
dev_alert(adapter->pdev_dev,
"%s uncorrectable ECC data error\n", name[idx]);
t4_write_reg(adapter, addr, v);
if (v & (PERR_INT_CAUSE_F | ECC_UE_INT_CAUSE_F))
t4_fatal_err(adapter);
}
/*
* MA interrupt handler.
*/
static void ma_intr_handler(struct adapter *adap)
{
u32 v, status = t4_read_reg(adap, MA_INT_CAUSE_A);
if (status & MEM_PERR_INT_CAUSE_F) {
dev_alert(adap->pdev_dev,
"MA parity error, parity status %#x\n",
t4_read_reg(adap, MA_PARITY_ERROR_STATUS1_A));
if (is_t5(adap->params.chip))
dev_alert(adap->pdev_dev,
"MA parity error, parity status %#x\n",
t4_read_reg(adap,
MA_PARITY_ERROR_STATUS2_A));
}
if (status & MEM_WRAP_INT_CAUSE_F) {
v = t4_read_reg(adap, MA_INT_WRAP_STATUS_A);
dev_alert(adap->pdev_dev, "MA address wrap-around error by "
"client %u to address %#x\n",
MEM_WRAP_CLIENT_NUM_G(v),
MEM_WRAP_ADDRESS_G(v) << 4);
}
t4_write_reg(adap, MA_INT_CAUSE_A, status);
t4_fatal_err(adap);
}
/*
* SMB interrupt handler.
*/
static void smb_intr_handler(struct adapter *adap)
{
static const struct intr_info smb_intr_info[] = {
{ MSTTXFIFOPARINT_F, "SMB master Tx FIFO parity error", -1, 1 },
{ MSTRXFIFOPARINT_F, "SMB master Rx FIFO parity error", -1, 1 },
{ SLVFIFOPARINT_F, "SMB slave FIFO parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, SMB_INT_CAUSE_A, smb_intr_info))
t4_fatal_err(adap);
}
/*
* NC-SI interrupt handler.
*/
static void ncsi_intr_handler(struct adapter *adap)
{
static const struct intr_info ncsi_intr_info[] = {
{ CIM_DM_PRTY_ERR_F, "NC-SI CIM parity error", -1, 1 },
{ MPS_DM_PRTY_ERR_F, "NC-SI MPS parity error", -1, 1 },
{ TXFIFO_PRTY_ERR_F, "NC-SI Tx FIFO parity error", -1, 1 },
{ RXFIFO_PRTY_ERR_F, "NC-SI Rx FIFO parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, NCSI_INT_CAUSE_A, ncsi_intr_info))
t4_fatal_err(adap);
}
/*
* XGMAC interrupt handler.
*/
static void xgmac_intr_handler(struct adapter *adap, int port)
{
u32 v, int_cause_reg;
if (is_t4(adap->params.chip))
int_cause_reg = PORT_REG(port, XGMAC_PORT_INT_CAUSE_A);
else
int_cause_reg = T5_PORT_REG(port, MAC_PORT_INT_CAUSE_A);
v = t4_read_reg(adap, int_cause_reg);
v &= TXFIFO_PRTY_ERR_F | RXFIFO_PRTY_ERR_F;
if (!v)
return;
if (v & TXFIFO_PRTY_ERR_F)
dev_alert(adap->pdev_dev, "XGMAC %d Tx FIFO parity error\n",
port);
if (v & RXFIFO_PRTY_ERR_F)
dev_alert(adap->pdev_dev, "XGMAC %d Rx FIFO parity error\n",
port);
t4_write_reg(adap, PORT_REG(port, XGMAC_PORT_INT_CAUSE_A), v);
t4_fatal_err(adap);
}
/*
* PL interrupt handler.
*/
static void pl_intr_handler(struct adapter *adap)
{
static const struct intr_info pl_intr_info[] = {
{ FATALPERR_F, "T4 fatal parity error", -1, 1 },
{ PERRVFID_F, "PL VFID_MAP parity error", -1, 1 },
{ 0 }
};
if (t4_handle_intr_status(adap, PL_PL_INT_CAUSE_A, pl_intr_info))
t4_fatal_err(adap);
}
#define PF_INTR_MASK (PFSW_F)
#define GLBL_INTR_MASK (CIM_F | MPS_F | PL_F | PCIE_F | MC_F | EDC0_F | \
EDC1_F | LE_F | TP_F | MA_F | PM_TX_F | PM_RX_F | ULP_RX_F | \
CPL_SWITCH_F | SGE_F | ULP_TX_F | SF_F)
/**
* t4_slow_intr_handler - control path interrupt handler
* @adapter: the adapter
*
* T4 interrupt handler for non-data global interrupt events, e.g., errors.
* The designation 'slow' is because it involves register reads, while
* data interrupts typically don't involve any MMIOs.
*/
int t4_slow_intr_handler(struct adapter *adapter)
{
/* There are rare cases where a PL_INT_CAUSE bit may end up getting
* set when the corresponding PL_INT_ENABLE bit isn't set. It's
* easiest just to mask that case here.
*/
u32 raw_cause = t4_read_reg(adapter, PL_INT_CAUSE_A);
u32 enable = t4_read_reg(adapter, PL_INT_ENABLE_A);
u32 cause = raw_cause & enable;
if (!(cause & GLBL_INTR_MASK))
return 0;
if (cause & CIM_F)
cim_intr_handler(adapter);
if (cause & MPS_F)
mps_intr_handler(adapter);
if (cause & NCSI_F)
ncsi_intr_handler(adapter);
if (cause & PL_F)
pl_intr_handler(adapter);
if (cause & SMB_F)
smb_intr_handler(adapter);
if (cause & XGMAC0_F)
xgmac_intr_handler(adapter, 0);
if (cause & XGMAC1_F)
xgmac_intr_handler(adapter, 1);
if (cause & XGMAC_KR0_F)
xgmac_intr_handler(adapter, 2);
if (cause & XGMAC_KR1_F)
xgmac_intr_handler(adapter, 3);
if (cause & PCIE_F)
pcie_intr_handler(adapter);
if (cause & MC_F)
mem_intr_handler(adapter, MEM_MC);
if (is_t5(adapter->params.chip) && (cause & MC1_F))
mem_intr_handler(adapter, MEM_MC1);
if (cause & EDC0_F)
mem_intr_handler(adapter, MEM_EDC0);
if (cause & EDC1_F)
mem_intr_handler(adapter, MEM_EDC1);
if (cause & LE_F)
le_intr_handler(adapter);
if (cause & TP_F)
tp_intr_handler(adapter);
if (cause & MA_F)
ma_intr_handler(adapter);
if (cause & PM_TX_F)
pmtx_intr_handler(adapter);
if (cause & PM_RX_F)
pmrx_intr_handler(adapter);
if (cause & ULP_RX_F)
ulprx_intr_handler(adapter);
if (cause & CPL_SWITCH_F)
cplsw_intr_handler(adapter);
if (cause & SGE_F)
sge_intr_handler(adapter);
if (cause & ULP_TX_F)
ulptx_intr_handler(adapter);
/* Clear the interrupts just processed for which we are the master. */
t4_write_reg(adapter, PL_INT_CAUSE_A, raw_cause & GLBL_INTR_MASK);
(void)t4_read_reg(adapter, PL_INT_CAUSE_A); /* flush */
return 1;
}
/**
* t4_intr_enable - enable interrupts
* @adapter: the adapter whose interrupts should be enabled
*
* Enable PF-specific interrupts for the calling function and the top-level
* interrupt concentrator for global interrupts. Interrupts are already
* enabled at each module, here we just enable the roots of the interrupt
* hierarchies.
*
* Note: this function should be called only when the driver manages
* non PF-specific interrupts from the various HW modules. Only one PCI
* function at a time should be doing this.
*/
void t4_intr_enable(struct adapter *adapter)
{
u32 val = 0;
u32 whoami = t4_read_reg(adapter, PL_WHOAMI_A);
u32 pf = CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5 ?
SOURCEPF_G(whoami) : T6_SOURCEPF_G(whoami);
if (CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5)
val = ERR_DROPPED_DB_F | ERR_EGR_CTXT_PRIO_F | DBFIFO_HP_INT_F;
t4_write_reg(adapter, SGE_INT_ENABLE3_A, ERR_CPL_EXCEED_IQE_SIZE_F |
ERR_INVALID_CIDX_INC_F | ERR_CPL_OPCODE_0_F |
ERR_DATA_CPL_ON_HIGH_QID1_F | INGRESS_SIZE_ERR_F |
ERR_DATA_CPL_ON_HIGH_QID0_F | ERR_BAD_DB_PIDX3_F |
ERR_BAD_DB_PIDX2_F | ERR_BAD_DB_PIDX1_F |
ERR_BAD_DB_PIDX0_F | ERR_ING_CTXT_PRIO_F |
DBFIFO_LP_INT_F | EGRESS_SIZE_ERR_F | val);
t4_write_reg(adapter, MYPF_REG(PL_PF_INT_ENABLE_A), PF_INTR_MASK);
t4_set_reg_field(adapter, PL_INT_MAP0_A, 0, 1 << pf);
}
/**
* t4_intr_disable - disable interrupts
* @adapter: the adapter whose interrupts should be disabled
*
* Disable interrupts. We only disable the top-level interrupt
* concentrators. The caller must be a PCI function managing global
* interrupts.
*/
void t4_intr_disable(struct adapter *adapter)
{
u32 whoami, pf;
if (pci_channel_offline(adapter->pdev))
return;
whoami = t4_read_reg(adapter, PL_WHOAMI_A);
pf = CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5 ?
SOURCEPF_G(whoami) : T6_SOURCEPF_G(whoami);
t4_write_reg(adapter, MYPF_REG(PL_PF_INT_ENABLE_A), 0);
t4_set_reg_field(adapter, PL_INT_MAP0_A, 1 << pf, 0);
}
unsigned int t4_chip_rss_size(struct adapter *adap)
{
if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
return RSS_NENTRIES;
else
return T6_RSS_NENTRIES;
}
/**
* t4_config_rss_range - configure a portion of the RSS mapping table
* @adapter: the adapter
* @mbox: mbox to use for the FW command
* @viid: virtual interface whose RSS subtable is to be written
* @start: start entry in the table to write
* @n: how many table entries to write
* @rspq: values for the response queue lookup table
* @nrspq: number of values in @rspq
*
* Programs the selected part of the VI's RSS mapping table with the
* provided values. If @nrspq < @n the supplied values are used repeatedly
* until the full table range is populated.
*
* The caller must ensure the values in @rspq are in the range allowed for
* @viid.
*/
int t4_config_rss_range(struct adapter *adapter, int mbox, unsigned int viid,
int start, int n, const u16 *rspq, unsigned int nrspq)
{
int ret;
const u16 *rsp = rspq;
const u16 *rsp_end = rspq + nrspq;
struct fw_rss_ind_tbl_cmd cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_RSS_IND_TBL_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_RSS_IND_TBL_CMD_VIID_V(viid));
cmd.retval_len16 = cpu_to_be32(FW_LEN16(cmd));
/* each fw_rss_ind_tbl_cmd takes up to 32 entries */
while (n > 0) {
int nq = min(n, 32);
__be32 *qp = &cmd.iq0_to_iq2;
cmd.niqid = cpu_to_be16(nq);
cmd.startidx = cpu_to_be16(start);
start += nq;
n -= nq;
while (nq > 0) {
unsigned int v;
v = FW_RSS_IND_TBL_CMD_IQ0_V(*rsp);
if (++rsp >= rsp_end)
rsp = rspq;
v |= FW_RSS_IND_TBL_CMD_IQ1_V(*rsp);
if (++rsp >= rsp_end)
rsp = rspq;
v |= FW_RSS_IND_TBL_CMD_IQ2_V(*rsp);
if (++rsp >= rsp_end)
rsp = rspq;
*qp++ = cpu_to_be32(v);
nq -= 3;
}
ret = t4_wr_mbox(adapter, mbox, &cmd, sizeof(cmd), NULL);
if (ret)
return ret;
}
return 0;
}
/**
* t4_config_glbl_rss - configure the global RSS mode
* @adapter: the adapter
* @mbox: mbox to use for the FW command
* @mode: global RSS mode
* @flags: mode-specific flags
*
* Sets the global RSS mode.
*/
int t4_config_glbl_rss(struct adapter *adapter, int mbox, unsigned int mode,
unsigned int flags)
{
struct fw_rss_glb_config_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_write = cpu_to_be32(FW_CMD_OP_V(FW_RSS_GLB_CONFIG_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F);
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
if (mode == FW_RSS_GLB_CONFIG_CMD_MODE_MANUAL) {
c.u.manual.mode_pkd =
cpu_to_be32(FW_RSS_GLB_CONFIG_CMD_MODE_V(mode));
} else if (mode == FW_RSS_GLB_CONFIG_CMD_MODE_BASICVIRTUAL) {
c.u.basicvirtual.mode_pkd =
cpu_to_be32(FW_RSS_GLB_CONFIG_CMD_MODE_V(mode));
c.u.basicvirtual.synmapen_to_hashtoeplitz = cpu_to_be32(flags);
} else
return -EINVAL;
return t4_wr_mbox(adapter, mbox, &c, sizeof(c), NULL);
}
/**
* t4_config_vi_rss - configure per VI RSS settings
* @adapter: the adapter
* @mbox: mbox to use for the FW command
* @viid: the VI id
* @flags: RSS flags
* @defq: id of the default RSS queue for the VI.
*
* Configures VI-specific RSS properties.
*/
int t4_config_vi_rss(struct adapter *adapter, int mbox, unsigned int viid,
unsigned int flags, unsigned int defq)
{
struct fw_rss_vi_config_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_RSS_VI_CONFIG_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_RSS_VI_CONFIG_CMD_VIID_V(viid));
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
c.u.basicvirtual.defaultq_to_udpen = cpu_to_be32(flags |
FW_RSS_VI_CONFIG_CMD_DEFAULTQ_V(defq));
return t4_wr_mbox(adapter, mbox, &c, sizeof(c), NULL);
}
/* Read an RSS table row */
static int rd_rss_row(struct adapter *adap, int row, u32 *val)
{
t4_write_reg(adap, TP_RSS_LKP_TABLE_A, 0xfff00000 | row);
return t4_wait_op_done_val(adap, TP_RSS_LKP_TABLE_A, LKPTBLROWVLD_F, 1,
5, 0, val);
}
/**
* t4_read_rss - read the contents of the RSS mapping table
* @adapter: the adapter
* @map: holds the contents of the RSS mapping table
*
* Reads the contents of the RSS hash->queue mapping table.
*/
int t4_read_rss(struct adapter *adapter, u16 *map)
{
int i, ret, nentries;
u32 val;
nentries = t4_chip_rss_size(adapter);
for (i = 0; i < nentries / 2; ++i) {
ret = rd_rss_row(adapter, i, &val);
if (ret)
return ret;
*map++ = LKPTBLQUEUE0_G(val);
*map++ = LKPTBLQUEUE1_G(val);
}
return 0;
}
static unsigned int t4_use_ldst(struct adapter *adap)
{
return (adap->flags & CXGB4_FW_OK) && !adap->use_bd;
}
/**
* t4_tp_fw_ldst_rw - Access TP indirect register through LDST
* @adap: the adapter
* @cmd: TP fw ldst address space type
* @vals: where the indirect register values are stored/written
* @nregs: how many indirect registers to read/write
* @start_index: index of first indirect register to read/write
* @rw: Read (1) or Write (0)
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Access TP indirect registers through LDST
*/
static int t4_tp_fw_ldst_rw(struct adapter *adap, int cmd, u32 *vals,
unsigned int nregs, unsigned int start_index,
unsigned int rw, bool sleep_ok)
{
int ret = 0;
unsigned int i;
struct fw_ldst_cmd c;
for (i = 0; i < nregs; i++) {
memset(&c, 0, sizeof(c));
c.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F |
(rw ? FW_CMD_READ_F :
FW_CMD_WRITE_F) |
FW_LDST_CMD_ADDRSPACE_V(cmd));
c.cycles_to_len16 = cpu_to_be32(FW_LEN16(c));
c.u.addrval.addr = cpu_to_be32(start_index + i);
c.u.addrval.val = rw ? 0 : cpu_to_be32(vals[i]);
ret = t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c,
sleep_ok);
if (ret)
return ret;
if (rw)
vals[i] = be32_to_cpu(c.u.addrval.val);
}
return 0;
}
/**
* t4_tp_indirect_rw - Read/Write TP indirect register through LDST or backdoor
* @adap: the adapter
* @reg_addr: Address Register
* @reg_data: Data register
* @buff: where the indirect register values are stored/written
* @nregs: how many indirect registers to read/write
* @start_index: index of first indirect register to read/write
* @rw: READ(1) or WRITE(0)
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Read/Write TP indirect registers through LDST if possible.
* Else, use backdoor access
**/
static void t4_tp_indirect_rw(struct adapter *adap, u32 reg_addr, u32 reg_data,
u32 *buff, u32 nregs, u32 start_index, int rw,
bool sleep_ok)
{
int rc = -EINVAL;
int cmd;
switch (reg_addr) {
case TP_PIO_ADDR_A:
cmd = FW_LDST_ADDRSPC_TP_PIO;
break;
case TP_TM_PIO_ADDR_A:
cmd = FW_LDST_ADDRSPC_TP_TM_PIO;
break;
case TP_MIB_INDEX_A:
cmd = FW_LDST_ADDRSPC_TP_MIB;
break;
default:
goto indirect_access;
}
if (t4_use_ldst(adap))
rc = t4_tp_fw_ldst_rw(adap, cmd, buff, nregs, start_index, rw,
sleep_ok);
indirect_access:
if (rc) {
if (rw)
t4_read_indirect(adap, reg_addr, reg_data, buff, nregs,
start_index);
else
t4_write_indirect(adap, reg_addr, reg_data, buff, nregs,
start_index);
}
}
/**
* t4_tp_pio_read - Read TP PIO registers
* @adap: the adapter
* @buff: where the indirect register values are written
* @nregs: how many indirect registers to read
* @start_index: index of first indirect register to read
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Read TP PIO Registers
**/
void t4_tp_pio_read(struct adapter *adap, u32 *buff, u32 nregs,
u32 start_index, bool sleep_ok)
{
t4_tp_indirect_rw(adap, TP_PIO_ADDR_A, TP_PIO_DATA_A, buff, nregs,
start_index, 1, sleep_ok);
}
/**
* t4_tp_pio_write - Write TP PIO registers
* @adap: the adapter
* @buff: where the indirect register values are stored
* @nregs: how many indirect registers to write
* @start_index: index of first indirect register to write
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Write TP PIO Registers
**/
static void t4_tp_pio_write(struct adapter *adap, u32 *buff, u32 nregs,
u32 start_index, bool sleep_ok)
{
t4_tp_indirect_rw(adap, TP_PIO_ADDR_A, TP_PIO_DATA_A, buff, nregs,
start_index, 0, sleep_ok);
}
/**
* t4_tp_tm_pio_read - Read TP TM PIO registers
* @adap: the adapter
* @buff: where the indirect register values are written
* @nregs: how many indirect registers to read
* @start_index: index of first indirect register to read
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Read TP TM PIO Registers
**/
void t4_tp_tm_pio_read(struct adapter *adap, u32 *buff, u32 nregs,
u32 start_index, bool sleep_ok)
{
t4_tp_indirect_rw(adap, TP_TM_PIO_ADDR_A, TP_TM_PIO_DATA_A, buff,
nregs, start_index, 1, sleep_ok);
}
/**
* t4_tp_mib_read - Read TP MIB registers
* @adap: the adapter
* @buff: where the indirect register values are written
* @nregs: how many indirect registers to read
* @start_index: index of first indirect register to read
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Read TP MIB Registers
**/
void t4_tp_mib_read(struct adapter *adap, u32 *buff, u32 nregs, u32 start_index,
bool sleep_ok)
{
t4_tp_indirect_rw(adap, TP_MIB_INDEX_A, TP_MIB_DATA_A, buff, nregs,
start_index, 1, sleep_ok);
}
/**
* t4_read_rss_key - read the global RSS key
* @adap: the adapter
* @key: 10-entry array holding the 320-bit RSS key
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Reads the global 320-bit RSS key.
*/
void t4_read_rss_key(struct adapter *adap, u32 *key, bool sleep_ok)
{
t4_tp_pio_read(adap, key, 10, TP_RSS_SECRET_KEY0_A, sleep_ok);
}
/**
* t4_write_rss_key - program one of the RSS keys
* @adap: the adapter
* @key: 10-entry array holding the 320-bit RSS key
* @idx: which RSS key to write
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Writes one of the RSS keys with the given 320-bit value. If @idx is
* 0..15 the corresponding entry in the RSS key table is written,
* otherwise the global RSS key is written.
*/
void t4_write_rss_key(struct adapter *adap, const u32 *key, int idx,
bool sleep_ok)
{
u8 rss_key_addr_cnt = 16;
u32 vrt = t4_read_reg(adap, TP_RSS_CONFIG_VRT_A);
/* T6 and later: for KeyMode 3 (per-vf and per-vf scramble),
* allows access to key addresses 16-63 by using KeyWrAddrX
* as index[5:4](upper 2) into key table
*/
if ((CHELSIO_CHIP_VERSION(adap->params.chip) > CHELSIO_T5) &&
(vrt & KEYEXTEND_F) && (KEYMODE_G(vrt) == 3))
rss_key_addr_cnt = 32;
t4_tp_pio_write(adap, (void *)key, 10, TP_RSS_SECRET_KEY0_A, sleep_ok);
if (idx >= 0 && idx < rss_key_addr_cnt) {
if (rss_key_addr_cnt > 16)
t4_write_reg(adap, TP_RSS_CONFIG_VRT_A,
KEYWRADDRX_V(idx >> 4) |
T6_VFWRADDR_V(idx) | KEYWREN_F);
else
t4_write_reg(adap, TP_RSS_CONFIG_VRT_A,
KEYWRADDR_V(idx) | KEYWREN_F);
}
}
/**
* t4_read_rss_pf_config - read PF RSS Configuration Table
* @adapter: the adapter
* @index: the entry in the PF RSS table to read
* @valp: where to store the returned value
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Reads the PF RSS Configuration Table at the specified index and returns
* the value found there.
*/
void t4_read_rss_pf_config(struct adapter *adapter, unsigned int index,
u32 *valp, bool sleep_ok)
{
t4_tp_pio_read(adapter, valp, 1, TP_RSS_PF0_CONFIG_A + index, sleep_ok);
}
/**
* t4_read_rss_vf_config - read VF RSS Configuration Table
* @adapter: the adapter
* @index: the entry in the VF RSS table to read
* @vfl: where to store the returned VFL
* @vfh: where to store the returned VFH
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Reads the VF RSS Configuration Table at the specified index and returns
* the (VFL, VFH) values found there.
*/
void t4_read_rss_vf_config(struct adapter *adapter, unsigned int index,
u32 *vfl, u32 *vfh, bool sleep_ok)
{
u32 vrt, mask, data;
if (CHELSIO_CHIP_VERSION(adapter->params.chip) <= CHELSIO_T5) {
mask = VFWRADDR_V(VFWRADDR_M);
data = VFWRADDR_V(index);
} else {
mask = T6_VFWRADDR_V(T6_VFWRADDR_M);
data = T6_VFWRADDR_V(index);
}
/* Request that the index'th VF Table values be read into VFL/VFH.
*/
vrt = t4_read_reg(adapter, TP_RSS_CONFIG_VRT_A);
vrt &= ~(VFRDRG_F | VFWREN_F | KEYWREN_F | mask);
vrt |= data | VFRDEN_F;
t4_write_reg(adapter, TP_RSS_CONFIG_VRT_A, vrt);
/* Grab the VFL/VFH values ...
*/
t4_tp_pio_read(adapter, vfl, 1, TP_RSS_VFL_CONFIG_A, sleep_ok);
t4_tp_pio_read(adapter, vfh, 1, TP_RSS_VFH_CONFIG_A, sleep_ok);
}
/**
* t4_read_rss_pf_map - read PF RSS Map
* @adapter: the adapter
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Reads the PF RSS Map register and returns its value.
*/
u32 t4_read_rss_pf_map(struct adapter *adapter, bool sleep_ok)
{
u32 pfmap;
t4_tp_pio_read(adapter, &pfmap, 1, TP_RSS_PF_MAP_A, sleep_ok);
return pfmap;
}
/**
* t4_read_rss_pf_mask - read PF RSS Mask
* @adapter: the adapter
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Reads the PF RSS Mask register and returns its value.
*/
u32 t4_read_rss_pf_mask(struct adapter *adapter, bool sleep_ok)
{
u32 pfmask;
t4_tp_pio_read(adapter, &pfmask, 1, TP_RSS_PF_MSK_A, sleep_ok);
return pfmask;
}
/**
* t4_tp_get_tcp_stats - read TP's TCP MIB counters
* @adap: the adapter
* @v4: holds the TCP/IP counter values
* @v6: holds the TCP/IPv6 counter values
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Returns the values of TP's TCP/IP and TCP/IPv6 MIB counters.
* Either @v4 or @v6 may be %NULL to skip the corresponding stats.
*/
void t4_tp_get_tcp_stats(struct adapter *adap, struct tp_tcp_stats *v4,
struct tp_tcp_stats *v6, bool sleep_ok)
{
u32 val[TP_MIB_TCP_RXT_SEG_LO_A - TP_MIB_TCP_OUT_RST_A + 1];
#define STAT_IDX(x) ((TP_MIB_TCP_##x##_A) - TP_MIB_TCP_OUT_RST_A)
#define STAT(x) val[STAT_IDX(x)]
#define STAT64(x) (((u64)STAT(x##_HI) << 32) | STAT(x##_LO))
if (v4) {
t4_tp_mib_read(adap, val, ARRAY_SIZE(val),
TP_MIB_TCP_OUT_RST_A, sleep_ok);
v4->tcp_out_rsts = STAT(OUT_RST);
v4->tcp_in_segs = STAT64(IN_SEG);
v4->tcp_out_segs = STAT64(OUT_SEG);
v4->tcp_retrans_segs = STAT64(RXT_SEG);
}
if (v6) {
t4_tp_mib_read(adap, val, ARRAY_SIZE(val),
TP_MIB_TCP_V6OUT_RST_A, sleep_ok);
v6->tcp_out_rsts = STAT(OUT_RST);
v6->tcp_in_segs = STAT64(IN_SEG);
v6->tcp_out_segs = STAT64(OUT_SEG);
v6->tcp_retrans_segs = STAT64(RXT_SEG);
}
#undef STAT64
#undef STAT
#undef STAT_IDX
}
/**
* t4_tp_get_err_stats - read TP's error MIB counters
* @adap: the adapter
* @st: holds the counter values
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Returns the values of TP's error counters.
*/
void t4_tp_get_err_stats(struct adapter *adap, struct tp_err_stats *st,
bool sleep_ok)
{
int nchan = adap->params.arch.nchan;
t4_tp_mib_read(adap, st->mac_in_errs, nchan, TP_MIB_MAC_IN_ERR_0_A,
sleep_ok);
t4_tp_mib_read(adap, st->hdr_in_errs, nchan, TP_MIB_HDR_IN_ERR_0_A,
sleep_ok);
t4_tp_mib_read(adap, st->tcp_in_errs, nchan, TP_MIB_TCP_IN_ERR_0_A,
sleep_ok);
t4_tp_mib_read(adap, st->tnl_cong_drops, nchan,
TP_MIB_TNL_CNG_DROP_0_A, sleep_ok);
t4_tp_mib_read(adap, st->ofld_chan_drops, nchan,
TP_MIB_OFD_CHN_DROP_0_A, sleep_ok);
t4_tp_mib_read(adap, st->tnl_tx_drops, nchan, TP_MIB_TNL_DROP_0_A,
sleep_ok);
t4_tp_mib_read(adap, st->ofld_vlan_drops, nchan,
TP_MIB_OFD_VLN_DROP_0_A, sleep_ok);
t4_tp_mib_read(adap, st->tcp6_in_errs, nchan,
TP_MIB_TCP_V6IN_ERR_0_A, sleep_ok);
t4_tp_mib_read(adap, &st->ofld_no_neigh, 2, TP_MIB_OFD_ARP_DROP_A,
sleep_ok);
}
/**
* t4_tp_get_cpl_stats - read TP's CPL MIB counters
* @adap: the adapter
* @st: holds the counter values
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Returns the values of TP's CPL counters.
*/
void t4_tp_get_cpl_stats(struct adapter *adap, struct tp_cpl_stats *st,
bool sleep_ok)
{
int nchan = adap->params.arch.nchan;
t4_tp_mib_read(adap, st->req, nchan, TP_MIB_CPL_IN_REQ_0_A, sleep_ok);
t4_tp_mib_read(adap, st->rsp, nchan, TP_MIB_CPL_OUT_RSP_0_A, sleep_ok);
}
/**
* t4_tp_get_rdma_stats - read TP's RDMA MIB counters
* @adap: the adapter
* @st: holds the counter values
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Returns the values of TP's RDMA counters.
*/
void t4_tp_get_rdma_stats(struct adapter *adap, struct tp_rdma_stats *st,
bool sleep_ok)
{
t4_tp_mib_read(adap, &st->rqe_dfr_pkt, 2, TP_MIB_RQE_DFR_PKT_A,
sleep_ok);
}
/**
* t4_get_fcoe_stats - read TP's FCoE MIB counters for a port
* @adap: the adapter
* @idx: the port index
* @st: holds the counter values
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Returns the values of TP's FCoE counters for the selected port.
*/
void t4_get_fcoe_stats(struct adapter *adap, unsigned int idx,
struct tp_fcoe_stats *st, bool sleep_ok)
{
u32 val[2];
t4_tp_mib_read(adap, &st->frames_ddp, 1, TP_MIB_FCOE_DDP_0_A + idx,
sleep_ok);
t4_tp_mib_read(adap, &st->frames_drop, 1,
TP_MIB_FCOE_DROP_0_A + idx, sleep_ok);
t4_tp_mib_read(adap, val, 2, TP_MIB_FCOE_BYTE_0_HI_A + 2 * idx,
sleep_ok);
st->octets_ddp = ((u64)val[0] << 32) | val[1];
}
/**
* t4_get_usm_stats - read TP's non-TCP DDP MIB counters
* @adap: the adapter
* @st: holds the counter values
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Returns the values of TP's counters for non-TCP directly-placed packets.
*/
void t4_get_usm_stats(struct adapter *adap, struct tp_usm_stats *st,
bool sleep_ok)
{
u32 val[4];
t4_tp_mib_read(adap, val, 4, TP_MIB_USM_PKTS_A, sleep_ok);
st->frames = val[0];
st->drops = val[1];
st->octets = ((u64)val[2] << 32) | val[3];
}
/**
* t4_read_mtu_tbl - returns the values in the HW path MTU table
* @adap: the adapter
* @mtus: where to store the MTU values
* @mtu_log: where to store the MTU base-2 log (may be %NULL)
*
* Reads the HW path MTU table.
*/
void t4_read_mtu_tbl(struct adapter *adap, u16 *mtus, u8 *mtu_log)
{
u32 v;
int i;
for (i = 0; i < NMTUS; ++i) {
t4_write_reg(adap, TP_MTU_TABLE_A,
MTUINDEX_V(0xff) | MTUVALUE_V(i));
v = t4_read_reg(adap, TP_MTU_TABLE_A);
mtus[i] = MTUVALUE_G(v);
if (mtu_log)
mtu_log[i] = MTUWIDTH_G(v);
}
}
/**
* t4_read_cong_tbl - reads the congestion control table
* @adap: the adapter
* @incr: where to store the alpha values
*
* Reads the additive increments programmed into the HW congestion
* control table.
*/
void t4_read_cong_tbl(struct adapter *adap, u16 incr[NMTUS][NCCTRL_WIN])
{
unsigned int mtu, w;
for (mtu = 0; mtu < NMTUS; ++mtu)
for (w = 0; w < NCCTRL_WIN; ++w) {
t4_write_reg(adap, TP_CCTRL_TABLE_A,
ROWINDEX_V(0xffff) | (mtu << 5) | w);
incr[mtu][w] = (u16)t4_read_reg(adap,
TP_CCTRL_TABLE_A) & 0x1fff;
}
}
/**
* t4_tp_wr_bits_indirect - set/clear bits in an indirect TP register
* @adap: the adapter
* @addr: the indirect TP register address
* @mask: specifies the field within the register to modify
* @val: new value for the field
*
* Sets a field of an indirect TP register to the given value.
*/
void t4_tp_wr_bits_indirect(struct adapter *adap, unsigned int addr,
unsigned int mask, unsigned int val)
{
t4_write_reg(adap, TP_PIO_ADDR_A, addr);
val |= t4_read_reg(adap, TP_PIO_DATA_A) & ~mask;
t4_write_reg(adap, TP_PIO_DATA_A, val);
}
/**
* init_cong_ctrl - initialize congestion control parameters
* @a: the alpha values for congestion control
* @b: the beta values for congestion control
*
* Initialize the congestion control parameters.
*/
static void init_cong_ctrl(unsigned short *a, unsigned short *b)
{
a[0] = a[1] = a[2] = a[3] = a[4] = a[5] = a[6] = a[7] = a[8] = 1;
a[9] = 2;
a[10] = 3;
a[11] = 4;
a[12] = 5;
a[13] = 6;
a[14] = 7;
a[15] = 8;
a[16] = 9;
a[17] = 10;
a[18] = 14;
a[19] = 17;
a[20] = 21;
a[21] = 25;
a[22] = 30;
a[23] = 35;
a[24] = 45;
a[25] = 60;
a[26] = 80;
a[27] = 100;
a[28] = 200;
a[29] = 300;
a[30] = 400;
a[31] = 500;
b[0] = b[1] = b[2] = b[3] = b[4] = b[5] = b[6] = b[7] = b[8] = 0;
b[9] = b[10] = 1;
b[11] = b[12] = 2;
b[13] = b[14] = b[15] = b[16] = 3;
b[17] = b[18] = b[19] = b[20] = b[21] = 4;
b[22] = b[23] = b[24] = b[25] = b[26] = b[27] = 5;
b[28] = b[29] = 6;
b[30] = b[31] = 7;
}
/* The minimum additive increment value for the congestion control table */
#define CC_MIN_INCR 2U
/**
* t4_load_mtus - write the MTU and congestion control HW tables
* @adap: the adapter
* @mtus: the values for the MTU table
* @alpha: the values for the congestion control alpha parameter
* @beta: the values for the congestion control beta parameter
*
* Write the HW MTU table with the supplied MTUs and the high-speed
* congestion control table with the supplied alpha, beta, and MTUs.
* We write the two tables together because the additive increments
* depend on the MTUs.
*/
void t4_load_mtus(struct adapter *adap, const unsigned short *mtus,
const unsigned short *alpha, const unsigned short *beta)
{
static const unsigned int avg_pkts[NCCTRL_WIN] = {
2, 6, 10, 14, 20, 28, 40, 56, 80, 112, 160, 224, 320, 448, 640,
896, 1281, 1792, 2560, 3584, 5120, 7168, 10240, 14336, 20480,
28672, 40960, 57344, 81920, 114688, 163840, 229376
};
unsigned int i, w;
for (i = 0; i < NMTUS; ++i) {
unsigned int mtu = mtus[i];
unsigned int log2 = fls(mtu);
if (!(mtu & ((1 << log2) >> 2))) /* round */
log2--;
t4_write_reg(adap, TP_MTU_TABLE_A, MTUINDEX_V(i) |
MTUWIDTH_V(log2) | MTUVALUE_V(mtu));
for (w = 0; w < NCCTRL_WIN; ++w) {
unsigned int inc;
inc = max(((mtu - 40) * alpha[w]) / avg_pkts[w],
CC_MIN_INCR);
t4_write_reg(adap, TP_CCTRL_TABLE_A, (i << 21) |
(w << 16) | (beta[w] << 13) | inc);
}
}
}
/* Calculates a rate in bytes/s given the number of 256-byte units per 4K core
* clocks. The formula is
*
* bytes/s = bytes256 * 256 * ClkFreq / 4096
*
* which is equivalent to
*
* bytes/s = 62.5 * bytes256 * ClkFreq_ms
*/
static u64 chan_rate(struct adapter *adap, unsigned int bytes256)
{
u64 v = bytes256 * adap->params.vpd.cclk;
return v * 62 + v / 2;
}
/**
* t4_get_chan_txrate - get the current per channel Tx rates
* @adap: the adapter
* @nic_rate: rates for NIC traffic
* @ofld_rate: rates for offloaded traffic
*
* Return the current Tx rates in bytes/s for NIC and offloaded traffic
* for each channel.
*/
void t4_get_chan_txrate(struct adapter *adap, u64 *nic_rate, u64 *ofld_rate)
{
u32 v;
v = t4_read_reg(adap, TP_TX_TRATE_A);
nic_rate[0] = chan_rate(adap, TNLRATE0_G(v));
nic_rate[1] = chan_rate(adap, TNLRATE1_G(v));
if (adap->params.arch.nchan == NCHAN) {
nic_rate[2] = chan_rate(adap, TNLRATE2_G(v));
nic_rate[3] = chan_rate(adap, TNLRATE3_G(v));
}
v = t4_read_reg(adap, TP_TX_ORATE_A);
ofld_rate[0] = chan_rate(adap, OFDRATE0_G(v));
ofld_rate[1] = chan_rate(adap, OFDRATE1_G(v));
if (adap->params.arch.nchan == NCHAN) {
ofld_rate[2] = chan_rate(adap, OFDRATE2_G(v));
ofld_rate[3] = chan_rate(adap, OFDRATE3_G(v));
}
}
/**
* t4_set_trace_filter - configure one of the tracing filters
* @adap: the adapter
* @tp: the desired trace filter parameters
* @idx: which filter to configure
* @enable: whether to enable or disable the filter
*
* Configures one of the tracing filters available in HW. If @enable is
* %0 @tp is not examined and may be %NULL. The user is responsible to
* set the single/multiple trace mode by writing to MPS_TRC_CFG_A register
*/
int t4_set_trace_filter(struct adapter *adap, const struct trace_params *tp,
int idx, int enable)
{
int i, ofst = idx * 4;
u32 data_reg, mask_reg, cfg;
if (!enable) {
t4_write_reg(adap, MPS_TRC_FILTER_MATCH_CTL_A_A + ofst, 0);
return 0;
}
cfg = t4_read_reg(adap, MPS_TRC_CFG_A);
if (cfg & TRCMULTIFILTER_F) {
/* If multiple tracers are enabled, then maximum
* capture size is 2.5KB (FIFO size of a single channel)
* minus 2 flits for CPL_TRACE_PKT header.
*/
if (tp->snap_len > ((10 * 1024 / 4) - (2 * 8)))
return -EINVAL;
} else {
/* If multiple tracers are disabled, to avoid deadlocks
* maximum packet capture size of 9600 bytes is recommended.
* Also in this mode, only trace0 can be enabled and running.
*/
if (tp->snap_len > 9600 || idx)
return -EINVAL;
}
if (tp->port > (is_t4(adap->params.chip) ? 11 : 19) || tp->invert > 1 ||
tp->skip_len > TFLENGTH_M || tp->skip_ofst > TFOFFSET_M ||
tp->min_len > TFMINPKTSIZE_M)
return -EINVAL;
/* stop the tracer we'll be changing */
t4_write_reg(adap, MPS_TRC_FILTER_MATCH_CTL_A_A + ofst, 0);
idx *= (MPS_TRC_FILTER1_MATCH_A - MPS_TRC_FILTER0_MATCH_A);
data_reg = MPS_TRC_FILTER0_MATCH_A + idx;
mask_reg = MPS_TRC_FILTER0_DONT_CARE_A + idx;
for (i = 0; i < TRACE_LEN / 4; i++, data_reg += 4, mask_reg += 4) {
t4_write_reg(adap, data_reg, tp->data[i]);
t4_write_reg(adap, mask_reg, ~tp->mask[i]);
}
t4_write_reg(adap, MPS_TRC_FILTER_MATCH_CTL_B_A + ofst,
TFCAPTUREMAX_V(tp->snap_len) |
TFMINPKTSIZE_V(tp->min_len));
t4_write_reg(adap, MPS_TRC_FILTER_MATCH_CTL_A_A + ofst,
TFOFFSET_V(tp->skip_ofst) | TFLENGTH_V(tp->skip_len) |
(is_t4(adap->params.chip) ?
TFPORT_V(tp->port) | TFEN_F | TFINVERTMATCH_V(tp->invert) :
T5_TFPORT_V(tp->port) | T5_TFEN_F |
T5_TFINVERTMATCH_V(tp->invert)));
return 0;
}
/**
* t4_get_trace_filter - query one of the tracing filters
* @adap: the adapter
* @tp: the current trace filter parameters
* @idx: which trace filter to query
* @enabled: non-zero if the filter is enabled
*
* Returns the current settings of one of the HW tracing filters.
*/
void t4_get_trace_filter(struct adapter *adap, struct trace_params *tp, int idx,
int *enabled)
{
u32 ctla, ctlb;
int i, ofst = idx * 4;
u32 data_reg, mask_reg;
ctla = t4_read_reg(adap, MPS_TRC_FILTER_MATCH_CTL_A_A + ofst);
ctlb = t4_read_reg(adap, MPS_TRC_FILTER_MATCH_CTL_B_A + ofst);
if (is_t4(adap->params.chip)) {
*enabled = !!(ctla & TFEN_F);
tp->port = TFPORT_G(ctla);
tp->invert = !!(ctla & TFINVERTMATCH_F);
} else {
*enabled = !!(ctla & T5_TFEN_F);
tp->port = T5_TFPORT_G(ctla);
tp->invert = !!(ctla & T5_TFINVERTMATCH_F);
}
tp->snap_len = TFCAPTUREMAX_G(ctlb);
tp->min_len = TFMINPKTSIZE_G(ctlb);
tp->skip_ofst = TFOFFSET_G(ctla);
tp->skip_len = TFLENGTH_G(ctla);
ofst = (MPS_TRC_FILTER1_MATCH_A - MPS_TRC_FILTER0_MATCH_A) * idx;
data_reg = MPS_TRC_FILTER0_MATCH_A + ofst;
mask_reg = MPS_TRC_FILTER0_DONT_CARE_A + ofst;
for (i = 0; i < TRACE_LEN / 4; i++, data_reg += 4, mask_reg += 4) {
tp->mask[i] = ~t4_read_reg(adap, mask_reg);
tp->data[i] = t4_read_reg(adap, data_reg) & tp->mask[i];
}
}
/**
* t4_pmtx_get_stats - returns the HW stats from PMTX
* @adap: the adapter
* @cnt: where to store the count statistics
* @cycles: where to store the cycle statistics
*
* Returns performance statistics from PMTX.
*/
void t4_pmtx_get_stats(struct adapter *adap, u32 cnt[], u64 cycles[])
{
int i;
u32 data[2];
for (i = 0; i < adap->params.arch.pm_stats_cnt; i++) {
t4_write_reg(adap, PM_TX_STAT_CONFIG_A, i + 1);
cnt[i] = t4_read_reg(adap, PM_TX_STAT_COUNT_A);
if (is_t4(adap->params.chip)) {
cycles[i] = t4_read_reg64(adap, PM_TX_STAT_LSB_A);
} else {
t4_read_indirect(adap, PM_TX_DBG_CTRL_A,
PM_TX_DBG_DATA_A, data, 2,
PM_TX_DBG_STAT_MSB_A);
cycles[i] = (((u64)data[0] << 32) | data[1]);
}
}
}
/**
* t4_pmrx_get_stats - returns the HW stats from PMRX
* @adap: the adapter
* @cnt: where to store the count statistics
* @cycles: where to store the cycle statistics
*
* Returns performance statistics from PMRX.
*/
void t4_pmrx_get_stats(struct adapter *adap, u32 cnt[], u64 cycles[])
{
int i;
u32 data[2];
for (i = 0; i < adap->params.arch.pm_stats_cnt; i++) {
t4_write_reg(adap, PM_RX_STAT_CONFIG_A, i + 1);
cnt[i] = t4_read_reg(adap, PM_RX_STAT_COUNT_A);
if (is_t4(adap->params.chip)) {
cycles[i] = t4_read_reg64(adap, PM_RX_STAT_LSB_A);
} else {
t4_read_indirect(adap, PM_RX_DBG_CTRL_A,
PM_RX_DBG_DATA_A, data, 2,
PM_RX_DBG_STAT_MSB_A);
cycles[i] = (((u64)data[0] << 32) | data[1]);
}
}
}
/**
* compute_mps_bg_map - compute the MPS Buffer Group Map for a Port
* @adapter: the adapter
* @pidx: the port index
*
* Computes and returns a bitmap indicating which MPS buffer groups are
* associated with the given Port. Bit i is set if buffer group i is
* used by the Port.
*/
static inline unsigned int compute_mps_bg_map(struct adapter *adapter,
int pidx)
{
unsigned int chip_version, nports;
chip_version = CHELSIO_CHIP_VERSION(adapter->params.chip);
nports = 1 << NUMPORTS_G(t4_read_reg(adapter, MPS_CMN_CTL_A));
switch (chip_version) {
case CHELSIO_T4:
case CHELSIO_T5:
switch (nports) {
case 1: return 0xf;
case 2: return 3 << (2 * pidx);
case 4: return 1 << pidx;
}
break;
case CHELSIO_T6:
switch (nports) {
case 2: return 1 << (2 * pidx);
}
break;
}
dev_err(adapter->pdev_dev, "Need MPS Buffer Group Map for Chip %0x, Nports %d\n",
chip_version, nports);
return 0;
}
/**
* t4_get_mps_bg_map - return the buffer groups associated with a port
* @adapter: the adapter
* @pidx: the port index
*
* Returns a bitmap indicating which MPS buffer groups are associated
* with the given Port. Bit i is set if buffer group i is used by the
* Port.
*/
unsigned int t4_get_mps_bg_map(struct adapter *adapter, int pidx)
{
u8 *mps_bg_map;
unsigned int nports;
nports = 1 << NUMPORTS_G(t4_read_reg(adapter, MPS_CMN_CTL_A));
if (pidx >= nports) {
CH_WARN(adapter, "MPS Port Index %d >= Nports %d\n",
pidx, nports);
return 0;
}
/* If we've already retrieved/computed this, just return the result.
*/
mps_bg_map = adapter->params.mps_bg_map;
if (mps_bg_map[pidx])
return mps_bg_map[pidx];
/* Newer Firmware can tell us what the MPS Buffer Group Map is.
* If we're talking to such Firmware, let it tell us. If the new
* API isn't supported, revert back to old hardcoded way. The value
* obtained from Firmware is encoded in below format:
*
* val = (( MPSBGMAP[Port 3] << 24 ) |
* ( MPSBGMAP[Port 2] << 16 ) |
* ( MPSBGMAP[Port 1] << 8 ) |
* ( MPSBGMAP[Port 0] << 0 ))
*/
if (adapter->flags & CXGB4_FW_OK) {
u32 param, val;
int ret;
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_MPSBGMAP));
ret = t4_query_params_ns(adapter, adapter->mbox, adapter->pf,
0, 1, ¶m, &val);
if (!ret) {
int p;
/* Store the BG Map for all of the Ports in order to
* avoid more calls to the Firmware in the future.
*/
for (p = 0; p < MAX_NPORTS; p++, val >>= 8)
mps_bg_map[p] = val & 0xff;
return mps_bg_map[pidx];
}
}
/* Either we're not talking to the Firmware or we're dealing with
* older Firmware which doesn't support the new API to get the MPS
* Buffer Group Map. Fall back to computing it ourselves.
*/
mps_bg_map[pidx] = compute_mps_bg_map(adapter, pidx);
return mps_bg_map[pidx];
}
/**
* t4_get_tp_e2c_map - return the E2C channel map associated with a port
* @adapter: the adapter
* @pidx: the port index
*/
static unsigned int t4_get_tp_e2c_map(struct adapter *adapter, int pidx)
{
unsigned int nports;
u32 param, val = 0;
int ret;
nports = 1 << NUMPORTS_G(t4_read_reg(adapter, MPS_CMN_CTL_A));
if (pidx >= nports) {
CH_WARN(adapter, "TP E2C Channel Port Index %d >= Nports %d\n",
pidx, nports);
return 0;
}
/* FW version >= 1.16.44.0 can determine E2C channel map using
* FW_PARAMS_PARAM_DEV_TPCHMAP API.
*/
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_TPCHMAP));
ret = t4_query_params_ns(adapter, adapter->mbox, adapter->pf,
0, 1, ¶m, &val);
if (!ret)
return (val >> (8 * pidx)) & 0xff;
return 0;
}
/**
* t4_get_tp_ch_map - return TP ingress channels associated with a port
* @adap: the adapter
* @pidx: the port index
*
* Returns a bitmap indicating which TP Ingress Channels are associated
* with a given Port. Bit i is set if TP Ingress Channel i is used by
* the Port.
*/
unsigned int t4_get_tp_ch_map(struct adapter *adap, int pidx)
{
unsigned int chip_version = CHELSIO_CHIP_VERSION(adap->params.chip);
unsigned int nports = 1 << NUMPORTS_G(t4_read_reg(adap, MPS_CMN_CTL_A));
if (pidx >= nports) {
dev_warn(adap->pdev_dev, "TP Port Index %d >= Nports %d\n",
pidx, nports);
return 0;
}
switch (chip_version) {
case CHELSIO_T4:
case CHELSIO_T5:
/* Note that this happens to be the same values as the MPS
* Buffer Group Map for these Chips. But we replicate the code
* here because they're really separate concepts.
*/
switch (nports) {
case 1: return 0xf;
case 2: return 3 << (2 * pidx);
case 4: return 1 << pidx;
}
break;
case CHELSIO_T6:
switch (nports) {
case 1:
case 2: return 1 << pidx;
}
break;
}
dev_err(adap->pdev_dev, "Need TP Channel Map for Chip %0x, Nports %d\n",
chip_version, nports);
return 0;
}
/**
* t4_get_port_type_description - return Port Type string description
* @port_type: firmware Port Type enumeration
*/
const char *t4_get_port_type_description(enum fw_port_type port_type)
{
static const char *const port_type_description[] = {
"Fiber_XFI",
"Fiber_XAUI",
"BT_SGMII",
"BT_XFI",
"BT_XAUI",
"KX4",
"CX4",
"KX",
"KR",
"SFP",
"BP_AP",
"BP4_AP",
"QSFP_10G",
"QSA",
"QSFP",
"BP40_BA",
"KR4_100G",
"CR4_QSFP",
"CR_QSFP",
"CR2_QSFP",
"SFP28",
"KR_SFP28",
"KR_XLAUI"
};
if (port_type < ARRAY_SIZE(port_type_description))
return port_type_description[port_type];
return "UNKNOWN";
}
/**
* t4_get_port_stats_offset - collect port stats relative to a previous
* snapshot
* @adap: The adapter
* @idx: The port
* @stats: Current stats to fill
* @offset: Previous stats snapshot
*/
void t4_get_port_stats_offset(struct adapter *adap, int idx,
struct port_stats *stats,
struct port_stats *offset)
{
u64 *s, *o;
int i;
t4_get_port_stats(adap, idx, stats);
for (i = 0, s = (u64 *)stats, o = (u64 *)offset;
i < (sizeof(struct port_stats) / sizeof(u64));
i++, s++, o++)
*s -= *o;
}
/**
* t4_get_port_stats - collect port statistics
* @adap: the adapter
* @idx: the port index
* @p: the stats structure to fill
*
* Collect statistics related to the given port from HW.
*/
void t4_get_port_stats(struct adapter *adap, int idx, struct port_stats *p)
{
u32 bgmap = t4_get_mps_bg_map(adap, idx);
u32 stat_ctl = t4_read_reg(adap, MPS_STAT_CTL_A);
#define GET_STAT(name) \
t4_read_reg64(adap, \
(is_t4(adap->params.chip) ? PORT_REG(idx, MPS_PORT_STAT_##name##_L) : \
T5_PORT_REG(idx, MPS_PORT_STAT_##name##_L)))
#define GET_STAT_COM(name) t4_read_reg64(adap, MPS_STAT_##name##_L)
p->tx_octets = GET_STAT(TX_PORT_BYTES);
p->tx_frames = GET_STAT(TX_PORT_FRAMES);
p->tx_bcast_frames = GET_STAT(TX_PORT_BCAST);
p->tx_mcast_frames = GET_STAT(TX_PORT_MCAST);
p->tx_ucast_frames = GET_STAT(TX_PORT_UCAST);
p->tx_error_frames = GET_STAT(TX_PORT_ERROR);
p->tx_frames_64 = GET_STAT(TX_PORT_64B);
p->tx_frames_65_127 = GET_STAT(TX_PORT_65B_127B);
p->tx_frames_128_255 = GET_STAT(TX_PORT_128B_255B);
p->tx_frames_256_511 = GET_STAT(TX_PORT_256B_511B);
p->tx_frames_512_1023 = GET_STAT(TX_PORT_512B_1023B);
p->tx_frames_1024_1518 = GET_STAT(TX_PORT_1024B_1518B);
p->tx_frames_1519_max = GET_STAT(TX_PORT_1519B_MAX);
p->tx_drop = GET_STAT(TX_PORT_DROP);
p->tx_pause = GET_STAT(TX_PORT_PAUSE);
p->tx_ppp0 = GET_STAT(TX_PORT_PPP0);
p->tx_ppp1 = GET_STAT(TX_PORT_PPP1);
p->tx_ppp2 = GET_STAT(TX_PORT_PPP2);
p->tx_ppp3 = GET_STAT(TX_PORT_PPP3);
p->tx_ppp4 = GET_STAT(TX_PORT_PPP4);
p->tx_ppp5 = GET_STAT(TX_PORT_PPP5);
p->tx_ppp6 = GET_STAT(TX_PORT_PPP6);
p->tx_ppp7 = GET_STAT(TX_PORT_PPP7);
if (CHELSIO_CHIP_VERSION(adap->params.chip) >= CHELSIO_T5) {
if (stat_ctl & COUNTPAUSESTATTX_F)
p->tx_frames_64 -= p->tx_pause;
if (stat_ctl & COUNTPAUSEMCTX_F)
p->tx_mcast_frames -= p->tx_pause;
}
p->rx_octets = GET_STAT(RX_PORT_BYTES);
p->rx_frames = GET_STAT(RX_PORT_FRAMES);
p->rx_bcast_frames = GET_STAT(RX_PORT_BCAST);
p->rx_mcast_frames = GET_STAT(RX_PORT_MCAST);
p->rx_ucast_frames = GET_STAT(RX_PORT_UCAST);
p->rx_too_long = GET_STAT(RX_PORT_MTU_ERROR);
p->rx_jabber = GET_STAT(RX_PORT_MTU_CRC_ERROR);
p->rx_fcs_err = GET_STAT(RX_PORT_CRC_ERROR);
p->rx_len_err = GET_STAT(RX_PORT_LEN_ERROR);
p->rx_symbol_err = GET_STAT(RX_PORT_SYM_ERROR);
p->rx_runt = GET_STAT(RX_PORT_LESS_64B);
p->rx_frames_64 = GET_STAT(RX_PORT_64B);
p->rx_frames_65_127 = GET_STAT(RX_PORT_65B_127B);
p->rx_frames_128_255 = GET_STAT(RX_PORT_128B_255B);
p->rx_frames_256_511 = GET_STAT(RX_PORT_256B_511B);
p->rx_frames_512_1023 = GET_STAT(RX_PORT_512B_1023B);
p->rx_frames_1024_1518 = GET_STAT(RX_PORT_1024B_1518B);
p->rx_frames_1519_max = GET_STAT(RX_PORT_1519B_MAX);
p->rx_pause = GET_STAT(RX_PORT_PAUSE);
p->rx_ppp0 = GET_STAT(RX_PORT_PPP0);
p->rx_ppp1 = GET_STAT(RX_PORT_PPP1);
p->rx_ppp2 = GET_STAT(RX_PORT_PPP2);
p->rx_ppp3 = GET_STAT(RX_PORT_PPP3);
p->rx_ppp4 = GET_STAT(RX_PORT_PPP4);
p->rx_ppp5 = GET_STAT(RX_PORT_PPP5);
p->rx_ppp6 = GET_STAT(RX_PORT_PPP6);
p->rx_ppp7 = GET_STAT(RX_PORT_PPP7);
if (CHELSIO_CHIP_VERSION(adap->params.chip) >= CHELSIO_T5) {
if (stat_ctl & COUNTPAUSESTATRX_F)
p->rx_frames_64 -= p->rx_pause;
if (stat_ctl & COUNTPAUSEMCRX_F)
p->rx_mcast_frames -= p->rx_pause;
}
p->rx_ovflow0 = (bgmap & 1) ? GET_STAT_COM(RX_BG_0_MAC_DROP_FRAME) : 0;
p->rx_ovflow1 = (bgmap & 2) ? GET_STAT_COM(RX_BG_1_MAC_DROP_FRAME) : 0;
p->rx_ovflow2 = (bgmap & 4) ? GET_STAT_COM(RX_BG_2_MAC_DROP_FRAME) : 0;
p->rx_ovflow3 = (bgmap & 8) ? GET_STAT_COM(RX_BG_3_MAC_DROP_FRAME) : 0;
p->rx_trunc0 = (bgmap & 1) ? GET_STAT_COM(RX_BG_0_MAC_TRUNC_FRAME) : 0;
p->rx_trunc1 = (bgmap & 2) ? GET_STAT_COM(RX_BG_1_MAC_TRUNC_FRAME) : 0;
p->rx_trunc2 = (bgmap & 4) ? GET_STAT_COM(RX_BG_2_MAC_TRUNC_FRAME) : 0;
p->rx_trunc3 = (bgmap & 8) ? GET_STAT_COM(RX_BG_3_MAC_TRUNC_FRAME) : 0;
#undef GET_STAT
#undef GET_STAT_COM
}
/**
* t4_get_lb_stats - collect loopback port statistics
* @adap: the adapter
* @idx: the loopback port index
* @p: the stats structure to fill
*
* Return HW statistics for the given loopback port.
*/
void t4_get_lb_stats(struct adapter *adap, int idx, struct lb_port_stats *p)
{
u32 bgmap = t4_get_mps_bg_map(adap, idx);
#define GET_STAT(name) \
t4_read_reg64(adap, \
(is_t4(adap->params.chip) ? \
PORT_REG(idx, MPS_PORT_STAT_LB_PORT_##name##_L) : \
T5_PORT_REG(idx, MPS_PORT_STAT_LB_PORT_##name##_L)))
#define GET_STAT_COM(name) t4_read_reg64(adap, MPS_STAT_##name##_L)
p->octets = GET_STAT(BYTES);
p->frames = GET_STAT(FRAMES);
p->bcast_frames = GET_STAT(BCAST);
p->mcast_frames = GET_STAT(MCAST);
p->ucast_frames = GET_STAT(UCAST);
p->error_frames = GET_STAT(ERROR);
p->frames_64 = GET_STAT(64B);
p->frames_65_127 = GET_STAT(65B_127B);
p->frames_128_255 = GET_STAT(128B_255B);
p->frames_256_511 = GET_STAT(256B_511B);
p->frames_512_1023 = GET_STAT(512B_1023B);
p->frames_1024_1518 = GET_STAT(1024B_1518B);
p->frames_1519_max = GET_STAT(1519B_MAX);
p->drop = GET_STAT(DROP_FRAMES);
p->ovflow0 = (bgmap & 1) ? GET_STAT_COM(RX_BG_0_LB_DROP_FRAME) : 0;
p->ovflow1 = (bgmap & 2) ? GET_STAT_COM(RX_BG_1_LB_DROP_FRAME) : 0;
p->ovflow2 = (bgmap & 4) ? GET_STAT_COM(RX_BG_2_LB_DROP_FRAME) : 0;
p->ovflow3 = (bgmap & 8) ? GET_STAT_COM(RX_BG_3_LB_DROP_FRAME) : 0;
p->trunc0 = (bgmap & 1) ? GET_STAT_COM(RX_BG_0_LB_TRUNC_FRAME) : 0;
p->trunc1 = (bgmap & 2) ? GET_STAT_COM(RX_BG_1_LB_TRUNC_FRAME) : 0;
p->trunc2 = (bgmap & 4) ? GET_STAT_COM(RX_BG_2_LB_TRUNC_FRAME) : 0;
p->trunc3 = (bgmap & 8) ? GET_STAT_COM(RX_BG_3_LB_TRUNC_FRAME) : 0;
#undef GET_STAT
#undef GET_STAT_COM
}
/* t4_mk_filtdelwr - create a delete filter WR
* @ftid: the filter ID
* @wr: the filter work request to populate
* @qid: ingress queue to receive the delete notification
*
* Creates a filter work request to delete the supplied filter. If @qid is
* negative the delete notification is suppressed.
*/
void t4_mk_filtdelwr(unsigned int ftid, struct fw_filter_wr *wr, int qid)
{
memset(wr, 0, sizeof(*wr));
wr->op_pkd = cpu_to_be32(FW_WR_OP_V(FW_FILTER_WR));
wr->len16_pkd = cpu_to_be32(FW_WR_LEN16_V(sizeof(*wr) / 16));
wr->tid_to_iq = cpu_to_be32(FW_FILTER_WR_TID_V(ftid) |
FW_FILTER_WR_NOREPLY_V(qid < 0));
wr->del_filter_to_l2tix = cpu_to_be32(FW_FILTER_WR_DEL_FILTER_F);
if (qid >= 0)
wr->rx_chan_rx_rpl_iq =
cpu_to_be16(FW_FILTER_WR_RX_RPL_IQ_V(qid));
}
#define INIT_CMD(var, cmd, rd_wr) do { \
(var).op_to_write = cpu_to_be32(FW_CMD_OP_V(FW_##cmd##_CMD) | \
FW_CMD_REQUEST_F | \
FW_CMD_##rd_wr##_F); \
(var).retval_len16 = cpu_to_be32(FW_LEN16(var)); \
} while (0)
int t4_fwaddrspace_write(struct adapter *adap, unsigned int mbox,
u32 addr, u32 val)
{
u32 ldst_addrspace;
struct fw_ldst_cmd c;
memset(&c, 0, sizeof(c));
ldst_addrspace = FW_LDST_CMD_ADDRSPACE_V(FW_LDST_ADDRSPC_FIRMWARE);
c.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_WRITE_F |
ldst_addrspace);
c.cycles_to_len16 = cpu_to_be32(FW_LEN16(c));
c.u.addrval.addr = cpu_to_be32(addr);
c.u.addrval.val = cpu_to_be32(val);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_mdio_rd - read a PHY register through MDIO
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @phy_addr: the PHY address
* @mmd: the PHY MMD to access (0 for clause 22 PHYs)
* @reg: the register to read
* @valp: where to store the value
*
* Issues a FW command through the given mailbox to read a PHY register.
*/
int t4_mdio_rd(struct adapter *adap, unsigned int mbox, unsigned int phy_addr,
unsigned int mmd, unsigned int reg, u16 *valp)
{
int ret;
u32 ldst_addrspace;
struct fw_ldst_cmd c;
memset(&c, 0, sizeof(c));
ldst_addrspace = FW_LDST_CMD_ADDRSPACE_V(FW_LDST_ADDRSPC_MDIO);
c.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
ldst_addrspace);
c.cycles_to_len16 = cpu_to_be32(FW_LEN16(c));
c.u.mdio.paddr_mmd = cpu_to_be16(FW_LDST_CMD_PADDR_V(phy_addr) |
FW_LDST_CMD_MMD_V(mmd));
c.u.mdio.raddr = cpu_to_be16(reg);
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0)
*valp = be16_to_cpu(c.u.mdio.rval);
return ret;
}
/**
* t4_mdio_wr - write a PHY register through MDIO
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @phy_addr: the PHY address
* @mmd: the PHY MMD to access (0 for clause 22 PHYs)
* @reg: the register to write
* @val: value to write
*
* Issues a FW command through the given mailbox to write a PHY register.
*/
int t4_mdio_wr(struct adapter *adap, unsigned int mbox, unsigned int phy_addr,
unsigned int mmd, unsigned int reg, u16 val)
{
u32 ldst_addrspace;
struct fw_ldst_cmd c;
memset(&c, 0, sizeof(c));
ldst_addrspace = FW_LDST_CMD_ADDRSPACE_V(FW_LDST_ADDRSPC_MDIO);
c.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
ldst_addrspace);
c.cycles_to_len16 = cpu_to_be32(FW_LEN16(c));
c.u.mdio.paddr_mmd = cpu_to_be16(FW_LDST_CMD_PADDR_V(phy_addr) |
FW_LDST_CMD_MMD_V(mmd));
c.u.mdio.raddr = cpu_to_be16(reg);
c.u.mdio.rval = cpu_to_be16(val);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_sge_decode_idma_state - decode the idma state
* @adapter: the adapter
* @state: the state idma is stuck in
*/
void t4_sge_decode_idma_state(struct adapter *adapter, int state)
{
static const char * const t4_decode[] = {
"IDMA_IDLE",
"IDMA_PUSH_MORE_CPL_FIFO",
"IDMA_PUSH_CPL_MSG_HEADER_TO_FIFO",
"Not used",
"IDMA_PHYSADDR_SEND_PCIEHDR",
"IDMA_PHYSADDR_SEND_PAYLOAD_FIRST",
"IDMA_PHYSADDR_SEND_PAYLOAD",
"IDMA_SEND_FIFO_TO_IMSG",
"IDMA_FL_REQ_DATA_FL_PREP",
"IDMA_FL_REQ_DATA_FL",
"IDMA_FL_DROP",
"IDMA_FL_H_REQ_HEADER_FL",
"IDMA_FL_H_SEND_PCIEHDR",
"IDMA_FL_H_PUSH_CPL_FIFO",
"IDMA_FL_H_SEND_CPL",
"IDMA_FL_H_SEND_IP_HDR_FIRST",
"IDMA_FL_H_SEND_IP_HDR",
"IDMA_FL_H_REQ_NEXT_HEADER_FL",
"IDMA_FL_H_SEND_NEXT_PCIEHDR",
"IDMA_FL_H_SEND_IP_HDR_PADDING",
"IDMA_FL_D_SEND_PCIEHDR",
"IDMA_FL_D_SEND_CPL_AND_IP_HDR",
"IDMA_FL_D_REQ_NEXT_DATA_FL",
"IDMA_FL_SEND_PCIEHDR",
"IDMA_FL_PUSH_CPL_FIFO",
"IDMA_FL_SEND_CPL",
"IDMA_FL_SEND_PAYLOAD_FIRST",
"IDMA_FL_SEND_PAYLOAD",
"IDMA_FL_REQ_NEXT_DATA_FL",
"IDMA_FL_SEND_NEXT_PCIEHDR",
"IDMA_FL_SEND_PADDING",
"IDMA_FL_SEND_COMPLETION_TO_IMSG",
"IDMA_FL_SEND_FIFO_TO_IMSG",
"IDMA_FL_REQ_DATAFL_DONE",
"IDMA_FL_REQ_HEADERFL_DONE",
};
static const char * const t5_decode[] = {
"IDMA_IDLE",
"IDMA_ALMOST_IDLE",
"IDMA_PUSH_MORE_CPL_FIFO",
"IDMA_PUSH_CPL_MSG_HEADER_TO_FIFO",
"IDMA_SGEFLRFLUSH_SEND_PCIEHDR",
"IDMA_PHYSADDR_SEND_PCIEHDR",
"IDMA_PHYSADDR_SEND_PAYLOAD_FIRST",
"IDMA_PHYSADDR_SEND_PAYLOAD",
"IDMA_SEND_FIFO_TO_IMSG",
"IDMA_FL_REQ_DATA_FL",
"IDMA_FL_DROP",
"IDMA_FL_DROP_SEND_INC",
"IDMA_FL_H_REQ_HEADER_FL",
"IDMA_FL_H_SEND_PCIEHDR",
"IDMA_FL_H_PUSH_CPL_FIFO",
"IDMA_FL_H_SEND_CPL",
"IDMA_FL_H_SEND_IP_HDR_FIRST",
"IDMA_FL_H_SEND_IP_HDR",
"IDMA_FL_H_REQ_NEXT_HEADER_FL",
"IDMA_FL_H_SEND_NEXT_PCIEHDR",
"IDMA_FL_H_SEND_IP_HDR_PADDING",
"IDMA_FL_D_SEND_PCIEHDR",
"IDMA_FL_D_SEND_CPL_AND_IP_HDR",
"IDMA_FL_D_REQ_NEXT_DATA_FL",
"IDMA_FL_SEND_PCIEHDR",
"IDMA_FL_PUSH_CPL_FIFO",
"IDMA_FL_SEND_CPL",
"IDMA_FL_SEND_PAYLOAD_FIRST",
"IDMA_FL_SEND_PAYLOAD",
"IDMA_FL_REQ_NEXT_DATA_FL",
"IDMA_FL_SEND_NEXT_PCIEHDR",
"IDMA_FL_SEND_PADDING",
"IDMA_FL_SEND_COMPLETION_TO_IMSG",
};
static const char * const t6_decode[] = {
"IDMA_IDLE",
"IDMA_PUSH_MORE_CPL_FIFO",
"IDMA_PUSH_CPL_MSG_HEADER_TO_FIFO",
"IDMA_SGEFLRFLUSH_SEND_PCIEHDR",
"IDMA_PHYSADDR_SEND_PCIEHDR",
"IDMA_PHYSADDR_SEND_PAYLOAD_FIRST",
"IDMA_PHYSADDR_SEND_PAYLOAD",
"IDMA_FL_REQ_DATA_FL",
"IDMA_FL_DROP",
"IDMA_FL_DROP_SEND_INC",
"IDMA_FL_H_REQ_HEADER_FL",
"IDMA_FL_H_SEND_PCIEHDR",
"IDMA_FL_H_PUSH_CPL_FIFO",
"IDMA_FL_H_SEND_CPL",
"IDMA_FL_H_SEND_IP_HDR_FIRST",
"IDMA_FL_H_SEND_IP_HDR",
"IDMA_FL_H_REQ_NEXT_HEADER_FL",
"IDMA_FL_H_SEND_NEXT_PCIEHDR",
"IDMA_FL_H_SEND_IP_HDR_PADDING",
"IDMA_FL_D_SEND_PCIEHDR",
"IDMA_FL_D_SEND_CPL_AND_IP_HDR",
"IDMA_FL_D_REQ_NEXT_DATA_FL",
"IDMA_FL_SEND_PCIEHDR",
"IDMA_FL_PUSH_CPL_FIFO",
"IDMA_FL_SEND_CPL",
"IDMA_FL_SEND_PAYLOAD_FIRST",
"IDMA_FL_SEND_PAYLOAD",
"IDMA_FL_REQ_NEXT_DATA_FL",
"IDMA_FL_SEND_NEXT_PCIEHDR",
"IDMA_FL_SEND_PADDING",
"IDMA_FL_SEND_COMPLETION_TO_IMSG",
};
static const u32 sge_regs[] = {
SGE_DEBUG_DATA_LOW_INDEX_2_A,
SGE_DEBUG_DATA_LOW_INDEX_3_A,
SGE_DEBUG_DATA_HIGH_INDEX_10_A,
};
const char **sge_idma_decode;
int sge_idma_decode_nstates;
int i;
unsigned int chip_version = CHELSIO_CHIP_VERSION(adapter->params.chip);
/* Select the right set of decode strings to dump depending on the
* adapter chip type.
*/
switch (chip_version) {
case CHELSIO_T4:
sge_idma_decode = (const char **)t4_decode;
sge_idma_decode_nstates = ARRAY_SIZE(t4_decode);
break;
case CHELSIO_T5:
sge_idma_decode = (const char **)t5_decode;
sge_idma_decode_nstates = ARRAY_SIZE(t5_decode);
break;
case CHELSIO_T6:
sge_idma_decode = (const char **)t6_decode;
sge_idma_decode_nstates = ARRAY_SIZE(t6_decode);
break;
default:
dev_err(adapter->pdev_dev,
"Unsupported chip version %d\n", chip_version);
return;
}
if (is_t4(adapter->params.chip)) {
sge_idma_decode = (const char **)t4_decode;
sge_idma_decode_nstates = ARRAY_SIZE(t4_decode);
} else {
sge_idma_decode = (const char **)t5_decode;
sge_idma_decode_nstates = ARRAY_SIZE(t5_decode);
}
if (state < sge_idma_decode_nstates)
CH_WARN(adapter, "idma state %s\n", sge_idma_decode[state]);
else
CH_WARN(adapter, "idma state %d unknown\n", state);
for (i = 0; i < ARRAY_SIZE(sge_regs); i++)
CH_WARN(adapter, "SGE register %#x value %#x\n",
sge_regs[i], t4_read_reg(adapter, sge_regs[i]));
}
/**
* t4_sge_ctxt_flush - flush the SGE context cache
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @ctxt_type: Egress or Ingress
*
* Issues a FW command through the given mailbox to flush the
* SGE context cache.
*/
int t4_sge_ctxt_flush(struct adapter *adap, unsigned int mbox, int ctxt_type)
{
int ret;
u32 ldst_addrspace;
struct fw_ldst_cmd c;
memset(&c, 0, sizeof(c));
ldst_addrspace = FW_LDST_CMD_ADDRSPACE_V(ctxt_type == CTXT_EGRESS ?
FW_LDST_ADDRSPC_SGE_EGRC :
FW_LDST_ADDRSPC_SGE_INGC);
c.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
ldst_addrspace);
c.cycles_to_len16 = cpu_to_be32(FW_LEN16(c));
c.u.idctxt.msg_ctxtflush = cpu_to_be32(FW_LDST_CMD_CTXTFLUSH_F);
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
return ret;
}
/**
* t4_read_sge_dbqtimers - read SGE Doorbell Queue Timer values
* @adap: the adapter
* @ndbqtimers: size of the provided SGE Doorbell Queue Timer table
* @dbqtimers: SGE Doorbell Queue Timer table
*
* Reads the SGE Doorbell Queue Timer values into the provided table.
* Returns 0 on success (Firmware and Hardware support this feature),
* an error on failure.
*/
int t4_read_sge_dbqtimers(struct adapter *adap, unsigned int ndbqtimers,
u16 *dbqtimers)
{
int ret, dbqtimerix;
ret = 0;
dbqtimerix = 0;
while (dbqtimerix < ndbqtimers) {
int nparams, param;
u32 params[7], vals[7];
nparams = ndbqtimers - dbqtimerix;
if (nparams > ARRAY_SIZE(params))
nparams = ARRAY_SIZE(params);
for (param = 0; param < nparams; param++)
params[param] =
(FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_DBQ_TIMER) |
FW_PARAMS_PARAM_Y_V(dbqtimerix + param));
ret = t4_query_params(adap, adap->mbox, adap->pf, 0,
nparams, params, vals);
if (ret)
break;
for (param = 0; param < nparams; param++)
dbqtimers[dbqtimerix++] = vals[param];
}
return ret;
}
/**
* t4_fw_hello - establish communication with FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @evt_mbox: mailbox to receive async FW events
* @master: specifies the caller's willingness to be the device master
* @state: returns the current device state (if non-NULL)
*
* Issues a command to establish communication with FW. Returns either
* an error (negative integer) or the mailbox of the Master PF.
*/
int t4_fw_hello(struct adapter *adap, unsigned int mbox, unsigned int evt_mbox,
enum dev_master master, enum dev_state *state)
{
int ret;
struct fw_hello_cmd c;
u32 v;
unsigned int master_mbox;
int retries = FW_CMD_HELLO_RETRIES;
retry:
memset(&c, 0, sizeof(c));
INIT_CMD(c, HELLO, WRITE);
c.err_to_clearinit = cpu_to_be32(
FW_HELLO_CMD_MASTERDIS_V(master == MASTER_CANT) |
FW_HELLO_CMD_MASTERFORCE_V(master == MASTER_MUST) |
FW_HELLO_CMD_MBMASTER_V(master == MASTER_MUST ?
mbox : FW_HELLO_CMD_MBMASTER_M) |
FW_HELLO_CMD_MBASYNCNOT_V(evt_mbox) |
FW_HELLO_CMD_STAGE_V(fw_hello_cmd_stage_os) |
FW_HELLO_CMD_CLEARINIT_F);
/*
* Issue the HELLO command to the firmware. If it's not successful
* but indicates that we got a "busy" or "timeout" condition, retry
* the HELLO until we exhaust our retry limit. If we do exceed our
* retry limit, check to see if the firmware left us any error
* information and report that if so.
*/
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret < 0) {
if ((ret == -EBUSY || ret == -ETIMEDOUT) && retries-- > 0)
goto retry;
if (t4_read_reg(adap, PCIE_FW_A) & PCIE_FW_ERR_F)
t4_report_fw_error(adap);
return ret;
}
v = be32_to_cpu(c.err_to_clearinit);
master_mbox = FW_HELLO_CMD_MBMASTER_G(v);
if (state) {
if (v & FW_HELLO_CMD_ERR_F)
*state = DEV_STATE_ERR;
else if (v & FW_HELLO_CMD_INIT_F)
*state = DEV_STATE_INIT;
else
*state = DEV_STATE_UNINIT;
}
/*
* If we're not the Master PF then we need to wait around for the
* Master PF Driver to finish setting up the adapter.
*
* Note that we also do this wait if we're a non-Master-capable PF and
* there is no current Master PF; a Master PF may show up momentarily
* and we wouldn't want to fail pointlessly. (This can happen when an
* OS loads lots of different drivers rapidly at the same time). In
* this case, the Master PF returned by the firmware will be
* PCIE_FW_MASTER_M so the test below will work ...
*/
if ((v & (FW_HELLO_CMD_ERR_F|FW_HELLO_CMD_INIT_F)) == 0 &&
master_mbox != mbox) {
int waiting = FW_CMD_HELLO_TIMEOUT;
/*
* Wait for the firmware to either indicate an error or
* initialized state. If we see either of these we bail out
* and report the issue to the caller. If we exhaust the
* "hello timeout" and we haven't exhausted our retries, try
* again. Otherwise bail with a timeout error.
*/
for (;;) {
u32 pcie_fw;
msleep(50);
waiting -= 50;
/*
* If neither Error nor Initialized are indicated
* by the firmware keep waiting till we exhaust our
* timeout ... and then retry if we haven't exhausted
* our retries ...
*/
pcie_fw = t4_read_reg(adap, PCIE_FW_A);
if (!(pcie_fw & (PCIE_FW_ERR_F|PCIE_FW_INIT_F))) {
if (waiting <= 0) {
if (retries-- > 0)
goto retry;
return -ETIMEDOUT;
}
continue;
}
/*
* We either have an Error or Initialized condition
* report errors preferentially.
*/
if (state) {
if (pcie_fw & PCIE_FW_ERR_F)
*state = DEV_STATE_ERR;
else if (pcie_fw & PCIE_FW_INIT_F)
*state = DEV_STATE_INIT;
}
/*
* If we arrived before a Master PF was selected and
* there's not a valid Master PF, grab its identity
* for our caller.
*/
if (master_mbox == PCIE_FW_MASTER_M &&
(pcie_fw & PCIE_FW_MASTER_VLD_F))
master_mbox = PCIE_FW_MASTER_G(pcie_fw);
break;
}
}
return master_mbox;
}
/**
* t4_fw_bye - end communication with FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
*
* Issues a command to terminate communication with FW.
*/
int t4_fw_bye(struct adapter *adap, unsigned int mbox)
{
struct fw_bye_cmd c;
memset(&c, 0, sizeof(c));
INIT_CMD(c, BYE, WRITE);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_init_cmd - ask FW to initialize the device
* @adap: the adapter
* @mbox: mailbox to use for the FW command
*
* Issues a command to FW to partially initialize the device. This
* performs initialization that generally doesn't depend on user input.
*/
int t4_early_init(struct adapter *adap, unsigned int mbox)
{
struct fw_initialize_cmd c;
memset(&c, 0, sizeof(c));
INIT_CMD(c, INITIALIZE, WRITE);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_fw_reset - issue a reset to FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @reset: specifies the type of reset to perform
*
* Issues a reset command of the specified type to FW.
*/
int t4_fw_reset(struct adapter *adap, unsigned int mbox, int reset)
{
struct fw_reset_cmd c;
memset(&c, 0, sizeof(c));
INIT_CMD(c, RESET, WRITE);
c.val = cpu_to_be32(reset);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_fw_halt - issue a reset/halt to FW and put uP into RESET
* @adap: the adapter
* @mbox: mailbox to use for the FW RESET command (if desired)
* @force: force uP into RESET even if FW RESET command fails
*
* Issues a RESET command to firmware (if desired) with a HALT indication
* and then puts the microprocessor into RESET state. The RESET command
* will only be issued if a legitimate mailbox is provided (mbox <=
* PCIE_FW_MASTER_M).
*
* This is generally used in order for the host to safely manipulate the
* adapter without fear of conflicting with whatever the firmware might
* be doing. The only way out of this state is to RESTART the firmware
* ...
*/
static int t4_fw_halt(struct adapter *adap, unsigned int mbox, int force)
{
int ret = 0;
/*
* If a legitimate mailbox is provided, issue a RESET command
* with a HALT indication.
*/
if (mbox <= PCIE_FW_MASTER_M) {
struct fw_reset_cmd c;
memset(&c, 0, sizeof(c));
INIT_CMD(c, RESET, WRITE);
c.val = cpu_to_be32(PIORST_F | PIORSTMODE_F);
c.halt_pkd = cpu_to_be32(FW_RESET_CMD_HALT_F);
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/*
* Normally we won't complete the operation if the firmware RESET
* command fails but if our caller insists we'll go ahead and put the
* uP into RESET. This can be useful if the firmware is hung or even
* missing ... We'll have to take the risk of putting the uP into
* RESET without the cooperation of firmware in that case.
*
* We also force the firmware's HALT flag to be on in case we bypassed
* the firmware RESET command above or we're dealing with old firmware
* which doesn't have the HALT capability. This will serve as a flag
* for the incoming firmware to know that it's coming out of a HALT
* rather than a RESET ... if it's new enough to understand that ...
*/
if (ret == 0 || force) {
t4_set_reg_field(adap, CIM_BOOT_CFG_A, UPCRST_F, UPCRST_F);
t4_set_reg_field(adap, PCIE_FW_A, PCIE_FW_HALT_F,
PCIE_FW_HALT_F);
}
/*
* And we always return the result of the firmware RESET command
* even when we force the uP into RESET ...
*/
return ret;
}
/**
* t4_fw_restart - restart the firmware by taking the uP out of RESET
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @reset: if we want to do a RESET to restart things
*
* Restart firmware previously halted by t4_fw_halt(). On successful
* return the previous PF Master remains as the new PF Master and there
* is no need to issue a new HELLO command, etc.
*
* We do this in two ways:
*
* 1. If we're dealing with newer firmware we'll simply want to take
* the chip's microprocessor out of RESET. This will cause the
* firmware to start up from its start vector. And then we'll loop
* until the firmware indicates it's started again (PCIE_FW.HALT
* reset to 0) or we timeout.
*
* 2. If we're dealing with older firmware then we'll need to RESET
* the chip since older firmware won't recognize the PCIE_FW.HALT
* flag and automatically RESET itself on startup.
*/
static int t4_fw_restart(struct adapter *adap, unsigned int mbox, int reset)
{
if (reset) {
/*
* Since we're directing the RESET instead of the firmware
* doing it automatically, we need to clear the PCIE_FW.HALT
* bit.
*/
t4_set_reg_field(adap, PCIE_FW_A, PCIE_FW_HALT_F, 0);
/*
* If we've been given a valid mailbox, first try to get the
* firmware to do the RESET. If that works, great and we can
* return success. Otherwise, if we haven't been given a
* valid mailbox or the RESET command failed, fall back to
* hitting the chip with a hammer.
*/
if (mbox <= PCIE_FW_MASTER_M) {
t4_set_reg_field(adap, CIM_BOOT_CFG_A, UPCRST_F, 0);
msleep(100);
if (t4_fw_reset(adap, mbox,
PIORST_F | PIORSTMODE_F) == 0)
return 0;
}
t4_write_reg(adap, PL_RST_A, PIORST_F | PIORSTMODE_F);
msleep(2000);
} else {
int ms;
t4_set_reg_field(adap, CIM_BOOT_CFG_A, UPCRST_F, 0);
for (ms = 0; ms < FW_CMD_MAX_TIMEOUT; ) {
if (!(t4_read_reg(adap, PCIE_FW_A) & PCIE_FW_HALT_F))
return 0;
msleep(100);
ms += 100;
}
return -ETIMEDOUT;
}
return 0;
}
/**
* t4_fw_upgrade - perform all of the steps necessary to upgrade FW
* @adap: the adapter
* @mbox: mailbox to use for the FW RESET command (if desired)
* @fw_data: the firmware image to write
* @size: image size
* @force: force upgrade even if firmware doesn't cooperate
*
* Perform all of the steps necessary for upgrading an adapter's
* firmware image. Normally this requires the cooperation of the
* existing firmware in order to halt all existing activities
* but if an invalid mailbox token is passed in we skip that step
* (though we'll still put the adapter microprocessor into RESET in
* that case).
*
* On successful return the new firmware will have been loaded and
* the adapter will have been fully RESET losing all previous setup
* state. On unsuccessful return the adapter may be completely hosed ...
* positive errno indicates that the adapter is ~probably~ intact, a
* negative errno indicates that things are looking bad ...
*/
int t4_fw_upgrade(struct adapter *adap, unsigned int mbox,
const u8 *fw_data, unsigned int size, int force)
{
const struct fw_hdr *fw_hdr = (const struct fw_hdr *)fw_data;
int reset, ret;
if (!t4_fw_matches_chip(adap, fw_hdr))
return -EINVAL;
/* Disable CXGB4_FW_OK flag so that mbox commands with CXGB4_FW_OK flag
* set wont be sent when we are flashing FW.
*/
adap->flags &= ~CXGB4_FW_OK;
ret = t4_fw_halt(adap, mbox, force);
if (ret < 0 && !force)
goto out;
ret = t4_load_fw(adap, fw_data, size);
if (ret < 0)
goto out;
/*
* If there was a Firmware Configuration File stored in FLASH,
* there's a good chance that it won't be compatible with the new
* Firmware. In order to prevent difficult to diagnose adapter
* initialization issues, we clear out the Firmware Configuration File
* portion of the FLASH . The user will need to re-FLASH a new
* Firmware Configuration File which is compatible with the new
* Firmware if that's desired.
*/
(void)t4_load_cfg(adap, NULL, 0);
/*
* Older versions of the firmware don't understand the new
* PCIE_FW.HALT flag and so won't know to perform a RESET when they
* restart. So for newly loaded older firmware we'll have to do the
* RESET for it so it starts up on a clean slate. We can tell if
* the newly loaded firmware will handle this right by checking
* its header flags to see if it advertises the capability.
*/
reset = ((be32_to_cpu(fw_hdr->flags) & FW_HDR_FLAGS_RESET_HALT) == 0);
ret = t4_fw_restart(adap, mbox, reset);
/* Grab potentially new Firmware Device Log parameters so we can see
* how healthy the new Firmware is. It's okay to contact the new
* Firmware for these parameters even though, as far as it's
* concerned, we've never said "HELLO" to it ...
*/
(void)t4_init_devlog_params(adap);
out:
adap->flags |= CXGB4_FW_OK;
return ret;
}
/**
* t4_fl_pkt_align - return the fl packet alignment
* @adap: the adapter
*
* T4 has a single field to specify the packing and padding boundary.
* T5 onwards has separate fields for this and hence the alignment for
* next packet offset is maximum of these two.
*
*/
int t4_fl_pkt_align(struct adapter *adap)
{
u32 sge_control, sge_control2;
unsigned int ingpadboundary, ingpackboundary, fl_align, ingpad_shift;
sge_control = t4_read_reg(adap, SGE_CONTROL_A);
/* T4 uses a single control field to specify both the PCIe Padding and
* Packing Boundary. T5 introduced the ability to specify these
* separately. The actual Ingress Packet Data alignment boundary
* within Packed Buffer Mode is the maximum of these two
* specifications. (Note that it makes no real practical sense to
* have the Padding Boundary be larger than the Packing Boundary but you
* could set the chip up that way and, in fact, legacy T4 code would
* end doing this because it would initialize the Padding Boundary and
* leave the Packing Boundary initialized to 0 (16 bytes).)
* Padding Boundary values in T6 starts from 8B,
* where as it is 32B for T4 and T5.
*/
if (CHELSIO_CHIP_VERSION(adap->params.chip) <= CHELSIO_T5)
ingpad_shift = INGPADBOUNDARY_SHIFT_X;
else
ingpad_shift = T6_INGPADBOUNDARY_SHIFT_X;
ingpadboundary = 1 << (INGPADBOUNDARY_G(sge_control) + ingpad_shift);
fl_align = ingpadboundary;
if (!is_t4(adap->params.chip)) {
/* T5 has a weird interpretation of one of the PCIe Packing
* Boundary values. No idea why ...
*/
sge_control2 = t4_read_reg(adap, SGE_CONTROL2_A);
ingpackboundary = INGPACKBOUNDARY_G(sge_control2);
if (ingpackboundary == INGPACKBOUNDARY_16B_X)
ingpackboundary = 16;
else
ingpackboundary = 1 << (ingpackboundary +
INGPACKBOUNDARY_SHIFT_X);
fl_align = max(ingpadboundary, ingpackboundary);
}
return fl_align;
}
/**
* t4_fixup_host_params - fix up host-dependent parameters
* @adap: the adapter
* @page_size: the host's Base Page Size
* @cache_line_size: the host's Cache Line Size
*
* Various registers in T4 contain values which are dependent on the
* host's Base Page and Cache Line Sizes. This function will fix all of
* those registers with the appropriate values as passed in ...
*/
int t4_fixup_host_params(struct adapter *adap, unsigned int page_size,
unsigned int cache_line_size)
{
unsigned int page_shift = fls(page_size) - 1;
unsigned int sge_hps = page_shift - 10;
unsigned int stat_len = cache_line_size > 64 ? 128 : 64;
unsigned int fl_align = cache_line_size < 32 ? 32 : cache_line_size;
unsigned int fl_align_log = fls(fl_align) - 1;
t4_write_reg(adap, SGE_HOST_PAGE_SIZE_A,
HOSTPAGESIZEPF0_V(sge_hps) |
HOSTPAGESIZEPF1_V(sge_hps) |
HOSTPAGESIZEPF2_V(sge_hps) |
HOSTPAGESIZEPF3_V(sge_hps) |
HOSTPAGESIZEPF4_V(sge_hps) |
HOSTPAGESIZEPF5_V(sge_hps) |
HOSTPAGESIZEPF6_V(sge_hps) |
HOSTPAGESIZEPF7_V(sge_hps));
if (is_t4(adap->params.chip)) {
t4_set_reg_field(adap, SGE_CONTROL_A,
INGPADBOUNDARY_V(INGPADBOUNDARY_M) |
EGRSTATUSPAGESIZE_F,
INGPADBOUNDARY_V(fl_align_log -
INGPADBOUNDARY_SHIFT_X) |
EGRSTATUSPAGESIZE_V(stat_len != 64));
} else {
unsigned int pack_align;
unsigned int ingpad, ingpack;
/* T5 introduced the separation of the Free List Padding and
* Packing Boundaries. Thus, we can select a smaller Padding
* Boundary to avoid uselessly chewing up PCIe Link and Memory
* Bandwidth, and use a Packing Boundary which is large enough
* to avoid false sharing between CPUs, etc.
*
* For the PCI Link, the smaller the Padding Boundary the
* better. For the Memory Controller, a smaller Padding
* Boundary is better until we cross under the Memory Line
* Size (the minimum unit of transfer to/from Memory). If we
* have a Padding Boundary which is smaller than the Memory
* Line Size, that'll involve a Read-Modify-Write cycle on the
* Memory Controller which is never good.
*/
/* We want the Packing Boundary to be based on the Cache Line
* Size in order to help avoid False Sharing performance
* issues between CPUs, etc. We also want the Packing
* Boundary to incorporate the PCI-E Maximum Payload Size. We
* get best performance when the Packing Boundary is a
* multiple of the Maximum Payload Size.
*/
pack_align = fl_align;
if (pci_is_pcie(adap->pdev)) {
unsigned int mps, mps_log;
u16 devctl;
/* The PCIe Device Control Maximum Payload Size field
* [bits 7:5] encodes sizes as powers of 2 starting at
* 128 bytes.
*/
pcie_capability_read_word(adap->pdev, PCI_EXP_DEVCTL,
&devctl);
mps_log = ((devctl & PCI_EXP_DEVCTL_PAYLOAD) >> 5) + 7;
mps = 1 << mps_log;
if (mps > pack_align)
pack_align = mps;
}
/* N.B. T5/T6 have a crazy special interpretation of the "0"
* value for the Packing Boundary. This corresponds to 16
* bytes instead of the expected 32 bytes. So if we want 32
* bytes, the best we can really do is 64 bytes ...
*/
if (pack_align <= 16) {
ingpack = INGPACKBOUNDARY_16B_X;
fl_align = 16;
} else if (pack_align == 32) {
ingpack = INGPACKBOUNDARY_64B_X;
fl_align = 64;
} else {
unsigned int pack_align_log = fls(pack_align) - 1;
ingpack = pack_align_log - INGPACKBOUNDARY_SHIFT_X;
fl_align = pack_align;
}
/* Use the smallest Ingress Padding which isn't smaller than
* the Memory Controller Read/Write Size. We'll take that as
* being 8 bytes since we don't know of any system with a
* wider Memory Controller Bus Width.
*/
if (is_t5(adap->params.chip))
ingpad = INGPADBOUNDARY_32B_X;
else
ingpad = T6_INGPADBOUNDARY_8B_X;
t4_set_reg_field(adap, SGE_CONTROL_A,
INGPADBOUNDARY_V(INGPADBOUNDARY_M) |
EGRSTATUSPAGESIZE_F,
INGPADBOUNDARY_V(ingpad) |
EGRSTATUSPAGESIZE_V(stat_len != 64));
t4_set_reg_field(adap, SGE_CONTROL2_A,
INGPACKBOUNDARY_V(INGPACKBOUNDARY_M),
INGPACKBOUNDARY_V(ingpack));
}
/*
* Adjust various SGE Free List Host Buffer Sizes.
*
* This is something of a crock since we're using fixed indices into
* the array which are also known by the sge.c code and the T4
* Firmware Configuration File. We need to come up with a much better
* approach to managing this array. For now, the first four entries
* are:
*
* 0: Host Page Size
* 1: 64KB
* 2: Buffer size corresponding to 1500 byte MTU (unpacked mode)
* 3: Buffer size corresponding to 9000 byte MTU (unpacked mode)
*
* For the single-MTU buffers in unpacked mode we need to include
* space for the SGE Control Packet Shift, 14 byte Ethernet header,
* possible 4 byte VLAN tag, all rounded up to the next Ingress Packet
* Padding boundary. All of these are accommodated in the Factory
* Default Firmware Configuration File but we need to adjust it for
* this host's cache line size.
*/
t4_write_reg(adap, SGE_FL_BUFFER_SIZE0_A, page_size);
t4_write_reg(adap, SGE_FL_BUFFER_SIZE2_A,
(t4_read_reg(adap, SGE_FL_BUFFER_SIZE2_A) + fl_align-1)
& ~(fl_align-1));
t4_write_reg(adap, SGE_FL_BUFFER_SIZE3_A,
(t4_read_reg(adap, SGE_FL_BUFFER_SIZE3_A) + fl_align-1)
& ~(fl_align-1));
t4_write_reg(adap, ULP_RX_TDDP_PSZ_A, HPZ0_V(page_shift - 12));
return 0;
}
/**
* t4_fw_initialize - ask FW to initialize the device
* @adap: the adapter
* @mbox: mailbox to use for the FW command
*
* Issues a command to FW to partially initialize the device. This
* performs initialization that generally doesn't depend on user input.
*/
int t4_fw_initialize(struct adapter *adap, unsigned int mbox)
{
struct fw_initialize_cmd c;
memset(&c, 0, sizeof(c));
INIT_CMD(c, INITIALIZE, WRITE);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_query_params_rw - query FW or device parameters
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF
* @vf: the VF
* @nparams: the number of parameters
* @params: the parameter names
* @val: the parameter values
* @rw: Write and read flag
* @sleep_ok: if true, we may sleep awaiting mbox cmd completion
*
* Reads the value of FW or device parameters. Up to 7 parameters can be
* queried at once.
*/
int t4_query_params_rw(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int nparams, const u32 *params,
u32 *val, int rw, bool sleep_ok)
{
int i, ret;
struct fw_params_cmd c;
__be32 *p = &c.param[0].mnem;
if (nparams > 7)
return -EINVAL;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_PARAMS_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
FW_PARAMS_CMD_PFN_V(pf) |
FW_PARAMS_CMD_VFN_V(vf));
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
for (i = 0; i < nparams; i++) {
*p++ = cpu_to_be32(*params++);
if (rw)
*p = cpu_to_be32(*(val + i));
p++;
}
ret = t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), &c, sleep_ok);
if (ret == 0)
for (i = 0, p = &c.param[0].val; i < nparams; i++, p += 2)
*val++ = be32_to_cpu(*p);
return ret;
}
int t4_query_params(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int nparams, const u32 *params,
u32 *val)
{
return t4_query_params_rw(adap, mbox, pf, vf, nparams, params, val, 0,
true);
}
int t4_query_params_ns(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int nparams, const u32 *params,
u32 *val)
{
return t4_query_params_rw(adap, mbox, pf, vf, nparams, params, val, 0,
false);
}
/**
* t4_set_params_timeout - sets FW or device parameters
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF
* @vf: the VF
* @nparams: the number of parameters
* @params: the parameter names
* @val: the parameter values
* @timeout: the timeout time
*
* Sets the value of FW or device parameters. Up to 7 parameters can be
* specified at once.
*/
int t4_set_params_timeout(struct adapter *adap, unsigned int mbox,
unsigned int pf, unsigned int vf,
unsigned int nparams, const u32 *params,
const u32 *val, int timeout)
{
struct fw_params_cmd c;
__be32 *p = &c.param[0].mnem;
if (nparams > 7)
return -EINVAL;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_PARAMS_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_PARAMS_CMD_PFN_V(pf) |
FW_PARAMS_CMD_VFN_V(vf));
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
while (nparams--) {
*p++ = cpu_to_be32(*params++);
*p++ = cpu_to_be32(*val++);
}
return t4_wr_mbox_timeout(adap, mbox, &c, sizeof(c), NULL, timeout);
}
/**
* t4_set_params - sets FW or device parameters
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF
* @vf: the VF
* @nparams: the number of parameters
* @params: the parameter names
* @val: the parameter values
*
* Sets the value of FW or device parameters. Up to 7 parameters can be
* specified at once.
*/
int t4_set_params(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int nparams, const u32 *params,
const u32 *val)
{
return t4_set_params_timeout(adap, mbox, pf, vf, nparams, params, val,
FW_CMD_MAX_TIMEOUT);
}
/**
* t4_cfg_pfvf - configure PF/VF resource limits
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF being configured
* @vf: the VF being configured
* @txq: the max number of egress queues
* @txq_eth_ctrl: the max number of egress Ethernet or control queues
* @rxqi: the max number of interrupt-capable ingress queues
* @rxq: the max number of interruptless ingress queues
* @tc: the PCI traffic class
* @vi: the max number of virtual interfaces
* @cmask: the channel access rights mask for the PF/VF
* @pmask: the port access rights mask for the PF/VF
* @nexact: the maximum number of exact MPS filters
* @rcaps: read capabilities
* @wxcaps: write/execute capabilities
*
* Configures resource limits and capabilities for a physical or virtual
* function.
*/
int t4_cfg_pfvf(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int txq, unsigned int txq_eth_ctrl,
unsigned int rxqi, unsigned int rxq, unsigned int tc,
unsigned int vi, unsigned int cmask, unsigned int pmask,
unsigned int nexact, unsigned int rcaps, unsigned int wxcaps)
{
struct fw_pfvf_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_PFVF_CMD) | FW_CMD_REQUEST_F |
FW_CMD_WRITE_F | FW_PFVF_CMD_PFN_V(pf) |
FW_PFVF_CMD_VFN_V(vf));
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
c.niqflint_niq = cpu_to_be32(FW_PFVF_CMD_NIQFLINT_V(rxqi) |
FW_PFVF_CMD_NIQ_V(rxq));
c.type_to_neq = cpu_to_be32(FW_PFVF_CMD_CMASK_V(cmask) |
FW_PFVF_CMD_PMASK_V(pmask) |
FW_PFVF_CMD_NEQ_V(txq));
c.tc_to_nexactf = cpu_to_be32(FW_PFVF_CMD_TC_V(tc) |
FW_PFVF_CMD_NVI_V(vi) |
FW_PFVF_CMD_NEXACTF_V(nexact));
c.r_caps_to_nethctrl = cpu_to_be32(FW_PFVF_CMD_R_CAPS_V(rcaps) |
FW_PFVF_CMD_WX_CAPS_V(wxcaps) |
FW_PFVF_CMD_NETHCTRL_V(txq_eth_ctrl));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_alloc_vi - allocate a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @port: physical port associated with the VI
* @pf: the PF owning the VI
* @vf: the VF owning the VI
* @nmac: number of MAC addresses needed (1 to 5)
* @mac: the MAC addresses of the VI
* @rss_size: size of RSS table slice associated with this VI
* @vivld: the destination to store the VI Valid value.
* @vin: the destination to store the VIN value.
*
* Allocates a virtual interface for the given physical port. If @mac is
* not %NULL it contains the MAC addresses of the VI as assigned by FW.
* @mac should be large enough to hold @nmac Ethernet addresses, they are
* stored consecutively so the space needed is @nmac * 6 bytes.
* Returns a negative error number or the non-negative VI id.
*/
int t4_alloc_vi(struct adapter *adap, unsigned int mbox, unsigned int port,
unsigned int pf, unsigned int vf, unsigned int nmac, u8 *mac,
unsigned int *rss_size, u8 *vivld, u8 *vin)
{
int ret;
struct fw_vi_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_VI_CMD) | FW_CMD_REQUEST_F |
FW_CMD_WRITE_F | FW_CMD_EXEC_F |
FW_VI_CMD_PFN_V(pf) | FW_VI_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_VI_CMD_ALLOC_F | FW_LEN16(c));
c.portid_pkd = FW_VI_CMD_PORTID_V(port);
c.nmac = nmac - 1;
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret)
return ret;
if (mac) {
memcpy(mac, c.mac, sizeof(c.mac));
switch (nmac) {
case 5:
memcpy(mac + 24, c.nmac3, sizeof(c.nmac3));
/* Fall through */
case 4:
memcpy(mac + 18, c.nmac2, sizeof(c.nmac2));
/* Fall through */
case 3:
memcpy(mac + 12, c.nmac1, sizeof(c.nmac1));
/* Fall through */
case 2:
memcpy(mac + 6, c.nmac0, sizeof(c.nmac0));
}
}
if (rss_size)
*rss_size = FW_VI_CMD_RSSSIZE_G(be16_to_cpu(c.rsssize_pkd));
if (vivld)
*vivld = FW_VI_CMD_VFVLD_G(be32_to_cpu(c.alloc_to_len16));
if (vin)
*vin = FW_VI_CMD_VIN_G(be32_to_cpu(c.alloc_to_len16));
return FW_VI_CMD_VIID_G(be16_to_cpu(c.type_viid));
}
/**
* t4_free_vi - free a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the VI
* @vf: the VF owning the VI
* @viid: virtual interface identifiler
*
* Free a previously allocated virtual interface.
*/
int t4_free_vi(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int viid)
{
struct fw_vi_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_VI_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_EXEC_F |
FW_VI_CMD_PFN_V(pf) |
FW_VI_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_VI_CMD_FREE_F | FW_LEN16(c));
c.type_viid = cpu_to_be16(FW_VI_CMD_VIID_V(viid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
}
/**
* t4_set_rxmode - set Rx properties of a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @mtu: the new MTU or -1
* @promisc: 1 to enable promiscuous mode, 0 to disable it, -1 no change
* @all_multi: 1 to enable all-multi mode, 0 to disable it, -1 no change
* @bcast: 1 to enable broadcast Rx, 0 to disable it, -1 no change
* @vlanex: 1 to enable HW VLAN extraction, 0 to disable it, -1 no change
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Sets Rx properties of a virtual interface.
*/
int t4_set_rxmode(struct adapter *adap, unsigned int mbox, unsigned int viid,
int mtu, int promisc, int all_multi, int bcast, int vlanex,
bool sleep_ok)
{
struct fw_vi_rxmode_cmd c;
/* convert to FW values */
if (mtu < 0)
mtu = FW_RXMODE_MTU_NO_CHG;
if (promisc < 0)
promisc = FW_VI_RXMODE_CMD_PROMISCEN_M;
if (all_multi < 0)
all_multi = FW_VI_RXMODE_CMD_ALLMULTIEN_M;
if (bcast < 0)
bcast = FW_VI_RXMODE_CMD_BROADCASTEN_M;
if (vlanex < 0)
vlanex = FW_VI_RXMODE_CMD_VLANEXEN_M;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_RXMODE_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_VI_RXMODE_CMD_VIID_V(viid));
c.retval_len16 = cpu_to_be32(FW_LEN16(c));
c.mtu_to_vlanexen =
cpu_to_be32(FW_VI_RXMODE_CMD_MTU_V(mtu) |
FW_VI_RXMODE_CMD_PROMISCEN_V(promisc) |
FW_VI_RXMODE_CMD_ALLMULTIEN_V(all_multi) |
FW_VI_RXMODE_CMD_BROADCASTEN_V(bcast) |
FW_VI_RXMODE_CMD_VLANEXEN_V(vlanex));
return t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), NULL, sleep_ok);
}
/**
* t4_free_encap_mac_filt - frees MPS entry at given index
* @adap: the adapter
* @viid: the VI id
* @idx: index of MPS entry to be freed
* @sleep_ok: call is allowed to sleep
*
* Frees the MPS entry at supplied index
*
* Returns a negative error number or zero on success
*/
int t4_free_encap_mac_filt(struct adapter *adap, unsigned int viid,
int idx, bool sleep_ok)
{
struct fw_vi_mac_exact *p;
u8 addr[] = {0, 0, 0, 0, 0, 0};
struct fw_vi_mac_cmd c;
int ret = 0;
u32 exact;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_CMD_EXEC_V(0) |
FW_VI_MAC_CMD_VIID_V(viid));
exact = FW_VI_MAC_CMD_ENTRY_TYPE_V(FW_VI_MAC_TYPE_EXACTMAC);
c.freemacs_to_len16 = cpu_to_be32(FW_VI_MAC_CMD_FREEMACS_V(0) |
exact |
FW_CMD_LEN16_V(1));
p = c.u.exact;
p->valid_to_idx = cpu_to_be16(FW_VI_MAC_CMD_VALID_F |
FW_VI_MAC_CMD_IDX_V(idx));
memcpy(p->macaddr, addr, sizeof(p->macaddr));
ret = t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c, sleep_ok);
return ret;
}
/**
* t4_free_raw_mac_filt - Frees a raw mac entry in mps tcam
* @adap: the adapter
* @viid: the VI id
* @addr: the MAC address
* @mask: the mask
* @idx: index of the entry in mps tcam
* @lookup_type: MAC address for inner (1) or outer (0) header
* @port_id: the port index
* @sleep_ok: call is allowed to sleep
*
* Removes the mac entry at the specified index using raw mac interface.
*
* Returns a negative error number on failure.
*/
int t4_free_raw_mac_filt(struct adapter *adap, unsigned int viid,
const u8 *addr, const u8 *mask, unsigned int idx,
u8 lookup_type, u8 port_id, bool sleep_ok)
{
struct fw_vi_mac_cmd c;
struct fw_vi_mac_raw *p = &c.u.raw;
u32 val;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_CMD_EXEC_V(0) |
FW_VI_MAC_CMD_VIID_V(viid));
val = FW_CMD_LEN16_V(1) |
FW_VI_MAC_CMD_ENTRY_TYPE_V(FW_VI_MAC_TYPE_RAW);
c.freemacs_to_len16 = cpu_to_be32(FW_VI_MAC_CMD_FREEMACS_V(0) |
FW_CMD_LEN16_V(val));
p->raw_idx_pkd = cpu_to_be32(FW_VI_MAC_CMD_RAW_IDX_V(idx) |
FW_VI_MAC_ID_BASED_FREE);
/* Lookup Type. Outer header: 0, Inner header: 1 */
p->data0_pkd = cpu_to_be32(DATALKPTYPE_V(lookup_type) |
DATAPORTNUM_V(port_id));
/* Lookup mask and port mask */
p->data0m_pkd = cpu_to_be64(DATALKPTYPE_V(DATALKPTYPE_M) |
DATAPORTNUM_V(DATAPORTNUM_M));
/* Copy the address and the mask */
memcpy((u8 *)&p->data1[0] + 2, addr, ETH_ALEN);
memcpy((u8 *)&p->data1m[0] + 2, mask, ETH_ALEN);
return t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c, sleep_ok);
}
/**
* t4_alloc_encap_mac_filt - Adds a mac entry in mps tcam with VNI support
* @adap: the adapter
* @viid: the VI id
* @addr: the MAC address
* @mask: the mask
* @vni: the VNI id for the tunnel protocol
* @vni_mask: mask for the VNI id
* @dip_hit: to enable DIP match for the MPS entry
* @lookup_type: MAC address for inner (1) or outer (0) header
* @sleep_ok: call is allowed to sleep
*
* Allocates an MPS entry with specified MAC address and VNI value.
*
* Returns a negative error number or the allocated index for this mac.
*/
int t4_alloc_encap_mac_filt(struct adapter *adap, unsigned int viid,
const u8 *addr, const u8 *mask, unsigned int vni,
unsigned int vni_mask, u8 dip_hit, u8 lookup_type,
bool sleep_ok)
{
struct fw_vi_mac_cmd c;
struct fw_vi_mac_vni *p = c.u.exact_vni;
int ret = 0;
u32 val;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_VI_MAC_CMD_VIID_V(viid));
val = FW_CMD_LEN16_V(1) |
FW_VI_MAC_CMD_ENTRY_TYPE_V(FW_VI_MAC_TYPE_EXACTMAC_VNI);
c.freemacs_to_len16 = cpu_to_be32(val);
p->valid_to_idx = cpu_to_be16(FW_VI_MAC_CMD_VALID_F |
FW_VI_MAC_CMD_IDX_V(FW_VI_MAC_ADD_MAC));
memcpy(p->macaddr, addr, sizeof(p->macaddr));
memcpy(p->macaddr_mask, mask, sizeof(p->macaddr_mask));
p->lookup_type_to_vni =
cpu_to_be32(FW_VI_MAC_CMD_VNI_V(vni) |
FW_VI_MAC_CMD_DIP_HIT_V(dip_hit) |
FW_VI_MAC_CMD_LOOKUP_TYPE_V(lookup_type));
p->vni_mask_pkd = cpu_to_be32(FW_VI_MAC_CMD_VNI_MASK_V(vni_mask));
ret = t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c, sleep_ok);
if (ret == 0)
ret = FW_VI_MAC_CMD_IDX_G(be16_to_cpu(p->valid_to_idx));
return ret;
}
/**
* t4_alloc_raw_mac_filt - Adds a mac entry in mps tcam
* @adap: the adapter
* @viid: the VI id
* @addr: the MAC address
* @mask: the mask
* @idx: index at which to add this entry
* @lookup_type: MAC address for inner (1) or outer (0) header
* @port_id: the port index
* @sleep_ok: call is allowed to sleep
*
* Adds the mac entry at the specified index using raw mac interface.
*
* Returns a negative error number or the allocated index for this mac.
*/
int t4_alloc_raw_mac_filt(struct adapter *adap, unsigned int viid,
const u8 *addr, const u8 *mask, unsigned int idx,
u8 lookup_type, u8 port_id, bool sleep_ok)
{
int ret = 0;
struct fw_vi_mac_cmd c;
struct fw_vi_mac_raw *p = &c.u.raw;
u32 val;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_VI_MAC_CMD_VIID_V(viid));
val = FW_CMD_LEN16_V(1) |
FW_VI_MAC_CMD_ENTRY_TYPE_V(FW_VI_MAC_TYPE_RAW);
c.freemacs_to_len16 = cpu_to_be32(val);
/* Specify that this is an inner mac address */
p->raw_idx_pkd = cpu_to_be32(FW_VI_MAC_CMD_RAW_IDX_V(idx));
/* Lookup Type. Outer header: 0, Inner header: 1 */
p->data0_pkd = cpu_to_be32(DATALKPTYPE_V(lookup_type) |
DATAPORTNUM_V(port_id));
/* Lookup mask and port mask */
p->data0m_pkd = cpu_to_be64(DATALKPTYPE_V(DATALKPTYPE_M) |
DATAPORTNUM_V(DATAPORTNUM_M));
/* Copy the address and the mask */
memcpy((u8 *)&p->data1[0] + 2, addr, ETH_ALEN);
memcpy((u8 *)&p->data1m[0] + 2, mask, ETH_ALEN);
ret = t4_wr_mbox_meat(adap, adap->mbox, &c, sizeof(c), &c, sleep_ok);
if (ret == 0) {
ret = FW_VI_MAC_CMD_RAW_IDX_G(be32_to_cpu(p->raw_idx_pkd));
if (ret != idx)
ret = -ENOMEM;
}
return ret;
}
/**
* t4_alloc_mac_filt - allocates exact-match filters for MAC addresses
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @free: if true any existing filters for this VI id are first removed
* @naddr: the number of MAC addresses to allocate filters for (up to 7)
* @addr: the MAC address(es)
* @idx: where to store the index of each allocated filter
* @hash: pointer to hash address filter bitmap
* @sleep_ok: call is allowed to sleep
*
* Allocates an exact-match filter for each of the supplied addresses and
* sets it to the corresponding address. If @idx is not %NULL it should
* have at least @naddr entries, each of which will be set to the index of
* the filter allocated for the corresponding MAC address. If a filter
* could not be allocated for an address its index is set to 0xffff.
* If @hash is not %NULL addresses that fail to allocate an exact filter
* are hashed and update the hash filter bitmap pointed at by @hash.
*
* Returns a negative error number or the number of filters allocated.
*/
int t4_alloc_mac_filt(struct adapter *adap, unsigned int mbox,
unsigned int viid, bool free, unsigned int naddr,
const u8 **addr, u16 *idx, u64 *hash, bool sleep_ok)
{
int offset, ret = 0;
struct fw_vi_mac_cmd c;
unsigned int nfilters = 0;
unsigned int max_naddr = adap->params.arch.mps_tcam_size;
unsigned int rem = naddr;
if (naddr > max_naddr)
return -EINVAL;
for (offset = 0; offset < naddr ; /**/) {
unsigned int fw_naddr = (rem < ARRAY_SIZE(c.u.exact) ?
rem : ARRAY_SIZE(c.u.exact));
size_t len16 = DIV_ROUND_UP(offsetof(struct fw_vi_mac_cmd,
u.exact[fw_naddr]), 16);
struct fw_vi_mac_exact *p;
int i;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_WRITE_F |
FW_CMD_EXEC_V(free) |
FW_VI_MAC_CMD_VIID_V(viid));
c.freemacs_to_len16 =
cpu_to_be32(FW_VI_MAC_CMD_FREEMACS_V(free) |
FW_CMD_LEN16_V(len16));
for (i = 0, p = c.u.exact; i < fw_naddr; i++, p++) {
p->valid_to_idx =
cpu_to_be16(FW_VI_MAC_CMD_VALID_F |
FW_VI_MAC_CMD_IDX_V(
FW_VI_MAC_ADD_MAC));
memcpy(p->macaddr, addr[offset + i],
sizeof(p->macaddr));
}
/* It's okay if we run out of space in our MAC address arena.
* Some of the addresses we submit may get stored so we need
* to run through the reply to see what the results were ...
*/
ret = t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), &c, sleep_ok);
if (ret && ret != -FW_ENOMEM)
break;
for (i = 0, p = c.u.exact; i < fw_naddr; i++, p++) {
u16 index = FW_VI_MAC_CMD_IDX_G(
be16_to_cpu(p->valid_to_idx));
if (idx)
idx[offset + i] = (index >= max_naddr ?
0xffff : index);
if (index < max_naddr)
nfilters++;
else if (hash)
*hash |= (1ULL <<
hash_mac_addr(addr[offset + i]));
}
free = false;
offset += fw_naddr;
rem -= fw_naddr;
}
if (ret == 0 || ret == -FW_ENOMEM)
ret = nfilters;
return ret;
}
/**
* t4_free_mac_filt - frees exact-match filters of given MAC addresses
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @naddr: the number of MAC addresses to allocate filters for (up to 7)
* @addr: the MAC address(es)
* @sleep_ok: call is allowed to sleep
*
* Frees the exact-match filter for each of the supplied addresses
*
* Returns a negative error number or the number of filters freed.
*/
int t4_free_mac_filt(struct adapter *adap, unsigned int mbox,
unsigned int viid, unsigned int naddr,
const u8 **addr, bool sleep_ok)
{
int offset, ret = 0;
struct fw_vi_mac_cmd c;
unsigned int nfilters = 0;
unsigned int max_naddr = is_t4(adap->params.chip) ?
NUM_MPS_CLS_SRAM_L_INSTANCES :
NUM_MPS_T5_CLS_SRAM_L_INSTANCES;
unsigned int rem = naddr;
if (naddr > max_naddr)
return -EINVAL;
for (offset = 0; offset < (int)naddr ; /**/) {
unsigned int fw_naddr = (rem < ARRAY_SIZE(c.u.exact)
? rem
: ARRAY_SIZE(c.u.exact));
size_t len16 = DIV_ROUND_UP(offsetof(struct fw_vi_mac_cmd,
u.exact[fw_naddr]), 16);
struct fw_vi_mac_exact *p;
int i;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_WRITE_F |
FW_CMD_EXEC_V(0) |
FW_VI_MAC_CMD_VIID_V(viid));
c.freemacs_to_len16 =
cpu_to_be32(FW_VI_MAC_CMD_FREEMACS_V(0) |
FW_CMD_LEN16_V(len16));
for (i = 0, p = c.u.exact; i < (int)fw_naddr; i++, p++) {
p->valid_to_idx = cpu_to_be16(
FW_VI_MAC_CMD_VALID_F |
FW_VI_MAC_CMD_IDX_V(FW_VI_MAC_MAC_BASED_FREE));
memcpy(p->macaddr, addr[offset+i], sizeof(p->macaddr));
}
ret = t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), &c, sleep_ok);
if (ret)
break;
for (i = 0, p = c.u.exact; i < fw_naddr; i++, p++) {
u16 index = FW_VI_MAC_CMD_IDX_G(
be16_to_cpu(p->valid_to_idx));
if (index < max_naddr)
nfilters++;
}
offset += fw_naddr;
rem -= fw_naddr;
}
if (ret == 0)
ret = nfilters;
return ret;
}
/**
* t4_change_mac - modifies the exact-match filter for a MAC address
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @idx: index of existing filter for old value of MAC address, or -1
* @addr: the new MAC address value
* @persist: whether a new MAC allocation should be persistent
* @smt_idx: the destination to store the new SMT index.
*
* Modifies an exact-match filter and sets it to the new MAC address.
* Note that in general it is not possible to modify the value of a given
* filter so the generic way to modify an address filter is to free the one
* being used by the old address value and allocate a new filter for the
* new address value. @idx can be -1 if the address is a new addition.
*
* Returns a negative error number or the index of the filter with the new
* MAC value.
*/
int t4_change_mac(struct adapter *adap, unsigned int mbox, unsigned int viid,
int idx, const u8 *addr, bool persist, u8 *smt_idx)
{
int ret, mode;
struct fw_vi_mac_cmd c;
struct fw_vi_mac_exact *p = c.u.exact;
unsigned int max_mac_addr = adap->params.arch.mps_tcam_size;
if (idx < 0) /* new allocation */
idx = persist ? FW_VI_MAC_ADD_PERSIST_MAC : FW_VI_MAC_ADD_MAC;
mode = smt_idx ? FW_VI_MAC_SMT_AND_MPSTCAM : FW_VI_MAC_MPS_TCAM_ENTRY;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_VI_MAC_CMD_VIID_V(viid));
c.freemacs_to_len16 = cpu_to_be32(FW_CMD_LEN16_V(1));
p->valid_to_idx = cpu_to_be16(FW_VI_MAC_CMD_VALID_F |
FW_VI_MAC_CMD_SMAC_RESULT_V(mode) |
FW_VI_MAC_CMD_IDX_V(idx));
memcpy(p->macaddr, addr, sizeof(p->macaddr));
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0) {
ret = FW_VI_MAC_CMD_IDX_G(be16_to_cpu(p->valid_to_idx));
if (ret >= max_mac_addr)
ret = -ENOMEM;
if (smt_idx) {
if (adap->params.viid_smt_extn_support) {
*smt_idx = FW_VI_MAC_CMD_SMTID_G
(be32_to_cpu(c.op_to_viid));
} else {
/* In T4/T5, SMT contains 256 SMAC entries
* organized in 128 rows of 2 entries each.
* In T6, SMT contains 256 SMAC entries in
* 256 rows.
*/
if (CHELSIO_CHIP_VERSION(adap->params.chip) <=
CHELSIO_T5)
*smt_idx = (viid & FW_VIID_VIN_M) << 1;
else
*smt_idx = (viid & FW_VIID_VIN_M);
}
}
}
return ret;
}
/**
* t4_set_addr_hash - program the MAC inexact-match hash filter
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @ucast: whether the hash filter should also match unicast addresses
* @vec: the value to be written to the hash filter
* @sleep_ok: call is allowed to sleep
*
* Sets the 64-bit inexact-match hash filter for a virtual interface.
*/
int t4_set_addr_hash(struct adapter *adap, unsigned int mbox, unsigned int viid,
bool ucast, u64 vec, bool sleep_ok)
{
struct fw_vi_mac_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_MAC_CMD) |
FW_CMD_REQUEST_F | FW_CMD_WRITE_F |
FW_VI_ENABLE_CMD_VIID_V(viid));
c.freemacs_to_len16 = cpu_to_be32(FW_VI_MAC_CMD_HASHVECEN_F |
FW_VI_MAC_CMD_HASHUNIEN_V(ucast) |
FW_CMD_LEN16_V(1));
c.u.hash.hashvec = cpu_to_be64(vec);
return t4_wr_mbox_meat(adap, mbox, &c, sizeof(c), NULL, sleep_ok);
}
/**
* t4_enable_vi_params - enable/disable a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @rx_en: 1=enable Rx, 0=disable Rx
* @tx_en: 1=enable Tx, 0=disable Tx
* @dcb_en: 1=enable delivery of Data Center Bridging messages.
*
* Enables/disables a virtual interface. Note that setting DCB Enable
* only makes sense when enabling a Virtual Interface ...
*/
int t4_enable_vi_params(struct adapter *adap, unsigned int mbox,
unsigned int viid, bool rx_en, bool tx_en, bool dcb_en)
{
struct fw_vi_enable_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_ENABLE_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_VI_ENABLE_CMD_VIID_V(viid));
c.ien_to_len16 = cpu_to_be32(FW_VI_ENABLE_CMD_IEN_V(rx_en) |
FW_VI_ENABLE_CMD_EEN_V(tx_en) |
FW_VI_ENABLE_CMD_DCB_INFO_V(dcb_en) |
FW_LEN16(c));
return t4_wr_mbox_ns(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_enable_vi - enable/disable a virtual interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @rx_en: 1=enable Rx, 0=disable Rx
* @tx_en: 1=enable Tx, 0=disable Tx
*
* Enables/disables a virtual interface.
*/
int t4_enable_vi(struct adapter *adap, unsigned int mbox, unsigned int viid,
bool rx_en, bool tx_en)
{
return t4_enable_vi_params(adap, mbox, viid, rx_en, tx_en, 0);
}
/**
* t4_enable_pi_params - enable/disable a Port's Virtual Interface
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pi: the Port Information structure
* @rx_en: 1=enable Rx, 0=disable Rx
* @tx_en: 1=enable Tx, 0=disable Tx
* @dcb_en: 1=enable delivery of Data Center Bridging messages.
*
* Enables/disables a Port's Virtual Interface. Note that setting DCB
* Enable only makes sense when enabling a Virtual Interface ...
* If the Virtual Interface enable/disable operation is successful,
* we notify the OS-specific code of a potential Link Status change
* via the OS Contract API t4_os_link_changed().
*/
int t4_enable_pi_params(struct adapter *adap, unsigned int mbox,
struct port_info *pi,
bool rx_en, bool tx_en, bool dcb_en)
{
int ret = t4_enable_vi_params(adap, mbox, pi->viid,
rx_en, tx_en, dcb_en);
if (ret)
return ret;
t4_os_link_changed(adap, pi->port_id,
rx_en && tx_en && pi->link_cfg.link_ok);
return 0;
}
/**
* t4_identify_port - identify a VI's port by blinking its LED
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @viid: the VI id
* @nblinks: how many times to blink LED at 2.5 Hz
*
* Identifies a VI's port by blinking its LED.
*/
int t4_identify_port(struct adapter *adap, unsigned int mbox, unsigned int viid,
unsigned int nblinks)
{
struct fw_vi_enable_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_viid = cpu_to_be32(FW_CMD_OP_V(FW_VI_ENABLE_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_VI_ENABLE_CMD_VIID_V(viid));
c.ien_to_len16 = cpu_to_be32(FW_VI_ENABLE_CMD_LED_F | FW_LEN16(c));
c.blinkdur = cpu_to_be16(nblinks);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_iq_stop - stop an ingress queue and its FLs
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queues
* @vf: the VF owning the queues
* @iqtype: the ingress queue type (FW_IQ_TYPE_FL_INT_CAP, etc.)
* @iqid: ingress queue id
* @fl0id: FL0 queue id or 0xffff if no attached FL0
* @fl1id: FL1 queue id or 0xffff if no attached FL1
*
* Stops an ingress queue and its associated FLs, if any. This causes
* any current or future data/messages destined for these queues to be
* tossed.
*/
int t4_iq_stop(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int iqtype, unsigned int iqid,
unsigned int fl0id, unsigned int fl1id)
{
struct fw_iq_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_IQ_CMD) | FW_CMD_REQUEST_F |
FW_CMD_EXEC_F | FW_IQ_CMD_PFN_V(pf) |
FW_IQ_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_IQ_CMD_IQSTOP_F | FW_LEN16(c));
c.type_to_iqandstindex = cpu_to_be32(FW_IQ_CMD_TYPE_V(iqtype));
c.iqid = cpu_to_be16(iqid);
c.fl0id = cpu_to_be16(fl0id);
c.fl1id = cpu_to_be16(fl1id);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_iq_free - free an ingress queue and its FLs
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queues
* @vf: the VF owning the queues
* @iqtype: the ingress queue type
* @iqid: ingress queue id
* @fl0id: FL0 queue id or 0xffff if no attached FL0
* @fl1id: FL1 queue id or 0xffff if no attached FL1
*
* Frees an ingress queue and its associated FLs, if any.
*/
int t4_iq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int iqtype, unsigned int iqid,
unsigned int fl0id, unsigned int fl1id)
{
struct fw_iq_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_IQ_CMD) | FW_CMD_REQUEST_F |
FW_CMD_EXEC_F | FW_IQ_CMD_PFN_V(pf) |
FW_IQ_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_IQ_CMD_FREE_F | FW_LEN16(c));
c.type_to_iqandstindex = cpu_to_be32(FW_IQ_CMD_TYPE_V(iqtype));
c.iqid = cpu_to_be16(iqid);
c.fl0id = cpu_to_be16(fl0id);
c.fl1id = cpu_to_be16(fl1id);
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_eth_eq_free - free an Ethernet egress queue
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queue
* @vf: the VF owning the queue
* @eqid: egress queue id
*
* Frees an Ethernet egress queue.
*/
int t4_eth_eq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int eqid)
{
struct fw_eq_eth_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_EQ_ETH_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_EQ_ETH_CMD_PFN_V(pf) |
FW_EQ_ETH_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_EQ_ETH_CMD_FREE_F | FW_LEN16(c));
c.eqid_pkd = cpu_to_be32(FW_EQ_ETH_CMD_EQID_V(eqid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_ctrl_eq_free - free a control egress queue
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queue
* @vf: the VF owning the queue
* @eqid: egress queue id
*
* Frees a control egress queue.
*/
int t4_ctrl_eq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int eqid)
{
struct fw_eq_ctrl_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_EQ_CTRL_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_EQ_CTRL_CMD_PFN_V(pf) |
FW_EQ_CTRL_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_EQ_CTRL_CMD_FREE_F | FW_LEN16(c));
c.cmpliqid_eqid = cpu_to_be32(FW_EQ_CTRL_CMD_EQID_V(eqid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_ofld_eq_free - free an offload egress queue
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @pf: the PF owning the queue
* @vf: the VF owning the queue
* @eqid: egress queue id
*
* Frees a control egress queue.
*/
int t4_ofld_eq_free(struct adapter *adap, unsigned int mbox, unsigned int pf,
unsigned int vf, unsigned int eqid)
{
struct fw_eq_ofld_cmd c;
memset(&c, 0, sizeof(c));
c.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_EQ_OFLD_CMD) |
FW_CMD_REQUEST_F | FW_CMD_EXEC_F |
FW_EQ_OFLD_CMD_PFN_V(pf) |
FW_EQ_OFLD_CMD_VFN_V(vf));
c.alloc_to_len16 = cpu_to_be32(FW_EQ_OFLD_CMD_FREE_F | FW_LEN16(c));
c.eqid_pkd = cpu_to_be32(FW_EQ_OFLD_CMD_EQID_V(eqid));
return t4_wr_mbox(adap, mbox, &c, sizeof(c), NULL);
}
/**
* t4_link_down_rc_str - return a string for a Link Down Reason Code
* @link_down_rc: Link Down Reason Code
*
* Returns a string representation of the Link Down Reason Code.
*/
static const char *t4_link_down_rc_str(unsigned char link_down_rc)
{
static const char * const reason[] = {
"Link Down",
"Remote Fault",
"Auto-negotiation Failure",
"Reserved",
"Insufficient Airflow",
"Unable To Determine Reason",
"No RX Signal Detected",
"Reserved",
};
if (link_down_rc >= ARRAY_SIZE(reason))
return "Bad Reason Code";
return reason[link_down_rc];
}
/* Return the highest speed set in the port capabilities, in Mb/s. */
static unsigned int fwcap_to_speed(fw_port_cap32_t caps)
{
#define TEST_SPEED_RETURN(__caps_speed, __speed) \
do { \
if (caps & FW_PORT_CAP32_SPEED_##__caps_speed) \
return __speed; \
} while (0)
TEST_SPEED_RETURN(400G, 400000);
TEST_SPEED_RETURN(200G, 200000);
TEST_SPEED_RETURN(100G, 100000);
TEST_SPEED_RETURN(50G, 50000);
TEST_SPEED_RETURN(40G, 40000);
TEST_SPEED_RETURN(25G, 25000);
TEST_SPEED_RETURN(10G, 10000);
TEST_SPEED_RETURN(1G, 1000);
TEST_SPEED_RETURN(100M, 100);
#undef TEST_SPEED_RETURN
return 0;
}
/**
* fwcap_to_fwspeed - return highest speed in Port Capabilities
* @acaps: advertised Port Capabilities
*
* Get the highest speed for the port from the advertised Port
* Capabilities. It will be either the highest speed from the list of
* speeds or whatever user has set using ethtool.
*/
static fw_port_cap32_t fwcap_to_fwspeed(fw_port_cap32_t acaps)
{
#define TEST_SPEED_RETURN(__caps_speed) \
do { \
if (acaps & FW_PORT_CAP32_SPEED_##__caps_speed) \
return FW_PORT_CAP32_SPEED_##__caps_speed; \
} while (0)
TEST_SPEED_RETURN(400G);
TEST_SPEED_RETURN(200G);
TEST_SPEED_RETURN(100G);
TEST_SPEED_RETURN(50G);
TEST_SPEED_RETURN(40G);
TEST_SPEED_RETURN(25G);
TEST_SPEED_RETURN(10G);
TEST_SPEED_RETURN(1G);
TEST_SPEED_RETURN(100M);
#undef TEST_SPEED_RETURN
return 0;
}
/**
* lstatus_to_fwcap - translate old lstatus to 32-bit Port Capabilities
* @lstatus: old FW_PORT_ACTION_GET_PORT_INFO lstatus value
*
* Translates old FW_PORT_ACTION_GET_PORT_INFO lstatus field into new
* 32-bit Port Capabilities value.
*/
static fw_port_cap32_t lstatus_to_fwcap(u32 lstatus)
{
fw_port_cap32_t linkattr = 0;
/* Unfortunately the format of the Link Status in the old
* 16-bit Port Information message isn't the same as the
* 16-bit Port Capabilities bitfield used everywhere else ...
*/
if (lstatus & FW_PORT_CMD_RXPAUSE_F)
linkattr |= FW_PORT_CAP32_FC_RX;
if (lstatus & FW_PORT_CMD_TXPAUSE_F)
linkattr |= FW_PORT_CAP32_FC_TX;
if (lstatus & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_100M))
linkattr |= FW_PORT_CAP32_SPEED_100M;
if (lstatus & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_1G))
linkattr |= FW_PORT_CAP32_SPEED_1G;
if (lstatus & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_10G))
linkattr |= FW_PORT_CAP32_SPEED_10G;
if (lstatus & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_25G))
linkattr |= FW_PORT_CAP32_SPEED_25G;
if (lstatus & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_40G))
linkattr |= FW_PORT_CAP32_SPEED_40G;
if (lstatus & FW_PORT_CMD_LSPEED_V(FW_PORT_CAP_SPEED_100G))
linkattr |= FW_PORT_CAP32_SPEED_100G;
return linkattr;
}
/**
* t4_handle_get_port_info - process a FW reply message
* @pi: the port info
* @rpl: start of the FW message
*
* Processes a GET_PORT_INFO FW reply message.
*/
void t4_handle_get_port_info(struct port_info *pi, const __be64 *rpl)
{
const struct fw_port_cmd *cmd = (const void *)rpl;
fw_port_cap32_t pcaps, acaps, lpacaps, linkattr;
struct link_config *lc = &pi->link_cfg;
struct adapter *adapter = pi->adapter;
unsigned int speed, fc, fec, adv_fc;
enum fw_port_module_type mod_type;
int action, link_ok, linkdnrc;
enum fw_port_type port_type;
/* Extract the various fields from the Port Information message.
*/
action = FW_PORT_CMD_ACTION_G(be32_to_cpu(cmd->action_to_len16));
switch (action) {
case FW_PORT_ACTION_GET_PORT_INFO: {
u32 lstatus = be32_to_cpu(cmd->u.info.lstatus_to_modtype);
link_ok = (lstatus & FW_PORT_CMD_LSTATUS_F) != 0;
linkdnrc = FW_PORT_CMD_LINKDNRC_G(lstatus);
port_type = FW_PORT_CMD_PTYPE_G(lstatus);
mod_type = FW_PORT_CMD_MODTYPE_G(lstatus);
pcaps = fwcaps16_to_caps32(be16_to_cpu(cmd->u.info.pcap));
acaps = fwcaps16_to_caps32(be16_to_cpu(cmd->u.info.acap));
lpacaps = fwcaps16_to_caps32(be16_to_cpu(cmd->u.info.lpacap));
linkattr = lstatus_to_fwcap(lstatus);
break;
}
case FW_PORT_ACTION_GET_PORT_INFO32: {
u32 lstatus32;
lstatus32 = be32_to_cpu(cmd->u.info32.lstatus32_to_cbllen32);
link_ok = (lstatus32 & FW_PORT_CMD_LSTATUS32_F) != 0;
linkdnrc = FW_PORT_CMD_LINKDNRC32_G(lstatus32);
port_type = FW_PORT_CMD_PORTTYPE32_G(lstatus32);
mod_type = FW_PORT_CMD_MODTYPE32_G(lstatus32);
pcaps = be32_to_cpu(cmd->u.info32.pcaps32);
acaps = be32_to_cpu(cmd->u.info32.acaps32);
lpacaps = be32_to_cpu(cmd->u.info32.lpacaps32);
linkattr = be32_to_cpu(cmd->u.info32.linkattr32);
break;
}
default:
dev_err(adapter->pdev_dev, "Handle Port Information: Bad Command/Action %#x\n",
be32_to_cpu(cmd->action_to_len16));
return;
}
fec = fwcap_to_cc_fec(acaps);
adv_fc = fwcap_to_cc_pause(acaps);
fc = fwcap_to_cc_pause(linkattr);
speed = fwcap_to_speed(linkattr);
/* Reset state for communicating new Transceiver Module status and
* whether the OS-dependent layer wants us to redo the current
* "sticky" L1 Configure Link Parameters.
*/
lc->new_module = false;
lc->redo_l1cfg = false;
if (mod_type != pi->mod_type) {
/* With the newer SFP28 and QSFP28 Transceiver Module Types,
* various fundamental Port Capabilities which used to be
* immutable can now change radically. We can now have
* Speeds, Auto-Negotiation, Forward Error Correction, etc.
* all change based on what Transceiver Module is inserted.
* So we need to record the Physical "Port" Capabilities on
* every Transceiver Module change.
*/
lc->pcaps = pcaps;
/* When a new Transceiver Module is inserted, the Firmware
* will examine its i2c EPROM to determine its type and
* general operating parameters including things like Forward
* Error Control, etc. Various IEEE 802.3 standards dictate
* how to interpret these i2c values to determine default
* "sutomatic" settings. We record these for future use when
* the user explicitly requests these standards-based values.
*/
lc->def_acaps = acaps;
/* Some versions of the early T6 Firmware "cheated" when
* handling different Transceiver Modules by changing the
* underlaying Port Type reported to the Host Drivers. As
* such we need to capture whatever Port Type the Firmware
* sends us and record it in case it's different from what we
* were told earlier. Unfortunately, since Firmware is
* forever, we'll need to keep this code here forever, but in
* later T6 Firmware it should just be an assignment of the
* same value already recorded.
*/
pi->port_type = port_type;
/* Record new Module Type information.
*/
pi->mod_type = mod_type;
/* Let the OS-dependent layer know if we have a new
* Transceiver Module inserted.
*/
lc->new_module = t4_is_inserted_mod_type(mod_type);
t4_os_portmod_changed(adapter, pi->port_id);
}
if (link_ok != lc->link_ok || speed != lc->speed ||
fc != lc->fc || adv_fc != lc->advertised_fc ||
fec != lc->fec) {
/* something changed */
if (!link_ok && lc->link_ok) {
lc->link_down_rc = linkdnrc;
dev_warn_ratelimited(adapter->pdev_dev,
"Port %d link down, reason: %s\n",
pi->tx_chan,
t4_link_down_rc_str(linkdnrc));
}
lc->link_ok = link_ok;
lc->speed = speed;
lc->advertised_fc = adv_fc;
lc->fc = fc;
lc->fec = fec;
lc->lpacaps = lpacaps;
lc->acaps = acaps & ADVERT_MASK;
/* If we're not physically capable of Auto-Negotiation, note
* this as Auto-Negotiation disabled. Otherwise, we track
* what Auto-Negotiation settings we have. Note parallel
* structure in t4_link_l1cfg_core() and init_link_config().
*/
if (!(lc->acaps & FW_PORT_CAP32_ANEG)) {
lc->autoneg = AUTONEG_DISABLE;
} else if (lc->acaps & FW_PORT_CAP32_ANEG) {
lc->autoneg = AUTONEG_ENABLE;
} else {
/* When Autoneg is disabled, user needs to set
* single speed.
* Similar to cxgb4_ethtool.c: set_link_ksettings
*/
lc->acaps = 0;
lc->speed_caps = fwcap_to_fwspeed(acaps);
lc->autoneg = AUTONEG_DISABLE;
}
t4_os_link_changed(adapter, pi->port_id, link_ok);
}
/* If we have a new Transceiver Module and the OS-dependent code has
* told us that it wants us to redo whatever "sticky" L1 Configuration
* Link Parameters are set, do that now.
*/
if (lc->new_module && lc->redo_l1cfg) {
struct link_config old_lc;
int ret;
/* Save the current L1 Configuration and restore it if an
* error occurs. We probably should fix the l1_cfg*()
* routines not to change the link_config when an error
* occurs ...
*/
old_lc = *lc;
ret = t4_link_l1cfg_ns(adapter, adapter->mbox, pi->lport, lc);
if (ret) {
*lc = old_lc;
dev_warn(adapter->pdev_dev,
"Attempt to update new Transceiver Module settings failed\n");
}
}
lc->new_module = false;
lc->redo_l1cfg = false;
}
/**
* t4_update_port_info - retrieve and update port information if changed
* @pi: the port_info
*
* We issue a Get Port Information Command to the Firmware and, if
* successful, we check to see if anything is different from what we
* last recorded and update things accordingly.
*/
int t4_update_port_info(struct port_info *pi)
{
unsigned int fw_caps = pi->adapter->params.fw_caps_support;
struct fw_port_cmd port_cmd;
int ret;
memset(&port_cmd, 0, sizeof(port_cmd));
port_cmd.op_to_portid = cpu_to_be32(FW_CMD_OP_V(FW_PORT_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
FW_PORT_CMD_PORTID_V(pi->tx_chan));
port_cmd.action_to_len16 = cpu_to_be32(
FW_PORT_CMD_ACTION_V(fw_caps == FW_CAPS16
? FW_PORT_ACTION_GET_PORT_INFO
: FW_PORT_ACTION_GET_PORT_INFO32) |
FW_LEN16(port_cmd));
ret = t4_wr_mbox(pi->adapter, pi->adapter->mbox,
&port_cmd, sizeof(port_cmd), &port_cmd);
if (ret)
return ret;
t4_handle_get_port_info(pi, (__be64 *)&port_cmd);
return 0;
}
/**
* t4_get_link_params - retrieve basic link parameters for given port
* @pi: the port
* @link_okp: value return pointer for link up/down
* @speedp: value return pointer for speed (Mb/s)
* @mtup: value return pointer for mtu
*
* Retrieves basic link parameters for a port: link up/down, speed (Mb/s),
* and MTU for a specified port. A negative error is returned on
* failure; 0 on success.
*/
int t4_get_link_params(struct port_info *pi, unsigned int *link_okp,
unsigned int *speedp, unsigned int *mtup)
{
unsigned int fw_caps = pi->adapter->params.fw_caps_support;
unsigned int action, link_ok, mtu;
struct fw_port_cmd port_cmd;
fw_port_cap32_t linkattr;
int ret;
memset(&port_cmd, 0, sizeof(port_cmd));
port_cmd.op_to_portid = cpu_to_be32(FW_CMD_OP_V(FW_PORT_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
FW_PORT_CMD_PORTID_V(pi->tx_chan));
action = (fw_caps == FW_CAPS16
? FW_PORT_ACTION_GET_PORT_INFO
: FW_PORT_ACTION_GET_PORT_INFO32);
port_cmd.action_to_len16 = cpu_to_be32(
FW_PORT_CMD_ACTION_V(action) |
FW_LEN16(port_cmd));
ret = t4_wr_mbox(pi->adapter, pi->adapter->mbox,
&port_cmd, sizeof(port_cmd), &port_cmd);
if (ret)
return ret;
if (action == FW_PORT_ACTION_GET_PORT_INFO) {
u32 lstatus = be32_to_cpu(port_cmd.u.info.lstatus_to_modtype);
link_ok = !!(lstatus & FW_PORT_CMD_LSTATUS_F);
linkattr = lstatus_to_fwcap(lstatus);
mtu = be16_to_cpu(port_cmd.u.info.mtu);
} else {
u32 lstatus32 =
be32_to_cpu(port_cmd.u.info32.lstatus32_to_cbllen32);
link_ok = !!(lstatus32 & FW_PORT_CMD_LSTATUS32_F);
linkattr = be32_to_cpu(port_cmd.u.info32.linkattr32);
mtu = FW_PORT_CMD_MTU32_G(
be32_to_cpu(port_cmd.u.info32.auxlinfo32_mtu32));
}
if (link_okp)
*link_okp = link_ok;
if (speedp)
*speedp = fwcap_to_speed(linkattr);
if (mtup)
*mtup = mtu;
return 0;
}
/**
* t4_handle_fw_rpl - process a FW reply message
* @adap: the adapter
* @rpl: start of the FW message
*
* Processes a FW message, such as link state change messages.
*/
int t4_handle_fw_rpl(struct adapter *adap, const __be64 *rpl)
{
u8 opcode = *(const u8 *)rpl;
/* This might be a port command ... this simplifies the following
* conditionals ... We can get away with pre-dereferencing
* action_to_len16 because it's in the first 16 bytes and all messages
* will be at least that long.
*/
const struct fw_port_cmd *p = (const void *)rpl;
unsigned int action =
FW_PORT_CMD_ACTION_G(be32_to_cpu(p->action_to_len16));
if (opcode == FW_PORT_CMD &&
(action == FW_PORT_ACTION_GET_PORT_INFO ||
action == FW_PORT_ACTION_GET_PORT_INFO32)) {
int i;
int chan = FW_PORT_CMD_PORTID_G(be32_to_cpu(p->op_to_portid));
struct port_info *pi = NULL;
for_each_port(adap, i) {
pi = adap2pinfo(adap, i);
if (pi->tx_chan == chan)
break;
}
t4_handle_get_port_info(pi, rpl);
} else {
dev_warn(adap->pdev_dev, "Unknown firmware reply %d\n",
opcode);
return -EINVAL;
}
return 0;
}
static void get_pci_mode(struct adapter *adapter, struct pci_params *p)
{
u16 val;
if (pci_is_pcie(adapter->pdev)) {
pcie_capability_read_word(adapter->pdev, PCI_EXP_LNKSTA, &val);
p->speed = val & PCI_EXP_LNKSTA_CLS;
p->width = (val & PCI_EXP_LNKSTA_NLW) >> 4;
}
}
/**
* init_link_config - initialize a link's SW state
* @lc: pointer to structure holding the link state
* @pcaps: link Port Capabilities
* @acaps: link current Advertised Port Capabilities
*
* Initializes the SW state maintained for each link, including the link's
* capabilities and default speed/flow-control/autonegotiation settings.
*/
static void init_link_config(struct link_config *lc, fw_port_cap32_t pcaps,
fw_port_cap32_t acaps)
{
lc->pcaps = pcaps;
lc->def_acaps = acaps;
lc->lpacaps = 0;
lc->speed_caps = 0;
lc->speed = 0;
lc->requested_fc = lc->fc = PAUSE_RX | PAUSE_TX;
/* For Forward Error Control, we default to whatever the Firmware
* tells us the Link is currently advertising.
*/
lc->requested_fec = FEC_AUTO;
lc->fec = fwcap_to_cc_fec(lc->def_acaps);
/* If the Port is capable of Auto-Negtotiation, initialize it as
* "enabled" and copy over all of the Physical Port Capabilities
* to the Advertised Port Capabilities. Otherwise mark it as
* Auto-Negotiate disabled and select the highest supported speed
* for the link. Note parallel structure in t4_link_l1cfg_core()
* and t4_handle_get_port_info().
*/
if (lc->pcaps & FW_PORT_CAP32_ANEG) {
lc->acaps = lc->pcaps & ADVERT_MASK;
lc->autoneg = AUTONEG_ENABLE;
lc->requested_fc |= PAUSE_AUTONEG;
} else {
lc->acaps = 0;
lc->autoneg = AUTONEG_DISABLE;
lc->speed_caps = fwcap_to_fwspeed(acaps);
}
}
#define CIM_PF_NOACCESS 0xeeeeeeee
int t4_wait_dev_ready(void __iomem *regs)
{
u32 whoami;
whoami = readl(regs + PL_WHOAMI_A);
if (whoami != 0xffffffff && whoami != CIM_PF_NOACCESS)
return 0;
msleep(500);
whoami = readl(regs + PL_WHOAMI_A);
return (whoami != 0xffffffff && whoami != CIM_PF_NOACCESS ? 0 : -EIO);
}
struct flash_desc {
u32 vendor_and_model_id;
u32 size_mb;
};
static int t4_get_flash_params(struct adapter *adap)
{
/* Table for non-Numonix supported flash parts. Numonix parts are left
* to the preexisting code. All flash parts have 64KB sectors.
*/
static struct flash_desc supported_flash[] = {
{ 0x150201, 4 << 20 }, /* Spansion 4MB S25FL032P */
};
unsigned int part, manufacturer;
unsigned int density, size = 0;
u32 flashid = 0;
int ret;
/* Issue a Read ID Command to the Flash part. We decode supported
* Flash parts and their sizes from this. There's a newer Query
* Command which can retrieve detailed geometry information but many
* Flash parts don't support it.
*/
ret = sf1_write(adap, 1, 1, 0, SF_RD_ID);
if (!ret)
ret = sf1_read(adap, 3, 0, 1, &flashid);
t4_write_reg(adap, SF_OP_A, 0); /* unlock SF */
if (ret)
return ret;
/* Check to see if it's one of our non-standard supported Flash parts.
*/
for (part = 0; part < ARRAY_SIZE(supported_flash); part++)
if (supported_flash[part].vendor_and_model_id == flashid) {
adap->params.sf_size = supported_flash[part].size_mb;
adap->params.sf_nsec =
adap->params.sf_size / SF_SEC_SIZE;
goto found;
}
/* Decode Flash part size. The code below looks repetitive with
* common encodings, but that's not guaranteed in the JEDEC
* specification for the Read JEDEC ID command. The only thing that
* we're guaranteed by the JEDEC specification is where the
* Manufacturer ID is in the returned result. After that each
* Manufacturer ~could~ encode things completely differently.
* Note, all Flash parts must have 64KB sectors.
*/
manufacturer = flashid & 0xff;
switch (manufacturer) {
case 0x20: { /* Micron/Numonix */
/* This Density -> Size decoding table is taken from Micron
* Data Sheets.
*/
density = (flashid >> 16) & 0xff;
switch (density) {
case 0x14: /* 1MB */
size = 1 << 20;
break;
case 0x15: /* 2MB */
size = 1 << 21;
break;
case 0x16: /* 4MB */
size = 1 << 22;
break;
case 0x17: /* 8MB */
size = 1 << 23;
break;
case 0x18: /* 16MB */
size = 1 << 24;
break;
case 0x19: /* 32MB */
size = 1 << 25;
break;
case 0x20: /* 64MB */
size = 1 << 26;
break;
case 0x21: /* 128MB */
size = 1 << 27;
break;
case 0x22: /* 256MB */
size = 1 << 28;
break;
}
break;
}
case 0x9d: { /* ISSI -- Integrated Silicon Solution, Inc. */
/* This Density -> Size decoding table is taken from ISSI
* Data Sheets.
*/
density = (flashid >> 16) & 0xff;
switch (density) {
case 0x16: /* 32 MB */
size = 1 << 25;
break;
case 0x17: /* 64MB */
size = 1 << 26;
break;
}
break;
}
case 0xc2: { /* Macronix */
/* This Density -> Size decoding table is taken from Macronix
* Data Sheets.
*/
density = (flashid >> 16) & 0xff;
switch (density) {
case 0x17: /* 8MB */
size = 1 << 23;
break;
case 0x18: /* 16MB */
size = 1 << 24;
break;
}
break;
}
case 0xef: { /* Winbond */
/* This Density -> Size decoding table is taken from Winbond
* Data Sheets.
*/
density = (flashid >> 16) & 0xff;
switch (density) {
case 0x17: /* 8MB */
size = 1 << 23;
break;
case 0x18: /* 16MB */
size = 1 << 24;
break;
}
break;
}
}
/* If we didn't recognize the FLASH part, that's no real issue: the
* Hardware/Software contract says that Hardware will _*ALWAYS*_
* use a FLASH part which is at least 4MB in size and has 64KB
* sectors. The unrecognized FLASH part is likely to be much larger
* than 4MB, but that's all we really need.
*/
if (size == 0) {
dev_warn(adap->pdev_dev, "Unknown Flash Part, ID = %#x, assuming 4MB\n",
flashid);
size = 1 << 22;
}
/* Store decoded Flash size and fall through into vetting code. */
adap->params.sf_size = size;
adap->params.sf_nsec = size / SF_SEC_SIZE;
found:
if (adap->params.sf_size < FLASH_MIN_SIZE)
dev_warn(adap->pdev_dev, "WARNING: Flash Part ID %#x, size %#x < %#x\n",
flashid, adap->params.sf_size, FLASH_MIN_SIZE);
return 0;
}
/**
* t4_prep_adapter - prepare SW and HW for operation
* @adapter: the adapter
*
* Initialize adapter SW state for the various HW modules, set initial
* values for some adapter tunables, take PHYs out of reset, and
* initialize the MDIO interface.
*/
int t4_prep_adapter(struct adapter *adapter)
{
int ret, ver;
uint16_t device_id;
u32 pl_rev;
get_pci_mode(adapter, &adapter->params.pci);
pl_rev = REV_G(t4_read_reg(adapter, PL_REV_A));
ret = t4_get_flash_params(adapter);
if (ret < 0) {
dev_err(adapter->pdev_dev, "error %d identifying flash\n", ret);
return ret;
}
/* Retrieve adapter's device ID
*/
pci_read_config_word(adapter->pdev, PCI_DEVICE_ID, &device_id);
ver = device_id >> 12;
adapter->params.chip = 0;
switch (ver) {
case CHELSIO_T4:
adapter->params.chip |= CHELSIO_CHIP_CODE(CHELSIO_T4, pl_rev);
adapter->params.arch.sge_fl_db = DBPRIO_F;
adapter->params.arch.mps_tcam_size =
NUM_MPS_CLS_SRAM_L_INSTANCES;
adapter->params.arch.mps_rplc_size = 128;
adapter->params.arch.nchan = NCHAN;
adapter->params.arch.pm_stats_cnt = PM_NSTATS;
adapter->params.arch.vfcount = 128;
/* Congestion map is for 4 channels so that
* MPS can have 4 priority per port.
*/
adapter->params.arch.cng_ch_bits_log = 2;
break;
case CHELSIO_T5:
adapter->params.chip |= CHELSIO_CHIP_CODE(CHELSIO_T5, pl_rev);
adapter->params.arch.sge_fl_db = DBPRIO_F | DBTYPE_F;
adapter->params.arch.mps_tcam_size =
NUM_MPS_T5_CLS_SRAM_L_INSTANCES;
adapter->params.arch.mps_rplc_size = 128;
adapter->params.arch.nchan = NCHAN;
adapter->params.arch.pm_stats_cnt = PM_NSTATS;
adapter->params.arch.vfcount = 128;
adapter->params.arch.cng_ch_bits_log = 2;
break;
case CHELSIO_T6:
adapter->params.chip |= CHELSIO_CHIP_CODE(CHELSIO_T6, pl_rev);
adapter->params.arch.sge_fl_db = 0;
adapter->params.arch.mps_tcam_size =
NUM_MPS_T5_CLS_SRAM_L_INSTANCES;
adapter->params.arch.mps_rplc_size = 256;
adapter->params.arch.nchan = 2;
adapter->params.arch.pm_stats_cnt = T6_PM_NSTATS;
adapter->params.arch.vfcount = 256;
/* Congestion map will be for 2 channels so that
* MPS can have 8 priority per port.
*/
adapter->params.arch.cng_ch_bits_log = 3;
break;
default:
dev_err(adapter->pdev_dev, "Device %d is not supported\n",
device_id);
return -EINVAL;
}
adapter->params.cim_la_size = CIMLA_SIZE;
init_cong_ctrl(adapter->params.a_wnd, adapter->params.b_wnd);
/*
* Default port for debugging in case we can't reach FW.
*/
adapter->params.nports = 1;
adapter->params.portvec = 1;
adapter->params.vpd.cclk = 50000;
/* Set PCIe completion timeout to 4 seconds. */
pcie_capability_clear_and_set_word(adapter->pdev, PCI_EXP_DEVCTL2,
PCI_EXP_DEVCTL2_COMP_TIMEOUT, 0xd);
return 0;
}
/**
* t4_shutdown_adapter - shut down adapter, host & wire
* @adapter: the adapter
*
* Perform an emergency shutdown of the adapter and stop it from
* continuing any further communication on the ports or DMA to the
* host. This is typically used when the adapter and/or firmware
* have crashed and we want to prevent any further accidental
* communication with the rest of the world. This will also force
* the port Link Status to go down -- if register writes work --
* which should help our peers figure out that we're down.
*/
int t4_shutdown_adapter(struct adapter *adapter)
{
int port;
t4_intr_disable(adapter);
t4_write_reg(adapter, DBG_GPIO_EN_A, 0);
for_each_port(adapter, port) {
u32 a_port_cfg = is_t4(adapter->params.chip) ?
PORT_REG(port, XGMAC_PORT_CFG_A) :
T5_PORT_REG(port, MAC_PORT_CFG_A);
t4_write_reg(adapter, a_port_cfg,
t4_read_reg(adapter, a_port_cfg)
& ~SIGNAL_DET_V(1));
}
t4_set_reg_field(adapter, SGE_CONTROL_A, GLOBALENABLE_F, 0);
return 0;
}
/**
* t4_bar2_sge_qregs - return BAR2 SGE Queue register information
* @adapter: the adapter
* @qid: the Queue ID
* @qtype: the Ingress or Egress type for @qid
* @user: true if this request is for a user mode queue
* @pbar2_qoffset: BAR2 Queue Offset
* @pbar2_qid: BAR2 Queue ID or 0 for Queue ID inferred SGE Queues
*
* Returns the BAR2 SGE Queue Registers information associated with the
* indicated Absolute Queue ID. These are passed back in return value
* pointers. @qtype should be T4_BAR2_QTYPE_EGRESS for Egress Queue
* and T4_BAR2_QTYPE_INGRESS for Ingress Queues.
*
* This may return an error which indicates that BAR2 SGE Queue
* registers aren't available. If an error is not returned, then the
* following values are returned:
*
* *@pbar2_qoffset: the BAR2 Offset of the @qid Registers
* *@pbar2_qid: the BAR2 SGE Queue ID or 0 of @qid
*
* If the returned BAR2 Queue ID is 0, then BAR2 SGE registers which
* require the "Inferred Queue ID" ability may be used. E.g. the
* Write Combining Doorbell Buffer. If the BAR2 Queue ID is not 0,
* then these "Inferred Queue ID" register may not be used.
*/
int t4_bar2_sge_qregs(struct adapter *adapter,
unsigned int qid,
enum t4_bar2_qtype qtype,
int user,
u64 *pbar2_qoffset,
unsigned int *pbar2_qid)
{
unsigned int page_shift, page_size, qpp_shift, qpp_mask;
u64 bar2_page_offset, bar2_qoffset;
unsigned int bar2_qid, bar2_qid_offset, bar2_qinferred;
/* T4 doesn't support BAR2 SGE Queue registers for kernel mode queues */
if (!user && is_t4(adapter->params.chip))
return -EINVAL;
/* Get our SGE Page Size parameters.
*/
page_shift = adapter->params.sge.hps + 10;
page_size = 1 << page_shift;
/* Get the right Queues per Page parameters for our Queue.
*/
qpp_shift = (qtype == T4_BAR2_QTYPE_EGRESS
? adapter->params.sge.eq_qpp
: adapter->params.sge.iq_qpp);
qpp_mask = (1 << qpp_shift) - 1;
/* Calculate the basics of the BAR2 SGE Queue register area:
* o The BAR2 page the Queue registers will be in.
* o The BAR2 Queue ID.
* o The BAR2 Queue ID Offset into the BAR2 page.
*/
bar2_page_offset = ((u64)(qid >> qpp_shift) << page_shift);
bar2_qid = qid & qpp_mask;
bar2_qid_offset = bar2_qid * SGE_UDB_SIZE;
/* If the BAR2 Queue ID Offset is less than the Page Size, then the
* hardware will infer the Absolute Queue ID simply from the writes to
* the BAR2 Queue ID Offset within the BAR2 Page (and we need to use a
* BAR2 Queue ID of 0 for those writes). Otherwise, we'll simply
* write to the first BAR2 SGE Queue Area within the BAR2 Page with
* the BAR2 Queue ID and the hardware will infer the Absolute Queue ID
* from the BAR2 Page and BAR2 Queue ID.
*
* One important censequence of this is that some BAR2 SGE registers
* have a "Queue ID" field and we can write the BAR2 SGE Queue ID
* there. But other registers synthesize the SGE Queue ID purely
* from the writes to the registers -- the Write Combined Doorbell
* Buffer is a good example. These BAR2 SGE Registers are only
* available for those BAR2 SGE Register areas where the SGE Absolute
* Queue ID can be inferred from simple writes.
*/
bar2_qoffset = bar2_page_offset;
bar2_qinferred = (bar2_qid_offset < page_size);
if (bar2_qinferred) {
bar2_qoffset += bar2_qid_offset;
bar2_qid = 0;
}
*pbar2_qoffset = bar2_qoffset;
*pbar2_qid = bar2_qid;
return 0;
}
/**
* t4_init_devlog_params - initialize adapter->params.devlog
* @adap: the adapter
*
* Initialize various fields of the adapter's Firmware Device Log
* Parameters structure.
*/
int t4_init_devlog_params(struct adapter *adap)
{
struct devlog_params *dparams = &adap->params.devlog;
u32 pf_dparams;
unsigned int devlog_meminfo;
struct fw_devlog_cmd devlog_cmd;
int ret;
/* If we're dealing with newer firmware, the Device Log Parameters
* are stored in a designated register which allows us to access the
* Device Log even if we can't talk to the firmware.
*/
pf_dparams =
t4_read_reg(adap, PCIE_FW_REG(PCIE_FW_PF_A, PCIE_FW_PF_DEVLOG));
if (pf_dparams) {
unsigned int nentries, nentries128;
dparams->memtype = PCIE_FW_PF_DEVLOG_MEMTYPE_G(pf_dparams);
dparams->start = PCIE_FW_PF_DEVLOG_ADDR16_G(pf_dparams) << 4;
nentries128 = PCIE_FW_PF_DEVLOG_NENTRIES128_G(pf_dparams);
nentries = (nentries128 + 1) * 128;
dparams->size = nentries * sizeof(struct fw_devlog_e);
return 0;
}
/* Otherwise, ask the firmware for it's Device Log Parameters.
*/
memset(&devlog_cmd, 0, sizeof(devlog_cmd));
devlog_cmd.op_to_write = cpu_to_be32(FW_CMD_OP_V(FW_DEVLOG_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F);
devlog_cmd.retval_len16 = cpu_to_be32(FW_LEN16(devlog_cmd));
ret = t4_wr_mbox(adap, adap->mbox, &devlog_cmd, sizeof(devlog_cmd),
&devlog_cmd);
if (ret)
return ret;
devlog_meminfo =
be32_to_cpu(devlog_cmd.memtype_devlog_memaddr16_devlog);
dparams->memtype = FW_DEVLOG_CMD_MEMTYPE_DEVLOG_G(devlog_meminfo);
dparams->start = FW_DEVLOG_CMD_MEMADDR16_DEVLOG_G(devlog_meminfo) << 4;
dparams->size = be32_to_cpu(devlog_cmd.memsize_devlog);
return 0;
}
/**
* t4_init_sge_params - initialize adap->params.sge
* @adapter: the adapter
*
* Initialize various fields of the adapter's SGE Parameters structure.
*/
int t4_init_sge_params(struct adapter *adapter)
{
struct sge_params *sge_params = &adapter->params.sge;
u32 hps, qpp;
unsigned int s_hps, s_qpp;
/* Extract the SGE Page Size for our PF.
*/
hps = t4_read_reg(adapter, SGE_HOST_PAGE_SIZE_A);
s_hps = (HOSTPAGESIZEPF0_S +
(HOSTPAGESIZEPF1_S - HOSTPAGESIZEPF0_S) * adapter->pf);
sge_params->hps = ((hps >> s_hps) & HOSTPAGESIZEPF0_M);
/* Extract the SGE Egress and Ingess Queues Per Page for our PF.
*/
s_qpp = (QUEUESPERPAGEPF0_S +
(QUEUESPERPAGEPF1_S - QUEUESPERPAGEPF0_S) * adapter->pf);
qpp = t4_read_reg(adapter, SGE_EGRESS_QUEUES_PER_PAGE_PF_A);
sge_params->eq_qpp = ((qpp >> s_qpp) & QUEUESPERPAGEPF0_M);
qpp = t4_read_reg(adapter, SGE_INGRESS_QUEUES_PER_PAGE_PF_A);
sge_params->iq_qpp = ((qpp >> s_qpp) & QUEUESPERPAGEPF0_M);
return 0;
}
/**
* t4_init_tp_params - initialize adap->params.tp
* @adap: the adapter
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Initialize various fields of the adapter's TP Parameters structure.
*/
int t4_init_tp_params(struct adapter *adap, bool sleep_ok)
{
u32 param, val, v;
int chan, ret;
v = t4_read_reg(adap, TP_TIMER_RESOLUTION_A);
adap->params.tp.tre = TIMERRESOLUTION_G(v);
adap->params.tp.dack_re = DELAYEDACKRESOLUTION_G(v);
/* MODQ_REQ_MAP defaults to setting queues 0-3 to chan 0-3 */
for (chan = 0; chan < NCHAN; chan++)
adap->params.tp.tx_modq[chan] = chan;
/* Cache the adapter's Compressed Filter Mode/Mask and global Ingress
* Configuration.
*/
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_DEV) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_DEV_FILTER) |
FW_PARAMS_PARAM_Y_V(FW_PARAM_DEV_FILTER_MODE_MASK));
/* Read current value */
ret = t4_query_params(adap, adap->mbox, adap->pf, 0, 1,
¶m, &val);
if (ret == 0) {
dev_info(adap->pdev_dev,
"Current filter mode/mask 0x%x:0x%x\n",
FW_PARAMS_PARAM_FILTER_MODE_G(val),
FW_PARAMS_PARAM_FILTER_MASK_G(val));
adap->params.tp.vlan_pri_map =
FW_PARAMS_PARAM_FILTER_MODE_G(val);
adap->params.tp.filter_mask =
FW_PARAMS_PARAM_FILTER_MASK_G(val);
} else {
dev_info(adap->pdev_dev,
"Failed to read filter mode/mask via fw api, using indirect-reg-read\n");
/* Incase of older-fw (which doesn't expose the api
* FW_PARAM_DEV_FILTER_MODE_MASK) and newer-driver (which uses
* the fw api) combination, fall-back to older method of reading
* the filter mode from indirect-register
*/
t4_tp_pio_read(adap, &adap->params.tp.vlan_pri_map, 1,
TP_VLAN_PRI_MAP_A, sleep_ok);
/* With the older-fw and newer-driver combination we might run
* into an issue when user wants to use hash filter region but
* the filter_mask is zero, in this case filter_mask validation
* is tough. To avoid that we set the filter_mask same as filter
* mode, which will behave exactly as the older way of ignoring
* the filter mask validation.
*/
adap->params.tp.filter_mask = adap->params.tp.vlan_pri_map;
}
t4_tp_pio_read(adap, &adap->params.tp.ingress_config, 1,
TP_INGRESS_CONFIG_A, sleep_ok);
/* For T6, cache the adapter's compressed error vector
* and passing outer header info for encapsulated packets.
*/
if (CHELSIO_CHIP_VERSION(adap->params.chip) > CHELSIO_T5) {
v = t4_read_reg(adap, TP_OUT_CONFIG_A);
adap->params.tp.rx_pkt_encap = (v & CRXPKTENC_F) ? 1 : 0;
}
/* Now that we have TP_VLAN_PRI_MAP cached, we can calculate the field
* shift positions of several elements of the Compressed Filter Tuple
* for this adapter which we need frequently ...
*/
adap->params.tp.fcoe_shift = t4_filter_field_shift(adap, FCOE_F);
adap->params.tp.port_shift = t4_filter_field_shift(adap, PORT_F);
adap->params.tp.vnic_shift = t4_filter_field_shift(adap, VNIC_ID_F);
adap->params.tp.vlan_shift = t4_filter_field_shift(adap, VLAN_F);
adap->params.tp.tos_shift = t4_filter_field_shift(adap, TOS_F);
adap->params.tp.protocol_shift = t4_filter_field_shift(adap,
PROTOCOL_F);
adap->params.tp.ethertype_shift = t4_filter_field_shift(adap,
ETHERTYPE_F);
adap->params.tp.macmatch_shift = t4_filter_field_shift(adap,
MACMATCH_F);
adap->params.tp.matchtype_shift = t4_filter_field_shift(adap,
MPSHITTYPE_F);
adap->params.tp.frag_shift = t4_filter_field_shift(adap,
FRAGMENTATION_F);
/* If TP_INGRESS_CONFIG.VNID == 0, then TP_VLAN_PRI_MAP.VNIC_ID
* represents the presence of an Outer VLAN instead of a VNIC ID.
*/
if ((adap->params.tp.ingress_config & VNIC_F) == 0)
adap->params.tp.vnic_shift = -1;
v = t4_read_reg(adap, LE_3_DB_HASH_MASK_GEN_IPV4_T6_A);
adap->params.tp.hash_filter_mask = v;
v = t4_read_reg(adap, LE_4_DB_HASH_MASK_GEN_IPV4_T6_A);
adap->params.tp.hash_filter_mask |= ((u64)v << 32);
return 0;
}
/**
* t4_filter_field_shift - calculate filter field shift
* @adap: the adapter
* @filter_sel: the desired field (from TP_VLAN_PRI_MAP bits)
*
* Return the shift position of a filter field within the Compressed
* Filter Tuple. The filter field is specified via its selection bit
* within TP_VLAN_PRI_MAL (filter mode). E.g. F_VLAN.
*/
int t4_filter_field_shift(const struct adapter *adap, int filter_sel)
{
unsigned int filter_mode = adap->params.tp.vlan_pri_map;
unsigned int sel;
int field_shift;
if ((filter_mode & filter_sel) == 0)
return -1;
for (sel = 1, field_shift = 0; sel < filter_sel; sel <<= 1) {
switch (filter_mode & sel) {
case FCOE_F:
field_shift += FT_FCOE_W;
break;
case PORT_F:
field_shift += FT_PORT_W;
break;
case VNIC_ID_F:
field_shift += FT_VNIC_ID_W;
break;
case VLAN_F:
field_shift += FT_VLAN_W;
break;
case TOS_F:
field_shift += FT_TOS_W;
break;
case PROTOCOL_F:
field_shift += FT_PROTOCOL_W;
break;
case ETHERTYPE_F:
field_shift += FT_ETHERTYPE_W;
break;
case MACMATCH_F:
field_shift += FT_MACMATCH_W;
break;
case MPSHITTYPE_F:
field_shift += FT_MPSHITTYPE_W;
break;
case FRAGMENTATION_F:
field_shift += FT_FRAGMENTATION_W;
break;
}
}
return field_shift;
}
int t4_init_rss_mode(struct adapter *adap, int mbox)
{
int i, ret;
struct fw_rss_vi_config_cmd rvc;
memset(&rvc, 0, sizeof(rvc));
for_each_port(adap, i) {
struct port_info *p = adap2pinfo(adap, i);
rvc.op_to_viid =
cpu_to_be32(FW_CMD_OP_V(FW_RSS_VI_CONFIG_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
FW_RSS_VI_CONFIG_CMD_VIID_V(p->viid));
rvc.retval_len16 = cpu_to_be32(FW_LEN16(rvc));
ret = t4_wr_mbox(adap, mbox, &rvc, sizeof(rvc), &rvc);
if (ret)
return ret;
p->rss_mode = be32_to_cpu(rvc.u.basicvirtual.defaultq_to_udpen);
}
return 0;
}
/**
* t4_init_portinfo - allocate a virtual interface and initialize port_info
* @pi: the port_info
* @mbox: mailbox to use for the FW command
* @port: physical port associated with the VI
* @pf: the PF owning the VI
* @vf: the VF owning the VI
* @mac: the MAC address of the VI
*
* Allocates a virtual interface for the given physical port. If @mac is
* not %NULL it contains the MAC address of the VI as assigned by FW.
* @mac should be large enough to hold an Ethernet address.
* Returns < 0 on error.
*/
int t4_init_portinfo(struct port_info *pi, int mbox,
int port, int pf, int vf, u8 mac[])
{
struct adapter *adapter = pi->adapter;
unsigned int fw_caps = adapter->params.fw_caps_support;
struct fw_port_cmd cmd;
unsigned int rss_size;
enum fw_port_type port_type;
int mdio_addr;
fw_port_cap32_t pcaps, acaps;
u8 vivld = 0, vin = 0;
int ret;
/* If we haven't yet determined whether we're talking to Firmware
* which knows the new 32-bit Port Capabilities, it's time to find
* out now. This will also tell new Firmware to send us Port Status
* Updates using the new 32-bit Port Capabilities version of the
* Port Information message.
*/
if (fw_caps == FW_CAPS_UNKNOWN) {
u32 param, val;
param = (FW_PARAMS_MNEM_V(FW_PARAMS_MNEM_PFVF) |
FW_PARAMS_PARAM_X_V(FW_PARAMS_PARAM_PFVF_PORT_CAPS32));
val = 1;
ret = t4_set_params(adapter, mbox, pf, vf, 1, ¶m, &val);
fw_caps = (ret == 0 ? FW_CAPS32 : FW_CAPS16);
adapter->params.fw_caps_support = fw_caps;
}
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_portid = cpu_to_be32(FW_CMD_OP_V(FW_PORT_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
FW_PORT_CMD_PORTID_V(port));
cmd.action_to_len16 = cpu_to_be32(
FW_PORT_CMD_ACTION_V(fw_caps == FW_CAPS16
? FW_PORT_ACTION_GET_PORT_INFO
: FW_PORT_ACTION_GET_PORT_INFO32) |
FW_LEN16(cmd));
ret = t4_wr_mbox(pi->adapter, mbox, &cmd, sizeof(cmd), &cmd);
if (ret)
return ret;
/* Extract the various fields from the Port Information message.
*/
if (fw_caps == FW_CAPS16) {
u32 lstatus = be32_to_cpu(cmd.u.info.lstatus_to_modtype);
port_type = FW_PORT_CMD_PTYPE_G(lstatus);
mdio_addr = ((lstatus & FW_PORT_CMD_MDIOCAP_F)
? FW_PORT_CMD_MDIOADDR_G(lstatus)
: -1);
pcaps = fwcaps16_to_caps32(be16_to_cpu(cmd.u.info.pcap));
acaps = fwcaps16_to_caps32(be16_to_cpu(cmd.u.info.acap));
} else {
u32 lstatus32 = be32_to_cpu(cmd.u.info32.lstatus32_to_cbllen32);
port_type = FW_PORT_CMD_PORTTYPE32_G(lstatus32);
mdio_addr = ((lstatus32 & FW_PORT_CMD_MDIOCAP32_F)
? FW_PORT_CMD_MDIOADDR32_G(lstatus32)
: -1);
pcaps = be32_to_cpu(cmd.u.info32.pcaps32);
acaps = be32_to_cpu(cmd.u.info32.acaps32);
}
ret = t4_alloc_vi(pi->adapter, mbox, port, pf, vf, 1, mac, &rss_size,
&vivld, &vin);
if (ret < 0)
return ret;
pi->viid = ret;
pi->tx_chan = port;
pi->lport = port;
pi->rss_size = rss_size;
pi->rx_cchan = t4_get_tp_e2c_map(pi->adapter, port);
/* If fw supports returning the VIN as part of FW_VI_CMD,
* save the returned values.
*/
if (adapter->params.viid_smt_extn_support) {
pi->vivld = vivld;
pi->vin = vin;
} else {
/* Retrieve the values from VIID */
pi->vivld = FW_VIID_VIVLD_G(pi->viid);
pi->vin = FW_VIID_VIN_G(pi->viid);
}
pi->port_type = port_type;
pi->mdio_addr = mdio_addr;
pi->mod_type = FW_PORT_MOD_TYPE_NA;
init_link_config(&pi->link_cfg, pcaps, acaps);
return 0;
}
int t4_port_init(struct adapter *adap, int mbox, int pf, int vf)
{
u8 addr[6];
int ret, i, j = 0;
for_each_port(adap, i) {
struct port_info *pi = adap2pinfo(adap, i);
while ((adap->params.portvec & (1 << j)) == 0)
j++;
ret = t4_init_portinfo(pi, mbox, j, pf, vf, addr);
if (ret)
return ret;
memcpy(adap->port[i]->dev_addr, addr, ETH_ALEN);
j++;
}
return 0;
}
/**
* t4_read_cimq_cfg - read CIM queue configuration
* @adap: the adapter
* @base: holds the queue base addresses in bytes
* @size: holds the queue sizes in bytes
* @thres: holds the queue full thresholds in bytes
*
* Returns the current configuration of the CIM queues, starting with
* the IBQs, then the OBQs.
*/
void t4_read_cimq_cfg(struct adapter *adap, u16 *base, u16 *size, u16 *thres)
{
unsigned int i, v;
int cim_num_obq = is_t4(adap->params.chip) ?
CIM_NUM_OBQ : CIM_NUM_OBQ_T5;
for (i = 0; i < CIM_NUM_IBQ; i++) {
t4_write_reg(adap, CIM_QUEUE_CONFIG_REF_A, IBQSELECT_F |
QUENUMSELECT_V(i));
v = t4_read_reg(adap, CIM_QUEUE_CONFIG_CTRL_A);
/* value is in 256-byte units */
*base++ = CIMQBASE_G(v) * 256;
*size++ = CIMQSIZE_G(v) * 256;
*thres++ = QUEFULLTHRSH_G(v) * 8; /* 8-byte unit */
}
for (i = 0; i < cim_num_obq; i++) {
t4_write_reg(adap, CIM_QUEUE_CONFIG_REF_A, OBQSELECT_F |
QUENUMSELECT_V(i));
v = t4_read_reg(adap, CIM_QUEUE_CONFIG_CTRL_A);
/* value is in 256-byte units */
*base++ = CIMQBASE_G(v) * 256;
*size++ = CIMQSIZE_G(v) * 256;
}
}
/**
* t4_read_cim_ibq - read the contents of a CIM inbound queue
* @adap: the adapter
* @qid: the queue index
* @data: where to store the queue contents
* @n: capacity of @data in 32-bit words
*
* Reads the contents of the selected CIM queue starting at address 0 up
* to the capacity of @data. @n must be a multiple of 4. Returns < 0 on
* error and the number of 32-bit words actually read on success.
*/
int t4_read_cim_ibq(struct adapter *adap, unsigned int qid, u32 *data, size_t n)
{
int i, err, attempts;
unsigned int addr;
const unsigned int nwords = CIM_IBQ_SIZE * 4;
if (qid > 5 || (n & 3))
return -EINVAL;
addr = qid * nwords;
if (n > nwords)
n = nwords;
/* It might take 3-10ms before the IBQ debug read access is allowed.
* Wait for 1 Sec with a delay of 1 usec.
*/
attempts = 1000000;
for (i = 0; i < n; i++, addr++) {
t4_write_reg(adap, CIM_IBQ_DBG_CFG_A, IBQDBGADDR_V(addr) |
IBQDBGEN_F);
err = t4_wait_op_done(adap, CIM_IBQ_DBG_CFG_A, IBQDBGBUSY_F, 0,
attempts, 1);
if (err)
return err;
*data++ = t4_read_reg(adap, CIM_IBQ_DBG_DATA_A);
}
t4_write_reg(adap, CIM_IBQ_DBG_CFG_A, 0);
return i;
}
/**
* t4_read_cim_obq - read the contents of a CIM outbound queue
* @adap: the adapter
* @qid: the queue index
* @data: where to store the queue contents
* @n: capacity of @data in 32-bit words
*
* Reads the contents of the selected CIM queue starting at address 0 up
* to the capacity of @data. @n must be a multiple of 4. Returns < 0 on
* error and the number of 32-bit words actually read on success.
*/
int t4_read_cim_obq(struct adapter *adap, unsigned int qid, u32 *data, size_t n)
{
int i, err;
unsigned int addr, v, nwords;
int cim_num_obq = is_t4(adap->params.chip) ?
CIM_NUM_OBQ : CIM_NUM_OBQ_T5;
if ((qid > (cim_num_obq - 1)) || (n & 3))
return -EINVAL;
t4_write_reg(adap, CIM_QUEUE_CONFIG_REF_A, OBQSELECT_F |
QUENUMSELECT_V(qid));
v = t4_read_reg(adap, CIM_QUEUE_CONFIG_CTRL_A);
addr = CIMQBASE_G(v) * 64; /* muliple of 256 -> muliple of 4 */
nwords = CIMQSIZE_G(v) * 64; /* same */
if (n > nwords)
n = nwords;
for (i = 0; i < n; i++, addr++) {
t4_write_reg(adap, CIM_OBQ_DBG_CFG_A, OBQDBGADDR_V(addr) |
OBQDBGEN_F);
err = t4_wait_op_done(adap, CIM_OBQ_DBG_CFG_A, OBQDBGBUSY_F, 0,
2, 1);
if (err)
return err;
*data++ = t4_read_reg(adap, CIM_OBQ_DBG_DATA_A);
}
t4_write_reg(adap, CIM_OBQ_DBG_CFG_A, 0);
return i;
}
/**
* t4_cim_read - read a block from CIM internal address space
* @adap: the adapter
* @addr: the start address within the CIM address space
* @n: number of words to read
* @valp: where to store the result
*
* Reads a block of 4-byte words from the CIM intenal address space.
*/
int t4_cim_read(struct adapter *adap, unsigned int addr, unsigned int n,
unsigned int *valp)
{
int ret = 0;
if (t4_read_reg(adap, CIM_HOST_ACC_CTRL_A) & HOSTBUSY_F)
return -EBUSY;
for ( ; !ret && n--; addr += 4) {
t4_write_reg(adap, CIM_HOST_ACC_CTRL_A, addr);
ret = t4_wait_op_done(adap, CIM_HOST_ACC_CTRL_A, HOSTBUSY_F,
0, 5, 2);
if (!ret)
*valp++ = t4_read_reg(adap, CIM_HOST_ACC_DATA_A);
}
return ret;
}
/**
* t4_cim_write - write a block into CIM internal address space
* @adap: the adapter
* @addr: the start address within the CIM address space
* @n: number of words to write
* @valp: set of values to write
*
* Writes a block of 4-byte words into the CIM intenal address space.
*/
int t4_cim_write(struct adapter *adap, unsigned int addr, unsigned int n,
const unsigned int *valp)
{
int ret = 0;
if (t4_read_reg(adap, CIM_HOST_ACC_CTRL_A) & HOSTBUSY_F)
return -EBUSY;
for ( ; !ret && n--; addr += 4) {
t4_write_reg(adap, CIM_HOST_ACC_DATA_A, *valp++);
t4_write_reg(adap, CIM_HOST_ACC_CTRL_A, addr | HOSTWRITE_F);
ret = t4_wait_op_done(adap, CIM_HOST_ACC_CTRL_A, HOSTBUSY_F,
0, 5, 2);
}
return ret;
}
static int t4_cim_write1(struct adapter *adap, unsigned int addr,
unsigned int val)
{
return t4_cim_write(adap, addr, 1, &val);
}
/**
* t4_cim_read_la - read CIM LA capture buffer
* @adap: the adapter
* @la_buf: where to store the LA data
* @wrptr: the HW write pointer within the capture buffer
*
* Reads the contents of the CIM LA buffer with the most recent entry at
* the end of the returned data and with the entry at @wrptr first.
* We try to leave the LA in the running state we find it in.
*/
int t4_cim_read_la(struct adapter *adap, u32 *la_buf, unsigned int *wrptr)
{
int i, ret;
unsigned int cfg, val, idx;
ret = t4_cim_read(adap, UP_UP_DBG_LA_CFG_A, 1, &cfg);
if (ret)
return ret;
if (cfg & UPDBGLAEN_F) { /* LA is running, freeze it */
ret = t4_cim_write1(adap, UP_UP_DBG_LA_CFG_A, 0);
if (ret)
return ret;
}
ret = t4_cim_read(adap, UP_UP_DBG_LA_CFG_A, 1, &val);
if (ret)
goto restart;
idx = UPDBGLAWRPTR_G(val);
if (wrptr)
*wrptr = idx;
for (i = 0; i < adap->params.cim_la_size; i++) {
ret = t4_cim_write1(adap, UP_UP_DBG_LA_CFG_A,
UPDBGLARDPTR_V(idx) | UPDBGLARDEN_F);
if (ret)
break;
ret = t4_cim_read(adap, UP_UP_DBG_LA_CFG_A, 1, &val);
if (ret)
break;
if (val & UPDBGLARDEN_F) {
ret = -ETIMEDOUT;
break;
}
ret = t4_cim_read(adap, UP_UP_DBG_LA_DATA_A, 1, &la_buf[i]);
if (ret)
break;
/* Bits 0-3 of UpDbgLaRdPtr can be between 0000 to 1001 to
* identify the 32-bit portion of the full 312-bit data
*/
if (is_t6(adap->params.chip) && (idx & 0xf) >= 9)
idx = (idx & 0xff0) + 0x10;
else
idx++;
/* address can't exceed 0xfff */
idx &= UPDBGLARDPTR_M;
}
restart:
if (cfg & UPDBGLAEN_F) {
int r = t4_cim_write1(adap, UP_UP_DBG_LA_CFG_A,
cfg & ~UPDBGLARDEN_F);
if (!ret)
ret = r;
}
return ret;
}
/**
* t4_tp_read_la - read TP LA capture buffer
* @adap: the adapter
* @la_buf: where to store the LA data
* @wrptr: the HW write pointer within the capture buffer
*
* Reads the contents of the TP LA buffer with the most recent entry at
* the end of the returned data and with the entry at @wrptr first.
* We leave the LA in the running state we find it in.
*/
void t4_tp_read_la(struct adapter *adap, u64 *la_buf, unsigned int *wrptr)
{
bool last_incomplete;
unsigned int i, cfg, val, idx;
cfg = t4_read_reg(adap, TP_DBG_LA_CONFIG_A) & 0xffff;
if (cfg & DBGLAENABLE_F) /* freeze LA */
t4_write_reg(adap, TP_DBG_LA_CONFIG_A,
adap->params.tp.la_mask | (cfg ^ DBGLAENABLE_F));
val = t4_read_reg(adap, TP_DBG_LA_CONFIG_A);
idx = DBGLAWPTR_G(val);
last_incomplete = DBGLAMODE_G(val) >= 2 && (val & DBGLAWHLF_F) == 0;
if (last_incomplete)
idx = (idx + 1) & DBGLARPTR_M;
if (wrptr)
*wrptr = idx;
val &= 0xffff;
val &= ~DBGLARPTR_V(DBGLARPTR_M);
val |= adap->params.tp.la_mask;
for (i = 0; i < TPLA_SIZE; i++) {
t4_write_reg(adap, TP_DBG_LA_CONFIG_A, DBGLARPTR_V(idx) | val);
la_buf[i] = t4_read_reg64(adap, TP_DBG_LA_DATAL_A);
idx = (idx + 1) & DBGLARPTR_M;
}
/* Wipe out last entry if it isn't valid */
if (last_incomplete)
la_buf[TPLA_SIZE - 1] = ~0ULL;
if (cfg & DBGLAENABLE_F) /* restore running state */
t4_write_reg(adap, TP_DBG_LA_CONFIG_A,
cfg | adap->params.tp.la_mask);
}
/* SGE Hung Ingress DMA Warning Threshold time and Warning Repeat Rate (in
* seconds). If we find one of the SGE Ingress DMA State Machines in the same
* state for more than the Warning Threshold then we'll issue a warning about
* a potential hang. We'll repeat the warning as the SGE Ingress DMA Channel
* appears to be hung every Warning Repeat second till the situation clears.
* If the situation clears, we'll note that as well.
*/
#define SGE_IDMA_WARN_THRESH 1
#define SGE_IDMA_WARN_REPEAT 300
/**
* t4_idma_monitor_init - initialize SGE Ingress DMA Monitor
* @adapter: the adapter
* @idma: the adapter IDMA Monitor state
*
* Initialize the state of an SGE Ingress DMA Monitor.
*/
void t4_idma_monitor_init(struct adapter *adapter,
struct sge_idma_monitor_state *idma)
{
/* Initialize the state variables for detecting an SGE Ingress DMA
* hang. The SGE has internal counters which count up on each clock
* tick whenever the SGE finds its Ingress DMA State Engines in the
* same state they were on the previous clock tick. The clock used is
* the Core Clock so we have a limit on the maximum "time" they can
* record; typically a very small number of seconds. For instance,
* with a 600MHz Core Clock, we can only count up to a bit more than
* 7s. So we'll synthesize a larger counter in order to not run the
* risk of having the "timers" overflow and give us the flexibility to
* maintain a Hung SGE State Machine of our own which operates across
* a longer time frame.
*/
idma->idma_1s_thresh = core_ticks_per_usec(adapter) * 1000000; /* 1s */
idma->idma_stalled[0] = 0;
idma->idma_stalled[1] = 0;
}
/**
* t4_idma_monitor - monitor SGE Ingress DMA state
* @adapter: the adapter
* @idma: the adapter IDMA Monitor state
* @hz: number of ticks/second
* @ticks: number of ticks since the last IDMA Monitor call
*/
void t4_idma_monitor(struct adapter *adapter,
struct sge_idma_monitor_state *idma,
int hz, int ticks)
{
int i, idma_same_state_cnt[2];
/* Read the SGE Debug Ingress DMA Same State Count registers. These
* are counters inside the SGE which count up on each clock when the
* SGE finds its Ingress DMA State Engines in the same states they
* were in the previous clock. The counters will peg out at
* 0xffffffff without wrapping around so once they pass the 1s
* threshold they'll stay above that till the IDMA state changes.
*/
t4_write_reg(adapter, SGE_DEBUG_INDEX_A, 13);
idma_same_state_cnt[0] = t4_read_reg(adapter, SGE_DEBUG_DATA_HIGH_A);
idma_same_state_cnt[1] = t4_read_reg(adapter, SGE_DEBUG_DATA_LOW_A);
for (i = 0; i < 2; i++) {
u32 debug0, debug11;
/* If the Ingress DMA Same State Counter ("timer") is less
* than 1s, then we can reset our synthesized Stall Timer and
* continue. If we have previously emitted warnings about a
* potential stalled Ingress Queue, issue a note indicating
* that the Ingress Queue has resumed forward progress.
*/
if (idma_same_state_cnt[i] < idma->idma_1s_thresh) {
if (idma->idma_stalled[i] >= SGE_IDMA_WARN_THRESH * hz)
dev_warn(adapter->pdev_dev, "SGE idma%d, queue %u, "
"resumed after %d seconds\n",
i, idma->idma_qid[i],
idma->idma_stalled[i] / hz);
idma->idma_stalled[i] = 0;
continue;
}
/* Synthesize an SGE Ingress DMA Same State Timer in the Hz
* domain. The first time we get here it'll be because we
* passed the 1s Threshold; each additional time it'll be
* because the RX Timer Callback is being fired on its regular
* schedule.
*
* If the stall is below our Potential Hung Ingress Queue
* Warning Threshold, continue.
*/
if (idma->idma_stalled[i] == 0) {
idma->idma_stalled[i] = hz;
idma->idma_warn[i] = 0;
} else {
idma->idma_stalled[i] += ticks;
idma->idma_warn[i] -= ticks;
}
if (idma->idma_stalled[i] < SGE_IDMA_WARN_THRESH * hz)
continue;
/* We'll issue a warning every SGE_IDMA_WARN_REPEAT seconds.
*/
if (idma->idma_warn[i] > 0)
continue;
idma->idma_warn[i] = SGE_IDMA_WARN_REPEAT * hz;
/* Read and save the SGE IDMA State and Queue ID information.
* We do this every time in case it changes across time ...
* can't be too careful ...
*/
t4_write_reg(adapter, SGE_DEBUG_INDEX_A, 0);
debug0 = t4_read_reg(adapter, SGE_DEBUG_DATA_LOW_A);
idma->idma_state[i] = (debug0 >> (i * 9)) & 0x3f;
t4_write_reg(adapter, SGE_DEBUG_INDEX_A, 11);
debug11 = t4_read_reg(adapter, SGE_DEBUG_DATA_LOW_A);
idma->idma_qid[i] = (debug11 >> (i * 16)) & 0xffff;
dev_warn(adapter->pdev_dev, "SGE idma%u, queue %u, potentially stuck in "
"state %u for %d seconds (debug0=%#x, debug11=%#x)\n",
i, idma->idma_qid[i], idma->idma_state[i],
idma->idma_stalled[i] / hz,
debug0, debug11);
t4_sge_decode_idma_state(adapter, idma->idma_state[i]);
}
}
/**
* t4_load_cfg - download config file
* @adap: the adapter
* @cfg_data: the cfg text file to write
* @size: text file size
*
* Write the supplied config text file to the card's serial flash.
*/
int t4_load_cfg(struct adapter *adap, const u8 *cfg_data, unsigned int size)
{
int ret, i, n, cfg_addr;
unsigned int addr;
unsigned int flash_cfg_start_sec;
unsigned int sf_sec_size = adap->params.sf_size / adap->params.sf_nsec;
cfg_addr = t4_flash_cfg_addr(adap);
if (cfg_addr < 0)
return cfg_addr;
addr = cfg_addr;
flash_cfg_start_sec = addr / SF_SEC_SIZE;
if (size > FLASH_CFG_MAX_SIZE) {
dev_err(adap->pdev_dev, "cfg file too large, max is %u bytes\n",
FLASH_CFG_MAX_SIZE);
return -EFBIG;
}
i = DIV_ROUND_UP(FLASH_CFG_MAX_SIZE, /* # of sectors spanned */
sf_sec_size);
ret = t4_flash_erase_sectors(adap, flash_cfg_start_sec,
flash_cfg_start_sec + i - 1);
/* If size == 0 then we're simply erasing the FLASH sectors associated
* with the on-adapter Firmware Configuration File.
*/
if (ret || size == 0)
goto out;
/* this will write to the flash up to SF_PAGE_SIZE at a time */
for (i = 0; i < size; i += SF_PAGE_SIZE) {
if ((size - i) < SF_PAGE_SIZE)
n = size - i;
else
n = SF_PAGE_SIZE;
ret = t4_write_flash(adap, addr, n, cfg_data);
if (ret)
goto out;
addr += SF_PAGE_SIZE;
cfg_data += SF_PAGE_SIZE;
}
out:
if (ret)
dev_err(adap->pdev_dev, "config file %s failed %d\n",
(size == 0 ? "clear" : "download"), ret);
return ret;
}
/**
* t4_set_vf_mac - Set MAC address for the specified VF
* @adapter: The adapter
* @vf: one of the VFs instantiated by the specified PF
* @naddr: the number of MAC addresses
* @addr: the MAC address(es) to be set to the specified VF
*/
int t4_set_vf_mac_acl(struct adapter *adapter, unsigned int vf,
unsigned int naddr, u8 *addr)
{
struct fw_acl_mac_cmd cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_ACL_MAC_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_WRITE_F |
FW_ACL_MAC_CMD_PFN_V(adapter->pf) |
FW_ACL_MAC_CMD_VFN_V(vf));
/* Note: Do not enable the ACL */
cmd.en_to_len16 = cpu_to_be32((unsigned int)FW_LEN16(cmd));
cmd.nmac = naddr;
switch (adapter->pf) {
case 3:
memcpy(cmd.macaddr3, addr, sizeof(cmd.macaddr3));
break;
case 2:
memcpy(cmd.macaddr2, addr, sizeof(cmd.macaddr2));
break;
case 1:
memcpy(cmd.macaddr1, addr, sizeof(cmd.macaddr1));
break;
case 0:
memcpy(cmd.macaddr0, addr, sizeof(cmd.macaddr0));
break;
}
return t4_wr_mbox(adapter, adapter->mbox, &cmd, sizeof(cmd), &cmd);
}
/**
* t4_read_pace_tbl - read the pace table
* @adap: the adapter
* @pace_vals: holds the returned values
*
* Returns the values of TP's pace table in microseconds.
*/
void t4_read_pace_tbl(struct adapter *adap, unsigned int pace_vals[NTX_SCHED])
{
unsigned int i, v;
for (i = 0; i < NTX_SCHED; i++) {
t4_write_reg(adap, TP_PACE_TABLE_A, 0xffff0000 + i);
v = t4_read_reg(adap, TP_PACE_TABLE_A);
pace_vals[i] = dack_ticks_to_usec(adap, v);
}
}
/**
* t4_get_tx_sched - get the configuration of a Tx HW traffic scheduler
* @adap: the adapter
* @sched: the scheduler index
* @kbps: the byte rate in Kbps
* @ipg: the interpacket delay in tenths of nanoseconds
* @sleep_ok: if true we may sleep while awaiting command completion
*
* Return the current configuration of a HW Tx scheduler.
*/
void t4_get_tx_sched(struct adapter *adap, unsigned int sched,
unsigned int *kbps, unsigned int *ipg, bool sleep_ok)
{
unsigned int v, addr, bpt, cpt;
if (kbps) {
addr = TP_TX_MOD_Q1_Q0_RATE_LIMIT_A - sched / 2;
t4_tp_tm_pio_read(adap, &v, 1, addr, sleep_ok);
if (sched & 1)
v >>= 16;
bpt = (v >> 8) & 0xff;
cpt = v & 0xff;
if (!cpt) {
*kbps = 0; /* scheduler disabled */
} else {
v = (adap->params.vpd.cclk * 1000) / cpt; /* ticks/s */
*kbps = (v * bpt) / 125;
}
}
if (ipg) {
addr = TP_TX_MOD_Q1_Q0_TIMER_SEPARATOR_A - sched / 2;
t4_tp_tm_pio_read(adap, &v, 1, addr, sleep_ok);
if (sched & 1)
v >>= 16;
v &= 0xffff;
*ipg = (10000 * v) / core_ticks_per_usec(adap);
}
}
/* t4_sge_ctxt_rd - read an SGE context through FW
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @cid: the context id
* @ctype: the context type
* @data: where to store the context data
*
* Issues a FW command through the given mailbox to read an SGE context.
*/
int t4_sge_ctxt_rd(struct adapter *adap, unsigned int mbox, unsigned int cid,
enum ctxt_type ctype, u32 *data)
{
struct fw_ldst_cmd c;
int ret;
if (ctype == CTXT_FLM)
ret = FW_LDST_ADDRSPC_SGE_FLMC;
else
ret = FW_LDST_ADDRSPC_SGE_CONMC;
memset(&c, 0, sizeof(c));
c.op_to_addrspace = cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F | FW_CMD_READ_F |
FW_LDST_CMD_ADDRSPACE_V(ret));
c.cycles_to_len16 = cpu_to_be32(FW_LEN16(c));
c.u.idctxt.physid = cpu_to_be32(cid);
ret = t4_wr_mbox(adap, mbox, &c, sizeof(c), &c);
if (ret == 0) {
data[0] = be32_to_cpu(c.u.idctxt.ctxt_data0);
data[1] = be32_to_cpu(c.u.idctxt.ctxt_data1);
data[2] = be32_to_cpu(c.u.idctxt.ctxt_data2);
data[3] = be32_to_cpu(c.u.idctxt.ctxt_data3);
data[4] = be32_to_cpu(c.u.idctxt.ctxt_data4);
data[5] = be32_to_cpu(c.u.idctxt.ctxt_data5);
}
return ret;
}
/**
* t4_sge_ctxt_rd_bd - read an SGE context bypassing FW
* @adap: the adapter
* @cid: the context id
* @ctype: the context type
* @data: where to store the context data
*
* Reads an SGE context directly, bypassing FW. This is only for
* debugging when FW is unavailable.
*/
int t4_sge_ctxt_rd_bd(struct adapter *adap, unsigned int cid,
enum ctxt_type ctype, u32 *data)
{
int i, ret;
t4_write_reg(adap, SGE_CTXT_CMD_A, CTXTQID_V(cid) | CTXTTYPE_V(ctype));
ret = t4_wait_op_done(adap, SGE_CTXT_CMD_A, BUSY_F, 0, 3, 1);
if (!ret)
for (i = SGE_CTXT_DATA0_A; i <= SGE_CTXT_DATA5_A; i += 4)
*data++ = t4_read_reg(adap, i);
return ret;
}
int t4_sched_params(struct adapter *adapter, u8 type, u8 level, u8 mode,
u8 rateunit, u8 ratemode, u8 channel, u8 class,
u32 minrate, u32 maxrate, u16 weight, u16 pktsize,
u16 burstsize)
{
struct fw_sched_cmd cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.op_to_write = cpu_to_be32(FW_CMD_OP_V(FW_SCHED_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_WRITE_F);
cmd.retval_len16 = cpu_to_be32(FW_LEN16(cmd));
cmd.u.params.sc = FW_SCHED_SC_PARAMS;
cmd.u.params.type = type;
cmd.u.params.level = level;
cmd.u.params.mode = mode;
cmd.u.params.ch = channel;
cmd.u.params.cl = class;
cmd.u.params.unit = rateunit;
cmd.u.params.rate = ratemode;
cmd.u.params.min = cpu_to_be32(minrate);
cmd.u.params.max = cpu_to_be32(maxrate);
cmd.u.params.weight = cpu_to_be16(weight);
cmd.u.params.pktsize = cpu_to_be16(pktsize);
cmd.u.params.burstsize = cpu_to_be16(burstsize);
return t4_wr_mbox_meat(adapter, adapter->mbox, &cmd, sizeof(cmd),
NULL, 1);
}
/**
* t4_i2c_rd - read I2C data from adapter
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @port: Port number if per-port device; <0 if not
* @devid: per-port device ID or absolute device ID
* @offset: byte offset into device I2C space
* @len: byte length of I2C space data
* @buf: buffer in which to return I2C data
*
* Reads the I2C data from the indicated device and location.
*/
int t4_i2c_rd(struct adapter *adap, unsigned int mbox, int port,
unsigned int devid, unsigned int offset,
unsigned int len, u8 *buf)
{
struct fw_ldst_cmd ldst_cmd, ldst_rpl;
unsigned int i2c_max = sizeof(ldst_cmd.u.i2c.data);
int ret = 0;
if (len > I2C_PAGE_SIZE)
return -EINVAL;
/* Dont allow reads that spans multiple pages */
if (offset < I2C_PAGE_SIZE && offset + len > I2C_PAGE_SIZE)
return -EINVAL;
memset(&ldst_cmd, 0, sizeof(ldst_cmd));
ldst_cmd.op_to_addrspace =
cpu_to_be32(FW_CMD_OP_V(FW_LDST_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_READ_F |
FW_LDST_CMD_ADDRSPACE_V(FW_LDST_ADDRSPC_I2C));
ldst_cmd.cycles_to_len16 = cpu_to_be32(FW_LEN16(ldst_cmd));
ldst_cmd.u.i2c.pid = (port < 0 ? 0xff : port);
ldst_cmd.u.i2c.did = devid;
while (len > 0) {
unsigned int i2c_len = (len < i2c_max) ? len : i2c_max;
ldst_cmd.u.i2c.boffset = offset;
ldst_cmd.u.i2c.blen = i2c_len;
ret = t4_wr_mbox(adap, mbox, &ldst_cmd, sizeof(ldst_cmd),
&ldst_rpl);
if (ret)
break;
memcpy(buf, ldst_rpl.u.i2c.data, i2c_len);
offset += i2c_len;
buf += i2c_len;
len -= i2c_len;
}
return ret;
}
/**
* t4_set_vlan_acl - Set a VLAN id for the specified VF
* @adap: the adapter
* @mbox: mailbox to use for the FW command
* @vf: one of the VFs instantiated by the specified PF
* @vlan: The vlanid to be set
*/
int t4_set_vlan_acl(struct adapter *adap, unsigned int mbox, unsigned int vf,
u16 vlan)
{
struct fw_acl_vlan_cmd vlan_cmd;
unsigned int enable;
enable = (vlan ? FW_ACL_VLAN_CMD_EN_F : 0);
memset(&vlan_cmd, 0, sizeof(vlan_cmd));
vlan_cmd.op_to_vfn = cpu_to_be32(FW_CMD_OP_V(FW_ACL_VLAN_CMD) |
FW_CMD_REQUEST_F |
FW_CMD_WRITE_F |
FW_CMD_EXEC_F |
FW_ACL_VLAN_CMD_PFN_V(adap->pf) |
FW_ACL_VLAN_CMD_VFN_V(vf));
vlan_cmd.en_to_len16 = cpu_to_be32(enable | FW_LEN16(vlan_cmd));
/* Drop all packets that donot match vlan id */
vlan_cmd.dropnovlan_fm = (enable
? (FW_ACL_VLAN_CMD_DROPNOVLAN_F |
FW_ACL_VLAN_CMD_FM_F) : 0);
if (enable != 0) {
vlan_cmd.nvlan = 1;
vlan_cmd.vlanid[0] = cpu_to_be16(vlan);
}
return t4_wr_mbox(adap, adap->mbox, &vlan_cmd, sizeof(vlan_cmd), NULL);
}
|
/****************************************************************************
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "renderer/CCPrimitive.h"
#include "renderer/CCVertexIndexBuffer.h"
NS_CC_BEGIN
Primitive* Primitive::create(VertexData* verts, IndexBuffer* indices, int type)
{
auto result = new (std::nothrow) Primitive();
if( result && result->init(verts, indices, type))
{
result->autorelease();
return result;
}
CC_SAFE_DELETE(result);
return nullptr;
}
const VertexData* Primitive::getVertexData() const
{
return _verts;
}
const IndexBuffer* Primitive::getIndexData() const
{
return _indices;
}
Primitive::Primitive()
: _verts(nullptr)
, _indices(nullptr)
, _type(GL_POINTS)
, _start(0)
, _count(0)
{
}
Primitive::~Primitive()
{
CC_SAFE_RELEASE_NULL(_verts);
CC_SAFE_RELEASE_NULL(_indices);
}
bool Primitive::init(VertexData* verts, IndexBuffer* indices, int type)
{
if( nullptr == verts ) return false;
if(verts != _verts)
{
CC_SAFE_RELEASE(_verts);
CC_SAFE_RETAIN(verts);
_verts = verts;
}
if(indices != _indices)
{
CC_SAFE_RETAIN(indices);
CC_SAFE_RELEASE(_indices);
_indices = indices;
}
_type = type;
return true;
}
void Primitive::draw()
{
if(_verts)
{
_verts->use();
if(_indices!= nullptr)
{
GLenum type = (_indices->getType() == IndexBuffer::IndexType::INDEX_TYPE_SHORT_16) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indices->getVBO());
size_t offset = _start * _indices->getSizePerIndex();
glDrawElements((GLenum)_type, _count, type, (GLvoid*)offset);
}
else
{
glDrawArrays((GLenum)_type, _start, _count);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
void Primitive::setStart(int start)
{
_start = start;
}
void Primitive::setCount(int count)
{
_count = count;
}
NS_CC_END
|
// ImagePixel.cpp: implementation of the CImagePixel class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ImagePixel.h"
#include "Image.h"
CImagePixel::CImagePixel()
{
m_pInput=NULL;
}
CImagePixel::CImagePixel(CImage* pInput)
{
m_pInput=pInput;
Init(pInput);
}
CImagePixel::~CImagePixel()
{
}
void CImagePixel::Init(CImage* pInput)
{
m_pInput=pInput;
m_pCPP.resize(m_pInput->GetHeight());
for(int i=0; i<m_pInput->GetHeight(); i++)
{
m_pCPP[i]=m_pInput->GetPixel(0, i);
}
}
CPixelRGB8 CImagePixel::GetPixel(float x, float y, int& count)
{
///< bilinear filtering getpixel
CPixelRGB8 color;
int x1,y1,x2,y2;
x1=(int)x;
x2=x1+1;
y1=(int)y;
y2=y1+1;
count=1;
// 4°³ Çȼ¿Áß Çϳª¶óµµ ¹Û¿¡ ÀÖ´Â °æ¿ì
if(x1<0 || x2>=m_pInput->GetWidth() || y1<0 || y2>=m_pInput->GetHeight())
{
count=0;
color=CPixelRGB8 (0,0,0);
}
// ¸ðµÎ ¾È¿¡ Àִ°æ¿ì
else
{
CPixelRGB8 c1,c2,c3,c4;
float errx=x-x1;
float erry=y-y1;
float ex1=(1.f-errx)*(1.f-errx);
float ex2=errx*errx;
float ey1=(1.f-erry)*(1.f-erry);
float ey2=erry*erry;
// p1: x1,y1
// p2: x1,y2
// p3: x2,y1
// p4: y2,y2
float w1,w2,w3,w4;
w1=ex1+ey1;
w2=ex1+ey2;
w3=ex2+ey1;
w4=ex2+ey2;
float sum=w1+w2+w3+w4;
w1/=sum;
w2/=sum;
w3/=sum;
w4/=sum;
count=4;
c1=GetPixel(x1,y1);
c2=GetPixel(x1,y2);
c3=GetPixel(x2,y1);
c4=GetPixel(x2,y2);
color=CPixelRGB8 (int((c1.R)*w1+(c2.R)*w2+(c3.R)*w3+(c4.R)*w4),
int((c1.G)*w1+(c2.G)*w2+(c3.G)*w3+(c4.G)*w4),
int((c1.B)*w1+(c2.B)*w2+(c3.B)*w3+(c4.B)*w4));
}
return color;
}
void CImagePixel::SetPixel(float fx, float fy, CPixelRGB8 color)
{
int width=m_pInput->GetWidth();
int height=m_pInput->GetHeight();
int x,y;
x=int(fx*width);
y=int(fy*height);
if(x<0) x=0;
if(y<0) y=0;
if(x>=width) x=width-1;
if(y>=height) y=height-1;
SetPixel(x,y,color);
}
void CImagePixel::DrawHorizLine(int x, int y, int width, CPixelRGB8 color)
{
{
std::vector<CPixelRGB8 *> & inputptr=m_pCPP;
if(x<0) return;
if(x>=m_pInput->GetWidth()) return;
if(y<0) return;
if(y>=m_pInput->GetHeight()) return;
if (x+width>=m_pInput->GetWidth())
width=m_pInput->GetWidth()-x-1;
for(int i=x; i<x+width; i++)
{
inputptr[y][i]=color;
}
}
}
void CImagePixel::DrawVertLine(int x, int y, int height, CPixelRGB8 color,bool bDotted)
{
int step=1;
if(bDotted) step=3;
std::vector<CPixelRGB8 *> & inputptr=(m_pCPP);
if(x<0) return;
if(x>=m_pInput->GetWidth()) return;
if(y<0) return;
if(y>=m_pInput->GetHeight()) return;
if (y+height>=m_pInput->GetHeight())
height=m_pInput->GetHeight()-y-1;
for(int j=y; j<y+height; j+=step)
{
inputptr[j][x]=color;
}
}
void CImagePixel::DrawLineBox(const TRect& rect, CPixelRGB8 color)
{
DrawHorizLine(rect.left, rect.top, rect.Width(), color);
DrawHorizLine(rect.left, rect.bottom-1, rect.Width(), color);
DrawVertLine(rect.left, rect.top, rect.Height(), color);
DrawVertLine(rect.right-1, rect.top, rect.Height(), color);
}
void CImagePixel::DrawBox(const TRect& _rect, CPixelRGB8 sColor)
{
TRect rect=_rect;
if(rect.left> rect.right) std::swap(rect.left, rect.right);
if(rect.top> rect.bottom) std::swap(rect.top, rect.bottom);
if(rect.left<0) rect.left=0;
if(rect.top<0) rect.top=0;
if(rect.bottom>Height())rect.bottom=Height();
if(rect.right>Width())rect.right=Width();
{
std::vector<CPixelRGB8 *> & inputptr=m_pCPP;
/*
// easy to read version
for(int j=rect.top; j<rect.bottom; j++)
{
CPixelRGB8* ptr=inputptr[j];
for(int i=rect.left; i<rect.right; i++)
{
memcpy(&ptr[i],&sColor,sizeof(CPixelRGB8));
}
}
*/
// fast version
CPixelRGB8* aBuffer;
int width=rect.right-rect.left;
if(width>0)
{
aBuffer=new CPixelRGB8[width];
for(int i=0; i<width; i++)
aBuffer[i]=sColor;
for(int j=rect.top; j<rect.bottom; j++)
{
CPixelRGB8* ptr=inputptr[j];
memcpy(&ptr[rect.left],aBuffer, sizeof(CPixelRGB8)*(width));
}
delete[] aBuffer;
}
}
}
void CImagePixel::Clear(CPixelRGB8 color)
{
int width=m_pInput->GetWidth();
int height=m_pInput->GetHeight();
DrawBox(TRect(0,0, width, height), color);
}
void CImagePixel::DrawPattern(int x, int y, const CImagePixel& patternPixel, bool bUseColorKey, CPixelRGB8 sColorkey, bool bOverideColor, CPixelRGB8 overrideColor)
{
int imageWidth=m_pInput->GetWidth();
int imageHeight=m_pInput->GetHeight();
int patternWidth=patternPixel.m_pInput->GetWidth();
int patternHeight=patternPixel.m_pInput->GetHeight();
int imagex, imagey;
if(bUseColorKey)
{
if(bOverideColor)
{
float ovR=float((overrideColor.R))/255.f;
float ovG=float((overrideColor.G))/255.f;
float ovB=float((overrideColor.B))/255.f;
for(int j=0; j<patternHeight; j++)
for(int i=0; i<patternWidth; i++)
{
imagex=x+i; imagey=y+j;
if(imagex>=0 && imagex<imageWidth && imagey>=0 && imagey <imageHeight)
{
if(memcmp(&patternPixel.GetPixel(i,j),&sColorkey, sizeof(CPixelRGB8))!=0)
{
// SetPixel( imagex, imagey, overrideColor);
CPixelRGB8& c=Pixel(imagex, imagey);
CPixelRGB8& cc=patternPixel.Pixel(i,j);
c.R=cc.R*ovR;
c.G=cc.G*ovG;
c.B=cc.B*ovB;
}
}
}
}
else
{
for(int j=0; j<patternHeight; j++)
for(int i=0; i<patternWidth; i++)
{
imagex=x+i; imagey=y+j;
if(imagex>=0 && imagex<imageWidth && imagey>=0 && imagey <imageHeight)
{
if(memcmp(&patternPixel.Pixel(i,j),&sColorkey, sizeof(CPixelRGB8))!=0)
GetPixel(imagex,imagey)=patternPixel.GetPixel(i,j);
}
}
}
}
else
{
ASSERT(!bOverideColor);
for(int j=0; j<patternHeight; j++)
{
CPixelRGB8* target=&GetPixel(x,y+j);
CPixelRGB8* source=&patternPixel.Pixel(0,j);
memcpy(target,source, sizeof(CPixelRGB8)*patternWidth);
}
}
}
void CImagePixel::DrawPattern(int x, int y, CImage* pPattern, bool bUseColorkey, CPixelRGB8 colorkey, bool bOverideColor, CPixelRGB8 overrideColor)
{
CImagePixel patternPixel(pPattern);
DrawPattern(x,y,patternPixel,bUseColorkey,colorkey,bOverideColor,overrideColor);
}
void CImagePixel::DrawLine(int x1, int y1, int x2, int y2, CPixelRGB8 color) //!< inputptr, inputptr2Áß Çϳª´Â NULL·Î ÁÙ°Í.
{
int dx,dy,x,y,x_end,p,const1,const2,y_end;
int delta;
dx=abs(x1-x2);
dy=abs(y1-y2);
if (((y1-y2)>0 && (x1-x2)>0 ) || (y1-y2)<0 && (x1-x2)<0)
{
delta=1; //±â¿ï±â >0
}
else
{
delta=-1; //±â¿ï±â <0
}
if(dx>dy) //±â¿ï±â 0 < |m| <=1
{
p=2*dy-dx;
const1=2*dy;
const2=2*(dy-dx);
if(x1>x2)
{
x=x2;y=y2;
x_end=x1;
}
else
{
x=x1;y=y1;
x_end=x2;
}
SetPixel( x,y, color);
while(x<x_end)
{
x=x+1;
if(p<0)
{
p=p+const1;
}
else
{
y=y+delta;
p=p+const2;
}
SetPixel( x,y, color);
} //±â¿ï±â |m| > 1
}
else
{
p=2*dx-dy;
const1=2*dx;
const2=2*(dx-dy);
if(y1>y2)
{
y=y2;x=x2;
y_end=y1;
}
else
{
y=y1;x=x1;
y_end=y2;
}
SetPixel( x,y, color);
while(y<y_end)
{
y=y+1;
if(p<0)
{
p=p+const1;
}
else
{
x=x+delta;
p=p+const2;
}
SetPixel( x,y, color);
}
}
}
void CImagePixel::DrawSubPattern(int x, int y, const CImagePixel& patternPixel, const TRect& patternRect, bool bUseColorKey, CPixelRGB8 sColorkey)
{
int imageWidth=m_pInput->GetWidth();
int imageHeight=m_pInput->GetHeight();
int patternWidth=patternPixel.m_pInput->GetWidth();
int patternHeight=patternPixel.m_pInput->GetHeight();
ASSERT(patternRect.right<=patternWidth);
ASSERT(patternRect.top<=patternHeight);
int imagex, imagey;
if(bUseColorKey)
{
for(int j=patternRect.top; j<patternRect.bottom; j++)
for(int i=patternRect.left; i<patternRect.right; i++)
{
imagex=x+i-patternRect.left; imagey=y+j-patternRect.top;
if(imagex>=0 && imagex<imageWidth && imagey>=0 && imagey <imageHeight)
{
if(memcmp(&patternPixel.Pixel(i,j),&sColorkey, sizeof(CPixelRGB8))!=0)
Pixel(imagex,imagey)=patternPixel.Pixel(i,j);
}
}
}
else
{
TRect rect=patternRect;
if(x<0)
{
rect.left-=x;
x-=x;
}
if(x+rect.Width()>imageWidth)
{
int delta=x+rect.Width()-imageWidth;
rect.right-=delta;
}
if(rect.Width()>0)
{
for(int j=rect.top; j<rect.bottom; j++)
{
imagey=y+j-rect.top;
if(imagey>=0 && imagey <imageHeight)
{
CPixelRGB8* target=&Pixel(x,imagey);
CPixelRGB8* source=&patternPixel.Pixel(rect.left,j);
memcpy(target,source, sizeof(CPixelRGB8)*rect.Width());
}
}
}
}
}
void CImagePixel::DrawText(int x, int y, const char* str, bool bUserColorKey, CPixelRGB8 colorkey)
{
static CImage* pText=NULL;
if(!pText)
{
pText=new CImage();
pText->Load("resource/default/ascii.bmp");
}
CImage& cText=*pText;
CImagePixel patternPixel(&cText);
#define FONT_HEIGHT 16
#define FONT_WIDTH 8
int len=strlen(str);
for(int i=0; i<len; i++)
{
char c=str[i];
int code=(c-' ');
ASSERT(code>=0 && code<32*3);
int left=code%32*FONT_WIDTH ;
int top=code/32*FONT_HEIGHT;
DrawSubPattern(x+i*FONT_WIDTH , y, patternPixel, TRect(left,top,left+FONT_WIDTH , top+FONT_HEIGHT), bUserColorKey, colorkey);
}
}
|
<?php
/**
* @file
* Contains \Drupal\filter\Tests\FilterAPITest.
*/
namespace Drupal\filter\Tests;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\Core\TypedData\OptionsProviderInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\filter\Plugin\DataType\FilterFormat;
use Drupal\filter\Plugin\FilterInterface;
use Drupal\system\Tests\Entity\EntityUnitTestBase;
use Symfony\Component\Validator\ConstraintViolationListInterface;
/**
* Tests the behavior of the API of the Filter module.
*
* @group filter
*/
class FilterAPITest extends EntityUnitTestBase {
public static $modules = array('system', 'filter', 'filter_test', 'user');
protected function setUp() {
parent::setUp();
$this->installConfig(array('system', 'filter'));
}
/**
* Tests that the filter order is respected.
*/
function testCheckMarkupFilterOrder() {
// Create crazy HTML format.
$crazy_format = entity_create('filter_format', array(
'format' => 'crazy',
'name' => 'Crazy',
'weight' => 1,
'filters' => array(
'filter_html_escape' => array(
'weight' => 10,
'status' => 1,
),
'filter_html' => array(
'weight' => -10,
'status' => 1,
'settings' => array(
'allowed_html' => '<p>',
),
),
)
));
$crazy_format->save();
$text = "<p>Llamas are <not> awesome!</p>";
$expected_filtered_text = "<p>Llamas are awesome!</p>";
$this->assertIdentical(check_markup($text, 'crazy'), $expected_filtered_text, 'Filters applied in correct order.');
}
/**
* Tests the ability to apply only a subset of filters.
*/
function testCheckMarkupFilterSubset() {
$text = "Text with <marquee>evil content and</marquee> a URL: http://drupal.org!";
$expected_filtered_text = "Text with evil content and a URL: <a href=\"http://drupal.org\">http://drupal.org</a>!";
$expected_filter_text_without_html_generators = "Text with evil content and a URL: http://drupal.org!";
$actual_filtered_text = check_markup($text, 'filtered_html', '', array());
$this->verbose("Actual:<pre>$actual_filtered_text</pre>Expected:<pre>$expected_filtered_text</pre>");
$this->assertIdentical(
$actual_filtered_text,
$expected_filtered_text,
'Expected filter result.'
);
$actual_filtered_text_without_html_generators = check_markup($text, 'filtered_html', '', array(FilterInterface::TYPE_MARKUP_LANGUAGE));
$this->verbose("Actual:<pre>$actual_filtered_text_without_html_generators</pre>Expected:<pre>$expected_filter_text_without_html_generators</pre>");
$this->assertIdentical(
$actual_filtered_text_without_html_generators,
$expected_filter_text_without_html_generators,
'Expected filter result when skipping FilterInterface::TYPE_MARKUP_LANGUAGE filters.'
);
// Related to @see FilterSecurityTest.php/testSkipSecurityFilters(), but
// this check focuses on the ability to filter multiple filter types at once.
// Drupal core only ships with these two types of filters, so this is the
// most extensive test possible.
$actual_filtered_text_without_html_generators = check_markup($text, 'filtered_html', '', array(FilterInterface::TYPE_HTML_RESTRICTOR, FilterInterface::TYPE_MARKUP_LANGUAGE));
$this->verbose("Actual:<pre>$actual_filtered_text_without_html_generators</pre>Expected:<pre>$expected_filter_text_without_html_generators</pre>");
$this->assertIdentical(
$actual_filtered_text_without_html_generators,
$expected_filter_text_without_html_generators,
'Expected filter result when skipping FilterInterface::TYPE_MARKUP_LANGUAGE filters, even when trying to disable filters of the FilterInterface::TYPE_HTML_RESTRICTOR type.'
);
}
/**
* Tests the following functions for a variety of formats:
* - \Drupal\filter\Entity\FilterFormatInterface::getHtmlRestrictions()
* - \Drupal\filter\Entity\FilterFormatInterface::getFilterTypes()
*/
function testFilterFormatAPI() {
// Test on filtered_html.
$filtered_html_format = entity_load('filter_format', 'filtered_html');
$this->assertIdentical(
$filtered_html_format->getHtmlRestrictions(),
array('allowed' => array('p' => TRUE, 'br' => TRUE, 'strong' => TRUE, 'a' => TRUE, '*' => array('style' => FALSE, 'on*' => FALSE))),
'FilterFormatInterface::getHtmlRestrictions() works as expected for the filtered_html format.'
);
$this->assertIdentical(
$filtered_html_format->getFilterTypes(),
array(FilterInterface::TYPE_HTML_RESTRICTOR, FilterInterface::TYPE_MARKUP_LANGUAGE),
'FilterFormatInterface::getFilterTypes() works as expected for the filtered_html format.'
);
// Test on full_html.
$full_html_format = entity_load('filter_format', 'full_html');
$this->assertIdentical(
$full_html_format->getHtmlRestrictions(),
FALSE, // Every tag is allowed.
'FilterFormatInterface::getHtmlRestrictions() works as expected for the full_html format.'
);
$this->assertIdentical(
$full_html_format->getFilterTypes(),
array(),
'FilterFormatInterface::getFilterTypes() works as expected for the full_html format.'
);
// Test on stupid_filtered_html, where nothing is allowed.
$stupid_filtered_html_format = entity_create('filter_format', array(
'format' => 'stupid_filtered_html',
'name' => 'Stupid Filtered HTML',
'filters' => array(
'filter_html' => array(
'status' => 1,
'settings' => array(
'allowed_html' => '', // Nothing is allowed.
),
),
),
));
$stupid_filtered_html_format->save();
$this->assertIdentical(
$stupid_filtered_html_format->getHtmlRestrictions(),
array('allowed' => array()), // No tag is allowed.
'FilterFormatInterface::getHtmlRestrictions() works as expected for the stupid_filtered_html format.'
);
$this->assertIdentical(
$stupid_filtered_html_format->getFilterTypes(),
array(FilterInterface::TYPE_HTML_RESTRICTOR),
'FilterFormatInterface::getFilterTypes() works as expected for the stupid_filtered_html format.'
);
// Test on very_restricted_html, where there's two different filters of the
// FilterInterface::TYPE_HTML_RESTRICTOR type, each restricting in different ways.
$very_restricted_html_format = entity_create('filter_format', array(
'format' => 'very_restricted_html',
'name' => 'Very Restricted HTML',
'filters' => array(
'filter_html' => array(
'status' => 1,
'settings' => array(
'allowed_html' => '<p> <br> <a> <strong>',
),
),
'filter_test_restrict_tags_and_attributes' => array(
'status' => 1,
'settings' => array(
'restrictions' => array(
'allowed' => array(
'p' => TRUE,
'br' => FALSE,
'a' => array('href' => TRUE),
'em' => TRUE,
),
)
),
),
)
));
$very_restricted_html_format->save();
$this->assertIdentical(
$very_restricted_html_format->getHtmlRestrictions(),
array('allowed' => array('p' => TRUE, 'br' => FALSE, 'a' => array('href' => TRUE), '*' => array('style' => FALSE, 'on*' => FALSE))),
'FilterFormatInterface::getHtmlRestrictions() works as expected for the very_restricted_html format.'
);
$this->assertIdentical(
$very_restricted_html_format->getFilterTypes(),
array(FilterInterface::TYPE_HTML_RESTRICTOR),
'FilterFormatInterface::getFilterTypes() works as expected for the very_restricted_html format.'
);
}
/**
* Tests the 'processed_text' element.
*
* check_markup() is a wrapper for the 'processed_text' element, for use in
* simple scenarios; the 'processed_text' element has more advanced features:
* it lets filters attach assets, associate cache tags and define
* #post_render_cache callbacks.
* This test focuses solely on those advanced features.
*/
function testProcessedTextElement() {
entity_create('filter_format', array(
'format' => 'element_test',
'name' => 'processed_text element test format',
'filters' => array(
'filter_test_assets' => array(
'weight' => -1,
'status' => TRUE,
),
'filter_test_cache_tags' => array(
'weight' => 0,
'status' => TRUE,
),
'filter_test_post_render_cache' => array(
'weight' => 1,
'status' => TRUE,
),
// Run the HTML corrector filter last, because it has the potential to
// break the render cache placeholders added by the
// filter_test_post_render_cache filter.
'filter_htmlcorrector' => array(
'weight' => 10,
'status' => TRUE,
),
),
))->save();
$build = array(
'#type' => 'processed_text',
'#text' => '<p>Hello, world!</p>',
'#format' => 'element_test',
);
drupal_render($build);
// Verify the assets, cache tags and #post_render_cache callbacks.
$expected_assets = array(
// The assets attached by the filter_test_assets filter.
'library' => array(
'filter/caption',
),
);
$this->assertEqual($expected_assets, $build['#attached'], 'Expected assets present');
$expected_cache_tags = array(
// The cache tag set by the processed_text element itself.
'filter_format:element_test',
// The cache tags set by the filter_test_cache_tags filter.
'foo:bar',
'foo:baz',
);
$this->assertEqual($expected_cache_tags, $build['#cache']['tags'], 'Expected cache tags present.');
$expected_markup = '<p>Hello, world!</p><p>This is a dynamic llama.</p>';
$this->assertEqual($expected_markup, $build['#markup'], 'Expected #post_render_cache callback has been applied.');
}
/**
* Tests the function of the typed data type.
*/
function testTypedDataAPI() {
$definition = DataDefinition::create('filter_format');
$data = \Drupal::typedDataManager()->create($definition);
$this->assertTrue($data instanceof OptionsProviderInterface, 'Typed data object implements \Drupal\Core\TypedData\OptionsProviderInterface');
$filtered_html_user = $this->createUser(array('uid' => 2), array(
entity_load('filter_format', 'filtered_html')->getPermissionName(),
));
// Test with anonymous user.
$user = new AnonymousUserSession();
\Drupal::currentUser()->setAccount($user);
$expected_available_options = array(
'filtered_html' => 'Filtered HTML',
'full_html' => 'Full HTML',
'filter_test' => 'Test format',
'plain_text' => 'Plain text',
);
$available_values = $data->getPossibleValues();
$this->assertEqual($available_values, array_keys($expected_available_options));
$available_options = $data->getPossibleOptions();
$this->assertEqual($available_options, $expected_available_options);
$allowed_values = $data->getSettableValues($user);
$this->assertEqual($allowed_values, array('plain_text'));
$allowed_options = $data->getSettableOptions($user);
$this->assertEqual($allowed_options, array('plain_text' => 'Plain text'));
$data->setValue('foo');
$violations = $data->validate();
$this->assertFilterFormatViolation($violations, 'foo');
// Make sure the information provided by a violation is correct.
$violation = $violations[0];
$this->assertEqual($violation->getRoot(), $data, 'Violation root is filter format.');
$this->assertEqual($violation->getPropertyPath(), '', 'Violation property path is correct.');
$this->assertEqual($violation->getInvalidValue(), 'foo', 'Violation contains invalid value.');
$data->setValue('plain_text');
$violations = $data->validate();
$this->assertEqual(count($violations), 0, "No validation violation for format 'plain_text' found");
// Anonymous doesn't have access to the 'filtered_html' format.
$data->setValue('filtered_html');
$violations = $data->validate();
$this->assertFilterFormatViolation($violations, 'filtered_html');
// Set user with access to 'filtered_html' format.
\Drupal::currentUser()->setAccount($filtered_html_user);
$violations = $data->validate();
$this->assertEqual(count($violations), 0, "No validation violation for accessible format 'filtered_html' found.");
$allowed_values = $data->getSettableValues($filtered_html_user);
$this->assertEqual($allowed_values, array('filtered_html', 'plain_text'));
$allowed_options = $data->getSettableOptions($filtered_html_user);
$expected_allowed_options = array(
'filtered_html' => 'Filtered HTML',
'plain_text' => 'Plain text',
);
$this->assertEqual($allowed_options, $expected_allowed_options);
}
/**
* Tests that FilterFormat::preSave() only saves customized plugins.
*/
public function testFilterFormatPreSave() {
/** @var \Drupal\filter\FilterFormatInterface $crazy_format */
$crazy_format = entity_create('filter_format', array(
'format' => 'crazy',
'name' => 'Crazy',
'weight' => 1,
'filters' => array(
'filter_html_escape' => array(
'weight' => 10,
'status' => 1,
),
'filter_html' => array(
'weight' => -10,
'status' => 1,
'settings' => array(
'allowed_html' => '<p>',
),
),
)
));
$crazy_format->save();
// Use config to directly load the configuration and check that only enabled
// or customized plugins are saved to configuration.
$filters = \Drupal::config('filter.format.crazy')->get('filters');
$this->assertEqual(array('filter_html_escape', 'filter_html'), array_keys($filters));
// Disable a plugin to ensure that disabled plugins with custom settings are
// stored in configuration.
$crazy_format->setFilterConfig('filter_html_escape', array('status' => FALSE));
$crazy_format->save();
$filters = \Drupal::config('filter.format.crazy')->get('filters');
$this->assertEqual(array('filter_html_escape', 'filter_html'), array_keys($filters));
// Set the settings as per default to ensure that disable plugins in this
// state are not stored in configuration.
$crazy_format->setFilterConfig('filter_html_escape', array('weight' => -10));
$crazy_format->save();
$filters = \Drupal::config('filter.format.crazy')->get('filters');
$this->assertEqual(array('filter_html'), array_keys($filters));
}
/**
* Checks if an expected violation exists in the given violations.
*
* @param \Symfony\Component\Validator\ConstraintViolationListInterface $violations
* The violations to assert.
* @param mixed $invalid_value
* The expected invalid value.
*/
public function assertFilterFormatViolation(ConstraintViolationListInterface $violations, $invalid_value) {
$filter_format_violation_found = FALSE;
foreach ($violations as $violation) {
if ($violation->getRoot() instanceof FilterFormat && $violation->getInvalidValue() === $invalid_value) {
$filter_format_violation_found = TRUE;
break;
}
}
$this->assertTrue($filter_format_violation_found, format_string('Validation violation for invalid value "%invalid_value" found', array('%invalid_value' => $invalid_value)));
}
}
|
// { dg-options "-std=gnu++11" }
// Copyright (C) 2005-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 20.6.6.2 Template class shared_ptr [util.smartptr.shared]
#include <memory>
#include <testsuite_hooks.h>
struct A { };
struct B : A { };
// 20.6.6.2.1 shared_ptr constructors [util.smartptr.shared.const]
// Construction from pointer
int
test01()
{
bool test __attribute__((unused)) = true;
A * const a = 0;
std::shared_ptr<A> p(a);
VERIFY( p.get() == 0 );
VERIFY( p.use_count() == 1 );
return 0;
}
int
test02()
{
bool test __attribute__((unused)) = true;
A * const a = new A;
std::shared_ptr<A> p(a);
VERIFY( p.get() == a );
VERIFY( p.use_count() == 1 );
return 0;
}
int
test03()
{
bool test __attribute__((unused)) = true;
B * const b = new B;
std::shared_ptr<A> p(b);
VERIFY( p.get() == b );
VERIFY( p.use_count() == 1 );
return 0;
}
int
main()
{
test01();
test02();
test03();
return 0;
}
|
"""
Boolean geometry utilities.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
import sys
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__credits__ = 'Art of Illusion <http://www.artofillusion.org/>'
__date__ = '$Date: 2008/02/05 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def _getAccessibleAttribute(attributeName):
'Get the accessible attribute.'
if attributeName in globalAccessibleAttributeDictionary:
return globalAccessibleAttributeDictionary[attributeName]
return None
def continuous(valueString):
'Print continuous.'
sys.stdout.write(str(valueString))
return valueString
def line(valueString):
'Print line.'
print(valueString)
return valueString
globalAccessibleAttributeDictionary = {'continuous' : continuous, 'line' : line}
|
<?php
/**
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Maintenance
*/
require_once __DIR__ . '/Maintenance.php';
/**
* @ingroup Maintenance
*/
class PageExists extends Maintenance {
public function __construct() {
parent::__construct();
$this->addDescription( 'Report whether a specific page exists' );
$this->addArg( 'title', 'Page title to check whether it exists' );
}
public function execute() {
$titleArg = $this->getArg();
$title = Title::newFromText( $titleArg );
$pageExists = $title && $title->exists();
$text = '';
$code = 0;
if ( $pageExists ) {
$text = "{$title} exists.";
} else {
$text = "{$titleArg} doesn't exist.";
$code = 1;
}
$this->output( $text );
$this->error( '', $code );
}
}
$maintClass = "PageExists";
require_once RUN_MAINTENANCE_IF_MAIN;
|
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CoreBundle\Helper;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class TrackingPixelHelper
*/
class TrackingPixelHelper
{
/**
* @param Request $request
*
* @return Response
*/
public static function getResponse(Request $request)
{
ignore_user_abort(true);
//turn off gzip compression
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', 1);
}
ini_set('zlib.output_compression', 0);
$response = new Response();
//removing any content encoding like gzip etc.
$response->headers->set('Content-encoding', 'none');
//check to ses if request is a POST
if ($request->getMethod() == 'GET') {
//return 1x1 pixel transparent gif
$response->headers->set('Content-type', 'image/gif');
//avoid cache time on browser side
$response->headers->set('Content-Length', '42');
$response->headers->set('Cache-Control', 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate');
$response->headers->set('Expires', 'Wed, 11 Jan 2000 12:59:00 GMT');
$response->headers->set('Last-Modified', 'Wed, 11 Jan 2006 12:59:00 GMT');
$response->headers->set('Pragma', 'no-cache');
$response->setContent(self::getImage());
} else {
$response->setContent(' ');
}
return $response;
}
/**
* @return string
*/
public static function getImage()
{
return sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%',71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59);
}
}
|
<?php
$_['heading_title'] = '欢迎访问 %s';
?> |
/******************************************************************************
*
* Copyright (C) 2009 - 2014 Xilinx, Inc. All rights reserved.
*
* 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.
*
* Use of the Software is limited solely to applications:
* (a) running on a Xilinx device, or
* (b) that interact with a Xilinx device through a bus or interconnect.
*
* 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
* XILINX CONSORTIUM 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 of the Xilinx shall not be used
* in advertising or otherwise to promote the sale, use or other dealings in
* this Software without prior written authorization from Xilinx.
*
******************************************************************************/
/*****************************************************************************
*
* @file sleep.c
*
* This function provides a second delay using the Global Timer register in
* the ARM Cortex A9 MP core.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- -------- -------- -----------------------------------------------
* 1.00a ecm/sdm 11/11/09 First release
* 3.07a sgd 07/05/12 Updated sleep function to make use Global Timer
* </pre>
*
******************************************************************************/
/***************************** Include Files *********************************/
#include "sleep.h"
#include "xtime_l.h"
#include "xparameters.h"
/*****************************************************************************/
/*
*
* This API is used to provide delays in seconds
*
* @param seconds requested
*
* @return 0 always
*
* @note None.
*
****************************************************************************/
int sleep(unsigned int seconds)
{
XTime tEnd, tCur;
XTime_GetTime(&tCur);
tEnd = tCur + ((XTime) seconds) * COUNTS_PER_SECOND;
do
{
XTime_GetTime(&tCur);
} while (tCur < tEnd);
return 0;
}
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.armor.glyphs;
import com.watabou.noosa.Camera;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Roots;
import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.particles.EarthParticle;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor.Glyph;
import com.shatteredpixel.shatteredpixeldungeon.plants.Earthroot;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite.Glowing;
import com.watabou.utils.Random;
public class Entanglement extends Glyph {
private static final String TXT_ENTANGLEMENT = "%s of entanglement";
private static ItemSprite.Glowing GREEN = new ItemSprite.Glowing( 0x448822 );
@Override
public int proc( Armor armor, Char attacker, Char defender, int damage ) {
int level = Math.max( 0, armor.level );
if (Random.Int( 4 ) == 0) {
Buff.prolong( defender, Roots.class, 5 - level / 5 );
Buff.affect( defender, Earthroot.Armor.class ).level( 5 * (level + 1) );
CellEmitter.bottom( defender.pos ).start( EarthParticle.FACTORY, 0.05f, 8 );
Camera.main.shake( 1, 0.4f );
}
return damage;
}
@Override
public String name( String weaponName) {
return String.format( TXT_ENTANGLEMENT, weaponName );
}
@Override
public Glowing glowing() {
return GREEN;
}
}
|
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
package network
import (
"context"
"encoding/json"
"net/http"
"path"
"strconv"
"github.com/joyent/triton-go/client"
"github.com/pkg/errors"
)
type FabricsClient struct {
client *client.Client
}
type FabricVLAN struct {
Name string `json:"name"`
ID int `json:"vlan_id"`
Description string `json:"description"`
}
type ListVLANsInput struct{}
func (c *FabricsClient) ListVLANs(ctx context.Context, _ *ListVLANsInput) ([]*FabricVLAN, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans")
reqInputs := client.RequestInput{
Method: http.MethodGet,
Path: fullPath,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to list VLANs")
}
var result []*FabricVLAN
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode list VLANs response")
}
return result, nil
}
type CreateVLANInput struct {
Name string `json:"name"`
ID int `json:"vlan_id"`
Description string `json:"description,omitempty"`
}
func (c *FabricsClient) CreateVLAN(ctx context.Context, input *CreateVLANInput) (*FabricVLAN, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans")
reqInputs := client.RequestInput{
Method: http.MethodPost,
Path: fullPath,
Body: input,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to create VLAN")
}
var result *FabricVLAN
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode create VLAN response")
}
return result, nil
}
type UpdateVLANInput struct {
ID int `json:"-"`
Name string `json:"name"`
Description string `json:"description"`
}
func (c *FabricsClient) UpdateVLAN(ctx context.Context, input *UpdateVLANInput) (*FabricVLAN, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID))
reqInputs := client.RequestInput{
Method: http.MethodPut,
Path: fullPath,
Body: input,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to update VLAN")
}
var result *FabricVLAN
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode update VLAN response")
}
return result, nil
}
type GetVLANInput struct {
ID int `json:"-"`
}
func (c *FabricsClient) GetVLAN(ctx context.Context, input *GetVLANInput) (*FabricVLAN, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID))
reqInputs := client.RequestInput{
Method: http.MethodGet,
Path: fullPath,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to get VLAN")
}
var result *FabricVLAN
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode get VLAN response")
}
return result, nil
}
type DeleteVLANInput struct {
ID int `json:"-"`
}
func (c *FabricsClient) DeleteVLAN(ctx context.Context, input *DeleteVLANInput) error {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID))
reqInputs := client.RequestInput{
Method: http.MethodDelete,
Path: fullPath,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return errors.Wrap(err, "unable to delete VLAN")
}
return nil
}
type ListFabricsInput struct {
FabricVLANID int `json:"-"`
}
func (c *FabricsClient) List(ctx context.Context, input *ListFabricsInput) ([]*Network, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks")
reqInputs := client.RequestInput{
Method: http.MethodGet,
Path: fullPath,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to list fabrics")
}
var result []*Network
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode list fabrics response")
}
return result, nil
}
type CreateFabricInput struct {
FabricVLANID int `json:"-"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Subnet string `json:"subnet"`
ProvisionStartIP string `json:"provision_start_ip"`
ProvisionEndIP string `json:"provision_end_ip"`
Gateway string `json:"gateway,omitempty"`
Resolvers []string `json:"resolvers,omitempty"`
Routes map[string]string `json:"routes,omitempty"`
InternetNAT bool `json:"internet_nat"`
}
func (c *FabricsClient) Create(ctx context.Context, input *CreateFabricInput) (*Network, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks")
reqInputs := client.RequestInput{
Method: http.MethodPost,
Path: fullPath,
Body: input,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to create fabric")
}
var result *Network
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode create fabric response")
}
return result, nil
}
type GetFabricInput struct {
FabricVLANID int `json:"-"`
NetworkID string `json:"-"`
}
func (c *FabricsClient) Get(ctx context.Context, input *GetFabricInput) (*Network, error) {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID)
reqInputs := client.RequestInput{
Method: http.MethodGet,
Path: fullPath,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return nil, errors.Wrap(err, "unable to get fabric")
}
var result *Network
decoder := json.NewDecoder(respReader)
if err = decoder.Decode(&result); err != nil {
return nil, errors.Wrap(err, "unable to decode get fabric response")
}
return result, nil
}
type DeleteFabricInput struct {
FabricVLANID int `json:"-"`
NetworkID string `json:"-"`
}
func (c *FabricsClient) Delete(ctx context.Context, input *DeleteFabricInput) error {
fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID)
reqInputs := client.RequestInput{
Method: http.MethodDelete,
Path: fullPath,
}
respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
if respReader != nil {
defer respReader.Close()
}
if err != nil {
return errors.Wrap(err, "unable to delete fabric")
}
return nil
}
|
class Report
attr_reader :group, :since
attr_reader :questions, :answers, :users, :badges, :votes
def initialize(group, since = Time.now.yesterday)
@group = group
@since = since
@questions = group.questions.where(:created_at => {:$gt => since}).count
@answers = group.answers.where(:created_at => {:$gt => since}).count
@users = group.memberships.count
@badges = group.badges.where(:created_at => {:$gt => since}).count
end
end
|
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum 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 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types
import (
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
type bytesBacked interface {
Bytes() []byte
}
const bloomLength = 256
// Bloom represents a 256 bit bloom filter.
type Bloom [bloomLength]byte
// BytesToBloom converts a byte slice to a bloom filter.
// It panics if b is not of suitable size.
func BytesToBloom(b []byte) Bloom {
var bloom Bloom
bloom.SetBytes(b)
return bloom
}
// SetBytes sets the content of b to the given bytes.
// It panics if d is not of suitable size.
func (b *Bloom) SetBytes(d []byte) {
if len(b) < len(d) {
panic(fmt.Sprintf("bloom bytes too big %d %d", len(b), len(d)))
}
copy(b[bloomLength-len(d):], d)
}
// Add adds d to the filter. Future calls of Test(d) will return true.
func (b *Bloom) Add(d *big.Int) {
bin := new(big.Int).SetBytes(b[:])
bin.Or(bin, bloom9(d.Bytes()))
b.SetBytes(bin.Bytes())
}
// Big converts b to a big integer.
func (b Bloom) Big() *big.Int {
return new(big.Int).SetBytes(b[:])
}
func (b Bloom) Bytes() []byte {
return b[:]
}
func (b Bloom) Test(test *big.Int) bool {
return BloomLookup(b, test)
}
func (b Bloom) TestBytes(test []byte) bool {
return b.Test(new(big.Int).SetBytes(test))
}
// MarshalText encodes b as a hex string with 0x prefix.
func (b Bloom) MarshalText() ([]byte, error) {
return hexutil.Bytes(b[:]).MarshalText()
}
// UnmarshalText b as a hex string with 0x prefix.
func (b *Bloom) UnmarshalText(input []byte) error {
return hexutil.UnmarshalFixedText("Bloom", input, b[:])
}
func CreateBloom(receipts Receipts) Bloom {
bin := new(big.Int)
for _, receipt := range receipts {
bin.Or(bin, LogsBloom(receipt.Logs))
}
return BytesToBloom(bin.Bytes())
}
func LogsBloom(logs []*Log) *big.Int {
bin := new(big.Int)
for _, log := range logs {
bin.Or(bin, bloom9(log.Address.Bytes()))
for _, b := range log.Topics {
bin.Or(bin, bloom9(b[:]))
}
}
return bin
}
func bloom9(b []byte) *big.Int {
b = crypto.Keccak256(b[:])
r := new(big.Int)
for i := 0; i < 6; i += 2 {
t := big.NewInt(1)
b := (uint(b[i+1]) + (uint(b[i]) << 8)) & 2047
r.Or(r, t.Lsh(t, b))
}
return r
}
var Bloom9 = bloom9
func BloomLookup(bin Bloom, topic bytesBacked) bool {
bloom := bin.Big()
cmp := bloom9(topic.Bytes()[:])
return bloom.And(bloom, cmp).Cmp(cmp) == 0
}
|
## mako
<%!
from django.utils.translation import ugettext as _
from branding.api import get_footer
%>
<% footer = get_footer(is_secure=is_secure) %>
<%namespace name='static' file='static_content.html'/>
## WARNING: These files are specific to edx.org and are not used in installations outside of that domain. Open edX users will want to use the file "footer.html" for any changes or overrides.
<footer id="footer-edx-v3" role="contentinfo" aria-label="${_("Page Footer")}"
## When rendering the footer through the branding API,
## the direction may not be set on the parent element,
## so we set it here.
% if bidi:
dir=${bidi}
% endif
>
<h2 class="sr footer-about-title">${_("About edX")}</h2>
<div class="footer-content-wrapper">
<div class="footer-logo">
<img alt="edX logo" src="${footer['logo_image']}">
</div>
<div class="site-details">
<nav class="site-nav" aria-label="${_("About edX")}">
% for link in footer["navigation_links"]:
<a href="${link['url']}">${link['title']}</a>
% endfor
</nav>
<nav class="legal-notices" aria-label="${_("Legal")}">
% for link in footer["legal_links"]:
<a href="${link['url']}">${link['title']}</a>
% endfor
</nav>
<p class="copyright">${_(
u"\u00A9 edX Inc. All rights reserved except where noted. "
u"EdX, Open edX and the edX and Open EdX logos are registered trademarks "
u"or trademarks of edX Inc."
)}
</p>
## The OpenEdX link may be hidden when this view is served
## through an API to partner sites (such as marketing sites or blogs),
## which are not technically powered by OpenEdX.
% if not hide_openedx_link:
<div class="openedx-link">
<a href="${footer['openedx_link']['url']}" title="${footer['openedx_link']['title']}">
<img alt="${footer['openedx_link']['title']}" src="${footer['openedx_link']['image']}" width="140">
</a>
</div>
% endif
</div>
<div class="external-links">
<div class="social-media-links">
% for link in footer['social_links']:
<a href="${link['url']}" class="sm-link external" title="${link['title']}" rel="noreferrer">
<span class="icon fa ${link['icon-class']}" aria-hidden="true"></span>
<span class="sr">${link['action']}</span>
</a>
% endfor
</div>
<div class="mobile-app-links">
% for link in footer['mobile_links']:
<a href="${link['url']}" class="app-link external">
<img alt="${link['title']}" src="${link['image']}">
</a>
% endfor
</div>
</div>
</div>
</footer>
% if include_dependencies:
<%static:js group='base_vendor'/>
<%static:css group='style-vendor'/>
<%include file="widgets/segment-io.html" />
<%include file="widgets/segment-io-footer.html" />
% endif
% if bidi == 'rtl':
<%static:css group='style-lms-footer-edx-rtl'/>
% else:
<%static:css group='style-lms-footer-edx'/>
% endif
% if footer_css_urls:
% for url in footer_css_urls:
<link rel="stylesheet" type="text/css" href="${url}"></link>
% endfor
% endif
% if footer_js_url:
<script type="text/javascript" src="${footer_js_url}"></script>
% endif
|
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.addons.point_of_sale.point_of_sale import pos_session
class pos_session_opening(osv.osv_memory):
_name = 'pos.session.opening'
_columns = {
'pos_config_id' : fields.many2one('pos.config', string='Point of Sale', required=True),
'pos_session_id' : fields.many2one('pos.session', string='PoS Session'),
'pos_state' : fields.related('pos_session_id', 'state',
type='selection',
selection=pos_session.POS_SESSION_STATE,
string='Session Status', readonly=True),
'pos_state_str' : fields.char('Status', readonly=True),
'show_config' : fields.boolean('Show Config', readonly=True),
'pos_session_name' : fields.related('pos_session_id', 'name', string="Session Name",
type='char', size=64, readonly=True),
'pos_session_username' : fields.related('pos_session_id', 'user_id', 'name',
type='char', size=64, readonly=True)
}
def open_ui(self, cr, uid, ids, context=None):
data = self.browse(cr, uid, ids[0], context=context)
context = dict(context or {})
context['active_id'] = data.pos_session_id.id
return {
'type' : 'ir.actions.act_url',
'url': '/pos/web/',
'target': 'self',
}
def open_existing_session_cb_close(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids[0], context=context)
wizard.pos_session_id.signal_workflow('cashbox_control')
return self.open_session_cb(cr, uid, ids, context)
def open_session_cb(self, cr, uid, ids, context=None):
assert len(ids) == 1, "you can open only one session at a time"
proxy = self.pool.get('pos.session')
wizard = self.browse(cr, uid, ids[0], context=context)
if not wizard.pos_session_id:
values = {
'user_id' : uid,
'config_id' : wizard.pos_config_id.id,
}
session_id = proxy.create(cr, uid, values, context=context)
s = proxy.browse(cr, uid, session_id, context=context)
if s.state=='opened':
return self.open_ui(cr, uid, ids, context=context)
return self._open_session(session_id)
return self._open_session(wizard.pos_session_id.id)
def open_existing_session_cb(self, cr, uid, ids, context=None):
assert len(ids) == 1
wizard = self.browse(cr, uid, ids[0], context=context)
return self._open_session(wizard.pos_session_id.id)
def _open_session(self, session_id):
return {
'name': _('Session'),
'view_type': 'form',
'view_mode': 'form,tree',
'res_model': 'pos.session',
'res_id': session_id,
'view_id': False,
'type': 'ir.actions.act_window',
}
def on_change_config(self, cr, uid, ids, config_id, context=None):
result = {
'pos_session_id': False,
'pos_state': False,
'pos_state_str' : '',
'pos_session_username' : False,
'pos_session_name' : False,
}
if not config_id:
return {'value' : result}
proxy = self.pool.get('pos.session')
session_ids = proxy.search(cr, uid, [
('state', '!=', 'closed'),
('config_id', '=', config_id),
('user_id', '=', uid),
], context=context)
if session_ids:
session = proxy.browse(cr, uid, session_ids[0], context=context)
result['pos_state'] = str(session.state)
result['pos_state_str'] = dict(pos_session.POS_SESSION_STATE).get(session.state, '')
result['pos_session_id'] = session.id
result['pos_session_name'] = session.name
result['pos_session_username'] = session.user_id.name
return {'value' : result}
def default_get(self, cr, uid, fieldnames, context=None):
so = self.pool.get('pos.session')
session_ids = so.search(cr, uid, [('state','<>','closed'), ('user_id','=',uid)], context=context)
if session_ids:
result = so.browse(cr, uid, session_ids[0], context=context).config_id.id
else:
current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
result = current_user.pos_config and current_user.pos_config.id or False
if not result:
r = self.pool.get('pos.config').search(cr, uid, [], context=context)
result = r and r[0] or False
count = self.pool.get('pos.config').search_count(cr, uid, [('state', '=', 'active')], context=context)
show_config = bool(count > 1)
return {
'pos_config_id' : result,
'show_config' : show_config,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.