code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package p {
object Container {
private[p] val invisible = "smth"
}
package p2 {
import p.Container
object User {
Container./*resolved: true*/invisible
}
}
}
package p3 {
import p.Container
object User {
Container./*accessible: false*/invisible
}
}
| triggerNZ/intellij-scala | testdata/resolve2/bug2/SCL1934.scala | Scala | apache-2.0 | 263 |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fixchain
import (
"context"
"fmt"
"log"
"sync"
"sync/atomic"
"time"
ct "github.com/google/certificate-transparency-go"
"github.com/google/certificate-transparency-go/client"
"github.com/google/certificate-transparency-go/x509"
)
// Limiter is an interface to allow different rate limiters to be used with the
// Logger.
type Limiter interface {
Wait()
}
// Logger contains methods to asynchronously log certificate chains to a
// Certificate Transparency log and properties to store information about each
// attempt that is made to post a certificate chain to said log.
type Logger struct {
ctx context.Context
client client.AddLogClient
roots *x509.CertPool
toPost chan *toPost
errors chan<- *FixError
active uint32
queued uint32 // How many chains have been queued to be posted.
posted uint32 // How many chains have been posted.
reposted uint32 // How many chains for an already-posted cert have been queued.
chainReposted uint32 // How many chains have been queued again.
// Note that wg counts the number of active requests, not
// active servers, because we can't close it to signal the
// end, because of retries.
wg sync.WaitGroup
limiter Limiter
postCertCache *lockedMap
postChainCache *lockedMap
}
// IsPosted tells the caller whether a chain for the given certificate has
// already been successfully posted to the log by this Logger.
func (l *Logger) IsPosted(cert *x509.Certificate) bool {
return l.postCertCache.get(hash(cert))
}
// QueueChain adds the given chain to the queue to be posted to the log.
func (l *Logger) QueueChain(chain []*x509.Certificate) {
if chain == nil {
return
}
atomic.AddUint32(&l.queued, 1)
// Has a chain for the cert this chain if for already been successfully
//posted to the log by this Logger?
h := hash(chain[0]) // Chains are cert -> root
if l.postCertCache.get(h) {
atomic.AddUint32(&l.reposted, 1)
return // Don't post chain for a cert that has already had a chain posted.
}
// If we assume all chains for the same cert are equally
// likely to succeed, then we could mark the cert as posted
// here. However, bugs might cause a log to refuse one chain
// and accept another, so try each unique chain.
// Has this Logger already tried to post this chain?
h = hashChain(chain)
if l.postChainCache.get(h) {
atomic.AddUint32(&l.chainReposted, 1)
return
}
l.postChainCache.set(h, true)
l.postToLog(&toPost{chain: chain})
}
// Wait for all of the active requests to finish being processed.
func (l *Logger) Wait() {
l.wg.Wait()
}
// RootCerts returns the root certificates that the log accepts.
func (l *Logger) RootCerts() *x509.CertPool {
if l.roots == nil {
// Retry if unable to get roots.
for i := 0; i < 10; i++ {
roots, err := l.getRoots()
if err == nil {
l.roots = roots
return l.roots
}
log.Println(err)
}
log.Fatalf("Can't get roots for log")
}
return l.roots
}
func (l *Logger) getRoots() (*x509.CertPool, error) {
roots, err := l.client.GetAcceptedRoots(l.ctx)
if err != nil {
return nil, fmt.Errorf("failed to get roots: %s", err)
}
ret := x509.NewCertPool()
for _, root := range roots {
r, err := x509.ParseCertificate(root.Data)
switch err.(type) {
case nil, x509.NonFatalErrors:
// ignore
default:
return nil, fmt.Errorf("can't parse certificate: %s %#v", err, root.Data)
}
ret.AddCert(r)
}
return ret, nil
}
type toPost struct {
chain []*x509.Certificate
}
// postToLog(), rather than its asynchronous couterpart asyncPostToLog(), is
// used during the initial queueing of chains to avoid spinning up an excessive
// number of goroutines, and unecessarily using up memory. If asyncPostToLog()
// was called instead, then every time a new chain was queued, a new goroutine
// would be created, each holding their own chain - regardless of whether there
// were postServers available to process them or not. If a large number of
// chains were queued in a short period of time, this could lead to a large
// number of these additional goroutines being created, resulting in excessive
// memory usage.
func (l *Logger) postToLog(p *toPost) {
l.wg.Add(1) // Add to the wg as we are adding a new active request to the logger queue.
l.toPost <- p
}
// asyncPostToLog(), rather than its synchronous couterpart postToLog(), is used
// during retries to avoid deadlock. Without the separate goroutine created in
// asyncPostToLog(), deadlock can occur in the following situation:
//
// Suppose there is only one postServer() goroutine running, and it is blocked
// waiting for a toPost on the toPost chan. A toPost gets added to the chan,
// which causes the following to happen:
// - the postServer takes the toPost from the chan.
// - the postServer calls l.postChain(toPost), and waits for
// l.postChain() to return before going back to the toPost
// chan for another toPost.
// - l.postChain() begins execution. Suppose the first post
// attempt of the toPost fails for some network-related
// reason.
// - l.postChain retries and calls l.postToLog() to queue up the
// toPost to try to post it again.
// - l.postToLog() tries to put the toPost on the toPost chan,
// and blocks until a postServer takes it off the chan.
// But the one and only postServer is still waiting for l.postChain (and
// therefore l.postToLog) to return, and will not go to take another toPost off
// the toPost chan until that happens.
// Thus, deadlock.
//
// Similar situations with multiple postServers can easily be imagined.
func (l *Logger) asyncPostToLog(p *toPost) {
l.wg.Add(1) // Add to the wg as we are adding a new active request to the logger queue.
go func() {
l.toPost <- p
}()
}
func (l *Logger) postChain(p *toPost) {
h := hash(p.chain[0])
if l.postCertCache.get(h) {
atomic.AddUint32(&l.reposted, 1)
return
}
derChain := make([]ct.ASN1Cert, 0, len(p.chain))
for _, cert := range p.chain {
derChain = append(derChain, ct.ASN1Cert{Data: cert.Raw})
}
l.limiter.Wait()
atomic.AddUint32(&l.posted, 1)
_, err := l.client.AddChain(l.ctx, derChain)
if err != nil {
l.errors <- &FixError{
Type: LogPostFailed,
Chain: p.chain,
Error: fmt.Errorf("add-chain failed: %s", err),
}
return
}
// If the post was successful, cache.
l.postCertCache.set(h, true)
}
func (l *Logger) postServer() {
for {
c := <-l.toPost
atomic.AddUint32(&l.active, 1)
l.postChain(c)
atomic.AddUint32(&l.active, ^uint32(0))
l.wg.Done()
}
}
func (l *Logger) logStats() {
t := time.NewTicker(time.Second)
go func() {
for range t.C {
log.Printf("posters: %d active, %d posted, %d queued, %d certs requeued, %d chains requeued",
l.active, l.posted, l.queued, l.reposted, l.chainReposted)
}
}()
}
// NewLogger creates a new asynchronous logger to log chains to the
// Certificate Transparency log at the given url. It starts up a pool of
// workerCount workers. Errors are pushed to the errors channel. client is
// used to post the chains to the log.
func NewLogger(ctx context.Context, workerCount int, errors chan<- *FixError, client client.AddLogClient, limiter Limiter, logStats bool) *Logger {
l := &Logger{
ctx: ctx,
client: client,
errors: errors,
toPost: make(chan *toPost),
postCertCache: newLockedMap(),
postChainCache: newLockedMap(),
limiter: limiter,
}
l.RootCerts()
// Start post server pool.
for i := 0; i < workerCount; i++ {
go l.postServer()
}
if logStats {
l.logStats()
}
return l
}
| imcsk8/origin | vendor/github.com/google/certificate-transparency-go/fixchain/logger.go | GO | apache-2.0 | 8,160 |
<html>
<body>
Sequence component classes for the science model.
</body>
</html>
| arturog8m/ocs | bundle/edu.gemini.pot/src/main/resources/edu/gemini/spModel/seqcomp/package.html | HTML | bsd-3-clause | 80 |
/*****************************************************************************
Copyright (c) 2011, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native middle-level C interface to LAPACK function csytrs
* Author: Intel Corporation
* Generated November, 2011
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_csytrs_work( int matrix_order, char uplo, lapack_int n,
lapack_int nrhs, const lapack_complex_float* a,
lapack_int lda, const lapack_int* ipiv,
lapack_complex_float* b, lapack_int ldb )
{
lapack_int info = 0;
if( matrix_order == LAPACK_COL_MAJOR ) {
/* Call LAPACK function and adjust info */
LAPACK_csytrs( &uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, &info );
if( info < 0 ) {
info = info - 1;
}
} else if( matrix_order == LAPACK_ROW_MAJOR ) {
lapack_int lda_t = MAX(1,n);
lapack_int ldb_t = MAX(1,n);
lapack_complex_float* a_t = NULL;
lapack_complex_float* b_t = NULL;
/* Check leading dimension(s) */
if( lda < n ) {
info = -6;
LAPACKE_xerbla( "LAPACKE_csytrs_work", info );
return info;
}
if( ldb < nrhs ) {
info = -9;
LAPACKE_xerbla( "LAPACKE_csytrs_work", info );
return info;
}
/* Allocate memory for temporary array(s) */
a_t = (lapack_complex_float*)
LAPACKE_malloc( sizeof(lapack_complex_float) * lda_t * MAX(1,n) );
if( a_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_0;
}
b_t = (lapack_complex_float*)
LAPACKE_malloc( sizeof(lapack_complex_float) *
ldb_t * MAX(1,nrhs) );
if( b_t == NULL ) {
info = LAPACK_TRANSPOSE_MEMORY_ERROR;
goto exit_level_1;
}
/* Transpose input matrices */
LAPACKE_csy_trans( matrix_order, uplo, n, a, lda, a_t, lda_t );
LAPACKE_cge_trans( matrix_order, n, nrhs, b, ldb, b_t, ldb_t );
/* Call LAPACK function and adjust info */
LAPACK_csytrs( &uplo, &n, &nrhs, a_t, &lda_t, ipiv, b_t, &ldb_t,
&info );
if( info < 0 ) {
info = info - 1;
}
/* Transpose output matrices */
LAPACKE_cge_trans( LAPACK_COL_MAJOR, n, nrhs, b_t, ldb_t, b, ldb );
/* Release memory and exit */
LAPACKE_free( b_t );
exit_level_1:
LAPACKE_free( a_t );
exit_level_0:
if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_csytrs_work", info );
}
} else {
info = -1;
LAPACKE_xerbla( "LAPACKE_csytrs_work", info );
}
return info;
}
| hpanderson/OpenBLAS | lapack-netlib/lapacke/src/lapacke_csytrs_work.c | C | bsd-3-clause | 4,467 |
<!doctype html>
<link rel="stylesheet" href="s.css" />
<h1>Tests for <a href="../../">recipes</a>/<a href="../">effect</a>/corner-folded</h1>
<p class="doc">
See <a href="http://nicolasgallagher.com/pure-css-folded-corner-effect/demo/">http://nicolasgallagher.com/pure-css-folded-corner-effect/demo/</a> for original effect
</p>
<h2>Top Left</h2>
<div class="wrapper">
<div class="corner-folded-top-left"></div>
</div>
<hr />
<h2>Top Right</h2>
<div class="wrapper">
<div class="corner-folded-top-right"></div>
</div>
<hr />
<h2>Bottom Left</h2>
<div class="wrapper">
<div class="corner-folded-bottom-left"></div>
</div>
<hr />
<h2>Bottom Right</h2>
<div class="wrapper">
<div class="corner-folded-bottom-right"></div>
</div>
| hackathon-3d/team-gryffindor-repo | www/touch/resources/themes/vendor/compass-recipes/tests/recipes/effect/corner-folded/index.html | HTML | gpl-2.0 | 755 |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"@GDScript",
"GDScript",
]
def get_doc_path():
return "doc_classes"
| honix/godot | modules/gdscript/config.py | Python | mit | 209 |
// Stupid jQuery table plugin.
(function($) {
$.fn.stupidtable = function(sortFns) {
return this.each(function() {
var $table = $(this);
sortFns = sortFns || {};
sortFns = $.extend({}, $.fn.stupidtable.default_sort_fns, sortFns);
$table.data('sortFns', sortFns);
$table.on("click.stupidtable", "thead th", function() {
$(this).stupidsort();
});
// Sort th immediately if data-sort-onload="yes" is specified. Limit to
// the first one found - only one default sort column makes sense anyway.
var $th_onload_sort = $table.find("th[data-sort-onload=yes]").eq(0);
$th_onload_sort.stupidsort();
});
};
// Allow specification of settings on a per-table basis. Call on a table
// jquery object. Call *before* calling .stuidtable();
$.fn.stupidtable_settings = function(settings) {
return this.each(function() {
var $table = $(this);
var final_settings = $.extend({}, $.fn.stupidtable.default_settings, settings);
$table.stupidtable.settings = final_settings;
});
};
// Expects $("#mytable").stupidtable() to have already been called.
// Call on a table header.
$.fn.stupidsort = function(force_direction){
var $this_th = $(this);
var th_index = 0; // we'll increment this soon
var dir = $.fn.stupidtable.dir;
var $table = $this_th.closest("table");
var datatype = $this_th.data("sort") || null;
// Bring in default settings if none provided
if(!$table.stupidtable.settings){
$table.stupidtable.settings = $.extend({}, $.fn.stupidtable.default_settings);
}
// No datatype? Nothing to do.
if (datatype === null) {
return;
}
var sortFns = $table.data('sortFns');
var sortMethod = sortFns[datatype];
// =========================================================
// End var setup, begin sorting procedures
// =========================================================
// Account for colspans
$this_th.parents("tr").find("th").slice(0, $(this).index()).each(function() {
var cols = $(this).attr("colspan") || 1;
th_index += parseInt(cols,10);
});
var sort_dir;
if(arguments.length == 1){
sort_dir = force_direction;
}
else{
sort_dir = force_direction || $this_th.data("sort-default") || dir.ASC;
if ($this_th.data("sort-dir"))
sort_dir = $this_th.data("sort-dir") === dir.ASC ? dir.DESC : dir.ASC;
}
$this_th.data("sort-dir", sort_dir);
$table.trigger("beforetablesort", {column: th_index, direction: sort_dir, $th: $this_th});
// More reliable method of forcing a redraw
$table.css("display");
// Run sorting asynchronously on a timout to force browser redraw after
// `beforetablesort` callback. Also avoids locking up the browser too much.
setTimeout(function() {
// Gather the elements for this column
var column = [];
var trs = $table.children("tbody").children("tr");
// Extract the data for the column that needs to be sorted and pair it up
// with the TR itself into a tuple. This way sorting the values will
// incidentally sort the trs.
trs.each(function(index,tr) {
var $e = $(tr).children().eq(th_index);
var sort_val = $e.data("sort-value");
// Store and read from the .data cache for display text only sorts
// instead of looking through the DOM every time
if(typeof(sort_val) === "undefined"){
var txt = $e.text();
$e.data('sort-value', txt);
sort_val = txt;
}
column.push([sort_val, tr, index]);
});
// Sort by the data-order-by value. Sort by position in the table if
// values are the same. This enforces a stable sort across all browsers.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90
column.sort(function(a, b) {
var diff = sortMethod(a[0], b[0]);
if (diff === 0)
return a[2] - b[2];
else
return diff;
});
if (sort_dir != dir.ASC)
column.reverse();
var sort_info = {
column: column,
sort_dir: sort_dir,
$th: $this_th,
th_index: th_index,
$table: $table,
datatype: datatype,
compare_fn: sortMethod
}
if(!$table.stupidtable.settings.should_redraw(sort_info)){
return;
}
// Replace the content of tbody with the sorted rows. Strangely
// enough, .append accomplishes this for us.
trs = $.map(column, function(kv) { return kv[1]; });
$table.children("tbody").append(trs);
// Reset siblings
$table.find("th").data("sort-dir", null).removeClass("sorting-desc sorting-asc");
$this_th.data("sort-dir", sort_dir).addClass("sorting-"+sort_dir);
$table.trigger("aftertablesort", {column: th_index, direction: sort_dir, $th: $this_th});
$table.css("display");
}, 10);
return $this_th;
};
// Call on a sortable td to update its value in the sort. This should be the
// only mechanism used to update a cell's sort value. If your display value is
// different from your sort value, use jQuery's .text() or .html() to update
// the td contents, Assumes stupidtable has already been called for the table.
$.fn.updateSortVal = function(new_sort_val){
var $this_td = $(this);
if($this_td.is('[data-sort-value]')){
// For visual consistency with the .data cache
$this_td.attr('data-sort-value', new_sort_val);
}
$this_td.data("sort-value", new_sort_val);
return $this_td;
};
// ------------------------------------------------------------------
// Default settings
// ------------------------------------------------------------------
$.fn.stupidtable.default_settings = {
should_redraw: function(sort_info){
return true;
}
};
$.fn.stupidtable.dir = {ASC: "asc", DESC: "desc"};
$.fn.stupidtable.default_sort_fns = {
"int": function(a, b) {
return parseInt(a, 10) - parseInt(b, 10);
},
"float": function(a, b) {
return parseFloat(a) - parseFloat(b);
},
"string": function(a, b) {
return a.toString().localeCompare(b.toString());
},
"string-ins": function(a, b) {
a = a.toString().toLocaleLowerCase();
b = b.toString().toLocaleLowerCase();
return a.localeCompare(b);
}
};
})(jQuery);
| tholu/cdnjs | ajax/libs/stupidtable/1.1.0/stupidtable.js | JavaScript | mit | 6,427 |
// <copyright file="GammaDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// 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.
// </copyright>
using System;
using MathNet.Numerics.Distributions;
namespace Examples.ContinuousDistributionsExamples
{
/// <summary>
/// Gamma distribution example
/// </summary>
public class GammaDistribution : IExample
{
/// <summary>
/// Gets the name of this example
/// </summary>
/// <seealso cref="http://reference.wolfram.com/mathematica/ref/GammaDistribution.html"/>
public string Name
{
get
{
return "Gamma distribution";
}
}
/// <summary>
/// Gets the description of this example
/// </summary>
public string Description
{
get
{
return "Gamma distribution properties and samples generating examples";
}
}
/// <summary>
/// Run example
/// </summary>
/// <a href="http://en.wikipedia.org/wiki/Gamma_distribution">Gamma distribution</a>
public void Run()
{
// 1. Initialize the new instance of the Gamma distribution class with parameter Shape = 1, Scale = 0.5.
var gamma = new Gamma(1, 2.0);
Console.WriteLine(@"1. Initialize the new instance of the Gamma distribution class with parameters Shape = {0}, Scale = {1}", gamma.Shape, gamma.Scale);
Console.WriteLine();
// 2. Distributuion properties:
Console.WriteLine(@"2. {0} distributuion properties:", gamma);
// Cumulative distribution function
Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", gamma.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));
// Probability density
Console.WriteLine(@"{0} - Probability density at location '0.3'", gamma.Density(0.3).ToString(" #0.00000;-#0.00000"));
// Log probability density
Console.WriteLine(@"{0} - Log probability density at location '0.3'", gamma.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));
// Entropy
Console.WriteLine(@"{0} - Entropy", gamma.Entropy.ToString(" #0.00000;-#0.00000"));
// Largest element in the domain
Console.WriteLine(@"{0} - Largest element in the domain", gamma.Maximum.ToString(" #0.00000;-#0.00000"));
// Smallest element in the domain
Console.WriteLine(@"{0} - Smallest element in the domain", gamma.Minimum.ToString(" #0.00000;-#0.00000"));
// Mean
Console.WriteLine(@"{0} - Mean", gamma.Mean.ToString(" #0.00000;-#0.00000"));
// Mode
Console.WriteLine(@"{0} - Mode", gamma.Mode.ToString(" #0.00000;-#0.00000"));
// Variance
Console.WriteLine(@"{0} - Variance", gamma.Variance.ToString(" #0.00000;-#0.00000"));
// Standard deviation
Console.WriteLine(@"{0} - Standard deviation", gamma.StdDev.ToString(" #0.00000;-#0.00000"));
// Skewness
Console.WriteLine(@"{0} - Skewness", gamma.Skewness.ToString(" #0.00000;-#0.00000"));
Console.WriteLine();
// 3. Generate 10 samples of the Gamma distribution
Console.WriteLine(@"3. Generate 10 samples of the Gamma distribution");
for (var i = 0; i < 10; i++)
{
Console.Write(gamma.Sample().ToString("N05") + @" ");
}
Console.WriteLine();
Console.WriteLine();
// 4. Generate 100000 samples of the Gamma(1, 2) distribution and display histogram
Console.WriteLine(@"4. Generate 100000 samples of the Gamma(1, 2) distribution and display histogram");
var data = new double[100000];
Gamma.Samples(data, 1, 2);
ConsoleHelper.DisplayHistogram(data);
Console.WriteLine();
// 5. Generate 100000 samples of the Gamma(8) distribution and display histogram
Console.WriteLine(@"5. Generate 100000 samples of the Gamma(5, 1) distribution and display histogram");
Gamma.Samples(data, 5, 1);
ConsoleHelper.DisplayHistogram(data);
}
}
}
| grovesNL/mathnet-numerics | src/Examples/ContinuousDistributions/GammaDistribution.cs | C# | mit | 5,558 |
/*
* 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 thrift
import "context"
// A processor is a generic object which operates upon an input stream and
// writes to some output stream.
type TProcessor interface {
Process(ctx context.Context, in, out TProtocol) (bool, TException)
}
type TProcessorFunction interface {
Process(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException)
}
// The default processor factory just returns a singleton
// instance.
type TProcessorFactory interface {
GetProcessor(trans TTransport) TProcessor
}
type tProcessorFactory struct {
processor TProcessor
}
func NewTProcessorFactory(p TProcessor) TProcessorFactory {
return &tProcessorFactory{processor: p}
}
func (p *tProcessorFactory) GetProcessor(trans TTransport) TProcessor {
return p.processor
}
/**
* The default processor factory just returns a singleton
* instance.
*/
type TProcessorFunctionFactory interface {
GetProcessorFunction(trans TTransport) TProcessorFunction
}
type tProcessorFunctionFactory struct {
processor TProcessorFunction
}
func NewTProcessorFunctionFactory(p TProcessorFunction) TProcessorFunctionFactory {
return &tProcessorFunctionFactory{processor: p}
}
func (p *tProcessorFunctionFactory) GetProcessorFunction(trans TTransport) TProcessorFunction {
return p.processor
}
| lomik/go-carbon | vendor/github.com/apache/thrift/lib/go/thrift/processor_factory.go | GO | mit | 2,085 |
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/scenario1_Events.html", {
ready: function (element, options) {
document.getElementById("registerReadingChanged").addEventListener("click", registerUnregisterReadingChanged, false);
document.getElementById("registerReadingChanged").disabled = true;
Windows.Devices.Sensors.Pedometer.getDefaultAsync().then(function (pedometer) {
if (!pedometer) {
WinJS.log && WinJS.log("No Pedomter found", "sample", "error");
}
else {
WinJS.log && WinJS.log("Default Pedometer opened", "sample", "status");
pedometer.reportInterval = 1000;
}
defaultPedometer = pedometer;
// enable button if pedometer is successfully opened
document.getElementById("registerReadingChanged").disabled = false;
},
function error(e) {
WinJS.log && WinJS.log("Error when opening default pedometer. " + e.message, "sample", "error");
}
)
},
unload: function () {
document.removeEventListener("visibilitychange", visibilityChangeHandler, false);
document.getElementById("registerReadingChanged").innerText = "Register ReadingChanged";
// Return the report interval to its default to release resources while the sensor is not in use
if (defaultPedometer) {
defaultPedometer.reportInterval = 0;
defaultPedometer.removeEventListener("readingchanged", onReadingChanged);
registeredForEvent = false;
}
}
});
var registeredForEvent = false;
var defaultPedometer = null;
var totalStepsCount = 0;
var unknownStepsCount = 0;
var walkingStepsCount = 0;
var runningStepsCount = 0;
function visibilityChangeHandler() {
// This is the event handler for VisibilityChanged events. You would register for these notifications
// if handling sensor data when the app is not visible could cause unintended actions in the app.
if (document.msVisibilityState === "visible") {
// Re-enable sensor input. No need to restore the desired reportInterval (it is restored for us upon app resume)
defaultPedometer.addEventListener("readingchanged", onReadingChanged);
} else {
// Disable sensor input. No need to restore the default reportInterval (resources will be released upon app suspension)
defaultPedometer.removeEventListener("readingchanged", onReadingChanged);
}
}
/// <summary>
/// Helper function to register/un-register to the 'readingchanged' event of the default pedometer
/// </summary>
function registerUnregisterReadingChanged() {
if (registeredForEvent) {
WinJS.log && WinJS.log("Unregistering for event invoked", "sample", "error");
defaultPedometer.removeEventListener("readingchanged", onReadingChanged, false);
document.getElementById("registerReadingChanged").innerText = "Register ReadingChanged";
registeredForEvent = false;
document.removeEventListener("visibilitychange", visibilityChangeHandler, false);
WinJS.log && WinJS.log("Unregsitered for event", "sample", "status");
}
else {
document.addEventListener("visibilitychange", visibilityChangeHandler, false);
defaultPedometer.addEventListener("readingchanged", onReadingChanged);
document.getElementById("registerReadingChanged").innerText = "Unregister ReadingChanged";
registeredForEvent = true;
WinJS.log && WinJS.log("Regsitered for event", "sample", "status");
}
}
/// <summary>
/// Invoked when the underlying pedometer sees a change in the step count for a step kind.
/// </summary>
/// <param name="sender">unused</param>
function onReadingChanged(e) {
var reading = e.reading;
var newStepsTaken = 0;
var readingTimeStamp = document.getElementById("readingTimeStamp");
var duration = 0;
// Event can still be in queue after unload is called
// so check if elements are still loaded.
// update html page
if (readingTimeStamp) {
readingTimeStamp.innerText = reading.timestamp;
switch (reading.stepKind) {
case Windows.Devices.Sensors.PedometerStepKind.unknown:
newStepsTaken = reading.cumulativeSteps - unknownStepsCount;
unknownStepsCount = reading.cumulativeSteps;
document.getElementById("unknownCount").innerHTML = unknownStepsCount;
document.getElementById("unknownDuration").innerHTML = reading.cumulativeStepsDuration;
break;
case Windows.Devices.Sensors.PedometerStepKind.walking:
newStepsTaken = reading.cumulativeSteps - walkingStepsCount;
walkingStepsCount = reading.cumulativeSteps;
document.getElementById("walkingCount").innerHTML = walkingStepsCount;
document.getElementById("walkingDuration").innerHTML = reading.cumulativeStepsDuration;
break;
case Windows.Devices.Sensors.PedometerStepKind.running:
newStepsTaken = reading.cumulativeSteps - runningStepsCount;
runningStepsCount = reading.cumulativeSteps;
document.getElementById("runningCount").innerHTML = runningStepsCount;
document.getElementById("runningDuration").innerHTML = reading.cumulativeStepsDuration;
break;
default:
WinJS.log && WinJS.log("Invalid Step Kind", "sample", "error");
break;
}
totalStepsCount += newStepsTaken;
document.getElementById("totalStepsCount").innerText = totalStepsCount.toString();
WinJS.log && WinJS.log("Getting readings", "sample", "status");
}
}
})();
| justasmal/Windows-universal-samples | pedometer/js/js/scenario1_events.js | JavaScript | mit | 6,328 |
exports.Connector = require('./lib/connector');
exports.SqlConnector = require('./lib/sql');
| soltrinox/vator-api-serv | node_modules/loopback-datasource-juggler/node_modules/loopback-connector/index.js | JavaScript | mit | 93 |
# 1.6.0 (2016.09.04)
* Ubuntu 16.04 support
# 1.5.2 (2016.04.22)
* Fix for `manage` parameter for `blackfire::php` (@Schnitzel)
# 1.5.1 (2016.03.08)
* Hotfix for `ini_path` (@Schnitzel)
# 1.5.0 (2016.03.07)
* Added new parameter `ini_path` (@Schnitzel)
# 1.4.2 (2016.03.03)
* Bound PE dependency
# 1.4.1 (2016.02.27)
* Update README and bound apt dependency
# 1.4.0 (2015.12.05)
* Puppet 4 compatibility
* Handle `log_level` passed as a string (@jtreminio)
* Added apt to manifest as a dependency
# 1.3.0 (2015.06.01)
* Added support for puppetlabs-apt 2.0
* Added support for Debian 8
* CentOS bugfixes
# 1.2.2 (2015.04.08)
* Bugfixes
# 1.2.1 (2015.04.06)
* Fixed refreshes
* Debian 6 support
| integratedfordevelopers/integrated-puphpet | puppet/modules/blackfire/CHANGELOG.md | Markdown | mit | 718 |
/*
* Copyright (c) 2003, 2007-11 Matteo Frigo
* Copyright (c) 2003, 2007-11 Massachusetts Institute of Technology
*
* 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
*
*/
#include SIMD_HEADER
#define VTW VTW1
#define TWVL TWVL1
#define BYTW BYTW1
#define BYTWJ BYTWJ1
#define GENUS XSIMD(dft_q1fsimd_genus)
extern const ct_genus GENUS;
| mesjetiu/grandorgue-es | src/fftw/src/dft/simd/q1f.h | C | gpl-2.0 | 1,013 |
/*
USB Driver layer for GSM modems
Copyright (C) 2005 Matthias Urlichs <[email protected]>
This driver is free software; you can redistribute it and/or modify
it under the terms of Version 2 of the GNU General Public License as
published by the Free Software Foundation.
Portions copied from the Keyspan driver by Hugh Blemings <[email protected]>
History: see the git log.
Work sponsored by: Sigos GmbH, Germany <[email protected]>
This driver exists because the "normal" serial driver doesn't work too well
with GSM modems. Issues:
- data loss -- one single Receive URB is not nearly enough
- controlling the baud rate doesn't make sense
*/
#define DRIVER_AUTHOR "Matthias Urlichs <[email protected]>"
#define DRIVER_DESC "USB Driver for GSM modems"
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/bitops.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/serial.h>
#include "usb-wwan.h"
void usb_wwan_dtr_rts(struct usb_serial_port *port, int on)
{
struct usb_wwan_port_private *portdata;
struct usb_wwan_intf_private *intfdata;
intfdata = port->serial->private;
if (!intfdata->send_setup)
return;
portdata = usb_get_serial_port_data(port);
/* FIXME: locking */
portdata->rts_state = on;
portdata->dtr_state = on;
intfdata->send_setup(port);
}
EXPORT_SYMBOL(usb_wwan_dtr_rts);
void usb_wwan_set_termios(struct tty_struct *tty,
struct usb_serial_port *port,
struct ktermios *old_termios)
{
struct usb_wwan_intf_private *intfdata = port->serial->private;
/* Doesn't support option setting */
tty_termios_copy_hw(&tty->termios, old_termios);
if (intfdata->send_setup)
intfdata->send_setup(port);
}
EXPORT_SYMBOL(usb_wwan_set_termios);
int usb_wwan_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
unsigned int value;
struct usb_wwan_port_private *portdata;
portdata = usb_get_serial_port_data(port);
value = ((portdata->rts_state) ? TIOCM_RTS : 0) |
((portdata->dtr_state) ? TIOCM_DTR : 0) |
((portdata->cts_state) ? TIOCM_CTS : 0) |
((portdata->dsr_state) ? TIOCM_DSR : 0) |
((portdata->dcd_state) ? TIOCM_CAR : 0) |
((portdata->ri_state) ? TIOCM_RNG : 0);
return value;
}
EXPORT_SYMBOL(usb_wwan_tiocmget);
int usb_wwan_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_wwan_port_private *portdata;
struct usb_wwan_intf_private *intfdata;
portdata = usb_get_serial_port_data(port);
intfdata = port->serial->private;
if (!intfdata->send_setup)
return -EINVAL;
/* FIXME: what locks portdata fields ? */
if (set & TIOCM_RTS)
portdata->rts_state = 1;
if (set & TIOCM_DTR)
portdata->dtr_state = 1;
if (clear & TIOCM_RTS)
portdata->rts_state = 0;
if (clear & TIOCM_DTR)
portdata->dtr_state = 0;
return intfdata->send_setup(port);
}
EXPORT_SYMBOL(usb_wwan_tiocmset);
static int get_serial_info(struct usb_serial_port *port,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.line = port->minor;
tmp.port = port->port_number;
tmp.baud_base = tty_get_baud_rate(port->port.tty);
tmp.close_delay = port->port.close_delay / 10;
tmp.closing_wait = port->port.closing_wait == ASYNC_CLOSING_WAIT_NONE ?
ASYNC_CLOSING_WAIT_NONE :
port->port.closing_wait / 10;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int set_serial_info(struct usb_serial_port *port,
struct serial_struct __user *newinfo)
{
struct serial_struct new_serial;
unsigned int closing_wait, close_delay;
int retval = 0;
if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
return -EFAULT;
close_delay = new_serial.close_delay * 10;
closing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ?
ASYNC_CLOSING_WAIT_NONE : new_serial.closing_wait * 10;
mutex_lock(&port->port.mutex);
if (!capable(CAP_SYS_ADMIN)) {
if ((close_delay != port->port.close_delay) ||
(closing_wait != port->port.closing_wait))
retval = -EPERM;
else
retval = -EOPNOTSUPP;
} else {
port->port.close_delay = close_delay;
port->port.closing_wait = closing_wait;
}
mutex_unlock(&port->port.mutex);
return retval;
}
int usb_wwan_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
dev_dbg(&port->dev, "%s cmd 0x%04x\n", __func__, cmd);
switch (cmd) {
case TIOCGSERIAL:
return get_serial_info(port,
(struct serial_struct __user *) arg);
case TIOCSSERIAL:
return set_serial_info(port,
(struct serial_struct __user *) arg);
default:
break;
}
dev_dbg(&port->dev, "%s arg not supported\n", __func__);
return -ENOIOCTLCMD;
}
EXPORT_SYMBOL(usb_wwan_ioctl);
/* Write */
int usb_wwan_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *buf, int count)
{
struct usb_wwan_port_private *portdata;
struct usb_wwan_intf_private *intfdata;
int i;
int left, todo;
struct urb *this_urb = NULL; /* spurious */
int err;
unsigned long flags;
portdata = usb_get_serial_port_data(port);
intfdata = port->serial->private;
dev_dbg(&port->dev, "%s: write (%d chars)\n", __func__, count);
i = 0;
left = count;
for (i = 0; left > 0 && i < N_OUT_URB; i++) {
todo = left;
if (todo > OUT_BUFLEN)
todo = OUT_BUFLEN;
this_urb = portdata->out_urbs[i];
if (test_and_set_bit(i, &portdata->out_busy)) {
if (time_before(jiffies,
portdata->tx_start_time[i] + 10 * HZ))
continue;
usb_unlink_urb(this_urb);
continue;
}
dev_dbg(&port->dev, "%s: endpoint %d buf %d\n", __func__,
usb_pipeendpoint(this_urb->pipe), i);
err = usb_autopm_get_interface_async(port->serial->interface);
if (err < 0) {
clear_bit(i, &portdata->out_busy);
break;
}
/* send the data */
memcpy(this_urb->transfer_buffer, buf, todo);
this_urb->transfer_buffer_length = todo;
spin_lock_irqsave(&intfdata->susp_lock, flags);
if (intfdata->suspended) {
usb_anchor_urb(this_urb, &portdata->delayed);
spin_unlock_irqrestore(&intfdata->susp_lock, flags);
} else {
intfdata->in_flight++;
spin_unlock_irqrestore(&intfdata->susp_lock, flags);
err = usb_submit_urb(this_urb, GFP_ATOMIC);
if (err) {
dev_dbg(&port->dev,
"usb_submit_urb %p (write bulk) failed (%d)\n",
this_urb, err);
clear_bit(i, &portdata->out_busy);
spin_lock_irqsave(&intfdata->susp_lock, flags);
intfdata->in_flight--;
spin_unlock_irqrestore(&intfdata->susp_lock,
flags);
usb_autopm_put_interface_async(port->serial->interface);
break;
}
}
portdata->tx_start_time[i] = jiffies;
buf += todo;
left -= todo;
}
count -= left;
dev_dbg(&port->dev, "%s: wrote (did %d)\n", __func__, count);
return count;
}
EXPORT_SYMBOL(usb_wwan_write);
static void usb_wwan_indat_callback(struct urb *urb)
{
int err;
int endpoint;
struct usb_serial_port *port;
struct device *dev;
unsigned char *data = urb->transfer_buffer;
int status = urb->status;
endpoint = usb_pipeendpoint(urb->pipe);
port = urb->context;
dev = &port->dev;
if (status) {
dev_dbg(dev, "%s: nonzero status: %d on endpoint %02x.\n",
__func__, status, endpoint);
} else {
if (urb->actual_length) {
tty_insert_flip_string(&port->port, data,
urb->actual_length);
tty_flip_buffer_push(&port->port);
} else
dev_dbg(dev, "%s: empty read urb received\n", __func__);
}
/* Resubmit urb so we continue receiving */
err = usb_submit_urb(urb, GFP_ATOMIC);
if (err) {
if (err != -EPERM) {
dev_err(dev, "%s: resubmit read urb failed. (%d)\n",
__func__, err);
/* busy also in error unless we are killed */
usb_mark_last_busy(port->serial->dev);
}
} else {
usb_mark_last_busy(port->serial->dev);
}
}
static void usb_wwan_outdat_callback(struct urb *urb)
{
struct usb_serial_port *port;
struct usb_wwan_port_private *portdata;
struct usb_wwan_intf_private *intfdata;
int i;
port = urb->context;
intfdata = port->serial->private;
usb_serial_port_softint(port);
usb_autopm_put_interface_async(port->serial->interface);
portdata = usb_get_serial_port_data(port);
spin_lock(&intfdata->susp_lock);
intfdata->in_flight--;
spin_unlock(&intfdata->susp_lock);
for (i = 0; i < N_OUT_URB; ++i) {
if (portdata->out_urbs[i] == urb) {
smp_mb__before_clear_bit();
clear_bit(i, &portdata->out_busy);
break;
}
}
}
int usb_wwan_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_wwan_port_private *portdata;
int i;
int data_len = 0;
struct urb *this_urb;
portdata = usb_get_serial_port_data(port);
for (i = 0; i < N_OUT_URB; i++) {
this_urb = portdata->out_urbs[i];
if (this_urb && !test_bit(i, &portdata->out_busy))
data_len += OUT_BUFLEN;
}
dev_dbg(&port->dev, "%s: %d\n", __func__, data_len);
return data_len;
}
EXPORT_SYMBOL(usb_wwan_write_room);
int usb_wwan_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_wwan_port_private *portdata;
int i;
int data_len = 0;
struct urb *this_urb;
portdata = usb_get_serial_port_data(port);
for (i = 0; i < N_OUT_URB; i++) {
this_urb = portdata->out_urbs[i];
/* FIXME: This locking is insufficient as this_urb may
go unused during the test */
if (this_urb && test_bit(i, &portdata->out_busy))
data_len += this_urb->transfer_buffer_length;
}
dev_dbg(&port->dev, "%s: %d\n", __func__, data_len);
return data_len;
}
EXPORT_SYMBOL(usb_wwan_chars_in_buffer);
int usb_wwan_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_wwan_port_private *portdata;
struct usb_wwan_intf_private *intfdata;
struct usb_serial *serial = port->serial;
int i, err;
struct urb *urb;
portdata = usb_get_serial_port_data(port);
intfdata = serial->private;
if (port->interrupt_in_urb) {
err = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (err) {
dev_dbg(&port->dev, "%s: submit int urb failed: %d\n",
__func__, err);
}
}
/* Start reading from the IN endpoint */
for (i = 0; i < N_IN_URB; i++) {
urb = portdata->in_urbs[i];
if (!urb)
continue;
err = usb_submit_urb(urb, GFP_KERNEL);
if (err) {
dev_dbg(&port->dev, "%s: submit urb %d failed (%d) %d\n",
__func__, i, err, urb->transfer_buffer_length);
}
}
if (intfdata->send_setup)
intfdata->send_setup(port);
serial->interface->needs_remote_wakeup = 1;
spin_lock_irq(&intfdata->susp_lock);
portdata->opened = 1;
spin_unlock_irq(&intfdata->susp_lock);
/* this balances a get in the generic USB serial code */
usb_autopm_put_interface(serial->interface);
return 0;
}
EXPORT_SYMBOL(usb_wwan_open);
static void unbusy_queued_urb(struct urb *urb,
struct usb_wwan_port_private *portdata)
{
int i;
for (i = 0; i < N_OUT_URB; i++) {
if (urb == portdata->out_urbs[i]) {
clear_bit(i, &portdata->out_busy);
break;
}
}
}
void usb_wwan_close(struct usb_serial_port *port)
{
int i;
struct usb_serial *serial = port->serial;
struct usb_wwan_port_private *portdata;
struct usb_wwan_intf_private *intfdata = port->serial->private;
struct urb *urb;
portdata = usb_get_serial_port_data(port);
/* Stop reading/writing urbs */
spin_lock_irq(&intfdata->susp_lock);
portdata->opened = 0;
spin_unlock_irq(&intfdata->susp_lock);
for (;;) {
urb = usb_get_from_anchor(&portdata->delayed);
if (!urb)
break;
unbusy_queued_urb(urb, portdata);
usb_autopm_put_interface_async(serial->interface);
}
for (i = 0; i < N_IN_URB; i++)
usb_kill_urb(portdata->in_urbs[i]);
for (i = 0; i < N_OUT_URB; i++)
usb_kill_urb(portdata->out_urbs[i]);
usb_kill_urb(port->interrupt_in_urb);
/* balancing - important as an error cannot be handled*/
usb_autopm_get_interface_no_resume(serial->interface);
serial->interface->needs_remote_wakeup = 0;
}
EXPORT_SYMBOL(usb_wwan_close);
/* Helper functions used by usb_wwan_setup_urbs */
static struct urb *usb_wwan_setup_urb(struct usb_serial_port *port,
int endpoint,
int dir, void *ctx, char *buf, int len,
void (*callback) (struct urb *))
{
struct usb_serial *serial = port->serial;
struct urb *urb;
urb = usb_alloc_urb(0, GFP_KERNEL); /* No ISO */
if (urb == NULL) {
dev_dbg(&serial->interface->dev,
"%s: alloc for endpoint %d failed.\n", __func__,
endpoint);
return NULL;
}
/* Fill URB using supplied data. */
usb_fill_bulk_urb(urb, serial->dev,
usb_sndbulkpipe(serial->dev, endpoint) | dir,
buf, len, callback, ctx);
return urb;
}
int usb_wwan_port_probe(struct usb_serial_port *port)
{
struct usb_wwan_port_private *portdata;
struct urb *urb;
u8 *buffer;
int i;
if (!port->bulk_in_size || !port->bulk_out_size)
return -ENODEV;
portdata = kzalloc(sizeof(*portdata), GFP_KERNEL);
if (!portdata)
return -ENOMEM;
init_usb_anchor(&portdata->delayed);
for (i = 0; i < N_IN_URB; i++) {
buffer = (u8 *)__get_free_page(GFP_KERNEL);
if (!buffer)
goto bail_out_error;
portdata->in_buffer[i] = buffer;
urb = usb_wwan_setup_urb(port, port->bulk_in_endpointAddress,
USB_DIR_IN, port,
buffer, IN_BUFLEN,
usb_wwan_indat_callback);
portdata->in_urbs[i] = urb;
}
for (i = 0; i < N_OUT_URB; i++) {
buffer = kmalloc(OUT_BUFLEN, GFP_KERNEL);
if (!buffer)
goto bail_out_error2;
portdata->out_buffer[i] = buffer;
urb = usb_wwan_setup_urb(port, port->bulk_out_endpointAddress,
USB_DIR_OUT, port,
buffer, OUT_BUFLEN,
usb_wwan_outdat_callback);
portdata->out_urbs[i] = urb;
}
usb_set_serial_port_data(port, portdata);
return 0;
bail_out_error2:
for (i = 0; i < N_OUT_URB; i++) {
usb_free_urb(portdata->out_urbs[i]);
kfree(portdata->out_buffer[i]);
}
bail_out_error:
for (i = 0; i < N_IN_URB; i++) {
usb_free_urb(portdata->in_urbs[i]);
free_page((unsigned long)portdata->in_buffer[i]);
}
kfree(portdata);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(usb_wwan_port_probe);
int usb_wwan_port_remove(struct usb_serial_port *port)
{
int i;
struct usb_wwan_port_private *portdata;
portdata = usb_get_serial_port_data(port);
usb_set_serial_port_data(port, NULL);
/* Stop reading/writing urbs and free them */
for (i = 0; i < N_IN_URB; i++) {
usb_kill_urb(portdata->in_urbs[i]);
usb_free_urb(portdata->in_urbs[i]);
free_page((unsigned long)portdata->in_buffer[i]);
}
for (i = 0; i < N_OUT_URB; i++) {
usb_kill_urb(portdata->out_urbs[i]);
usb_free_urb(portdata->out_urbs[i]);
kfree(portdata->out_buffer[i]);
}
/* Now free port private data */
kfree(portdata);
return 0;
}
EXPORT_SYMBOL(usb_wwan_port_remove);
#ifdef CONFIG_PM
static void stop_read_write_urbs(struct usb_serial *serial)
{
int i, j;
struct usb_serial_port *port;
struct usb_wwan_port_private *portdata;
/* Stop reading/writing urbs */
for (i = 0; i < serial->num_ports; ++i) {
port = serial->port[i];
portdata = usb_get_serial_port_data(port);
if (!portdata)
continue;
for (j = 0; j < N_IN_URB; j++)
usb_kill_urb(portdata->in_urbs[j]);
for (j = 0; j < N_OUT_URB; j++)
usb_kill_urb(portdata->out_urbs[j]);
}
}
int usb_wwan_suspend(struct usb_serial *serial, pm_message_t message)
{
struct usb_wwan_intf_private *intfdata = serial->private;
spin_lock_irq(&intfdata->susp_lock);
if (PMSG_IS_AUTO(message)) {
if (intfdata->in_flight) {
spin_unlock_irq(&intfdata->susp_lock);
return -EBUSY;
}
}
intfdata->suspended = 1;
spin_unlock_irq(&intfdata->susp_lock);
stop_read_write_urbs(serial);
return 0;
}
EXPORT_SYMBOL(usb_wwan_suspend);
static int play_delayed(struct usb_serial_port *port)
{
struct usb_wwan_intf_private *data;
struct usb_wwan_port_private *portdata;
struct urb *urb;
int err = 0;
portdata = usb_get_serial_port_data(port);
data = port->serial->private;
while ((urb = usb_get_from_anchor(&portdata->delayed))) {
err = usb_submit_urb(urb, GFP_ATOMIC);
if (!err) {
data->in_flight++;
} else {
/* we have to throw away the rest */
do {
unbusy_queued_urb(urb, portdata);
usb_autopm_put_interface_no_suspend(port->serial->interface);
} while ((urb = usb_get_from_anchor(&portdata->delayed)));
break;
}
}
return err;
}
int usb_wwan_resume(struct usb_serial *serial)
{
int i, j;
struct usb_serial_port *port;
struct usb_wwan_intf_private *intfdata = serial->private;
struct usb_wwan_port_private *portdata;
struct urb *urb;
int err;
int err_count = 0;
spin_lock_irq(&intfdata->susp_lock);
for (i = 0; i < serial->num_ports; i++) {
/* walk all ports */
port = serial->port[i];
portdata = usb_get_serial_port_data(port);
/* skip closed ports */
if (!portdata || !portdata->opened)
continue;
if (port->interrupt_in_urb) {
err = usb_submit_urb(port->interrupt_in_urb,
GFP_ATOMIC);
if (err) {
dev_err(&port->dev,
"%s: submit int urb failed: %d\n",
__func__, err);
err_count++;
}
}
err = play_delayed(port);
if (err)
err_count++;
for (j = 0; j < N_IN_URB; j++) {
urb = portdata->in_urbs[j];
err = usb_submit_urb(urb, GFP_ATOMIC);
if (err < 0) {
dev_err(&port->dev, "%s: Error %d for bulk URB %d\n",
__func__, err, i);
err_count++;
}
}
}
intfdata->suspended = 0;
spin_unlock_irq(&intfdata->susp_lock);
if (err_count)
return -EIO;
return 0;
}
EXPORT_SYMBOL(usb_wwan_resume);
#endif
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| Lprigara/KernelLinuxRaspberry | drivers/usb/serial/usb_wwan.c | C | gpl-2.0 | 17,776 |
/**
* Command-line tools bundled with Freenet which can be called separately
* from the node by using java -cp ... classname. Some of these are only
* of interest to devs, but @see AddRef is used on Windows to handle .fref
* files (sending them to the node as darknet references).
*/
package freenet.tools;
| xor-freenet/fred-staging | src/freenet/tools/package-info.java | Java | gpl-2.0 | 313 |
from Components.config import config, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, ConfigSelection, ConfigPassword
from Components.Console import Console
from Components.Network import iNetwork
import enigma
import os
import sys
import types
from string import maketrans, strip
from re import compile as re_compile, search as re_search, escape as re_escape
from pythonwifi.iwlibs import getNICnames, Wireless, Iwfreq, getWNICnames
from pythonwifi import flags as wififlags
list = []
list.append("Unencrypted")
list.append("WEP")
list.append("WPA")
list.append("WPA/WPA2")
list.append("WPA2")
weplist = []
weplist.append("ASCII")
weplist.append("HEX")
config.plugins.wlan = ConfigSubsection()
config.plugins.wlan.essid = NoSave(ConfigText(default = "", fixed_size = False))
config.plugins.wlan.hiddenessid = NoSave(ConfigYesNo(default = False))
config.plugins.wlan.encryption = NoSave(ConfigSelection(list, default = "WPA2"))
config.plugins.wlan.wepkeytype = NoSave(ConfigSelection(weplist, default = "ASCII"))
config.plugins.wlan.psk = NoSave(ConfigPassword(default = "", fixed_size = False))
def getWlanConfigName(iface):
return '/etc/wpa_supplicant.' + iface + '.conf'
class Wlan:
def __init__(self, iface = None):
self.iface = iface
self.oldInterfaceState = None
a = ''; b = ''
for i in range(0, 255):
a = a + chr(i)
if i < 32 or i > 127:
b = b + ' '
else:
b = b + chr(i)
self.asciitrans = maketrans(a, b)
def asciify(self, str):
return str.translate(self.asciitrans)
def getWirelessInterfaces(self):
return getWNICnames()
def setInterface(self, iface = None):
self.iface = iface
def getInterface(self):
return self.iface
def getNetworkList(self):
if self.oldInterfaceState is None:
self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
if self.oldInterfaceState is False:
if iNetwork.getAdapterAttribute(self.iface, "up") is False:
iNetwork.setAdapterAttribute(self.iface, "up", True)
enigma.eConsoleAppContainer().execute("ifconfig %s up" % self.iface)
ifobj = Wireless(self.iface) # a Wireless NIC Object
try:
scanresults = ifobj.scan()
except:
scanresults = None
print "[Wlan.py] No wireless networks could be found"
aps = {}
if scanresults is not None:
(num_channels, frequencies) = ifobj.getChannelInfo()
index = 1
for result in scanresults:
bssid = result.bssid
if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
encryption = False
elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
encryption = True
else:
encryption = None
signal = str(result.quality.siglevel-0x100) + " dBm"
quality = "%s/%s" % (result.quality.quality,ifobj.getQualityMax().quality)
extra = []
for element in result.custom:
element = element.encode()
extra.append( strip(self.asciify(element)) )
for element in extra:
if 'SignalStrength' in element:
signal = element[element.index('SignalStrength')+15:element.index(',L')]
if 'LinkQuality' in element:
quality = element[element.index('LinkQuality')+12:len(element)]
aps[bssid] = {
'active' : True,
'bssid': result.bssid,
'channel': frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
'encrypted': encryption,
'essid': strip(self.asciify(result.essid)),
'iface': self.iface,
'maxrate' : ifobj._formatBitrate(result.rate[-1][-1]),
'noise' : '',#result.quality.nlevel-0x100,
'quality' : str(quality),
'signal' : str(signal),
'custom' : extra,
}
index = index + 1
return aps
def stopGetNetworkList(self):
if self.oldInterfaceState is not None:
if self.oldInterfaceState is False:
iNetwork.setAdapterAttribute(self.iface, "up", False)
enigma.eConsoleAppContainer().execute("ifconfig %s down" % self.iface)
self.oldInterfaceState = None
self.iface = None
iWlan = Wlan()
class wpaSupplicant:
def __init__(self):
pass
def writeConfig(self, iface):
essid = config.plugins.wlan.essid.value
hiddenessid = config.plugins.wlan.hiddenessid.value
encryption = config.plugins.wlan.encryption.value
wepkeytype = config.plugins.wlan.wepkeytype.value
psk = config.plugins.wlan.psk.value
fp = file(getWlanConfigName(iface), 'w')
fp.write('#WPA Supplicant Configuration by enigma2\n')
fp.write('ctrl_interface=/var/run/wpa_supplicant\n')
fp.write('eapol_version=1\n')
fp.write('fast_reauth=1\n')
fp.write('ap_scan=1\n')
fp.write('network={\n')
fp.write('\tssid="'+essid+'"\n')
if hiddenessid:
fp.write('\tscan_ssid=1\n')
else:
fp.write('\tscan_ssid=0\n')
if encryption in ('WPA', 'WPA2', 'WPA/WPA2'):
fp.write('\tkey_mgmt=WPA-PSK\n')
if encryption == 'WPA':
fp.write('\tproto=WPA\n')
fp.write('\tpairwise=TKIP\n')
fp.write('\tgroup=TKIP\n')
elif encryption == 'WPA2':
fp.write('\tproto=RSN\n')
fp.write('\tpairwise=CCMP\n')
fp.write('\tgroup=CCMP\n')
else:
fp.write('\tproto=WPA RSN\n')
fp.write('\tpairwise=CCMP TKIP\n')
fp.write('\tgroup=CCMP TKIP\n')
fp.write('\tpsk="'+psk+'"\n')
elif encryption == 'WEP':
fp.write('\tkey_mgmt=NONE\n')
if wepkeytype == 'ASCII':
fp.write('\twep_key0="'+psk+'"\n')
else:
fp.write('\twep_key0='+psk+'\n')
else:
fp.write('\tkey_mgmt=NONE\n')
fp.write('}')
fp.write('\n')
fp.close()
#system('cat ' + getWlanConfigName(iface))
def loadConfig(self,iface):
configfile = getWlanConfigName(iface)
if not os.path.exists(configfile):
configfile = '/etc/wpa_supplicant.conf'
try:
#parse the wpasupplicant configfile
print "[Wlan.py] parsing configfile: ",configfile
fp = file(configfile, 'r')
supplicant = fp.readlines()
fp.close()
essid = None
encryption = "Unencrypted"
for s in supplicant:
split = s.strip().split('=',1)
if split[0] == 'scan_ssid':
if split[1] == '1':
config.plugins.wlan.hiddenessid.value = True
else:
config.plugins.wlan.hiddenessid.value = False
elif split[0] == 'ssid':
essid = split[1][1:-1]
config.plugins.wlan.essid.value = essid
elif split[0] == 'proto':
if split[1] == 'WPA' :
mode = 'WPA'
if split[1] == 'RSN':
mode = 'WPA2'
if split[1] in ('WPA RSN', 'WPA WPA2'):
mode = 'WPA/WPA2'
encryption = mode
elif split[0] == 'wep_key0':
encryption = 'WEP'
if split[1].startswith('"') and split[1].endswith('"'):
config.plugins.wlan.wepkeytype.value = 'ASCII'
config.plugins.wlan.psk.value = split[1][1:-1]
else:
config.plugins.wlan.wepkeytype.value = 'HEX'
config.plugins.wlan.psk.value = split[1]
elif split[0] == 'psk':
config.plugins.wlan.psk.value = split[1][1:-1]
else:
pass
config.plugins.wlan.encryption.value = encryption
wsconfig = {
'hiddenessid': config.plugins.wlan.hiddenessid.value,
'ssid': config.plugins.wlan.essid.value,
'encryption': config.plugins.wlan.encryption.value,
'wepkeytype': config.plugins.wlan.wepkeytype.value,
'key': config.plugins.wlan.psk.value,
}
for (key, item) in wsconfig.items():
if item is "None" or item is "":
if key == 'hiddenessid':
wsconfig['hiddenessid'] = False
if key == 'ssid':
wsconfig['ssid'] = ""
if key == 'encryption':
wsconfig['encryption'] = "WPA2"
if key == 'wepkeytype':
wsconfig['wepkeytype'] = "ASCII"
if key == 'key':
wsconfig['key'] = ""
except:
print "[Wlan.py] Error parsing ",configfile
wsconfig = {
'hiddenessid': False,
'ssid': "",
'encryption': "WPA2",
'wepkeytype': "ASCII",
'key': "",
}
#print "[Wlan.py] WS-CONFIG-->",wsconfig
return wsconfig
class Status:
def __init__(self):
self.wlaniface = {}
self.backupwlaniface = {}
self.statusCallback = None
self.WlanConsole = Console()
def stopWlanConsole(self):
if self.WlanConsole is not None:
print "[iStatus] killing self.WlanConsole"
self.WlanConsole.killAll()
self.WlanConsole = None
def getDataForInterface(self, iface, callback = None):
self.WlanConsole = Console()
cmd = "iwconfig " + iface
if callback is not None:
self.statusCallback = callback
self.WlanConsole.ePopen(cmd, self.iwconfigFinished, iface)
def iwconfigFinished(self, result, retval, extra_args):
iface = extra_args
data = { 'essid': False, 'frequency': False, 'accesspoint': False, 'bitrate': False, 'encryption': False, 'quality': False, 'signal': False }
for line in result.splitlines():
line = line.strip()
if "ESSID" in line:
if "off/any" in line:
ssid = "off"
else:
if "Nickname" in line:
ssid=(line[line.index('ESSID')+7:line.index('" Nickname')])
else:
ssid=(line[line.index('ESSID')+7:len(line)-1])
if ssid is not None:
data['essid'] = ssid
if "Frequency" in line:
frequency = line[line.index('Frequency')+10 :line.index(' GHz')]
if frequency is not None:
data['frequency'] = frequency
if "Access Point" in line:
if "Sensitivity" in line:
ap=line[line.index('Access Point')+14:line.index(' Sensitivity')]
else:
ap=line[line.index('Access Point')+14:len(line)]
if ap is not None:
data['accesspoint'] = ap
if "Bit Rate" in line:
if "kb" in line:
br = line[line.index('Bit Rate')+9 :line.index(' kb/s')]
else:
br = line[line.index('Bit Rate')+9 :line.index(' Mb/s')]
if br is not None:
data['bitrate'] = br
if "Encryption key" in line:
if ":off" in line:
enc = "off"
elif "Security" in line:
enc = line[line.index('Encryption key')+15 :line.index(' Security')]
if enc is not None:
enc = "on"
else:
enc = line[line.index('Encryption key')+15 :len(line)]
if enc is not None:
enc = "on"
if enc is not None:
data['encryption'] = enc
if 'Quality' in line:
if "/100" in line:
qual = line[line.index('Quality')+8:line.index(' Signal')]
else:
qual = line[line.index('Quality')+8:line.index('Sig')]
if qual is not None:
data['quality'] = qual
if 'Signal level' in line:
if "dBm" in line:
signal = line[line.index('Signal level')+13 :line.index(' dBm')] + " dBm"
elif "/100" in line:
if "Noise" in line:
signal = line[line.index('Signal level')+13:line.index(' Noise')]
else:
signal = line[line.index('Signal level')+13:len(line)]
else:
if "Noise" in line:
signal = line[line.index('Signal level')+13:line.index(' Noise')]
else:
signal = line[line.index('Signal level')+13:len(line)]
if signal is not None:
data['signal'] = signal
self.wlaniface[iface] = data
self.backupwlaniface = self.wlaniface
if self.WlanConsole is not None:
if len(self.WlanConsole.appContainers) == 0:
print "[Wlan.py] self.wlaniface after loading:", self.wlaniface
if self.statusCallback is not None:
self.statusCallback(True,self.wlaniface)
self.statusCallback = None
def getAdapterAttribute(self, iface, attribute):
self.iface = iface
if self.wlaniface.has_key(self.iface):
if self.wlaniface[self.iface].has_key(attribute):
return self.wlaniface[self.iface][attribute]
return None
iStatus = Status()
| kingvuplus/rr | lib/python/Plugins/SystemPlugins/WirelessLan/Wlan.py | Python | gpl-2.0 | 11,316 |
/*
* Based on arch/arm/kernel/armksyms.c
*
* Copyright (C) 2000 Russell King
* Copyright (C) 2012 ARM Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/export.h>
#include "exynos-memcpy.h"
#ifdef CONFIG_SOC_EXYNOS8890
EXPORT_SYMBOL(__copy_to_user_pld2);
EXPORT_SYMBOL(memcpy_pld2);
#endif
| morogoku/MoRoKernel-S7-v2 | drivers/soc/samsung/memory/syms.c | C | gpl-2.0 | 854 |
/* http://keith-wood.name/countdown.html
* Spanish initialisation for the jQuery countdown extension
* Written by Sergio Carracedo Martinez [email protected] (2008) */
(function($) {
$.countdown.regionalOptions['es'] = {
labels: ['Años', 'Meses', 'Semanas', 'Días', 'Horas', 'Minutos', 'Segundos'],
labels1: ['Año', 'Mes', 'Semana', 'Día', 'Hora', 'Minuto', 'Segundo'],
compactLabels: ['a', 'm', 's', 'd'],
whichLabels: null,
digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
timeSeparator: ':', isRTL: false};
$.countdown.setDefaults($.countdown.regionalOptions['es']);
})(jQuery);
| hikaram/wee | wp-content/themes/wee/libs/countdown/jquery.countdown-es.js | JavaScript | gpl-2.0 | 638 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2005,2006,2007 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <[email protected]>
*/
#include "ipv4-interface.h"
#include "loopback-net-device.h"
#include "ipv4-l3-protocol.h"
#include "ipv4-queue-disc-item.h"
#include "arp-l3-protocol.h"
#include "arp-cache.h"
#include "ns3/net-device.h"
#include "ns3/log.h"
#include "ns3/packet.h"
#include "ns3/node.h"
#include "ns3/pointer.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("Ipv4Interface");
NS_OBJECT_ENSURE_REGISTERED (Ipv4Interface);
TypeId
Ipv4Interface::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::Ipv4Interface")
.SetParent<Object> ()
.SetGroupName ("Internet")
.AddAttribute ("ArpCache",
"The arp cache for this ipv4 interface",
PointerValue (0),
MakePointerAccessor (&Ipv4Interface::SetArpCache,
&Ipv4Interface::GetArpCache),
MakePointerChecker<ArpCache> ())
;
;
return tid;
}
/**
* By default, Ipv4 interface are created in the "down" state
* with no IP addresses. Before becoming useable, the user must
* invoke SetUp on them once an Ipv4 address and mask have been set.
*/
Ipv4Interface::Ipv4Interface ()
: m_ifup (false),
m_forwarding (true),
m_metric (1),
m_node (0),
m_device (0),
m_tc (0),
m_cache (0)
{
NS_LOG_FUNCTION (this);
}
Ipv4Interface::~Ipv4Interface ()
{
NS_LOG_FUNCTION (this);
}
void
Ipv4Interface::DoDispose (void)
{
NS_LOG_FUNCTION (this);
m_node = 0;
m_device = 0;
m_tc = 0;
m_cache = 0;
Object::DoDispose ();
}
void
Ipv4Interface::SetNode (Ptr<Node> node)
{
NS_LOG_FUNCTION (this << node);
m_node = node;
DoSetup ();
}
void
Ipv4Interface::SetDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
m_device = device;
DoSetup ();
}
void
Ipv4Interface::SetTrafficControl (Ptr<TrafficControlLayer> tc)
{
NS_LOG_FUNCTION (this << tc);
m_tc = tc;
}
void
Ipv4Interface::DoSetup (void)
{
NS_LOG_FUNCTION (this);
if (m_node == 0 || m_device == 0)
{
return;
}
if (!m_device->NeedsArp ())
{
return;
}
Ptr<ArpL3Protocol> arp = m_node->GetObject<ArpL3Protocol> ();
m_cache = arp->CreateCache (m_device, this);
}
Ptr<NetDevice>
Ipv4Interface::GetDevice (void) const
{
NS_LOG_FUNCTION (this);
return m_device;
}
void
Ipv4Interface::SetMetric (uint16_t metric)
{
NS_LOG_FUNCTION (this << metric);
m_metric = metric;
}
uint16_t
Ipv4Interface::GetMetric (void) const
{
NS_LOG_FUNCTION (this);
return m_metric;
}
void
Ipv4Interface::SetArpCache (Ptr<ArpCache> a)
{
NS_LOG_FUNCTION (this << a);
m_cache = a;
}
Ptr<ArpCache>
Ipv4Interface::GetArpCache () const
{
NS_LOG_FUNCTION (this);
return m_cache;
}
/**
* These are IP interface states and may be distinct from
* NetDevice states, such as found in real implementations
* (where the device may be down but IP interface state is still up).
*/
bool
Ipv4Interface::IsUp (void) const
{
NS_LOG_FUNCTION (this);
return m_ifup;
}
bool
Ipv4Interface::IsDown (void) const
{
NS_LOG_FUNCTION (this);
return !m_ifup;
}
void
Ipv4Interface::SetUp (void)
{
NS_LOG_FUNCTION (this);
m_ifup = true;
}
void
Ipv4Interface::SetDown (void)
{
NS_LOG_FUNCTION (this);
m_ifup = false;
}
bool
Ipv4Interface::IsForwarding (void) const
{
NS_LOG_FUNCTION (this);
return m_forwarding;
}
void
Ipv4Interface::SetForwarding (bool val)
{
NS_LOG_FUNCTION (this << val);
m_forwarding = val;
}
void
Ipv4Interface::Send (Ptr<Packet> p, const Ipv4Header & hdr, Ipv4Address dest)
{
NS_LOG_FUNCTION (this << *p << dest);
if (!IsUp ())
{
return;
}
// Check for a loopback device, if it's the case we don't pass through
// traffic control layer
if (DynamicCast<LoopbackNetDevice> (m_device))
{
/// \todo additional checks needed here (such as whether multicast
/// goes to loopback)?
p->AddHeader (hdr);
m_device->Send (p, m_device->GetBroadcast (), Ipv4L3Protocol::PROT_NUMBER);
return;
}
NS_ASSERT (m_tc != 0);
// is this packet aimed at a local interface ?
for (Ipv4InterfaceAddressListCI i = m_ifaddrs.begin (); i != m_ifaddrs.end (); ++i)
{
if (dest == (*i).GetLocal ())
{
p->AddHeader (hdr);
m_tc->Receive (m_device, p, Ipv4L3Protocol::PROT_NUMBER,
m_device->GetBroadcast (),
m_device->GetBroadcast (),
NetDevice::PACKET_HOST);
return;
}
}
if (m_device->NeedsArp ())
{
NS_LOG_LOGIC ("Needs ARP" << " " << dest);
Ptr<ArpL3Protocol> arp = m_node->GetObject<ArpL3Protocol> ();
Address hardwareDestination;
bool found = false;
if (dest.IsBroadcast ())
{
NS_LOG_LOGIC ("All-network Broadcast");
hardwareDestination = m_device->GetBroadcast ();
found = true;
}
else if (dest.IsMulticast ())
{
NS_LOG_LOGIC ("IsMulticast");
NS_ASSERT_MSG (m_device->IsMulticast (),
"ArpIpv4Interface::SendTo (): Sending multicast packet over "
"non-multicast device");
hardwareDestination = m_device->GetMulticast (dest);
found = true;
}
else
{
for (Ipv4InterfaceAddressListCI i = m_ifaddrs.begin (); i != m_ifaddrs.end (); ++i)
{
if (dest.IsSubnetDirectedBroadcast ((*i).GetMask ()))
{
NS_LOG_LOGIC ("Subnetwork Broadcast");
hardwareDestination = m_device->GetBroadcast ();
found = true;
break;
}
}
if (!found)
{
NS_LOG_LOGIC ("ARP Lookup");
found = arp->Lookup (p, hdr, dest, m_device, m_cache, &hardwareDestination);
}
}
if (found)
{
NS_LOG_LOGIC ("Address Resolved. Send.");
m_tc->Send (m_device, Create<Ipv4QueueDiscItem> (p, hardwareDestination, Ipv4L3Protocol::PROT_NUMBER, hdr));
}
}
else
{
NS_LOG_LOGIC ("Doesn't need ARP");
m_tc->Send (m_device, Create<Ipv4QueueDiscItem> (p, m_device->GetBroadcast (), Ipv4L3Protocol::PROT_NUMBER, hdr));
}
}
uint32_t
Ipv4Interface::GetNAddresses (void) const
{
NS_LOG_FUNCTION (this);
return m_ifaddrs.size ();
}
bool
Ipv4Interface::AddAddress (Ipv4InterfaceAddress addr)
{
NS_LOG_FUNCTION (this << addr);
m_ifaddrs.push_back (addr);
return true;
}
Ipv4InterfaceAddress
Ipv4Interface::GetAddress (uint32_t index) const
{
NS_LOG_FUNCTION (this << index);
if (index < m_ifaddrs.size ())
{
uint32_t tmp = 0;
for (Ipv4InterfaceAddressListCI i = m_ifaddrs.begin (); i!= m_ifaddrs.end (); i++)
{
if (tmp == index)
{
return *i;
}
++tmp;
}
}
NS_ASSERT (false); // Assert if not found
Ipv4InterfaceAddress addr;
return (addr); // quiet compiler
}
Ipv4InterfaceAddress
Ipv4Interface::RemoveAddress (uint32_t index)
{
NS_LOG_FUNCTION (this << index);
if (index >= m_ifaddrs.size ())
{
NS_ASSERT_MSG (false, "Bug in Ipv4Interface::RemoveAddress");
}
Ipv4InterfaceAddressListI i = m_ifaddrs.begin ();
uint32_t tmp = 0;
while (i != m_ifaddrs.end ())
{
if (tmp == index)
{
Ipv4InterfaceAddress addr = *i;
m_ifaddrs.erase (i);
return addr;
}
++tmp;
++i;
}
NS_ASSERT_MSG (false, "Address " << index << " not found");
Ipv4InterfaceAddress addr;
return (addr); // quiet compiler
}
Ipv4InterfaceAddress
Ipv4Interface::RemoveAddress(Ipv4Address address)
{
NS_LOG_FUNCTION(this << address);
if (address == address.GetLoopback())
{
NS_LOG_WARN ("Cannot remove loopback address.");
return Ipv4InterfaceAddress();
}
for(Ipv4InterfaceAddressListI it = m_ifaddrs.begin(); it != m_ifaddrs.end(); it++)
{
if((*it).GetLocal() == address)
{
Ipv4InterfaceAddress ifAddr = *it;
m_ifaddrs.erase(it);
return ifAddr;
}
}
return Ipv4InterfaceAddress();
}
} // namespace ns3
| manoj24rana/MobileIPv6 | src/internet/model/ipv4-interface.cc | C++ | gpl-2.0 | 9,045 |
/*
Linux Driver for Mylex DAC960/AcceleRAID/eXtremeRAID PCI RAID Controllers
Copyright 1998-2001 by Leonard N. Zubkoff <[email protected]>
Portions Copyright 2002 by Mylex (An IBM Business Unit)
This program is free software; you may redistribute and/or modify it under
the terms of the GNU General Public License Version 2 as published by the
Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for complete details.
*/
#define DAC960_DriverVersion "2.5.49"
#define DAC960_DriverDate "21 Aug 2007"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/miscdevice.h>
#include <linux/blkdev.h>
#include <linux/bio.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/genhd.h>
#include <linux/hdreg.h>
#include <linux/blkpg.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
#include <linux/reboot.h>
#include <linux/spinlock.h>
#include <linux/timer.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/random.h>
#include <linux/scatterlist.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include "DAC960.h"
#define DAC960_GAM_MINOR 252
static DAC960_Controller_T *DAC960_Controllers[DAC960_MaxControllers];
static int DAC960_ControllerCount;
static struct proc_dir_entry *DAC960_ProcDirectoryEntry;
static long disk_size(DAC960_Controller_T *p, int drive_nr)
{
if (p->FirmwareType == DAC960_V1_Controller) {
if (drive_nr >= p->LogicalDriveCount)
return 0;
return p->V1.LogicalDriveInformation[drive_nr].
LogicalDriveSize;
} else {
DAC960_V2_LogicalDeviceInfo_T *i =
p->V2.LogicalDeviceInformation[drive_nr];
if (i == NULL)
return 0;
return i->ConfigurableDeviceSize;
}
}
static int DAC960_open(struct inode *inode, struct file *file)
{
struct gendisk *disk = inode->i_bdev->bd_disk;
DAC960_Controller_T *p = disk->queue->queuedata;
int drive_nr = (long)disk->private_data;
if (p->FirmwareType == DAC960_V1_Controller) {
if (p->V1.LogicalDriveInformation[drive_nr].
LogicalDriveState == DAC960_V1_LogicalDrive_Offline)
return -ENXIO;
} else {
DAC960_V2_LogicalDeviceInfo_T *i =
p->V2.LogicalDeviceInformation[drive_nr];
if (!i || i->LogicalDeviceState == DAC960_V2_LogicalDevice_Offline)
return -ENXIO;
}
check_disk_change(inode->i_bdev);
if (!get_capacity(p->disks[drive_nr]))
return -ENXIO;
return 0;
}
static int DAC960_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct gendisk *disk = bdev->bd_disk;
DAC960_Controller_T *p = disk->queue->queuedata;
int drive_nr = (long)disk->private_data;
if (p->FirmwareType == DAC960_V1_Controller) {
geo->heads = p->V1.GeometryTranslationHeads;
geo->sectors = p->V1.GeometryTranslationSectors;
geo->cylinders = p->V1.LogicalDriveInformation[drive_nr].
LogicalDriveSize / (geo->heads * geo->sectors);
} else {
DAC960_V2_LogicalDeviceInfo_T *i =
p->V2.LogicalDeviceInformation[drive_nr];
switch (i->DriveGeometry) {
case DAC960_V2_Geometry_128_32:
geo->heads = 128;
geo->sectors = 32;
break;
case DAC960_V2_Geometry_255_63:
geo->heads = 255;
geo->sectors = 63;
break;
default:
DAC960_Error("Illegal Logical Device Geometry %d\n",
p, i->DriveGeometry);
return -EINVAL;
}
geo->cylinders = i->ConfigurableDeviceSize /
(geo->heads * geo->sectors);
}
return 0;
}
static int DAC960_media_changed(struct gendisk *disk)
{
DAC960_Controller_T *p = disk->queue->queuedata;
int drive_nr = (long)disk->private_data;
if (!p->LogicalDriveInitiallyAccessible[drive_nr])
return 1;
return 0;
}
static int DAC960_revalidate_disk(struct gendisk *disk)
{
DAC960_Controller_T *p = disk->queue->queuedata;
int unit = (long)disk->private_data;
set_capacity(disk, disk_size(p, unit));
return 0;
}
static struct block_device_operations DAC960_BlockDeviceOperations = {
.owner = THIS_MODULE,
.open = DAC960_open,
.getgeo = DAC960_getgeo,
.media_changed = DAC960_media_changed,
.revalidate_disk = DAC960_revalidate_disk,
};
/*
DAC960_AnnounceDriver announces the Driver Version and Date, Author's Name,
Copyright Notice, and Electronic Mail Address.
*/
static void DAC960_AnnounceDriver(DAC960_Controller_T *Controller)
{
DAC960_Announce("***** DAC960 RAID Driver Version "
DAC960_DriverVersion " of "
DAC960_DriverDate " *****\n", Controller);
DAC960_Announce("Copyright 1998-2001 by Leonard N. Zubkoff "
"<[email protected]>\n", Controller);
}
/*
DAC960_Failure prints a standardized error message, and then returns false.
*/
static bool DAC960_Failure(DAC960_Controller_T *Controller,
unsigned char *ErrorMessage)
{
DAC960_Error("While configuring DAC960 PCI RAID Controller at\n",
Controller);
if (Controller->IO_Address == 0)
DAC960_Error("PCI Bus %d Device %d Function %d I/O Address N/A "
"PCI Address 0x%X\n", Controller,
Controller->Bus, Controller->Device,
Controller->Function, Controller->PCI_Address);
else DAC960_Error("PCI Bus %d Device %d Function %d I/O Address "
"0x%X PCI Address 0x%X\n", Controller,
Controller->Bus, Controller->Device,
Controller->Function, Controller->IO_Address,
Controller->PCI_Address);
DAC960_Error("%s FAILED - DETACHING\n", Controller, ErrorMessage);
return false;
}
/*
init_dma_loaf() and slice_dma_loaf() are helper functions for
aggregating the dma-mapped memory for a well-known collection of
data structures that are of different lengths.
These routines don't guarantee any alignment. The caller must
include any space needed for alignment in the sizes of the structures
that are passed in.
*/
static bool init_dma_loaf(struct pci_dev *dev, struct dma_loaf *loaf,
size_t len)
{
void *cpu_addr;
dma_addr_t dma_handle;
cpu_addr = pci_alloc_consistent(dev, len, &dma_handle);
if (cpu_addr == NULL)
return false;
loaf->cpu_free = loaf->cpu_base = cpu_addr;
loaf->dma_free =loaf->dma_base = dma_handle;
loaf->length = len;
memset(cpu_addr, 0, len);
return true;
}
static void *slice_dma_loaf(struct dma_loaf *loaf, size_t len,
dma_addr_t *dma_handle)
{
void *cpu_end = loaf->cpu_free + len;
void *cpu_addr = loaf->cpu_free;
BUG_ON(cpu_end > loaf->cpu_base + loaf->length);
*dma_handle = loaf->dma_free;
loaf->cpu_free = cpu_end;
loaf->dma_free += len;
return cpu_addr;
}
static void free_dma_loaf(struct pci_dev *dev, struct dma_loaf *loaf_handle)
{
if (loaf_handle->cpu_base != NULL)
pci_free_consistent(dev, loaf_handle->length,
loaf_handle->cpu_base, loaf_handle->dma_base);
}
/*
DAC960_CreateAuxiliaryStructures allocates and initializes the auxiliary
data structures for Controller. It returns true on success and false on
failure.
*/
static bool DAC960_CreateAuxiliaryStructures(DAC960_Controller_T *Controller)
{
int CommandAllocationLength, CommandAllocationGroupSize;
int CommandsRemaining = 0, CommandIdentifier, CommandGroupByteCount;
void *AllocationPointer = NULL;
void *ScatterGatherCPU = NULL;
dma_addr_t ScatterGatherDMA;
struct pci_pool *ScatterGatherPool;
void *RequestSenseCPU = NULL;
dma_addr_t RequestSenseDMA;
struct pci_pool *RequestSensePool = NULL;
if (Controller->FirmwareType == DAC960_V1_Controller)
{
CommandAllocationLength = offsetof(DAC960_Command_T, V1.EndMarker);
CommandAllocationGroupSize = DAC960_V1_CommandAllocationGroupSize;
ScatterGatherPool = pci_pool_create("DAC960_V1_ScatterGather",
Controller->PCIDevice,
DAC960_V1_ScatterGatherLimit * sizeof(DAC960_V1_ScatterGatherSegment_T),
sizeof(DAC960_V1_ScatterGatherSegment_T), 0);
if (ScatterGatherPool == NULL)
return DAC960_Failure(Controller,
"AUXILIARY STRUCTURE CREATION (SG)");
Controller->ScatterGatherPool = ScatterGatherPool;
}
else
{
CommandAllocationLength = offsetof(DAC960_Command_T, V2.EndMarker);
CommandAllocationGroupSize = DAC960_V2_CommandAllocationGroupSize;
ScatterGatherPool = pci_pool_create("DAC960_V2_ScatterGather",
Controller->PCIDevice,
DAC960_V2_ScatterGatherLimit * sizeof(DAC960_V2_ScatterGatherSegment_T),
sizeof(DAC960_V2_ScatterGatherSegment_T), 0);
if (ScatterGatherPool == NULL)
return DAC960_Failure(Controller,
"AUXILIARY STRUCTURE CREATION (SG)");
RequestSensePool = pci_pool_create("DAC960_V2_RequestSense",
Controller->PCIDevice, sizeof(DAC960_SCSI_RequestSense_T),
sizeof(int), 0);
if (RequestSensePool == NULL) {
pci_pool_destroy(ScatterGatherPool);
return DAC960_Failure(Controller,
"AUXILIARY STRUCTURE CREATION (SG)");
}
Controller->ScatterGatherPool = ScatterGatherPool;
Controller->V2.RequestSensePool = RequestSensePool;
}
Controller->CommandAllocationGroupSize = CommandAllocationGroupSize;
Controller->FreeCommands = NULL;
for (CommandIdentifier = 1;
CommandIdentifier <= Controller->DriverQueueDepth;
CommandIdentifier++)
{
DAC960_Command_T *Command;
if (--CommandsRemaining <= 0)
{
CommandsRemaining =
Controller->DriverQueueDepth - CommandIdentifier + 1;
if (CommandsRemaining > CommandAllocationGroupSize)
CommandsRemaining = CommandAllocationGroupSize;
CommandGroupByteCount =
CommandsRemaining * CommandAllocationLength;
AllocationPointer = kzalloc(CommandGroupByteCount, GFP_ATOMIC);
if (AllocationPointer == NULL)
return DAC960_Failure(Controller,
"AUXILIARY STRUCTURE CREATION");
}
Command = (DAC960_Command_T *) AllocationPointer;
AllocationPointer += CommandAllocationLength;
Command->CommandIdentifier = CommandIdentifier;
Command->Controller = Controller;
Command->Next = Controller->FreeCommands;
Controller->FreeCommands = Command;
Controller->Commands[CommandIdentifier-1] = Command;
ScatterGatherCPU = pci_pool_alloc(ScatterGatherPool, GFP_ATOMIC,
&ScatterGatherDMA);
if (ScatterGatherCPU == NULL)
return DAC960_Failure(Controller, "AUXILIARY STRUCTURE CREATION");
if (RequestSensePool != NULL) {
RequestSenseCPU = pci_pool_alloc(RequestSensePool, GFP_ATOMIC,
&RequestSenseDMA);
if (RequestSenseCPU == NULL) {
pci_pool_free(ScatterGatherPool, ScatterGatherCPU,
ScatterGatherDMA);
return DAC960_Failure(Controller,
"AUXILIARY STRUCTURE CREATION");
}
}
if (Controller->FirmwareType == DAC960_V1_Controller) {
Command->cmd_sglist = Command->V1.ScatterList;
Command->V1.ScatterGatherList =
(DAC960_V1_ScatterGatherSegment_T *)ScatterGatherCPU;
Command->V1.ScatterGatherListDMA = ScatterGatherDMA;
sg_init_table(Command->cmd_sglist, DAC960_V1_ScatterGatherLimit);
} else {
Command->cmd_sglist = Command->V2.ScatterList;
Command->V2.ScatterGatherList =
(DAC960_V2_ScatterGatherSegment_T *)ScatterGatherCPU;
Command->V2.ScatterGatherListDMA = ScatterGatherDMA;
Command->V2.RequestSense =
(DAC960_SCSI_RequestSense_T *)RequestSenseCPU;
Command->V2.RequestSenseDMA = RequestSenseDMA;
sg_init_table(Command->cmd_sglist, DAC960_V2_ScatterGatherLimit);
}
}
return true;
}
/*
DAC960_DestroyAuxiliaryStructures deallocates the auxiliary data
structures for Controller.
*/
static void DAC960_DestroyAuxiliaryStructures(DAC960_Controller_T *Controller)
{
int i;
struct pci_pool *ScatterGatherPool = Controller->ScatterGatherPool;
struct pci_pool *RequestSensePool = NULL;
void *ScatterGatherCPU;
dma_addr_t ScatterGatherDMA;
void *RequestSenseCPU;
dma_addr_t RequestSenseDMA;
DAC960_Command_T *CommandGroup = NULL;
if (Controller->FirmwareType == DAC960_V2_Controller)
RequestSensePool = Controller->V2.RequestSensePool;
Controller->FreeCommands = NULL;
for (i = 0; i < Controller->DriverQueueDepth; i++)
{
DAC960_Command_T *Command = Controller->Commands[i];
if (Command == NULL)
continue;
if (Controller->FirmwareType == DAC960_V1_Controller) {
ScatterGatherCPU = (void *)Command->V1.ScatterGatherList;
ScatterGatherDMA = Command->V1.ScatterGatherListDMA;
RequestSenseCPU = NULL;
RequestSenseDMA = (dma_addr_t)0;
} else {
ScatterGatherCPU = (void *)Command->V2.ScatterGatherList;
ScatterGatherDMA = Command->V2.ScatterGatherListDMA;
RequestSenseCPU = (void *)Command->V2.RequestSense;
RequestSenseDMA = Command->V2.RequestSenseDMA;
}
if (ScatterGatherCPU != NULL)
pci_pool_free(ScatterGatherPool, ScatterGatherCPU, ScatterGatherDMA);
if (RequestSenseCPU != NULL)
pci_pool_free(RequestSensePool, RequestSenseCPU, RequestSenseDMA);
if ((Command->CommandIdentifier
% Controller->CommandAllocationGroupSize) == 1) {
/*
* We can't free the group of commands until all of the
* request sense and scatter gather dma structures are free.
* Remember the beginning of the group, but don't free it
* until we've reached the beginning of the next group.
*/
kfree(CommandGroup);
CommandGroup = Command;
}
Controller->Commands[i] = NULL;
}
kfree(CommandGroup);
if (Controller->CombinedStatusBuffer != NULL)
{
kfree(Controller->CombinedStatusBuffer);
Controller->CombinedStatusBuffer = NULL;
Controller->CurrentStatusBuffer = NULL;
}
if (ScatterGatherPool != NULL)
pci_pool_destroy(ScatterGatherPool);
if (Controller->FirmwareType == DAC960_V1_Controller)
return;
if (RequestSensePool != NULL)
pci_pool_destroy(RequestSensePool);
for (i = 0; i < DAC960_MaxLogicalDrives; i++) {
kfree(Controller->V2.LogicalDeviceInformation[i]);
Controller->V2.LogicalDeviceInformation[i] = NULL;
}
for (i = 0; i < DAC960_V2_MaxPhysicalDevices; i++)
{
kfree(Controller->V2.PhysicalDeviceInformation[i]);
Controller->V2.PhysicalDeviceInformation[i] = NULL;
kfree(Controller->V2.InquiryUnitSerialNumber[i]);
Controller->V2.InquiryUnitSerialNumber[i] = NULL;
}
}
/*
DAC960_V1_ClearCommand clears critical fields of Command for DAC960 V1
Firmware Controllers.
*/
static inline void DAC960_V1_ClearCommand(DAC960_Command_T *Command)
{
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
memset(CommandMailbox, 0, sizeof(DAC960_V1_CommandMailbox_T));
Command->V1.CommandStatus = 0;
}
/*
DAC960_V2_ClearCommand clears critical fields of Command for DAC960 V2
Firmware Controllers.
*/
static inline void DAC960_V2_ClearCommand(DAC960_Command_T *Command)
{
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
memset(CommandMailbox, 0, sizeof(DAC960_V2_CommandMailbox_T));
Command->V2.CommandStatus = 0;
}
/*
DAC960_AllocateCommand allocates a Command structure from Controller's
free list. During driver initialization, a special initialization command
has been placed on the free list to guarantee that command allocation can
never fail.
*/
static inline DAC960_Command_T *DAC960_AllocateCommand(DAC960_Controller_T
*Controller)
{
DAC960_Command_T *Command = Controller->FreeCommands;
if (Command == NULL) return NULL;
Controller->FreeCommands = Command->Next;
Command->Next = NULL;
return Command;
}
/*
DAC960_DeallocateCommand deallocates Command, returning it to Controller's
free list.
*/
static inline void DAC960_DeallocateCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
Command->Request = NULL;
Command->Next = Controller->FreeCommands;
Controller->FreeCommands = Command;
}
/*
DAC960_WaitForCommand waits for a wake_up on Controller's Command Wait Queue.
*/
static void DAC960_WaitForCommand(DAC960_Controller_T *Controller)
{
spin_unlock_irq(&Controller->queue_lock);
__wait_event(Controller->CommandWaitQueue, Controller->FreeCommands);
spin_lock_irq(&Controller->queue_lock);
}
/*
DAC960_GEM_QueueCommand queues Command for DAC960 GEM Series Controllers.
*/
static void DAC960_GEM_QueueCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandMailbox_T *NextCommandMailbox =
Controller->V2.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_GEM_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
DAC960_GEM_MemoryMailboxNewCommand(ControllerBaseAddress);
Controller->V2.PreviousCommandMailbox2 =
Controller->V2.PreviousCommandMailbox1;
Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
NextCommandMailbox = Controller->V2.FirstCommandMailbox;
Controller->V2.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_BA_QueueCommand queues Command for DAC960 BA Series Controllers.
*/
static void DAC960_BA_QueueCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandMailbox_T *NextCommandMailbox =
Controller->V2.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_BA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
DAC960_BA_MemoryMailboxNewCommand(ControllerBaseAddress);
Controller->V2.PreviousCommandMailbox2 =
Controller->V2.PreviousCommandMailbox1;
Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
NextCommandMailbox = Controller->V2.FirstCommandMailbox;
Controller->V2.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_LP_QueueCommand queues Command for DAC960 LP Series Controllers.
*/
static void DAC960_LP_QueueCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandMailbox_T *NextCommandMailbox =
Controller->V2.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_LP_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
DAC960_LP_MemoryMailboxNewCommand(ControllerBaseAddress);
Controller->V2.PreviousCommandMailbox2 =
Controller->V2.PreviousCommandMailbox1;
Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
NextCommandMailbox = Controller->V2.FirstCommandMailbox;
Controller->V2.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_LA_QueueCommandDualMode queues Command for DAC960 LA Series
Controllers with Dual Mode Firmware.
*/
static void DAC960_LA_QueueCommandDualMode(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandMailbox_T *NextCommandMailbox =
Controller->V1.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_LA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
DAC960_LA_MemoryMailboxNewCommand(ControllerBaseAddress);
Controller->V1.PreviousCommandMailbox2 =
Controller->V1.PreviousCommandMailbox1;
Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
NextCommandMailbox = Controller->V1.FirstCommandMailbox;
Controller->V1.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_LA_QueueCommandSingleMode queues Command for DAC960 LA Series
Controllers with Single Mode Firmware.
*/
static void DAC960_LA_QueueCommandSingleMode(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandMailbox_T *NextCommandMailbox =
Controller->V1.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_LA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
DAC960_LA_HardwareMailboxNewCommand(ControllerBaseAddress);
Controller->V1.PreviousCommandMailbox2 =
Controller->V1.PreviousCommandMailbox1;
Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
NextCommandMailbox = Controller->V1.FirstCommandMailbox;
Controller->V1.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_PG_QueueCommandDualMode queues Command for DAC960 PG Series
Controllers with Dual Mode Firmware.
*/
static void DAC960_PG_QueueCommandDualMode(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandMailbox_T *NextCommandMailbox =
Controller->V1.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_PG_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
DAC960_PG_MemoryMailboxNewCommand(ControllerBaseAddress);
Controller->V1.PreviousCommandMailbox2 =
Controller->V1.PreviousCommandMailbox1;
Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
NextCommandMailbox = Controller->V1.FirstCommandMailbox;
Controller->V1.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_PG_QueueCommandSingleMode queues Command for DAC960 PG Series
Controllers with Single Mode Firmware.
*/
static void DAC960_PG_QueueCommandSingleMode(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandMailbox_T *NextCommandMailbox =
Controller->V1.NextCommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
DAC960_PG_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
DAC960_PG_HardwareMailboxNewCommand(ControllerBaseAddress);
Controller->V1.PreviousCommandMailbox2 =
Controller->V1.PreviousCommandMailbox1;
Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
NextCommandMailbox = Controller->V1.FirstCommandMailbox;
Controller->V1.NextCommandMailbox = NextCommandMailbox;
}
/*
DAC960_PD_QueueCommand queues Command for DAC960 PD Series Controllers.
*/
static void DAC960_PD_QueueCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
while (DAC960_PD_MailboxFullP(ControllerBaseAddress))
udelay(1);
DAC960_PD_WriteCommandMailbox(ControllerBaseAddress, CommandMailbox);
DAC960_PD_NewCommand(ControllerBaseAddress);
}
/*
DAC960_P_QueueCommand queues Command for DAC960 P Series Controllers.
*/
static void DAC960_P_QueueCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
switch (CommandMailbox->Common.CommandOpcode)
{
case DAC960_V1_Enquiry:
CommandMailbox->Common.CommandOpcode = DAC960_V1_Enquiry_Old;
break;
case DAC960_V1_GetDeviceState:
CommandMailbox->Common.CommandOpcode = DAC960_V1_GetDeviceState_Old;
break;
case DAC960_V1_Read:
CommandMailbox->Common.CommandOpcode = DAC960_V1_Read_Old;
DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
break;
case DAC960_V1_Write:
CommandMailbox->Common.CommandOpcode = DAC960_V1_Write_Old;
DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
break;
case DAC960_V1_ReadWithScatterGather:
CommandMailbox->Common.CommandOpcode =
DAC960_V1_ReadWithScatterGather_Old;
DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
break;
case DAC960_V1_WriteWithScatterGather:
CommandMailbox->Common.CommandOpcode =
DAC960_V1_WriteWithScatterGather_Old;
DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
break;
default:
break;
}
while (DAC960_PD_MailboxFullP(ControllerBaseAddress))
udelay(1);
DAC960_PD_WriteCommandMailbox(ControllerBaseAddress, CommandMailbox);
DAC960_PD_NewCommand(ControllerBaseAddress);
}
/*
DAC960_ExecuteCommand executes Command and waits for completion.
*/
static void DAC960_ExecuteCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DECLARE_COMPLETION_ONSTACK(Completion);
unsigned long flags;
Command->Completion = &Completion;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_QueueCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
if (in_interrupt())
return;
wait_for_completion(&Completion);
}
/*
DAC960_V1_ExecuteType3 executes a DAC960 V1 Firmware Controller Type 3
Command and waits for completion. It returns true on success and false
on failure.
*/
static bool DAC960_V1_ExecuteType3(DAC960_Controller_T *Controller,
DAC960_V1_CommandOpcode_T CommandOpcode,
dma_addr_t DataDMA)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandStatus_T CommandStatus;
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->Type3.CommandOpcode = CommandOpcode;
CommandMailbox->Type3.BusAddress = DataDMA;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V1.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V1_NormalCompletion);
}
/*
DAC960_V1_ExecuteTypeB executes a DAC960 V1 Firmware Controller Type 3B
Command and waits for completion. It returns true on success and false
on failure.
*/
static bool DAC960_V1_ExecuteType3B(DAC960_Controller_T *Controller,
DAC960_V1_CommandOpcode_T CommandOpcode,
unsigned char CommandOpcode2,
dma_addr_t DataDMA)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandStatus_T CommandStatus;
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->Type3B.CommandOpcode = CommandOpcode;
CommandMailbox->Type3B.CommandOpcode2 = CommandOpcode2;
CommandMailbox->Type3B.BusAddress = DataDMA;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V1.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V1_NormalCompletion);
}
/*
DAC960_V1_ExecuteType3D executes a DAC960 V1 Firmware Controller Type 3D
Command and waits for completion. It returns true on success and false
on failure.
*/
static bool DAC960_V1_ExecuteType3D(DAC960_Controller_T *Controller,
DAC960_V1_CommandOpcode_T CommandOpcode,
unsigned char Channel,
unsigned char TargetID,
dma_addr_t DataDMA)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandStatus_T CommandStatus;
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->Type3D.CommandOpcode = CommandOpcode;
CommandMailbox->Type3D.Channel = Channel;
CommandMailbox->Type3D.TargetID = TargetID;
CommandMailbox->Type3D.BusAddress = DataDMA;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V1.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V1_NormalCompletion);
}
/*
DAC960_V2_GeneralInfo executes a DAC960 V2 Firmware General Information
Reading IOCTL Command and waits for completion. It returns true on success
and false on failure.
Return data in The controller's HealthStatusBuffer, which is dma-able memory
*/
static bool DAC960_V2_GeneralInfo(DAC960_Controller_T *Controller)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->Common.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->Common.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->Common.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->Common.DataTransferSize = sizeof(DAC960_V2_HealthStatusBuffer_T);
CommandMailbox->Common.IOCTL_Opcode = DAC960_V2_GetHealthStatus;
CommandMailbox->Common.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.HealthStatusBufferDMA;
CommandMailbox->Common.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->Common.DataTransferSize;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V2_ControllerInfo executes a DAC960 V2 Firmware Controller
Information Reading IOCTL Command and waits for completion. It returns
true on success and false on failure.
Data is returned in the controller's V2.NewControllerInformation dma-able
memory buffer.
*/
static bool DAC960_V2_NewControllerInfo(DAC960_Controller_T *Controller)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->ControllerInfo.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->ControllerInfo.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->ControllerInfo.DataTransferSize = sizeof(DAC960_V2_ControllerInfo_T);
CommandMailbox->ControllerInfo.ControllerNumber = 0;
CommandMailbox->ControllerInfo.IOCTL_Opcode = DAC960_V2_GetControllerInfo;
CommandMailbox->ControllerInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewControllerInformationDMA;
CommandMailbox->ControllerInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->ControllerInfo.DataTransferSize;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V2_LogicalDeviceInfo executes a DAC960 V2 Firmware Controller Logical
Device Information Reading IOCTL Command and waits for completion. It
returns true on success and false on failure.
Data is returned in the controller's V2.NewLogicalDeviceInformation
*/
static bool DAC960_V2_NewLogicalDeviceInfo(DAC960_Controller_T *Controller,
unsigned short LogicalDeviceNumber)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->LogicalDeviceInfo.CommandOpcode =
DAC960_V2_IOCTL;
CommandMailbox->LogicalDeviceInfo.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->LogicalDeviceInfo.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->LogicalDeviceInfo.DataTransferSize =
sizeof(DAC960_V2_LogicalDeviceInfo_T);
CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
LogicalDeviceNumber;
CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode = DAC960_V2_GetLogicalDeviceInfoValid;
CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewLogicalDeviceInformationDMA;
CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->LogicalDeviceInfo.DataTransferSize;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V2_PhysicalDeviceInfo executes a DAC960 V2 Firmware Controller "Read
Physical Device Information" IOCTL Command and waits for completion. It
returns true on success and false on failure.
The Channel, TargetID, LogicalUnit arguments should be 0 the first time
this function is called for a given controller. This will return data
for the "first" device on that controller. The returned data includes a
Channel, TargetID, LogicalUnit that can be passed in to this routine to
get data for the NEXT device on that controller.
Data is stored in the controller's V2.NewPhysicalDeviceInfo dma-able
memory buffer.
*/
static bool DAC960_V2_NewPhysicalDeviceInfo(DAC960_Controller_T *Controller,
unsigned char Channel,
unsigned char TargetID,
unsigned char LogicalUnit)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->PhysicalDeviceInfo.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->PhysicalDeviceInfo.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
sizeof(DAC960_V2_PhysicalDeviceInfo_T);
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.LogicalUnit = LogicalUnit;
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID = TargetID;
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel = Channel;
CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
DAC960_V2_GetPhysicalDeviceInfoValid;
CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewPhysicalDeviceInformationDMA;
CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->PhysicalDeviceInfo.DataTransferSize;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
static void DAC960_V2_ConstructNewUnitSerialNumber(
DAC960_Controller_T *Controller,
DAC960_V2_CommandMailbox_T *CommandMailbox, int Channel, int TargetID,
int LogicalUnit)
{
CommandMailbox->SCSI_10.CommandOpcode = DAC960_V2_SCSI_10_Passthru;
CommandMailbox->SCSI_10.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->SCSI_10.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->SCSI_10.DataTransferSize =
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
CommandMailbox->SCSI_10.PhysicalDevice.LogicalUnit = LogicalUnit;
CommandMailbox->SCSI_10.PhysicalDevice.TargetID = TargetID;
CommandMailbox->SCSI_10.PhysicalDevice.Channel = Channel;
CommandMailbox->SCSI_10.CDBLength = 6;
CommandMailbox->SCSI_10.SCSI_CDB[0] = 0x12; /* INQUIRY */
CommandMailbox->SCSI_10.SCSI_CDB[1] = 1; /* EVPD = 1 */
CommandMailbox->SCSI_10.SCSI_CDB[2] = 0x80; /* Page Code */
CommandMailbox->SCSI_10.SCSI_CDB[3] = 0; /* Reserved */
CommandMailbox->SCSI_10.SCSI_CDB[4] =
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
CommandMailbox->SCSI_10.SCSI_CDB[5] = 0; /* Control */
CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewInquiryUnitSerialNumberDMA;
CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->SCSI_10.DataTransferSize;
}
/*
DAC960_V2_NewUnitSerialNumber executes an SCSI pass-through
Inquiry command to a SCSI device identified by Channel number,
Target id, Logical Unit Number. This function Waits for completion
of the command.
The return data includes Unit Serial Number information for the
specified device.
Data is stored in the controller's V2.NewPhysicalDeviceInfo dma-able
memory buffer.
*/
static bool DAC960_V2_NewInquiryUnitSerialNumber(DAC960_Controller_T *Controller,
int Channel, int TargetID, int LogicalUnit)
{
DAC960_Command_T *Command;
DAC960_V2_CommandMailbox_T *CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
Command = DAC960_AllocateCommand(Controller);
CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
DAC960_V2_ConstructNewUnitSerialNumber(Controller, CommandMailbox,
Channel, TargetID, LogicalUnit);
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V2_DeviceOperation executes a DAC960 V2 Firmware Controller Device
Operation IOCTL Command and waits for completion. It returns true on
success and false on failure.
*/
static bool DAC960_V2_DeviceOperation(DAC960_Controller_T *Controller,
DAC960_V2_IOCTL_Opcode_T IOCTL_Opcode,
DAC960_V2_OperationDevice_T
OperationDevice)
{
DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox->DeviceOperation.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->DeviceOperation.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->DeviceOperation.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->DeviceOperation.IOCTL_Opcode = IOCTL_Opcode;
CommandMailbox->DeviceOperation.OperationDevice = OperationDevice;
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
DAC960_DeallocateCommand(Command);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V1_EnableMemoryMailboxInterface enables the Memory Mailbox Interface
for DAC960 V1 Firmware Controllers.
PD and P controller types have no memory mailbox, but still need the
other dma mapped memory.
*/
static bool DAC960_V1_EnableMemoryMailboxInterface(DAC960_Controller_T
*Controller)
{
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_HardwareType_T hw_type = Controller->HardwareType;
struct pci_dev *PCI_Device = Controller->PCIDevice;
struct dma_loaf *DmaPages = &Controller->DmaPages;
size_t DmaPagesSize;
size_t CommandMailboxesSize;
size_t StatusMailboxesSize;
DAC960_V1_CommandMailbox_T *CommandMailboxesMemory;
dma_addr_t CommandMailboxesMemoryDMA;
DAC960_V1_StatusMailbox_T *StatusMailboxesMemory;
dma_addr_t StatusMailboxesMemoryDMA;
DAC960_V1_CommandMailbox_T CommandMailbox;
DAC960_V1_CommandStatus_T CommandStatus;
int TimeoutCounter;
int i;
if (pci_set_dma_mask(Controller->PCIDevice, DMA_32BIT_MASK))
return DAC960_Failure(Controller, "DMA mask out of range");
Controller->BounceBufferLimit = DMA_32BIT_MASK;
if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller)) {
CommandMailboxesSize = 0;
StatusMailboxesSize = 0;
} else {
CommandMailboxesSize = DAC960_V1_CommandMailboxCount * sizeof(DAC960_V1_CommandMailbox_T);
StatusMailboxesSize = DAC960_V1_StatusMailboxCount * sizeof(DAC960_V1_StatusMailbox_T);
}
DmaPagesSize = CommandMailboxesSize + StatusMailboxesSize +
sizeof(DAC960_V1_DCDB_T) + sizeof(DAC960_V1_Enquiry_T) +
sizeof(DAC960_V1_ErrorTable_T) + sizeof(DAC960_V1_EventLogEntry_T) +
sizeof(DAC960_V1_RebuildProgress_T) +
sizeof(DAC960_V1_LogicalDriveInformationArray_T) +
sizeof(DAC960_V1_BackgroundInitializationStatus_T) +
sizeof(DAC960_V1_DeviceState_T) + sizeof(DAC960_SCSI_Inquiry_T) +
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
if (!init_dma_loaf(PCI_Device, DmaPages, DmaPagesSize))
return false;
if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller))
goto skip_mailboxes;
CommandMailboxesMemory = slice_dma_loaf(DmaPages,
CommandMailboxesSize, &CommandMailboxesMemoryDMA);
/* These are the base addresses for the command memory mailbox array */
Controller->V1.FirstCommandMailbox = CommandMailboxesMemory;
Controller->V1.FirstCommandMailboxDMA = CommandMailboxesMemoryDMA;
CommandMailboxesMemory += DAC960_V1_CommandMailboxCount - 1;
Controller->V1.LastCommandMailbox = CommandMailboxesMemory;
Controller->V1.NextCommandMailbox = Controller->V1.FirstCommandMailbox;
Controller->V1.PreviousCommandMailbox1 = Controller->V1.LastCommandMailbox;
Controller->V1.PreviousCommandMailbox2 =
Controller->V1.LastCommandMailbox - 1;
/* These are the base addresses for the status memory mailbox array */
StatusMailboxesMemory = slice_dma_loaf(DmaPages,
StatusMailboxesSize, &StatusMailboxesMemoryDMA);
Controller->V1.FirstStatusMailbox = StatusMailboxesMemory;
Controller->V1.FirstStatusMailboxDMA = StatusMailboxesMemoryDMA;
StatusMailboxesMemory += DAC960_V1_StatusMailboxCount - 1;
Controller->V1.LastStatusMailbox = StatusMailboxesMemory;
Controller->V1.NextStatusMailbox = Controller->V1.FirstStatusMailbox;
skip_mailboxes:
Controller->V1.MonitoringDCDB = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_DCDB_T),
&Controller->V1.MonitoringDCDB_DMA);
Controller->V1.NewEnquiry = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_Enquiry_T),
&Controller->V1.NewEnquiryDMA);
Controller->V1.NewErrorTable = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_ErrorTable_T),
&Controller->V1.NewErrorTableDMA);
Controller->V1.EventLogEntry = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_EventLogEntry_T),
&Controller->V1.EventLogEntryDMA);
Controller->V1.RebuildProgress = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_RebuildProgress_T),
&Controller->V1.RebuildProgressDMA);
Controller->V1.NewLogicalDriveInformation = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_LogicalDriveInformationArray_T),
&Controller->V1.NewLogicalDriveInformationDMA);
Controller->V1.BackgroundInitializationStatus = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_BackgroundInitializationStatus_T),
&Controller->V1.BackgroundInitializationStatusDMA);
Controller->V1.NewDeviceState = slice_dma_loaf(DmaPages,
sizeof(DAC960_V1_DeviceState_T),
&Controller->V1.NewDeviceStateDMA);
Controller->V1.NewInquiryStandardData = slice_dma_loaf(DmaPages,
sizeof(DAC960_SCSI_Inquiry_T),
&Controller->V1.NewInquiryStandardDataDMA);
Controller->V1.NewInquiryUnitSerialNumber = slice_dma_loaf(DmaPages,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
&Controller->V1.NewInquiryUnitSerialNumberDMA);
if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller))
return true;
/* Enable the Memory Mailbox Interface. */
Controller->V1.DualModeMemoryMailboxInterface = true;
CommandMailbox.TypeX.CommandOpcode = 0x2B;
CommandMailbox.TypeX.CommandIdentifier = 0;
CommandMailbox.TypeX.CommandOpcode2 = 0x14;
CommandMailbox.TypeX.CommandMailboxesBusAddress =
Controller->V1.FirstCommandMailboxDMA;
CommandMailbox.TypeX.StatusMailboxesBusAddress =
Controller->V1.FirstStatusMailboxDMA;
#define TIMEOUT_COUNT 1000000
for (i = 0; i < 2; i++)
switch (Controller->HardwareType)
{
case DAC960_LA_Controller:
TimeoutCounter = TIMEOUT_COUNT;
while (--TimeoutCounter >= 0)
{
if (!DAC960_LA_HardwareMailboxFullP(ControllerBaseAddress))
break;
udelay(10);
}
if (TimeoutCounter < 0) return false;
DAC960_LA_WriteHardwareMailbox(ControllerBaseAddress, &CommandMailbox);
DAC960_LA_HardwareMailboxNewCommand(ControllerBaseAddress);
TimeoutCounter = TIMEOUT_COUNT;
while (--TimeoutCounter >= 0)
{
if (DAC960_LA_HardwareMailboxStatusAvailableP(
ControllerBaseAddress))
break;
udelay(10);
}
if (TimeoutCounter < 0) return false;
CommandStatus = DAC960_LA_ReadStatusRegister(ControllerBaseAddress);
DAC960_LA_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
DAC960_LA_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
if (CommandStatus == DAC960_V1_NormalCompletion) return true;
Controller->V1.DualModeMemoryMailboxInterface = false;
CommandMailbox.TypeX.CommandOpcode2 = 0x10;
break;
case DAC960_PG_Controller:
TimeoutCounter = TIMEOUT_COUNT;
while (--TimeoutCounter >= 0)
{
if (!DAC960_PG_HardwareMailboxFullP(ControllerBaseAddress))
break;
udelay(10);
}
if (TimeoutCounter < 0) return false;
DAC960_PG_WriteHardwareMailbox(ControllerBaseAddress, &CommandMailbox);
DAC960_PG_HardwareMailboxNewCommand(ControllerBaseAddress);
TimeoutCounter = TIMEOUT_COUNT;
while (--TimeoutCounter >= 0)
{
if (DAC960_PG_HardwareMailboxStatusAvailableP(
ControllerBaseAddress))
break;
udelay(10);
}
if (TimeoutCounter < 0) return false;
CommandStatus = DAC960_PG_ReadStatusRegister(ControllerBaseAddress);
DAC960_PG_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
DAC960_PG_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
if (CommandStatus == DAC960_V1_NormalCompletion) return true;
Controller->V1.DualModeMemoryMailboxInterface = false;
CommandMailbox.TypeX.CommandOpcode2 = 0x10;
break;
default:
DAC960_Failure(Controller, "Unknown Controller Type\n");
break;
}
return false;
}
/*
DAC960_V2_EnableMemoryMailboxInterface enables the Memory Mailbox Interface
for DAC960 V2 Firmware Controllers.
Aggregate the space needed for the controller's memory mailbox and
the other data structures that will be targets of dma transfers with
the controller. Allocate a dma-mapped region of memory to hold these
structures. Then, save CPU pointers and dma_addr_t values to reference
the structures that are contained in that region.
*/
static bool DAC960_V2_EnableMemoryMailboxInterface(DAC960_Controller_T
*Controller)
{
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
struct pci_dev *PCI_Device = Controller->PCIDevice;
struct dma_loaf *DmaPages = &Controller->DmaPages;
size_t DmaPagesSize;
size_t CommandMailboxesSize;
size_t StatusMailboxesSize;
DAC960_V2_CommandMailbox_T *CommandMailboxesMemory;
dma_addr_t CommandMailboxesMemoryDMA;
DAC960_V2_StatusMailbox_T *StatusMailboxesMemory;
dma_addr_t StatusMailboxesMemoryDMA;
DAC960_V2_CommandMailbox_T *CommandMailbox;
dma_addr_t CommandMailboxDMA;
DAC960_V2_CommandStatus_T CommandStatus;
if (!pci_set_dma_mask(Controller->PCIDevice, DMA_64BIT_MASK))
Controller->BounceBufferLimit = DMA_64BIT_MASK;
else if (!pci_set_dma_mask(Controller->PCIDevice, DMA_32BIT_MASK))
Controller->BounceBufferLimit = DMA_32BIT_MASK;
else
return DAC960_Failure(Controller, "DMA mask out of range");
/* This is a temporary dma mapping, used only in the scope of this function */
CommandMailbox = pci_alloc_consistent(PCI_Device,
sizeof(DAC960_V2_CommandMailbox_T), &CommandMailboxDMA);
if (CommandMailbox == NULL)
return false;
CommandMailboxesSize = DAC960_V2_CommandMailboxCount * sizeof(DAC960_V2_CommandMailbox_T);
StatusMailboxesSize = DAC960_V2_StatusMailboxCount * sizeof(DAC960_V2_StatusMailbox_T);
DmaPagesSize =
CommandMailboxesSize + StatusMailboxesSize +
sizeof(DAC960_V2_HealthStatusBuffer_T) +
sizeof(DAC960_V2_ControllerInfo_T) +
sizeof(DAC960_V2_LogicalDeviceInfo_T) +
sizeof(DAC960_V2_PhysicalDeviceInfo_T) +
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T) +
sizeof(DAC960_V2_Event_T) +
sizeof(DAC960_V2_PhysicalToLogicalDevice_T);
if (!init_dma_loaf(PCI_Device, DmaPages, DmaPagesSize)) {
pci_free_consistent(PCI_Device, sizeof(DAC960_V2_CommandMailbox_T),
CommandMailbox, CommandMailboxDMA);
return false;
}
CommandMailboxesMemory = slice_dma_loaf(DmaPages,
CommandMailboxesSize, &CommandMailboxesMemoryDMA);
/* These are the base addresses for the command memory mailbox array */
Controller->V2.FirstCommandMailbox = CommandMailboxesMemory;
Controller->V2.FirstCommandMailboxDMA = CommandMailboxesMemoryDMA;
CommandMailboxesMemory += DAC960_V2_CommandMailboxCount - 1;
Controller->V2.LastCommandMailbox = CommandMailboxesMemory;
Controller->V2.NextCommandMailbox = Controller->V2.FirstCommandMailbox;
Controller->V2.PreviousCommandMailbox1 = Controller->V2.LastCommandMailbox;
Controller->V2.PreviousCommandMailbox2 =
Controller->V2.LastCommandMailbox - 1;
/* These are the base addresses for the status memory mailbox array */
StatusMailboxesMemory = slice_dma_loaf(DmaPages,
StatusMailboxesSize, &StatusMailboxesMemoryDMA);
Controller->V2.FirstStatusMailbox = StatusMailboxesMemory;
Controller->V2.FirstStatusMailboxDMA = StatusMailboxesMemoryDMA;
StatusMailboxesMemory += DAC960_V2_StatusMailboxCount - 1;
Controller->V2.LastStatusMailbox = StatusMailboxesMemory;
Controller->V2.NextStatusMailbox = Controller->V2.FirstStatusMailbox;
Controller->V2.HealthStatusBuffer = slice_dma_loaf(DmaPages,
sizeof(DAC960_V2_HealthStatusBuffer_T),
&Controller->V2.HealthStatusBufferDMA);
Controller->V2.NewControllerInformation = slice_dma_loaf(DmaPages,
sizeof(DAC960_V2_ControllerInfo_T),
&Controller->V2.NewControllerInformationDMA);
Controller->V2.NewLogicalDeviceInformation = slice_dma_loaf(DmaPages,
sizeof(DAC960_V2_LogicalDeviceInfo_T),
&Controller->V2.NewLogicalDeviceInformationDMA);
Controller->V2.NewPhysicalDeviceInformation = slice_dma_loaf(DmaPages,
sizeof(DAC960_V2_PhysicalDeviceInfo_T),
&Controller->V2.NewPhysicalDeviceInformationDMA);
Controller->V2.NewInquiryUnitSerialNumber = slice_dma_loaf(DmaPages,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
&Controller->V2.NewInquiryUnitSerialNumberDMA);
Controller->V2.Event = slice_dma_loaf(DmaPages,
sizeof(DAC960_V2_Event_T),
&Controller->V2.EventDMA);
Controller->V2.PhysicalToLogicalDevice = slice_dma_loaf(DmaPages,
sizeof(DAC960_V2_PhysicalToLogicalDevice_T),
&Controller->V2.PhysicalToLogicalDeviceDMA);
/*
Enable the Memory Mailbox Interface.
I don't know why we can't just use one of the memory mailboxes
we just allocated to do this, instead of using this temporary one.
Try this change later.
*/
memset(CommandMailbox, 0, sizeof(DAC960_V2_CommandMailbox_T));
CommandMailbox->SetMemoryMailbox.CommandIdentifier = 1;
CommandMailbox->SetMemoryMailbox.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->SetMemoryMailbox.CommandControlBits.NoAutoRequestSense = true;
CommandMailbox->SetMemoryMailbox.FirstCommandMailboxSizeKB =
(DAC960_V2_CommandMailboxCount * sizeof(DAC960_V2_CommandMailbox_T)) >> 10;
CommandMailbox->SetMemoryMailbox.FirstStatusMailboxSizeKB =
(DAC960_V2_StatusMailboxCount * sizeof(DAC960_V2_StatusMailbox_T)) >> 10;
CommandMailbox->SetMemoryMailbox.SecondCommandMailboxSizeKB = 0;
CommandMailbox->SetMemoryMailbox.SecondStatusMailboxSizeKB = 0;
CommandMailbox->SetMemoryMailbox.RequestSenseSize = 0;
CommandMailbox->SetMemoryMailbox.IOCTL_Opcode = DAC960_V2_SetMemoryMailbox;
CommandMailbox->SetMemoryMailbox.HealthStatusBufferSizeKB = 1;
CommandMailbox->SetMemoryMailbox.HealthStatusBufferBusAddress =
Controller->V2.HealthStatusBufferDMA;
CommandMailbox->SetMemoryMailbox.FirstCommandMailboxBusAddress =
Controller->V2.FirstCommandMailboxDMA;
CommandMailbox->SetMemoryMailbox.FirstStatusMailboxBusAddress =
Controller->V2.FirstStatusMailboxDMA;
switch (Controller->HardwareType)
{
case DAC960_GEM_Controller:
while (DAC960_GEM_HardwareMailboxFullP(ControllerBaseAddress))
udelay(1);
DAC960_GEM_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
DAC960_GEM_HardwareMailboxNewCommand(ControllerBaseAddress);
while (!DAC960_GEM_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
udelay(1);
CommandStatus = DAC960_GEM_ReadCommandStatus(ControllerBaseAddress);
DAC960_GEM_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
DAC960_GEM_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
break;
case DAC960_BA_Controller:
while (DAC960_BA_HardwareMailboxFullP(ControllerBaseAddress))
udelay(1);
DAC960_BA_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
DAC960_BA_HardwareMailboxNewCommand(ControllerBaseAddress);
while (!DAC960_BA_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
udelay(1);
CommandStatus = DAC960_BA_ReadCommandStatus(ControllerBaseAddress);
DAC960_BA_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
DAC960_BA_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
break;
case DAC960_LP_Controller:
while (DAC960_LP_HardwareMailboxFullP(ControllerBaseAddress))
udelay(1);
DAC960_LP_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
DAC960_LP_HardwareMailboxNewCommand(ControllerBaseAddress);
while (!DAC960_LP_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
udelay(1);
CommandStatus = DAC960_LP_ReadCommandStatus(ControllerBaseAddress);
DAC960_LP_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
DAC960_LP_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
break;
default:
DAC960_Failure(Controller, "Unknown Controller Type\n");
CommandStatus = DAC960_V2_AbormalCompletion;
break;
}
pci_free_consistent(PCI_Device, sizeof(DAC960_V2_CommandMailbox_T),
CommandMailbox, CommandMailboxDMA);
return (CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V1_ReadControllerConfiguration reads the Configuration Information
from DAC960 V1 Firmware Controllers and initializes the Controller structure.
*/
static bool DAC960_V1_ReadControllerConfiguration(DAC960_Controller_T
*Controller)
{
DAC960_V1_Enquiry2_T *Enquiry2;
dma_addr_t Enquiry2DMA;
DAC960_V1_Config2_T *Config2;
dma_addr_t Config2DMA;
int LogicalDriveNumber, Channel, TargetID;
struct dma_loaf local_dma;
if (!init_dma_loaf(Controller->PCIDevice, &local_dma,
sizeof(DAC960_V1_Enquiry2_T) + sizeof(DAC960_V1_Config2_T)))
return DAC960_Failure(Controller, "LOGICAL DEVICE ALLOCATION");
Enquiry2 = slice_dma_loaf(&local_dma, sizeof(DAC960_V1_Enquiry2_T), &Enquiry2DMA);
Config2 = slice_dma_loaf(&local_dma, sizeof(DAC960_V1_Config2_T), &Config2DMA);
if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_Enquiry,
Controller->V1.NewEnquiryDMA)) {
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "ENQUIRY");
}
memcpy(&Controller->V1.Enquiry, Controller->V1.NewEnquiry,
sizeof(DAC960_V1_Enquiry_T));
if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_Enquiry2, Enquiry2DMA)) {
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "ENQUIRY2");
}
if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_ReadConfig2, Config2DMA)) {
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "READ CONFIG2");
}
if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_GetLogicalDriveInformation,
Controller->V1.NewLogicalDriveInformationDMA)) {
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "GET LOGICAL DRIVE INFORMATION");
}
memcpy(&Controller->V1.LogicalDriveInformation,
Controller->V1.NewLogicalDriveInformation,
sizeof(DAC960_V1_LogicalDriveInformationArray_T));
for (Channel = 0; Channel < Enquiry2->ActualChannels; Channel++)
for (TargetID = 0; TargetID < Enquiry2->MaxTargets; TargetID++) {
if (!DAC960_V1_ExecuteType3D(Controller, DAC960_V1_GetDeviceState,
Channel, TargetID,
Controller->V1.NewDeviceStateDMA)) {
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "GET DEVICE STATE");
}
memcpy(&Controller->V1.DeviceState[Channel][TargetID],
Controller->V1.NewDeviceState, sizeof(DAC960_V1_DeviceState_T));
}
/*
Initialize the Controller Model Name and Full Model Name fields.
*/
switch (Enquiry2->HardwareID.SubModel)
{
case DAC960_V1_P_PD_PU:
if (Enquiry2->SCSICapability.BusSpeed == DAC960_V1_Ultra)
strcpy(Controller->ModelName, "DAC960PU");
else strcpy(Controller->ModelName, "DAC960PD");
break;
case DAC960_V1_PL:
strcpy(Controller->ModelName, "DAC960PL");
break;
case DAC960_V1_PG:
strcpy(Controller->ModelName, "DAC960PG");
break;
case DAC960_V1_PJ:
strcpy(Controller->ModelName, "DAC960PJ");
break;
case DAC960_V1_PR:
strcpy(Controller->ModelName, "DAC960PR");
break;
case DAC960_V1_PT:
strcpy(Controller->ModelName, "DAC960PT");
break;
case DAC960_V1_PTL0:
strcpy(Controller->ModelName, "DAC960PTL0");
break;
case DAC960_V1_PRL:
strcpy(Controller->ModelName, "DAC960PRL");
break;
case DAC960_V1_PTL1:
strcpy(Controller->ModelName, "DAC960PTL1");
break;
case DAC960_V1_1164P:
strcpy(Controller->ModelName, "DAC1164P");
break;
default:
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "MODEL VERIFICATION");
}
strcpy(Controller->FullModelName, "Mylex ");
strcat(Controller->FullModelName, Controller->ModelName);
/*
Initialize the Controller Firmware Version field and verify that it
is a supported firmware version. The supported firmware versions are:
DAC1164P 5.06 and above
DAC960PTL/PRL/PJ/PG 4.06 and above
DAC960PU/PD/PL 3.51 and above
DAC960PU/PD/PL/P 2.73 and above
*/
#if defined(CONFIG_ALPHA)
/*
DEC Alpha machines were often equipped with DAC960 cards that were
OEMed from Mylex, and had their own custom firmware. Version 2.70,
the last custom FW revision to be released by DEC for these older
controllers, appears to work quite well with this driver.
Cards tested successfully were several versions each of the PD and
PU, called by DEC the KZPSC and KZPAC, respectively, and having
the Manufacturer Numbers (from Mylex), usually on a sticker on the
back of the board, of:
KZPSC: D040347 (1-channel) or D040348 (2-channel) or D040349 (3-channel)
KZPAC: D040395 (1-channel) or D040396 (2-channel) or D040397 (3-channel)
*/
# define FIRMWARE_27X "2.70"
#else
# define FIRMWARE_27X "2.73"
#endif
if (Enquiry2->FirmwareID.MajorVersion == 0)
{
Enquiry2->FirmwareID.MajorVersion =
Controller->V1.Enquiry.MajorFirmwareVersion;
Enquiry2->FirmwareID.MinorVersion =
Controller->V1.Enquiry.MinorFirmwareVersion;
Enquiry2->FirmwareID.FirmwareType = '0';
Enquiry2->FirmwareID.TurnID = 0;
}
sprintf(Controller->FirmwareVersion, "%d.%02d-%c-%02d",
Enquiry2->FirmwareID.MajorVersion, Enquiry2->FirmwareID.MinorVersion,
Enquiry2->FirmwareID.FirmwareType, Enquiry2->FirmwareID.TurnID);
if (!((Controller->FirmwareVersion[0] == '5' &&
strcmp(Controller->FirmwareVersion, "5.06") >= 0) ||
(Controller->FirmwareVersion[0] == '4' &&
strcmp(Controller->FirmwareVersion, "4.06") >= 0) ||
(Controller->FirmwareVersion[0] == '3' &&
strcmp(Controller->FirmwareVersion, "3.51") >= 0) ||
(Controller->FirmwareVersion[0] == '2' &&
strcmp(Controller->FirmwareVersion, FIRMWARE_27X) >= 0)))
{
DAC960_Failure(Controller, "FIRMWARE VERSION VERIFICATION");
DAC960_Error("Firmware Version = '%s'\n", Controller,
Controller->FirmwareVersion);
free_dma_loaf(Controller->PCIDevice, &local_dma);
return false;
}
/*
Initialize the Controller Channels, Targets, Memory Size, and SAF-TE
Enclosure Management Enabled fields.
*/
Controller->Channels = Enquiry2->ActualChannels;
Controller->Targets = Enquiry2->MaxTargets;
Controller->MemorySize = Enquiry2->MemorySize >> 20;
Controller->V1.SAFTE_EnclosureManagementEnabled =
(Enquiry2->FaultManagementType == DAC960_V1_SAFTE);
/*
Initialize the Controller Queue Depth, Driver Queue Depth, Logical Drive
Count, Maximum Blocks per Command, Controller Scatter/Gather Limit, and
Driver Scatter/Gather Limit. The Driver Queue Depth must be at most one
less than the Controller Queue Depth to allow for an automatic drive
rebuild operation.
*/
Controller->ControllerQueueDepth = Controller->V1.Enquiry.MaxCommands;
Controller->DriverQueueDepth = Controller->ControllerQueueDepth - 1;
if (Controller->DriverQueueDepth > DAC960_MaxDriverQueueDepth)
Controller->DriverQueueDepth = DAC960_MaxDriverQueueDepth;
Controller->LogicalDriveCount =
Controller->V1.Enquiry.NumberOfLogicalDrives;
Controller->MaxBlocksPerCommand = Enquiry2->MaxBlocksPerCommand;
Controller->ControllerScatterGatherLimit = Enquiry2->MaxScatterGatherEntries;
Controller->DriverScatterGatherLimit =
Controller->ControllerScatterGatherLimit;
if (Controller->DriverScatterGatherLimit > DAC960_V1_ScatterGatherLimit)
Controller->DriverScatterGatherLimit = DAC960_V1_ScatterGatherLimit;
/*
Initialize the Stripe Size, Segment Size, and Geometry Translation.
*/
Controller->V1.StripeSize = Config2->BlocksPerStripe * Config2->BlockFactor
>> (10 - DAC960_BlockSizeBits);
Controller->V1.SegmentSize = Config2->BlocksPerCacheLine * Config2->BlockFactor
>> (10 - DAC960_BlockSizeBits);
switch (Config2->DriveGeometry)
{
case DAC960_V1_Geometry_128_32:
Controller->V1.GeometryTranslationHeads = 128;
Controller->V1.GeometryTranslationSectors = 32;
break;
case DAC960_V1_Geometry_255_63:
Controller->V1.GeometryTranslationHeads = 255;
Controller->V1.GeometryTranslationSectors = 63;
break;
default:
free_dma_loaf(Controller->PCIDevice, &local_dma);
return DAC960_Failure(Controller, "CONFIG2 DRIVE GEOMETRY");
}
/*
Initialize the Background Initialization Status.
*/
if ((Controller->FirmwareVersion[0] == '4' &&
strcmp(Controller->FirmwareVersion, "4.08") >= 0) ||
(Controller->FirmwareVersion[0] == '5' &&
strcmp(Controller->FirmwareVersion, "5.08") >= 0))
{
Controller->V1.BackgroundInitializationStatusSupported = true;
DAC960_V1_ExecuteType3B(Controller,
DAC960_V1_BackgroundInitializationControl, 0x20,
Controller->
V1.BackgroundInitializationStatusDMA);
memcpy(&Controller->V1.LastBackgroundInitializationStatus,
Controller->V1.BackgroundInitializationStatus,
sizeof(DAC960_V1_BackgroundInitializationStatus_T));
}
/*
Initialize the Logical Drive Initially Accessible flag.
*/
for (LogicalDriveNumber = 0;
LogicalDriveNumber < Controller->LogicalDriveCount;
LogicalDriveNumber++)
if (Controller->V1.LogicalDriveInformation
[LogicalDriveNumber].LogicalDriveState !=
DAC960_V1_LogicalDrive_Offline)
Controller->LogicalDriveInitiallyAccessible[LogicalDriveNumber] = true;
Controller->V1.LastRebuildStatus = DAC960_V1_NoRebuildOrCheckInProgress;
free_dma_loaf(Controller->PCIDevice, &local_dma);
return true;
}
/*
DAC960_V2_ReadControllerConfiguration reads the Configuration Information
from DAC960 V2 Firmware Controllers and initializes the Controller structure.
*/
static bool DAC960_V2_ReadControllerConfiguration(DAC960_Controller_T
*Controller)
{
DAC960_V2_ControllerInfo_T *ControllerInfo =
&Controller->V2.ControllerInformation;
unsigned short LogicalDeviceNumber = 0;
int ModelNameLength;
/* Get data into dma-able area, then copy into permanant location */
if (!DAC960_V2_NewControllerInfo(Controller))
return DAC960_Failure(Controller, "GET CONTROLLER INFO");
memcpy(ControllerInfo, Controller->V2.NewControllerInformation,
sizeof(DAC960_V2_ControllerInfo_T));
if (!DAC960_V2_GeneralInfo(Controller))
return DAC960_Failure(Controller, "GET HEALTH STATUS");
/*
Initialize the Controller Model Name and Full Model Name fields.
*/
ModelNameLength = sizeof(ControllerInfo->ControllerName);
if (ModelNameLength > sizeof(Controller->ModelName)-1)
ModelNameLength = sizeof(Controller->ModelName)-1;
memcpy(Controller->ModelName, ControllerInfo->ControllerName,
ModelNameLength);
ModelNameLength--;
while (Controller->ModelName[ModelNameLength] == ' ' ||
Controller->ModelName[ModelNameLength] == '\0')
ModelNameLength--;
Controller->ModelName[++ModelNameLength] = '\0';
strcpy(Controller->FullModelName, "Mylex ");
strcat(Controller->FullModelName, Controller->ModelName);
/*
Initialize the Controller Firmware Version field.
*/
sprintf(Controller->FirmwareVersion, "%d.%02d-%02d",
ControllerInfo->FirmwareMajorVersion,
ControllerInfo->FirmwareMinorVersion,
ControllerInfo->FirmwareTurnNumber);
if (ControllerInfo->FirmwareMajorVersion == 6 &&
ControllerInfo->FirmwareMinorVersion == 0 &&
ControllerInfo->FirmwareTurnNumber < 1)
{
DAC960_Info("FIRMWARE VERSION %s DOES NOT PROVIDE THE CONTROLLER\n",
Controller, Controller->FirmwareVersion);
DAC960_Info("STATUS MONITORING FUNCTIONALITY NEEDED BY THIS DRIVER.\n",
Controller);
DAC960_Info("PLEASE UPGRADE TO VERSION 6.00-01 OR ABOVE.\n",
Controller);
}
/*
Initialize the Controller Channels, Targets, and Memory Size.
*/
Controller->Channels = ControllerInfo->NumberOfPhysicalChannelsPresent;
Controller->Targets =
ControllerInfo->MaximumTargetsPerChannel
[ControllerInfo->NumberOfPhysicalChannelsPresent-1];
Controller->MemorySize = ControllerInfo->MemorySizeMB;
/*
Initialize the Controller Queue Depth, Driver Queue Depth, Logical Drive
Count, Maximum Blocks per Command, Controller Scatter/Gather Limit, and
Driver Scatter/Gather Limit. The Driver Queue Depth must be at most one
less than the Controller Queue Depth to allow for an automatic drive
rebuild operation.
*/
Controller->ControllerQueueDepth = ControllerInfo->MaximumParallelCommands;
Controller->DriverQueueDepth = Controller->ControllerQueueDepth - 1;
if (Controller->DriverQueueDepth > DAC960_MaxDriverQueueDepth)
Controller->DriverQueueDepth = DAC960_MaxDriverQueueDepth;
Controller->LogicalDriveCount = ControllerInfo->LogicalDevicesPresent;
Controller->MaxBlocksPerCommand =
ControllerInfo->MaximumDataTransferSizeInBlocks;
Controller->ControllerScatterGatherLimit =
ControllerInfo->MaximumScatterGatherEntries;
Controller->DriverScatterGatherLimit =
Controller->ControllerScatterGatherLimit;
if (Controller->DriverScatterGatherLimit > DAC960_V2_ScatterGatherLimit)
Controller->DriverScatterGatherLimit = DAC960_V2_ScatterGatherLimit;
/*
Initialize the Logical Device Information.
*/
while (true)
{
DAC960_V2_LogicalDeviceInfo_T *NewLogicalDeviceInfo =
Controller->V2.NewLogicalDeviceInformation;
DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo;
DAC960_V2_PhysicalDevice_T PhysicalDevice;
if (!DAC960_V2_NewLogicalDeviceInfo(Controller, LogicalDeviceNumber))
break;
LogicalDeviceNumber = NewLogicalDeviceInfo->LogicalDeviceNumber;
if (LogicalDeviceNumber >= DAC960_MaxLogicalDrives) {
DAC960_Error("DAC960: Logical Drive Number %d not supported\n",
Controller, LogicalDeviceNumber);
break;
}
if (NewLogicalDeviceInfo->DeviceBlockSizeInBytes != DAC960_BlockSize) {
DAC960_Error("DAC960: Logical Drive Block Size %d not supported\n",
Controller, NewLogicalDeviceInfo->DeviceBlockSizeInBytes);
LogicalDeviceNumber++;
continue;
}
PhysicalDevice.Controller = 0;
PhysicalDevice.Channel = NewLogicalDeviceInfo->Channel;
PhysicalDevice.TargetID = NewLogicalDeviceInfo->TargetID;
PhysicalDevice.LogicalUnit = NewLogicalDeviceInfo->LogicalUnit;
Controller->V2.LogicalDriveToVirtualDevice[LogicalDeviceNumber] =
PhysicalDevice;
if (NewLogicalDeviceInfo->LogicalDeviceState !=
DAC960_V2_LogicalDevice_Offline)
Controller->LogicalDriveInitiallyAccessible[LogicalDeviceNumber] = true;
LogicalDeviceInfo = kmalloc(sizeof(DAC960_V2_LogicalDeviceInfo_T),
GFP_ATOMIC);
if (LogicalDeviceInfo == NULL)
return DAC960_Failure(Controller, "LOGICAL DEVICE ALLOCATION");
Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber] =
LogicalDeviceInfo;
memcpy(LogicalDeviceInfo, NewLogicalDeviceInfo,
sizeof(DAC960_V2_LogicalDeviceInfo_T));
LogicalDeviceNumber++;
}
return true;
}
/*
DAC960_ReportControllerConfiguration reports the Configuration Information
for Controller.
*/
static bool DAC960_ReportControllerConfiguration(DAC960_Controller_T
*Controller)
{
DAC960_Info("Configuring Mylex %s PCI RAID Controller\n",
Controller, Controller->ModelName);
DAC960_Info(" Firmware Version: %s, Channels: %d, Memory Size: %dMB\n",
Controller, Controller->FirmwareVersion,
Controller->Channels, Controller->MemorySize);
DAC960_Info(" PCI Bus: %d, Device: %d, Function: %d, I/O Address: ",
Controller, Controller->Bus,
Controller->Device, Controller->Function);
if (Controller->IO_Address == 0)
DAC960_Info("Unassigned\n", Controller);
else DAC960_Info("0x%X\n", Controller, Controller->IO_Address);
DAC960_Info(" PCI Address: 0x%X mapped at 0x%lX, IRQ Channel: %d\n",
Controller, Controller->PCI_Address,
(unsigned long) Controller->BaseAddress,
Controller->IRQ_Channel);
DAC960_Info(" Controller Queue Depth: %d, "
"Maximum Blocks per Command: %d\n",
Controller, Controller->ControllerQueueDepth,
Controller->MaxBlocksPerCommand);
DAC960_Info(" Driver Queue Depth: %d, "
"Scatter/Gather Limit: %d of %d Segments\n",
Controller, Controller->DriverQueueDepth,
Controller->DriverScatterGatherLimit,
Controller->ControllerScatterGatherLimit);
if (Controller->FirmwareType == DAC960_V1_Controller)
{
DAC960_Info(" Stripe Size: %dKB, Segment Size: %dKB, "
"BIOS Geometry: %d/%d\n", Controller,
Controller->V1.StripeSize,
Controller->V1.SegmentSize,
Controller->V1.GeometryTranslationHeads,
Controller->V1.GeometryTranslationSectors);
if (Controller->V1.SAFTE_EnclosureManagementEnabled)
DAC960_Info(" SAF-TE Enclosure Management Enabled\n", Controller);
}
return true;
}
/*
DAC960_V1_ReadDeviceConfiguration reads the Device Configuration Information
for DAC960 V1 Firmware Controllers by requesting the SCSI Inquiry and SCSI
Inquiry Unit Serial Number information for each device connected to
Controller.
*/
static bool DAC960_V1_ReadDeviceConfiguration(DAC960_Controller_T
*Controller)
{
struct dma_loaf local_dma;
dma_addr_t DCDBs_dma[DAC960_V1_MaxChannels];
DAC960_V1_DCDB_T *DCDBs_cpu[DAC960_V1_MaxChannels];
dma_addr_t SCSI_Inquiry_dma[DAC960_V1_MaxChannels];
DAC960_SCSI_Inquiry_T *SCSI_Inquiry_cpu[DAC960_V1_MaxChannels];
dma_addr_t SCSI_NewInquiryUnitSerialNumberDMA[DAC960_V1_MaxChannels];
DAC960_SCSI_Inquiry_UnitSerialNumber_T *SCSI_NewInquiryUnitSerialNumberCPU[DAC960_V1_MaxChannels];
struct completion Completions[DAC960_V1_MaxChannels];
unsigned long flags;
int Channel, TargetID;
if (!init_dma_loaf(Controller->PCIDevice, &local_dma,
DAC960_V1_MaxChannels*(sizeof(DAC960_V1_DCDB_T) +
sizeof(DAC960_SCSI_Inquiry_T) +
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T))))
return DAC960_Failure(Controller,
"DMA ALLOCATION FAILED IN ReadDeviceConfiguration");
for (Channel = 0; Channel < Controller->Channels; Channel++) {
DCDBs_cpu[Channel] = slice_dma_loaf(&local_dma,
sizeof(DAC960_V1_DCDB_T), DCDBs_dma + Channel);
SCSI_Inquiry_cpu[Channel] = slice_dma_loaf(&local_dma,
sizeof(DAC960_SCSI_Inquiry_T),
SCSI_Inquiry_dma + Channel);
SCSI_NewInquiryUnitSerialNumberCPU[Channel] = slice_dma_loaf(&local_dma,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
SCSI_NewInquiryUnitSerialNumberDMA + Channel);
}
for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
{
/*
* For each channel, submit a probe for a device on that channel.
* The timeout interval for a device that is present is 10 seconds.
* With this approach, the timeout periods can elapse in parallel
* on each channel.
*/
for (Channel = 0; Channel < Controller->Channels; Channel++)
{
dma_addr_t NewInquiryStandardDataDMA = SCSI_Inquiry_dma[Channel];
DAC960_V1_DCDB_T *DCDB = DCDBs_cpu[Channel];
dma_addr_t DCDB_dma = DCDBs_dma[Channel];
DAC960_Command_T *Command = Controller->Commands[Channel];
struct completion *Completion = &Completions[Channel];
init_completion(Completion);
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
Command->Completion = Completion;
Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
Command->V1.CommandMailbox.Type3.BusAddress = DCDB_dma;
DCDB->Channel = Channel;
DCDB->TargetID = TargetID;
DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
DCDB->EarlyStatus = false;
DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
DCDB->NoAutomaticRequestSense = false;
DCDB->DisconnectPermitted = true;
DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_T);
DCDB->BusAddress = NewInquiryStandardDataDMA;
DCDB->CDBLength = 6;
DCDB->TransferLengthHigh4 = 0;
DCDB->SenseLength = sizeof(DCDB->SenseData);
DCDB->CDB[0] = 0x12; /* INQUIRY */
DCDB->CDB[1] = 0; /* EVPD = 0 */
DCDB->CDB[2] = 0; /* Page Code */
DCDB->CDB[3] = 0; /* Reserved */
DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_T);
DCDB->CDB[5] = 0; /* Control */
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_QueueCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
}
/*
* Wait for the problems submitted in the previous loop
* to complete. On the probes that are successful,
* get the serial number of the device that was found.
*/
for (Channel = 0; Channel < Controller->Channels; Channel++)
{
DAC960_SCSI_Inquiry_T *InquiryStandardData =
&Controller->V1.InquiryStandardData[Channel][TargetID];
DAC960_SCSI_Inquiry_T *NewInquiryStandardData = SCSI_Inquiry_cpu[Channel];
dma_addr_t NewInquiryUnitSerialNumberDMA =
SCSI_NewInquiryUnitSerialNumberDMA[Channel];
DAC960_SCSI_Inquiry_UnitSerialNumber_T *NewInquiryUnitSerialNumber =
SCSI_NewInquiryUnitSerialNumberCPU[Channel];
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
&Controller->V1.InquiryUnitSerialNumber[Channel][TargetID];
DAC960_Command_T *Command = Controller->Commands[Channel];
DAC960_V1_DCDB_T *DCDB = DCDBs_cpu[Channel];
struct completion *Completion = &Completions[Channel];
wait_for_completion(Completion);
if (Command->V1.CommandStatus != DAC960_V1_NormalCompletion) {
memset(InquiryStandardData, 0, sizeof(DAC960_SCSI_Inquiry_T));
InquiryStandardData->PeripheralDeviceType = 0x1F;
continue;
} else
memcpy(InquiryStandardData, NewInquiryStandardData, sizeof(DAC960_SCSI_Inquiry_T));
/* Preserve Channel and TargetID values from the previous loop */
Command->Completion = Completion;
DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
DCDB->BusAddress = NewInquiryUnitSerialNumberDMA;
DCDB->SenseLength = sizeof(DCDB->SenseData);
DCDB->CDB[0] = 0x12; /* INQUIRY */
DCDB->CDB[1] = 1; /* EVPD = 1 */
DCDB->CDB[2] = 0x80; /* Page Code */
DCDB->CDB[3] = 0; /* Reserved */
DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
DCDB->CDB[5] = 0; /* Control */
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_QueueCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
wait_for_completion(Completion);
if (Command->V1.CommandStatus != DAC960_V1_NormalCompletion) {
memset(InquiryUnitSerialNumber, 0,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
} else
memcpy(InquiryUnitSerialNumber, NewInquiryUnitSerialNumber,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
}
}
free_dma_loaf(Controller->PCIDevice, &local_dma);
return true;
}
/*
DAC960_V2_ReadDeviceConfiguration reads the Device Configuration Information
for DAC960 V2 Firmware Controllers by requesting the Physical Device
Information and SCSI Inquiry Unit Serial Number information for each
device connected to Controller.
*/
static bool DAC960_V2_ReadDeviceConfiguration(DAC960_Controller_T
*Controller)
{
unsigned char Channel = 0, TargetID = 0, LogicalUnit = 0;
unsigned short PhysicalDeviceIndex = 0;
while (true)
{
DAC960_V2_PhysicalDeviceInfo_T *NewPhysicalDeviceInfo =
Controller->V2.NewPhysicalDeviceInformation;
DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo;
DAC960_SCSI_Inquiry_UnitSerialNumber_T *NewInquiryUnitSerialNumber =
Controller->V2.NewInquiryUnitSerialNumber;
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber;
if (!DAC960_V2_NewPhysicalDeviceInfo(Controller, Channel, TargetID, LogicalUnit))
break;
PhysicalDeviceInfo = kmalloc(sizeof(DAC960_V2_PhysicalDeviceInfo_T),
GFP_ATOMIC);
if (PhysicalDeviceInfo == NULL)
return DAC960_Failure(Controller, "PHYSICAL DEVICE ALLOCATION");
Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex] =
PhysicalDeviceInfo;
memcpy(PhysicalDeviceInfo, NewPhysicalDeviceInfo,
sizeof(DAC960_V2_PhysicalDeviceInfo_T));
InquiryUnitSerialNumber = kmalloc(
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T), GFP_ATOMIC);
if (InquiryUnitSerialNumber == NULL) {
kfree(PhysicalDeviceInfo);
return DAC960_Failure(Controller, "SERIAL NUMBER ALLOCATION");
}
Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex] =
InquiryUnitSerialNumber;
Channel = NewPhysicalDeviceInfo->Channel;
TargetID = NewPhysicalDeviceInfo->TargetID;
LogicalUnit = NewPhysicalDeviceInfo->LogicalUnit;
/*
Some devices do NOT have Unit Serial Numbers.
This command fails for them. But, we still want to
remember those devices are there. Construct a
UnitSerialNumber structure for the failure case.
*/
if (!DAC960_V2_NewInquiryUnitSerialNumber(Controller, Channel, TargetID, LogicalUnit)) {
memset(InquiryUnitSerialNumber, 0,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
} else
memcpy(InquiryUnitSerialNumber, NewInquiryUnitSerialNumber,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
PhysicalDeviceIndex++;
LogicalUnit++;
}
return true;
}
/*
DAC960_SanitizeInquiryData sanitizes the Vendor, Model, Revision, and
Product Serial Number fields of the Inquiry Standard Data and Inquiry
Unit Serial Number structures.
*/
static void DAC960_SanitizeInquiryData(DAC960_SCSI_Inquiry_T
*InquiryStandardData,
DAC960_SCSI_Inquiry_UnitSerialNumber_T
*InquiryUnitSerialNumber,
unsigned char *Vendor,
unsigned char *Model,
unsigned char *Revision,
unsigned char *SerialNumber)
{
int SerialNumberLength, i;
if (InquiryStandardData->PeripheralDeviceType == 0x1F) return;
for (i = 0; i < sizeof(InquiryStandardData->VendorIdentification); i++)
{
unsigned char VendorCharacter =
InquiryStandardData->VendorIdentification[i];
Vendor[i] = (VendorCharacter >= ' ' && VendorCharacter <= '~'
? VendorCharacter : ' ');
}
Vendor[sizeof(InquiryStandardData->VendorIdentification)] = '\0';
for (i = 0; i < sizeof(InquiryStandardData->ProductIdentification); i++)
{
unsigned char ModelCharacter =
InquiryStandardData->ProductIdentification[i];
Model[i] = (ModelCharacter >= ' ' && ModelCharacter <= '~'
? ModelCharacter : ' ');
}
Model[sizeof(InquiryStandardData->ProductIdentification)] = '\0';
for (i = 0; i < sizeof(InquiryStandardData->ProductRevisionLevel); i++)
{
unsigned char RevisionCharacter =
InquiryStandardData->ProductRevisionLevel[i];
Revision[i] = (RevisionCharacter >= ' ' && RevisionCharacter <= '~'
? RevisionCharacter : ' ');
}
Revision[sizeof(InquiryStandardData->ProductRevisionLevel)] = '\0';
if (InquiryUnitSerialNumber->PeripheralDeviceType == 0x1F) return;
SerialNumberLength = InquiryUnitSerialNumber->PageLength;
if (SerialNumberLength >
sizeof(InquiryUnitSerialNumber->ProductSerialNumber))
SerialNumberLength = sizeof(InquiryUnitSerialNumber->ProductSerialNumber);
for (i = 0; i < SerialNumberLength; i++)
{
unsigned char SerialNumberCharacter =
InquiryUnitSerialNumber->ProductSerialNumber[i];
SerialNumber[i] =
(SerialNumberCharacter >= ' ' && SerialNumberCharacter <= '~'
? SerialNumberCharacter : ' ');
}
SerialNumber[SerialNumberLength] = '\0';
}
/*
DAC960_V1_ReportDeviceConfiguration reports the Device Configuration
Information for DAC960 V1 Firmware Controllers.
*/
static bool DAC960_V1_ReportDeviceConfiguration(DAC960_Controller_T
*Controller)
{
int LogicalDriveNumber, Channel, TargetID;
DAC960_Info(" Physical Devices:\n", Controller);
for (Channel = 0; Channel < Controller->Channels; Channel++)
for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
{
DAC960_SCSI_Inquiry_T *InquiryStandardData =
&Controller->V1.InquiryStandardData[Channel][TargetID];
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
&Controller->V1.InquiryUnitSerialNumber[Channel][TargetID];
DAC960_V1_DeviceState_T *DeviceState =
&Controller->V1.DeviceState[Channel][TargetID];
DAC960_V1_ErrorTableEntry_T *ErrorEntry =
&Controller->V1.ErrorTable.ErrorTableEntries[Channel][TargetID];
char Vendor[1+sizeof(InquiryStandardData->VendorIdentification)];
char Model[1+sizeof(InquiryStandardData->ProductIdentification)];
char Revision[1+sizeof(InquiryStandardData->ProductRevisionLevel)];
char SerialNumber[1+sizeof(InquiryUnitSerialNumber
->ProductSerialNumber)];
if (InquiryStandardData->PeripheralDeviceType == 0x1F) continue;
DAC960_SanitizeInquiryData(InquiryStandardData, InquiryUnitSerialNumber,
Vendor, Model, Revision, SerialNumber);
DAC960_Info(" %d:%d%s Vendor: %s Model: %s Revision: %s\n",
Controller, Channel, TargetID, (TargetID < 10 ? " " : ""),
Vendor, Model, Revision);
if (InquiryUnitSerialNumber->PeripheralDeviceType != 0x1F)
DAC960_Info(" Serial Number: %s\n", Controller, SerialNumber);
if (DeviceState->Present &&
DeviceState->DeviceType == DAC960_V1_DiskType)
{
if (Controller->V1.DeviceResetCount[Channel][TargetID] > 0)
DAC960_Info(" Disk Status: %s, %u blocks, %d resets\n",
Controller,
(DeviceState->DeviceState == DAC960_V1_Device_Dead
? "Dead"
: DeviceState->DeviceState
== DAC960_V1_Device_WriteOnly
? "Write-Only"
: DeviceState->DeviceState
== DAC960_V1_Device_Online
? "Online" : "Standby"),
DeviceState->DiskSize,
Controller->V1.DeviceResetCount[Channel][TargetID]);
else
DAC960_Info(" Disk Status: %s, %u blocks\n", Controller,
(DeviceState->DeviceState == DAC960_V1_Device_Dead
? "Dead"
: DeviceState->DeviceState
== DAC960_V1_Device_WriteOnly
? "Write-Only"
: DeviceState->DeviceState
== DAC960_V1_Device_Online
? "Online" : "Standby"),
DeviceState->DiskSize);
}
if (ErrorEntry->ParityErrorCount > 0 ||
ErrorEntry->SoftErrorCount > 0 ||
ErrorEntry->HardErrorCount > 0 ||
ErrorEntry->MiscErrorCount > 0)
DAC960_Info(" Errors - Parity: %d, Soft: %d, "
"Hard: %d, Misc: %d\n", Controller,
ErrorEntry->ParityErrorCount,
ErrorEntry->SoftErrorCount,
ErrorEntry->HardErrorCount,
ErrorEntry->MiscErrorCount);
}
DAC960_Info(" Logical Drives:\n", Controller);
for (LogicalDriveNumber = 0;
LogicalDriveNumber < Controller->LogicalDriveCount;
LogicalDriveNumber++)
{
DAC960_V1_LogicalDriveInformation_T *LogicalDriveInformation =
&Controller->V1.LogicalDriveInformation[LogicalDriveNumber];
DAC960_Info(" /dev/rd/c%dd%d: RAID-%d, %s, %u blocks, %s\n",
Controller, Controller->ControllerNumber, LogicalDriveNumber,
LogicalDriveInformation->RAIDLevel,
(LogicalDriveInformation->LogicalDriveState
== DAC960_V1_LogicalDrive_Online
? "Online"
: LogicalDriveInformation->LogicalDriveState
== DAC960_V1_LogicalDrive_Critical
? "Critical" : "Offline"),
LogicalDriveInformation->LogicalDriveSize,
(LogicalDriveInformation->WriteBack
? "Write Back" : "Write Thru"));
}
return true;
}
/*
DAC960_V2_ReportDeviceConfiguration reports the Device Configuration
Information for DAC960 V2 Firmware Controllers.
*/
static bool DAC960_V2_ReportDeviceConfiguration(DAC960_Controller_T
*Controller)
{
int PhysicalDeviceIndex, LogicalDriveNumber;
DAC960_Info(" Physical Devices:\n", Controller);
for (PhysicalDeviceIndex = 0;
PhysicalDeviceIndex < DAC960_V2_MaxPhysicalDevices;
PhysicalDeviceIndex++)
{
DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
DAC960_SCSI_Inquiry_T *InquiryStandardData =
(DAC960_SCSI_Inquiry_T *) &PhysicalDeviceInfo->SCSI_InquiryData;
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
char Vendor[1+sizeof(InquiryStandardData->VendorIdentification)];
char Model[1+sizeof(InquiryStandardData->ProductIdentification)];
char Revision[1+sizeof(InquiryStandardData->ProductRevisionLevel)];
char SerialNumber[1+sizeof(InquiryUnitSerialNumber->ProductSerialNumber)];
if (PhysicalDeviceInfo == NULL) break;
DAC960_SanitizeInquiryData(InquiryStandardData, InquiryUnitSerialNumber,
Vendor, Model, Revision, SerialNumber);
DAC960_Info(" %d:%d%s Vendor: %s Model: %s Revision: %s\n",
Controller,
PhysicalDeviceInfo->Channel,
PhysicalDeviceInfo->TargetID,
(PhysicalDeviceInfo->TargetID < 10 ? " " : ""),
Vendor, Model, Revision);
if (PhysicalDeviceInfo->NegotiatedSynchronousMegaTransfers == 0)
DAC960_Info(" %sAsynchronous\n", Controller,
(PhysicalDeviceInfo->NegotiatedDataWidthBits == 16
? "Wide " :""));
else
DAC960_Info(" %sSynchronous at %d MB/sec\n", Controller,
(PhysicalDeviceInfo->NegotiatedDataWidthBits == 16
? "Wide " :""),
(PhysicalDeviceInfo->NegotiatedSynchronousMegaTransfers
* PhysicalDeviceInfo->NegotiatedDataWidthBits/8));
if (InquiryUnitSerialNumber->PeripheralDeviceType != 0x1F)
DAC960_Info(" Serial Number: %s\n", Controller, SerialNumber);
if (PhysicalDeviceInfo->PhysicalDeviceState ==
DAC960_V2_Device_Unconfigured)
continue;
DAC960_Info(" Disk Status: %s, %u blocks\n", Controller,
(PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Online
? "Online"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Rebuild
? "Rebuild"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Missing
? "Missing"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Critical
? "Critical"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Dead
? "Dead"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_SuspectedDead
? "Suspected-Dead"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_CommandedOffline
? "Commanded-Offline"
: PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Standby
? "Standby" : "Unknown"),
PhysicalDeviceInfo->ConfigurableDeviceSize);
if (PhysicalDeviceInfo->ParityErrors == 0 &&
PhysicalDeviceInfo->SoftErrors == 0 &&
PhysicalDeviceInfo->HardErrors == 0 &&
PhysicalDeviceInfo->MiscellaneousErrors == 0 &&
PhysicalDeviceInfo->CommandTimeouts == 0 &&
PhysicalDeviceInfo->Retries == 0 &&
PhysicalDeviceInfo->Aborts == 0 &&
PhysicalDeviceInfo->PredictedFailuresDetected == 0)
continue;
DAC960_Info(" Errors - Parity: %d, Soft: %d, "
"Hard: %d, Misc: %d\n", Controller,
PhysicalDeviceInfo->ParityErrors,
PhysicalDeviceInfo->SoftErrors,
PhysicalDeviceInfo->HardErrors,
PhysicalDeviceInfo->MiscellaneousErrors);
DAC960_Info(" Timeouts: %d, Retries: %d, "
"Aborts: %d, Predicted: %d\n", Controller,
PhysicalDeviceInfo->CommandTimeouts,
PhysicalDeviceInfo->Retries,
PhysicalDeviceInfo->Aborts,
PhysicalDeviceInfo->PredictedFailuresDetected);
}
DAC960_Info(" Logical Drives:\n", Controller);
for (LogicalDriveNumber = 0;
LogicalDriveNumber < DAC960_MaxLogicalDrives;
LogicalDriveNumber++)
{
DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
unsigned char *ReadCacheStatus[] = { "Read Cache Disabled",
"Read Cache Enabled",
"Read Ahead Enabled",
"Intelligent Read Ahead Enabled",
"-", "-", "-", "-" };
unsigned char *WriteCacheStatus[] = { "Write Cache Disabled",
"Logical Device Read Only",
"Write Cache Enabled",
"Intelligent Write Cache Enabled",
"-", "-", "-", "-" };
unsigned char *GeometryTranslation;
if (LogicalDeviceInfo == NULL) continue;
switch (LogicalDeviceInfo->DriveGeometry)
{
case DAC960_V2_Geometry_128_32:
GeometryTranslation = "128/32";
break;
case DAC960_V2_Geometry_255_63:
GeometryTranslation = "255/63";
break;
default:
GeometryTranslation = "Invalid";
DAC960_Error("Illegal Logical Device Geometry %d\n",
Controller, LogicalDeviceInfo->DriveGeometry);
break;
}
DAC960_Info(" /dev/rd/c%dd%d: RAID-%d, %s, %u blocks\n",
Controller, Controller->ControllerNumber, LogicalDriveNumber,
LogicalDeviceInfo->RAIDLevel,
(LogicalDeviceInfo->LogicalDeviceState
== DAC960_V2_LogicalDevice_Online
? "Online"
: LogicalDeviceInfo->LogicalDeviceState
== DAC960_V2_LogicalDevice_Critical
? "Critical" : "Offline"),
LogicalDeviceInfo->ConfigurableDeviceSize);
DAC960_Info(" Logical Device %s, BIOS Geometry: %s\n",
Controller,
(LogicalDeviceInfo->LogicalDeviceControl
.LogicalDeviceInitialized
? "Initialized" : "Uninitialized"),
GeometryTranslation);
if (LogicalDeviceInfo->StripeSize == 0)
{
if (LogicalDeviceInfo->CacheLineSize == 0)
DAC960_Info(" Stripe Size: N/A, "
"Segment Size: N/A\n", Controller);
else
DAC960_Info(" Stripe Size: N/A, "
"Segment Size: %dKB\n", Controller,
1 << (LogicalDeviceInfo->CacheLineSize - 2));
}
else
{
if (LogicalDeviceInfo->CacheLineSize == 0)
DAC960_Info(" Stripe Size: %dKB, "
"Segment Size: N/A\n", Controller,
1 << (LogicalDeviceInfo->StripeSize - 2));
else
DAC960_Info(" Stripe Size: %dKB, "
"Segment Size: %dKB\n", Controller,
1 << (LogicalDeviceInfo->StripeSize - 2),
1 << (LogicalDeviceInfo->CacheLineSize - 2));
}
DAC960_Info(" %s, %s\n", Controller,
ReadCacheStatus[
LogicalDeviceInfo->LogicalDeviceControl.ReadCache],
WriteCacheStatus[
LogicalDeviceInfo->LogicalDeviceControl.WriteCache]);
if (LogicalDeviceInfo->SoftErrors > 0 ||
LogicalDeviceInfo->CommandsFailed > 0 ||
LogicalDeviceInfo->DeferredWriteErrors)
DAC960_Info(" Errors - Soft: %d, Failed: %d, "
"Deferred Write: %d\n", Controller,
LogicalDeviceInfo->SoftErrors,
LogicalDeviceInfo->CommandsFailed,
LogicalDeviceInfo->DeferredWriteErrors);
}
return true;
}
/*
DAC960_RegisterBlockDevice registers the Block Device structures
associated with Controller.
*/
static bool DAC960_RegisterBlockDevice(DAC960_Controller_T *Controller)
{
int MajorNumber = DAC960_MAJOR + Controller->ControllerNumber;
int n;
/*
Register the Block Device Major Number for this DAC960 Controller.
*/
if (register_blkdev(MajorNumber, "dac960") < 0)
return false;
for (n = 0; n < DAC960_MaxLogicalDrives; n++) {
struct gendisk *disk = Controller->disks[n];
struct request_queue *RequestQueue;
/* for now, let all request queues share controller's lock */
RequestQueue = blk_init_queue(DAC960_RequestFunction,&Controller->queue_lock);
if (!RequestQueue) {
printk("DAC960: failure to allocate request queue\n");
continue;
}
Controller->RequestQueue[n] = RequestQueue;
blk_queue_bounce_limit(RequestQueue, Controller->BounceBufferLimit);
RequestQueue->queuedata = Controller;
blk_queue_max_hw_segments(RequestQueue, Controller->DriverScatterGatherLimit);
blk_queue_max_phys_segments(RequestQueue, Controller->DriverScatterGatherLimit);
blk_queue_max_sectors(RequestQueue, Controller->MaxBlocksPerCommand);
disk->queue = RequestQueue;
sprintf(disk->disk_name, "rd/c%dd%d", Controller->ControllerNumber, n);
disk->major = MajorNumber;
disk->first_minor = n << DAC960_MaxPartitionsBits;
disk->fops = &DAC960_BlockDeviceOperations;
}
/*
Indicate the Block Device Registration completed successfully,
*/
return true;
}
/*
DAC960_UnregisterBlockDevice unregisters the Block Device structures
associated with Controller.
*/
static void DAC960_UnregisterBlockDevice(DAC960_Controller_T *Controller)
{
int MajorNumber = DAC960_MAJOR + Controller->ControllerNumber;
int disk;
/* does order matter when deleting gendisk and cleanup in request queue? */
for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++) {
del_gendisk(Controller->disks[disk]);
blk_cleanup_queue(Controller->RequestQueue[disk]);
Controller->RequestQueue[disk] = NULL;
}
/*
Unregister the Block Device Major Number for this DAC960 Controller.
*/
unregister_blkdev(MajorNumber, "dac960");
}
/*
DAC960_ComputeGenericDiskInfo computes the values for the Generic Disk
Information Partition Sector Counts and Block Sizes.
*/
static void DAC960_ComputeGenericDiskInfo(DAC960_Controller_T *Controller)
{
int disk;
for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++)
set_capacity(Controller->disks[disk], disk_size(Controller, disk));
}
/*
DAC960_ReportErrorStatus reports Controller BIOS Messages passed through
the Error Status Register when the driver performs the BIOS handshaking.
It returns true for fatal errors and false otherwise.
*/
static bool DAC960_ReportErrorStatus(DAC960_Controller_T *Controller,
unsigned char ErrorStatus,
unsigned char Parameter0,
unsigned char Parameter1)
{
switch (ErrorStatus)
{
case 0x00:
DAC960_Notice("Physical Device %d:%d Not Responding\n",
Controller, Parameter1, Parameter0);
break;
case 0x08:
if (Controller->DriveSpinUpMessageDisplayed) break;
DAC960_Notice("Spinning Up Drives\n", Controller);
Controller->DriveSpinUpMessageDisplayed = true;
break;
case 0x30:
DAC960_Notice("Configuration Checksum Error\n", Controller);
break;
case 0x60:
DAC960_Notice("Mirror Race Recovery Failed\n", Controller);
break;
case 0x70:
DAC960_Notice("Mirror Race Recovery In Progress\n", Controller);
break;
case 0x90:
DAC960_Notice("Physical Device %d:%d COD Mismatch\n",
Controller, Parameter1, Parameter0);
break;
case 0xA0:
DAC960_Notice("Logical Drive Installation Aborted\n", Controller);
break;
case 0xB0:
DAC960_Notice("Mirror Race On A Critical Logical Drive\n", Controller);
break;
case 0xD0:
DAC960_Notice("New Controller Configuration Found\n", Controller);
break;
case 0xF0:
DAC960_Error("Fatal Memory Parity Error for Controller at\n", Controller);
return true;
default:
DAC960_Error("Unknown Initialization Error %02X for Controller at\n",
Controller, ErrorStatus);
return true;
}
return false;
}
/*
* DAC960_DetectCleanup releases the resources that were allocated
* during DAC960_DetectController(). DAC960_DetectController can
* has several internal failure points, so not ALL resources may
* have been allocated. It's important to free only
* resources that HAVE been allocated. The code below always
* tests that the resource has been allocated before attempting to
* free it.
*/
static void DAC960_DetectCleanup(DAC960_Controller_T *Controller)
{
int i;
/* Free the memory mailbox, status, and related structures */
free_dma_loaf(Controller->PCIDevice, &Controller->DmaPages);
if (Controller->MemoryMappedAddress) {
switch(Controller->HardwareType)
{
case DAC960_GEM_Controller:
DAC960_GEM_DisableInterrupts(Controller->BaseAddress);
break;
case DAC960_BA_Controller:
DAC960_BA_DisableInterrupts(Controller->BaseAddress);
break;
case DAC960_LP_Controller:
DAC960_LP_DisableInterrupts(Controller->BaseAddress);
break;
case DAC960_LA_Controller:
DAC960_LA_DisableInterrupts(Controller->BaseAddress);
break;
case DAC960_PG_Controller:
DAC960_PG_DisableInterrupts(Controller->BaseAddress);
break;
case DAC960_PD_Controller:
DAC960_PD_DisableInterrupts(Controller->BaseAddress);
break;
case DAC960_P_Controller:
DAC960_PD_DisableInterrupts(Controller->BaseAddress);
break;
}
iounmap(Controller->MemoryMappedAddress);
}
if (Controller->IRQ_Channel)
free_irq(Controller->IRQ_Channel, Controller);
if (Controller->IO_Address)
release_region(Controller->IO_Address, 0x80);
pci_disable_device(Controller->PCIDevice);
for (i = 0; (i < DAC960_MaxLogicalDrives) && Controller->disks[i]; i++)
put_disk(Controller->disks[i]);
DAC960_Controllers[Controller->ControllerNumber] = NULL;
kfree(Controller);
}
/*
DAC960_DetectController detects Mylex DAC960/AcceleRAID/eXtremeRAID
PCI RAID Controllers by interrogating the PCI Configuration Space for
Controller Type.
*/
static DAC960_Controller_T *
DAC960_DetectController(struct pci_dev *PCI_Device,
const struct pci_device_id *entry)
{
struct DAC960_privdata *privdata =
(struct DAC960_privdata *)entry->driver_data;
irq_handler_t InterruptHandler = privdata->InterruptHandler;
unsigned int MemoryWindowSize = privdata->MemoryWindowSize;
DAC960_Controller_T *Controller = NULL;
unsigned char DeviceFunction = PCI_Device->devfn;
unsigned char ErrorStatus, Parameter0, Parameter1;
unsigned int IRQ_Channel;
void __iomem *BaseAddress;
int i;
Controller = kzalloc(sizeof(DAC960_Controller_T), GFP_ATOMIC);
if (Controller == NULL) {
DAC960_Error("Unable to allocate Controller structure for "
"Controller at\n", NULL);
return NULL;
}
Controller->ControllerNumber = DAC960_ControllerCount;
DAC960_Controllers[DAC960_ControllerCount++] = Controller;
Controller->Bus = PCI_Device->bus->number;
Controller->FirmwareType = privdata->FirmwareType;
Controller->HardwareType = privdata->HardwareType;
Controller->Device = DeviceFunction >> 3;
Controller->Function = DeviceFunction & 0x7;
Controller->PCIDevice = PCI_Device;
strcpy(Controller->FullModelName, "DAC960");
if (pci_enable_device(PCI_Device))
goto Failure;
switch (Controller->HardwareType)
{
case DAC960_GEM_Controller:
Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
break;
case DAC960_BA_Controller:
Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
break;
case DAC960_LP_Controller:
Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
break;
case DAC960_LA_Controller:
Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
break;
case DAC960_PG_Controller:
Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
break;
case DAC960_PD_Controller:
Controller->IO_Address = pci_resource_start(PCI_Device, 0);
Controller->PCI_Address = pci_resource_start(PCI_Device, 1);
break;
case DAC960_P_Controller:
Controller->IO_Address = pci_resource_start(PCI_Device, 0);
Controller->PCI_Address = pci_resource_start(PCI_Device, 1);
break;
}
pci_set_drvdata(PCI_Device, (void *)((long)Controller->ControllerNumber));
for (i = 0; i < DAC960_MaxLogicalDrives; i++) {
Controller->disks[i] = alloc_disk(1<<DAC960_MaxPartitionsBits);
if (!Controller->disks[i])
goto Failure;
Controller->disks[i]->private_data = (void *)((long)i);
}
init_waitqueue_head(&Controller->CommandWaitQueue);
init_waitqueue_head(&Controller->HealthStatusWaitQueue);
spin_lock_init(&Controller->queue_lock);
DAC960_AnnounceDriver(Controller);
/*
Map the Controller Register Window.
*/
if (MemoryWindowSize < PAGE_SIZE)
MemoryWindowSize = PAGE_SIZE;
Controller->MemoryMappedAddress =
ioremap_nocache(Controller->PCI_Address & PAGE_MASK, MemoryWindowSize);
Controller->BaseAddress =
Controller->MemoryMappedAddress + (Controller->PCI_Address & ~PAGE_MASK);
if (Controller->MemoryMappedAddress == NULL)
{
DAC960_Error("Unable to map Controller Register Window for "
"Controller at\n", Controller);
goto Failure;
}
BaseAddress = Controller->BaseAddress;
switch (Controller->HardwareType)
{
case DAC960_GEM_Controller:
DAC960_GEM_DisableInterrupts(BaseAddress);
DAC960_GEM_AcknowledgeHardwareMailboxStatus(BaseAddress);
udelay(1000);
while (DAC960_GEM_InitializationInProgressP(BaseAddress))
{
if (DAC960_GEM_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to Enable Memory Mailbox Interface "
"for Controller at\n", Controller);
goto Failure;
}
DAC960_GEM_EnableInterrupts(BaseAddress);
Controller->QueueCommand = DAC960_GEM_QueueCommand;
Controller->ReadControllerConfiguration =
DAC960_V2_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V2_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V2_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V2_QueueReadWriteCommand;
break;
case DAC960_BA_Controller:
DAC960_BA_DisableInterrupts(BaseAddress);
DAC960_BA_AcknowledgeHardwareMailboxStatus(BaseAddress);
udelay(1000);
while (DAC960_BA_InitializationInProgressP(BaseAddress))
{
if (DAC960_BA_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to Enable Memory Mailbox Interface "
"for Controller at\n", Controller);
goto Failure;
}
DAC960_BA_EnableInterrupts(BaseAddress);
Controller->QueueCommand = DAC960_BA_QueueCommand;
Controller->ReadControllerConfiguration =
DAC960_V2_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V2_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V2_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V2_QueueReadWriteCommand;
break;
case DAC960_LP_Controller:
DAC960_LP_DisableInterrupts(BaseAddress);
DAC960_LP_AcknowledgeHardwareMailboxStatus(BaseAddress);
udelay(1000);
while (DAC960_LP_InitializationInProgressP(BaseAddress))
{
if (DAC960_LP_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to Enable Memory Mailbox Interface "
"for Controller at\n", Controller);
goto Failure;
}
DAC960_LP_EnableInterrupts(BaseAddress);
Controller->QueueCommand = DAC960_LP_QueueCommand;
Controller->ReadControllerConfiguration =
DAC960_V2_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V2_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V2_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V2_QueueReadWriteCommand;
break;
case DAC960_LA_Controller:
DAC960_LA_DisableInterrupts(BaseAddress);
DAC960_LA_AcknowledgeHardwareMailboxStatus(BaseAddress);
udelay(1000);
while (DAC960_LA_InitializationInProgressP(BaseAddress))
{
if (DAC960_LA_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to Enable Memory Mailbox Interface "
"for Controller at\n", Controller);
goto Failure;
}
DAC960_LA_EnableInterrupts(BaseAddress);
if (Controller->V1.DualModeMemoryMailboxInterface)
Controller->QueueCommand = DAC960_LA_QueueCommandDualMode;
else Controller->QueueCommand = DAC960_LA_QueueCommandSingleMode;
Controller->ReadControllerConfiguration =
DAC960_V1_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V1_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V1_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V1_QueueReadWriteCommand;
break;
case DAC960_PG_Controller:
DAC960_PG_DisableInterrupts(BaseAddress);
DAC960_PG_AcknowledgeHardwareMailboxStatus(BaseAddress);
udelay(1000);
while (DAC960_PG_InitializationInProgressP(BaseAddress))
{
if (DAC960_PG_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to Enable Memory Mailbox Interface "
"for Controller at\n", Controller);
goto Failure;
}
DAC960_PG_EnableInterrupts(BaseAddress);
if (Controller->V1.DualModeMemoryMailboxInterface)
Controller->QueueCommand = DAC960_PG_QueueCommandDualMode;
else Controller->QueueCommand = DAC960_PG_QueueCommandSingleMode;
Controller->ReadControllerConfiguration =
DAC960_V1_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V1_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V1_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V1_QueueReadWriteCommand;
break;
case DAC960_PD_Controller:
if (!request_region(Controller->IO_Address, 0x80,
Controller->FullModelName)) {
DAC960_Error("IO port 0x%d busy for Controller at\n",
Controller, Controller->IO_Address);
goto Failure;
}
DAC960_PD_DisableInterrupts(BaseAddress);
DAC960_PD_AcknowledgeStatus(BaseAddress);
udelay(1000);
while (DAC960_PD_InitializationInProgressP(BaseAddress))
{
if (DAC960_PD_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to allocate DMA mapped memory "
"for Controller at\n", Controller);
goto Failure;
}
DAC960_PD_EnableInterrupts(BaseAddress);
Controller->QueueCommand = DAC960_PD_QueueCommand;
Controller->ReadControllerConfiguration =
DAC960_V1_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V1_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V1_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V1_QueueReadWriteCommand;
break;
case DAC960_P_Controller:
if (!request_region(Controller->IO_Address, 0x80,
Controller->FullModelName)){
DAC960_Error("IO port 0x%d busy for Controller at\n",
Controller, Controller->IO_Address);
goto Failure;
}
DAC960_PD_DisableInterrupts(BaseAddress);
DAC960_PD_AcknowledgeStatus(BaseAddress);
udelay(1000);
while (DAC960_PD_InitializationInProgressP(BaseAddress))
{
if (DAC960_PD_ReadErrorStatus(BaseAddress, &ErrorStatus,
&Parameter0, &Parameter1) &&
DAC960_ReportErrorStatus(Controller, ErrorStatus,
Parameter0, Parameter1))
goto Failure;
udelay(10);
}
if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
{
DAC960_Error("Unable to allocate DMA mapped memory"
"for Controller at\n", Controller);
goto Failure;
}
DAC960_PD_EnableInterrupts(BaseAddress);
Controller->QueueCommand = DAC960_P_QueueCommand;
Controller->ReadControllerConfiguration =
DAC960_V1_ReadControllerConfiguration;
Controller->ReadDeviceConfiguration =
DAC960_V1_ReadDeviceConfiguration;
Controller->ReportDeviceConfiguration =
DAC960_V1_ReportDeviceConfiguration;
Controller->QueueReadWriteCommand =
DAC960_V1_QueueReadWriteCommand;
break;
}
/*
Acquire shared access to the IRQ Channel.
*/
IRQ_Channel = PCI_Device->irq;
if (request_irq(IRQ_Channel, InterruptHandler, IRQF_SHARED,
Controller->FullModelName, Controller) < 0)
{
DAC960_Error("Unable to acquire IRQ Channel %d for Controller at\n",
Controller, Controller->IRQ_Channel);
goto Failure;
}
Controller->IRQ_Channel = IRQ_Channel;
Controller->InitialCommand.CommandIdentifier = 1;
Controller->InitialCommand.Controller = Controller;
Controller->Commands[0] = &Controller->InitialCommand;
Controller->FreeCommands = &Controller->InitialCommand;
return Controller;
Failure:
if (Controller->IO_Address == 0)
DAC960_Error("PCI Bus %d Device %d Function %d I/O Address N/A "
"PCI Address 0x%X\n", Controller,
Controller->Bus, Controller->Device,
Controller->Function, Controller->PCI_Address);
else
DAC960_Error("PCI Bus %d Device %d Function %d I/O Address "
"0x%X PCI Address 0x%X\n", Controller,
Controller->Bus, Controller->Device,
Controller->Function, Controller->IO_Address,
Controller->PCI_Address);
DAC960_DetectCleanup(Controller);
DAC960_ControllerCount--;
return NULL;
}
/*
DAC960_InitializeController initializes Controller.
*/
static bool
DAC960_InitializeController(DAC960_Controller_T *Controller)
{
if (DAC960_ReadControllerConfiguration(Controller) &&
DAC960_ReportControllerConfiguration(Controller) &&
DAC960_CreateAuxiliaryStructures(Controller) &&
DAC960_ReadDeviceConfiguration(Controller) &&
DAC960_ReportDeviceConfiguration(Controller) &&
DAC960_RegisterBlockDevice(Controller))
{
/*
Initialize the Monitoring Timer.
*/
init_timer(&Controller->MonitoringTimer);
Controller->MonitoringTimer.expires =
jiffies + DAC960_MonitoringTimerInterval;
Controller->MonitoringTimer.data = (unsigned long) Controller;
Controller->MonitoringTimer.function = DAC960_MonitoringTimerFunction;
add_timer(&Controller->MonitoringTimer);
Controller->ControllerInitialized = true;
return true;
}
return false;
}
/*
DAC960_FinalizeController finalizes Controller.
*/
static void DAC960_FinalizeController(DAC960_Controller_T *Controller)
{
if (Controller->ControllerInitialized)
{
unsigned long flags;
/*
* Acquiring and releasing lock here eliminates
* a very low probability race.
*
* The code below allocates controller command structures
* from the free list without holding the controller lock.
* This is safe assuming there is no other activity on
* the controller at the time.
*
* But, there might be a monitoring command still
* in progress. Setting the Shutdown flag while holding
* the lock ensures that there is no monitoring command
* in the interrupt handler currently, and any monitoring
* commands that complete from this time on will NOT return
* their command structure to the free list.
*/
spin_lock_irqsave(&Controller->queue_lock, flags);
Controller->ShutdownMonitoringTimer = 1;
spin_unlock_irqrestore(&Controller->queue_lock, flags);
del_timer_sync(&Controller->MonitoringTimer);
if (Controller->FirmwareType == DAC960_V1_Controller)
{
DAC960_Notice("Flushing Cache...", Controller);
DAC960_V1_ExecuteType3(Controller, DAC960_V1_Flush, 0);
DAC960_Notice("done\n", Controller);
if (Controller->HardwareType == DAC960_PD_Controller)
release_region(Controller->IO_Address, 0x80);
}
else
{
DAC960_Notice("Flushing Cache...", Controller);
DAC960_V2_DeviceOperation(Controller, DAC960_V2_PauseDevice,
DAC960_V2_RAID_Controller);
DAC960_Notice("done\n", Controller);
}
}
DAC960_UnregisterBlockDevice(Controller);
DAC960_DestroyAuxiliaryStructures(Controller);
DAC960_DestroyProcEntries(Controller);
DAC960_DetectCleanup(Controller);
}
/*
DAC960_Probe verifies controller's existence and
initializes the DAC960 Driver for that controller.
*/
static int
DAC960_Probe(struct pci_dev *dev, const struct pci_device_id *entry)
{
int disk;
DAC960_Controller_T *Controller;
if (DAC960_ControllerCount == DAC960_MaxControllers)
{
DAC960_Error("More than %d DAC960 Controllers detected - "
"ignoring from Controller at\n",
NULL, DAC960_MaxControllers);
return -ENODEV;
}
Controller = DAC960_DetectController(dev, entry);
if (!Controller)
return -ENODEV;
if (!DAC960_InitializeController(Controller)) {
DAC960_FinalizeController(Controller);
return -ENODEV;
}
for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++) {
set_capacity(Controller->disks[disk], disk_size(Controller, disk));
add_disk(Controller->disks[disk]);
}
DAC960_CreateProcEntries(Controller);
return 0;
}
/*
DAC960_Finalize finalizes the DAC960 Driver.
*/
static void DAC960_Remove(struct pci_dev *PCI_Device)
{
int Controller_Number = (long)pci_get_drvdata(PCI_Device);
DAC960_Controller_T *Controller = DAC960_Controllers[Controller_Number];
if (Controller != NULL)
DAC960_FinalizeController(Controller);
}
/*
DAC960_V1_QueueReadWriteCommand prepares and queues a Read/Write Command for
DAC960 V1 Firmware Controllers.
*/
static void DAC960_V1_QueueReadWriteCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_ScatterGatherSegment_T *ScatterGatherList =
Command->V1.ScatterGatherList;
struct scatterlist *ScatterList = Command->V1.ScatterList;
DAC960_V1_ClearCommand(Command);
if (Command->SegmentCount == 1)
{
if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
CommandMailbox->Type5.CommandOpcode = DAC960_V1_Read;
else
CommandMailbox->Type5.CommandOpcode = DAC960_V1_Write;
CommandMailbox->Type5.LD.TransferLength = Command->BlockCount;
CommandMailbox->Type5.LD.LogicalDriveNumber = Command->LogicalDriveNumber;
CommandMailbox->Type5.LogicalBlockAddress = Command->BlockNumber;
CommandMailbox->Type5.BusAddress =
(DAC960_BusAddress32_T)sg_dma_address(ScatterList);
}
else
{
int i;
if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
CommandMailbox->Type5.CommandOpcode = DAC960_V1_ReadWithScatterGather;
else
CommandMailbox->Type5.CommandOpcode = DAC960_V1_WriteWithScatterGather;
CommandMailbox->Type5.LD.TransferLength = Command->BlockCount;
CommandMailbox->Type5.LD.LogicalDriveNumber = Command->LogicalDriveNumber;
CommandMailbox->Type5.LogicalBlockAddress = Command->BlockNumber;
CommandMailbox->Type5.BusAddress = Command->V1.ScatterGatherListDMA;
CommandMailbox->Type5.ScatterGatherCount = Command->SegmentCount;
for (i = 0; i < Command->SegmentCount; i++, ScatterList++, ScatterGatherList++) {
ScatterGatherList->SegmentDataPointer =
(DAC960_BusAddress32_T)sg_dma_address(ScatterList);
ScatterGatherList->SegmentByteCount =
(DAC960_ByteCount32_T)sg_dma_len(ScatterList);
}
}
DAC960_QueueCommand(Command);
}
/*
DAC960_V2_QueueReadWriteCommand prepares and queues a Read/Write Command for
DAC960 V2 Firmware Controllers.
*/
static void DAC960_V2_QueueReadWriteCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
struct scatterlist *ScatterList = Command->V2.ScatterList;
DAC960_V2_ClearCommand(Command);
CommandMailbox->SCSI_10.CommandOpcode = DAC960_V2_SCSI_10;
CommandMailbox->SCSI_10.CommandControlBits.DataTransferControllerToHost =
(Command->DmaDirection == PCI_DMA_FROMDEVICE);
CommandMailbox->SCSI_10.DataTransferSize =
Command->BlockCount << DAC960_BlockSizeBits;
CommandMailbox->SCSI_10.RequestSenseBusAddress = Command->V2.RequestSenseDMA;
CommandMailbox->SCSI_10.PhysicalDevice =
Controller->V2.LogicalDriveToVirtualDevice[Command->LogicalDriveNumber];
CommandMailbox->SCSI_10.RequestSenseSize = sizeof(DAC960_SCSI_RequestSense_T);
CommandMailbox->SCSI_10.CDBLength = 10;
CommandMailbox->SCSI_10.SCSI_CDB[0] =
(Command->DmaDirection == PCI_DMA_FROMDEVICE ? 0x28 : 0x2A);
CommandMailbox->SCSI_10.SCSI_CDB[2] = Command->BlockNumber >> 24;
CommandMailbox->SCSI_10.SCSI_CDB[3] = Command->BlockNumber >> 16;
CommandMailbox->SCSI_10.SCSI_CDB[4] = Command->BlockNumber >> 8;
CommandMailbox->SCSI_10.SCSI_CDB[5] = Command->BlockNumber;
CommandMailbox->SCSI_10.SCSI_CDB[7] = Command->BlockCount >> 8;
CommandMailbox->SCSI_10.SCSI_CDB[8] = Command->BlockCount;
if (Command->SegmentCount == 1)
{
CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
(DAC960_BusAddress64_T)sg_dma_address(ScatterList);
CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->SCSI_10.DataTransferSize;
}
else
{
DAC960_V2_ScatterGatherSegment_T *ScatterGatherList;
int i;
if (Command->SegmentCount > 2)
{
ScatterGatherList = Command->V2.ScatterGatherList;
CommandMailbox->SCSI_10.CommandControlBits
.AdditionalScatterGatherListMemory = true;
CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ExtendedScatterGather.ScatterGatherList0Length = Command->SegmentCount;
CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ExtendedScatterGather.ScatterGatherList0Address =
Command->V2.ScatterGatherListDMA;
}
else
ScatterGatherList = CommandMailbox->SCSI_10.DataTransferMemoryAddress
.ScatterGatherSegments;
for (i = 0; i < Command->SegmentCount; i++, ScatterList++, ScatterGatherList++) {
ScatterGatherList->SegmentDataPointer =
(DAC960_BusAddress64_T)sg_dma_address(ScatterList);
ScatterGatherList->SegmentByteCount =
(DAC960_ByteCount64_T)sg_dma_len(ScatterList);
}
}
DAC960_QueueCommand(Command);
}
static int DAC960_process_queue(DAC960_Controller_T *Controller, struct request_queue *req_q)
{
struct request *Request;
DAC960_Command_T *Command;
while(1) {
Request = elv_next_request(req_q);
if (!Request)
return 1;
Command = DAC960_AllocateCommand(Controller);
if (Command == NULL)
return 0;
if (rq_data_dir(Request) == READ) {
Command->DmaDirection = PCI_DMA_FROMDEVICE;
Command->CommandType = DAC960_ReadCommand;
} else {
Command->DmaDirection = PCI_DMA_TODEVICE;
Command->CommandType = DAC960_WriteCommand;
}
Command->Completion = Request->end_io_data;
Command->LogicalDriveNumber = (long)Request->rq_disk->private_data;
Command->BlockNumber = Request->sector;
Command->BlockCount = Request->nr_sectors;
Command->Request = Request;
blkdev_dequeue_request(Request);
Command->SegmentCount = blk_rq_map_sg(req_q,
Command->Request, Command->cmd_sglist);
/* pci_map_sg MAY change the value of SegCount */
Command->SegmentCount = pci_map_sg(Controller->PCIDevice, Command->cmd_sglist,
Command->SegmentCount, Command->DmaDirection);
DAC960_QueueReadWriteCommand(Command);
}
}
/*
DAC960_ProcessRequest attempts to remove one I/O Request from Controller's
I/O Request Queue and queues it to the Controller. WaitForCommand is true if
this function should wait for a Command to become available if necessary.
This function returns true if an I/O Request was queued and false otherwise.
*/
static void DAC960_ProcessRequest(DAC960_Controller_T *controller)
{
int i;
if (!controller->ControllerInitialized)
return;
/* Do this better later! */
for (i = controller->req_q_index; i < DAC960_MaxLogicalDrives; i++) {
struct request_queue *req_q = controller->RequestQueue[i];
if (req_q == NULL)
continue;
if (!DAC960_process_queue(controller, req_q)) {
controller->req_q_index = i;
return;
}
}
if (controller->req_q_index == 0)
return;
for (i = 0; i < controller->req_q_index; i++) {
struct request_queue *req_q = controller->RequestQueue[i];
if (req_q == NULL)
continue;
if (!DAC960_process_queue(controller, req_q)) {
controller->req_q_index = i;
return;
}
}
}
/*
DAC960_queue_partial_rw extracts one bio from the request already
associated with argument command, and construct a new command block to retry I/O
only on that bio. Queue that command to the controller.
This function re-uses a previously-allocated Command,
there is no failure mode from trying to allocate a command.
*/
static void DAC960_queue_partial_rw(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
struct request *Request = Command->Request;
struct request_queue *req_q = Controller->RequestQueue[Command->LogicalDriveNumber];
if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
Command->CommandType = DAC960_ReadRetryCommand;
else
Command->CommandType = DAC960_WriteRetryCommand;
/*
* We could be more efficient with these mapping requests
* and map only the portions that we need. But since this
* code should almost never be called, just go with a
* simple coding.
*/
(void)blk_rq_map_sg(req_q, Command->Request, Command->cmd_sglist);
(void)pci_map_sg(Controller->PCIDevice, Command->cmd_sglist, 1, Command->DmaDirection);
/*
* Resubmitting the request sector at a time is really tedious.
* But, this should almost never happen. So, we're willing to pay
* this price so that in the end, as much of the transfer is completed
* successfully as possible.
*/
Command->SegmentCount = 1;
Command->BlockNumber = Request->sector;
Command->BlockCount = 1;
DAC960_QueueReadWriteCommand(Command);
return;
}
/*
DAC960_RequestFunction is the I/O Request Function for DAC960 Controllers.
*/
static void DAC960_RequestFunction(struct request_queue *RequestQueue)
{
DAC960_ProcessRequest(RequestQueue->queuedata);
}
/*
DAC960_ProcessCompletedBuffer performs completion processing for an
individual Buffer.
*/
static inline bool DAC960_ProcessCompletedRequest(DAC960_Command_T *Command,
bool SuccessfulIO)
{
struct request *Request = Command->Request;
int Error = SuccessfulIO ? 0 : -EIO;
pci_unmap_sg(Command->Controller->PCIDevice, Command->cmd_sglist,
Command->SegmentCount, Command->DmaDirection);
if (!__blk_end_request(Request, Error, Command->BlockCount << 9)) {
if (Command->Completion) {
complete(Command->Completion);
Command->Completion = NULL;
}
return true;
}
return false;
}
/*
DAC960_V1_ReadWriteError prints an appropriate error message for Command
when an error occurs on a Read or Write operation.
*/
static void DAC960_V1_ReadWriteError(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
unsigned char *CommandName = "UNKNOWN";
switch (Command->CommandType)
{
case DAC960_ReadCommand:
case DAC960_ReadRetryCommand:
CommandName = "READ";
break;
case DAC960_WriteCommand:
case DAC960_WriteRetryCommand:
CommandName = "WRITE";
break;
case DAC960_MonitoringCommand:
case DAC960_ImmediateCommand:
case DAC960_QueuedCommand:
break;
}
switch (Command->V1.CommandStatus)
{
case DAC960_V1_IrrecoverableDataError:
DAC960_Error("Irrecoverable Data Error on %s:\n",
Controller, CommandName);
break;
case DAC960_V1_LogicalDriveNonexistentOrOffline:
DAC960_Error("Logical Drive Nonexistent or Offline on %s:\n",
Controller, CommandName);
break;
case DAC960_V1_AccessBeyondEndOfLogicalDrive:
DAC960_Error("Attempt to Access Beyond End of Logical Drive "
"on %s:\n", Controller, CommandName);
break;
case DAC960_V1_BadDataEncountered:
DAC960_Error("Bad Data Encountered on %s:\n", Controller, CommandName);
break;
default:
DAC960_Error("Unexpected Error Status %04X on %s:\n",
Controller, Command->V1.CommandStatus, CommandName);
break;
}
DAC960_Error(" /dev/rd/c%dd%d: absolute blocks %u..%u\n",
Controller, Controller->ControllerNumber,
Command->LogicalDriveNumber, Command->BlockNumber,
Command->BlockNumber + Command->BlockCount - 1);
}
/*
DAC960_V1_ProcessCompletedCommand performs completion processing for Command
for DAC960 V1 Firmware Controllers.
*/
static void DAC960_V1_ProcessCompletedCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DAC960_CommandType_T CommandType = Command->CommandType;
DAC960_V1_CommandOpcode_T CommandOpcode =
Command->V1.CommandMailbox.Common.CommandOpcode;
DAC960_V1_CommandStatus_T CommandStatus = Command->V1.CommandStatus;
if (CommandType == DAC960_ReadCommand ||
CommandType == DAC960_WriteCommand)
{
#ifdef FORCE_RETRY_DEBUG
CommandStatus = DAC960_V1_IrrecoverableDataError;
#endif
if (CommandStatus == DAC960_V1_NormalCompletion) {
if (!DAC960_ProcessCompletedRequest(Command, true))
BUG();
} else if (CommandStatus == DAC960_V1_IrrecoverableDataError ||
CommandStatus == DAC960_V1_BadDataEncountered)
{
/*
* break the command down into pieces and resubmit each
* piece, hoping that some of them will succeed.
*/
DAC960_queue_partial_rw(Command);
return;
}
else
{
if (CommandStatus != DAC960_V1_LogicalDriveNonexistentOrOffline)
DAC960_V1_ReadWriteError(Command);
if (!DAC960_ProcessCompletedRequest(Command, false))
BUG();
}
}
else if (CommandType == DAC960_ReadRetryCommand ||
CommandType == DAC960_WriteRetryCommand)
{
bool normal_completion;
#ifdef FORCE_RETRY_FAILURE_DEBUG
static int retry_count = 1;
#endif
/*
Perform completion processing for the portion that was
retried, and submit the next portion, if any.
*/
normal_completion = true;
if (CommandStatus != DAC960_V1_NormalCompletion) {
normal_completion = false;
if (CommandStatus != DAC960_V1_LogicalDriveNonexistentOrOffline)
DAC960_V1_ReadWriteError(Command);
}
#ifdef FORCE_RETRY_FAILURE_DEBUG
if (!(++retry_count % 10000)) {
printk("V1 error retry failure test\n");
normal_completion = false;
DAC960_V1_ReadWriteError(Command);
}
#endif
if (!DAC960_ProcessCompletedRequest(Command, normal_completion)) {
DAC960_queue_partial_rw(Command);
return;
}
}
else if (CommandType == DAC960_MonitoringCommand)
{
if (Controller->ShutdownMonitoringTimer)
return;
if (CommandOpcode == DAC960_V1_Enquiry)
{
DAC960_V1_Enquiry_T *OldEnquiry = &Controller->V1.Enquiry;
DAC960_V1_Enquiry_T *NewEnquiry = Controller->V1.NewEnquiry;
unsigned int OldCriticalLogicalDriveCount =
OldEnquiry->CriticalLogicalDriveCount;
unsigned int NewCriticalLogicalDriveCount =
NewEnquiry->CriticalLogicalDriveCount;
if (NewEnquiry->NumberOfLogicalDrives > Controller->LogicalDriveCount)
{
int LogicalDriveNumber = Controller->LogicalDriveCount - 1;
while (++LogicalDriveNumber < NewEnquiry->NumberOfLogicalDrives)
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"Now Exists\n", Controller,
LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
Controller->LogicalDriveCount = NewEnquiry->NumberOfLogicalDrives;
DAC960_ComputeGenericDiskInfo(Controller);
}
if (NewEnquiry->NumberOfLogicalDrives < Controller->LogicalDriveCount)
{
int LogicalDriveNumber = NewEnquiry->NumberOfLogicalDrives - 1;
while (++LogicalDriveNumber < Controller->LogicalDriveCount)
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"No Longer Exists\n", Controller,
LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
Controller->LogicalDriveCount = NewEnquiry->NumberOfLogicalDrives;
DAC960_ComputeGenericDiskInfo(Controller);
}
if (NewEnquiry->StatusFlags.DeferredWriteError !=
OldEnquiry->StatusFlags.DeferredWriteError)
DAC960_Critical("Deferred Write Error Flag is now %s\n", Controller,
(NewEnquiry->StatusFlags.DeferredWriteError
? "TRUE" : "FALSE"));
if ((NewCriticalLogicalDriveCount > 0 ||
NewCriticalLogicalDriveCount != OldCriticalLogicalDriveCount) ||
(NewEnquiry->OfflineLogicalDriveCount > 0 ||
NewEnquiry->OfflineLogicalDriveCount !=
OldEnquiry->OfflineLogicalDriveCount) ||
(NewEnquiry->DeadDriveCount > 0 ||
NewEnquiry->DeadDriveCount !=
OldEnquiry->DeadDriveCount) ||
(NewEnquiry->EventLogSequenceNumber !=
OldEnquiry->EventLogSequenceNumber) ||
Controller->MonitoringTimerCount == 0 ||
time_after_eq(jiffies, Controller->SecondaryMonitoringTime
+ DAC960_SecondaryMonitoringInterval))
{
Controller->V1.NeedLogicalDriveInformation = true;
Controller->V1.NewEventLogSequenceNumber =
NewEnquiry->EventLogSequenceNumber;
Controller->V1.NeedErrorTableInformation = true;
Controller->V1.NeedDeviceStateInformation = true;
Controller->V1.StartDeviceStateScan = true;
Controller->V1.NeedBackgroundInitializationStatus =
Controller->V1.BackgroundInitializationStatusSupported;
Controller->SecondaryMonitoringTime = jiffies;
}
if (NewEnquiry->RebuildFlag == DAC960_V1_StandbyRebuildInProgress ||
NewEnquiry->RebuildFlag
== DAC960_V1_BackgroundRebuildInProgress ||
OldEnquiry->RebuildFlag == DAC960_V1_StandbyRebuildInProgress ||
OldEnquiry->RebuildFlag == DAC960_V1_BackgroundRebuildInProgress)
{
Controller->V1.NeedRebuildProgress = true;
Controller->V1.RebuildProgressFirst =
(NewEnquiry->CriticalLogicalDriveCount <
OldEnquiry->CriticalLogicalDriveCount);
}
if (OldEnquiry->RebuildFlag == DAC960_V1_BackgroundCheckInProgress)
switch (NewEnquiry->RebuildFlag)
{
case DAC960_V1_NoStandbyRebuildOrCheckInProgress:
DAC960_Progress("Consistency Check Completed Successfully\n",
Controller);
break;
case DAC960_V1_StandbyRebuildInProgress:
case DAC960_V1_BackgroundRebuildInProgress:
break;
case DAC960_V1_BackgroundCheckInProgress:
Controller->V1.NeedConsistencyCheckProgress = true;
break;
case DAC960_V1_StandbyRebuildCompletedWithError:
DAC960_Progress("Consistency Check Completed with Error\n",
Controller);
break;
case DAC960_V1_BackgroundRebuildOrCheckFailed_DriveFailed:
DAC960_Progress("Consistency Check Failed - "
"Physical Device Failed\n", Controller);
break;
case DAC960_V1_BackgroundRebuildOrCheckFailed_LogicalDriveFailed:
DAC960_Progress("Consistency Check Failed - "
"Logical Drive Failed\n", Controller);
break;
case DAC960_V1_BackgroundRebuildOrCheckFailed_OtherCauses:
DAC960_Progress("Consistency Check Failed - Other Causes\n",
Controller);
break;
case DAC960_V1_BackgroundRebuildOrCheckSuccessfullyTerminated:
DAC960_Progress("Consistency Check Successfully Terminated\n",
Controller);
break;
}
else if (NewEnquiry->RebuildFlag
== DAC960_V1_BackgroundCheckInProgress)
Controller->V1.NeedConsistencyCheckProgress = true;
Controller->MonitoringAlertMode =
(NewEnquiry->CriticalLogicalDriveCount > 0 ||
NewEnquiry->OfflineLogicalDriveCount > 0 ||
NewEnquiry->DeadDriveCount > 0);
if (NewEnquiry->RebuildFlag > DAC960_V1_BackgroundCheckInProgress)
{
Controller->V1.PendingRebuildFlag = NewEnquiry->RebuildFlag;
Controller->V1.RebuildFlagPending = true;
}
memcpy(&Controller->V1.Enquiry, &Controller->V1.NewEnquiry,
sizeof(DAC960_V1_Enquiry_T));
}
else if (CommandOpcode == DAC960_V1_PerformEventLogOperation)
{
static char
*DAC960_EventMessages[] =
{ "killed because write recovery failed",
"killed because of SCSI bus reset failure",
"killed because of double check condition",
"killed because it was removed",
"killed because of gross error on SCSI chip",
"killed because of bad tag returned from drive",
"killed because of timeout on SCSI command",
"killed because of reset SCSI command issued from system",
"killed because busy or parity error count exceeded limit",
"killed because of 'kill drive' command from system",
"killed because of selection timeout",
"killed due to SCSI phase sequence error",
"killed due to unknown status" };
DAC960_V1_EventLogEntry_T *EventLogEntry =
Controller->V1.EventLogEntry;
if (EventLogEntry->SequenceNumber ==
Controller->V1.OldEventLogSequenceNumber)
{
unsigned char SenseKey = EventLogEntry->SenseKey;
unsigned char AdditionalSenseCode =
EventLogEntry->AdditionalSenseCode;
unsigned char AdditionalSenseCodeQualifier =
EventLogEntry->AdditionalSenseCodeQualifier;
if (SenseKey == DAC960_SenseKey_VendorSpecific &&
AdditionalSenseCode == 0x80 &&
AdditionalSenseCodeQualifier <
ARRAY_SIZE(DAC960_EventMessages))
DAC960_Critical("Physical Device %d:%d %s\n", Controller,
EventLogEntry->Channel,
EventLogEntry->TargetID,
DAC960_EventMessages[
AdditionalSenseCodeQualifier]);
else if (SenseKey == DAC960_SenseKey_UnitAttention &&
AdditionalSenseCode == 0x29)
{
if (Controller->MonitoringTimerCount > 0)
Controller->V1.DeviceResetCount[EventLogEntry->Channel]
[EventLogEntry->TargetID]++;
}
else if (!(SenseKey == DAC960_SenseKey_NoSense ||
(SenseKey == DAC960_SenseKey_NotReady &&
AdditionalSenseCode == 0x04 &&
(AdditionalSenseCodeQualifier == 0x01 ||
AdditionalSenseCodeQualifier == 0x02))))
{
DAC960_Critical("Physical Device %d:%d Error Log: "
"Sense Key = %X, ASC = %02X, ASCQ = %02X\n",
Controller,
EventLogEntry->Channel,
EventLogEntry->TargetID,
SenseKey,
AdditionalSenseCode,
AdditionalSenseCodeQualifier);
DAC960_Critical("Physical Device %d:%d Error Log: "
"Information = %02X%02X%02X%02X "
"%02X%02X%02X%02X\n",
Controller,
EventLogEntry->Channel,
EventLogEntry->TargetID,
EventLogEntry->Information[0],
EventLogEntry->Information[1],
EventLogEntry->Information[2],
EventLogEntry->Information[3],
EventLogEntry->CommandSpecificInformation[0],
EventLogEntry->CommandSpecificInformation[1],
EventLogEntry->CommandSpecificInformation[2],
EventLogEntry->CommandSpecificInformation[3]);
}
}
Controller->V1.OldEventLogSequenceNumber++;
}
else if (CommandOpcode == DAC960_V1_GetErrorTable)
{
DAC960_V1_ErrorTable_T *OldErrorTable = &Controller->V1.ErrorTable;
DAC960_V1_ErrorTable_T *NewErrorTable = Controller->V1.NewErrorTable;
int Channel, TargetID;
for (Channel = 0; Channel < Controller->Channels; Channel++)
for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
{
DAC960_V1_ErrorTableEntry_T *NewErrorEntry =
&NewErrorTable->ErrorTableEntries[Channel][TargetID];
DAC960_V1_ErrorTableEntry_T *OldErrorEntry =
&OldErrorTable->ErrorTableEntries[Channel][TargetID];
if ((NewErrorEntry->ParityErrorCount !=
OldErrorEntry->ParityErrorCount) ||
(NewErrorEntry->SoftErrorCount !=
OldErrorEntry->SoftErrorCount) ||
(NewErrorEntry->HardErrorCount !=
OldErrorEntry->HardErrorCount) ||
(NewErrorEntry->MiscErrorCount !=
OldErrorEntry->MiscErrorCount))
DAC960_Critical("Physical Device %d:%d Errors: "
"Parity = %d, Soft = %d, "
"Hard = %d, Misc = %d\n",
Controller, Channel, TargetID,
NewErrorEntry->ParityErrorCount,
NewErrorEntry->SoftErrorCount,
NewErrorEntry->HardErrorCount,
NewErrorEntry->MiscErrorCount);
}
memcpy(&Controller->V1.ErrorTable, Controller->V1.NewErrorTable,
sizeof(DAC960_V1_ErrorTable_T));
}
else if (CommandOpcode == DAC960_V1_GetDeviceState)
{
DAC960_V1_DeviceState_T *OldDeviceState =
&Controller->V1.DeviceState[Controller->V1.DeviceStateChannel]
[Controller->V1.DeviceStateTargetID];
DAC960_V1_DeviceState_T *NewDeviceState =
Controller->V1.NewDeviceState;
if (NewDeviceState->DeviceState != OldDeviceState->DeviceState)
DAC960_Critical("Physical Device %d:%d is now %s\n", Controller,
Controller->V1.DeviceStateChannel,
Controller->V1.DeviceStateTargetID,
(NewDeviceState->DeviceState
== DAC960_V1_Device_Dead
? "DEAD"
: NewDeviceState->DeviceState
== DAC960_V1_Device_WriteOnly
? "WRITE-ONLY"
: NewDeviceState->DeviceState
== DAC960_V1_Device_Online
? "ONLINE" : "STANDBY"));
if (OldDeviceState->DeviceState == DAC960_V1_Device_Dead &&
NewDeviceState->DeviceState != DAC960_V1_Device_Dead)
{
Controller->V1.NeedDeviceInquiryInformation = true;
Controller->V1.NeedDeviceSerialNumberInformation = true;
Controller->V1.DeviceResetCount
[Controller->V1.DeviceStateChannel]
[Controller->V1.DeviceStateTargetID] = 0;
}
memcpy(OldDeviceState, NewDeviceState,
sizeof(DAC960_V1_DeviceState_T));
}
else if (CommandOpcode == DAC960_V1_GetLogicalDriveInformation)
{
int LogicalDriveNumber;
for (LogicalDriveNumber = 0;
LogicalDriveNumber < Controller->LogicalDriveCount;
LogicalDriveNumber++)
{
DAC960_V1_LogicalDriveInformation_T *OldLogicalDriveInformation =
&Controller->V1.LogicalDriveInformation[LogicalDriveNumber];
DAC960_V1_LogicalDriveInformation_T *NewLogicalDriveInformation =
&(*Controller->V1.NewLogicalDriveInformation)[LogicalDriveNumber];
if (NewLogicalDriveInformation->LogicalDriveState !=
OldLogicalDriveInformation->LogicalDriveState)
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"is now %s\n", Controller,
LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(NewLogicalDriveInformation->LogicalDriveState
== DAC960_V1_LogicalDrive_Online
? "ONLINE"
: NewLogicalDriveInformation->LogicalDriveState
== DAC960_V1_LogicalDrive_Critical
? "CRITICAL" : "OFFLINE"));
if (NewLogicalDriveInformation->WriteBack !=
OldLogicalDriveInformation->WriteBack)
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"is now %s\n", Controller,
LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(NewLogicalDriveInformation->WriteBack
? "WRITE BACK" : "WRITE THRU"));
}
memcpy(&Controller->V1.LogicalDriveInformation,
Controller->V1.NewLogicalDriveInformation,
sizeof(DAC960_V1_LogicalDriveInformationArray_T));
}
else if (CommandOpcode == DAC960_V1_GetRebuildProgress)
{
unsigned int LogicalDriveNumber =
Controller->V1.RebuildProgress->LogicalDriveNumber;
unsigned int LogicalDriveSize =
Controller->V1.RebuildProgress->LogicalDriveSize;
unsigned int BlocksCompleted =
LogicalDriveSize - Controller->V1.RebuildProgress->RemainingBlocks;
if (CommandStatus == DAC960_V1_NoRebuildOrCheckInProgress &&
Controller->V1.LastRebuildStatus == DAC960_V1_NormalCompletion)
CommandStatus = DAC960_V1_RebuildSuccessful;
switch (CommandStatus)
{
case DAC960_V1_NormalCompletion:
Controller->EphemeralProgressMessage = true;
DAC960_Progress("Rebuild in Progress: "
"Logical Drive %d (/dev/rd/c%dd%d) "
"%d%% completed\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(100 * (BlocksCompleted >> 7))
/ (LogicalDriveSize >> 7));
Controller->EphemeralProgressMessage = false;
break;
case DAC960_V1_RebuildFailed_LogicalDriveFailure:
DAC960_Progress("Rebuild Failed due to "
"Logical Drive Failure\n", Controller);
break;
case DAC960_V1_RebuildFailed_BadBlocksOnOther:
DAC960_Progress("Rebuild Failed due to "
"Bad Blocks on Other Drives\n", Controller);
break;
case DAC960_V1_RebuildFailed_NewDriveFailed:
DAC960_Progress("Rebuild Failed due to "
"Failure of Drive Being Rebuilt\n", Controller);
break;
case DAC960_V1_NoRebuildOrCheckInProgress:
break;
case DAC960_V1_RebuildSuccessful:
DAC960_Progress("Rebuild Completed Successfully\n", Controller);
break;
case DAC960_V1_RebuildSuccessfullyTerminated:
DAC960_Progress("Rebuild Successfully Terminated\n", Controller);
break;
}
Controller->V1.LastRebuildStatus = CommandStatus;
if (CommandType != DAC960_MonitoringCommand &&
Controller->V1.RebuildStatusPending)
{
Command->V1.CommandStatus = Controller->V1.PendingRebuildStatus;
Controller->V1.RebuildStatusPending = false;
}
else if (CommandType == DAC960_MonitoringCommand &&
CommandStatus != DAC960_V1_NormalCompletion &&
CommandStatus != DAC960_V1_NoRebuildOrCheckInProgress)
{
Controller->V1.PendingRebuildStatus = CommandStatus;
Controller->V1.RebuildStatusPending = true;
}
}
else if (CommandOpcode == DAC960_V1_RebuildStat)
{
unsigned int LogicalDriveNumber =
Controller->V1.RebuildProgress->LogicalDriveNumber;
unsigned int LogicalDriveSize =
Controller->V1.RebuildProgress->LogicalDriveSize;
unsigned int BlocksCompleted =
LogicalDriveSize - Controller->V1.RebuildProgress->RemainingBlocks;
if (CommandStatus == DAC960_V1_NormalCompletion)
{
Controller->EphemeralProgressMessage = true;
DAC960_Progress("Consistency Check in Progress: "
"Logical Drive %d (/dev/rd/c%dd%d) "
"%d%% completed\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(100 * (BlocksCompleted >> 7))
/ (LogicalDriveSize >> 7));
Controller->EphemeralProgressMessage = false;
}
}
else if (CommandOpcode == DAC960_V1_BackgroundInitializationControl)
{
unsigned int LogicalDriveNumber =
Controller->V1.BackgroundInitializationStatus->LogicalDriveNumber;
unsigned int LogicalDriveSize =
Controller->V1.BackgroundInitializationStatus->LogicalDriveSize;
unsigned int BlocksCompleted =
Controller->V1.BackgroundInitializationStatus->BlocksCompleted;
switch (CommandStatus)
{
case DAC960_V1_NormalCompletion:
switch (Controller->V1.BackgroundInitializationStatus->Status)
{
case DAC960_V1_BackgroundInitializationInvalid:
break;
case DAC960_V1_BackgroundInitializationStarted:
DAC960_Progress("Background Initialization Started\n",
Controller);
break;
case DAC960_V1_BackgroundInitializationInProgress:
if (BlocksCompleted ==
Controller->V1.LastBackgroundInitializationStatus.
BlocksCompleted &&
LogicalDriveNumber ==
Controller->V1.LastBackgroundInitializationStatus.
LogicalDriveNumber)
break;
Controller->EphemeralProgressMessage = true;
DAC960_Progress("Background Initialization in Progress: "
"Logical Drive %d (/dev/rd/c%dd%d) "
"%d%% completed\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(100 * (BlocksCompleted >> 7))
/ (LogicalDriveSize >> 7));
Controller->EphemeralProgressMessage = false;
break;
case DAC960_V1_BackgroundInitializationSuspended:
DAC960_Progress("Background Initialization Suspended\n",
Controller);
break;
case DAC960_V1_BackgroundInitializationCancelled:
DAC960_Progress("Background Initialization Cancelled\n",
Controller);
break;
}
memcpy(&Controller->V1.LastBackgroundInitializationStatus,
Controller->V1.BackgroundInitializationStatus,
sizeof(DAC960_V1_BackgroundInitializationStatus_T));
break;
case DAC960_V1_BackgroundInitSuccessful:
if (Controller->V1.BackgroundInitializationStatus->Status ==
DAC960_V1_BackgroundInitializationInProgress)
DAC960_Progress("Background Initialization "
"Completed Successfully\n", Controller);
Controller->V1.BackgroundInitializationStatus->Status =
DAC960_V1_BackgroundInitializationInvalid;
break;
case DAC960_V1_BackgroundInitAborted:
if (Controller->V1.BackgroundInitializationStatus->Status ==
DAC960_V1_BackgroundInitializationInProgress)
DAC960_Progress("Background Initialization Aborted\n",
Controller);
Controller->V1.BackgroundInitializationStatus->Status =
DAC960_V1_BackgroundInitializationInvalid;
break;
case DAC960_V1_NoBackgroundInitInProgress:
break;
}
}
else if (CommandOpcode == DAC960_V1_DCDB)
{
/*
This is a bit ugly.
The InquiryStandardData and
the InquiryUntitSerialNumber information
retrieval operations BOTH use the DAC960_V1_DCDB
commands. the test above can't distinguish between
these two cases.
Instead, we rely on the order of code later in this
function to ensure that DeviceInquiryInformation commands
are submitted before DeviceSerialNumber commands.
*/
if (Controller->V1.NeedDeviceInquiryInformation)
{
DAC960_SCSI_Inquiry_T *InquiryStandardData =
&Controller->V1.InquiryStandardData
[Controller->V1.DeviceStateChannel]
[Controller->V1.DeviceStateTargetID];
if (CommandStatus != DAC960_V1_NormalCompletion)
{
memset(InquiryStandardData, 0,
sizeof(DAC960_SCSI_Inquiry_T));
InquiryStandardData->PeripheralDeviceType = 0x1F;
}
else
memcpy(InquiryStandardData,
Controller->V1.NewInquiryStandardData,
sizeof(DAC960_SCSI_Inquiry_T));
Controller->V1.NeedDeviceInquiryInformation = false;
}
else if (Controller->V1.NeedDeviceSerialNumberInformation)
{
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
&Controller->V1.InquiryUnitSerialNumber
[Controller->V1.DeviceStateChannel]
[Controller->V1.DeviceStateTargetID];
if (CommandStatus != DAC960_V1_NormalCompletion)
{
memset(InquiryUnitSerialNumber, 0,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
}
else
memcpy(InquiryUnitSerialNumber,
Controller->V1.NewInquiryUnitSerialNumber,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
Controller->V1.NeedDeviceSerialNumberInformation = false;
}
}
/*
Begin submitting new monitoring commands.
*/
if (Controller->V1.NewEventLogSequenceNumber
- Controller->V1.OldEventLogSequenceNumber > 0)
{
Command->V1.CommandMailbox.Type3E.CommandOpcode =
DAC960_V1_PerformEventLogOperation;
Command->V1.CommandMailbox.Type3E.OperationType =
DAC960_V1_GetEventLogEntry;
Command->V1.CommandMailbox.Type3E.OperationQualifier = 1;
Command->V1.CommandMailbox.Type3E.SequenceNumber =
Controller->V1.OldEventLogSequenceNumber;
Command->V1.CommandMailbox.Type3E.BusAddress =
Controller->V1.EventLogEntryDMA;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedErrorTableInformation)
{
Controller->V1.NeedErrorTableInformation = false;
Command->V1.CommandMailbox.Type3.CommandOpcode =
DAC960_V1_GetErrorTable;
Command->V1.CommandMailbox.Type3.BusAddress =
Controller->V1.NewErrorTableDMA;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedRebuildProgress &&
Controller->V1.RebuildProgressFirst)
{
Controller->V1.NeedRebuildProgress = false;
Command->V1.CommandMailbox.Type3.CommandOpcode =
DAC960_V1_GetRebuildProgress;
Command->V1.CommandMailbox.Type3.BusAddress =
Controller->V1.RebuildProgressDMA;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedDeviceStateInformation)
{
if (Controller->V1.NeedDeviceInquiryInformation)
{
DAC960_V1_DCDB_T *DCDB = Controller->V1.MonitoringDCDB;
dma_addr_t DCDB_DMA = Controller->V1.MonitoringDCDB_DMA;
dma_addr_t NewInquiryStandardDataDMA =
Controller->V1.NewInquiryStandardDataDMA;
Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
Command->V1.CommandMailbox.Type3.BusAddress = DCDB_DMA;
DCDB->Channel = Controller->V1.DeviceStateChannel;
DCDB->TargetID = Controller->V1.DeviceStateTargetID;
DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
DCDB->EarlyStatus = false;
DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
DCDB->NoAutomaticRequestSense = false;
DCDB->DisconnectPermitted = true;
DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_T);
DCDB->BusAddress = NewInquiryStandardDataDMA;
DCDB->CDBLength = 6;
DCDB->TransferLengthHigh4 = 0;
DCDB->SenseLength = sizeof(DCDB->SenseData);
DCDB->CDB[0] = 0x12; /* INQUIRY */
DCDB->CDB[1] = 0; /* EVPD = 0 */
DCDB->CDB[2] = 0; /* Page Code */
DCDB->CDB[3] = 0; /* Reserved */
DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_T);
DCDB->CDB[5] = 0; /* Control */
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedDeviceSerialNumberInformation)
{
DAC960_V1_DCDB_T *DCDB = Controller->V1.MonitoringDCDB;
dma_addr_t DCDB_DMA = Controller->V1.MonitoringDCDB_DMA;
dma_addr_t NewInquiryUnitSerialNumberDMA =
Controller->V1.NewInquiryUnitSerialNumberDMA;
Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
Command->V1.CommandMailbox.Type3.BusAddress = DCDB_DMA;
DCDB->Channel = Controller->V1.DeviceStateChannel;
DCDB->TargetID = Controller->V1.DeviceStateTargetID;
DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
DCDB->EarlyStatus = false;
DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
DCDB->NoAutomaticRequestSense = false;
DCDB->DisconnectPermitted = true;
DCDB->TransferLength =
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
DCDB->BusAddress = NewInquiryUnitSerialNumberDMA;
DCDB->CDBLength = 6;
DCDB->TransferLengthHigh4 = 0;
DCDB->SenseLength = sizeof(DCDB->SenseData);
DCDB->CDB[0] = 0x12; /* INQUIRY */
DCDB->CDB[1] = 1; /* EVPD = 1 */
DCDB->CDB[2] = 0x80; /* Page Code */
DCDB->CDB[3] = 0; /* Reserved */
DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
DCDB->CDB[5] = 0; /* Control */
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.StartDeviceStateScan)
{
Controller->V1.DeviceStateChannel = 0;
Controller->V1.DeviceStateTargetID = 0;
Controller->V1.StartDeviceStateScan = false;
}
else if (++Controller->V1.DeviceStateTargetID == Controller->Targets)
{
Controller->V1.DeviceStateChannel++;
Controller->V1.DeviceStateTargetID = 0;
}
if (Controller->V1.DeviceStateChannel < Controller->Channels)
{
Controller->V1.NewDeviceState->DeviceState =
DAC960_V1_Device_Dead;
Command->V1.CommandMailbox.Type3D.CommandOpcode =
DAC960_V1_GetDeviceState;
Command->V1.CommandMailbox.Type3D.Channel =
Controller->V1.DeviceStateChannel;
Command->V1.CommandMailbox.Type3D.TargetID =
Controller->V1.DeviceStateTargetID;
Command->V1.CommandMailbox.Type3D.BusAddress =
Controller->V1.NewDeviceStateDMA;
DAC960_QueueCommand(Command);
return;
}
Controller->V1.NeedDeviceStateInformation = false;
}
if (Controller->V1.NeedLogicalDriveInformation)
{
Controller->V1.NeedLogicalDriveInformation = false;
Command->V1.CommandMailbox.Type3.CommandOpcode =
DAC960_V1_GetLogicalDriveInformation;
Command->V1.CommandMailbox.Type3.BusAddress =
Controller->V1.NewLogicalDriveInformationDMA;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedRebuildProgress)
{
Controller->V1.NeedRebuildProgress = false;
Command->V1.CommandMailbox.Type3.CommandOpcode =
DAC960_V1_GetRebuildProgress;
Command->V1.CommandMailbox.Type3.BusAddress =
Controller->V1.RebuildProgressDMA;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedConsistencyCheckProgress)
{
Controller->V1.NeedConsistencyCheckProgress = false;
Command->V1.CommandMailbox.Type3.CommandOpcode =
DAC960_V1_RebuildStat;
Command->V1.CommandMailbox.Type3.BusAddress =
Controller->V1.RebuildProgressDMA;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V1.NeedBackgroundInitializationStatus)
{
Controller->V1.NeedBackgroundInitializationStatus = false;
Command->V1.CommandMailbox.Type3B.CommandOpcode =
DAC960_V1_BackgroundInitializationControl;
Command->V1.CommandMailbox.Type3B.CommandOpcode2 = 0x20;
Command->V1.CommandMailbox.Type3B.BusAddress =
Controller->V1.BackgroundInitializationStatusDMA;
DAC960_QueueCommand(Command);
return;
}
Controller->MonitoringTimerCount++;
Controller->MonitoringTimer.expires =
jiffies + DAC960_MonitoringTimerInterval;
add_timer(&Controller->MonitoringTimer);
}
if (CommandType == DAC960_ImmediateCommand)
{
complete(Command->Completion);
Command->Completion = NULL;
return;
}
if (CommandType == DAC960_QueuedCommand)
{
DAC960_V1_KernelCommand_T *KernelCommand = Command->V1.KernelCommand;
KernelCommand->CommandStatus = Command->V1.CommandStatus;
Command->V1.KernelCommand = NULL;
if (CommandOpcode == DAC960_V1_DCDB)
Controller->V1.DirectCommandActive[KernelCommand->DCDB->Channel]
[KernelCommand->DCDB->TargetID] =
false;
DAC960_DeallocateCommand(Command);
KernelCommand->CompletionFunction(KernelCommand);
return;
}
/*
Queue a Status Monitoring Command to the Controller using the just
completed Command if one was deferred previously due to lack of a
free Command when the Monitoring Timer Function was called.
*/
if (Controller->MonitoringCommandDeferred)
{
Controller->MonitoringCommandDeferred = false;
DAC960_V1_QueueMonitoringCommand(Command);
return;
}
/*
Deallocate the Command.
*/
DAC960_DeallocateCommand(Command);
/*
Wake up any processes waiting on a free Command.
*/
wake_up(&Controller->CommandWaitQueue);
}
/*
DAC960_V2_ReadWriteError prints an appropriate error message for Command
when an error occurs on a Read or Write operation.
*/
static void DAC960_V2_ReadWriteError(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
unsigned char *SenseErrors[] = { "NO SENSE", "RECOVERED ERROR",
"NOT READY", "MEDIUM ERROR",
"HARDWARE ERROR", "ILLEGAL REQUEST",
"UNIT ATTENTION", "DATA PROTECT",
"BLANK CHECK", "VENDOR-SPECIFIC",
"COPY ABORTED", "ABORTED COMMAND",
"EQUAL", "VOLUME OVERFLOW",
"MISCOMPARE", "RESERVED" };
unsigned char *CommandName = "UNKNOWN";
switch (Command->CommandType)
{
case DAC960_ReadCommand:
case DAC960_ReadRetryCommand:
CommandName = "READ";
break;
case DAC960_WriteCommand:
case DAC960_WriteRetryCommand:
CommandName = "WRITE";
break;
case DAC960_MonitoringCommand:
case DAC960_ImmediateCommand:
case DAC960_QueuedCommand:
break;
}
DAC960_Error("Error Condition %s on %s:\n", Controller,
SenseErrors[Command->V2.RequestSense->SenseKey], CommandName);
DAC960_Error(" /dev/rd/c%dd%d: absolute blocks %u..%u\n",
Controller, Controller->ControllerNumber,
Command->LogicalDriveNumber, Command->BlockNumber,
Command->BlockNumber + Command->BlockCount - 1);
}
/*
DAC960_V2_ReportEvent prints an appropriate message when a Controller Event
occurs.
*/
static void DAC960_V2_ReportEvent(DAC960_Controller_T *Controller,
DAC960_V2_Event_T *Event)
{
DAC960_SCSI_RequestSense_T *RequestSense =
(DAC960_SCSI_RequestSense_T *) &Event->RequestSenseData;
unsigned char MessageBuffer[DAC960_LineBufferSize];
static struct { int EventCode; unsigned char *EventMessage; } EventList[] =
{ /* Physical Device Events (0x0000 - 0x007F) */
{ 0x0001, "P Online" },
{ 0x0002, "P Standby" },
{ 0x0005, "P Automatic Rebuild Started" },
{ 0x0006, "P Manual Rebuild Started" },
{ 0x0007, "P Rebuild Completed" },
{ 0x0008, "P Rebuild Cancelled" },
{ 0x0009, "P Rebuild Failed for Unknown Reasons" },
{ 0x000A, "P Rebuild Failed due to New Physical Device" },
{ 0x000B, "P Rebuild Failed due to Logical Drive Failure" },
{ 0x000C, "S Offline" },
{ 0x000D, "P Found" },
{ 0x000E, "P Removed" },
{ 0x000F, "P Unconfigured" },
{ 0x0010, "P Expand Capacity Started" },
{ 0x0011, "P Expand Capacity Completed" },
{ 0x0012, "P Expand Capacity Failed" },
{ 0x0013, "P Command Timed Out" },
{ 0x0014, "P Command Aborted" },
{ 0x0015, "P Command Retried" },
{ 0x0016, "P Parity Error" },
{ 0x0017, "P Soft Error" },
{ 0x0018, "P Miscellaneous Error" },
{ 0x0019, "P Reset" },
{ 0x001A, "P Active Spare Found" },
{ 0x001B, "P Warm Spare Found" },
{ 0x001C, "S Sense Data Received" },
{ 0x001D, "P Initialization Started" },
{ 0x001E, "P Initialization Completed" },
{ 0x001F, "P Initialization Failed" },
{ 0x0020, "P Initialization Cancelled" },
{ 0x0021, "P Failed because Write Recovery Failed" },
{ 0x0022, "P Failed because SCSI Bus Reset Failed" },
{ 0x0023, "P Failed because of Double Check Condition" },
{ 0x0024, "P Failed because Device Cannot Be Accessed" },
{ 0x0025, "P Failed because of Gross Error on SCSI Processor" },
{ 0x0026, "P Failed because of Bad Tag from Device" },
{ 0x0027, "P Failed because of Command Timeout" },
{ 0x0028, "P Failed because of System Reset" },
{ 0x0029, "P Failed because of Busy Status or Parity Error" },
{ 0x002A, "P Failed because Host Set Device to Failed State" },
{ 0x002B, "P Failed because of Selection Timeout" },
{ 0x002C, "P Failed because of SCSI Bus Phase Error" },
{ 0x002D, "P Failed because Device Returned Unknown Status" },
{ 0x002E, "P Failed because Device Not Ready" },
{ 0x002F, "P Failed because Device Not Found at Startup" },
{ 0x0030, "P Failed because COD Write Operation Failed" },
{ 0x0031, "P Failed because BDT Write Operation Failed" },
{ 0x0039, "P Missing at Startup" },
{ 0x003A, "P Start Rebuild Failed due to Physical Drive Too Small" },
{ 0x003C, "P Temporarily Offline Device Automatically Made Online" },
{ 0x003D, "P Standby Rebuild Started" },
/* Logical Device Events (0x0080 - 0x00FF) */
{ 0x0080, "M Consistency Check Started" },
{ 0x0081, "M Consistency Check Completed" },
{ 0x0082, "M Consistency Check Cancelled" },
{ 0x0083, "M Consistency Check Completed With Errors" },
{ 0x0084, "M Consistency Check Failed due to Logical Drive Failure" },
{ 0x0085, "M Consistency Check Failed due to Physical Device Failure" },
{ 0x0086, "L Offline" },
{ 0x0087, "L Critical" },
{ 0x0088, "L Online" },
{ 0x0089, "M Automatic Rebuild Started" },
{ 0x008A, "M Manual Rebuild Started" },
{ 0x008B, "M Rebuild Completed" },
{ 0x008C, "M Rebuild Cancelled" },
{ 0x008D, "M Rebuild Failed for Unknown Reasons" },
{ 0x008E, "M Rebuild Failed due to New Physical Device" },
{ 0x008F, "M Rebuild Failed due to Logical Drive Failure" },
{ 0x0090, "M Initialization Started" },
{ 0x0091, "M Initialization Completed" },
{ 0x0092, "M Initialization Cancelled" },
{ 0x0093, "M Initialization Failed" },
{ 0x0094, "L Found" },
{ 0x0095, "L Deleted" },
{ 0x0096, "M Expand Capacity Started" },
{ 0x0097, "M Expand Capacity Completed" },
{ 0x0098, "M Expand Capacity Failed" },
{ 0x0099, "L Bad Block Found" },
{ 0x009A, "L Size Changed" },
{ 0x009B, "L Type Changed" },
{ 0x009C, "L Bad Data Block Found" },
{ 0x009E, "L Read of Data Block in BDT" },
{ 0x009F, "L Write Back Data for Disk Block Lost" },
{ 0x00A0, "L Temporarily Offline RAID-5/3 Drive Made Online" },
{ 0x00A1, "L Temporarily Offline RAID-6/1/0/7 Drive Made Online" },
{ 0x00A2, "L Standby Rebuild Started" },
/* Fault Management Events (0x0100 - 0x017F) */
{ 0x0140, "E Fan %d Failed" },
{ 0x0141, "E Fan %d OK" },
{ 0x0142, "E Fan %d Not Present" },
{ 0x0143, "E Power Supply %d Failed" },
{ 0x0144, "E Power Supply %d OK" },
{ 0x0145, "E Power Supply %d Not Present" },
{ 0x0146, "E Temperature Sensor %d Temperature Exceeds Safe Limit" },
{ 0x0147, "E Temperature Sensor %d Temperature Exceeds Working Limit" },
{ 0x0148, "E Temperature Sensor %d Temperature Normal" },
{ 0x0149, "E Temperature Sensor %d Not Present" },
{ 0x014A, "E Enclosure Management Unit %d Access Critical" },
{ 0x014B, "E Enclosure Management Unit %d Access OK" },
{ 0x014C, "E Enclosure Management Unit %d Access Offline" },
/* Controller Events (0x0180 - 0x01FF) */
{ 0x0181, "C Cache Write Back Error" },
{ 0x0188, "C Battery Backup Unit Found" },
{ 0x0189, "C Battery Backup Unit Charge Level Low" },
{ 0x018A, "C Battery Backup Unit Charge Level OK" },
{ 0x0193, "C Installation Aborted" },
{ 0x0195, "C Battery Backup Unit Physically Removed" },
{ 0x0196, "C Memory Error During Warm Boot" },
{ 0x019E, "C Memory Soft ECC Error Corrected" },
{ 0x019F, "C Memory Hard ECC Error Corrected" },
{ 0x01A2, "C Battery Backup Unit Failed" },
{ 0x01AB, "C Mirror Race Recovery Failed" },
{ 0x01AC, "C Mirror Race on Critical Drive" },
/* Controller Internal Processor Events */
{ 0x0380, "C Internal Controller Hung" },
{ 0x0381, "C Internal Controller Firmware Breakpoint" },
{ 0x0390, "C Internal Controller i960 Processor Specific Error" },
{ 0x03A0, "C Internal Controller StrongARM Processor Specific Error" },
{ 0, "" } };
int EventListIndex = 0, EventCode;
unsigned char EventType, *EventMessage;
if (Event->EventCode == 0x1C &&
RequestSense->SenseKey == DAC960_SenseKey_VendorSpecific &&
(RequestSense->AdditionalSenseCode == 0x80 ||
RequestSense->AdditionalSenseCode == 0x81))
Event->EventCode = ((RequestSense->AdditionalSenseCode - 0x80) << 8) |
RequestSense->AdditionalSenseCodeQualifier;
while (true)
{
EventCode = EventList[EventListIndex].EventCode;
if (EventCode == Event->EventCode || EventCode == 0) break;
EventListIndex++;
}
EventType = EventList[EventListIndex].EventMessage[0];
EventMessage = &EventList[EventListIndex].EventMessage[2];
if (EventCode == 0)
{
DAC960_Critical("Unknown Controller Event Code %04X\n",
Controller, Event->EventCode);
return;
}
switch (EventType)
{
case 'P':
DAC960_Critical("Physical Device %d:%d %s\n", Controller,
Event->Channel, Event->TargetID, EventMessage);
break;
case 'L':
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) %s\n", Controller,
Event->LogicalUnit, Controller->ControllerNumber,
Event->LogicalUnit, EventMessage);
break;
case 'M':
DAC960_Progress("Logical Drive %d (/dev/rd/c%dd%d) %s\n", Controller,
Event->LogicalUnit, Controller->ControllerNumber,
Event->LogicalUnit, EventMessage);
break;
case 'S':
if (RequestSense->SenseKey == DAC960_SenseKey_NoSense ||
(RequestSense->SenseKey == DAC960_SenseKey_NotReady &&
RequestSense->AdditionalSenseCode == 0x04 &&
(RequestSense->AdditionalSenseCodeQualifier == 0x01 ||
RequestSense->AdditionalSenseCodeQualifier == 0x02)))
break;
DAC960_Critical("Physical Device %d:%d %s\n", Controller,
Event->Channel, Event->TargetID, EventMessage);
DAC960_Critical("Physical Device %d:%d Request Sense: "
"Sense Key = %X, ASC = %02X, ASCQ = %02X\n",
Controller,
Event->Channel,
Event->TargetID,
RequestSense->SenseKey,
RequestSense->AdditionalSenseCode,
RequestSense->AdditionalSenseCodeQualifier);
DAC960_Critical("Physical Device %d:%d Request Sense: "
"Information = %02X%02X%02X%02X "
"%02X%02X%02X%02X\n",
Controller,
Event->Channel,
Event->TargetID,
RequestSense->Information[0],
RequestSense->Information[1],
RequestSense->Information[2],
RequestSense->Information[3],
RequestSense->CommandSpecificInformation[0],
RequestSense->CommandSpecificInformation[1],
RequestSense->CommandSpecificInformation[2],
RequestSense->CommandSpecificInformation[3]);
break;
case 'E':
if (Controller->SuppressEnclosureMessages) break;
sprintf(MessageBuffer, EventMessage, Event->LogicalUnit);
DAC960_Critical("Enclosure %d %s\n", Controller,
Event->TargetID, MessageBuffer);
break;
case 'C':
DAC960_Critical("Controller %s\n", Controller, EventMessage);
break;
default:
DAC960_Critical("Unknown Controller Event Code %04X\n",
Controller, Event->EventCode);
break;
}
}
/*
DAC960_V2_ReportProgress prints an appropriate progress message for
Logical Device Long Operations.
*/
static void DAC960_V2_ReportProgress(DAC960_Controller_T *Controller,
unsigned char *MessageString,
unsigned int LogicalDeviceNumber,
unsigned long BlocksCompleted,
unsigned long LogicalDeviceSize)
{
Controller->EphemeralProgressMessage = true;
DAC960_Progress("%s in Progress: Logical Drive %d (/dev/rd/c%dd%d) "
"%d%% completed\n", Controller,
MessageString,
LogicalDeviceNumber,
Controller->ControllerNumber,
LogicalDeviceNumber,
(100 * (BlocksCompleted >> 7)) / (LogicalDeviceSize >> 7));
Controller->EphemeralProgressMessage = false;
}
/*
DAC960_V2_ProcessCompletedCommand performs completion processing for Command
for DAC960 V2 Firmware Controllers.
*/
static void DAC960_V2_ProcessCompletedCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DAC960_CommandType_T CommandType = Command->CommandType;
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_IOCTL_Opcode_T CommandOpcode = CommandMailbox->Common.IOCTL_Opcode;
DAC960_V2_CommandStatus_T CommandStatus = Command->V2.CommandStatus;
if (CommandType == DAC960_ReadCommand ||
CommandType == DAC960_WriteCommand)
{
#ifdef FORCE_RETRY_DEBUG
CommandStatus = DAC960_V2_AbormalCompletion;
#endif
Command->V2.RequestSense->SenseKey = DAC960_SenseKey_MediumError;
if (CommandStatus == DAC960_V2_NormalCompletion) {
if (!DAC960_ProcessCompletedRequest(Command, true))
BUG();
} else if (Command->V2.RequestSense->SenseKey == DAC960_SenseKey_MediumError)
{
/*
* break the command down into pieces and resubmit each
* piece, hoping that some of them will succeed.
*/
DAC960_queue_partial_rw(Command);
return;
}
else
{
if (Command->V2.RequestSense->SenseKey != DAC960_SenseKey_NotReady)
DAC960_V2_ReadWriteError(Command);
/*
Perform completion processing for all buffers in this I/O Request.
*/
(void)DAC960_ProcessCompletedRequest(Command, false);
}
}
else if (CommandType == DAC960_ReadRetryCommand ||
CommandType == DAC960_WriteRetryCommand)
{
bool normal_completion;
#ifdef FORCE_RETRY_FAILURE_DEBUG
static int retry_count = 1;
#endif
/*
Perform completion processing for the portion that was
retried, and submit the next portion, if any.
*/
normal_completion = true;
if (CommandStatus != DAC960_V2_NormalCompletion) {
normal_completion = false;
if (Command->V2.RequestSense->SenseKey != DAC960_SenseKey_NotReady)
DAC960_V2_ReadWriteError(Command);
}
#ifdef FORCE_RETRY_FAILURE_DEBUG
if (!(++retry_count % 10000)) {
printk("V2 error retry failure test\n");
normal_completion = false;
DAC960_V2_ReadWriteError(Command);
}
#endif
if (!DAC960_ProcessCompletedRequest(Command, normal_completion)) {
DAC960_queue_partial_rw(Command);
return;
}
}
else if (CommandType == DAC960_MonitoringCommand)
{
if (Controller->ShutdownMonitoringTimer)
return;
if (CommandOpcode == DAC960_V2_GetControllerInfo)
{
DAC960_V2_ControllerInfo_T *NewControllerInfo =
Controller->V2.NewControllerInformation;
DAC960_V2_ControllerInfo_T *ControllerInfo =
&Controller->V2.ControllerInformation;
Controller->LogicalDriveCount =
NewControllerInfo->LogicalDevicesPresent;
Controller->V2.NeedLogicalDeviceInformation = true;
Controller->V2.NeedPhysicalDeviceInformation = true;
Controller->V2.StartLogicalDeviceInformationScan = true;
Controller->V2.StartPhysicalDeviceInformationScan = true;
Controller->MonitoringAlertMode =
(NewControllerInfo->LogicalDevicesCritical > 0 ||
NewControllerInfo->LogicalDevicesOffline > 0 ||
NewControllerInfo->PhysicalDisksCritical > 0 ||
NewControllerInfo->PhysicalDisksOffline > 0);
memcpy(ControllerInfo, NewControllerInfo,
sizeof(DAC960_V2_ControllerInfo_T));
}
else if (CommandOpcode == DAC960_V2_GetEvent)
{
if (CommandStatus == DAC960_V2_NormalCompletion) {
DAC960_V2_ReportEvent(Controller, Controller->V2.Event);
}
Controller->V2.NextEventSequenceNumber++;
}
else if (CommandOpcode == DAC960_V2_GetPhysicalDeviceInfoValid &&
CommandStatus == DAC960_V2_NormalCompletion)
{
DAC960_V2_PhysicalDeviceInfo_T *NewPhysicalDeviceInfo =
Controller->V2.NewPhysicalDeviceInformation;
unsigned int PhysicalDeviceIndex = Controller->V2.PhysicalDeviceIndex;
DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
unsigned int DeviceIndex;
while (PhysicalDeviceInfo != NULL &&
(NewPhysicalDeviceInfo->Channel >
PhysicalDeviceInfo->Channel ||
(NewPhysicalDeviceInfo->Channel ==
PhysicalDeviceInfo->Channel &&
(NewPhysicalDeviceInfo->TargetID >
PhysicalDeviceInfo->TargetID ||
(NewPhysicalDeviceInfo->TargetID ==
PhysicalDeviceInfo->TargetID &&
NewPhysicalDeviceInfo->LogicalUnit >
PhysicalDeviceInfo->LogicalUnit)))))
{
DAC960_Critical("Physical Device %d:%d No Longer Exists\n",
Controller,
PhysicalDeviceInfo->Channel,
PhysicalDeviceInfo->TargetID);
Controller->V2.PhysicalDeviceInformation
[PhysicalDeviceIndex] = NULL;
Controller->V2.InquiryUnitSerialNumber
[PhysicalDeviceIndex] = NULL;
kfree(PhysicalDeviceInfo);
kfree(InquiryUnitSerialNumber);
for (DeviceIndex = PhysicalDeviceIndex;
DeviceIndex < DAC960_V2_MaxPhysicalDevices - 1;
DeviceIndex++)
{
Controller->V2.PhysicalDeviceInformation[DeviceIndex] =
Controller->V2.PhysicalDeviceInformation[DeviceIndex+1];
Controller->V2.InquiryUnitSerialNumber[DeviceIndex] =
Controller->V2.InquiryUnitSerialNumber[DeviceIndex+1];
}
Controller->V2.PhysicalDeviceInformation
[DAC960_V2_MaxPhysicalDevices-1] = NULL;
Controller->V2.InquiryUnitSerialNumber
[DAC960_V2_MaxPhysicalDevices-1] = NULL;
PhysicalDeviceInfo =
Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
InquiryUnitSerialNumber =
Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
}
if (PhysicalDeviceInfo == NULL ||
(NewPhysicalDeviceInfo->Channel !=
PhysicalDeviceInfo->Channel) ||
(NewPhysicalDeviceInfo->TargetID !=
PhysicalDeviceInfo->TargetID) ||
(NewPhysicalDeviceInfo->LogicalUnit !=
PhysicalDeviceInfo->LogicalUnit))
{
PhysicalDeviceInfo =
kmalloc(sizeof(DAC960_V2_PhysicalDeviceInfo_T), GFP_ATOMIC);
InquiryUnitSerialNumber =
kmalloc(sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
GFP_ATOMIC);
if (InquiryUnitSerialNumber == NULL ||
PhysicalDeviceInfo == NULL)
{
kfree(InquiryUnitSerialNumber);
InquiryUnitSerialNumber = NULL;
kfree(PhysicalDeviceInfo);
PhysicalDeviceInfo = NULL;
}
DAC960_Critical("Physical Device %d:%d Now Exists%s\n",
Controller,
NewPhysicalDeviceInfo->Channel,
NewPhysicalDeviceInfo->TargetID,
(PhysicalDeviceInfo != NULL
? "" : " - Allocation Failed"));
if (PhysicalDeviceInfo != NULL)
{
memset(PhysicalDeviceInfo, 0,
sizeof(DAC960_V2_PhysicalDeviceInfo_T));
PhysicalDeviceInfo->PhysicalDeviceState =
DAC960_V2_Device_InvalidState;
memset(InquiryUnitSerialNumber, 0,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
for (DeviceIndex = DAC960_V2_MaxPhysicalDevices - 1;
DeviceIndex > PhysicalDeviceIndex;
DeviceIndex--)
{
Controller->V2.PhysicalDeviceInformation[DeviceIndex] =
Controller->V2.PhysicalDeviceInformation[DeviceIndex-1];
Controller->V2.InquiryUnitSerialNumber[DeviceIndex] =
Controller->V2.InquiryUnitSerialNumber[DeviceIndex-1];
}
Controller->V2.PhysicalDeviceInformation
[PhysicalDeviceIndex] =
PhysicalDeviceInfo;
Controller->V2.InquiryUnitSerialNumber
[PhysicalDeviceIndex] =
InquiryUnitSerialNumber;
Controller->V2.NeedDeviceSerialNumberInformation = true;
}
}
if (PhysicalDeviceInfo != NULL)
{
if (NewPhysicalDeviceInfo->PhysicalDeviceState !=
PhysicalDeviceInfo->PhysicalDeviceState)
DAC960_Critical(
"Physical Device %d:%d is now %s\n", Controller,
NewPhysicalDeviceInfo->Channel,
NewPhysicalDeviceInfo->TargetID,
(NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Online
? "ONLINE"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Rebuild
? "REBUILD"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Missing
? "MISSING"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Critical
? "CRITICAL"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Dead
? "DEAD"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_SuspectedDead
? "SUSPECTED-DEAD"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_CommandedOffline
? "COMMANDED-OFFLINE"
: NewPhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Standby
? "STANDBY" : "UNKNOWN"));
if ((NewPhysicalDeviceInfo->ParityErrors !=
PhysicalDeviceInfo->ParityErrors) ||
(NewPhysicalDeviceInfo->SoftErrors !=
PhysicalDeviceInfo->SoftErrors) ||
(NewPhysicalDeviceInfo->HardErrors !=
PhysicalDeviceInfo->HardErrors) ||
(NewPhysicalDeviceInfo->MiscellaneousErrors !=
PhysicalDeviceInfo->MiscellaneousErrors) ||
(NewPhysicalDeviceInfo->CommandTimeouts !=
PhysicalDeviceInfo->CommandTimeouts) ||
(NewPhysicalDeviceInfo->Retries !=
PhysicalDeviceInfo->Retries) ||
(NewPhysicalDeviceInfo->Aborts !=
PhysicalDeviceInfo->Aborts) ||
(NewPhysicalDeviceInfo->PredictedFailuresDetected !=
PhysicalDeviceInfo->PredictedFailuresDetected))
{
DAC960_Critical("Physical Device %d:%d Errors: "
"Parity = %d, Soft = %d, "
"Hard = %d, Misc = %d\n",
Controller,
NewPhysicalDeviceInfo->Channel,
NewPhysicalDeviceInfo->TargetID,
NewPhysicalDeviceInfo->ParityErrors,
NewPhysicalDeviceInfo->SoftErrors,
NewPhysicalDeviceInfo->HardErrors,
NewPhysicalDeviceInfo->MiscellaneousErrors);
DAC960_Critical("Physical Device %d:%d Errors: "
"Timeouts = %d, Retries = %d, "
"Aborts = %d, Predicted = %d\n",
Controller,
NewPhysicalDeviceInfo->Channel,
NewPhysicalDeviceInfo->TargetID,
NewPhysicalDeviceInfo->CommandTimeouts,
NewPhysicalDeviceInfo->Retries,
NewPhysicalDeviceInfo->Aborts,
NewPhysicalDeviceInfo
->PredictedFailuresDetected);
}
if ((PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_Dead ||
PhysicalDeviceInfo->PhysicalDeviceState
== DAC960_V2_Device_InvalidState) &&
NewPhysicalDeviceInfo->PhysicalDeviceState
!= DAC960_V2_Device_Dead)
Controller->V2.NeedDeviceSerialNumberInformation = true;
memcpy(PhysicalDeviceInfo, NewPhysicalDeviceInfo,
sizeof(DAC960_V2_PhysicalDeviceInfo_T));
}
NewPhysicalDeviceInfo->LogicalUnit++;
Controller->V2.PhysicalDeviceIndex++;
}
else if (CommandOpcode == DAC960_V2_GetPhysicalDeviceInfoValid)
{
unsigned int DeviceIndex;
for (DeviceIndex = Controller->V2.PhysicalDeviceIndex;
DeviceIndex < DAC960_V2_MaxPhysicalDevices;
DeviceIndex++)
{
DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
Controller->V2.PhysicalDeviceInformation[DeviceIndex];
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
Controller->V2.InquiryUnitSerialNumber[DeviceIndex];
if (PhysicalDeviceInfo == NULL) break;
DAC960_Critical("Physical Device %d:%d No Longer Exists\n",
Controller,
PhysicalDeviceInfo->Channel,
PhysicalDeviceInfo->TargetID);
Controller->V2.PhysicalDeviceInformation[DeviceIndex] = NULL;
Controller->V2.InquiryUnitSerialNumber[DeviceIndex] = NULL;
kfree(PhysicalDeviceInfo);
kfree(InquiryUnitSerialNumber);
}
Controller->V2.NeedPhysicalDeviceInformation = false;
}
else if (CommandOpcode == DAC960_V2_GetLogicalDeviceInfoValid &&
CommandStatus == DAC960_V2_NormalCompletion)
{
DAC960_V2_LogicalDeviceInfo_T *NewLogicalDeviceInfo =
Controller->V2.NewLogicalDeviceInformation;
unsigned short LogicalDeviceNumber =
NewLogicalDeviceInfo->LogicalDeviceNumber;
DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber];
if (LogicalDeviceInfo == NULL)
{
DAC960_V2_PhysicalDevice_T PhysicalDevice;
PhysicalDevice.Controller = 0;
PhysicalDevice.Channel = NewLogicalDeviceInfo->Channel;
PhysicalDevice.TargetID = NewLogicalDeviceInfo->TargetID;
PhysicalDevice.LogicalUnit = NewLogicalDeviceInfo->LogicalUnit;
Controller->V2.LogicalDriveToVirtualDevice[LogicalDeviceNumber] =
PhysicalDevice;
LogicalDeviceInfo = kmalloc(sizeof(DAC960_V2_LogicalDeviceInfo_T),
GFP_ATOMIC);
Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber] =
LogicalDeviceInfo;
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"Now Exists%s\n", Controller,
LogicalDeviceNumber,
Controller->ControllerNumber,
LogicalDeviceNumber,
(LogicalDeviceInfo != NULL
? "" : " - Allocation Failed"));
if (LogicalDeviceInfo != NULL)
{
memset(LogicalDeviceInfo, 0,
sizeof(DAC960_V2_LogicalDeviceInfo_T));
DAC960_ComputeGenericDiskInfo(Controller);
}
}
if (LogicalDeviceInfo != NULL)
{
unsigned long LogicalDeviceSize =
NewLogicalDeviceInfo->ConfigurableDeviceSize;
if (NewLogicalDeviceInfo->LogicalDeviceState !=
LogicalDeviceInfo->LogicalDeviceState)
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"is now %s\n", Controller,
LogicalDeviceNumber,
Controller->ControllerNumber,
LogicalDeviceNumber,
(NewLogicalDeviceInfo->LogicalDeviceState
== DAC960_V2_LogicalDevice_Online
? "ONLINE"
: NewLogicalDeviceInfo->LogicalDeviceState
== DAC960_V2_LogicalDevice_Critical
? "CRITICAL" : "OFFLINE"));
if ((NewLogicalDeviceInfo->SoftErrors !=
LogicalDeviceInfo->SoftErrors) ||
(NewLogicalDeviceInfo->CommandsFailed !=
LogicalDeviceInfo->CommandsFailed) ||
(NewLogicalDeviceInfo->DeferredWriteErrors !=
LogicalDeviceInfo->DeferredWriteErrors))
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) Errors: "
"Soft = %d, Failed = %d, Deferred Write = %d\n",
Controller, LogicalDeviceNumber,
Controller->ControllerNumber,
LogicalDeviceNumber,
NewLogicalDeviceInfo->SoftErrors,
NewLogicalDeviceInfo->CommandsFailed,
NewLogicalDeviceInfo->DeferredWriteErrors);
if (NewLogicalDeviceInfo->ConsistencyCheckInProgress)
DAC960_V2_ReportProgress(Controller,
"Consistency Check",
LogicalDeviceNumber,
NewLogicalDeviceInfo
->ConsistencyCheckBlockNumber,
LogicalDeviceSize);
else if (NewLogicalDeviceInfo->RebuildInProgress)
DAC960_V2_ReportProgress(Controller,
"Rebuild",
LogicalDeviceNumber,
NewLogicalDeviceInfo
->RebuildBlockNumber,
LogicalDeviceSize);
else if (NewLogicalDeviceInfo->BackgroundInitializationInProgress)
DAC960_V2_ReportProgress(Controller,
"Background Initialization",
LogicalDeviceNumber,
NewLogicalDeviceInfo
->BackgroundInitializationBlockNumber,
LogicalDeviceSize);
else if (NewLogicalDeviceInfo->ForegroundInitializationInProgress)
DAC960_V2_ReportProgress(Controller,
"Foreground Initialization",
LogicalDeviceNumber,
NewLogicalDeviceInfo
->ForegroundInitializationBlockNumber,
LogicalDeviceSize);
else if (NewLogicalDeviceInfo->DataMigrationInProgress)
DAC960_V2_ReportProgress(Controller,
"Data Migration",
LogicalDeviceNumber,
NewLogicalDeviceInfo
->DataMigrationBlockNumber,
LogicalDeviceSize);
else if (NewLogicalDeviceInfo->PatrolOperationInProgress)
DAC960_V2_ReportProgress(Controller,
"Patrol Operation",
LogicalDeviceNumber,
NewLogicalDeviceInfo
->PatrolOperationBlockNumber,
LogicalDeviceSize);
if (LogicalDeviceInfo->BackgroundInitializationInProgress &&
!NewLogicalDeviceInfo->BackgroundInitializationInProgress)
DAC960_Progress("Logical Drive %d (/dev/rd/c%dd%d) "
"Background Initialization %s\n",
Controller,
LogicalDeviceNumber,
Controller->ControllerNumber,
LogicalDeviceNumber,
(NewLogicalDeviceInfo->LogicalDeviceControl
.LogicalDeviceInitialized
? "Completed" : "Failed"));
memcpy(LogicalDeviceInfo, NewLogicalDeviceInfo,
sizeof(DAC960_V2_LogicalDeviceInfo_T));
}
Controller->V2.LogicalDriveFoundDuringScan
[LogicalDeviceNumber] = true;
NewLogicalDeviceInfo->LogicalDeviceNumber++;
}
else if (CommandOpcode == DAC960_V2_GetLogicalDeviceInfoValid)
{
int LogicalDriveNumber;
for (LogicalDriveNumber = 0;
LogicalDriveNumber < DAC960_MaxLogicalDrives;
LogicalDriveNumber++)
{
DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
if (LogicalDeviceInfo == NULL ||
Controller->V2.LogicalDriveFoundDuringScan
[LogicalDriveNumber])
continue;
DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
"No Longer Exists\n", Controller,
LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
Controller->V2.LogicalDeviceInformation
[LogicalDriveNumber] = NULL;
kfree(LogicalDeviceInfo);
Controller->LogicalDriveInitiallyAccessible
[LogicalDriveNumber] = false;
DAC960_ComputeGenericDiskInfo(Controller);
}
Controller->V2.NeedLogicalDeviceInformation = false;
}
else if (CommandOpcode == DAC960_V2_SCSI_10_Passthru)
{
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
Controller->V2.InquiryUnitSerialNumber[Controller->V2.PhysicalDeviceIndex - 1];
if (CommandStatus != DAC960_V2_NormalCompletion) {
memset(InquiryUnitSerialNumber,
0, sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
} else
memcpy(InquiryUnitSerialNumber,
Controller->V2.NewInquiryUnitSerialNumber,
sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
Controller->V2.NeedDeviceSerialNumberInformation = false;
}
if (Controller->V2.HealthStatusBuffer->NextEventSequenceNumber
- Controller->V2.NextEventSequenceNumber > 0)
{
CommandMailbox->GetEvent.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->GetEvent.DataTransferSize = sizeof(DAC960_V2_Event_T);
CommandMailbox->GetEvent.EventSequenceNumberHigh16 =
Controller->V2.NextEventSequenceNumber >> 16;
CommandMailbox->GetEvent.ControllerNumber = 0;
CommandMailbox->GetEvent.IOCTL_Opcode =
DAC960_V2_GetEvent;
CommandMailbox->GetEvent.EventSequenceNumberLow16 =
Controller->V2.NextEventSequenceNumber & 0xFFFF;
CommandMailbox->GetEvent.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.EventDMA;
CommandMailbox->GetEvent.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->GetEvent.DataTransferSize;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V2.NeedPhysicalDeviceInformation)
{
if (Controller->V2.NeedDeviceSerialNumberInformation)
{
DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
Controller->V2.NewInquiryUnitSerialNumber;
InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
DAC960_V2_ConstructNewUnitSerialNumber(Controller, CommandMailbox,
Controller->V2.NewPhysicalDeviceInformation->Channel,
Controller->V2.NewPhysicalDeviceInformation->TargetID,
Controller->V2.NewPhysicalDeviceInformation->LogicalUnit - 1);
DAC960_QueueCommand(Command);
return;
}
if (Controller->V2.StartPhysicalDeviceInformationScan)
{
Controller->V2.PhysicalDeviceIndex = 0;
Controller->V2.NewPhysicalDeviceInformation->Channel = 0;
Controller->V2.NewPhysicalDeviceInformation->TargetID = 0;
Controller->V2.NewPhysicalDeviceInformation->LogicalUnit = 0;
Controller->V2.StartPhysicalDeviceInformationScan = false;
}
CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
sizeof(DAC960_V2_PhysicalDeviceInfo_T);
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.LogicalUnit =
Controller->V2.NewPhysicalDeviceInformation->LogicalUnit;
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID =
Controller->V2.NewPhysicalDeviceInformation->TargetID;
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel =
Controller->V2.NewPhysicalDeviceInformation->Channel;
CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
DAC960_V2_GetPhysicalDeviceInfoValid;
CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewPhysicalDeviceInformationDMA;
CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->PhysicalDeviceInfo.DataTransferSize;
DAC960_QueueCommand(Command);
return;
}
if (Controller->V2.NeedLogicalDeviceInformation)
{
if (Controller->V2.StartLogicalDeviceInformationScan)
{
int LogicalDriveNumber;
for (LogicalDriveNumber = 0;
LogicalDriveNumber < DAC960_MaxLogicalDrives;
LogicalDriveNumber++)
Controller->V2.LogicalDriveFoundDuringScan
[LogicalDriveNumber] = false;
Controller->V2.NewLogicalDeviceInformation->LogicalDeviceNumber = 0;
Controller->V2.StartLogicalDeviceInformationScan = false;
}
CommandMailbox->LogicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->LogicalDeviceInfo.DataTransferSize =
sizeof(DAC960_V2_LogicalDeviceInfo_T);
CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
Controller->V2.NewLogicalDeviceInformation->LogicalDeviceNumber;
CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode =
DAC960_V2_GetLogicalDeviceInfoValid;
CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewLogicalDeviceInformationDMA;
CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->LogicalDeviceInfo.DataTransferSize;
DAC960_QueueCommand(Command);
return;
}
Controller->MonitoringTimerCount++;
Controller->MonitoringTimer.expires =
jiffies + DAC960_HealthStatusMonitoringInterval;
add_timer(&Controller->MonitoringTimer);
}
if (CommandType == DAC960_ImmediateCommand)
{
complete(Command->Completion);
Command->Completion = NULL;
return;
}
if (CommandType == DAC960_QueuedCommand)
{
DAC960_V2_KernelCommand_T *KernelCommand = Command->V2.KernelCommand;
KernelCommand->CommandStatus = CommandStatus;
KernelCommand->RequestSenseLength = Command->V2.RequestSenseLength;
KernelCommand->DataTransferLength = Command->V2.DataTransferResidue;
Command->V2.KernelCommand = NULL;
DAC960_DeallocateCommand(Command);
KernelCommand->CompletionFunction(KernelCommand);
return;
}
/*
Queue a Status Monitoring Command to the Controller using the just
completed Command if one was deferred previously due to lack of a
free Command when the Monitoring Timer Function was called.
*/
if (Controller->MonitoringCommandDeferred)
{
Controller->MonitoringCommandDeferred = false;
DAC960_V2_QueueMonitoringCommand(Command);
return;
}
/*
Deallocate the Command.
*/
DAC960_DeallocateCommand(Command);
/*
Wake up any processes waiting on a free Command.
*/
wake_up(&Controller->CommandWaitQueue);
}
/*
DAC960_GEM_InterruptHandler handles hardware interrupts from DAC960 GEM Series
Controllers.
*/
static irqreturn_t DAC960_GEM_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V2_StatusMailbox_T *NextStatusMailbox;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_GEM_AcknowledgeInterrupt(ControllerBaseAddress);
NextStatusMailbox = Controller->V2.NextStatusMailbox;
while (NextStatusMailbox->Fields.CommandIdentifier > 0)
{
DAC960_V2_CommandIdentifier_T CommandIdentifier =
NextStatusMailbox->Fields.CommandIdentifier;
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
Command->V2.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
Command->V2.RequestSenseLength =
NextStatusMailbox->Fields.RequestSenseLength;
Command->V2.DataTransferResidue =
NextStatusMailbox->Fields.DataTransferResidue;
NextStatusMailbox->Words[0] = 0;
if (++NextStatusMailbox > Controller->V2.LastStatusMailbox)
NextStatusMailbox = Controller->V2.FirstStatusMailbox;
DAC960_V2_ProcessCompletedCommand(Command);
}
Controller->V2.NextStatusMailbox = NextStatusMailbox;
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_BA_InterruptHandler handles hardware interrupts from DAC960 BA Series
Controllers.
*/
static irqreturn_t DAC960_BA_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V2_StatusMailbox_T *NextStatusMailbox;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_BA_AcknowledgeInterrupt(ControllerBaseAddress);
NextStatusMailbox = Controller->V2.NextStatusMailbox;
while (NextStatusMailbox->Fields.CommandIdentifier > 0)
{
DAC960_V2_CommandIdentifier_T CommandIdentifier =
NextStatusMailbox->Fields.CommandIdentifier;
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
Command->V2.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
Command->V2.RequestSenseLength =
NextStatusMailbox->Fields.RequestSenseLength;
Command->V2.DataTransferResidue =
NextStatusMailbox->Fields.DataTransferResidue;
NextStatusMailbox->Words[0] = 0;
if (++NextStatusMailbox > Controller->V2.LastStatusMailbox)
NextStatusMailbox = Controller->V2.FirstStatusMailbox;
DAC960_V2_ProcessCompletedCommand(Command);
}
Controller->V2.NextStatusMailbox = NextStatusMailbox;
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_LP_InterruptHandler handles hardware interrupts from DAC960 LP Series
Controllers.
*/
static irqreturn_t DAC960_LP_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V2_StatusMailbox_T *NextStatusMailbox;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_LP_AcknowledgeInterrupt(ControllerBaseAddress);
NextStatusMailbox = Controller->V2.NextStatusMailbox;
while (NextStatusMailbox->Fields.CommandIdentifier > 0)
{
DAC960_V2_CommandIdentifier_T CommandIdentifier =
NextStatusMailbox->Fields.CommandIdentifier;
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
Command->V2.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
Command->V2.RequestSenseLength =
NextStatusMailbox->Fields.RequestSenseLength;
Command->V2.DataTransferResidue =
NextStatusMailbox->Fields.DataTransferResidue;
NextStatusMailbox->Words[0] = 0;
if (++NextStatusMailbox > Controller->V2.LastStatusMailbox)
NextStatusMailbox = Controller->V2.FirstStatusMailbox;
DAC960_V2_ProcessCompletedCommand(Command);
}
Controller->V2.NextStatusMailbox = NextStatusMailbox;
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_LA_InterruptHandler handles hardware interrupts from DAC960 LA Series
Controllers.
*/
static irqreturn_t DAC960_LA_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_StatusMailbox_T *NextStatusMailbox;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_LA_AcknowledgeInterrupt(ControllerBaseAddress);
NextStatusMailbox = Controller->V1.NextStatusMailbox;
while (NextStatusMailbox->Fields.Valid)
{
DAC960_V1_CommandIdentifier_T CommandIdentifier =
NextStatusMailbox->Fields.CommandIdentifier;
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
Command->V1.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
NextStatusMailbox->Word = 0;
if (++NextStatusMailbox > Controller->V1.LastStatusMailbox)
NextStatusMailbox = Controller->V1.FirstStatusMailbox;
DAC960_V1_ProcessCompletedCommand(Command);
}
Controller->V1.NextStatusMailbox = NextStatusMailbox;
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_PG_InterruptHandler handles hardware interrupts from DAC960 PG Series
Controllers.
*/
static irqreturn_t DAC960_PG_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
DAC960_V1_StatusMailbox_T *NextStatusMailbox;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_PG_AcknowledgeInterrupt(ControllerBaseAddress);
NextStatusMailbox = Controller->V1.NextStatusMailbox;
while (NextStatusMailbox->Fields.Valid)
{
DAC960_V1_CommandIdentifier_T CommandIdentifier =
NextStatusMailbox->Fields.CommandIdentifier;
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
Command->V1.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
NextStatusMailbox->Word = 0;
if (++NextStatusMailbox > Controller->V1.LastStatusMailbox)
NextStatusMailbox = Controller->V1.FirstStatusMailbox;
DAC960_V1_ProcessCompletedCommand(Command);
}
Controller->V1.NextStatusMailbox = NextStatusMailbox;
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_PD_InterruptHandler handles hardware interrupts from DAC960 PD Series
Controllers.
*/
static irqreturn_t DAC960_PD_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
while (DAC960_PD_StatusAvailableP(ControllerBaseAddress))
{
DAC960_V1_CommandIdentifier_T CommandIdentifier =
DAC960_PD_ReadStatusCommandIdentifier(ControllerBaseAddress);
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
Command->V1.CommandStatus =
DAC960_PD_ReadStatusRegister(ControllerBaseAddress);
DAC960_PD_AcknowledgeInterrupt(ControllerBaseAddress);
DAC960_PD_AcknowledgeStatus(ControllerBaseAddress);
DAC960_V1_ProcessCompletedCommand(Command);
}
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_P_InterruptHandler handles hardware interrupts from DAC960 P Series
Controllers.
Translations of DAC960_V1_Enquiry and DAC960_V1_GetDeviceState rely
on the data having been placed into DAC960_Controller_T, rather than
an arbitrary buffer.
*/
static irqreturn_t DAC960_P_InterruptHandler(int IRQ_Channel,
void *DeviceIdentifier)
{
DAC960_Controller_T *Controller = DeviceIdentifier;
void __iomem *ControllerBaseAddress = Controller->BaseAddress;
unsigned long flags;
spin_lock_irqsave(&Controller->queue_lock, flags);
while (DAC960_PD_StatusAvailableP(ControllerBaseAddress))
{
DAC960_V1_CommandIdentifier_T CommandIdentifier =
DAC960_PD_ReadStatusCommandIdentifier(ControllerBaseAddress);
DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_CommandOpcode_T CommandOpcode =
CommandMailbox->Common.CommandOpcode;
Command->V1.CommandStatus =
DAC960_PD_ReadStatusRegister(ControllerBaseAddress);
DAC960_PD_AcknowledgeInterrupt(ControllerBaseAddress);
DAC960_PD_AcknowledgeStatus(ControllerBaseAddress);
switch (CommandOpcode)
{
case DAC960_V1_Enquiry_Old:
Command->V1.CommandMailbox.Common.CommandOpcode = DAC960_V1_Enquiry;
DAC960_P_To_PD_TranslateEnquiry(Controller->V1.NewEnquiry);
break;
case DAC960_V1_GetDeviceState_Old:
Command->V1.CommandMailbox.Common.CommandOpcode =
DAC960_V1_GetDeviceState;
DAC960_P_To_PD_TranslateDeviceState(Controller->V1.NewDeviceState);
break;
case DAC960_V1_Read_Old:
Command->V1.CommandMailbox.Common.CommandOpcode = DAC960_V1_Read;
DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
break;
case DAC960_V1_Write_Old:
Command->V1.CommandMailbox.Common.CommandOpcode = DAC960_V1_Write;
DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
break;
case DAC960_V1_ReadWithScatterGather_Old:
Command->V1.CommandMailbox.Common.CommandOpcode =
DAC960_V1_ReadWithScatterGather;
DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
break;
case DAC960_V1_WriteWithScatterGather_Old:
Command->V1.CommandMailbox.Common.CommandOpcode =
DAC960_V1_WriteWithScatterGather;
DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
break;
default:
break;
}
DAC960_V1_ProcessCompletedCommand(Command);
}
/*
Attempt to remove additional I/O Requests from the Controller's
I/O Request Queue and queue them to the Controller.
*/
DAC960_ProcessRequest(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return IRQ_HANDLED;
}
/*
DAC960_V1_QueueMonitoringCommand queues a Monitoring Command to DAC960 V1
Firmware Controllers.
*/
static void DAC960_V1_QueueMonitoringCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_MonitoringCommand;
CommandMailbox->Type3.CommandOpcode = DAC960_V1_Enquiry;
CommandMailbox->Type3.BusAddress = Controller->V1.NewEnquiryDMA;
DAC960_QueueCommand(Command);
}
/*
DAC960_V2_QueueMonitoringCommand queues a Monitoring Command to DAC960 V2
Firmware Controllers.
*/
static void DAC960_V2_QueueMonitoringCommand(DAC960_Command_T *Command)
{
DAC960_Controller_T *Controller = Command->Controller;
DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_MonitoringCommand;
CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->ControllerInfo.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->ControllerInfo.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->ControllerInfo.DataTransferSize =
sizeof(DAC960_V2_ControllerInfo_T);
CommandMailbox->ControllerInfo.ControllerNumber = 0;
CommandMailbox->ControllerInfo.IOCTL_Opcode = DAC960_V2_GetControllerInfo;
CommandMailbox->ControllerInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewControllerInformationDMA;
CommandMailbox->ControllerInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->ControllerInfo.DataTransferSize;
DAC960_QueueCommand(Command);
}
/*
DAC960_MonitoringTimerFunction is the timer function for monitoring
the status of DAC960 Controllers.
*/
static void DAC960_MonitoringTimerFunction(unsigned long TimerData)
{
DAC960_Controller_T *Controller = (DAC960_Controller_T *) TimerData;
DAC960_Command_T *Command;
unsigned long flags;
if (Controller->FirmwareType == DAC960_V1_Controller)
{
spin_lock_irqsave(&Controller->queue_lock, flags);
/*
Queue a Status Monitoring Command to Controller.
*/
Command = DAC960_AllocateCommand(Controller);
if (Command != NULL)
DAC960_V1_QueueMonitoringCommand(Command);
else Controller->MonitoringCommandDeferred = true;
spin_unlock_irqrestore(&Controller->queue_lock, flags);
}
else
{
DAC960_V2_ControllerInfo_T *ControllerInfo =
&Controller->V2.ControllerInformation;
unsigned int StatusChangeCounter =
Controller->V2.HealthStatusBuffer->StatusChangeCounter;
bool ForceMonitoringCommand = false;
if (time_after(jiffies, Controller->SecondaryMonitoringTime
+ DAC960_SecondaryMonitoringInterval))
{
int LogicalDriveNumber;
for (LogicalDriveNumber = 0;
LogicalDriveNumber < DAC960_MaxLogicalDrives;
LogicalDriveNumber++)
{
DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
if (LogicalDeviceInfo == NULL) continue;
if (!LogicalDeviceInfo->LogicalDeviceControl
.LogicalDeviceInitialized)
{
ForceMonitoringCommand = true;
break;
}
}
Controller->SecondaryMonitoringTime = jiffies;
}
if (StatusChangeCounter == Controller->V2.StatusChangeCounter &&
Controller->V2.HealthStatusBuffer->NextEventSequenceNumber
== Controller->V2.NextEventSequenceNumber &&
(ControllerInfo->BackgroundInitializationsActive +
ControllerInfo->LogicalDeviceInitializationsActive +
ControllerInfo->PhysicalDeviceInitializationsActive +
ControllerInfo->ConsistencyChecksActive +
ControllerInfo->RebuildsActive +
ControllerInfo->OnlineExpansionsActive == 0 ||
time_before(jiffies, Controller->PrimaryMonitoringTime
+ DAC960_MonitoringTimerInterval)) &&
!ForceMonitoringCommand)
{
Controller->MonitoringTimer.expires =
jiffies + DAC960_HealthStatusMonitoringInterval;
add_timer(&Controller->MonitoringTimer);
return;
}
Controller->V2.StatusChangeCounter = StatusChangeCounter;
Controller->PrimaryMonitoringTime = jiffies;
spin_lock_irqsave(&Controller->queue_lock, flags);
/*
Queue a Status Monitoring Command to Controller.
*/
Command = DAC960_AllocateCommand(Controller);
if (Command != NULL)
DAC960_V2_QueueMonitoringCommand(Command);
else Controller->MonitoringCommandDeferred = true;
spin_unlock_irqrestore(&Controller->queue_lock, flags);
/*
Wake up any processes waiting on a Health Status Buffer change.
*/
wake_up(&Controller->HealthStatusWaitQueue);
}
}
/*
DAC960_CheckStatusBuffer verifies that there is room to hold ByteCount
additional bytes in the Combined Status Buffer and grows the buffer if
necessary. It returns true if there is enough room and false otherwise.
*/
static bool DAC960_CheckStatusBuffer(DAC960_Controller_T *Controller,
unsigned int ByteCount)
{
unsigned char *NewStatusBuffer;
if (Controller->InitialStatusLength + 1 +
Controller->CurrentStatusLength + ByteCount + 1 <=
Controller->CombinedStatusBufferLength)
return true;
if (Controller->CombinedStatusBufferLength == 0)
{
unsigned int NewStatusBufferLength = DAC960_InitialStatusBufferSize;
while (NewStatusBufferLength < ByteCount)
NewStatusBufferLength *= 2;
Controller->CombinedStatusBuffer = kmalloc(NewStatusBufferLength,
GFP_ATOMIC);
if (Controller->CombinedStatusBuffer == NULL) return false;
Controller->CombinedStatusBufferLength = NewStatusBufferLength;
return true;
}
NewStatusBuffer = kmalloc(2 * Controller->CombinedStatusBufferLength,
GFP_ATOMIC);
if (NewStatusBuffer == NULL)
{
DAC960_Warning("Unable to expand Combined Status Buffer - Truncating\n",
Controller);
return false;
}
memcpy(NewStatusBuffer, Controller->CombinedStatusBuffer,
Controller->CombinedStatusBufferLength);
kfree(Controller->CombinedStatusBuffer);
Controller->CombinedStatusBuffer = NewStatusBuffer;
Controller->CombinedStatusBufferLength *= 2;
Controller->CurrentStatusBuffer =
&NewStatusBuffer[Controller->InitialStatusLength + 1];
return true;
}
/*
DAC960_Message prints Driver Messages.
*/
static void DAC960_Message(DAC960_MessageLevel_T MessageLevel,
unsigned char *Format,
DAC960_Controller_T *Controller,
...)
{
static unsigned char Buffer[DAC960_LineBufferSize];
static bool BeginningOfLine = true;
va_list Arguments;
int Length = 0;
va_start(Arguments, Controller);
Length = vsprintf(Buffer, Format, Arguments);
va_end(Arguments);
if (Controller == NULL)
printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
DAC960_ControllerCount, Buffer);
else if (MessageLevel == DAC960_AnnounceLevel ||
MessageLevel == DAC960_InfoLevel)
{
if (!Controller->ControllerInitialized)
{
if (DAC960_CheckStatusBuffer(Controller, Length))
{
strcpy(&Controller->CombinedStatusBuffer
[Controller->InitialStatusLength],
Buffer);
Controller->InitialStatusLength += Length;
Controller->CurrentStatusBuffer =
&Controller->CombinedStatusBuffer
[Controller->InitialStatusLength + 1];
}
if (MessageLevel == DAC960_AnnounceLevel)
{
static int AnnouncementLines = 0;
if (++AnnouncementLines <= 2)
printk("%sDAC960: %s", DAC960_MessageLevelMap[MessageLevel],
Buffer);
}
else
{
if (BeginningOfLine)
{
if (Buffer[0] != '\n' || Length > 1)
printk("%sDAC960#%d: %s",
DAC960_MessageLevelMap[MessageLevel],
Controller->ControllerNumber, Buffer);
}
else printk("%s", Buffer);
}
}
else if (DAC960_CheckStatusBuffer(Controller, Length))
{
strcpy(&Controller->CurrentStatusBuffer[
Controller->CurrentStatusLength], Buffer);
Controller->CurrentStatusLength += Length;
}
}
else if (MessageLevel == DAC960_ProgressLevel)
{
strcpy(Controller->ProgressBuffer, Buffer);
Controller->ProgressBufferLength = Length;
if (Controller->EphemeralProgressMessage)
{
if (time_after_eq(jiffies, Controller->LastProgressReportTime
+ DAC960_ProgressReportingInterval))
{
printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
Controller->ControllerNumber, Buffer);
Controller->LastProgressReportTime = jiffies;
}
}
else printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
Controller->ControllerNumber, Buffer);
}
else if (MessageLevel == DAC960_UserCriticalLevel)
{
strcpy(&Controller->UserStatusBuffer[Controller->UserStatusLength],
Buffer);
Controller->UserStatusLength += Length;
if (Buffer[0] != '\n' || Length > 1)
printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
Controller->ControllerNumber, Buffer);
}
else
{
if (BeginningOfLine)
printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
Controller->ControllerNumber, Buffer);
else printk("%s", Buffer);
}
BeginningOfLine = (Buffer[Length-1] == '\n');
}
/*
DAC960_ParsePhysicalDevice parses spaces followed by a Physical Device
Channel:TargetID specification from a User Command string. It updates
Channel and TargetID and returns true on success and false on failure.
*/
static bool DAC960_ParsePhysicalDevice(DAC960_Controller_T *Controller,
char *UserCommandString,
unsigned char *Channel,
unsigned char *TargetID)
{
char *NewUserCommandString = UserCommandString;
unsigned long XChannel, XTargetID;
while (*UserCommandString == ' ') UserCommandString++;
if (UserCommandString == NewUserCommandString)
return false;
XChannel = simple_strtoul(UserCommandString, &NewUserCommandString, 10);
if (NewUserCommandString == UserCommandString ||
*NewUserCommandString != ':' ||
XChannel >= Controller->Channels)
return false;
UserCommandString = ++NewUserCommandString;
XTargetID = simple_strtoul(UserCommandString, &NewUserCommandString, 10);
if (NewUserCommandString == UserCommandString ||
*NewUserCommandString != '\0' ||
XTargetID >= Controller->Targets)
return false;
*Channel = XChannel;
*TargetID = XTargetID;
return true;
}
/*
DAC960_ParseLogicalDrive parses spaces followed by a Logical Drive Number
specification from a User Command string. It updates LogicalDriveNumber and
returns true on success and false on failure.
*/
static bool DAC960_ParseLogicalDrive(DAC960_Controller_T *Controller,
char *UserCommandString,
unsigned char *LogicalDriveNumber)
{
char *NewUserCommandString = UserCommandString;
unsigned long XLogicalDriveNumber;
while (*UserCommandString == ' ') UserCommandString++;
if (UserCommandString == NewUserCommandString)
return false;
XLogicalDriveNumber =
simple_strtoul(UserCommandString, &NewUserCommandString, 10);
if (NewUserCommandString == UserCommandString ||
*NewUserCommandString != '\0' ||
XLogicalDriveNumber > DAC960_MaxLogicalDrives - 1)
return false;
*LogicalDriveNumber = XLogicalDriveNumber;
return true;
}
/*
DAC960_V1_SetDeviceState sets the Device State for a Physical Device for
DAC960 V1 Firmware Controllers.
*/
static void DAC960_V1_SetDeviceState(DAC960_Controller_T *Controller,
DAC960_Command_T *Command,
unsigned char Channel,
unsigned char TargetID,
DAC960_V1_PhysicalDeviceState_T
DeviceState,
const unsigned char *DeviceStateString)
{
DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
CommandMailbox->Type3D.CommandOpcode = DAC960_V1_StartDevice;
CommandMailbox->Type3D.Channel = Channel;
CommandMailbox->Type3D.TargetID = TargetID;
CommandMailbox->Type3D.DeviceState = DeviceState;
CommandMailbox->Type3D.Modifier = 0;
DAC960_ExecuteCommand(Command);
switch (Command->V1.CommandStatus)
{
case DAC960_V1_NormalCompletion:
DAC960_UserCritical("%s of Physical Device %d:%d Succeeded\n", Controller,
DeviceStateString, Channel, TargetID);
break;
case DAC960_V1_UnableToStartDevice:
DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
"Unable to Start Device\n", Controller,
DeviceStateString, Channel, TargetID);
break;
case DAC960_V1_NoDeviceAtAddress:
DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
"No Device at Address\n", Controller,
DeviceStateString, Channel, TargetID);
break;
case DAC960_V1_InvalidChannelOrTargetOrModifier:
DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
"Invalid Channel or Target or Modifier\n",
Controller, DeviceStateString, Channel, TargetID);
break;
case DAC960_V1_ChannelBusy:
DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
"Channel Busy\n", Controller,
DeviceStateString, Channel, TargetID);
break;
default:
DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
"Unexpected Status %04X\n", Controller,
DeviceStateString, Channel, TargetID,
Command->V1.CommandStatus);
break;
}
}
/*
DAC960_V1_ExecuteUserCommand executes a User Command for DAC960 V1 Firmware
Controllers.
*/
static bool DAC960_V1_ExecuteUserCommand(DAC960_Controller_T *Controller,
unsigned char *UserCommand)
{
DAC960_Command_T *Command;
DAC960_V1_CommandMailbox_T *CommandMailbox;
unsigned long flags;
unsigned char Channel, TargetID, LogicalDriveNumber;
spin_lock_irqsave(&Controller->queue_lock, flags);
while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
DAC960_WaitForCommand(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
Controller->UserStatusLength = 0;
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox = &Command->V1.CommandMailbox;
if (strcmp(UserCommand, "flush-cache") == 0)
{
CommandMailbox->Type3.CommandOpcode = DAC960_V1_Flush;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Cache Flush Completed\n", Controller);
}
else if (strncmp(UserCommand, "kill", 4) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[4],
&Channel, &TargetID))
{
DAC960_V1_DeviceState_T *DeviceState =
&Controller->V1.DeviceState[Channel][TargetID];
if (DeviceState->Present &&
DeviceState->DeviceType == DAC960_V1_DiskType &&
DeviceState->DeviceState != DAC960_V1_Device_Dead)
DAC960_V1_SetDeviceState(Controller, Command, Channel, TargetID,
DAC960_V1_Device_Dead, "Kill");
else DAC960_UserCritical("Kill of Physical Device %d:%d Illegal\n",
Controller, Channel, TargetID);
}
else if (strncmp(UserCommand, "make-online", 11) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[11],
&Channel, &TargetID))
{
DAC960_V1_DeviceState_T *DeviceState =
&Controller->V1.DeviceState[Channel][TargetID];
if (DeviceState->Present &&
DeviceState->DeviceType == DAC960_V1_DiskType &&
DeviceState->DeviceState == DAC960_V1_Device_Dead)
DAC960_V1_SetDeviceState(Controller, Command, Channel, TargetID,
DAC960_V1_Device_Online, "Make Online");
else DAC960_UserCritical("Make Online of Physical Device %d:%d Illegal\n",
Controller, Channel, TargetID);
}
else if (strncmp(UserCommand, "make-standby", 12) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[12],
&Channel, &TargetID))
{
DAC960_V1_DeviceState_T *DeviceState =
&Controller->V1.DeviceState[Channel][TargetID];
if (DeviceState->Present &&
DeviceState->DeviceType == DAC960_V1_DiskType &&
DeviceState->DeviceState == DAC960_V1_Device_Dead)
DAC960_V1_SetDeviceState(Controller, Command, Channel, TargetID,
DAC960_V1_Device_Standby, "Make Standby");
else DAC960_UserCritical("Make Standby of Physical "
"Device %d:%d Illegal\n",
Controller, Channel, TargetID);
}
else if (strncmp(UserCommand, "rebuild", 7) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[7],
&Channel, &TargetID))
{
CommandMailbox->Type3D.CommandOpcode = DAC960_V1_RebuildAsync;
CommandMailbox->Type3D.Channel = Channel;
CommandMailbox->Type3D.TargetID = TargetID;
DAC960_ExecuteCommand(Command);
switch (Command->V1.CommandStatus)
{
case DAC960_V1_NormalCompletion:
DAC960_UserCritical("Rebuild of Physical Device %d:%d Initiated\n",
Controller, Channel, TargetID);
break;
case DAC960_V1_AttemptToRebuildOnlineDrive:
DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
"Attempt to Rebuild Online or "
"Unresponsive Drive\n",
Controller, Channel, TargetID);
break;
case DAC960_V1_NewDiskFailedDuringRebuild:
DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
"New Disk Failed During Rebuild\n",
Controller, Channel, TargetID);
break;
case DAC960_V1_InvalidDeviceAddress:
DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
"Invalid Device Address\n",
Controller, Channel, TargetID);
break;
case DAC960_V1_RebuildOrCheckAlreadyInProgress:
DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
"Rebuild or Consistency Check Already "
"in Progress\n", Controller, Channel, TargetID);
break;
default:
DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
"Unexpected Status %04X\n", Controller,
Channel, TargetID, Command->V1.CommandStatus);
break;
}
}
else if (strncmp(UserCommand, "check-consistency", 17) == 0 &&
DAC960_ParseLogicalDrive(Controller, &UserCommand[17],
&LogicalDriveNumber))
{
CommandMailbox->Type3C.CommandOpcode = DAC960_V1_CheckConsistencyAsync;
CommandMailbox->Type3C.LogicalDriveNumber = LogicalDriveNumber;
CommandMailbox->Type3C.AutoRestore = true;
DAC960_ExecuteCommand(Command);
switch (Command->V1.CommandStatus)
{
case DAC960_V1_NormalCompletion:
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) Initiated\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
break;
case DAC960_V1_DependentDiskIsDead:
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) Failed - "
"Dependent Physical Device is DEAD\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
break;
case DAC960_V1_InvalidOrNonredundantLogicalDrive:
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) Failed - "
"Invalid or Nonredundant Logical Drive\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
break;
case DAC960_V1_RebuildOrCheckAlreadyInProgress:
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) Failed - Rebuild or "
"Consistency Check Already in Progress\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber);
break;
default:
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) Failed - "
"Unexpected Status %04X\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber, Command->V1.CommandStatus);
break;
}
}
else if (strcmp(UserCommand, "cancel-rebuild") == 0 ||
strcmp(UserCommand, "cancel-consistency-check") == 0)
{
/*
the OldRebuildRateConstant is never actually used
once its value is retrieved from the controller.
*/
unsigned char *OldRebuildRateConstant;
dma_addr_t OldRebuildRateConstantDMA;
OldRebuildRateConstant = pci_alloc_consistent( Controller->PCIDevice,
sizeof(char), &OldRebuildRateConstantDMA);
if (OldRebuildRateConstant == NULL) {
DAC960_UserCritical("Cancellation of Rebuild or "
"Consistency Check Failed - "
"Out of Memory",
Controller);
goto failure;
}
CommandMailbox->Type3R.CommandOpcode = DAC960_V1_RebuildControl;
CommandMailbox->Type3R.RebuildRateConstant = 0xFF;
CommandMailbox->Type3R.BusAddress = OldRebuildRateConstantDMA;
DAC960_ExecuteCommand(Command);
switch (Command->V1.CommandStatus)
{
case DAC960_V1_NormalCompletion:
DAC960_UserCritical("Rebuild or Consistency Check Cancelled\n",
Controller);
break;
default:
DAC960_UserCritical("Cancellation of Rebuild or "
"Consistency Check Failed - "
"Unexpected Status %04X\n",
Controller, Command->V1.CommandStatus);
break;
}
failure:
pci_free_consistent(Controller->PCIDevice, sizeof(char),
OldRebuildRateConstant, OldRebuildRateConstantDMA);
}
else DAC960_UserCritical("Illegal User Command: '%s'\n",
Controller, UserCommand);
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_DeallocateCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return true;
}
/*
DAC960_V2_TranslatePhysicalDevice translates a Physical Device Channel and
TargetID into a Logical Device. It returns true on success and false
on failure.
*/
static bool DAC960_V2_TranslatePhysicalDevice(DAC960_Command_T *Command,
unsigned char Channel,
unsigned char TargetID,
unsigned short
*LogicalDeviceNumber)
{
DAC960_V2_CommandMailbox_T SavedCommandMailbox, *CommandMailbox;
DAC960_Controller_T *Controller = Command->Controller;
CommandMailbox = &Command->V2.CommandMailbox;
memcpy(&SavedCommandMailbox, CommandMailbox,
sizeof(DAC960_V2_CommandMailbox_T));
CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->PhysicalDeviceInfo.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->PhysicalDeviceInfo.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
sizeof(DAC960_V2_PhysicalToLogicalDevice_T);
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID = TargetID;
CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel = Channel;
CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
DAC960_V2_TranslatePhysicalToLogicalDevice;
CommandMailbox->Common.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.PhysicalToLogicalDeviceDMA;
CommandMailbox->Common.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->Common.DataTransferSize;
DAC960_ExecuteCommand(Command);
*LogicalDeviceNumber = Controller->V2.PhysicalToLogicalDevice->LogicalDeviceNumber;
memcpy(CommandMailbox, &SavedCommandMailbox,
sizeof(DAC960_V2_CommandMailbox_T));
return (Command->V2.CommandStatus == DAC960_V2_NormalCompletion);
}
/*
DAC960_V2_ExecuteUserCommand executes a User Command for DAC960 V2 Firmware
Controllers.
*/
static bool DAC960_V2_ExecuteUserCommand(DAC960_Controller_T *Controller,
unsigned char *UserCommand)
{
DAC960_Command_T *Command;
DAC960_V2_CommandMailbox_T *CommandMailbox;
unsigned long flags;
unsigned char Channel, TargetID, LogicalDriveNumber;
unsigned short LogicalDeviceNumber;
spin_lock_irqsave(&Controller->queue_lock, flags);
while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
DAC960_WaitForCommand(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
Controller->UserStatusLength = 0;
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox = &Command->V2.CommandMailbox;
CommandMailbox->Common.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->Common.CommandControlBits.DataTransferControllerToHost = true;
CommandMailbox->Common.CommandControlBits.NoAutoRequestSense = true;
if (strcmp(UserCommand, "flush-cache") == 0)
{
CommandMailbox->DeviceOperation.IOCTL_Opcode = DAC960_V2_PauseDevice;
CommandMailbox->DeviceOperation.OperationDevice =
DAC960_V2_RAID_Controller;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Cache Flush Completed\n", Controller);
}
else if (strncmp(UserCommand, "kill", 4) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[4],
&Channel, &TargetID) &&
DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
&LogicalDeviceNumber))
{
CommandMailbox->SetDeviceState.LogicalDevice.LogicalDeviceNumber =
LogicalDeviceNumber;
CommandMailbox->SetDeviceState.IOCTL_Opcode =
DAC960_V2_SetDeviceState;
CommandMailbox->SetDeviceState.DeviceState.PhysicalDeviceState =
DAC960_V2_Device_Dead;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Kill of Physical Device %d:%d %s\n",
Controller, Channel, TargetID,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Succeeded" : "Failed"));
}
else if (strncmp(UserCommand, "make-online", 11) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[11],
&Channel, &TargetID) &&
DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
&LogicalDeviceNumber))
{
CommandMailbox->SetDeviceState.LogicalDevice.LogicalDeviceNumber =
LogicalDeviceNumber;
CommandMailbox->SetDeviceState.IOCTL_Opcode =
DAC960_V2_SetDeviceState;
CommandMailbox->SetDeviceState.DeviceState.PhysicalDeviceState =
DAC960_V2_Device_Online;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Make Online of Physical Device %d:%d %s\n",
Controller, Channel, TargetID,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Succeeded" : "Failed"));
}
else if (strncmp(UserCommand, "make-standby", 12) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[12],
&Channel, &TargetID) &&
DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
&LogicalDeviceNumber))
{
CommandMailbox->SetDeviceState.LogicalDevice.LogicalDeviceNumber =
LogicalDeviceNumber;
CommandMailbox->SetDeviceState.IOCTL_Opcode =
DAC960_V2_SetDeviceState;
CommandMailbox->SetDeviceState.DeviceState.PhysicalDeviceState =
DAC960_V2_Device_Standby;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Make Standby of Physical Device %d:%d %s\n",
Controller, Channel, TargetID,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Succeeded" : "Failed"));
}
else if (strncmp(UserCommand, "rebuild", 7) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[7],
&Channel, &TargetID) &&
DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
&LogicalDeviceNumber))
{
CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
LogicalDeviceNumber;
CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode =
DAC960_V2_RebuildDeviceStart;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Rebuild of Physical Device %d:%d %s\n",
Controller, Channel, TargetID,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Initiated" : "Not Initiated"));
}
else if (strncmp(UserCommand, "cancel-rebuild", 14) == 0 &&
DAC960_ParsePhysicalDevice(Controller, &UserCommand[14],
&Channel, &TargetID) &&
DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
&LogicalDeviceNumber))
{
CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
LogicalDeviceNumber;
CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode =
DAC960_V2_RebuildDeviceStop;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Rebuild of Physical Device %d:%d %s\n",
Controller, Channel, TargetID,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Cancelled" : "Not Cancelled"));
}
else if (strncmp(UserCommand, "check-consistency", 17) == 0 &&
DAC960_ParseLogicalDrive(Controller, &UserCommand[17],
&LogicalDriveNumber))
{
CommandMailbox->ConsistencyCheck.LogicalDevice.LogicalDeviceNumber =
LogicalDriveNumber;
CommandMailbox->ConsistencyCheck.IOCTL_Opcode =
DAC960_V2_ConsistencyCheckStart;
CommandMailbox->ConsistencyCheck.RestoreConsistency = true;
CommandMailbox->ConsistencyCheck.InitializedAreaOnly = false;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) %s\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Initiated" : "Not Initiated"));
}
else if (strncmp(UserCommand, "cancel-consistency-check", 24) == 0 &&
DAC960_ParseLogicalDrive(Controller, &UserCommand[24],
&LogicalDriveNumber))
{
CommandMailbox->ConsistencyCheck.LogicalDevice.LogicalDeviceNumber =
LogicalDriveNumber;
CommandMailbox->ConsistencyCheck.IOCTL_Opcode =
DAC960_V2_ConsistencyCheckStop;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Consistency Check of Logical Drive %d "
"(/dev/rd/c%dd%d) %s\n",
Controller, LogicalDriveNumber,
Controller->ControllerNumber,
LogicalDriveNumber,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Cancelled" : "Not Cancelled"));
}
else if (strcmp(UserCommand, "perform-discovery") == 0)
{
CommandMailbox->Common.IOCTL_Opcode = DAC960_V2_StartDiscovery;
DAC960_ExecuteCommand(Command);
DAC960_UserCritical("Discovery %s\n", Controller,
(Command->V2.CommandStatus
== DAC960_V2_NormalCompletion
? "Initiated" : "Not Initiated"));
if (Command->V2.CommandStatus == DAC960_V2_NormalCompletion)
{
CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
CommandMailbox->ControllerInfo.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->ControllerInfo.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->ControllerInfo.DataTransferSize =
sizeof(DAC960_V2_ControllerInfo_T);
CommandMailbox->ControllerInfo.ControllerNumber = 0;
CommandMailbox->ControllerInfo.IOCTL_Opcode =
DAC960_V2_GetControllerInfo;
/*
* How does this NOT race with the queued Monitoring
* usage of this structure?
*/
CommandMailbox->ControllerInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer =
Controller->V2.NewControllerInformationDMA;
CommandMailbox->ControllerInfo.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->ControllerInfo.DataTransferSize;
DAC960_ExecuteCommand(Command);
while (Controller->V2.NewControllerInformation->PhysicalScanActive)
{
DAC960_ExecuteCommand(Command);
sleep_on_timeout(&Controller->CommandWaitQueue, HZ);
}
DAC960_UserCritical("Discovery Completed\n", Controller);
}
}
else if (strcmp(UserCommand, "suppress-enclosure-messages") == 0)
Controller->SuppressEnclosureMessages = true;
else DAC960_UserCritical("Illegal User Command: '%s'\n",
Controller, UserCommand);
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_DeallocateCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
return true;
}
/*
DAC960_ProcReadStatus implements reading /proc/rd/status.
*/
static int DAC960_ProcReadStatus(char *Page, char **Start, off_t Offset,
int Count, int *EOF, void *Data)
{
unsigned char *StatusMessage = "OK\n";
int ControllerNumber, BytesAvailable;
for (ControllerNumber = 0;
ControllerNumber < DAC960_ControllerCount;
ControllerNumber++)
{
DAC960_Controller_T *Controller = DAC960_Controllers[ControllerNumber];
if (Controller == NULL) continue;
if (Controller->MonitoringAlertMode)
{
StatusMessage = "ALERT\n";
break;
}
}
BytesAvailable = strlen(StatusMessage) - Offset;
if (Count >= BytesAvailable)
{
Count = BytesAvailable;
*EOF = true;
}
if (Count <= 0) return 0;
*Start = Page;
memcpy(Page, &StatusMessage[Offset], Count);
return Count;
}
/*
DAC960_ProcReadInitialStatus implements reading /proc/rd/cN/initial_status.
*/
static int DAC960_ProcReadInitialStatus(char *Page, char **Start, off_t Offset,
int Count, int *EOF, void *Data)
{
DAC960_Controller_T *Controller = (DAC960_Controller_T *) Data;
int BytesAvailable = Controller->InitialStatusLength - Offset;
if (Count >= BytesAvailable)
{
Count = BytesAvailable;
*EOF = true;
}
if (Count <= 0) return 0;
*Start = Page;
memcpy(Page, &Controller->CombinedStatusBuffer[Offset], Count);
return Count;
}
/*
DAC960_ProcReadCurrentStatus implements reading /proc/rd/cN/current_status.
*/
static int DAC960_ProcReadCurrentStatus(char *Page, char **Start, off_t Offset,
int Count, int *EOF, void *Data)
{
DAC960_Controller_T *Controller = (DAC960_Controller_T *) Data;
unsigned char *StatusMessage =
"No Rebuild or Consistency Check in Progress\n";
int ProgressMessageLength = strlen(StatusMessage);
int BytesAvailable;
if (jiffies != Controller->LastCurrentStatusTime)
{
Controller->CurrentStatusLength = 0;
DAC960_AnnounceDriver(Controller);
DAC960_ReportControllerConfiguration(Controller);
DAC960_ReportDeviceConfiguration(Controller);
if (Controller->ProgressBufferLength > 0)
ProgressMessageLength = Controller->ProgressBufferLength;
if (DAC960_CheckStatusBuffer(Controller, 2 + ProgressMessageLength))
{
unsigned char *CurrentStatusBuffer = Controller->CurrentStatusBuffer;
CurrentStatusBuffer[Controller->CurrentStatusLength++] = ' ';
CurrentStatusBuffer[Controller->CurrentStatusLength++] = ' ';
if (Controller->ProgressBufferLength > 0)
strcpy(&CurrentStatusBuffer[Controller->CurrentStatusLength],
Controller->ProgressBuffer);
else
strcpy(&CurrentStatusBuffer[Controller->CurrentStatusLength],
StatusMessage);
Controller->CurrentStatusLength += ProgressMessageLength;
}
Controller->LastCurrentStatusTime = jiffies;
}
BytesAvailable = Controller->CurrentStatusLength - Offset;
if (Count >= BytesAvailable)
{
Count = BytesAvailable;
*EOF = true;
}
if (Count <= 0) return 0;
*Start = Page;
memcpy(Page, &Controller->CurrentStatusBuffer[Offset], Count);
return Count;
}
/*
DAC960_ProcReadUserCommand implements reading /proc/rd/cN/user_command.
*/
static int DAC960_ProcReadUserCommand(char *Page, char **Start, off_t Offset,
int Count, int *EOF, void *Data)
{
DAC960_Controller_T *Controller = (DAC960_Controller_T *) Data;
int BytesAvailable = Controller->UserStatusLength - Offset;
if (Count >= BytesAvailable)
{
Count = BytesAvailable;
*EOF = true;
}
if (Count <= 0) return 0;
*Start = Page;
memcpy(Page, &Controller->UserStatusBuffer[Offset], Count);
return Count;
}
/*
DAC960_ProcWriteUserCommand implements writing /proc/rd/cN/user_command.
*/
static int DAC960_ProcWriteUserCommand(struct file *file,
const char __user *Buffer,
unsigned long Count, void *Data)
{
DAC960_Controller_T *Controller = (DAC960_Controller_T *) Data;
unsigned char CommandBuffer[80];
int Length;
if (Count > sizeof(CommandBuffer)-1) return -EINVAL;
if (copy_from_user(CommandBuffer, Buffer, Count)) return -EFAULT;
CommandBuffer[Count] = '\0';
Length = strlen(CommandBuffer);
if (CommandBuffer[Length-1] == '\n')
CommandBuffer[--Length] = '\0';
if (Controller->FirmwareType == DAC960_V1_Controller)
return (DAC960_V1_ExecuteUserCommand(Controller, CommandBuffer)
? Count : -EBUSY);
else
return (DAC960_V2_ExecuteUserCommand(Controller, CommandBuffer)
? Count : -EBUSY);
}
/*
DAC960_CreateProcEntries creates the /proc/rd/... entries for the
DAC960 Driver.
*/
static void DAC960_CreateProcEntries(DAC960_Controller_T *Controller)
{
struct proc_dir_entry *StatusProcEntry;
struct proc_dir_entry *ControllerProcEntry;
struct proc_dir_entry *UserCommandProcEntry;
if (DAC960_ProcDirectoryEntry == NULL) {
DAC960_ProcDirectoryEntry = proc_mkdir("rd", NULL);
StatusProcEntry = create_proc_read_entry("status", 0,
DAC960_ProcDirectoryEntry,
DAC960_ProcReadStatus, NULL);
}
sprintf(Controller->ControllerName, "c%d", Controller->ControllerNumber);
ControllerProcEntry = proc_mkdir(Controller->ControllerName,
DAC960_ProcDirectoryEntry);
create_proc_read_entry("initial_status", 0, ControllerProcEntry,
DAC960_ProcReadInitialStatus, Controller);
create_proc_read_entry("current_status", 0, ControllerProcEntry,
DAC960_ProcReadCurrentStatus, Controller);
UserCommandProcEntry =
create_proc_read_entry("user_command", S_IWUSR | S_IRUSR,
ControllerProcEntry, DAC960_ProcReadUserCommand,
Controller);
UserCommandProcEntry->write_proc = DAC960_ProcWriteUserCommand;
Controller->ControllerProcEntry = ControllerProcEntry;
}
/*
DAC960_DestroyProcEntries destroys the /proc/rd/... entries for the
DAC960 Driver.
*/
static void DAC960_DestroyProcEntries(DAC960_Controller_T *Controller)
{
if (Controller->ControllerProcEntry == NULL)
return;
remove_proc_entry("initial_status", Controller->ControllerProcEntry);
remove_proc_entry("current_status", Controller->ControllerProcEntry);
remove_proc_entry("user_command", Controller->ControllerProcEntry);
remove_proc_entry(Controller->ControllerName, DAC960_ProcDirectoryEntry);
Controller->ControllerProcEntry = NULL;
}
#ifdef DAC960_GAM_MINOR
/*
* DAC960_gam_ioctl is the ioctl function for performing RAID operations.
*/
static long DAC960_gam_ioctl(struct file *file, unsigned int Request,
unsigned long Argument)
{
long ErrorCode = 0;
if (!capable(CAP_SYS_ADMIN)) return -EACCES;
lock_kernel();
switch (Request)
{
case DAC960_IOCTL_GET_CONTROLLER_COUNT:
ErrorCode = DAC960_ControllerCount;
break;
case DAC960_IOCTL_GET_CONTROLLER_INFO:
{
DAC960_ControllerInfo_T __user *UserSpaceControllerInfo =
(DAC960_ControllerInfo_T __user *) Argument;
DAC960_ControllerInfo_T ControllerInfo;
DAC960_Controller_T *Controller;
int ControllerNumber;
if (UserSpaceControllerInfo == NULL)
ErrorCode = -EINVAL;
else ErrorCode = get_user(ControllerNumber,
&UserSpaceControllerInfo->ControllerNumber);
if (ErrorCode != 0)
break;;
ErrorCode = -ENXIO;
if (ControllerNumber < 0 ||
ControllerNumber > DAC960_ControllerCount - 1) {
break;
}
Controller = DAC960_Controllers[ControllerNumber];
if (Controller == NULL)
break;;
memset(&ControllerInfo, 0, sizeof(DAC960_ControllerInfo_T));
ControllerInfo.ControllerNumber = ControllerNumber;
ControllerInfo.FirmwareType = Controller->FirmwareType;
ControllerInfo.Channels = Controller->Channels;
ControllerInfo.Targets = Controller->Targets;
ControllerInfo.PCI_Bus = Controller->Bus;
ControllerInfo.PCI_Device = Controller->Device;
ControllerInfo.PCI_Function = Controller->Function;
ControllerInfo.IRQ_Channel = Controller->IRQ_Channel;
ControllerInfo.PCI_Address = Controller->PCI_Address;
strcpy(ControllerInfo.ModelName, Controller->ModelName);
strcpy(ControllerInfo.FirmwareVersion, Controller->FirmwareVersion);
ErrorCode = (copy_to_user(UserSpaceControllerInfo, &ControllerInfo,
sizeof(DAC960_ControllerInfo_T)) ? -EFAULT : 0);
break;
}
case DAC960_IOCTL_V1_EXECUTE_COMMAND:
{
DAC960_V1_UserCommand_T __user *UserSpaceUserCommand =
(DAC960_V1_UserCommand_T __user *) Argument;
DAC960_V1_UserCommand_T UserCommand;
DAC960_Controller_T *Controller;
DAC960_Command_T *Command = NULL;
DAC960_V1_CommandOpcode_T CommandOpcode;
DAC960_V1_CommandStatus_T CommandStatus;
DAC960_V1_DCDB_T DCDB;
DAC960_V1_DCDB_T *DCDB_IOBUF = NULL;
dma_addr_t DCDB_IOBUFDMA;
unsigned long flags;
int ControllerNumber, DataTransferLength;
unsigned char *DataTransferBuffer = NULL;
dma_addr_t DataTransferBufferDMA;
if (UserSpaceUserCommand == NULL) {
ErrorCode = -EINVAL;
break;
}
if (copy_from_user(&UserCommand, UserSpaceUserCommand,
sizeof(DAC960_V1_UserCommand_T))) {
ErrorCode = -EFAULT;
break;
}
ControllerNumber = UserCommand.ControllerNumber;
ErrorCode = -ENXIO;
if (ControllerNumber < 0 ||
ControllerNumber > DAC960_ControllerCount - 1)
break;
Controller = DAC960_Controllers[ControllerNumber];
if (Controller == NULL)
break;
ErrorCode = -EINVAL;
if (Controller->FirmwareType != DAC960_V1_Controller)
break;
CommandOpcode = UserCommand.CommandMailbox.Common.CommandOpcode;
DataTransferLength = UserCommand.DataTransferLength;
if (CommandOpcode & 0x80)
break;
if (CommandOpcode == DAC960_V1_DCDB)
{
if (copy_from_user(&DCDB, UserCommand.DCDB,
sizeof(DAC960_V1_DCDB_T))) {
ErrorCode = -EFAULT;
break;
}
if (DCDB.Channel >= DAC960_V1_MaxChannels)
break;
if (!((DataTransferLength == 0 &&
DCDB.Direction
== DAC960_V1_DCDB_NoDataTransfer) ||
(DataTransferLength > 0 &&
DCDB.Direction
== DAC960_V1_DCDB_DataTransferDeviceToSystem) ||
(DataTransferLength < 0 &&
DCDB.Direction
== DAC960_V1_DCDB_DataTransferSystemToDevice)))
break;
if (((DCDB.TransferLengthHigh4 << 16) | DCDB.TransferLength)
!= abs(DataTransferLength))
break;
DCDB_IOBUF = pci_alloc_consistent(Controller->PCIDevice,
sizeof(DAC960_V1_DCDB_T), &DCDB_IOBUFDMA);
if (DCDB_IOBUF == NULL) {
ErrorCode = -ENOMEM;
break;
}
}
ErrorCode = -ENOMEM;
if (DataTransferLength > 0)
{
DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
DataTransferLength, &DataTransferBufferDMA);
if (DataTransferBuffer == NULL)
break;
memset(DataTransferBuffer, 0, DataTransferLength);
}
else if (DataTransferLength < 0)
{
DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
-DataTransferLength, &DataTransferBufferDMA);
if (DataTransferBuffer == NULL)
break;
if (copy_from_user(DataTransferBuffer,
UserCommand.DataTransferBuffer,
-DataTransferLength)) {
ErrorCode = -EFAULT;
break;
}
}
if (CommandOpcode == DAC960_V1_DCDB)
{
spin_lock_irqsave(&Controller->queue_lock, flags);
while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
DAC960_WaitForCommand(Controller);
while (Controller->V1.DirectCommandActive[DCDB.Channel]
[DCDB.TargetID])
{
spin_unlock_irq(&Controller->queue_lock);
__wait_event(Controller->CommandWaitQueue,
!Controller->V1.DirectCommandActive
[DCDB.Channel][DCDB.TargetID]);
spin_lock_irq(&Controller->queue_lock);
}
Controller->V1.DirectCommandActive[DCDB.Channel]
[DCDB.TargetID] = true;
spin_unlock_irqrestore(&Controller->queue_lock, flags);
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
memcpy(&Command->V1.CommandMailbox, &UserCommand.CommandMailbox,
sizeof(DAC960_V1_CommandMailbox_T));
Command->V1.CommandMailbox.Type3.BusAddress = DCDB_IOBUFDMA;
DCDB.BusAddress = DataTransferBufferDMA;
memcpy(DCDB_IOBUF, &DCDB, sizeof(DAC960_V1_DCDB_T));
}
else
{
spin_lock_irqsave(&Controller->queue_lock, flags);
while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
DAC960_WaitForCommand(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
DAC960_V1_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
memcpy(&Command->V1.CommandMailbox, &UserCommand.CommandMailbox,
sizeof(DAC960_V1_CommandMailbox_T));
if (DataTransferBuffer != NULL)
Command->V1.CommandMailbox.Type3.BusAddress =
DataTransferBufferDMA;
}
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V1.CommandStatus;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_DeallocateCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
if (DataTransferLength > 0)
{
if (copy_to_user(UserCommand.DataTransferBuffer,
DataTransferBuffer, DataTransferLength)) {
ErrorCode = -EFAULT;
goto Failure1;
}
}
if (CommandOpcode == DAC960_V1_DCDB)
{
/*
I don't believe Target or Channel in the DCDB_IOBUF
should be any different from the contents of DCDB.
*/
Controller->V1.DirectCommandActive[DCDB.Channel]
[DCDB.TargetID] = false;
if (copy_to_user(UserCommand.DCDB, DCDB_IOBUF,
sizeof(DAC960_V1_DCDB_T))) {
ErrorCode = -EFAULT;
goto Failure1;
}
}
ErrorCode = CommandStatus;
Failure1:
if (DataTransferBuffer != NULL)
pci_free_consistent(Controller->PCIDevice, abs(DataTransferLength),
DataTransferBuffer, DataTransferBufferDMA);
if (DCDB_IOBUF != NULL)
pci_free_consistent(Controller->PCIDevice, sizeof(DAC960_V1_DCDB_T),
DCDB_IOBUF, DCDB_IOBUFDMA);
break;
}
case DAC960_IOCTL_V2_EXECUTE_COMMAND:
{
DAC960_V2_UserCommand_T __user *UserSpaceUserCommand =
(DAC960_V2_UserCommand_T __user *) Argument;
DAC960_V2_UserCommand_T UserCommand;
DAC960_Controller_T *Controller;
DAC960_Command_T *Command = NULL;
DAC960_V2_CommandMailbox_T *CommandMailbox;
DAC960_V2_CommandStatus_T CommandStatus;
unsigned long flags;
int ControllerNumber, DataTransferLength;
int DataTransferResidue, RequestSenseLength;
unsigned char *DataTransferBuffer = NULL;
dma_addr_t DataTransferBufferDMA;
unsigned char *RequestSenseBuffer = NULL;
dma_addr_t RequestSenseBufferDMA;
ErrorCode = -EINVAL;
if (UserSpaceUserCommand == NULL)
break;
if (copy_from_user(&UserCommand, UserSpaceUserCommand,
sizeof(DAC960_V2_UserCommand_T))) {
ErrorCode = -EFAULT;
break;
}
ErrorCode = -ENXIO;
ControllerNumber = UserCommand.ControllerNumber;
if (ControllerNumber < 0 ||
ControllerNumber > DAC960_ControllerCount - 1)
break;
Controller = DAC960_Controllers[ControllerNumber];
if (Controller == NULL)
break;
if (Controller->FirmwareType != DAC960_V2_Controller){
ErrorCode = -EINVAL;
break;
}
DataTransferLength = UserCommand.DataTransferLength;
ErrorCode = -ENOMEM;
if (DataTransferLength > 0)
{
DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
DataTransferLength, &DataTransferBufferDMA);
if (DataTransferBuffer == NULL)
break;
memset(DataTransferBuffer, 0, DataTransferLength);
}
else if (DataTransferLength < 0)
{
DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
-DataTransferLength, &DataTransferBufferDMA);
if (DataTransferBuffer == NULL)
break;
if (copy_from_user(DataTransferBuffer,
UserCommand.DataTransferBuffer,
-DataTransferLength)) {
ErrorCode = -EFAULT;
goto Failure2;
}
}
RequestSenseLength = UserCommand.RequestSenseLength;
if (RequestSenseLength > 0)
{
RequestSenseBuffer = pci_alloc_consistent(Controller->PCIDevice,
RequestSenseLength, &RequestSenseBufferDMA);
if (RequestSenseBuffer == NULL)
{
ErrorCode = -ENOMEM;
goto Failure2;
}
memset(RequestSenseBuffer, 0, RequestSenseLength);
}
spin_lock_irqsave(&Controller->queue_lock, flags);
while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
DAC960_WaitForCommand(Controller);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
DAC960_V2_ClearCommand(Command);
Command->CommandType = DAC960_ImmediateCommand;
CommandMailbox = &Command->V2.CommandMailbox;
memcpy(CommandMailbox, &UserCommand.CommandMailbox,
sizeof(DAC960_V2_CommandMailbox_T));
CommandMailbox->Common.CommandControlBits
.AdditionalScatterGatherListMemory = false;
CommandMailbox->Common.CommandControlBits
.NoAutoRequestSense = true;
CommandMailbox->Common.DataTransferSize = 0;
CommandMailbox->Common.DataTransferPageNumber = 0;
memset(&CommandMailbox->Common.DataTransferMemoryAddress, 0,
sizeof(DAC960_V2_DataTransferMemoryAddress_T));
if (DataTransferLength != 0)
{
if (DataTransferLength > 0)
{
CommandMailbox->Common.CommandControlBits
.DataTransferControllerToHost = true;
CommandMailbox->Common.DataTransferSize = DataTransferLength;
}
else
{
CommandMailbox->Common.CommandControlBits
.DataTransferControllerToHost = false;
CommandMailbox->Common.DataTransferSize = -DataTransferLength;
}
CommandMailbox->Common.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentDataPointer = DataTransferBufferDMA;
CommandMailbox->Common.DataTransferMemoryAddress
.ScatterGatherSegments[0]
.SegmentByteCount =
CommandMailbox->Common.DataTransferSize;
}
if (RequestSenseLength > 0)
{
CommandMailbox->Common.CommandControlBits
.NoAutoRequestSense = false;
CommandMailbox->Common.RequestSenseSize = RequestSenseLength;
CommandMailbox->Common.RequestSenseBusAddress =
RequestSenseBufferDMA;
}
DAC960_ExecuteCommand(Command);
CommandStatus = Command->V2.CommandStatus;
RequestSenseLength = Command->V2.RequestSenseLength;
DataTransferResidue = Command->V2.DataTransferResidue;
spin_lock_irqsave(&Controller->queue_lock, flags);
DAC960_DeallocateCommand(Command);
spin_unlock_irqrestore(&Controller->queue_lock, flags);
if (RequestSenseLength > UserCommand.RequestSenseLength)
RequestSenseLength = UserCommand.RequestSenseLength;
if (copy_to_user(&UserSpaceUserCommand->DataTransferLength,
&DataTransferResidue,
sizeof(DataTransferResidue))) {
ErrorCode = -EFAULT;
goto Failure2;
}
if (copy_to_user(&UserSpaceUserCommand->RequestSenseLength,
&RequestSenseLength, sizeof(RequestSenseLength))) {
ErrorCode = -EFAULT;
goto Failure2;
}
if (DataTransferLength > 0)
{
if (copy_to_user(UserCommand.DataTransferBuffer,
DataTransferBuffer, DataTransferLength)) {
ErrorCode = -EFAULT;
goto Failure2;
}
}
if (RequestSenseLength > 0)
{
if (copy_to_user(UserCommand.RequestSenseBuffer,
RequestSenseBuffer, RequestSenseLength)) {
ErrorCode = -EFAULT;
goto Failure2;
}
}
ErrorCode = CommandStatus;
Failure2:
pci_free_consistent(Controller->PCIDevice, abs(DataTransferLength),
DataTransferBuffer, DataTransferBufferDMA);
if (RequestSenseBuffer != NULL)
pci_free_consistent(Controller->PCIDevice, RequestSenseLength,
RequestSenseBuffer, RequestSenseBufferDMA);
break;
}
case DAC960_IOCTL_V2_GET_HEALTH_STATUS:
{
DAC960_V2_GetHealthStatus_T __user *UserSpaceGetHealthStatus =
(DAC960_V2_GetHealthStatus_T __user *) Argument;
DAC960_V2_GetHealthStatus_T GetHealthStatus;
DAC960_V2_HealthStatusBuffer_T HealthStatusBuffer;
DAC960_Controller_T *Controller;
int ControllerNumber;
if (UserSpaceGetHealthStatus == NULL) {
ErrorCode = -EINVAL;
break;
}
if (copy_from_user(&GetHealthStatus, UserSpaceGetHealthStatus,
sizeof(DAC960_V2_GetHealthStatus_T))) {
ErrorCode = -EFAULT;
break;
}
ErrorCode = -ENXIO;
ControllerNumber = GetHealthStatus.ControllerNumber;
if (ControllerNumber < 0 ||
ControllerNumber > DAC960_ControllerCount - 1)
break;
Controller = DAC960_Controllers[ControllerNumber];
if (Controller == NULL)
break;
if (Controller->FirmwareType != DAC960_V2_Controller) {
ErrorCode = -EINVAL;
break;
}
if (copy_from_user(&HealthStatusBuffer,
GetHealthStatus.HealthStatusBuffer,
sizeof(DAC960_V2_HealthStatusBuffer_T))) {
ErrorCode = -EFAULT;
break;
}
while (Controller->V2.HealthStatusBuffer->StatusChangeCounter
== HealthStatusBuffer.StatusChangeCounter &&
Controller->V2.HealthStatusBuffer->NextEventSequenceNumber
== HealthStatusBuffer.NextEventSequenceNumber)
{
interruptible_sleep_on_timeout(&Controller->HealthStatusWaitQueue,
DAC960_MonitoringTimerInterval);
if (signal_pending(current)) {
ErrorCode = -EINTR;
break;
}
}
if (copy_to_user(GetHealthStatus.HealthStatusBuffer,
Controller->V2.HealthStatusBuffer,
sizeof(DAC960_V2_HealthStatusBuffer_T)))
ErrorCode = -EFAULT;
else
ErrorCode = 0;
}
default:
ErrorCode = -ENOTTY;
}
unlock_kernel();
return ErrorCode;
}
static const struct file_operations DAC960_gam_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = DAC960_gam_ioctl
};
static struct miscdevice DAC960_gam_dev = {
DAC960_GAM_MINOR,
"dac960_gam",
&DAC960_gam_fops
};
static int DAC960_gam_init(void)
{
int ret;
ret = misc_register(&DAC960_gam_dev);
if (ret)
printk(KERN_ERR "DAC960_gam: can't misc_register on minor %d\n", DAC960_GAM_MINOR);
return ret;
}
static void DAC960_gam_cleanup(void)
{
misc_deregister(&DAC960_gam_dev);
}
#endif /* DAC960_GAM_MINOR */
static struct DAC960_privdata DAC960_GEM_privdata = {
.HardwareType = DAC960_GEM_Controller,
.FirmwareType = DAC960_V2_Controller,
.InterruptHandler = DAC960_GEM_InterruptHandler,
.MemoryWindowSize = DAC960_GEM_RegisterWindowSize,
};
static struct DAC960_privdata DAC960_BA_privdata = {
.HardwareType = DAC960_BA_Controller,
.FirmwareType = DAC960_V2_Controller,
.InterruptHandler = DAC960_BA_InterruptHandler,
.MemoryWindowSize = DAC960_BA_RegisterWindowSize,
};
static struct DAC960_privdata DAC960_LP_privdata = {
.HardwareType = DAC960_LP_Controller,
.FirmwareType = DAC960_LP_Controller,
.InterruptHandler = DAC960_LP_InterruptHandler,
.MemoryWindowSize = DAC960_LP_RegisterWindowSize,
};
static struct DAC960_privdata DAC960_LA_privdata = {
.HardwareType = DAC960_LA_Controller,
.FirmwareType = DAC960_V1_Controller,
.InterruptHandler = DAC960_LA_InterruptHandler,
.MemoryWindowSize = DAC960_LA_RegisterWindowSize,
};
static struct DAC960_privdata DAC960_PG_privdata = {
.HardwareType = DAC960_PG_Controller,
.FirmwareType = DAC960_V1_Controller,
.InterruptHandler = DAC960_PG_InterruptHandler,
.MemoryWindowSize = DAC960_PG_RegisterWindowSize,
};
static struct DAC960_privdata DAC960_PD_privdata = {
.HardwareType = DAC960_PD_Controller,
.FirmwareType = DAC960_V1_Controller,
.InterruptHandler = DAC960_PD_InterruptHandler,
.MemoryWindowSize = DAC960_PD_RegisterWindowSize,
};
static struct DAC960_privdata DAC960_P_privdata = {
.HardwareType = DAC960_P_Controller,
.FirmwareType = DAC960_V1_Controller,
.InterruptHandler = DAC960_P_InterruptHandler,
.MemoryWindowSize = DAC960_PD_RegisterWindowSize,
};
static struct pci_device_id DAC960_id_table[] = {
{
.vendor = PCI_VENDOR_ID_MYLEX,
.device = PCI_DEVICE_ID_MYLEX_DAC960_GEM,
.subvendor = PCI_VENDOR_ID_MYLEX,
.subdevice = PCI_ANY_ID,
.driver_data = (unsigned long) &DAC960_GEM_privdata,
},
{
.vendor = PCI_VENDOR_ID_MYLEX,
.device = PCI_DEVICE_ID_MYLEX_DAC960_BA,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.driver_data = (unsigned long) &DAC960_BA_privdata,
},
{
.vendor = PCI_VENDOR_ID_MYLEX,
.device = PCI_DEVICE_ID_MYLEX_DAC960_LP,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.driver_data = (unsigned long) &DAC960_LP_privdata,
},
{
.vendor = PCI_VENDOR_ID_DEC,
.device = PCI_DEVICE_ID_DEC_21285,
.subvendor = PCI_VENDOR_ID_MYLEX,
.subdevice = PCI_DEVICE_ID_MYLEX_DAC960_LA,
.driver_data = (unsigned long) &DAC960_LA_privdata,
},
{
.vendor = PCI_VENDOR_ID_MYLEX,
.device = PCI_DEVICE_ID_MYLEX_DAC960_PG,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.driver_data = (unsigned long) &DAC960_PG_privdata,
},
{
.vendor = PCI_VENDOR_ID_MYLEX,
.device = PCI_DEVICE_ID_MYLEX_DAC960_PD,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.driver_data = (unsigned long) &DAC960_PD_privdata,
},
{
.vendor = PCI_VENDOR_ID_MYLEX,
.device = PCI_DEVICE_ID_MYLEX_DAC960_P,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.driver_data = (unsigned long) &DAC960_P_privdata,
},
{0, },
};
MODULE_DEVICE_TABLE(pci, DAC960_id_table);
static struct pci_driver DAC960_pci_driver = {
.name = "DAC960",
.id_table = DAC960_id_table,
.probe = DAC960_Probe,
.remove = DAC960_Remove,
};
static int DAC960_init_module(void)
{
int ret;
ret = pci_register_driver(&DAC960_pci_driver);
#ifdef DAC960_GAM_MINOR
if (!ret)
DAC960_gam_init();
#endif
return ret;
}
static void DAC960_cleanup_module(void)
{
int i;
#ifdef DAC960_GAM_MINOR
DAC960_gam_cleanup();
#endif
for (i = 0; i < DAC960_ControllerCount; i++) {
DAC960_Controller_T *Controller = DAC960_Controllers[i];
if (Controller == NULL)
continue;
DAC960_FinalizeController(Controller);
}
if (DAC960_ProcDirectoryEntry != NULL) {
remove_proc_entry("rd/status", NULL);
remove_proc_entry("rd", NULL);
}
DAC960_ControllerCount = 0;
pci_unregister_driver(&DAC960_pci_driver);
}
module_init(DAC960_init_module);
module_exit(DAC960_cleanup_module);
MODULE_LICENSE("GPL");
| JonnyH/pandora-kernel | drivers/block/DAC960.c | C | gpl-2.0 | 265,713 |
<p><?php printf(__('Ultimate Member is not yet available in your language: <strong>%1$s</strong>.','ultimatemember'), $locale); ?></p>
<p><?php _e('If you want to contribute this translation to the plugin, please add it on our <a href="https://ultimatemember.com/forums/">community forum</a>.','ultimatemember'); ?></p> | frammawiliansyah/web | wp-content/plugins/ultimate-member/admin/templates/dashboard/language-contrib.php | PHP | gpl-2.0 | 320 |
// PR c++/84664
// { dg-do compile { target c++11 } }
void
foo ()
{
auto &b = 1; // { dg-error "cannot bind" }
[] { b > 0; }; // { dg-error ".b. is not captured" }
}
| Gurgel100/gcc | gcc/testsuite/g++.dg/cpp0x/lambda/lambda-ice28.C | C++ | gpl-2.0 | 171 |
/* At one time this triggered ICEs with location wrapper nodes,
apparently requiring error-recovery (hence the various syntax
errors in this file. */
// { dg-excess-errors "expected to be full of errors, but not an ICE" }
namespace std
{
inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { }
}
namespace __gnu_cxx __attribute__ ((__visibility__ ("default")))
{
template<typename _Tp>
class new_allocator
{
typedef _Tp value_type;
};
}
namespace std
{
template<typename _Tp>
using __allocator_base = __gnu_cxx::new_allocator<_Tp>;
}
namespace std __attribute__ ((__visibility__ ("default")))
{
{
};
template<typename _Tp>
class allocator : public __allocator_base<_Tp>
{
};
template<typename _Alloc>
struct allocator_traits : __allocator_traits_base
{
};
template<typename _Tp>
struct allocator_traits<allocator<_Tp>>
{
using allocator_type = allocator<_Tp>;
template<typename _Up>
using rebind_alloc = allocator<_Up>;
allocate(allocator_type& __a, size_type __n)
};
}
namespace __gnu_cxx __attribute__ ((__visibility__ ("default")))
{
template<typename _Alloc, typename = typename _Alloc::value_type>
struct __alloc_traits
: std::allocator_traits<_Alloc>
{
typedef std::allocator_traits<_Alloc> _Base_type;
template<typename _Tp>
struct rebind
{ typedef typename _Base_type::template rebind_alloc<_Tp> other; };
};
{
{
}
}
}
{
{
}
}
namespace std __attribute__ ((__visibility__ ("default")))
{
struct char_traits;
namespace __cxx11 {
template<typename _CharT, typename _Traits = char_traits<_CharT>,
typename _Alloc = allocator<_CharT> >
class basic_string;
}
}
namespace std __attribute__ ((__visibility__ ("default")))
{
namespace __cxx11 {
template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string
{
typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template
rebind<_CharT>::other _Char_alloc_type;
typedef __gnu_cxx::__alloc_traits<_Char_alloc_type> _Alloc_traits;
public:
{
{
}
}
operator=(const basic_string& __str)
{
{
{
{
const auto __len = __str.size();
auto __alloc = __str._M_get_allocator();
auto __ptr = _Alloc_traits::allocate(__alloc, __len + 1);
}
}
}
}
{
}
size() const noexcept
}
namespace filesystem
{
class path
{
typedef char value_type;
typedef std::basic_string<value_type> string_type;
{
}
string_type _M_pathname;
};
class directory_entry
{
void assign(const filesystem::path& __p) { _M_path = __p; }
filesystem::path _M_path;
| Gurgel100/gcc | gcc/testsuite/g++.dg/wrappers/cp-stdlib.C | C++ | gpl-2.0 | 2,740 |
/* { dg-do compile } */
/* { dg-additional-options "-fno-tree-ch -fno-tree-vrp" } */
int x0;
void
br (int yp, int oo)
{
int *qi = &yp;
if (oo == 0)
{
g8:
if (x0 != 0)
x0 = yp;
else if (oo != 0)
x0 = yp;
if (x0 == 0)
{
*qi = 0;
x0 = *qi;
}
if (x0 != 0)
{
++oo;
goto g8;
}
if (yp == oo)
yp += !!oo;
}
else
{
x0 = 1;
while (x0 < 2)
{
qi = &oo;
++oo;
x0 = 1;
}
}
goto g8;
}
| Gurgel100/gcc | gcc/testsuite/gcc.dg/torture/pr84830.c | C | gpl-2.0 | 473 |
/*
dpc7146.c - v4l2 driver for the dpc7146 demonstration board
Copyright (C) 2000-2003 Michael Hunold <[email protected]>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define DEBUG_VARIABLE debug
#include <media/saa7146_vv.h>
#include <linux/video_decoder.h> /* for saa7111a */
#define I2C_SAA7111A 0x24
/* All unused bytes are reserverd. */
#define SAA711X_CHIP_VERSION 0x00
#define SAA711X_ANALOG_INPUT_CONTROL_1 0x02
#define SAA711X_ANALOG_INPUT_CONTROL_2 0x03
#define SAA711X_ANALOG_INPUT_CONTROL_3 0x04
#define SAA711X_ANALOG_INPUT_CONTROL_4 0x05
#define SAA711X_HORIZONTAL_SYNC_START 0x06
#define SAA711X_HORIZONTAL_SYNC_STOP 0x07
#define SAA711X_SYNC_CONTROL 0x08
#define SAA711X_LUMINANCE_CONTROL 0x09
#define SAA711X_LUMINANCE_BRIGHTNESS 0x0A
#define SAA711X_LUMINANCE_CONTRAST 0x0B
#define SAA711X_CHROMA_SATURATION 0x0C
#define SAA711X_CHROMA_HUE_CONTROL 0x0D
#define SAA711X_CHROMA_CONTROL 0x0E
#define SAA711X_FORMAT_DELAY_CONTROL 0x10
#define SAA711X_OUTPUT_CONTROL_1 0x11
#define SAA711X_OUTPUT_CONTROL_2 0x12
#define SAA711X_OUTPUT_CONTROL_3 0x13
#define SAA711X_V_GATE_1_START 0x15
#define SAA711X_V_GATE_1_STOP 0x16
#define SAA711X_V_GATE_1_MSB 0x17
#define SAA711X_TEXT_SLICER_STATUS 0x1A
#define SAA711X_DECODED_BYTES_OF_TS_1 0x1B
#define SAA711X_DECODED_BYTES_OF_TS_2 0x1C
#define SAA711X_STATUS_BYTE 0x1F
#define DPC_BOARD_CAN_DO_VBI(dev) (dev->revision != 0)
static int debug = 0;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "debug verbosity");
static int dpc_num = 0;
#define DPC_INPUTS 2
static struct v4l2_input dpc_inputs[DPC_INPUTS] = {
{ 0, "Port A", V4L2_INPUT_TYPE_CAMERA, 2, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
{ 1, "Port B", V4L2_INPUT_TYPE_CAMERA, 2, 0, V4L2_STD_PAL_BG|V4L2_STD_NTSC_M, 0 },
};
#define DPC_AUDIOS 0
static struct saa7146_extension_ioctls ioctls[] = {
{ VIDIOC_G_INPUT, SAA7146_EXCLUSIVE },
{ VIDIOC_S_INPUT, SAA7146_EXCLUSIVE },
{ VIDIOC_ENUMINPUT, SAA7146_EXCLUSIVE },
{ VIDIOC_S_STD, SAA7146_AFTER },
{ 0, 0 }
};
struct dpc
{
struct video_device *video_dev;
struct video_device *vbi_dev;
struct i2c_adapter i2c_adapter;
struct i2c_client *saa7111a;
int cur_input; /* current input */
};
/* fixme: add vbi stuff here */
static int dpc_probe(struct saa7146_dev* dev)
{
struct dpc* dpc = NULL;
struct i2c_client *client;
dpc = kzalloc(sizeof(struct dpc), GFP_KERNEL);
if( NULL == dpc ) {
printk("dpc_v4l2.o: dpc_probe: not enough kernel memory.\n");
return -ENOMEM;
}
/* FIXME: enable i2c-port pins, video-port-pins
video port pins should be enabled here ?! */
saa7146_write(dev, MC1, (MASK_08 | MASK_24 | MASK_10 | MASK_26));
dpc->i2c_adapter = (struct i2c_adapter) {
.class = I2C_CLASS_TV_ANALOG,
.name = "dpc7146",
};
saa7146_i2c_adapter_prepare(dev, &dpc->i2c_adapter, SAA7146_I2C_BUS_BIT_RATE_480);
if(i2c_add_adapter(&dpc->i2c_adapter) < 0) {
DEB_S(("cannot register i2c-device. skipping.\n"));
kfree(dpc);
return -EFAULT;
}
/* loop through all i2c-devices on the bus and look who is there */
list_for_each_entry(client, &dpc->i2c_adapter.clients, list)
if( I2C_SAA7111A == client->addr )
dpc->saa7111a = client;
/* check if all devices are present */
if( 0 == dpc->saa7111a ) {
DEB_D(("dpc_v4l2.o: dpc_attach failed for this device.\n"));
i2c_del_adapter(&dpc->i2c_adapter);
kfree(dpc);
return -ENODEV;
}
/* all devices are present, probe was successful */
DEB_D(("dpc_v4l2.o: dpc_probe succeeded for this device.\n"));
/* we store the pointer in our private data field */
dev->ext_priv = dpc;
return 0;
}
/* bring hardware to a sane state. this has to be done, just in case someone
wants to capture from this device before it has been properly initialized.
the capture engine would badly fail, because no valid signal arrives on the
saa7146, thus leading to timeouts and stuff. */
static int dpc_init_done(struct saa7146_dev* dev)
{
struct dpc* dpc = (struct dpc*)dev->ext_priv;
DEB_D(("dpc_v4l2.o: dpc_init_done called.\n"));
/* initialize the helper ics to useful values */
i2c_smbus_write_byte_data(dpc->saa7111a, 0x00, 0x11);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x02, 0xc0);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x03, 0x30);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x04, 0x00);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x05, 0x00);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x06, 0xde);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x07, 0xad);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x08, 0xa8);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x09, 0x00);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x0a, 0x80);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x0b, 0x47);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x0c, 0x40);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x0d, 0x00);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x0e, 0x03);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x10, 0xd0);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x11, 0x1c);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x12, 0xc1);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x13, 0x30);
i2c_smbus_write_byte_data(dpc->saa7111a, 0x1f, 0x81);
return 0;
}
static struct saa7146_ext_vv vv_data;
/* this function only gets called when the probing was successful */
static int dpc_attach(struct saa7146_dev* dev, struct saa7146_pci_extension_data *info)
{
struct dpc* dpc = (struct dpc*)dev->ext_priv;
DEB_D(("dpc_v4l2.o: dpc_attach called.\n"));
/* checking for i2c-devices can be omitted here, because we
already did this in "dpc_vl42_probe" */
saa7146_vv_init(dev,&vv_data);
if( 0 != saa7146_register_device(&dpc->video_dev, dev, "dpc", VFL_TYPE_GRABBER)) {
ERR(("cannot register capture v4l2 device. skipping.\n"));
return -1;
}
/* initialization stuff (vbi) (only for revision > 0 and for extensions which want it)*/
if( 0 != DPC_BOARD_CAN_DO_VBI(dev)) {
if( 0 != saa7146_register_device(&dpc->vbi_dev, dev, "dpc", VFL_TYPE_VBI)) {
ERR(("cannot register vbi v4l2 device. skipping.\n"));
}
}
i2c_use_client(dpc->saa7111a);
printk("dpc: found 'dpc7146 demonstration board'-%d.\n",dpc_num);
dpc_num++;
/* the rest */
dpc->cur_input = 0;
dpc_init_done(dev);
return 0;
}
static int dpc_detach(struct saa7146_dev* dev)
{
struct dpc* dpc = (struct dpc*)dev->ext_priv;
DEB_EE(("dev:%p\n",dev));
i2c_release_client(dpc->saa7111a);
saa7146_unregister_device(&dpc->video_dev,dev);
if( 0 != DPC_BOARD_CAN_DO_VBI(dev)) {
saa7146_unregister_device(&dpc->vbi_dev,dev);
}
saa7146_vv_release(dev);
dpc_num--;
i2c_del_adapter(&dpc->i2c_adapter);
kfree(dpc);
return 0;
}
#ifdef axa
int dpc_vbi_bypass(struct saa7146_dev* dev)
{
struct dpc* dpc = (struct dpc*)dev->ext_priv;
int i = 1;
/* switch bypass in saa7111a */
if ( 0 != dpc->saa7111a->driver->command(dpc->saa7111a,SAA711X_VBI_BYPASS, &i)) {
printk("dpc_v4l2.o: VBI_BYPASS: could not address saa7111a.\n");
return -1;
}
return 0;
}
#endif
static int dpc_ioctl(struct saa7146_fh *fh, unsigned int cmd, void *arg)
{
struct saa7146_dev *dev = fh->dev;
struct dpc* dpc = (struct dpc*)dev->ext_priv;
/*
struct saa7146_vv *vv = dev->vv_data;
*/
switch(cmd)
{
case VIDIOC_ENUMINPUT:
{
struct v4l2_input *i = arg;
DEB_EE(("VIDIOC_ENUMINPUT %d.\n",i->index));
if( i->index < 0 || i->index >= DPC_INPUTS) {
return -EINVAL;
}
memcpy(i, &dpc_inputs[i->index], sizeof(struct v4l2_input));
DEB_D(("dpc_v4l2.o: v4l2_ioctl: VIDIOC_ENUMINPUT %d.\n",i->index));
return 0;
}
case VIDIOC_G_INPUT:
{
int *input = (int *)arg;
*input = dpc->cur_input;
DEB_D(("dpc_v4l2.o: VIDIOC_G_INPUT: %d\n",*input));
return 0;
}
case VIDIOC_S_INPUT:
{
int input = *(int *)arg;
if (input < 0 || input >= DPC_INPUTS) {
return -EINVAL;
}
dpc->cur_input = input;
/* fixme: switch input here, switch audio, too! */
// saa7146_set_hps_source_and_sync(dev, input_port_selection[input].hps_source, input_port_selection[input].hps_sync);
printk("dpc_v4l2.o: VIDIOC_S_INPUT: fixme switch input.\n");
return 0;
}
default:
/*
DEB_D(("dpc_v4l2.o: v4l2_ioctl does not handle this ioctl.\n"));
*/
return -ENOIOCTLCMD;
}
return 0;
}
static int std_callback(struct saa7146_dev* dev, struct saa7146_standard *std)
{
return 0;
}
static struct saa7146_standard standard[] = {
{
.name = "PAL", .id = V4L2_STD_PAL,
.v_offset = 0x17, .v_field = 288,
.h_offset = 0x14, .h_pixels = 680,
.v_max_out = 576, .h_max_out = 768,
}, {
.name = "NTSC", .id = V4L2_STD_NTSC,
.v_offset = 0x16, .v_field = 240,
.h_offset = 0x06, .h_pixels = 708,
.v_max_out = 480, .h_max_out = 640,
}, {
.name = "SECAM", .id = V4L2_STD_SECAM,
.v_offset = 0x14, .v_field = 288,
.h_offset = 0x14, .h_pixels = 720,
.v_max_out = 576, .h_max_out = 768,
}
};
static struct saa7146_extension extension;
static struct saa7146_pci_extension_data dpc = {
.ext_priv = "Multimedia eXtension Board",
.ext = &extension,
};
static struct pci_device_id pci_tbl[] = {
{
.vendor = PCI_VENDOR_ID_PHILIPS,
.device = PCI_DEVICE_ID_PHILIPS_SAA7146,
.subvendor = 0x0000,
.subdevice = 0x0000,
.driver_data = (unsigned long)&dpc,
}, {
.vendor = 0,
}
};
MODULE_DEVICE_TABLE(pci, pci_tbl);
static struct saa7146_ext_vv vv_data = {
.inputs = DPC_INPUTS,
.capabilities = V4L2_CAP_VBI_CAPTURE,
.stds = &standard[0],
.num_stds = sizeof(standard)/sizeof(struct saa7146_standard),
.std_callback = &std_callback,
.ioctls = &ioctls[0],
.ioctl = dpc_ioctl,
};
static struct saa7146_extension extension = {
.name = "dpc7146 demonstration board",
.flags = SAA7146_USE_I2C_IRQ,
.pci_tbl = &pci_tbl[0],
.module = THIS_MODULE,
.probe = dpc_probe,
.attach = dpc_attach,
.detach = dpc_detach,
.irq_mask = 0,
.irq_func = NULL,
};
static int __init dpc_init_module(void)
{
if( 0 != saa7146_register_extension(&extension)) {
DEB_S(("failed to register extension.\n"));
return -ENODEV;
}
return 0;
}
static void __exit dpc_cleanup_module(void)
{
saa7146_unregister_extension(&extension);
}
module_init(dpc_init_module);
module_exit(dpc_cleanup_module);
MODULE_DESCRIPTION("video4linux-2 driver for the 'dpc7146 demonstration board'");
MODULE_AUTHOR("Michael Hunold <[email protected]>");
MODULE_LICENSE("GPL");
| janrinze/loox7xxport.loox2624 | drivers/media/video/dpc7146.c | C | gpl-2.0 | 11,053 |
/* { dg-require-effective-target vect_condition } */
/* { dg-additional-options "-fdump-tree-vect-details" } */
#include "tree-vect.h"
#define N 128
__attribute__((noinline, noclone)) void
foo (int *a, int stride)
{
int i;
for (i = 0; i < N/stride; i++, a += stride)
{
a[0] = a[0] ? 1 : 5;
a[1] = a[1] ? 2 : 6;
a[2] = a[2] ? 3 : 7;
a[3] = a[3] ? 4 : 8;
}
}
int a[N];
int main ()
{
int i;
check_vect ();
for (i = 0; i < N; i++)
{
a[i] = i;
asm volatile ("" ::: "memory");
}
foo (a, 4);
for (i = 1; i < N; i++)
if (a[i] != i%4 + 1)
abort ();
if (a[0] != 5)
abort ();
return 0;
}
/* { dg-final { scan-tree-dump {(no need for alias check [^\n]* when VF is 1|no alias between [^\n]* when [^\n]* is outside \(-16, 16\))} "vect" { target vect_element_align } } } */
/* { dg-final { scan-tree-dump-times "loop vectorized" 1 "vect" { target vect_element_align } } } */
| Gurgel100/gcc | gcc/testsuite/gcc.dg/vect/bb-slp-cond-1.c | C | gpl-2.0 | 952 |
//
// (c) 2000 Sun Microsystems, Inc.
// ALL RIGHTS RESERVED
//
// License Grant-
//
//
// Permission to use, copy, modify, and distribute this Software and its
// documentation for NON-COMMERCIAL or COMMERCIAL purposes and without fee is
// hereby granted.
//
// This Software is provided "AS IS". All express warranties, including any
// implied warranty of merchantability, satisfactory quality, fitness for a
// particular purpose, or non-infringement, are disclaimed, except to the extent
// that such disclaimers are held to be legally invalid.
//
// You acknowledge that Software is not designed, licensed or intended for use in
// the design, construction, operation or maintenance of any nuclear facility
// ("High Risk Activities"). Sun disclaims any express or implied warranty of
// fitness for such uses.
//
// Please refer to the file http://www.sun.com/policies/trademarks/ for further
// important trademark information and to
// http://java.sun.com/nav/business/index.html for further important licensing
// information for the Java Technology.
//
package jake2.util;
import java.util.Enumeration;
import java.util.Vector;
/**
* PrintfFormat allows the formatting of an array of
* objects embedded within a string. Primitive types
* must be passed using wrapper types. The formatting
* is controlled by a control string.
*<p>
* A control string is a Java string that contains a
* control specification. The control specification
* starts at the first percent sign (%) in the string,
* provided that this percent sign
*<ol>
*<li>is not escaped protected by a matching % or is
* not an escape % character,
*<li>is not at the end of the format string, and
*<li>precedes a sequence of characters that parses as
* a valid control specification.
*</ol>
*</p><p>
* A control specification usually takes the form:
*<pre> % ['-+ #0]* [0..9]* { . [0..9]* }+
* { [hlL] }+ [idfgGoxXeEcs]
*</pre>
* There are variants of this basic form that are
* discussed below.</p>
*<p>
* The format is composed of zero or more directives
* defined as follows:
*<ul>
*<li>ordinary characters, which are simply copied to
* the output stream;
*<li>escape sequences, which represent non-graphic
* characters; and
*<li>conversion specifications, each of which
* results in the fetching of zero or more arguments.
*</ul></p>
*<p>
* The results are undefined if there are insufficient
* arguments for the format. Usually an unchecked
* exception will be thrown. If the format is
* exhausted while arguments remain, the excess
* arguments are evaluated but are otherwise ignored.
* In format strings containing the % form of
* conversion specifications, each argument in the
* argument list is used exactly once.</p>
* <p>
* Conversions can be applied to the <code>n</code>th
* argument after the format in the argument list,
* rather than to the next unused argument. In this
* case, the conversion characer % is replaced by the
* sequence %<code>n</code>$, where <code>n</code> is
* a decimal integer giving the position of the
* argument in the argument list.</p>
* <p>
* In format strings containing the %<code>n</code>$
* form of conversion specifications, each argument
* in the argument list is used exactly once.</p>
*
*<h4>Escape Sequences</h4>
*<p>
* The following table lists escape sequences and
* associated actions on display devices capable of
* the action.
*<table>
*<tr><th align=left>Sequence</th>
* <th align=left>Name</th>
* <th align=left>Description</th></tr>
*<tr><td>\\</td><td>backlash</td><td>None.
*</td></tr>
*<tr><td>\a</td><td>alert</td><td>Attempts to alert
* the user through audible or visible
* notification.
*</td></tr>
*<tr><td>\b</td><td>backspace</td><td>Moves the
* printing position to one column before
* the current position, unless the
* current position is the start of a line.
*</td></tr>
*<tr><td>\f</td><td>form-feed</td><td>Moves the
* printing position to the initial
* printing position of the next logical
* page.
*</td></tr>
*<tr><td>\n</td><td>newline</td><td>Moves the
* printing position to the start of the
* next line.
*</td></tr>
*<tr><td>\r</td><td>carriage-return</td><td>Moves
* the printing position to the start of
* the current line.
*</td></tr>
*<tr><td>\t</td><td>tab</td><td>Moves the printing
* position to the next implementation-
* defined horizontal tab position.
*</td></tr>
*<tr><td>\v</td><td>vertical-tab</td><td>Moves the
* printing position to the start of the
* next implementation-defined vertical
* tab position.
*</td></tr>
*</table></p>
*<h4>Conversion Specifications</h4>
*<p>
* Each conversion specification is introduced by
* the percent sign character (%). After the character
* %, the following appear in sequence:</p>
*<p>
* Zero or more flags (in any order), which modify the
* meaning of the conversion specification.</p>
*<p>
* An optional minimum field width. If the converted
* value has fewer characters than the field width, it
* will be padded with spaces by default on the left;
* t will be padded on the right, if the left-
* adjustment flag (-), described below, is given to
* the field width. The field width takes the form
* of a decimal integer. If the conversion character
* is s, the field width is the the minimum number of
* characters to be printed.</p>
*<p>
* An optional precision that gives the minumum number
* of digits to appear for the d, i, o, x or X
* conversions (the field is padded with leading
* zeros); the number of digits to appear after the
* radix character for the e, E, and f conversions,
* the maximum number of significant digits for the g
* and G conversions; or the maximum number of
* characters to be written from a string is s and S
* conversions. The precision takes the form of an
* optional decimal digit string, where a null digit
* string is treated as 0. If a precision appears
* with a c conversion character the precision is
* ignored.
* </p>
*<p>
* An optional h specifies that a following d, i, o,
* x, or X conversion character applies to a type
* short argument (the argument will be promoted
* according to the integral promotions and its value
* converted to type short before printing).</p>
*<p>
* An optional l (ell) specifies that a following
* d, i, o, x, or X conversion character applies to a
* type long argument.</p>
*<p>
* A field width or precision may be indicated by an
* asterisk (*) instead of a digit string. In this
* case, an integer argument supplised the field width
* precision. The argument that is actually converted
* is not fetched until the conversion letter is seen,
* so the the arguments specifying field width or
* precision must appear before the argument (if any)
* to be converted. If the precision argument is
* negative, it will be changed to zero. A negative
* field width argument is taken as a - flag, followed
* by a positive field width.</p>
* <p>
* In format strings containing the %<code>n</code>$
* form of a conversion specification, a field width
* or precision may be indicated by the sequence
* *<code>m</code>$, where m is a decimal integer
* giving the position in the argument list (after the
* format argument) of an integer argument containing
* the field width or precision.</p>
* <p>
* The format can contain either numbered argument
* specifications (that is, %<code>n</code>$ and
* *<code>m</code>$), or unnumbered argument
* specifications (that is % and *), but normally not
* both. The only exception to this is that %% can
* be mixed with the %<code>n</code>$ form. The
* results of mixing numbered and unnumbered argument
* specifications in a format string are undefined.</p>
*
*<h4>Flag Characters</h4>
*<p>
* The flags and their meanings are:</p>
*<dl>
* <dt>'<dd> integer portion of the result of a
* decimal conversion (%i, %d, %f, %g, or %G) will
* be formatted with thousands' grouping
* characters. For other conversions the flag
* is ignored. The non-monetary grouping
* character is used.
* <dt>-<dd> result of the conversion is left-justified
* within the field. (It will be right-justified
* if this flag is not specified).</td></tr>
* <dt>+<dd> result of a signed conversion always
* begins with a sign (+ or -). (It will begin
* with a sign only when a negative value is
* converted if this flag is not specified.)
* <dt><space><dd> If the first character of a
* signed conversion is not a sign, a space
* character will be placed before the result.
* This means that if the space character and +
* flags both appear, the space flag will be
* ignored.
* <dt>#<dd> value is to be converted to an alternative
* form. For c, d, i, and s conversions, the flag
* has no effect. For o conversion, it increases
* the precision to force the first digit of the
* result to be a zero. For x or X conversion, a
* non-zero result has 0x or 0X prefixed to it,
* respectively. For e, E, f, g, and G
* conversions, the result always contains a radix
* character, even if no digits follow the radix
* character (normally, a decimal point appears in
* the result of these conversions only if a digit
* follows it). For g and G conversions, trailing
* zeros will not be removed from the result as
* they normally are.
* <dt>0<dd> d, i, o, x, X, e, E, f, g, and G
* conversions, leading zeros (following any
* indication of sign or base) are used to pad to
* the field width; no space padding is
* performed. If the 0 and - flags both appear,
* the 0 flag is ignored. For d, i, o, x, and X
* conversions, if a precision is specified, the
* 0 flag will be ignored. For c conversions,
* the flag is ignored.
*</dl>
*
*<h4>Conversion Characters</h4>
*<p>
* Each conversion character results in fetching zero
* or more arguments. The results are undefined if
* there are insufficient arguments for the format.
* Usually, an unchecked exception will be thrown.
* If the format is exhausted while arguments remain,
* the excess arguments are ignored.</p>
*
*<p>
* The conversion characters and their meanings are:
*</p>
*<dl>
* <dt>d,i<dd>The int argument is converted to a
* signed decimal in the style [-]dddd. The
* precision specifies the minimum number of
* digits to appear; if the value being
* converted can be represented in fewer
* digits, it will be expanded with leading
* zeros. The default precision is 1. The
* result of converting 0 with an explicit
* precision of 0 is no characters.
* <dt>o<dd> The int argument is converted to unsigned
* octal format in the style ddddd. The
* precision specifies the minimum number of
* digits to appear; if the value being
* converted can be represented in fewer
* digits, it will be expanded with leading
* zeros. The default precision is 1. The
* result of converting 0 with an explicit
* precision of 0 is no characters.
* <dt>x<dd> The int argument is converted to unsigned
* hexadecimal format in the style dddd; the
* letters abcdef are used. The precision
* specifies the minimum numberof digits to
* appear; if the value being converted can be
* represented in fewer digits, it will be
* expanded with leading zeros. The default
* precision is 1. The result of converting 0
* with an explicit precision of 0 is no
* characters.
* <dt>X<dd> Behaves the same as the x conversion
* character except that letters ABCDEF are
* used instead of abcdef.
* <dt>f<dd> The floating point number argument is
* written in decimal notation in the style
* [-]ddd.ddd, where the number of digits after
* the radix character (shown here as a decimal
* point) is equal to the precision
* specification. A Locale is used to determine
* the radix character to use in this format.
* If the precision is omitted from the
* argument, six digits are written after the
* radix character; if the precision is
* explicitly 0 and the # flag is not specified,
* no radix character appears. If a radix
* character appears, at least 1 digit appears
* before it. The value is rounded to the
* appropriate number of digits.
* <dt>e,E<dd>The floating point number argument is
* written in the style [-]d.ddde{+-}dd
* (the symbols {+-} indicate either a plus or
* minus sign), where there is one digit before
* the radix character (shown here as a decimal
* point) and the number of digits after it is
* equal to the precision. A Locale is used to
* determine the radix character to use in this
* format. When the precision is missing, six
* digits are written after the radix character;
* if the precision is 0 and the # flag is not
* specified, no radix character appears. The
* E conversion will produce a number with E
* instead of e introducing the exponent. The
* exponent always contains at least two digits.
* However, if the value to be written requires
* an exponent greater than two digits,
* additional exponent digits are written as
* necessary. The value is rounded to the
* appropriate number of digits.
* <dt>g,G<dd>The floating point number argument is
* written in style f or e (or in sytle E in the
* case of a G conversion character), with the
* precision specifying the number of
* significant digits. If the precision is
* zero, it is taken as one. The style used
* depends on the value converted: style e
* (or E) will be used only if the exponent
* resulting from the conversion is less than
* -4 or greater than or equal to the precision.
* Trailing zeros are removed from the result.
* A radix character appears only if it is
* followed by a digit.
* <dt>c,C<dd>The integer argument is converted to a
* char and the result is written.
*
* <dt>s,S<dd>The argument is taken to be a string and
* bytes from the string are written until the
* end of the string or the number of bytes
* indicated by the precision specification of
* the argument is reached. If the precision
* is omitted from the argument, it is taken to
* be infinite, so all characters up to the end
* of the string are written.
* <dt>%<dd>Write a % character; no argument is
* converted.
*</dl>
*<p>
* If a conversion specification does not match one of
* the above forms, an IllegalArgumentException is
* thrown and the instance of PrintfFormat is not
* created.</p>
*<p>
* If a floating point value is the internal
* representation for infinity, the output is
* [+]Infinity, where Infinity is either Infinity or
* Inf, depending on the desired output string length.
* Printing of the sign follows the rules described
* above.</p>
*<p>
* If a floating point value is the internal
* representation for "not-a-number," the output is
* [+]NaN. Printing of the sign follows the rules
* described above.</p>
*<p>
* In no case does a non-existent or small field width
* cause truncation of a field; if the result of a
* conversion is wider than the field width, the field
* is simply expanded to contain the conversion result.
*</p>
*<p>
* The behavior is like printf. One exception is that
* the minimum number of exponent digits is 3 instead
* of 2 for e and E formats when the optional L is used
* before the e, E, g, or G conversion character. The
* optional L does not imply conversion to a long long
* double. </p>
* <p>
* The biggest divergence from the C printf
* specification is in the use of 16 bit characters.
* This allows the handling of characters beyond the
* small ASCII character set and allows the utility to
* interoperate correctly with the rest of the Java
* runtime environment.</p>
*<p>
* Omissions from the C printf specification are
* numerous. All the known omissions are present
* because Java never uses bytes to represent
* characters and does not have pointers:</p>
*<ul>
* <li>%c is the same as %C.
* <li>%s is the same as %S.
* <li>u, p, and n conversion characters.
* <li>%ws format.
* <li>h modifier applied to an n conversion character.
* <li>l (ell) modifier applied to the c, n, or s
* conversion characters.
* <li>ll (ell ell) modifier to d, i, o, u, x, or X
* conversion characters.
* <li>ll (ell ell) modifier to an n conversion
* character.
* <li>c, C, d,i,o,u,x, and X conversion characters
* apply to Byte, Character, Short, Integer, Long
* types.
* <li>f, e, E, g, and G conversion characters apply
* to Float and Double types.
* <li>s and S conversion characters apply to String
* types.
* <li>All other reference types can be formatted
* using the s or S conversion characters only.
*</ul>
* <p>
* Most of this specification is quoted from the Unix
* man page for the sprintf utility.</p>
*
* @author Allan Jacobs
* @version 1
* Release 1: Initial release.
* Release 2: Asterisk field widths and precisions
* %n$ and *m$
* Bug fixes
* g format fix (2 digits in e form corrupt)
* rounding in f format implemented
* round up when digit not printed is 5
* formatting of -0.0f
* round up/down when last digits are 50000...
*/
public class PrintfFormat {
/**
* Constructs an array of control specifications
* possibly preceded, separated, or followed by
* ordinary strings. Control strings begin with
* unpaired percent signs. A pair of successive
* percent signs designates a single percent sign in
* the format.
* @param fmtArg Control string.
* @exception IllegalArgumentException if the control
* string is null, zero length, or otherwise
* malformed.
*/
// TODO(jgw)
// public PrintfFormat(String fmtArg) throws IllegalArgumentException {
// this(Locale.getDefault(), fmtArg);
// }
/**
* Constructs an array of control specifications
* possibly preceded, separated, or followed by
* ordinary strings. Control strings begin with
* unpaired percent signs. A pair of successive
* percent signs designates a single percent sign in
* the format.
* @param fmtArg Control string.
* @exception IllegalArgumentException if the control
* string is null, zero length, or otherwise
* malformed.
*/
public PrintfFormat(/* TODO(jgw) Locale locale,*/ String fmtArg) throws IllegalArgumentException {
// TODO(jgw) dfs = new DecimalFormatSymbols(locale);
int ePos = 0;
ConversionSpecification sFmt = null;
String unCS = this.nonControl(fmtArg, 0);
if (unCS != null) {
sFmt = new ConversionSpecification();
sFmt.setLiteral(unCS);
vFmt.addElement(sFmt);
}
while (cPos != -1 && cPos < fmtArg.length()) {
for (ePos = cPos + 1; ePos < fmtArg.length(); ePos++) {
char c = 0;
c = fmtArg.charAt(ePos);
if (c == 'i')
break;
if (c == 'd')
break;
if (c == 'f')
break;
if (c == 'g')
break;
if (c == 'G')
break;
if (c == 'o')
break;
if (c == 'x')
break;
if (c == 'X')
break;
if (c == 'e')
break;
if (c == 'E')
break;
if (c == 'c')
break;
if (c == 's')
break;
if (c == '%')
break;
}
ePos = Math.min(ePos + 1, fmtArg.length());
sFmt = new ConversionSpecification(fmtArg.substring(cPos, ePos));
vFmt.addElement(sFmt);
unCS = this.nonControl(fmtArg, ePos);
if (unCS != null) {
sFmt = new ConversionSpecification();
sFmt.setLiteral(unCS);
vFmt.addElement(sFmt);
}
}
}
/**
* Return a substring starting at
* <code>start</code> and ending at either the end
* of the String <code>s</code>, the next unpaired
* percent sign, or at the end of the String if the
* last character is a percent sign.
* @param s Control string.
* @param start Position in the string
* <code>s</code> to begin looking for the start
* of a control string.
* @return the substring from the start position
* to the beginning of the control string.
*/
private String nonControl(String s, int start) {
String ret = "";
cPos = s.indexOf("%", start);
if (cPos == -1)
cPos = s.length();
return s.substring(start, cPos);
}
/**
* Format an array of objects. Byte, Short,
* Integer, Long, Float, Double, and Character
* arguments are treated as wrappers for primitive
* types.
* @param o The array of objects to format.
* @return The formatted String.
*/
public String sprintf(Object[] o) {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
int i = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
else {
if (cs.isPositionalSpecification()) {
i = cs.getArgumentPosition() - 1;
if (cs.isPositionalFieldWidth()) {
int ifw = cs.getArgumentPositionForFieldWidth() - 1;
cs.setFieldWidthWithArg(((Integer) o[ifw]).intValue());
}
if (cs.isPositionalPrecision()) {
int ipr = cs.getArgumentPositionForPrecision() - 1;
cs.setPrecisionWithArg(((Integer) o[ipr]).intValue());
}
} else {
if (cs.isVariableFieldWidth()) {
cs.setFieldWidthWithArg(((Integer) o[i]).intValue());
i++;
}
if (cs.isVariablePrecision()) {
cs.setPrecisionWithArg(((Integer) o[i]).intValue());
i++;
}
}
if (o[i] instanceof Byte)
sb.append(cs.internalsprintf(((Byte) o[i]).byteValue()));
else if (o[i] instanceof Short)
sb.append(cs.internalsprintf(((Short) o[i]).shortValue()));
else if (o[i] instanceof Integer)
sb.append(cs.internalsprintf(((Integer) o[i]).intValue()));
else if (o[i] instanceof Long)
sb.append(cs.internalsprintf(((Long) o[i]).longValue()));
else if (o[i] instanceof Float)
sb.append(cs.internalsprintf(((Float) o[i]).floatValue()));
else if (o[i] instanceof Double)
sb.append(cs.internalsprintf(((Double) o[i]).doubleValue()));
else if (o[i] instanceof Character)
sb.append(cs.internalsprintf(((Character) o[i]).charValue()));
else if (o[i] instanceof String)
sb.append(cs.internalsprintf((String) o[i]));
else
sb.append(cs.internalsprintf(o[i]));
if (!cs.isPositionalSpecification())
i++;
}
}
return sb.toString();
}
/**
* Format nothing. Just use the control string.
* @return the formatted String.
*/
public String sprintf() {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
}
return sb.toString();
}
/**
* Format an int.
* @param x The int to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, G, s,
* or S.
*/
public String sprintf(int x) throws IllegalArgumentException {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
else
sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format an long.
* @param x The long to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, G, s,
* or S.
*/
public String sprintf(long x) throws IllegalArgumentException {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
else
sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format a double.
* @param x The double to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is c, C, s, S,
* d, d, x, X, or o.
*/
public String sprintf(double x) throws IllegalArgumentException {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
else
sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format a String.
* @param x The String to format.
* @return The formatted String.
* @exception IllegalArgumentException if the
* conversion character is neither s nor S.
*/
public String sprintf(String x) throws IllegalArgumentException {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
else
sb.append(cs.internalsprintf(x));
}
return sb.toString();
}
/**
* Format an Object. Convert wrapper types to
* their primitive equivalents and call the
* appropriate internal formatting method. Convert
* Strings using an internal formatting method for
* Strings. Otherwise use the default formatter
* (use toString).
* @param x the Object to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is inappropriate for
* formatting an unwrapped value.
*/
public String sprintf(Object x) throws IllegalArgumentException {
Enumeration e = vFmt.elements();
ConversionSpecification cs = null;
char c = 0;
StringBuffer sb = new StringBuffer();
while (e.hasMoreElements()) {
cs = (ConversionSpecification) e.nextElement();
c = cs.getConversionCharacter();
if (c == '\0')
sb.append(cs.getLiteral());
else if (c == '%')
sb.append("%");
else {
if (x instanceof Byte)
sb.append(cs.internalsprintf(((Byte) x).byteValue()));
else if (x instanceof Short)
sb.append(cs.internalsprintf(((Short) x).shortValue()));
else if (x instanceof Integer)
sb.append(cs.internalsprintf(((Integer) x).intValue()));
else if (x instanceof Long)
sb.append(cs.internalsprintf(((Long) x).longValue()));
else if (x instanceof Float)
sb.append(cs.internalsprintf(((Float) x).floatValue()));
else if (x instanceof Double)
sb.append(cs.internalsprintf(((Double) x).doubleValue()));
else if (x instanceof Character)
sb.append(cs.internalsprintf(((Character) x).charValue()));
else if (x instanceof String)
sb.append(cs.internalsprintf((String) x));
else
sb.append(cs.internalsprintf(x));
}
}
return sb.toString();
}
/**
*<p>
* ConversionSpecification allows the formatting of
* a single primitive or object embedded within a
* string. The formatting is controlled by a
* format string. Only one Java primitive or
* object can be formatted at a time.
*<p>
* A format string is a Java string that contains
* a control string. The control string starts at
* the first percent sign (%) in the string,
* provided that this percent sign
*<ol>
*<li>is not escaped protected by a matching % or
* is not an escape % character,
*<li>is not at the end of the format string, and
*<li>precedes a sequence of characters that parses
* as a valid control string.
*</ol>
*<p>
* A control string takes the form:
*<pre> % ['-+ #0]* [0..9]* { . [0..9]* }+
* { [hlL] }+ [idfgGoxXeEcs]
*</pre>
*<p>
* The behavior is like printf. One (hopefully the
* only) exception is that the minimum number of
* exponent digits is 3 instead of 2 for e and E
* formats when the optional L is used before the
* e, E, g, or G conversion character. The
* optional L does not imply conversion to a long
* long double.
*/
private class ConversionSpecification {
/**
* Constructor. Used to prepare an instance
* to hold a literal, not a control string.
*/
ConversionSpecification() {
}
/**
* Constructor for a conversion specification.
* The argument must begin with a % and end
* with the conversion character for the
* conversion specification.
* @param fmtArg String specifying the
* conversion specification.
* @exception IllegalArgumentException if the
* input string is null, zero length, or
* otherwise malformed.
*/
ConversionSpecification(String fmtArg) throws IllegalArgumentException {
if (fmtArg == null)
throw new NullPointerException();
if (fmtArg.length() == 0)
throw new IllegalArgumentException("Control strings must have positive" + " lengths.");
if (fmtArg.charAt(0) == '%') {
fmt = fmtArg;
pos = 1;
setArgPosition();
setFlagCharacters();
setFieldWidth();
setPrecision();
setOptionalHL();
if (setConversionCharacter()) {
if (pos == fmtArg.length()) {
if (leadingZeros && leftJustify)
leadingZeros = false;
if (precisionSet && leadingZeros) {
if (conversionCharacter == 'd'
|| conversionCharacter == 'i'
|| conversionCharacter == 'o'
|| conversionCharacter == 'x') {
leadingZeros = false;
}
}
} else
throw new IllegalArgumentException("Malformed conversion specification=" + fmtArg);
} else
throw new IllegalArgumentException("Malformed conversion specification=" + fmtArg);
} else
throw new IllegalArgumentException("Control strings must begin with %.");
}
/**
* Set the String for this instance.
* @param s the String to store.
*/
void setLiteral(String s) {
fmt = s;
}
/**
* Get the String for this instance. Translate
* any escape sequences.
*
* @return s the stored String.
*/
String getLiteral() {
StringBuffer sb = new StringBuffer();
int i = 0;
while (i < fmt.length()) {
if (fmt.charAt(i) == '\\') {
i++;
if (i < fmt.length()) {
char c = fmt.charAt(i);
switch (c) {
case 'a' :
sb.append((char) 0x07);
break;
case 'b' :
sb.append('\b');
break;
case 'f' :
sb.append('\f');
break;
case 'n' :
sb.append('\n');// TODO(jgw): sb.append(System.getProperty("line.separator"));
break;
case 'r' :
sb.append('\r');
break;
case 't' :
sb.append('\t');
break;
case 'v' :
sb.append((char) 0x0b);
break;
case '\\' :
sb.append('\\');
break;
}
i++;
} else
sb.append('\\');
} else
i++;
}
return fmt;
}
/**
* Get the conversion character that tells what
* type of control character this instance has.
*
* @return the conversion character.
*/
char getConversionCharacter() {
return conversionCharacter;
}
/**
* Check whether the specifier has a variable
* field width that is going to be set by an
* argument.
* @return <code>true</code> if the conversion
* uses an * field width; otherwise
* <code>false</code>.
*/
boolean isVariableFieldWidth() {
return variableFieldWidth;
}
/**
* Set the field width with an argument. A
* negative field width is taken as a - flag
* followed by a positive field width.
* @param fw the field width.
*/
void setFieldWidthWithArg(int fw) {
if (fw < 0)
leftJustify = true;
fieldWidthSet = true;
fieldWidth = Math.abs(fw);
}
/**
* Check whether the specifier has a variable
* precision that is going to be set by an
* argument.
* @return <code>true</code> if the conversion
* uses an * precision; otherwise
* <code>false</code>.
*/
boolean isVariablePrecision() {
return variablePrecision;
}
/**
* Set the precision with an argument. A
* negative precision will be changed to zero.
* @param pr the precision.
*/
void setPrecisionWithArg(int pr) {
precisionSet = true;
precision = Math.max(pr, 0);
}
/**
* Format an int argument using this conversion
* specification.
* @param s the int to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, or G.
*/
String internalsprintf(int s) throws IllegalArgumentException {
String s2 = "";
switch (conversionCharacter) {
case 'd' :
case 'i' :
if (optionalh)
s2 = printDFormat((short) s);
else if (optionall)
s2 = printDFormat((long) s);
else
s2 = printDFormat(s);
break;
case 'x' :
case 'X' :
if (optionalh)
s2 = printXFormat((short) s);
else if (optionall)
s2 = printXFormat((long) s);
else
s2 = printXFormat(s);
break;
case 'o' :
if (optionalh)
s2 = printOFormat((short) s);
else if (optionall)
s2 = printOFormat((long) s);
else
s2 = printOFormat(s);
break;
case 'c' :
case 'C' :
s2 = printCFormat((char) s);
break;
default :
throw new IllegalArgumentException(
"Cannot format a int with a format using a " + conversionCharacter + " conversion character.");
}
return s2;
}
/**
* Format a long argument using this conversion
* specification.
* @param s the long to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is f, e, E, g, or G.
*/
String internalsprintf(long s) throws IllegalArgumentException {
String s2 = "";
switch (conversionCharacter) {
case 'd' :
case 'i' :
if (optionalh)
s2 = printDFormat((short) s);
else if (optionall)
s2 = printDFormat(s);
else
s2 = printDFormat((int) s);
break;
case 'x' :
case 'X' :
if (optionalh)
s2 = printXFormat((short) s);
else if (optionall)
s2 = printXFormat(s);
else
s2 = printXFormat((int) s);
break;
case 'o' :
if (optionalh)
s2 = printOFormat((short) s);
else if (optionall)
s2 = printOFormat(s);
else
s2 = printOFormat((int) s);
break;
case 'c' :
case 'C' :
s2 = printCFormat((char) s);
break;
default :
throw new IllegalArgumentException(
"Cannot format a long with a format using a " + conversionCharacter + " conversion character.");
}
return s2;
}
/**
* Format a double argument using this conversion
* specification.
* @param s the double to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is c, C, s, S, i, d,
* x, X, or o.
*/
String internalsprintf(double s) throws IllegalArgumentException {
String s2 = "";
switch (conversionCharacter) {
case 'f' :
s2 = printFFormat(s);
break;
case 'E' :
case 'e' :
s2 = printEFormat(s);
break;
case 'G' :
case 'g' :
s2 = printGFormat(s);
break;
default :
throw new IllegalArgumentException(
"Cannot " + "format a double with a format using a " + conversionCharacter + " conversion character.");
}
return s2;
}
/**
* Format a String argument using this conversion
* specification.
* @param s the String to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is neither s nor S.
*/
String internalsprintf(String s) throws IllegalArgumentException {
String s2 = "";
if (conversionCharacter == 's' || conversionCharacter == 'S')
s2 = printSFormat(s);
else
throw new IllegalArgumentException(
"Cannot " + "format a String with a format using a " + conversionCharacter + " conversion character.");
return s2;
}
/**
* Format an Object argument using this conversion
* specification.
* @param s the Object to format.
* @return the formatted String.
* @exception IllegalArgumentException if the
* conversion character is neither s nor S.
*/
String internalsprintf(Object s) {
String s2 = "";
if (conversionCharacter == 's' || conversionCharacter == 'S')
s2 = printSFormat(s.toString());
else
throw new IllegalArgumentException(
"Cannot format a String with a format using" + " a " + conversionCharacter + " conversion character.");
return s2;
}
/**
* For f format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both
* a '+' and a ' ' are specified, the blank flag
* is ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the number of digits
* to appear after the radix character. Padding is
* with trailing 0s.
*/
private char[] fFormatDigits(double x) {
// int defaultDigits=6;
String sx, sxOut;
int i, j, k;
int n1In, n2In;
int expon = 0;
boolean minusSign = false;
if (x > 0.0)
sx = Double.toString(x);
else if (x < 0.0) {
sx = Double.toString(-x);
minusSign = true;
} else {
sx = Double.toString(x);
if (sx.charAt(0) == '-') {
minusSign = true;
sx = sx.substring(1);
}
}
int ePos = sx.indexOf('E');
int rPos = sx.indexOf('.');
if (rPos != -1)
n1In = rPos;
else if (ePos != -1)
n1In = ePos;
else
n1In = sx.length();
if (rPos != -1) {
if (ePos != -1)
n2In = ePos - rPos - 1;
else
n2In = sx.length() - rPos - 1;
} else
n2In = 0;
if (ePos != -1) {
int ie = ePos + 1;
expon = 0;
if (sx.charAt(ie) == '-') {
for (++ie; ie < sx.length(); ie++)
if (sx.charAt(ie) != '0')
break;
if (ie < sx.length())
expon = -Integer.parseInt(sx.substring(ie));
} else {
if (sx.charAt(ie) == '+')
++ie;
for (; ie < sx.length(); ie++)
if (sx.charAt(ie) != '0')
break;
if (ie < sx.length())
expon = Integer.parseInt(sx.substring(ie));
}
}
int p;
if (precisionSet)
p = precision;
else
p = defaultDigits - 1;
char[] ca1 = sx.toCharArray();
char[] ca2 = new char[n1In + n2In];
char[] ca3, ca4, ca5;
for (j = 0; j < n1In; j++)
ca2[j] = ca1[j];
i = j + 1;
for (k = 0; k < n2In; j++, i++, k++)
ca2[j] = ca1[i];
if (n1In + expon <= 0) {
ca3 = new char[-expon + n2In];
for (j = 0, k = 0; k < (-n1In - expon); k++, j++)
ca3[j] = '0';
for (i = 0; i < (n1In + n2In); i++, j++)
ca3[j] = ca2[i];
} else
ca3 = ca2;
boolean carry = false;
if (p < -expon + n2In) {
if (expon < 0)
i = p;
else
i = p + n1In;
carry = checkForCarry(ca3, i);
if (carry)
carry = startSymbolicCarry(ca3, i - 1, 0);
}
if (n1In + expon <= 0) {
ca4 = new char[2 + p];
if (!carry)
ca4[0] = '0';
else
ca4[0] = '1';
if (alternateForm || !precisionSet || precision != 0) {
ca4[1] = '.';
for (i = 0, j = 2; i < Math.min(p, ca3.length); i++, j++)
ca4[j] = ca3[i];
for (; j < ca4.length; j++)
ca4[j] = '0';
}
} else {
if (!carry) {
if (alternateForm || !precisionSet || precision != 0)
ca4 = new char[n1In + expon + p + 1];
else
ca4 = new char[n1In + expon];
j = 0;
} else {
if (alternateForm || !precisionSet || precision != 0)
ca4 = new char[n1In + expon + p + 2];
else
ca4 = new char[n1In + expon + 1];
ca4[0] = '1';
j = 1;
}
for (i = 0; i < Math.min(n1In + expon, ca3.length); i++, j++)
ca4[j] = ca3[i];
for (; i < n1In + expon; i++, j++)
ca4[j] = '0';
if (alternateForm || !precisionSet || precision != 0) {
ca4[j] = '.';
j++;
for (k = 0; i < ca3.length && k < p; i++, j++, k++)
ca4[j] = ca3[i];
for (; j < ca4.length; j++)
ca4[j] = '0';
}
}
int nZeros = 0;
if (!leftJustify && leadingZeros) {
int xThousands = 0;
if (thousands) {
int xlead = 0;
if (ca4[0] == '+' || ca4[0] == '-' || ca4[0] == ' ')
xlead = 1;
int xdp = xlead;
for (; xdp < ca4.length; xdp++)
if (ca4[xdp] == '.')
break;
xThousands = (xdp - xlead) / 3;
}
if (fieldWidthSet)
nZeros = fieldWidth - ca4.length;
if ((!minusSign && (leadingSign || leadingSpace)) || minusSign)
nZeros--;
nZeros -= xThousands;
if (nZeros < 0)
nZeros = 0;
}
j = 0;
if ((!minusSign && (leadingSign || leadingSpace)) || minusSign) {
ca5 = new char[ca4.length + nZeros + 1];
j++;
} else
ca5 = new char[ca4.length + nZeros];
if (!minusSign) {
if (leadingSign)
ca5[0] = '+';
if (leadingSpace)
ca5[0] = ' ';
} else
ca5[0] = '-';
for (i = 0; i < nZeros; i++, j++)
ca5[j] = '0';
for (i = 0; i < ca4.length; i++, j++)
ca5[j] = ca4[i];
int lead = 0;
if (ca5[0] == '+' || ca5[0] == '-' || ca5[0] == ' ')
lead = 1;
int dp = lead;
for (; dp < ca5.length; dp++)
if (ca5[dp] == '.')
break;
int nThousands = (dp - lead) / 3;
// Localize the decimal point.
if (dp < ca5.length)
ca5[dp] = '.'; // TODO(jgw) dfs.getDecimalSeparator();
char[] ca6 = ca5;
if (thousands && nThousands > 0) {
ca6 = new char[ca5.length + nThousands + lead];
ca6[0] = ca5[0];
for (i = lead, k = lead; i < dp; i++) {
if (i > 0 && (dp - i) % 3 == 0) {
// ca6[k]=',';
ca6[k] = ','; // TODO(jgw) dfs.getGroupingSeparator();
ca6[k + 1] = ca5[i];
k += 2;
} else {
ca6[k] = ca5[i];
k++;
}
}
for (; i < ca5.length; i++, k++) {
ca6[k] = ca5[i];
}
}
return ca6;
}
/**
* An intermediate routine on the way to creating
* an f format String. The method decides whether
* the input double value is an infinity,
* not-a-number, or a finite double and formats
* each type of input appropriately.
* @param x the double value to be formatted.
* @return the converted double value.
*/
private String fFormatString(double x) {
boolean noDigits = false;
char[] ca6, ca7;
if (Double.isInfinite(x)) {
if (x == Double.POSITIVE_INFINITY) {
if (leadingSign)
ca6 = "+Inf".toCharArray();
else if (leadingSpace)
ca6 = " Inf".toCharArray();
else
ca6 = "Inf".toCharArray();
} else
ca6 = "-Inf".toCharArray();
noDigits = true;
} else if (Double.isNaN(x)) {
if (leadingSign)
ca6 = "+NaN".toCharArray();
else if (leadingSpace)
ca6 = " NaN".toCharArray();
else
ca6 = "NaN".toCharArray();
noDigits = true;
} else
ca6 = fFormatDigits(x);
ca7 = applyFloatPadding(ca6, false);
return new String(ca7);
}
/**
* For e format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear after the radix character.
* Padding is with trailing 0s.
*
* The behavior is like printf. One (hopefully the
* only) exception is that the minimum number of
* exponent digits is 3 instead of 2 for e and E
* formats when the optional L is used before the
* e, E, g, or G conversion character. The optional
* L does not imply conversion to a long long
* double.
*/
private char[] eFormatDigits(double x, char eChar) {
char[] ca1, ca2, ca3;
// int defaultDigits=6;
String sx, sxOut;
int i, j, k, p;
int n1In, n2In;
int expon = 0;
int ePos, rPos, eSize;
boolean minusSign = false;
if (x > 0.0)
sx = Double.toString(x);
else if (x < 0.0) {
sx = Double.toString(-x);
minusSign = true;
} else {
sx = Double.toString(x);
if (sx.charAt(0) == '-') {
minusSign = true;
sx = sx.substring(1);
}
}
ePos = sx.indexOf('E');
if (ePos == -1)
ePos = sx.indexOf('e');
rPos = sx.indexOf('.');
if (rPos != -1)
n1In = rPos;
else if (ePos != -1)
n1In = ePos;
else
n1In = sx.length();
if (rPos != -1) {
if (ePos != -1)
n2In = ePos - rPos - 1;
else
n2In = sx.length() - rPos - 1;
} else
n2In = 0;
if (ePos != -1) {
int ie = ePos + 1;
expon = 0;
if (sx.charAt(ie) == '-') {
for (++ie; ie < sx.length(); ie++)
if (sx.charAt(ie) != '0')
break;
if (ie < sx.length())
expon = -Integer.parseInt(sx.substring(ie));
} else {
if (sx.charAt(ie) == '+')
++ie;
for (; ie < sx.length(); ie++)
if (sx.charAt(ie) != '0')
break;
if (ie < sx.length())
expon = Integer.parseInt(sx.substring(ie));
}
}
if (rPos != -1)
expon += rPos - 1;
if (precisionSet)
p = precision;
else
p = defaultDigits - 1;
if (rPos != -1 && ePos != -1)
ca1 = (sx.substring(0, rPos) + sx.substring(rPos + 1, ePos)).toCharArray();
else if (rPos != -1)
ca1 = (sx.substring(0, rPos) + sx.substring(rPos + 1)).toCharArray();
else if (ePos != -1)
ca1 = sx.substring(0, ePos).toCharArray();
else
ca1 = sx.toCharArray();
boolean carry = false;
int i0 = 0;
if (ca1[0] != '0')
i0 = 0;
else
for (i0 = 0; i0 < ca1.length; i0++)
if (ca1[i0] != '0')
break;
if (i0 + p < ca1.length - 1) {
carry = checkForCarry(ca1, i0 + p + 1);
if (carry)
carry = startSymbolicCarry(ca1, i0 + p, i0);
if (carry) {
ca2 = new char[i0 + p + 1];
ca2[i0] = '1';
for (j = 0; j < i0; j++)
ca2[j] = '0';
for (i = i0, j = i0 + 1; j < p + 1; i++, j++)
ca2[j] = ca1[i];
expon++;
ca1 = ca2;
}
}
if (Math.abs(expon) < 100 && !optionalL)
eSize = 4;
else
eSize = 5;
if (alternateForm || !precisionSet || precision != 0)
ca2 = new char[2 + p + eSize];
else
ca2 = new char[1 + eSize];
if (ca1[0] != '0') {
ca2[0] = ca1[0];
j = 1;
} else {
for (j = 1; j < (ePos == -1 ? ca1.length : ePos); j++)
if (ca1[j] != '0')
break;
if ((ePos != -1 && j < ePos) || (ePos == -1 && j < ca1.length)) {
ca2[0] = ca1[j];
expon -= j;
j++;
} else {
ca2[0] = '0';
j = 2;
}
}
if (alternateForm || !precisionSet || precision != 0) {
ca2[1] = '.';
i = 2;
} else
i = 1;
for (k = 0; k < p && j < ca1.length; j++, i++, k++)
ca2[i] = ca1[j];
for (; i < ca2.length - eSize; i++)
ca2[i] = '0';
ca2[i++] = eChar;
if (expon < 0)
ca2[i++] = '-';
else
ca2[i++] = '+';
expon = Math.abs(expon);
if (expon >= 100) {
switch (expon / 100) {
case 1 :
ca2[i] = '1';
break;
case 2 :
ca2[i] = '2';
break;
case 3 :
ca2[i] = '3';
break;
case 4 :
ca2[i] = '4';
break;
case 5 :
ca2[i] = '5';
break;
case 6 :
ca2[i] = '6';
break;
case 7 :
ca2[i] = '7';
break;
case 8 :
ca2[i] = '8';
break;
case 9 :
ca2[i] = '9';
break;
}
i++;
}
switch ((expon % 100) / 10) {
case 0 :
ca2[i] = '0';
break;
case 1 :
ca2[i] = '1';
break;
case 2 :
ca2[i] = '2';
break;
case 3 :
ca2[i] = '3';
break;
case 4 :
ca2[i] = '4';
break;
case 5 :
ca2[i] = '5';
break;
case 6 :
ca2[i] = '6';
break;
case 7 :
ca2[i] = '7';
break;
case 8 :
ca2[i] = '8';
break;
case 9 :
ca2[i] = '9';
break;
}
i++;
switch (expon % 10) {
case 0 :
ca2[i] = '0';
break;
case 1 :
ca2[i] = '1';
break;
case 2 :
ca2[i] = '2';
break;
case 3 :
ca2[i] = '3';
break;
case 4 :
ca2[i] = '4';
break;
case 5 :
ca2[i] = '5';
break;
case 6 :
ca2[i] = '6';
break;
case 7 :
ca2[i] = '7';
break;
case 8 :
ca2[i] = '8';
break;
case 9 :
ca2[i] = '9';
break;
}
int nZeros = 0;
if (!leftJustify && leadingZeros) {
int xThousands = 0;
if (thousands) {
int xlead = 0;
if (ca2[0] == '+' || ca2[0] == '-' || ca2[0] == ' ')
xlead = 1;
int xdp = xlead;
for (; xdp < ca2.length; xdp++)
if (ca2[xdp] == '.')
break;
xThousands = (xdp - xlead) / 3;
}
if (fieldWidthSet)
nZeros = fieldWidth - ca2.length;
if ((!minusSign && (leadingSign || leadingSpace)) || minusSign)
nZeros--;
nZeros -= xThousands;
if (nZeros < 0)
nZeros = 0;
}
j = 0;
if ((!minusSign && (leadingSign || leadingSpace)) || minusSign) {
ca3 = new char[ca2.length + nZeros + 1];
j++;
} else
ca3 = new char[ca2.length + nZeros];
if (!minusSign) {
if (leadingSign)
ca3[0] = '+';
if (leadingSpace)
ca3[0] = ' ';
} else
ca3[0] = '-';
for (k = 0; k < nZeros; j++, k++)
ca3[j] = '0';
for (i = 0; i < ca2.length && j < ca3.length; i++, j++)
ca3[j] = ca2[i];
int lead = 0;
if (ca3[0] == '+' || ca3[0] == '-' || ca3[0] == ' ')
lead = 1;
int dp = lead;
for (; dp < ca3.length; dp++)
if (ca3[dp] == '.')
break;
int nThousands = dp / 3;
// Localize the decimal point.
if (dp < ca3.length)
ca3[dp] = '.'; // TODO(jgw) dfs.getDecimalSeparator();
char[] ca4 = ca3;
if (thousands && nThousands > 0) {
ca4 = new char[ca3.length + nThousands + lead];
ca4[0] = ca3[0];
for (i = lead, k = lead; i < dp; i++) {
if (i > 0 && (dp - i) % 3 == 0) {
// ca4[k]=',';
ca4[k] = ','; // TODO(jgw) dfs.getGroupingSeparator();
ca4[k + 1] = ca3[i];
k += 2;
} else {
ca4[k] = ca3[i];
k++;
}
}
for (; i < ca3.length; i++, k++)
ca4[k] = ca3[i];
}
return ca4;
}
/**
* Check to see if the digits that are going to
* be truncated because of the precision should
* force a round in the preceding digits.
* @param ca1 the array of digits
* @param icarry the index of the first digit that
* is to be truncated from the print
* @return <code>true</code> if the truncation forces
* a round that will change the print
*/
private boolean checkForCarry(char[] ca1, int icarry) {
boolean carry = false;
if (icarry < ca1.length) {
if (ca1[icarry] == '6' || ca1[icarry] == '7' || ca1[icarry] == '8' || ca1[icarry] == '9')
carry = true;
else if (ca1[icarry] == '5') {
int ii = icarry + 1;
for (; ii < ca1.length; ii++)
if (ca1[ii] != '0')
break;
carry = ii < ca1.length;
if (!carry && icarry > 0) {
carry =
(ca1[icarry - 1] == '1'
|| ca1[icarry - 1] == '3'
|| ca1[icarry - 1] == '5'
|| ca1[icarry - 1] == '7'
|| ca1[icarry - 1] == '9');
}
}
}
return carry;
}
/**
* Start the symbolic carry process. The process
* is not quite finished because the symbolic
* carry may change the length of the string and
* change the exponent (in e format).
* @param cLast index of the last digit changed
* by the round
* @param cFirst index of the first digit allowed
* to be changed by this phase of the round
* @return <code>true</code> if the carry forces
* a round that will change the print still
* more
*/
private boolean startSymbolicCarry(char[] ca, int cLast, int cFirst) {
boolean carry = true;
for (int i = cLast; carry && i >= cFirst; i--) {
carry = false;
switch (ca[i]) {
case '0' :
ca[i] = '1';
break;
case '1' :
ca[i] = '2';
break;
case '2' :
ca[i] = '3';
break;
case '3' :
ca[i] = '4';
break;
case '4' :
ca[i] = '5';
break;
case '5' :
ca[i] = '6';
break;
case '6' :
ca[i] = '7';
break;
case '7' :
ca[i] = '8';
break;
case '8' :
ca[i] = '9';
break;
case '9' :
ca[i] = '0';
carry = true;
break;
}
}
return carry;
}
/**
* An intermediate routine on the way to creating
* an e format String. The method decides whether
* the input double value is an infinity,
* not-a-number, or a finite double and formats
* each type of input appropriately.
* @param x the double value to be formatted.
* @param eChar an 'e' or 'E' to use in the
* converted double value.
* @return the converted double value.
*/
private String eFormatString(double x, char eChar) {
boolean noDigits = false;
char[] ca4, ca5;
if (Double.isInfinite(x)) {
if (x == Double.POSITIVE_INFINITY) {
if (leadingSign)
ca4 = "+Inf".toCharArray();
else if (leadingSpace)
ca4 = " Inf".toCharArray();
else
ca4 = "Inf".toCharArray();
} else
ca4 = "-Inf".toCharArray();
noDigits = true;
} else if (Double.isNaN(x)) {
if (leadingSign)
ca4 = "+NaN".toCharArray();
else if (leadingSpace)
ca4 = " NaN".toCharArray();
else
ca4 = "NaN".toCharArray();
noDigits = true;
} else
ca4 = eFormatDigits(x, eChar);
ca5 = applyFloatPadding(ca4, false);
return new String(ca5);
}
/**
* Apply zero or blank, left or right padding.
* @param ca4 array of characters before padding is
* finished
* @param noDigits NaN or signed Inf
* @return a padded array of characters
*/
private char[] applyFloatPadding(char[] ca4, boolean noDigits) {
char[] ca5 = ca4;
if (fieldWidthSet) {
int i, j, nBlanks;
if (leftJustify) {
nBlanks = fieldWidth - ca4.length;
if (nBlanks > 0) {
ca5 = new char[ca4.length + nBlanks];
for (i = 0; i < ca4.length; i++)
ca5[i] = ca4[i];
for (j = 0; j < nBlanks; j++, i++)
ca5[i] = ' ';
}
} else if (!leadingZeros || noDigits) {
nBlanks = fieldWidth - ca4.length;
if (nBlanks > 0) {
ca5 = new char[ca4.length + nBlanks];
for (i = 0; i < nBlanks; i++)
ca5[i] = ' ';
for (j = 0; j < ca4.length; i++, j++)
ca5[i] = ca4[j];
}
} else if (leadingZeros) {
nBlanks = fieldWidth - ca4.length;
if (nBlanks > 0) {
ca5 = new char[ca4.length + nBlanks];
i = 0;
j = 0;
if (ca4[0] == '-') {
ca5[0] = '-';
i++;
j++;
}
for (int k = 0; k < nBlanks; i++, k++)
ca5[i] = '0';
for (; j < ca4.length; i++, j++)
ca5[i] = ca4[j];
}
}
}
return ca5;
}
/**
* Format method for the f conversion character.
* @param x the double to format.
* @return the formatted String.
*/
private String printFFormat(double x) {
return fFormatString(x);
}
/**
* Format method for the e or E conversion
* character.
* @param x the double to format.
* @return the formatted String.
*/
private String printEFormat(double x) {
if (conversionCharacter == 'e')
return eFormatString(x, 'e');
else
return eFormatString(x, 'E');
}
/**
* Format method for the g conversion character.
*
* For g format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear after the radix character.
* Padding is with trailing 0s.
* @param x the double to format.
* @return the formatted String.
*/
private String printGFormat(double x) {
String sx, sy, sz, ret;
int savePrecision = precision;
int i;
char[] ca4, ca5;
boolean noDigits = false;
if (Double.isInfinite(x)) {
if (x == Double.POSITIVE_INFINITY) {
if (leadingSign)
ca4 = "+Inf".toCharArray();
else if (leadingSpace)
ca4 = " Inf".toCharArray();
else
ca4 = "Inf".toCharArray();
} else
ca4 = "-Inf".toCharArray();
noDigits = true;
} else if (Double.isNaN(x)) {
if (leadingSign)
ca4 = "+NaN".toCharArray();
else if (leadingSpace)
ca4 = " NaN".toCharArray();
else
ca4 = "NaN".toCharArray();
noDigits = true;
} else {
if (!precisionSet)
precision = defaultDigits;
if (precision == 0)
precision = 1;
int ePos = -1;
if (conversionCharacter == 'g') {
sx = eFormatString(x, 'e').trim();
ePos = sx.indexOf('e');
} else {
sx = eFormatString(x, 'E').trim();
ePos = sx.indexOf('E');
}
i = ePos + 1;
int expon = 0;
if (sx.charAt(i) == '-') {
for (++i; i < sx.length(); i++)
if (sx.charAt(i) != '0')
break;
if (i < sx.length())
expon = -Integer.parseInt(sx.substring(i));
} else {
if (sx.charAt(i) == '+')
++i;
for (; i < sx.length(); i++)
if (sx.charAt(i) != '0')
break;
if (i < sx.length())
expon = Integer.parseInt(sx.substring(i));
}
// Trim trailing zeros.
// If the radix character is not followed by
// a digit, trim it, too.
if (!alternateForm) {
if (expon >= -4 && expon < precision)
sy = fFormatString(x).trim();
else
sy = sx.substring(0, ePos);
i = sy.length() - 1;
for (; i >= 0; i--)
if (sy.charAt(i) != '0')
break;
if (i >= 0 && sy.charAt(i) == '.')
i--;
if (i == -1)
sz = "0";
else if (!Character.isDigit(sy.charAt(i)))
sz = sy.substring(0, i + 1) + "0";
else
sz = sy.substring(0, i + 1);
if (expon >= -4 && expon < precision)
ret = sz;
else
ret = sz + sx.substring(ePos);
} else {
if (expon >= -4 && expon < precision)
ret = fFormatString(x).trim();
else
ret = sx;
}
// leading space was trimmed off during
// construction
if (leadingSpace)
if (x >= 0)
ret = " " + ret;
ca4 = ret.toCharArray();
}
// Pad with blanks or zeros.
ca5 = applyFloatPadding(ca4, false);
precision = savePrecision;
return new String(ca5);
}
/**
* Format method for the d conversion specifer and
* short argument.
*
* For d format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. A '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the short to format.
* @return the formatted String.
*/
private String printDFormat(short x) {
return printDFormat(Short.toString(x));
}
/**
* Format method for the d conversion character and
* long argument.
*
* For d format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. A '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the long to format.
* @return the formatted String.
*/
private String printDFormat(long x) {
return printDFormat(Long.toString(x));
}
/**
* Format method for the d conversion character and
* int argument.
*
* For d format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. A '+' character means that the conversion
* will always begin with a sign (+ or -). The
* blank flag character means that a non-negative
* input will be preceded with a blank. If both a
* '+' and a ' ' are specified, the blank flag is
* ignored. The '0' flag character implies that
* padding to the field width will be done with
* zeros instead of blanks.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the int to format.
* @return the formatted String.
*/
private String printDFormat(int x) {
return printDFormat(Integer.toString(x));
}
/**
* Utility method for formatting using the d
* conversion character.
* @param sx the String to format, the result of
* converting a short, int, or long to a
* String.
* @return the formatted String.
*/
private String printDFormat(String sx) {
int nLeadingZeros = 0;
int nBlanks = 0, n = 0;
int i = 0, jFirst = 0;
boolean neg = sx.charAt(0) == '-';
if (sx.equals("0") && precisionSet && precision == 0)
sx = "";
if (!neg) {
if (precisionSet && sx.length() < precision)
nLeadingZeros = precision - sx.length();
} else {
if (precisionSet && (sx.length() - 1) < precision)
nLeadingZeros = precision - sx.length() + 1;
}
if (nLeadingZeros < 0)
nLeadingZeros = 0;
if (fieldWidthSet) {
nBlanks = fieldWidth - nLeadingZeros - sx.length();
if (!neg && (leadingSign || leadingSpace))
nBlanks--;
}
if (nBlanks < 0)
nBlanks = 0;
if (leadingSign)
n++;
else if (leadingSpace)
n++;
n += nBlanks;
n += nLeadingZeros;
n += sx.length();
char[] ca = new char[n];
if (leftJustify) {
if (neg)
ca[i++] = '-';
else if (leadingSign)
ca[i++] = '+';
else if (leadingSpace)
ca[i++] = ' ';
char[] csx = sx.toCharArray();
jFirst = neg ? 1 : 0;
for (int j = 0; j < nLeadingZeros; i++, j++)
ca[i] = '0';
for (int j = jFirst; j < csx.length; j++, i++)
ca[i] = csx[j];
for (int j = 0; j < nBlanks; i++, j++)
ca[i] = ' ';
} else {
if (!leadingZeros) {
for (i = 0; i < nBlanks; i++)
ca[i] = ' ';
if (neg)
ca[i++] = '-';
else if (leadingSign)
ca[i++] = '+';
else if (leadingSpace)
ca[i++] = ' ';
} else {
if (neg)
ca[i++] = '-';
else if (leadingSign)
ca[i++] = '+';
else if (leadingSpace)
ca[i++] = ' ';
for (int j = 0; j < nBlanks; j++, i++)
ca[i] = '0';
}
for (int j = 0; j < nLeadingZeros; j++, i++)
ca[i] = '0';
char[] csx = sx.toCharArray();
jFirst = neg ? 1 : 0;
for (int j = jFirst; j < csx.length; j++, i++)
ca[i] = csx[j];
}
return new String(ca);
}
/**
* Format method for the x conversion character and
* short argument.
*
* For x format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means to lead with
* '0x'.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the short to format.
* @return the formatted String.
*/
private String printXFormat(short x) {
String sx = null;
if (x == Short.MIN_VALUE)
sx = "8000";
else if (x < 0) {
String t;
if (x == Short.MIN_VALUE)
t = "0";
else {
t = Integer.toString((~(-x - 1)) ^ Short.MIN_VALUE, 16);
if (t.charAt(0) == 'F' || t.charAt(0) == 'f')
t = t.substring(16, 32);
}
switch (t.length()) {
case 1 :
sx = "800" + t;
break;
case 2 :
sx = "80" + t;
break;
case 3 :
sx = "8" + t;
break;
case 4 :
switch (t.charAt(0)) {
case '1' :
sx = "9" + t.substring(1, 4);
break;
case '2' :
sx = "a" + t.substring(1, 4);
break;
case '3' :
sx = "b" + t.substring(1, 4);
break;
case '4' :
sx = "c" + t.substring(1, 4);
break;
case '5' :
sx = "d" + t.substring(1, 4);
break;
case '6' :
sx = "e" + t.substring(1, 4);
break;
case '7' :
sx = "f" + t.substring(1, 4);
break;
}
break;
}
} else
sx = Integer.toString((int) x, 16);
return printXFormat(sx);
}
/**
* Format method for the x conversion character and
* long argument.
*
* For x format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means to lead with
* '0x'.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the long to format.
* @return the formatted String.
*/
private String printXFormat(long x) {
String sx = null;
if (x == Long.MIN_VALUE)
sx = "8000000000000000";
else if (x < 0) {
String t = Long.toString((~(-x - 1)) ^ Long.MIN_VALUE, 16);
switch (t.length()) {
case 1 :
sx = "800000000000000" + t;
break;
case 2 :
sx = "80000000000000" + t;
break;
case 3 :
sx = "8000000000000" + t;
break;
case 4 :
sx = "800000000000" + t;
break;
case 5 :
sx = "80000000000" + t;
break;
case 6 :
sx = "8000000000" + t;
break;
case 7 :
sx = "800000000" + t;
break;
case 8 :
sx = "80000000" + t;
break;
case 9 :
sx = "8000000" + t;
break;
case 10 :
sx = "800000" + t;
break;
case 11 :
sx = "80000" + t;
break;
case 12 :
sx = "8000" + t;
break;
case 13 :
sx = "800" + t;
break;
case 14 :
sx = "80" + t;
break;
case 15 :
sx = "8" + t;
break;
case 16 :
switch (t.charAt(0)) {
case '1' :
sx = "9" + t.substring(1, 16);
break;
case '2' :
sx = "a" + t.substring(1, 16);
break;
case '3' :
sx = "b" + t.substring(1, 16);
break;
case '4' :
sx = "c" + t.substring(1, 16);
break;
case '5' :
sx = "d" + t.substring(1, 16);
break;
case '6' :
sx = "e" + t.substring(1, 16);
break;
case '7' :
sx = "f" + t.substring(1, 16);
break;
}
break;
}
} else
sx = Long.toString(x, 16);
return printXFormat(sx);
}
/**
* Format method for the x conversion character and
* int argument.
*
* For x format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means to lead with
* '0x'.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the int to format.
* @return the formatted String.
*/
private String printXFormat(int x) {
String sx = null;
if (x == Integer.MIN_VALUE)
sx = "80000000";
else if (x < 0) {
String t = Integer.toString((~(-x - 1)) ^ Integer.MIN_VALUE, 16);
switch (t.length()) {
case 1 :
sx = "8000000" + t;
break;
case 2 :
sx = "800000" + t;
break;
case 3 :
sx = "80000" + t;
break;
case 4 :
sx = "8000" + t;
break;
case 5 :
sx = "800" + t;
break;
case 6 :
sx = "80" + t;
break;
case 7 :
sx = "8" + t;
break;
case 8 :
switch (t.charAt(0)) {
case '1' :
sx = "9" + t.substring(1, 8);
break;
case '2' :
sx = "a" + t.substring(1, 8);
break;
case '3' :
sx = "b" + t.substring(1, 8);
break;
case '4' :
sx = "c" + t.substring(1, 8);
break;
case '5' :
sx = "d" + t.substring(1, 8);
break;
case '6' :
sx = "e" + t.substring(1, 8);
break;
case '7' :
sx = "f" + t.substring(1, 8);
break;
}
break;
}
} else
sx = Integer.toString(x, 16);
return printXFormat(sx);
}
/**
* Utility method for formatting using the x
* conversion character.
* @param sx the String to format, the result of
* converting a short, int, or long to a
* String.
* @return the formatted String.
*/
private String printXFormat(String sx) {
int nLeadingZeros = 0;
int nBlanks = 0;
if (sx.equals("0") && precisionSet && precision == 0)
sx = "";
if (precisionSet)
nLeadingZeros = precision - sx.length();
if (nLeadingZeros < 0)
nLeadingZeros = 0;
if (fieldWidthSet) {
nBlanks = fieldWidth - nLeadingZeros - sx.length();
if (alternateForm)
nBlanks = nBlanks - 2;
}
if (nBlanks < 0)
nBlanks = 0;
int n = 0;
if (alternateForm)
n += 2;
n += nLeadingZeros;
n += sx.length();
n += nBlanks;
char[] ca = new char[n];
int i = 0;
if (leftJustify) {
if (alternateForm) {
ca[i++] = '0';
ca[i++] = 'x';
}
for (int j = 0; j < nLeadingZeros; j++, i++)
ca[i] = '0';
char[] csx = sx.toCharArray();
for (int j = 0; j < csx.length; j++, i++)
ca[i] = csx[j];
for (int j = 0; j < nBlanks; j++, i++)
ca[i] = ' ';
} else {
if (!leadingZeros)
for (int j = 0; j < nBlanks; j++, i++)
ca[i] = ' ';
if (alternateForm) {
ca[i++] = '0';
ca[i++] = 'x';
}
if (leadingZeros)
for (int j = 0; j < nBlanks; j++, i++)
ca[i] = '0';
for (int j = 0; j < nLeadingZeros; j++, i++)
ca[i] = '0';
char[] csx = sx.toCharArray();
for (int j = 0; j < csx.length; j++, i++)
ca[i] = csx[j];
}
String caReturn = new String(ca);
if (conversionCharacter == 'X')
caReturn = caReturn.toUpperCase();
return caReturn;
}
/**
* Format method for the o conversion character and
* short argument.
*
* For o format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means that the
* output begins with a leading 0 and the precision
* is increased by 1.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the short to format.
* @return the formatted String.
*/
private String printOFormat(short x) {
String sx = null;
if (x == Short.MIN_VALUE)
sx = "100000";
else if (x < 0) {
String t = Integer.toString((~(-x - 1)) ^ Short.MIN_VALUE, 8);
switch (t.length()) {
case 1 :
sx = "10000" + t;
break;
case 2 :
sx = "1000" + t;
break;
case 3 :
sx = "100" + t;
break;
case 4 :
sx = "10" + t;
break;
case 5 :
sx = "1" + t;
break;
}
} else
sx = Integer.toString((int) x, 8);
return printOFormat(sx);
}
/**
* Format method for the o conversion character and
* long argument.
*
* For o format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means that the
* output begins with a leading 0 and the precision
* is increased by 1.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the long to format.
* @return the formatted String.
*/
private String printOFormat(long x) {
String sx = null;
if (x == Long.MIN_VALUE)
sx = "1000000000000000000000";
else if (x < 0) {
String t = Long.toString((~(-x - 1)) ^ Long.MIN_VALUE, 8);
switch (t.length()) {
case 1 :
sx = "100000000000000000000" + t;
break;
case 2 :
sx = "10000000000000000000" + t;
break;
case 3 :
sx = "1000000000000000000" + t;
break;
case 4 :
sx = "100000000000000000" + t;
break;
case 5 :
sx = "10000000000000000" + t;
break;
case 6 :
sx = "1000000000000000" + t;
break;
case 7 :
sx = "100000000000000" + t;
break;
case 8 :
sx = "10000000000000" + t;
break;
case 9 :
sx = "1000000000000" + t;
break;
case 10 :
sx = "100000000000" + t;
break;
case 11 :
sx = "10000000000" + t;
break;
case 12 :
sx = "1000000000" + t;
break;
case 13 :
sx = "100000000" + t;
break;
case 14 :
sx = "10000000" + t;
break;
case 15 :
sx = "1000000" + t;
break;
case 16 :
sx = "100000" + t;
break;
case 17 :
sx = "10000" + t;
break;
case 18 :
sx = "1000" + t;
break;
case 19 :
sx = "100" + t;
break;
case 20 :
sx = "10" + t;
break;
case 21 :
sx = "1" + t;
break;
}
} else
sx = Long.toString(x, 8);
return printOFormat(sx);
}
/**
* Format method for the o conversion character and
* int argument.
*
* For o format, the flag character '-', means that
* the output should be left justified within the
* field. The default is to pad with blanks on the
* left. The '#' flag character means that the
* output begins with a leading 0 and the precision
* is increased by 1.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is to
* add no padding. Padding is with blanks by
* default.
*
* The precision, if set, is the minimum number of
* digits to appear. Padding is with leading 0s.
* @param x the int to format.
* @return the formatted String.
*/
private String printOFormat(int x) {
String sx = null;
if (x == Integer.MIN_VALUE)
sx = "20000000000";
else if (x < 0) {
String t = Integer.toString((~(-x - 1)) ^ Integer.MIN_VALUE, 8);
switch (t.length()) {
case 1 :
sx = "2000000000" + t;
break;
case 2 :
sx = "200000000" + t;
break;
case 3 :
sx = "20000000" + t;
break;
case 4 :
sx = "2000000" + t;
break;
case 5 :
sx = "200000" + t;
break;
case 6 :
sx = "20000" + t;
break;
case 7 :
sx = "2000" + t;
break;
case 8 :
sx = "200" + t;
break;
case 9 :
sx = "20" + t;
break;
case 10 :
sx = "2" + t;
break;
case 11 :
sx = "3" + t.substring(1);
break;
}
} else
sx = Integer.toString(x, 8);
return printOFormat(sx);
}
/**
* Utility method for formatting using the o
* conversion character.
* @param sx the String to format, the result of
* converting a short, int, or long to a
* String.
* @return the formatted String.
*/
private String printOFormat(String sx) {
int nLeadingZeros = 0;
int nBlanks = 0;
if (sx.equals("0") && precisionSet && precision == 0)
sx = "";
if (precisionSet)
nLeadingZeros = precision - sx.length();
if (alternateForm)
nLeadingZeros++;
if (nLeadingZeros < 0)
nLeadingZeros = 0;
if (fieldWidthSet)
nBlanks = fieldWidth - nLeadingZeros - sx.length();
if (nBlanks < 0)
nBlanks = 0;
int n = nLeadingZeros + sx.length() + nBlanks;
char[] ca = new char[n];
int i;
if (leftJustify) {
for (i = 0; i < nLeadingZeros; i++)
ca[i] = '0';
char[] csx = sx.toCharArray();
for (int j = 0; j < csx.length; j++, i++)
ca[i] = csx[j];
for (int j = 0; j < nBlanks; j++, i++)
ca[i] = ' ';
} else {
if (leadingZeros)
for (i = 0; i < nBlanks; i++)
ca[i] = '0';
else
for (i = 0; i < nBlanks; i++)
ca[i] = ' ';
for (int j = 0; j < nLeadingZeros; j++, i++)
ca[i] = '0';
char[] csx = sx.toCharArray();
for (int j = 0; j < csx.length; j++, i++)
ca[i] = csx[j];
}
return new String(ca);
}
/**
* Format method for the c conversion character and
* char argument.
*
* The only flag character that affects c format is
* the '-', meaning that the output should be left
* justified within the field. The default is to
* pad with blanks on the left.
*
* The field width is treated as the minimum number
* of characters to be printed. Padding is with
* blanks by default. The default width is 1.
*
* The precision, if set, is ignored.
* @param x the char to format.
* @return the formatted String.
*/
private String printCFormat(char x) {
int nPrint = 1;
int width = fieldWidth;
if (!fieldWidthSet)
width = nPrint;
char[] ca = new char[width];
int i = 0;
if (leftJustify) {
ca[0] = x;
for (i = 1; i <= width - nPrint; i++)
ca[i] = ' ';
} else {
for (i = 0; i < width - nPrint; i++)
ca[i] = ' ';
ca[i] = x;
}
return new String(ca);
}
/**
* Format method for the s conversion character and
* String argument.
*
* The only flag character that affects s format is
* the '-', meaning that the output should be left
* justified within the field. The default is to
* pad with blanks on the left.
*
* The field width is treated as the minimum number
* of characters to be printed. The default is the
* smaller of the number of characters in the the
* input and the precision. Padding is with blanks
* by default.
*
* The precision, if set, specifies the maximum
* number of characters to be printed from the
* string. A null digit string is treated
* as a 0. The default is not to set a maximum
* number of characters to be printed.
* @param x the String to format.
* @return the formatted String.
*/
private String printSFormat(String x) {
int nPrint = x.length();
int width = fieldWidth;
if (precisionSet && nPrint > precision)
nPrint = precision;
if (!fieldWidthSet)
width = nPrint;
int n = 0;
if (width > nPrint)
n += width - nPrint;
if (nPrint >= x.length())
n += x.length();
else
n += nPrint;
char[] ca = new char[n];
int i = 0;
if (leftJustify) {
if (nPrint >= x.length()) {
char[] csx = x.toCharArray();
for (i = 0; i < x.length(); i++)
ca[i] = csx[i];
} else {
char[] csx = x.substring(0, nPrint).toCharArray();
for (i = 0; i < nPrint; i++)
ca[i] = csx[i];
}
for (int j = 0; j < width - nPrint; j++, i++)
ca[i] = ' ';
} else {
for (i = 0; i < width - nPrint; i++)
ca[i] = ' ';
if (nPrint >= x.length()) {
char[] csx = x.toCharArray();
for (int j = 0; j < x.length(); i++, j++)
ca[i] = csx[j];
} else {
char[] csx = x.substring(0, nPrint).toCharArray();
for (int j = 0; j < nPrint; i++, j++)
ca[i] = csx[j];
}
}
return new String(ca);
}
/**
* Check for a conversion character. If it is
* there, store it.
* @param x the String to format.
* @return <code>true</code> if the conversion
* character is there, and
* <code>false</code> otherwise.
*/
private boolean setConversionCharacter() {
/* idfgGoxXeEcs */
boolean ret = false;
conversionCharacter = '\0';
if (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (c == 'i'
|| c == 'd'
|| c == 'f'
|| c == 'g'
|| c == 'G'
|| c == 'o'
|| c == 'x'
|| c == 'X'
|| c == 'e'
|| c == 'E'
|| c == 'c'
|| c == 's'
|| c == '%') {
conversionCharacter = c;
pos++;
ret = true;
}
}
return ret;
}
/**
* Check for an h, l, or L in a format. An L is
* used to control the minimum number of digits
* in an exponent when using floating point
* formats. An l or h is used to control
* conversion of the input to a long or short,
* respectively, before formatting. If any of
* these is present, store them.
*/
private void setOptionalHL() {
optionalh = false;
optionall = false;
optionalL = false;
if (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (c == 'h') {
optionalh = true;
pos++;
} else if (c == 'l') {
optionall = true;
pos++;
} else if (c == 'L') {
optionalL = true;
pos++;
}
}
}
/**
* Set the precision.
*/
private void setPrecision() {
int firstPos = pos;
precisionSet = false;
if (pos < fmt.length() && fmt.charAt(pos) == '.') {
pos++;
if ((pos < fmt.length()) && (fmt.charAt(pos) == '*')) {
pos++;
if (!setPrecisionArgPosition()) {
variablePrecision = true;
precisionSet = true;
}
return;
} else {
while (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (Character.isDigit(c))
pos++;
else
break;
}
if (pos > firstPos + 1) {
String sz = fmt.substring(firstPos + 1, pos);
precision = Integer.parseInt(sz);
precisionSet = true;
}
}
}
}
/**
* Set the field width.
*/
private void setFieldWidth() {
int firstPos = pos;
fieldWidth = 0;
fieldWidthSet = false;
if ((pos < fmt.length()) && (fmt.charAt(pos) == '*')) {
pos++;
if (!setFieldWidthArgPosition()) {
variableFieldWidth = true;
fieldWidthSet = true;
}
} else {
while (pos < fmt.length()) {
char c = fmt.charAt(pos);
if (Character.isDigit(c))
pos++;
else
break;
}
if (firstPos < pos && firstPos < fmt.length()) {
String sz = fmt.substring(firstPos, pos);
fieldWidth = Integer.parseInt(sz);
fieldWidthSet = true;
}
}
}
/**
* Store the digits <code>n</code> in %n$ forms.
*/
private void setArgPosition() {
int xPos;
for (xPos = pos; xPos < fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos > pos && xPos < fmt.length()) {
if (fmt.charAt(xPos) == '$') {
positionalSpecification = true;
argumentPosition = Integer.parseInt(fmt.substring(pos, xPos));
pos = xPos + 1;
}
}
}
/**
* Store the digits <code>n</code> in *n$ forms.
*/
private boolean setFieldWidthArgPosition() {
boolean ret = false;
int xPos;
for (xPos = pos; xPos < fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos > pos && xPos < fmt.length()) {
if (fmt.charAt(xPos) == '$') {
positionalFieldWidth = true;
argumentPositionForFieldWidth = Integer.parseInt(fmt.substring(pos, xPos));
pos = xPos + 1;
ret = true;
}
}
return ret;
}
/**
* Store the digits <code>n</code> in *n$ forms.
*/
private boolean setPrecisionArgPosition() {
boolean ret = false;
int xPos;
for (xPos = pos; xPos < fmt.length(); xPos++) {
if (!Character.isDigit(fmt.charAt(xPos)))
break;
}
if (xPos > pos && xPos < fmt.length()) {
if (fmt.charAt(xPos) == '$') {
positionalPrecision = true;
argumentPositionForPrecision = Integer.parseInt(fmt.substring(pos, xPos));
pos = xPos + 1;
ret = true;
}
}
return ret;
}
boolean isPositionalSpecification() {
return positionalSpecification;
}
int getArgumentPosition() {
return argumentPosition;
}
boolean isPositionalFieldWidth() {
return positionalFieldWidth;
}
int getArgumentPositionForFieldWidth() {
return argumentPositionForFieldWidth;
}
boolean isPositionalPrecision() {
return positionalPrecision;
}
int getArgumentPositionForPrecision() {
return argumentPositionForPrecision;
}
/**
* Set flag characters, one of '-+#0 or a space.
*/
private void setFlagCharacters() {
/* '-+ #0 */
thousands = false;
leftJustify = false;
leadingSign = false;
leadingSpace = false;
alternateForm = false;
leadingZeros = false;
for (; pos < fmt.length(); pos++) {
char c = fmt.charAt(pos);
if (c == '\'')
thousands = true;
else if (c == '-') {
leftJustify = true;
leadingZeros = false;
} else if (c == '+') {
leadingSign = true;
leadingSpace = false;
} else if (c == ' ') {
if (!leadingSign)
leadingSpace = true;
} else if (c == '#')
alternateForm = true;
else if (c == '0') {
if (!leftJustify)
leadingZeros = true;
} else
break;
}
}
/**
* The integer portion of the result of a decimal
* conversion (i, d, u, f, g, or G) will be
* formatted with thousands' grouping characters.
* For other conversions the flag is ignored.
*/
private boolean thousands = false;
/**
* The result of the conversion will be
* left-justified within the field.
*/
private boolean leftJustify = false;
/**
* The result of a signed conversion will always
* begin with a sign (+ or -).
*/
private boolean leadingSign = false;
/**
* Flag indicating that left padding with spaces is
* specified.
*/
private boolean leadingSpace = false;
/**
* For an o conversion, increase the precision to
* force the first digit of the result to be a
* zero. For x (or X) conversions, a non-zero
* result will have 0x (or 0X) prepended to it.
* For e, E, f, g, or G conversions, the result
* will always contain a radix character, even if
* no digits follow the point. For g and G
* conversions, trailing zeros will not be removed
* from the result.
*/
private boolean alternateForm = false;
/**
* Flag indicating that left padding with zeroes is
* specified.
*/
private boolean leadingZeros = false;
/**
* Flag indicating that the field width is *.
*/
private boolean variableFieldWidth = false;
/**
* If the converted value has fewer bytes than the
* field width, it will be padded with spaces or
* zeroes.
*/
private int fieldWidth = 0;
/**
* Flag indicating whether or not the field width
* has been set.
*/
private boolean fieldWidthSet = false;
/**
* The minimum number of digits to appear for the
* d, i, o, u, x, or X conversions. The number of
* digits to appear after the radix character for
* the e, E, and f conversions. The maximum number
* of significant digits for the g and G
* conversions. The maximum number of bytes to be
* printed from a string in s and S conversions.
*/
private int precision = 0;
/** Default precision. */
private final static int defaultDigits = 6;
/**
* Flag indicating that the precision is *.
*/
private boolean variablePrecision = false;
/**
* Flag indicating whether or not the precision has
* been set.
*/
private boolean precisionSet = false;
/*
*/
private boolean positionalSpecification = false;
private int argumentPosition = 0;
private boolean positionalFieldWidth = false;
private int argumentPositionForFieldWidth = 0;
private boolean positionalPrecision = false;
private int argumentPositionForPrecision = 0;
/**
* Flag specifying that a following d, i, o, u, x,
* or X conversion character applies to a type
* short int.
*/
private boolean optionalh = false;
/**
* Flag specifying that a following d, i, o, u, x,
* or X conversion character applies to a type lont
* int argument.
*/
private boolean optionall = false;
/**
* Flag specifying that a following e, E, f, g, or
* G conversion character applies to a type double
* argument. This is a noop in Java.
*/
private boolean optionalL = false;
/** Control string type. */
private char conversionCharacter = '\0';
/**
* Position within the control string. Used by
* the constructor.
*/
private int pos = 0;
/** Literal or control format string. */
private String fmt;
}
/** Vector of control strings and format literals. */
private Vector vFmt = new Vector();
/** Character position. Used by the constructor. */
private int cPos = 0;
// /** Character position. Used by the constructor. */
// TODO(jgw) private DecimalFormatSymbols dfs = null;
}
| oscarmartins/oscarmartins-gameforce | src/jake2/util/PrintfFormat.java | Java | gpl-2.0 | 92,922 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "faceCorrectedSnGrad.H"
#include "fvMesh.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace fv
{
makeSnGradScheme(faceCorrectedSnGrad)
}
}
template<>
Foam::tmp<Foam::surfaceScalarField>
Foam::fv::faceCorrectedSnGrad<Foam::scalar>::correction
(
const volScalarField& vsf
) const
{
return fullGradCorrection(vsf);
}
template<>
Foam::tmp<Foam::surfaceVectorField>
Foam::fv::faceCorrectedSnGrad<Foam::vector>::correction
(
const volVectorField& vvf
) const
{
return fullGradCorrection(vvf);
}
// ************************************************************************* //
| Atizar/RapidCFD-dev | src/finiteVolume/finiteVolume/snGradSchemes/faceCorrectedSnGrad/faceCorrectedSnGrads.C | C++ | gpl-3.0 | 1,823 |
/* Definitions of target machine for GNU compiler, for SPARC running Solaris 2
using the GNU linker. */
/* Undefine this so that attribute((init_priority)) works. */
#undef CTORS_SECTION_ASM_OP
#undef DTORS_SECTION_ASM_OP
| uhhpctools/openuh-openacc | osprey/kgccfe/gnu/config/sparc/sol2-gld.h | C | gpl-3.0 | 228 |
-----------------------------------
-- Area: Northern San d'Oria
-- NPC: Coullene
-- Type: Involved in Quest (Flyers for Regine)
-- @zone: 231
-- @pos 146.420 0.000 127.601
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED)then
if(trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeCoulene") == 0)then
player:messageSpecial(11932);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeCoulene",1);
player:messageSpecial(FLYER_ACCEPTED);
trade:complete();
elseif(player:getVar("tradeCoulene") ==1)then
player:messageSpecial(11936);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,COULLENE_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| jono659/enko | scripts/zones/Northern_San_dOria/npcs/Coullene.lua | Lua | gpl-3.0 | 1,483 |
/*
* Copyright (C) 2015 Paul B Mahol
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/attributes.h"
#include "libavutil/cpu.h"
#include "libavutil/mem.h"
#include "libavutil/x86/asm.h"
#include "libavutil/x86/cpu.h"
#include "libavfilter/w3fdif.h"
void ff_w3fdif_simple_low_sse2(int32_t *work_line,
uint8_t *in_lines_cur[2],
const int16_t *coef, int linesize);
void ff_w3fdif_simple_high_sse2(int32_t *work_line,
uint8_t *in_lines_cur[3],
uint8_t *in_lines_adj[3],
const int16_t *coef, int linesize);
void ff_w3fdif_complex_low_sse2(int32_t *work_line,
uint8_t *in_lines_cur[4],
const int16_t *coef, int linesize);
void ff_w3fdif_complex_high_sse2(int32_t *work_line,
uint8_t *in_lines_cur[5],
uint8_t *in_lines_adj[5],
const int16_t *coef, int linesize);
void ff_w3fdif_scale_sse2(uint8_t *out_pixel, const int32_t *work_pixel, int linesize);
av_cold void ff_w3fdif_init_x86(W3FDIFDSPContext *dsp)
{
int cpu_flags = av_get_cpu_flags();
if (EXTERNAL_SSE2(cpu_flags)) {
dsp->filter_simple_low = ff_w3fdif_simple_low_sse2;
dsp->filter_simple_high = ff_w3fdif_simple_high_sse2;
dsp->filter_complex_low = ff_w3fdif_complex_low_sse2;
dsp->filter_scale = ff_w3fdif_scale_sse2;
}
if (ARCH_X86_64 && EXTERNAL_SSE2(cpu_flags)) {
dsp->filter_complex_high = ff_w3fdif_complex_high_sse2;
}
}
| chenzeyuan/smt | smt-player/ffmpeg/libavfilter/x86/vf_w3fdif_init.c | C | gpl-3.0 | 2,416 |
#! /bin/sh
#
# This file becomes the install section of the generated spec file.
#
python setup.py install --root=${RPM_BUILD_ROOT} --record="INSTALLED_FILES"
# Sort the filelist so that directories appear before files. This avoids
# duplicate filename problems on some systems.
touch DIRS
for i in `cat INSTALLED_FILES`; do
if [ -f ${RPM_BUILD_ROOT}/$i ]; then
echo $i >>FILES
fi
if [ -d ${RPM_BUILD_ROOT}/$i ]; then
echo %dir $i >>DIRS
fi
done
# Make sure we match foo.pyo and foo.pyc along with foo.py (but only once each)
sed -e "/\.py[co]$/d" -e "s/\.py$/.py*/" DIRS FILES >INSTALLED_FILES
| waseem18/oh-mainline | vendor/packages/scrapy/extras/rpm-install.sh | Shell | agpl-3.0 | 614 |
#pylint: disable=C0111
#pylint: disable=W0621
from lettuce import world, step
from lettuce.django import django_url
from course_modes.models import CourseMode
from nose.tools import assert_equal
UPSELL_LINK_CSS = '.message-upsell a.action-upgrade[href*="edx/999/Certificates"]'
def create_cert_course():
world.clear_courses()
org = 'edx'
number = '999'
name = 'Certificates'
course_id = '{org}/{number}/{name}'.format(
org=org, number=number, name=name)
world.scenario_dict['course_id'] = course_id
world.scenario_dict['COURSE'] = world.CourseFactory.create(
org=org, number=number, display_name=name)
audit_mode = world.CourseModeFactory.create(
course_id=course_id,
mode_slug='audit',
mode_display_name='audit course',
min_price=0,
)
assert isinstance(audit_mode, CourseMode)
verfied_mode = world.CourseModeFactory.create(
course_id=course_id,
mode_slug='verified',
mode_display_name='verified cert course',
min_price=16,
suggested_prices='32,64,128',
currency='usd',
)
assert isinstance(verfied_mode, CourseMode)
def register():
url = 'courses/{org}/{number}/{name}/about'.format(
org='edx', number='999', name='Certificates')
world.browser.visit(django_url(url))
world.css_click('section.intro a.register')
assert world.is_css_present('section.wrapper h3.title')
@step(u'the course has an honor mode')
def the_course_has_an_honor_mode(step):
create_cert_course()
honor_mode = world.CourseModeFactory.create(
course_id=world.scenario_dict['course_id'],
mode_slug='honor',
mode_display_name='honor mode',
min_price=0,
)
assert isinstance(honor_mode, CourseMode)
@step(u'I select the audit track$')
def select_the_audit_track(step):
create_cert_course()
register()
btn_css = 'input[value="Select Audit"]'
world.wait(1) # TODO remove this after troubleshooting JZ
world.css_find(btn_css)
world.css_click(btn_css)
def select_contribution(amount=32):
radio_css = 'input[value="{}"]'.format(amount)
world.css_click(radio_css)
assert world.css_find(radio_css).selected
def click_verified_track_button():
world.wait_for_ajax_complete()
btn_css = 'input[value="Select Certificate"]'
world.css_click(btn_css)
@step(u'I select the verified track for upgrade')
def select_verified_track_upgrade(step):
select_contribution(32)
world.wait_for_ajax_complete()
btn_css = 'input[value="Upgrade Your Registration"]'
world.css_click(btn_css)
# TODO: might want to change this depending on the changes for upgrade
assert world.is_css_present('section.progress')
@step(u'I select the verified track$')
def select_the_verified_track(step):
create_cert_course()
register()
select_contribution(32)
click_verified_track_button()
assert world.is_css_present('section.progress')
@step(u'I should see the course on my dashboard$')
def should_see_the_course_on_my_dashboard(step):
course_css = 'li.course-item'
assert world.is_css_present(course_css)
@step(u'I go to step "([^"]*)"$')
def goto_next_step(step, step_num):
btn_css = {
'1': '#face_next_button',
'2': '#face_next_link',
'3': '#photo_id_next_link',
'4': '#pay_button',
}
next_css = {
'1': 'div#wrapper-facephoto.carousel-active',
'2': 'div#wrapper-idphoto.carousel-active',
'3': 'div#wrapper-review.carousel-active',
'4': 'div#wrapper-review.carousel-active',
}
world.css_click(btn_css[step_num])
# Pressing the button will advance the carousel to the next item
# and give the wrapper div the "carousel-active" class
assert world.css_find(next_css[step_num])
@step(u'I capture my "([^"]*)" photo$')
def capture_my_photo(step, name):
# Hard coded red dot image
image_data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
snapshot_script = "$('#{}_image')[0].src = '{}';".format(name, image_data)
# Mirror the javascript of the photo_verification.html page
world.browser.execute_script(snapshot_script)
world.browser.execute_script("$('#{}_capture_button').hide();".format(name))
world.browser.execute_script("$('#{}_reset_button').show();".format(name))
world.browser.execute_script("$('#{}_approve_button').show();".format(name))
assert world.css_find('#{}_approve_button'.format(name))
@step(u'I approve my "([^"]*)" photo$')
def approve_my_photo(step, name):
button_css = {
'face': 'div#wrapper-facephoto li.control-approve',
'photo_id': 'div#wrapper-idphoto li.control-approve',
}
wrapper_css = {
'face': 'div#wrapper-facephoto',
'photo_id': 'div#wrapper-idphoto',
}
# Make sure that the carousel is in the right place
assert world.css_has_class(wrapper_css[name], 'carousel-active')
assert world.css_find(button_css[name])
# HACK: for now don't bother clicking the approve button for
# id_photo, because it is sending you back to Step 1.
# Come back and figure it out later. JZ Aug 29 2013
if name=='face':
world.css_click(button_css[name])
# Make sure you didn't advance the carousel
assert world.css_has_class(wrapper_css[name], 'carousel-active')
@step(u'I select a contribution amount$')
def select_contribution_amount(step):
select_contribution(32)
@step(u'I confirm that the details match$')
def confirm_details_match(step):
# First you need to scroll down on the page
# to make the element visible?
# Currently chrome is failing with ElementNotVisibleException
world.browser.execute_script("window.scrollTo(0,1024)")
cb_css = 'input#confirm_pics_good'
world.css_click(cb_css)
assert world.css_find(cb_css).checked
@step(u'I am at the payment page')
def at_the_payment_page(step):
world.wait_for_present('input[name=transactionSignature]')
@step(u'I submit valid payment information$')
def submit_payment(step):
# First make sure that the page is done if it still executing
# an ajax query.
world.wait_for_ajax_complete()
button_css = 'input[value=Submit]'
world.css_click(button_css)
@step(u'I have submitted face and ID photos$')
def submitted_face_and_id_photos(step):
step.given('I am logged in')
step.given('I select the verified track')
step.given('I go to step "1"')
step.given('I capture my "face" photo')
step.given('I approve my "face" photo')
step.given('I go to step "2"')
step.given('I capture my "photo_id" photo')
step.given('I approve my "photo_id" photo')
step.given('I go to step "3"')
@step(u'I have submitted photos to verify my identity')
def submitted_photos_to_verify_my_identity(step):
step.given('I have submitted face and ID photos')
step.given('I select a contribution amount')
step.given('I confirm that the details match')
step.given('I go to step "4"')
@step(u'I submit my photos and confirm')
def submit_photos_and_confirm(step):
step.given('I go to step "1"')
step.given('I capture my "face" photo')
step.given('I approve my "face" photo')
step.given('I go to step "2"')
step.given('I capture my "photo_id" photo')
step.given('I approve my "photo_id" photo')
step.given('I go to step "3"')
step.given('I select a contribution amount')
step.given('I confirm that the details match')
step.given('I go to step "4"')
@step(u'I see that my payment was successful')
def see_that_my_payment_was_successful(step):
title = world.css_find('div.wrapper-content-main h3.title')
assert_equal(title.text, u'Congratulations! You are now verified on edX.')
@step(u'I navigate to my dashboard')
def navigate_to_my_dashboard(step):
world.css_click('span.avatar')
assert world.css_find('section.my-courses')
@step(u'I see the course on my dashboard')
def see_the_course_on_my_dashboard(step):
course_link_css = 'section.my-courses a[href*="edx/999/Certificates"]'
assert world.is_css_present(course_link_css)
@step(u'I see the upsell link on my dashboard')
def see_upsell_link_on_my_dashboard(step):
course_link_css = UPSELL_LINK_CSS
assert world.is_css_present(course_link_css)
@step(u'I do not see the upsell link on my dashboard')
def see_upsell_link_on_my_dashboard(step):
course_link_css = UPSELL_LINK_CSS
assert not world.is_css_present(course_link_css)
@step(u'I select the upsell link on my dashboard')
def see_upsell_link_on_my_dashboard(step):
# expand the upsell section
world.css_click('.message-upsell')
course_link_css = UPSELL_LINK_CSS
# click the actual link
world.css_click(course_link_css)
@step(u'I see that I am on the verified track')
def see_that_i_am_on_the_verified_track(step):
id_verified_css = 'li.course-item article.course.verified'
assert world.is_css_present(id_verified_css)
@step(u'I leave the flow and return$')
def leave_the_flow_and_return(step):
world.visit('verify_student/verified/edx/999/Certificates')
@step(u'I am at the verified page$')
def see_the_payment_page(step):
assert world.css_find('button#pay_button')
@step(u'I edit my name$')
def edit_my_name(step):
btn_css = 'a.retake-photos'
world.css_click(btn_css)
@step(u'I give a reason why I cannot pay$')
def give_a_reason_why_i_cannot_pay(step):
register()
link_css = 'h5 i.expandable-icon'
world.css_click(link_css)
cb_css = 'input#honor-code'
world.css_click(cb_css)
text_css = 'li.field-explain textarea'
world.css_find(text_css).type('I cannot afford it.')
btn_css = 'input[value="Select Certificate"]'
world.css_click(btn_css)
| XiaodunServerGroup/xiaodun-platform | lms/djangoapps/wechat/features/certificates.py | Python | agpl-3.0 | 9,880 |
/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "KKSAction.h"
#include "Factory.h"
#include "Parser.h"
#include "FEProblem.h"
template<>
InputParameters validParams<KKSAction>()
{
InputParameters params = validParams<Action>();
params.addParam<std::string>("c_name_base", "c", "base name of the concentration variables");
params.addParam<std::string>("eta_name", "eta", "name of the order parameter");
params.addRequiredParam<std::vector<std::string> >("phase_names", "short names for the phases");
params.addRequiredParam<std::vector<std::string> >("c_names", "short names for the concentrations");
return params;
}
KKSAction::KKSAction(const InputParameters & params) :
Action(params)
// _z2(getParam<Real>("z2"))
{
}
void
KKSAction::act()
{
/*
InputParameters poly_params = _factory.getValidParams("BoundingBoxIC");
poly_params.set<VariableName>("variable") = var_name;
poly_params.set<Real>("x1") = _x1;
poly_params.set<Real>("y1") = _y1;
poly_params.set<Real>("z1") = _z1;
poly_params.set<Real>("x2") = _x2;
poly_params.set<Real>("y2") = _y2;
poly_params.set<Real>("z2") = _z2;
// Add initial condition
_problem->addInitialCondition("BoundingBoxIC", "InitialCondition", poly_params);
*/
}
| mellis13/moose | modules/phase_field/src/action/KKSAction.C | C++ | lgpl-2.1 | 1,626 |
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.cvsSupport2.cvsoperations.common;
import com.intellij.CvsBundle;
import com.intellij.cvsSupport2.CvsUtil;
import com.intellij.cvsSupport2.application.CvsEntriesManager;
import com.intellij.cvsSupport2.config.CvsApplicationLevelConfiguration;
import com.intellij.cvsSupport2.connections.CvsEnvironment;
import com.intellij.cvsSupport2.connections.CvsRootProvider;
import com.intellij.cvsSupport2.connections.pserver.PServerCvsSettings;
import com.intellij.cvsSupport2.cvsIgnore.IgnoreFileFilterBasedOnCvsEntriesManager;
import com.intellij.cvsSupport2.cvsoperations.cvsMessages.CvsMessagesListener;
import com.intellij.cvsSupport2.cvsoperations.cvsMessages.CvsMessagesTranslator;
import com.intellij.cvsSupport2.cvsoperations.cvsMessages.FileMessage;
import com.intellij.cvsSupport2.cvsoperations.javacvsSpecificImpls.AdminReaderOnCache;
import com.intellij.cvsSupport2.cvsoperations.javacvsSpecificImpls.AdminWriterOnCache;
import com.intellij.cvsSupport2.errorHandling.CannotFindCvsRootException;
import com.intellij.cvsSupport2.errorHandling.CvsException;
import com.intellij.cvsSupport2.javacvsImpl.FileReadOnlyHandler;
import com.intellij.cvsSupport2.javacvsImpl.ProjectContentInfoProvider;
import com.intellij.cvsSupport2.javacvsImpl.io.*;
import com.intellij.cvsSupport2.util.CvsVfsUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.netbeans.lib.cvsclient.ClientEnvironment;
import org.netbeans.lib.cvsclient.IClientEnvironment;
import org.netbeans.lib.cvsclient.IRequestProcessor;
import org.netbeans.lib.cvsclient.RequestProcessor;
import org.netbeans.lib.cvsclient.admin.Entry;
import org.netbeans.lib.cvsclient.admin.IAdminReader;
import org.netbeans.lib.cvsclient.admin.IAdminWriter;
import org.netbeans.lib.cvsclient.command.*;
import org.netbeans.lib.cvsclient.command.update.UpdateFileInfo;
import org.netbeans.lib.cvsclient.connection.AuthenticationException;
import org.netbeans.lib.cvsclient.connection.IConnection;
import org.netbeans.lib.cvsclient.event.*;
import org.netbeans.lib.cvsclient.file.FileObject;
import org.netbeans.lib.cvsclient.file.IFileSystem;
import org.netbeans.lib.cvsclient.file.ILocalFileReader;
import org.netbeans.lib.cvsclient.file.ILocalFileWriter;
import org.netbeans.lib.cvsclient.progress.IProgressViewer;
import org.netbeans.lib.cvsclient.progress.RangeProgressViewer;
import org.netbeans.lib.cvsclient.util.IIgnoreFileFilter;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public abstract class CvsCommandOperation extends CvsOperation implements IFileInfoListener,
IMessageListener,
IEntryListener,
IModuleExpansionListener,
ProjectContentInfoProvider {
private static final IAdminReader DEFAULT_ADMIN_READER = new AdminReaderOnCache();
protected final IAdminReader myAdminReader;
protected final IAdminWriter myAdminWriter;
protected static final Logger LOG = Logger.getInstance("#com.intellij.cvsSupport2.cvsoperations.common.CvsCommandOperation");
private String myLastProcessedCvsRoot;
private final UpdatedFilesManager myUpdatedFilesManager = new UpdatedFilesManager();
protected CvsCommandOperation() {
this(DEFAULT_ADMIN_READER);
}
protected CvsCommandOperation(IAdminReader adminReader, IAdminWriter adminWriter) {
myAdminReader = adminReader;
myAdminWriter = adminWriter;
}
protected CvsCommandOperation(IAdminReader adminReader) {
myAdminReader = adminReader;
myAdminWriter = new AdminWriterOnCache(myUpdatedFilesManager, this);
}
abstract protected Command createCommand(CvsRootProvider root,
CvsExecutionEnvironment cvsExecutionEnvironment);
@Override
public void execute(CvsExecutionEnvironment executionEnvironment, boolean underReadAction) throws VcsException, CommandAbortedException {
if (runInExclusiveLock()) {
synchronized (CvsOperation.class) {
doExecute(executionEnvironment, underReadAction);
}
}
else {
doExecute(executionEnvironment, underReadAction);
}
}
@Override
public void appendSelfCvsRootProvider(@NotNull Collection<CvsEnvironment> roots) throws CannotFindCvsRootException {
roots.addAll(getAllCvsRoots());
}
private void doExecute(final CvsExecutionEnvironment executionEnvironment, boolean underReadAction) throws VcsException {
final VcsException[] exc = new VcsException[1];
final Runnable action = () -> {
try {
final ReadWriteStatistics statistics = executionEnvironment.getReadWriteStatistics();
final Collection<CvsRootProvider> allCvsRoots;
try {
allCvsRoots = getAllCvsRoots();
}
catch (CannotFindCvsRootException e) {
throw createVcsExceptionOn(e, null);
}
final IProgressViewer progressViewer = new IProgressViewer() {
@Override
public void setProgress(double value) {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null) progressIndicator.setFraction(value);
}
};
int count = 0;
final double step = 1.0 / allCvsRoots.size();
for (CvsRootProvider cvsRootProvider : allCvsRoots) {
try {
final double lowerBound = step * count;
final RangeProgressViewer partialProgress = new RangeProgressViewer(progressViewer, lowerBound, lowerBound + step);
myLastProcessedCvsRoot = cvsRootProvider.getCvsRootAsString();
execute(cvsRootProvider, executionEnvironment, statistics, partialProgress);
count++;
}
catch (IOCommandException e) {
LOG.info(e);
throw createVcsExceptionOn(e.getIOException(), cvsRootProvider.getCvsRootAsString());
}
catch (CommandException e) {
LOG.info(e);
final Exception underlyingException = e.getUnderlyingException();
if (underlyingException != null) {
LOG.info(underlyingException);
}
throw createVcsExceptionOn(underlyingException == null ? e : underlyingException, cvsRootProvider.getCvsRootAsString());
}
}
}
catch (VcsException e) {
exc[0] = e;
}
};
if (underReadAction) {
ApplicationManager.getApplication().runReadAction(action);
} else {
action.run();
}
if (exc[0] != null) throw exc[0];
}
private static VcsException createVcsExceptionOn(Exception e, String cvsRoot) {
LOG.debug(e);
final String message = getMessageFrom(null, e);
if (message == null) {
return new CvsException(CvsBundle.message("exception.text.unknown.error"), e, cvsRoot);
}
return new CvsException(message, e, cvsRoot);
}
private static String getMessageFrom(String initialMessage, Throwable e) {
if (e == null) return initialMessage;
String result = initialMessage;
if (result != null && !result.isEmpty()) return result;
result = e.getLocalizedMessage();
if (result == null || result.isEmpty()) result = e.getMessage();
return getMessageFrom(result, e.getCause());
}
protected abstract Collection<CvsRootProvider> getAllCvsRoots() throws CannotFindCvsRootException;
protected void execute(CvsRootProvider root,
final CvsExecutionEnvironment executionEnvironment,
ReadWriteStatistics statistics, IProgressViewer progressViewer)
throws CommandException, VcsException {
final IConnection connection = root.createConnection(statistics);
execute(root, executionEnvironment, connection, progressViewer);
}
public void execute(final CvsRootProvider root,
final CvsExecutionEnvironment executionEnvironment,
IConnection connection, IProgressViewer progressViewer) throws CommandException {
final Command command = createCommand(root, executionEnvironment);
if (command == null) return;
LOG.assertTrue(connection != null, root.getCvsRootAsString());
final CvsMessagesListener cvsMessagesListener = executionEnvironment.getCvsMessagesListener();
final long start = System.currentTimeMillis();
try {
final IClientEnvironment clientEnvironment = createEnvironment(connection, root,
myUpdatedFilesManager,
executionEnvironment);
myUpdatedFilesManager.setCvsFileSystem(clientEnvironment.getCvsFileSystem());
final EventManager eventManager = new EventManager(CvsApplicationLevelConfiguration.getCharset());
final IGlobalOptions globalOptions = command.getGlobalOptions();
final IRequestProcessor requestProcessor = new RequestProcessor(clientEnvironment,
globalOptions,
eventManager,
new StreamLogger(),
executionEnvironment.getCvsCommandStopper(),
PServerCvsSettings.getTimeoutMillis());
eventManager.addFileInfoListener(this);
eventManager.addEntryListener(this);
eventManager.addMessageListener(this);
eventManager.addModuleExpansionListener(this);
final CvsMessagesTranslator cvsMessagesTranslator = new CvsMessagesTranslator(cvsMessagesListener,
clientEnvironment.getCvsFileSystem(),
myUpdatedFilesManager,
root.getCvsRootAsString());
cvsMessagesTranslator.registerTo(eventManager);
final CvsEntriesManager cvsEntriesManager = CvsEntriesManager.getInstance();
if (shouldMakeChangesOnTheLocalFileSystem()) {
eventManager.addEntryListener(new MergeSupportingEntryListener(clientEnvironment, cvsEntriesManager, myUpdatedFilesManager));
eventManager.addMessageListener(myUpdatedFilesManager);
}
modifyOptions(command.getGlobalOptions());
final String commandString = composeCommandString(root, command);
cvsMessagesListener.commandStarted(commandString);
setProgressText(CvsBundle.message("progress.text.command.running.for.file", getOperationName(), root.getCvsRootAsString()));
try {
command.execute(requestProcessor, eventManager, eventManager, clientEnvironment, progressViewer);
}
catch (AuthenticationException e) {
throw root.processException(new CommandException(e, "Authentication problem"));
}
cvsMessagesTranslator.operationCompleted();
}
catch (CommandException t) {
throw root.processException(t);
}
finally {
cvsMessagesListener.commandFinished(composeCommandString(root, command),
System.currentTimeMillis() - start);
executeFinishActions();
}
}
@NonNls protected abstract String getOperationName();
@SuppressWarnings({"HardCodedStringLiteral"})
private static String composeCommandString(CvsRootProvider root, Command command) {
final StringBuilder result = new StringBuilder();
result.append(root.getLocalRoot());
result.append(" cvs ");
final GlobalOptions globalOptions = command.getGlobalOptions();
if (globalOptions.isCheckedOutFilesReadOnly()) result.append("-r ");
if (globalOptions.isDoNoChanges()) result.append("-n ");
if (globalOptions.isNoHistoryLogging()) result.append("-l ");
if (globalOptions.isSomeQuiet()) result.append("-q ");
result.append(command.getCvsCommandLine());
return result.toString();
}
protected boolean shouldMakeChangesOnTheLocalFileSystem() {
return true;
}
protected boolean runInExclusiveLock() {
return true;
}
private static void setProgressText(String text) {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null) progressIndicator.setText(text);
}
private IClientEnvironment createEnvironment(IConnection connection,
final CvsRootProvider root,
UpdatedFilesManager mergedFilesCollector,
CvsExecutionEnvironment cvsExecutionEnv) {
final File localRoot = getLocalRootFor(root);
final File adminRoot = getAdminRootFor(root);
LOG.assertTrue(localRoot != null, getClass().getName());
LOG.assertTrue(adminRoot != null, getClass().getName());
return new ClientEnvironment(connection,
localRoot, adminRoot, root.getCvsRoot(),
createLocalFileReader(),
createLocalFileWriter(root.getCvsRootAsString(),
mergedFilesCollector,
cvsExecutionEnv),
myAdminReader, myAdminWriter,
getIgnoreFileFilter(), new FileReadOnlyHandler(),
CvsApplicationLevelConfiguration.getCharset());
}
protected ILocalFileWriter createLocalFileWriter(String cvsRoot,
UpdatedFilesManager mergedFilesCollector,
CvsExecutionEnvironment cvsExecutionEnvironment) {
return new StoringLineSeparatorsLocalFileWriter(new ReceiveTextFilePreprocessor(createReceivedFileProcessor(mergedFilesCollector,
cvsExecutionEnvironment.getPostCvsActivity())),
cvsExecutionEnvironment.getErrorProcessor(),
myUpdatedFilesManager,
cvsRoot,
this);
}
protected ReceivedFileProcessor createReceivedFileProcessor(UpdatedFilesManager mergedFilesCollector, PostCvsActivity postCvsActivity) {
return ReceivedFileProcessor.DEFAULT;
}
protected ILocalFileReader createLocalFileReader() {
return new LocalFileReaderBasedOnVFS(new SendTextFilePreprocessor(), this);
}
protected IIgnoreFileFilter getIgnoreFileFilter() {
return new IgnoreFileFilterBasedOnCvsEntriesManager();
}
protected File getAdminRootFor(CvsRootProvider root) {
return root.getAdminRoot();
}
protected File getLocalRootFor(CvsRootProvider root) {
return root.getLocalRoot();
}
@Override
public void fileInfoGenerated(Object info) {
if (info instanceof UpdateFileInfo) {
final UpdateFileInfo updateFileInfo = ((UpdateFileInfo)info);
if (FileMessage.CONFLICT.equals(updateFileInfo.getType())) {
CvsUtil.addConflict(updateFileInfo.getFile());
}
}
}
@Override
public void gotEntry(FileObject fileObject, Entry entry) {
}
@Override
public void messageSent(String message, final byte[] byteMessage, boolean error, boolean tagged) {
}
@Override
public void moduleExpanded(String module) {
}
@Override
public boolean fileIsUnderProject(final VirtualFile file) {
return true;
}
@Override
public boolean fileIsUnderProject(File file) {
return true;
}
@Override
public String getLastProcessedCvsRoot() {
return myLastProcessedCvsRoot;
}
private static class MergeSupportingEntryListener implements IEntryListener {
private final IClientEnvironment myClientEnvironment;
private final CvsEntriesManager myCvsEntriesManager;
private final UpdatedFilesManager myUpdatedFilesManager;
private final Map<File, Entry> myFileToPreviousEntryMap = new HashMap<>();
public MergeSupportingEntryListener(IClientEnvironment clientEnvironment,
CvsEntriesManager cvsEntriesManager,
UpdatedFilesManager mergedFilesCollector) {
myClientEnvironment = clientEnvironment;
myCvsEntriesManager = cvsEntriesManager;
myUpdatedFilesManager = mergedFilesCollector;
}
@Override
public void gotEntry(FileObject fileObject, Entry entry) {
final IFileSystem localFileSystem = myClientEnvironment.getCvsFileSystem().getLocalFileSystem();
final File file = localFileSystem.getFile(fileObject);
if (myUpdatedFilesManager.fileIsNotUpdated(file)) {
return;
}
final File parent = file.getParentFile();
final VirtualFile virtualParent = CvsVfsUtil.findFileByIoFile(parent);
if (entry != null) {
final Entry previousEntry = myFileToPreviousEntryMap.containsKey(file)
?
myFileToPreviousEntryMap.get(file)
: CvsEntriesManager.getInstance().getCachedEntry(virtualParent, entry.getFileName());
if (previousEntry != null) {
myFileToPreviousEntryMap.put(file, previousEntry);
if (entry.isResultOfMerge()) {
final UpdatedFilesManager.CurrentMergedFileInfo info = myUpdatedFilesManager.getInfo(file);
info.registerNewRevision(previousEntry);
CvsUtil.saveRevisionForMergedFile(virtualParent,
info.getOriginalEntry(),
info.getRevisions());
}
}
}
else {
myCvsEntriesManager.removeEntryForFile(parent, fileObject.getName());
}
if (entry != null) {
myCvsEntriesManager.setEntryForFile(virtualParent, entry);
}
if (entry == null || !entry.isResultOfMerge()) {
CvsUtil.removeConflict(file);
}
}
}
@Override
public void binaryMessageSent(final byte[] bytes) {
}
}
| michaelgallacher/intellij-community | plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/common/CvsCommandOperation.java | Java | apache-2.0 | 19,583 |
class AddServiceAncestry < ActiveRecord::Migration[5.0]
class Service < ActiveRecord::Base
self.inheritance_column = :_type_disabled # disable STI
end
def update_service_parent(parent)
ancestry = [parent.ancestry.presence, parent.id].compact.join("/") if parent
Service.where(:service_id => parent.try(:id)).each do |svc|
svc.update_attributes(:ancestry => ancestry) if ancestry
update_service_parent(svc)
end
end
def up
add_column :services, :ancestry, :string
add_index :services, :ancestry
say_with_time("Converting Services from service_id ancestry") do
update_service_parent(nil)
end
remove_column :services, :service_id
end
def down
add_column :services, :service_id, :bigint
add_index :services, :service_id
say_with_time("Converting Services from ancestry to service_id") do
Service.all.each do |service|
parent_service_id = service.ancestry.split("/").last.to_i if service.ancestry.present?
service.update_attributes(:service_id => parent_service_id)
end
end
remove_column :services, :ancestry
end
end
| maas-ufcg/manageiq | db/migrate/20160310170333_add_service_ancestry.rb | Ruby | apache-2.0 | 1,136 |
//===-- BPFISelDAGToDAG.cpp - A dag to dag inst selector for BPF ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines a DAG pattern matching instruction selector for BPF,
// converting from a legalized dag to a BPF dag.
//
//===----------------------------------------------------------------------===//
#include "BPF.h"
#include "BPFRegisterInfo.h"
#include "BPFSubtarget.h"
#include "BPFTargetMachine.h"
#include "llvm/CodeGen/FunctionLoweringInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
#define DEBUG_TYPE "bpf-isel"
// Instruction Selector Implementation
namespace {
class BPFDAGToDAGISel : public SelectionDAGISel {
/// Subtarget - Keep a pointer to the BPFSubtarget around so that we can
/// make the right decision when generating code for different subtargets.
const BPFSubtarget *Subtarget;
public:
explicit BPFDAGToDAGISel(BPFTargetMachine &TM)
: SelectionDAGISel(TM), Subtarget(nullptr) {
curr_func_ = nullptr;
}
StringRef getPassName() const override {
return "BPF DAG->DAG Pattern Instruction Selection";
}
bool runOnMachineFunction(MachineFunction &MF) override {
// Reset the subtarget each time through.
Subtarget = &MF.getSubtarget<BPFSubtarget>();
return SelectionDAGISel::runOnMachineFunction(MF);
}
void PreprocessISelDAG() override;
bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintCode,
std::vector<SDValue> &OutOps) override;
private:
// Include the pieces autogenerated from the target description.
#include "BPFGenDAGISel.inc"
void Select(SDNode *N) override;
// Complex Pattern for address selection.
bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset);
bool SelectFIAddr(SDValue Addr, SDValue &Base, SDValue &Offset);
// Node preprocessing cases
void PreprocessLoad(SDNode *Node, SelectionDAG::allnodes_iterator &I);
void PreprocessCopyToReg(SDNode *Node);
void PreprocessTrunc(SDNode *Node, SelectionDAG::allnodes_iterator &I);
// Find constants from a constant structure
typedef std::vector<unsigned char> val_vec_type;
bool fillGenericConstant(const DataLayout &DL, const Constant *CV,
val_vec_type &Vals, uint64_t Offset);
bool fillConstantDataArray(const DataLayout &DL, const ConstantDataArray *CDA,
val_vec_type &Vals, int Offset);
bool fillConstantArray(const DataLayout &DL, const ConstantArray *CA,
val_vec_type &Vals, int Offset);
bool fillConstantStruct(const DataLayout &DL, const ConstantStruct *CS,
val_vec_type &Vals, int Offset);
bool getConstantFieldValue(const GlobalAddressSDNode *Node, uint64_t Offset,
uint64_t Size, unsigned char *ByteSeq);
bool checkLoadDef(unsigned DefReg, unsigned match_load_op);
// Mapping from ConstantStruct global value to corresponding byte-list values
std::map<const void *, val_vec_type> cs_vals_;
// Mapping from vreg to load memory opcode
std::map<unsigned, unsigned> load_to_vreg_;
// Current function
const Function *curr_func_;
};
} // namespace
// ComplexPattern used on BPF Load/Store instructions
bool BPFDAGToDAGISel::SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
// if Address is FI, get the TargetFrameIndex.
SDLoc DL(Addr);
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
Offset = CurDAG->getTargetConstant(0, DL, MVT::i64);
return true;
}
if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
Addr.getOpcode() == ISD::TargetGlobalAddress)
return false;
// Addresses of the form Addr+const or Addr|const
if (CurDAG->isBaseWithConstantOffset(Addr)) {
ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
if (isInt<16>(CN->getSExtValue())) {
// If the first operand is a FI, get the TargetFI Node
if (FrameIndexSDNode *FIN =
dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
else
Base = Addr.getOperand(0);
Offset = CurDAG->getTargetConstant(CN->getSExtValue(), DL, MVT::i64);
return true;
}
}
Base = Addr;
Offset = CurDAG->getTargetConstant(0, DL, MVT::i64);
return true;
}
// ComplexPattern used on BPF FI instruction
bool BPFDAGToDAGISel::SelectFIAddr(SDValue Addr, SDValue &Base,
SDValue &Offset) {
SDLoc DL(Addr);
if (!CurDAG->isBaseWithConstantOffset(Addr))
return false;
// Addresses of the form Addr+const or Addr|const
ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
if (isInt<16>(CN->getSExtValue())) {
// If the first operand is a FI, get the TargetFI Node
if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
else
return false;
Offset = CurDAG->getTargetConstant(CN->getSExtValue(), DL, MVT::i64);
return true;
}
return false;
}
bool BPFDAGToDAGISel::SelectInlineAsmMemoryOperand(
const SDValue &Op, unsigned ConstraintCode, std::vector<SDValue> &OutOps) {
SDValue Op0, Op1;
switch (ConstraintCode) {
default:
return true;
case InlineAsm::Constraint_m: // memory
if (!SelectAddr(Op, Op0, Op1))
return true;
break;
}
SDLoc DL(Op);
SDValue AluOp = CurDAG->getTargetConstant(ISD::ADD, DL, MVT::i32);;
OutOps.push_back(Op0);
OutOps.push_back(Op1);
OutOps.push_back(AluOp);
return false;
}
void BPFDAGToDAGISel::Select(SDNode *Node) {
unsigned Opcode = Node->getOpcode();
// If we have a custom node, we already have selected!
if (Node->isMachineOpcode()) {
LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
return;
}
// tablegen selection should be handled here.
switch (Opcode) {
default:
break;
case ISD::SDIV: {
DebugLoc Empty;
const DebugLoc &DL = Node->getDebugLoc();
if (DL != Empty)
errs() << "Error at line " << DL.getLine() << ": ";
else
errs() << "Error: ";
errs() << "Unsupport signed division for DAG: ";
Node->print(errs(), CurDAG);
errs() << "Please convert to unsigned div/mod.\n";
break;
}
case ISD::INTRINSIC_W_CHAIN: {
unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
switch (IntNo) {
case Intrinsic::bpf_load_byte:
case Intrinsic::bpf_load_half:
case Intrinsic::bpf_load_word: {
SDLoc DL(Node);
SDValue Chain = Node->getOperand(0);
SDValue N1 = Node->getOperand(1);
SDValue Skb = Node->getOperand(2);
SDValue N3 = Node->getOperand(3);
SDValue R6Reg = CurDAG->getRegister(BPF::R6, MVT::i64);
Chain = CurDAG->getCopyToReg(Chain, DL, R6Reg, Skb, SDValue());
Node = CurDAG->UpdateNodeOperands(Node, Chain, N1, R6Reg, N3);
break;
}
}
break;
}
case ISD::FrameIndex: {
int FI = cast<FrameIndexSDNode>(Node)->getIndex();
EVT VT = Node->getValueType(0);
SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT);
unsigned Opc = BPF::MOV_rr;
if (Node->hasOneUse()) {
CurDAG->SelectNodeTo(Node, Opc, VT, TFI);
return;
}
ReplaceNode(Node, CurDAG->getMachineNode(Opc, SDLoc(Node), VT, TFI));
return;
}
}
// Select the default instruction
SelectCode(Node);
}
void BPFDAGToDAGISel::PreprocessLoad(SDNode *Node,
SelectionDAG::allnodes_iterator &I) {
union {
uint8_t c[8];
uint16_t s;
uint32_t i;
uint64_t d;
} new_val; // hold up the constant values replacing loads.
bool to_replace = false;
SDLoc DL(Node);
const LoadSDNode *LD = cast<LoadSDNode>(Node);
uint64_t size = LD->getMemOperand()->getSize();
if (!size || size > 8 || (size & (size - 1)))
return;
SDNode *LDAddrNode = LD->getOperand(1).getNode();
// Match LDAddr against either global_addr or (global_addr + offset)
unsigned opcode = LDAddrNode->getOpcode();
if (opcode == ISD::ADD) {
SDValue OP1 = LDAddrNode->getOperand(0);
SDValue OP2 = LDAddrNode->getOperand(1);
// We want to find the pattern global_addr + offset
SDNode *OP1N = OP1.getNode();
if (OP1N->getOpcode() <= ISD::BUILTIN_OP_END || OP1N->getNumOperands() == 0)
return;
LLVM_DEBUG(dbgs() << "Check candidate load: "; LD->dump(); dbgs() << '\n');
const GlobalAddressSDNode *GADN =
dyn_cast<GlobalAddressSDNode>(OP1N->getOperand(0).getNode());
const ConstantSDNode *CDN = dyn_cast<ConstantSDNode>(OP2.getNode());
if (GADN && CDN)
to_replace =
getConstantFieldValue(GADN, CDN->getZExtValue(), size, new_val.c);
} else if (LDAddrNode->getOpcode() > ISD::BUILTIN_OP_END &&
LDAddrNode->getNumOperands() > 0) {
LLVM_DEBUG(dbgs() << "Check candidate load: "; LD->dump(); dbgs() << '\n');
SDValue OP1 = LDAddrNode->getOperand(0);
if (const GlobalAddressSDNode *GADN =
dyn_cast<GlobalAddressSDNode>(OP1.getNode()))
to_replace = getConstantFieldValue(GADN, 0, size, new_val.c);
}
if (!to_replace)
return;
// replacing the old with a new value
uint64_t val;
if (size == 1)
val = new_val.c[0];
else if (size == 2)
val = new_val.s;
else if (size == 4)
val = new_val.i;
else {
val = new_val.d;
}
LLVM_DEBUG(dbgs() << "Replacing load of size " << size << " with constant "
<< val << '\n');
SDValue NVal = CurDAG->getConstant(val, DL, MVT::i64);
// After replacement, the current node is dead, we need to
// go backward one step to make iterator still work
I--;
SDValue From[] = {SDValue(Node, 0), SDValue(Node, 1)};
SDValue To[] = {NVal, NVal};
CurDAG->ReplaceAllUsesOfValuesWith(From, To, 2);
I++;
// It is safe to delete node now
CurDAG->DeleteNode(Node);
}
void BPFDAGToDAGISel::PreprocessISelDAG() {
// Iterate through all nodes, interested in the following cases:
//
// . loads from ConstantStruct or ConstantArray of constructs
// which can be turns into constant itself, with this we can
// avoid reading from read-only section at runtime.
//
// . reg truncating is often the result of 8/16/32bit->64bit or
// 8/16bit->32bit conversion. If the reg value is loaded with
// masked byte width, the AND operation can be removed since
// BPF LOAD already has zero extension.
//
// This also solved a correctness issue.
// In BPF socket-related program, e.g., __sk_buff->{data, data_end}
// are 32-bit registers, but later on, kernel verifier will rewrite
// it with 64-bit value. Therefore, truncating the value after the
// load will result in incorrect code.
// clear the load_to_vreg_ map so that we have a clean start
// for this function.
if (!curr_func_) {
curr_func_ = FuncInfo->Fn;
} else if (curr_func_ != FuncInfo->Fn) {
load_to_vreg_.clear();
curr_func_ = FuncInfo->Fn;
}
for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
E = CurDAG->allnodes_end();
I != E;) {
SDNode *Node = &*I++;
unsigned Opcode = Node->getOpcode();
if (Opcode == ISD::LOAD)
PreprocessLoad(Node, I);
else if (Opcode == ISD::CopyToReg)
PreprocessCopyToReg(Node);
else if (Opcode == ISD::AND)
PreprocessTrunc(Node, I);
}
}
bool BPFDAGToDAGISel::getConstantFieldValue(const GlobalAddressSDNode *Node,
uint64_t Offset, uint64_t Size,
unsigned char *ByteSeq) {
const GlobalVariable *V = dyn_cast<GlobalVariable>(Node->getGlobal());
if (!V || !V->hasInitializer())
return false;
const Constant *Init = V->getInitializer();
const DataLayout &DL = CurDAG->getDataLayout();
val_vec_type TmpVal;
auto it = cs_vals_.find(static_cast<const void *>(Init));
if (it != cs_vals_.end()) {
TmpVal = it->second;
} else {
uint64_t total_size = 0;
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(Init))
total_size =
DL.getStructLayout(cast<StructType>(CS->getType()))->getSizeInBytes();
else if (const ConstantArray *CA = dyn_cast<ConstantArray>(Init))
total_size = DL.getTypeAllocSize(CA->getType()->getElementType()) *
CA->getNumOperands();
else
return false;
val_vec_type Vals(total_size, 0);
if (fillGenericConstant(DL, Init, Vals, 0) == false)
return false;
cs_vals_[static_cast<const void *>(Init)] = Vals;
TmpVal = std::move(Vals);
}
// test whether host endianness matches target
union {
uint8_t c[2];
uint16_t s;
} test_buf;
uint16_t test_val = 0x2345;
if (DL.isLittleEndian())
support::endian::write16le(test_buf.c, test_val);
else
support::endian::write16be(test_buf.c, test_val);
bool endian_match = test_buf.s == test_val;
for (uint64_t i = Offset, j = 0; i < Offset + Size; i++, j++)
ByteSeq[j] = endian_match ? TmpVal[i] : TmpVal[Offset + Size - 1 - j];
return true;
}
bool BPFDAGToDAGISel::fillGenericConstant(const DataLayout &DL,
const Constant *CV,
val_vec_type &Vals, uint64_t Offset) {
uint64_t Size = DL.getTypeAllocSize(CV->getType());
if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
return true; // already done
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
uint64_t val = CI->getZExtValue();
LLVM_DEBUG(dbgs() << "Byte array at offset " << Offset << " with value "
<< val << '\n');
if (Size > 8 || (Size & (Size - 1)))
return false;
// Store based on target endian
for (uint64_t i = 0; i < Size; ++i) {
Vals[Offset + i] = DL.isLittleEndian()
? ((val >> (i * 8)) & 0xFF)
: ((val >> ((Size - i - 1) * 8)) & 0xFF);
}
return true;
}
if (const ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(CV))
return fillConstantDataArray(DL, CDA, Vals, Offset);
if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV))
return fillConstantArray(DL, CA, Vals, Offset);
if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
return fillConstantStruct(DL, CVS, Vals, Offset);
return false;
}
bool BPFDAGToDAGISel::fillConstantDataArray(const DataLayout &DL,
const ConstantDataArray *CDA,
val_vec_type &Vals, int Offset) {
for (unsigned i = 0, e = CDA->getNumElements(); i != e; ++i) {
if (fillGenericConstant(DL, CDA->getElementAsConstant(i), Vals, Offset) ==
false)
return false;
Offset += DL.getTypeAllocSize(CDA->getElementAsConstant(i)->getType());
}
return true;
}
bool BPFDAGToDAGISel::fillConstantArray(const DataLayout &DL,
const ConstantArray *CA,
val_vec_type &Vals, int Offset) {
for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
if (fillGenericConstant(DL, CA->getOperand(i), Vals, Offset) == false)
return false;
Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
}
return true;
}
bool BPFDAGToDAGISel::fillConstantStruct(const DataLayout &DL,
const ConstantStruct *CS,
val_vec_type &Vals, int Offset) {
const StructLayout *Layout = DL.getStructLayout(CS->getType());
for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
const Constant *Field = CS->getOperand(i);
uint64_t SizeSoFar = Layout->getElementOffset(i);
if (fillGenericConstant(DL, Field, Vals, Offset + SizeSoFar) == false)
return false;
}
return true;
}
void BPFDAGToDAGISel::PreprocessCopyToReg(SDNode *Node) {
const RegisterSDNode *RegN = dyn_cast<RegisterSDNode>(Node->getOperand(1));
if (!RegN || !TargetRegisterInfo::isVirtualRegister(RegN->getReg()))
return;
const LoadSDNode *LD = dyn_cast<LoadSDNode>(Node->getOperand(2));
if (!LD)
return;
// Assign a load value to a virtual register. record its load width
unsigned mem_load_op = 0;
switch (LD->getMemOperand()->getSize()) {
default:
return;
case 4:
mem_load_op = BPF::LDW;
break;
case 2:
mem_load_op = BPF::LDH;
break;
case 1:
mem_load_op = BPF::LDB;
break;
}
LLVM_DEBUG(dbgs() << "Find Load Value to VReg "
<< TargetRegisterInfo::virtReg2Index(RegN->getReg())
<< '\n');
load_to_vreg_[RegN->getReg()] = mem_load_op;
}
void BPFDAGToDAGISel::PreprocessTrunc(SDNode *Node,
SelectionDAG::allnodes_iterator &I) {
ConstantSDNode *MaskN = dyn_cast<ConstantSDNode>(Node->getOperand(1));
if (!MaskN)
return;
// The Reg operand should be a virtual register, which is defined
// outside the current basic block. DAG combiner has done a pretty
// good job in removing truncating inside a single basic block except
// when the Reg operand comes from bpf_load_[byte | half | word] for
// which the generic optimizer doesn't understand their results are
// zero extended.
SDValue BaseV = Node->getOperand(0);
if (BaseV.getOpcode() == ISD::INTRINSIC_W_CHAIN) {
unsigned IntNo = cast<ConstantSDNode>(BaseV->getOperand(1))->getZExtValue();
uint64_t MaskV = MaskN->getZExtValue();
if (!((IntNo == Intrinsic::bpf_load_byte && MaskV == 0xFF) ||
(IntNo == Intrinsic::bpf_load_half && MaskV == 0xFFFF) ||
(IntNo == Intrinsic::bpf_load_word && MaskV == 0xFFFFFFFF)))
return;
LLVM_DEBUG(dbgs() << "Remove the redundant AND operation in: ";
Node->dump(); dbgs() << '\n');
I--;
CurDAG->ReplaceAllUsesWith(SDValue(Node, 0), BaseV);
I++;
CurDAG->DeleteNode(Node);
return;
}
// Multiple basic blocks case.
if (BaseV.getOpcode() != ISD::CopyFromReg)
return;
unsigned match_load_op = 0;
switch (MaskN->getZExtValue()) {
default:
return;
case 0xFFFFFFFF:
match_load_op = BPF::LDW;
break;
case 0xFFFF:
match_load_op = BPF::LDH;
break;
case 0xFF:
match_load_op = BPF::LDB;
break;
}
const RegisterSDNode *RegN =
dyn_cast<RegisterSDNode>(BaseV.getNode()->getOperand(1));
if (!RegN || !TargetRegisterInfo::isVirtualRegister(RegN->getReg()))
return;
unsigned AndOpReg = RegN->getReg();
LLVM_DEBUG(dbgs() << "Examine " << printReg(AndOpReg) << '\n');
// Examine the PHI insns in the MachineBasicBlock to found out the
// definitions of this virtual register. At this stage (DAG2DAG
// transformation), only PHI machine insns are available in the machine basic
// block.
MachineBasicBlock *MBB = FuncInfo->MBB;
MachineInstr *MII = nullptr;
for (auto &MI : *MBB) {
for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
const MachineOperand &MOP = MI.getOperand(i);
if (!MOP.isReg() || !MOP.isDef())
continue;
unsigned Reg = MOP.getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg) && Reg == AndOpReg) {
MII = &MI;
break;
}
}
}
if (MII == nullptr) {
// No phi definition in this block.
if (!checkLoadDef(AndOpReg, match_load_op))
return;
} else {
// The PHI node looks like:
// %2 = PHI %0, <%bb.1>, %1, <%bb.3>
// Trace each incoming definition, e.g., (%0, %bb.1) and (%1, %bb.3)
// The AND operation can be removed if both %0 in %bb.1 and %1 in
// %bb.3 are defined with a load matching the MaskN.
LLVM_DEBUG(dbgs() << "Check PHI Insn: "; MII->dump(); dbgs() << '\n');
unsigned PrevReg = -1;
for (unsigned i = 0; i < MII->getNumOperands(); ++i) {
const MachineOperand &MOP = MII->getOperand(i);
if (MOP.isReg()) {
if (MOP.isDef())
continue;
PrevReg = MOP.getReg();
if (!TargetRegisterInfo::isVirtualRegister(PrevReg))
return;
if (!checkLoadDef(PrevReg, match_load_op))
return;
}
}
}
LLVM_DEBUG(dbgs() << "Remove the redundant AND operation in: "; Node->dump();
dbgs() << '\n');
I--;
CurDAG->ReplaceAllUsesWith(SDValue(Node, 0), BaseV);
I++;
CurDAG->DeleteNode(Node);
}
bool BPFDAGToDAGISel::checkLoadDef(unsigned DefReg, unsigned match_load_op) {
auto it = load_to_vreg_.find(DefReg);
if (it == load_to_vreg_.end())
return false; // The definition of register is not exported yet.
return it->second == match_load_op;
}
FunctionPass *llvm::createBPFISelDag(BPFTargetMachine &TM) {
return new BPFDAGToDAGISel(TM);
}
| apple/swift-llvm | lib/Target/BPF/BPFISelDAGToDAG.cpp | C++ | apache-2.0 | 21,614 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.eql.plugin;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.xpack.core.async.DeleteAsyncResultAction;
import org.elasticsearch.xpack.core.async.DeleteAsyncResultRequest;
import java.util.List;
import static org.elasticsearch.rest.RestRequest.Method.DELETE;
public class RestEqlDeleteAsyncResultAction extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(DELETE, "/_eql/search/{id}"));
}
@Override
public String getName() {
return "eql_delete_async_result";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
DeleteAsyncResultRequest delete = new DeleteAsyncResultRequest(request.param("id"));
return channel -> client.execute(DeleteAsyncResultAction.INSTANCE, delete, new RestToXContentListener<>(channel));
}
}
| robin13/elasticsearch | x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/RestEqlDeleteAsyncResultAction.java | Java | apache-2.0 | 1,334 |
# 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.
from ._executor import MesosExecutorDriverImpl as MesosExecutorDriver
| Gilbert88/mesos | src/python/executor/src/mesos/executor/__init__.py | Python | apache-2.0 | 855 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ContainerRegistry.Models
{
/// <summary>
/// Defines values for ProvisioningState.
/// </summary>
public static class ProvisioningState
{
public const string Creating = "Creating";
public const string Updating = "Updating";
public const string Deleting = "Deleting";
public const string Succeeded = "Succeeded";
public const string Failed = "Failed";
public const string Canceled = "Canceled";
}
}
| SiddharthChatrolaMs/azure-sdk-for-net | src/SDKs/ContainerRegistry/Management.ContainerRegistry/Generated/Models/ProvisioningState.cs | C# | apache-2.0 | 861 |
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.server.service;
import java.io.File;
import java.sql.SQLException;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.GoConfigFileDao;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.materials.Materials;
import com.thoughtworks.go.config.materials.SubprocessExecutionContext;
import com.thoughtworks.go.config.materials.svn.SvnMaterial;
import com.thoughtworks.go.domain.MaterialRevisions;
import com.thoughtworks.go.domain.Pipeline;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.svn.Subversion;
import com.thoughtworks.go.helper.MaterialsMother;
import com.thoughtworks.go.helper.PipelineMother;
import com.thoughtworks.go.helper.SvnTestRepo;
import com.thoughtworks.go.helper.SvnTestRepoWithExternal;
import com.thoughtworks.go.helper.TestRepo;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.materials.MaterialDatabaseUpdater;
import com.thoughtworks.go.server.scheduling.BuildCauseProducerService;
import com.thoughtworks.go.server.service.result.ServerHealthStateOperationResult;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.FileUtil;
import com.thoughtworks.go.util.TestFileUtil;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:WEB-INF/applicationContext-global.xml",
"classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
"classpath:WEB-INF/applicationContext-acegi-security.xml"
})
public class BuildCauseProducerServiceIntegrationSvnTest {
private static final String STAGE_NAME = "dev";
@Autowired private GoConfigService goConfigService;
@Autowired private GoConfigFileDao goConfigFileDao;
@Autowired private PipelineScheduleQueue pipelineScheduleQueue;
@Autowired private BuildCauseProducerService buildCauseProducerService;
@Autowired private MaterialDatabaseUpdater materialDatabaseUpdater;
@Autowired private SubprocessExecutionContext subprocessExecutionContext;
@Autowired PipelineService pipelineService;
@Autowired private DatabaseAccessHelper dbHelper;
private static GoConfigFileHelper configHelper = new GoConfigFileHelper();
public Subversion repository;
public SvnMaterial svnMaterial;
public static SvnTestRepo svnRepository;
private Pipeline latestPipeline;
private File workingFolder;
PipelineConfig mingleConfig;
@Before
public void setup() throws Exception {
dbHelper.onSetUp();
configHelper.usingCruiseConfigDao(goConfigFileDao);
configHelper.onSetUp();
workingFolder = TestFileUtil.createTempFolder("workingFolder");
}
private void repositoryForMaterial(SvnTestRepo svnRepository) {
this.svnRepository = svnRepository;
svnMaterial = MaterialsMother.svnMaterial(svnRepository.projectRepositoryUrl(), "foo", "user", "pass", true, "*.doc");
mingleConfig = configHelper.addPipeline("cruise", STAGE_NAME, svnMaterial.config(), "unit", "functional");
}
@After
public void teardown() throws Exception {
TestRepo.internalTearDown();
dbHelper.onTearDown();
FileUtil.deleteFolder(goConfigService.artifactsDir());
FileUtil.deleteFolder(workingFolder);
TestRepo.internalTearDown();
pipelineScheduleQueue.clear();
configHelper.onTearDown();
}
@Test
public void shouldCreateBuildCauseWithModifications() throws Exception {
repositoryForMaterial(new SvnTestRepo("svnTestRepo"));
prepareAPipelineWithHistory();
checkInFiles("foo");
ServerHealthStateOperationResult result = new ServerHealthStateOperationResult();
materialDatabaseUpdater.updateMaterial(svnMaterial);
buildCauseProducerService.autoSchedulePipeline(CaseInsensitiveString.str(mingleConfig.name()), result, 123);
assertThat(result.canContinue(), is(true));
BuildCause mingleBuildCause = pipelineScheduleQueue.toBeScheduled().get(CaseInsensitiveString.str(mingleConfig.name()));
MaterialRevisions materialRevisions = mingleBuildCause.getMaterialRevisions();
assertThat(materialRevisions.getRevisions().size(), is(1));
Materials materials = materialRevisions.getMaterials();
assertThat(materials.size(), is(1));
assertThat(materials.get(0), is((Material) svnMaterial));
}
@Test
public void shouldCreateBuildCauseWithModificationsForSvnRepoWithExternal() throws Exception {
SvnTestRepoWithExternal repo = new SvnTestRepoWithExternal();
repositoryForMaterial(repo);
prepareAPipelineWithHistory();
checkInFiles("foo");
ServerHealthStateOperationResult result = new ServerHealthStateOperationResult();
materialDatabaseUpdater.updateMaterial(svnMaterial);
buildCauseProducerService.autoSchedulePipeline(CaseInsensitiveString.str(mingleConfig.name()), result, 123);
assertThat(result.canContinue(), is(true));
BuildCause mingleBuildCause = pipelineScheduleQueue.toBeScheduled().get(CaseInsensitiveString.str(mingleConfig.name()));
MaterialRevisions materialRevisions = mingleBuildCause.getMaterialRevisions();
assertThat(materialRevisions.getRevisions().size(), is(2));
Materials materials = materialRevisions.getMaterials();
assertThat(materials.size(), is(2));
assertThat(materials.get(0), is((Material) svnMaterial));
SvnMaterial external = (SvnMaterial) materials.get(1);
assertThat(external.getUrl(), is(repo.externalRepositoryUrl()));
}
private void prepareAPipelineWithHistory() throws SQLException {
MaterialRevisions materialRevisions = new MaterialRevisions();
materialRevisions.addRevision(svnMaterial, svnMaterial.latestModification(workingFolder, subprocessExecutionContext));
BuildCause buildCause = BuildCause.createWithModifications(materialRevisions, "");
latestPipeline = PipelineMother.schedule(mingleConfig, buildCause);
latestPipeline = dbHelper.savePipelineWithStagesAndMaterials(latestPipeline);
dbHelper.passStage(latestPipeline.getStages().first());
}
private void checkInFiles(String... files) throws Exception {
for (String fileName : files) {
File file = new File(workingFolder, fileName);
FileUtils.writeStringToFile(file, "bla");
svnRepository.checkInOneFile(fileName, "random commit " + fileName);
}
}
} | beano/gocd | server/test/integration/com/thoughtworks/go/server/service/BuildCauseProducerServiceIntegrationSvnTest.java | Java | apache-2.0 | 7,844 |
/*
* 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.sql.catalyst.optimizer
import scala.reflect.runtime.universe.TypeTag
import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.plans.{Inner, PlanTest}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules.RuleExecutor
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{StringType, StructType}
class ColumnPruningSuite extends PlanTest {
object Optimize extends RuleExecutor[LogicalPlan] {
val batches = Batch("Column pruning", FixedPoint(100),
PushPredicateThroughNonJoin,
ColumnPruning,
RemoveNoopOperators,
CollapseProject) :: Nil
}
test("Column pruning for Generate when Generate.unrequiredChildIndex = child.output") {
val input = LocalRelation('a.int, 'b.int, 'c.array(StringType))
val query =
input
.generate(Explode('c), outputNames = "explode" :: Nil)
.select('c, 'explode)
.analyze
val optimized = Optimize.execute(query)
val correctAnswer =
input
.select('c)
.generate(Explode('c), outputNames = "explode" :: Nil)
.analyze
comparePlans(optimized, correctAnswer)
}
test("Fill Generate.unrequiredChildIndex if possible") {
val input = LocalRelation('b.array(StringType))
val query =
input
.generate(Explode('b), outputNames = "explode" :: Nil)
.select(('explode + 1).as("result"))
.analyze
val optimized = Optimize.execute(query)
val correctAnswer =
input
.generate(Explode('b), unrequiredChildIndex = input.output.zipWithIndex.map(_._2),
outputNames = "explode" :: Nil)
.select(('explode + 1).as("result"))
.analyze
comparePlans(optimized, correctAnswer)
}
test("Another fill Generate.unrequiredChildIndex if possible") {
val input = LocalRelation('a.int, 'b.int, 'c1.string, 'c2.string)
val query =
input
.generate(Explode(CreateArray(Seq('c1, 'c2))), outputNames = "explode" :: Nil)
.select('a, 'c1, 'explode)
.analyze
val optimized = Optimize.execute(query)
val correctAnswer =
input
.select('a, 'c1, 'c2)
.generate(Explode(CreateArray(Seq('c1, 'c2))),
unrequiredChildIndex = Seq(2),
outputNames = "explode" :: Nil)
.analyze
comparePlans(optimized, correctAnswer)
}
test("Nested column pruning for Generate") {
def runTest(
origGenerator: Generator,
replacedGenerator: Seq[String] => Generator,
aliasedExprs: Seq[String] => Seq[Expression],
unrequiredChildIndex: Seq[Int],
generatorOutputNames: Seq[String]): Unit = {
withSQLConf(SQLConf.NESTED_PRUNING_ON_EXPRESSIONS.key -> "true") {
val structType = StructType.fromDDL("d double, e array<string>, f double, g double, " +
"h array<struct<h1: int, h2: double>>")
val input = LocalRelation('a.int, 'b.int, 'c.struct(structType))
val generatorOutputs = generatorOutputNames.map(UnresolvedAttribute(_))
val selectedExprs = Seq(UnresolvedAttribute("a"), 'c.getField("d")) ++
generatorOutputs
val query =
input
.generate(origGenerator, outputNames = generatorOutputNames)
.select(selectedExprs: _*)
.analyze
val optimized = Optimize.execute(query)
val aliases = NestedColumnAliasingSuite.collectGeneratedAliases(optimized).toSeq
val selectedFields = UnresolvedAttribute("a") +: aliasedExprs(aliases)
val finalSelectedExprs = Seq(UnresolvedAttribute("a"), $"${aliases(0)}".as("c.d")) ++
generatorOutputs
val correctAnswer =
input
.select(selectedFields: _*)
.generate(replacedGenerator(aliases),
unrequiredChildIndex = unrequiredChildIndex,
outputNames = generatorOutputNames)
.select(finalSelectedExprs: _*)
.analyze
comparePlans(optimized, correctAnswer)
}
}
runTest(
Explode('c.getField("e")),
aliases => Explode($"${aliases(1)}".as("c.e")),
aliases => Seq('c.getField("d").as(aliases(0)), 'c.getField("e").as(aliases(1))),
Seq(2),
Seq("explode")
)
runTest(Stack(2 :: 'c.getField("f") :: 'c.getField("g") :: Nil),
aliases => Stack(2 :: $"${aliases(1)}".as("c.f") :: $"${aliases(2)}".as("c.g") :: Nil),
aliases => Seq(
'c.getField("d").as(aliases(0)),
'c.getField("f").as(aliases(1)),
'c.getField("g").as(aliases(2))),
Seq(2, 3),
Seq("stack")
)
runTest(
PosExplode('c.getField("e")),
aliases => PosExplode($"${aliases(1)}".as("c.e")),
aliases => Seq('c.getField("d").as(aliases(0)), 'c.getField("e").as(aliases(1))),
Seq(2),
Seq("pos", "explode")
)
runTest(
Inline('c.getField("h")),
aliases => Inline($"${aliases(1)}".as("c.h")),
aliases => Seq('c.getField("d").as(aliases(0)), 'c.getField("h").as(aliases(1))),
Seq(2),
Seq("h1", "h2")
)
}
test("Column pruning for Project on Sort") {
val input = LocalRelation('a.int, 'b.string, 'c.double)
val query = input.orderBy('b.asc).select('a).analyze
val optimized = Optimize.execute(query)
val correctAnswer = input.select('a, 'b).orderBy('b.asc).select('a).analyze
comparePlans(optimized, correctAnswer)
}
test("Column pruning for Expand") {
val input = LocalRelation('a.int, 'b.string, 'c.double)
val query =
Aggregate(
Seq('aa, 'gid),
Seq(sum('c).as("sum")),
Expand(
Seq(
Seq('a, 'b, 'c, Literal.create(null, StringType), 1),
Seq('a, 'b, 'c, 'a, 2)),
Seq('a, 'b, 'c, 'aa.int, 'gid.int),
input)).analyze
val optimized = Optimize.execute(query)
val expected =
Aggregate(
Seq('aa, 'gid),
Seq(sum('c).as("sum")),
Expand(
Seq(
Seq('c, Literal.create(null, StringType), 1),
Seq('c, 'a, 2)),
Seq('c, 'aa.int, 'gid.int),
Project(Seq('a, 'c),
input))).analyze
comparePlans(optimized, expected)
}
test("Column pruning on Filter") {
val input = LocalRelation('a.int, 'b.string, 'c.double)
val plan1 = Filter('a > 1, input).analyze
comparePlans(Optimize.execute(plan1), plan1)
val query = Project('a :: Nil, Filter('c > Literal(0.0), input)).analyze
comparePlans(Optimize.execute(query), query)
val plan2 = Filter('b > 1, Project(Seq('a, 'b), input)).analyze
val expected2 = Project(Seq('a, 'b), Filter('b > 1, input)).analyze
comparePlans(Optimize.execute(plan2), expected2)
val plan3 = Project(Seq('a), Filter('b > 1, Project(Seq('a, 'b), input))).analyze
val expected3 = Project(Seq('a), Filter('b > 1, input)).analyze
comparePlans(Optimize.execute(plan3), expected3)
}
test("Column pruning on except/intersect/distinct") {
val input = LocalRelation('a.int, 'b.string, 'c.double)
val query = Project('a :: Nil, Except(input, input, isAll = false)).analyze
comparePlans(Optimize.execute(query), query)
val query2 = Project('a :: Nil, Intersect(input, input, isAll = false)).analyze
comparePlans(Optimize.execute(query2), query2)
val query3 = Project('a :: Nil, Distinct(input)).analyze
comparePlans(Optimize.execute(query3), query3)
}
test("Column pruning on Project") {
val input = LocalRelation('a.int, 'b.string, 'c.double)
val query = Project('a :: Nil, Project(Seq('a, 'b), input)).analyze
val expected = Project(Seq('a), input).analyze
comparePlans(Optimize.execute(query), expected)
}
test("Eliminate the Project with an empty projectList") {
val input = OneRowRelation()
val expected = Project(Literal(1).as("1") :: Nil, input).analyze
val query1 =
Project(Literal(1).as("1") :: Nil, Project(Literal(1).as("1") :: Nil, input)).analyze
comparePlans(Optimize.execute(query1), expected)
val query2 =
Project(Literal(1).as("1") :: Nil, Project(Nil, input)).analyze
comparePlans(Optimize.execute(query2), expected)
// to make sure the top Project will not be removed.
comparePlans(Optimize.execute(expected), expected)
}
test("column pruning for group") {
val testRelation = LocalRelation('a.int, 'b.int, 'c.int)
val originalQuery =
testRelation
.groupBy('a)('a, count('b))
.select('a)
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer =
testRelation
.select('a)
.groupBy('a)('a).analyze
comparePlans(optimized, correctAnswer)
}
test("column pruning for group with alias") {
val testRelation = LocalRelation('a.int, 'b.int, 'c.int)
val originalQuery =
testRelation
.groupBy('a)('a as 'c, count('b))
.select('c)
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer =
testRelation
.select('a)
.groupBy('a)('a as 'c).analyze
comparePlans(optimized, correctAnswer)
}
test("column pruning for Project(ne, Limit)") {
val testRelation = LocalRelation('a.int, 'b.int, 'c.int)
val originalQuery =
testRelation
.select('a, 'b)
.limit(2)
.select('a)
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer =
testRelation
.select('a)
.limit(2).analyze
comparePlans(optimized, correctAnswer)
}
test("push down project past sort") {
val testRelation = LocalRelation('a.int, 'b.int, 'c.int)
val x = testRelation.subquery('x)
// push down valid
val originalQuery = {
x.select('a, 'b)
.sortBy(SortOrder('a, Ascending))
.select('a)
}
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer =
x.select('a)
.sortBy(SortOrder('a, Ascending)).analyze
comparePlans(optimized, correctAnswer)
// push down invalid
val originalQuery1 = {
x.select('a, 'b)
.sortBy(SortOrder('a, Ascending))
.select('b)
}
val optimized1 = Optimize.execute(originalQuery1.analyze)
val correctAnswer1 =
x.select('a, 'b)
.sortBy(SortOrder('a, Ascending))
.select('b).analyze
comparePlans(optimized1, correctAnswer1)
}
test("Column pruning on Window with useless aggregate functions") {
val input = LocalRelation('a.int, 'b.string, 'c.double, 'd.int)
val winSpec = windowSpec('a :: Nil, 'd.asc :: Nil, UnspecifiedFrame)
val winExpr = windowExpr(count('d), winSpec)
val originalQuery = input.groupBy('a, 'c, 'd)('a, 'c, 'd, winExpr.as('window)).select('a, 'c)
val correctAnswer = input.select('a, 'c, 'd).groupBy('a, 'c, 'd)('a, 'c).analyze
val optimized = Optimize.execute(originalQuery.analyze)
comparePlans(optimized, correctAnswer)
}
test("Column pruning on Window with selected agg expressions") {
val input = LocalRelation('a.int, 'b.string, 'c.double, 'd.int)
val winSpec = windowSpec('a :: Nil, 'b.asc :: Nil, UnspecifiedFrame)
val winExpr = windowExpr(count('b), winSpec)
val originalQuery =
input.select('a, 'b, 'c, 'd, winExpr.as('window)).where('window > 1).select('a, 'c)
val correctAnswer =
input.select('a, 'b, 'c)
.window(winExpr.as('window) :: Nil, 'a :: Nil, 'b.asc :: Nil)
.where('window > 1).select('a, 'c).analyze
val optimized = Optimize.execute(originalQuery.analyze)
comparePlans(optimized, correctAnswer)
}
test("Column pruning on Window in select") {
val input = LocalRelation('a.int, 'b.string, 'c.double, 'd.int)
val winSpec = windowSpec('a :: Nil, 'b.asc :: Nil, UnspecifiedFrame)
val winExpr = windowExpr(count('b), winSpec)
val originalQuery = input.select('a, 'b, 'c, 'd, winExpr.as('window)).select('a, 'c)
val correctAnswer = input.select('a, 'c).analyze
val optimized = Optimize.execute(originalQuery.analyze)
comparePlans(optimized, correctAnswer)
}
test("Column pruning on Union") {
val input1 = LocalRelation('a.int, 'b.string, 'c.double)
val input2 = LocalRelation('c.int, 'd.string, 'e.double)
val query = Project('b :: Nil, Union(input1 :: input2 :: Nil)).analyze
val expected = Union(Project('b :: Nil, input1) :: Project('d :: Nil, input2) :: Nil).analyze
comparePlans(Optimize.execute(query), expected)
}
test("Remove redundant projects in column pruning rule") {
val input = LocalRelation('key.int, 'value.string)
val query =
Project(Seq($"x.key", $"y.key"),
Join(
SubqueryAlias("x", input),
SubqueryAlias("y", input), Inner, None, JoinHint.NONE)).analyze
val optimized = Optimize.execute(query)
val expected =
Join(
Project(Seq($"x.key"), SubqueryAlias("x", input)),
Project(Seq($"y.key"), SubqueryAlias("y", input)),
Inner, None, JoinHint.NONE).analyze
comparePlans(optimized, expected)
}
implicit private def productEncoder[T <: Product : TypeTag] = ExpressionEncoder[T]()
private val func = identity[Iterator[OtherTuple]] _
test("Column pruning on MapPartitions") {
val input = LocalRelation('_1.int, '_2.int, 'c.int)
val plan1 = MapPartitions(func, input)
val correctAnswer1 =
MapPartitions(func, Project(Seq('_1, '_2), input)).analyze
comparePlans(Optimize.execute(plan1.analyze), correctAnswer1)
}
test("push project down into sample") {
val testRelation = LocalRelation('a.int, 'b.int, 'c.int)
val x = testRelation.subquery('x)
val query1 = Sample(0.0, 0.6, false, 11L, x).select('a)
val optimized1 = Optimize.execute(query1.analyze)
val expected1 = Sample(0.0, 0.6, false, 11L, x.select('a))
comparePlans(optimized1, expected1.analyze)
val query2 = Sample(0.0, 0.6, false, 11L, x).select('a as 'aa)
val optimized2 = Optimize.execute(query2.analyze)
val expected2 = Sample(0.0, 0.6, false, 11L, x.select('a as 'aa))
comparePlans(optimized2, expected2.analyze)
}
test("SPARK-24696 ColumnPruning rule fails to remove extra Project") {
val input = LocalRelation('key.int, 'value.string)
val query = input.select('key).where(rand(0L) > 0.5).where('key < 10).analyze
val optimized = Optimize.execute(query)
val expected = input.where(rand(0L) > 0.5).where('key < 10).select('key).analyze
comparePlans(optimized, expected)
}
test("SPARK-36559 Prune and drop distributed-sequence if the produced column is not referred") {
val input = LocalRelation('a.int, 'b.int, 'c.int)
val plan1 = AttachDistributedSequence('d.int, input).select('a)
val correctAnswer1 = Project(Seq('a), input).analyze
comparePlans(Optimize.execute(plan1.analyze), correctAnswer1)
}
}
| ueshin/apache-spark | sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ColumnPruningSuite.scala | Scala | apache-2.0 | 15,958 |
/*
* 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.sling.atom.taglib;
import javax.servlet.jsp.JspException;
import org.apache.abdera.model.Link;
public class LinkTagHandler extends AbstractAbderaHandler {
private static final long serialVersionUID = 1L;
private String href;
private String rel;
private String type;
private String lang;
private long length;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getRel() {
return rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
@Override
public int doEndTag() throws JspException {
Link link = getAbdera().getFactory().newLink();
link.setHref(href.replaceAll(" ", "%20"));
if (rel != null) link.setRel(rel);
if (type != null) link.setMimeType(type);
if (lang != null) link.setHrefLang(lang);
if (length != 0) link.setLength(length);
if (hasEntry()) {
getEntry().addLink(link);
} else {
getFeed().addLink(link);
}
return super.doEndTag();
}
}
| dulvac/sling | contrib/scripting/jsp-taglib-atom/src/main/java/org/apache/sling/atom/taglib/LinkTagHandler.java | Java | apache-2.0 | 2,355 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine.evaluation.expression;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil;
import com.intellij.debugger.engine.evaluation.EvaluateRuntimeException;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.HashMap;
import com.sun.jdi.Value;
import java.util.Map;
/**
* @author lex
*/
public class CodeFragmentEvaluator extends BlockStatementEvaluator{
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.CodeFragmentEvaluator");
private final CodeFragmentEvaluator myParentFragmentEvaluator;
private final Map<String, Object> mySyntheticLocals = new HashMap<>();
public CodeFragmentEvaluator(CodeFragmentEvaluator parentFragmentEvaluator) {
super(null);
myParentFragmentEvaluator = parentFragmentEvaluator;
}
public void setStatements(Evaluator[] evaluators) {
myStatements = evaluators;
}
public Value getValue(String localName, VirtualMachineProxyImpl vm) throws EvaluateException {
if(!mySyntheticLocals.containsKey(localName)) {
if(myParentFragmentEvaluator != null){
return myParentFragmentEvaluator.getValue(localName, vm);
} else {
throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.not.declared", localName));
}
}
Object value = mySyntheticLocals.get(localName);
if(value instanceof Value) {
return (Value)value;
}
else if(value == null) {
return null;
}
else if(value instanceof Boolean) {
return vm.mirrorOf(((Boolean)value).booleanValue());
}
else if(value instanceof Byte) {
return vm.mirrorOf(((Byte)value).byteValue());
}
else if(value instanceof Character) {
return vm.mirrorOf(((Character)value).charValue());
}
else if(value instanceof Short) {
return vm.mirrorOf(((Short)value).shortValue());
}
else if(value instanceof Integer) {
return vm.mirrorOf(((Integer)value).intValue());
}
else if(value instanceof Long) {
return vm.mirrorOf(((Long)value).longValue());
}
else if(value instanceof Float) {
return vm.mirrorOf(((Float)value).floatValue());
}
else if(value instanceof Double) {
return vm.mirrorOf(((Double)value).doubleValue());
}
else if(value instanceof String) {
return vm.mirrorOf((String)value);
}
else {
LOG.error("unknown default initializer type " + value.getClass().getName());
return null;
}
}
private boolean hasValue(String localName) {
if(!mySyntheticLocals.containsKey(localName)) {
if(myParentFragmentEvaluator != null){
return myParentFragmentEvaluator.hasValue(localName);
} else {
return false;
}
} else {
return true;
}
}
public void setInitialValue(String localName, Object value) {
LOG.assertTrue(!(value instanceof Value), "use setValue for jdi values");
if(hasValue(localName)) {
throw new EvaluateRuntimeException(
EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.already.declared", localName)));
}
mySyntheticLocals.put(localName, value);
}
public void setValue(String localName, Value value) throws EvaluateException {
if(!mySyntheticLocals.containsKey(localName)) {
if(myParentFragmentEvaluator != null){
myParentFragmentEvaluator.setValue(localName, value);
} else {
throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.not.declared", localName));
}
}
else {
mySyntheticLocals.put(localName, value);
}
}
}
| asedunov/intellij-community | java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/CodeFragmentEvaluator.java | Java | apache-2.0 | 4,521 |
// This Webpack plugin ensures `npm install <library>` forces a project rebuild.
// We’re not sure why this isn't Webpack's default behavior.
// See https://github.com/facebookincubator/create-react-app/issues/186.
function WatchMissingNodeModulesPlugin(nodeModulesPath) {
this.nodeModulesPath = nodeModulesPath;
}
WatchMissingNodeModulesPlugin.prototype.apply = function (compiler) {
compiler.plugin('emit', (compilation, callback) => {
var missingDeps = compilation.missingDependencies;
var nodeModulesPath = this.nodeModulesPath;
// If any missing files are expected to appear in node_modules...
if (missingDeps.some(file => file.indexOf(nodeModulesPath) !== -1)) {
// ...tell webpack to watch node_modules recursively until they appear.
compilation.contextDependencies.push(nodeModulesPath);
}
callback();
});
}
module.exports = WatchMissingNodeModulesPlugin;
| matobet/userportal | scripts/utils/WatchMissingNodeModulesPlugin.js | JavaScript | apache-2.0 | 913 |
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.service.http.balancer;
import org.kaazing.gateway.transport.IoHandlerAdapter;
import org.kaazing.gateway.transport.wsn.WsnSession;
class WsnBalancerServiceHandler extends IoHandlerAdapter<WsnSession> {
WsnBalancerServiceHandler() {
}
@Override
protected void doSessionCreated(WsnSession session) throws Exception {
session.close(false);
}
@Override
protected void doExceptionCaught(WsnSession session, Throwable cause) throws Exception {
// trigger sessionClosed to update connection capabilities accordingly
session.close(true);
}
@Override
protected void doSessionOpened(WsnSession session) throws Exception {
session.close(false);
}
}
| mgherghe/gateway | service/http.balancer/src/main/java/org/kaazing/gateway/service/http/balancer/WsnBalancerServiceHandler.java | Java | apache-2.0 | 1,376 |
#
# Copyright 2015, DornerWorks, Ltd.
#
# This software may be distributed and modified according to the terms of
# the GNU General Public License version 2. Note that NO WARRANTY is provided.
# See "LICENSE_GPLv2.txt" for details.
#
# @TAG(GD_GPL)
#
include ${SOURCE_ROOT}/src/plat/allwinnerA20/machine/Makefile
| rzhw/seL4 | src/plat/allwinnerA20/Makefile | Makefile | bsd-2-clause | 314 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-217.js
* @description Object.getOwnPropertyDescriptor returns data desc (all false) for properties on built-ins (EvalError.prototype)
*/
function testcase() {
var desc = Object.getOwnPropertyDescriptor(EvalError, "prototype");
if (desc.writable === false &&
desc.enumerable === false &&
desc.configurable === false &&
desc.hasOwnProperty('get') === false &&
desc.hasOwnProperty('set') === false) {
return true;
}
}
runTestCase(testcase);
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-217.js | JavaScript | bsd-3-clause | 594 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* "in"-expression wrapped into "eval" statement is allowed as a ExpressionNoIn in "for (ExpressionNoIn; FirstExpression; SecondExpression) Statement" IterationStatement
*
* @path ch12/12.6/12.6.3/S12.6.3_A5.js
* @description Using eval "for(eval("i in arr");1;)"
*/
arr = [1,2,3,4,5];
i = 1;
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
try {
for(eval("i in arr");1;) {break;};
} catch (e) {
$ERROR('#1.1: for(eval("i in arr");1;) {break;}; does not lead to throwing exception');
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
try {
for(eval("var i = 1 in arr");1;) {break;};
} catch (e) {
$ERROR('#2.1: for(eval("var i = 1 in arr");1;) {break;}; does not lead to throwing exception');
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
try {
for(eval("1 in arr");1;) {break;};
} catch (e) {
$ERROR('#3.1: for(eval("1 in arr");1;) {break;}; does not lead to throwing exception');
}
//
//////////////////////////////////////////////////////////////////////////////
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch12/12.6/12.6.3/S12.6.3_A5.js | JavaScript | bsd-3-clause | 1,347 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* SPACE (U+0020) may occur within strings
*
* @path ch07/7.2/S7.2_A2.4_T2.js
* @description Use real SPACE
*/
//CHECK#1
if (" str ing " !== "\u0020str\u0020ing\u0020") {
$ERROR('#1: " str ing " === "\\u0020str\\u0020ing\\u0020"');
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch07/7.2/S7.2_A2.4_T2.js | JavaScript | bsd-3-clause | 307 |
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.animation;
import com.jme3.export.*;
import com.jme3.material.MatParam;
import com.jme3.material.Material;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix4f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.RendererException;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.*;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
import com.jme3.shader.VarType;
import com.jme3.util.SafeArrayList;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The Skeleton control deforms a model according to a skeleton, It handles the
* computation of the deformation matrices and performs the transformations on
* the mesh
*
* @author Rémy Bouquet Based on AnimControl by Kirill Vainer
*/
public class SkeletonControl extends AbstractControl implements Cloneable {
/**
* The skeleton of the model.
*/
private Skeleton skeleton;
/**
* List of targets which this controller effects.
*/
private SafeArrayList<Mesh> targets = new SafeArrayList<Mesh>(Mesh.class);
/**
* Used to track when a mesh was updated. Meshes are only updated if they
* are visible in at least one camera.
*/
private boolean wasMeshUpdated = false;
/**
* User wishes to use hardware skinning if available.
*/
private transient boolean hwSkinningDesired = true;
/**
* Hardware skinning is currently being used.
*/
private transient boolean hwSkinningEnabled = false;
/**
* Hardware skinning was tested on this GPU, results
* are stored in {@link #hwSkinningSupported} variable.
*/
private transient boolean hwSkinningTested = false;
/**
* If hardware skinning was {@link #hwSkinningTested tested}, then
* this variable will be set to true if supported, and false if otherwise.
*/
private transient boolean hwSkinningSupported = false;
/**
* Bone offset matrices, recreated each frame
*/
private transient Matrix4f[] offsetMatrices;
/**
* Material references used for hardware skinning
*/
private Set<Material> materials = new HashSet<Material>();
/**
* Serialization only. Do not use.
*/
public SkeletonControl() {
}
private void switchToHardware() {
// Next full 10 bones (e.g. 30 on 24 bones)
int numBones = ((skeleton.getBoneCount() / 10) + 1) * 10;
for (Material m : materials) {
m.setInt("NumberOfBones", numBones);
}
for (Mesh mesh : targets) {
if (mesh.isAnimated()) {
mesh.prepareForAnim(false);
}
}
}
private void switchToSoftware() {
for (Material m : materials) {
if (m.getParam("NumberOfBones") != null) {
m.clearParam("NumberOfBones");
}
}
for (Mesh mesh : targets) {
if (mesh.isAnimated()) {
mesh.prepareForAnim(true);
}
}
}
private boolean testHardwareSupported(RenderManager rm) {
for (Material m : materials) {
// Some of the animated mesh(es) do not support hardware skinning,
// so it is not supported by the model.
if (m.getMaterialDef().getMaterialParam("NumberOfBones") == null) {
Logger.getLogger(SkeletonControl.class.getName()).log(Level.WARNING,
"Not using hardware skinning for {0}, " +
"because material {1} doesn''t support it.",
new Object[]{spatial, m.getMaterialDef().getName()});
return false;
}
}
switchToHardware();
try {
rm.preloadScene(spatial);
return true;
} catch (RendererException e) {
Logger.getLogger(SkeletonControl.class.getName()).log(Level.WARNING, "Could not enable HW skinning due to shader compile error:", e);
return false;
}
}
/**
* Specifies if hardware skinning is preferred. If it is preferred and
* supported by GPU, it shall be enabled, if its not preferred, or not
* supported by GPU, then it shall be disabled.
*
* @see #isHardwareSkinningUsed()
*/
public void setHardwareSkinningPreferred(boolean preferred) {
hwSkinningDesired = preferred;
}
/**
* @return True if hardware skinning is preferable to software skinning.
* Set to false by default.
*
* @see #setHardwareSkinningPreferred(boolean)
*/
public boolean isHardwareSkinningPreferred() {
return hwSkinningDesired;
}
/**
* @return True is hardware skinning is activated and is currently used, false otherwise.
*/
public boolean isHardwareSkinningUsed() {
return hwSkinningEnabled;
}
/**
* Creates a skeleton control. The list of targets will be acquired
* automatically when the control is attached to a node.
*
* @param skeleton the skeleton
*/
public SkeletonControl(Skeleton skeleton) {
this.skeleton = skeleton;
}
private void findTargets(Node node) {
for (Spatial child : node.getChildren()) {
if (child instanceof Geometry) {
Geometry geom = (Geometry) child;
Mesh mesh = geom.getMesh();
if (mesh.isAnimated()) {
targets.add(mesh);
materials.add(geom.getMaterial());
}
} else if (child instanceof Node) {
findTargets((Node) child);
}
}
}
@Override
public void setSpatial(Spatial spatial) {
super.setSpatial(spatial);
updateTargetsAndMaterials(spatial);
}
private void controlRenderSoftware() {
resetToBind(); // reset morph meshes to bind pose
offsetMatrices = skeleton.computeSkinningMatrices();
for (Mesh mesh : targets) {
// NOTE: This assumes that code higher up
// Already ensured those targets are animated
// otherwise a crash will happen in skin update
softwareSkinUpdate(mesh, offsetMatrices);
}
}
private void controlRenderHardware() {
offsetMatrices = skeleton.computeSkinningMatrices();
for (Material m : materials) {
MatParam currentParam = m.getParam("BoneMatrices");
if (currentParam != null) {
if (currentParam.getValue() != offsetMatrices) {
// Check to see if other SkeletonControl
// is operating on this material, in that case, user
// is sharing materials between models which is NOT allowed
// when hardware skinning used.
throw new UnsupportedOperationException(
"Material instances cannot be shared when hardware skinning is used. " +
"Ensure all models use unique material instances."
);
}
}
m.setParam("BoneMatrices", VarType.Matrix4Array, offsetMatrices);
}
}
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
if (!wasMeshUpdated) {
updateTargetsAndMaterials(spatial);
// Prevent illegal cases. These should never happen.
assert hwSkinningTested || (!hwSkinningTested && !hwSkinningSupported && !hwSkinningEnabled);
assert !hwSkinningEnabled || (hwSkinningEnabled && hwSkinningTested && hwSkinningSupported);
if (hwSkinningDesired && !hwSkinningTested) {
hwSkinningTested = true;
hwSkinningSupported = testHardwareSupported(rm);
if (hwSkinningSupported) {
hwSkinningEnabled = true;
Logger.getLogger(SkeletonControl.class.getName()).log(Level.INFO, "Hardware skinning engaged for " + spatial);
} else {
switchToSoftware();
}
} else if (hwSkinningDesired && hwSkinningSupported && !hwSkinningEnabled) {
switchToHardware();
hwSkinningEnabled = true;
} else if (!hwSkinningDesired && hwSkinningEnabled) {
switchToSoftware();
hwSkinningEnabled = false;
}
if (hwSkinningEnabled) {
controlRenderHardware();
} else {
controlRenderSoftware();
}
wasMeshUpdated = true;
}
}
@Override
protected void controlUpdate(float tpf) {
wasMeshUpdated = false;
}
//only do this for software updates
void resetToBind() {
for (Mesh mesh : targets) {
if (mesh.isAnimated()) {
Buffer bwBuff = mesh.getBuffer(Type.BoneWeight).getData();
Buffer biBuff = mesh.getBuffer(Type.BoneIndex).getData();
if (!biBuff.hasArray() || !bwBuff.hasArray()) {
mesh.prepareForAnim(true); // prepare for software animation
}
VertexBuffer bindPos = mesh.getBuffer(Type.BindPosePosition);
VertexBuffer bindNorm = mesh.getBuffer(Type.BindPoseNormal);
VertexBuffer pos = mesh.getBuffer(Type.Position);
VertexBuffer norm = mesh.getBuffer(Type.Normal);
FloatBuffer pb = (FloatBuffer) pos.getData();
FloatBuffer nb = (FloatBuffer) norm.getData();
FloatBuffer bpb = (FloatBuffer) bindPos.getData();
FloatBuffer bnb = (FloatBuffer) bindNorm.getData();
pb.clear();
nb.clear();
bpb.clear();
bnb.clear();
//reseting bind tangents if there is a bind tangent buffer
VertexBuffer bindTangents = mesh.getBuffer(Type.BindPoseTangent);
if (bindTangents != null) {
VertexBuffer tangents = mesh.getBuffer(Type.Tangent);
FloatBuffer tb = (FloatBuffer) tangents.getData();
FloatBuffer btb = (FloatBuffer) bindTangents.getData();
tb.clear();
btb.clear();
tb.put(btb).clear();
}
pb.put(bpb).clear();
nb.put(bnb).clear();
}
}
}
public Control cloneForSpatial(Spatial spatial) {
Node clonedNode = (Node) spatial;
SkeletonControl clone = new SkeletonControl();
AnimControl ctrl = spatial.getControl(AnimControl.class);
if (ctrl != null) {
// AnimControl is responsible for cloning the skeleton, not
// SkeletonControl.
clone.skeleton = ctrl.getSkeleton();
} else {
// If there's no AnimControl, create the clone ourselves.
clone.skeleton = new Skeleton(skeleton);
}
clone.hwSkinningDesired = this.hwSkinningDesired;
clone.hwSkinningEnabled = this.hwSkinningEnabled;
clone.hwSkinningSupported = this.hwSkinningSupported;
clone.hwSkinningTested = this.hwSkinningTested;
clone.setSpatial(clonedNode);
// Fix attachments for the cloned node
for (int i = 0; i < clonedNode.getQuantity(); i++) {
// go through attachment nodes, apply them to correct bone
Spatial child = clonedNode.getChild(i);
if (child instanceof Node) {
Node clonedAttachNode = (Node) child;
Bone originalBone = (Bone) clonedAttachNode.getUserData("AttachedBone");
if (originalBone != null) {
Bone clonedBone = clone.skeleton.getBone(originalBone.getName());
clonedAttachNode.setUserData("AttachedBone", clonedBone);
clonedBone.setAttachmentsNode(clonedAttachNode);
}
}
}
return clone;
}
/**
*
* @param boneName the name of the bone
* @return the node attached to this bone
*/
public Node getAttachmentsNode(String boneName) {
Bone b = skeleton.getBone(boneName);
if (b == null) {
throw new IllegalArgumentException("Given bone name does not exist "
+ "in the skeleton.");
}
Node n = b.getAttachmentsNode();
Node model = (Node) spatial;
model.attachChild(n);
return n;
}
/**
* returns the skeleton of this control
*
* @return
*/
public Skeleton getSkeleton() {
return skeleton;
}
/**
* returns a copy of array of the targets meshes of this control
*
* @return
*/
public Mesh[] getTargets() {
return targets.toArray(new Mesh[targets.size()]);
}
/**
* Update the mesh according to the given transformation matrices
*
* @param mesh then mesh
* @param offsetMatrices the transformation matrices to apply
*/
private void softwareSkinUpdate(Mesh mesh, Matrix4f[] offsetMatrices) {
VertexBuffer tb = mesh.getBuffer(Type.Tangent);
if (tb == null) {
//if there are no tangents use the classic skinning
applySkinning(mesh, offsetMatrices);
} else {
//if there are tangents use the skinning with tangents
applySkinningTangents(mesh, offsetMatrices, tb);
}
}
/**
* Method to apply skinning transforms to a mesh's buffers
*
* @param mesh the mesh
* @param offsetMatrices the offset matices to apply
*/
private void applySkinning(Mesh mesh, Matrix4f[] offsetMatrices) {
int maxWeightsPerVert = mesh.getMaxNumWeights();
if (maxWeightsPerVert <= 0) {
throw new IllegalStateException("Max weights per vert is incorrectly set!");
}
int fourMinusMaxWeights = 4 - maxWeightsPerVert;
// NOTE: This code assumes the vertex buffer is in bind pose
// resetToBind() has been called this frame
VertexBuffer vb = mesh.getBuffer(Type.Position);
FloatBuffer fvb = (FloatBuffer) vb.getData();
fvb.rewind();
VertexBuffer nb = mesh.getBuffer(Type.Normal);
FloatBuffer fnb = (FloatBuffer) nb.getData();
fnb.rewind();
// get boneIndexes and weights for mesh
ByteBuffer ib = (ByteBuffer) mesh.getBuffer(Type.BoneIndex).getData();
FloatBuffer wb = (FloatBuffer) mesh.getBuffer(Type.BoneWeight).getData();
ib.rewind();
wb.rewind();
float[] weights = wb.array();
byte[] indices = ib.array();
int idxWeights = 0;
TempVars vars = TempVars.get();
float[] posBuf = vars.skinPositions;
float[] normBuf = vars.skinNormals;
int iterations = (int) FastMath.ceil(fvb.limit() / ((float) posBuf.length));
int bufLength = posBuf.length;
for (int i = iterations - 1; i >= 0; i--) {
// read next set of positions and normals from native buffer
bufLength = Math.min(posBuf.length, fvb.remaining());
fvb.get(posBuf, 0, bufLength);
fnb.get(normBuf, 0, bufLength);
int verts = bufLength / 3;
int idxPositions = 0;
// iterate vertices and apply skinning transform for each effecting bone
for (int vert = verts - 1; vert >= 0; vert--) {
// Skip this vertex if the first weight is zero.
if (weights[idxWeights] == 0) {
idxPositions += 3;
idxWeights += 4;
continue;
}
float nmx = normBuf[idxPositions];
float vtx = posBuf[idxPositions++];
float nmy = normBuf[idxPositions];
float vty = posBuf[idxPositions++];
float nmz = normBuf[idxPositions];
float vtz = posBuf[idxPositions++];
float rx = 0, ry = 0, rz = 0, rnx = 0, rny = 0, rnz = 0;
for (int w = maxWeightsPerVert - 1; w >= 0; w--) {
float weight = weights[idxWeights];
Matrix4f mat = offsetMatrices[indices[idxWeights++] & 0xff];
rx += (mat.m00 * vtx + mat.m01 * vty + mat.m02 * vtz + mat.m03) * weight;
ry += (mat.m10 * vtx + mat.m11 * vty + mat.m12 * vtz + mat.m13) * weight;
rz += (mat.m20 * vtx + mat.m21 * vty + mat.m22 * vtz + mat.m23) * weight;
rnx += (nmx * mat.m00 + nmy * mat.m01 + nmz * mat.m02) * weight;
rny += (nmx * mat.m10 + nmy * mat.m11 + nmz * mat.m12) * weight;
rnz += (nmx * mat.m20 + nmy * mat.m21 + nmz * mat.m22) * weight;
}
idxWeights += fourMinusMaxWeights;
idxPositions -= 3;
normBuf[idxPositions] = rnx;
posBuf[idxPositions++] = rx;
normBuf[idxPositions] = rny;
posBuf[idxPositions++] = ry;
normBuf[idxPositions] = rnz;
posBuf[idxPositions++] = rz;
}
fvb.position(fvb.position() - bufLength);
fvb.put(posBuf, 0, bufLength);
fnb.position(fnb.position() - bufLength);
fnb.put(normBuf, 0, bufLength);
}
vars.release();
vb.updateData(fvb);
nb.updateData(fnb);
}
/**
* Specific method for skinning with tangents to avoid cluttering the
* classic skinning calculation with null checks that would slow down the
* process even if tangents don't have to be computed. Also the iteration
* has additional indexes since tangent has 4 components instead of 3 for
* pos and norm
*
* @param maxWeightsPerVert maximum number of weights per vertex
* @param mesh the mesh
* @param offsetMatrices the offsetMaytrices to apply
* @param tb the tangent vertexBuffer
*/
private void applySkinningTangents(Mesh mesh, Matrix4f[] offsetMatrices, VertexBuffer tb) {
int maxWeightsPerVert = mesh.getMaxNumWeights();
if (maxWeightsPerVert <= 0) {
throw new IllegalStateException("Max weights per vert is incorrectly set!");
}
int fourMinusMaxWeights = 4 - maxWeightsPerVert;
// NOTE: This code assumes the vertex buffer is in bind pose
// resetToBind() has been called this frame
VertexBuffer vb = mesh.getBuffer(Type.Position);
FloatBuffer fvb = (FloatBuffer) vb.getData();
fvb.rewind();
VertexBuffer nb = mesh.getBuffer(Type.Normal);
FloatBuffer fnb = (FloatBuffer) nb.getData();
fnb.rewind();
FloatBuffer ftb = (FloatBuffer) tb.getData();
ftb.rewind();
// get boneIndexes and weights for mesh
ByteBuffer ib = (ByteBuffer) mesh.getBuffer(Type.BoneIndex).getData();
FloatBuffer wb = (FloatBuffer) mesh.getBuffer(Type.BoneWeight).getData();
ib.rewind();
wb.rewind();
float[] weights = wb.array();
byte[] indices = ib.array();
int idxWeights = 0;
TempVars vars = TempVars.get();
float[] posBuf = vars.skinPositions;
float[] normBuf = vars.skinNormals;
float[] tanBuf = vars.skinTangents;
int iterations = (int) FastMath.ceil(fvb.limit() / ((float) posBuf.length));
int bufLength = 0;
int tanLength = 0;
for (int i = iterations - 1; i >= 0; i--) {
// read next set of positions and normals from native buffer
bufLength = Math.min(posBuf.length, fvb.remaining());
tanLength = Math.min(tanBuf.length, ftb.remaining());
fvb.get(posBuf, 0, bufLength);
fnb.get(normBuf, 0, bufLength);
ftb.get(tanBuf, 0, tanLength);
int verts = bufLength / 3;
int idxPositions = 0;
//tangents has their own index because of the 4 components
int idxTangents = 0;
// iterate vertices and apply skinning transform for each effecting bone
for (int vert = verts - 1; vert >= 0; vert--) {
// Skip this vertex if the first weight is zero.
if (weights[idxWeights] == 0) {
idxTangents += 4;
idxPositions += 3;
idxWeights += 4;
continue;
}
float nmx = normBuf[idxPositions];
float vtx = posBuf[idxPositions++];
float nmy = normBuf[idxPositions];
float vty = posBuf[idxPositions++];
float nmz = normBuf[idxPositions];
float vtz = posBuf[idxPositions++];
float tnx = tanBuf[idxTangents++];
float tny = tanBuf[idxTangents++];
float tnz = tanBuf[idxTangents++];
// skipping the 4th component of the tangent since it doesn't have to be transformed
idxTangents++;
float rx = 0, ry = 0, rz = 0, rnx = 0, rny = 0, rnz = 0, rtx = 0, rty = 0, rtz = 0;
for (int w = maxWeightsPerVert - 1; w >= 0; w--) {
float weight = weights[idxWeights];
Matrix4f mat = offsetMatrices[indices[idxWeights++] & 0xff];
rx += (mat.m00 * vtx + mat.m01 * vty + mat.m02 * vtz + mat.m03) * weight;
ry += (mat.m10 * vtx + mat.m11 * vty + mat.m12 * vtz + mat.m13) * weight;
rz += (mat.m20 * vtx + mat.m21 * vty + mat.m22 * vtz + mat.m23) * weight;
rnx += (nmx * mat.m00 + nmy * mat.m01 + nmz * mat.m02) * weight;
rny += (nmx * mat.m10 + nmy * mat.m11 + nmz * mat.m12) * weight;
rnz += (nmx * mat.m20 + nmy * mat.m21 + nmz * mat.m22) * weight;
rtx += (tnx * mat.m00 + tny * mat.m01 + tnz * mat.m02) * weight;
rty += (tnx * mat.m10 + tny * mat.m11 + tnz * mat.m12) * weight;
rtz += (tnx * mat.m20 + tny * mat.m21 + tnz * mat.m22) * weight;
}
idxWeights += fourMinusMaxWeights;
idxPositions -= 3;
normBuf[idxPositions] = rnx;
posBuf[idxPositions++] = rx;
normBuf[idxPositions] = rny;
posBuf[idxPositions++] = ry;
normBuf[idxPositions] = rnz;
posBuf[idxPositions++] = rz;
idxTangents -= 4;
tanBuf[idxTangents++] = rtx;
tanBuf[idxTangents++] = rty;
tanBuf[idxTangents++] = rtz;
//once again skipping the 4th component of the tangent
idxTangents++;
}
fvb.position(fvb.position() - bufLength);
fvb.put(posBuf, 0, bufLength);
fnb.position(fnb.position() - bufLength);
fnb.put(normBuf, 0, bufLength);
ftb.position(ftb.position() - tanLength);
ftb.put(tanBuf, 0, tanLength);
}
vars.release();
vb.updateData(fvb);
nb.updateData(fnb);
tb.updateData(ftb);
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
oc.write(skeleton, "skeleton", null);
//Targets and materials don't need to be saved, they'll be gathered on each frame
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule in = im.getCapsule(this);
skeleton = (Skeleton) in.readSavable("skeleton", null);
}
private void updateTargetsAndMaterials(Spatial spatial) {
targets.clear();
materials.clear();
if (spatial != null && spatial instanceof Node) {
Node node = (Node) spatial;
findTargets(node);
}
}
}
| sandervdo/jmonkeyengine | jme3-core/src/main/java/com/jme3/animation/SkeletonControl.java | Java | bsd-3-clause | 26,240 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* String.prototype.split (separator, limit) returns an Array object into which substrings of the result of converting this object to a string have
* been stored. The substrings are determined by searching from left to right for occurrences of
* separator; these occurrences are not part of any substring in the returned array, but serve to divide up
* the string value. The value of separator may be a string of any length or it may be a RegExp object
*
* @path ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A2_T38.js
* @description Call split("l",NaN), instance is String("hello")
*/
var __instance = new String("hello");
var __split = __instance.split("l", NaN);
var __expected = [];
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__split.constructor !== Array) {
$ERROR('#1: var __instance = new String("hello"); __split = __instance.split("l", NaN); __expected = []; __split.constructor === Array. Actual: '+__split.constructor );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__split.length !== __expected.length) {
$ERROR('#2: var __instance = new String("hello"); __split = __instance.split("l", NaN); __expected = []; __split.length === __expected.length. Actual: '+__split.length );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
if (__split[0] !== __expected[0]) {
$ERROR('#3: var __instance = new String("hello"); __split = __instance.split("l", NaN); __expected = []; __split[0] === '+__expected[0]+'. Actual: '+__split[index] );
}
//
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A2_T38.js | JavaScript | bsd-3-clause | 1,828 |
// SPDX-License-Identifier: GPL-2.0
#ifndef PERF_COPYFILE_H_
#define PERF_COPYFILE_H_
#include <linux/types.h>
#include <sys/types.h>
#include <fcntl.h>
struct nsinfo;
int copyfile(const char *from, const char *to);
int copyfile_mode(const char *from, const char *to, mode_t mode);
int copyfile_ns(const char *from, const char *to, struct nsinfo *nsi);
int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size);
#endif // PERF_COPYFILE_H_
| GuillaumeSeren/linux | tools/perf/util/copyfile.h | C | gpl-2.0 | 464 |
#!/usr/bin/env python
# Author: Costin Constantin <[email protected]>
# Copyright (c) 2015 Intel Corporation.
#
# Contributors: Alex Tereschenko <[email protected]>
#
# 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.
import mraa as m
import unittest as u
class GeneralChecks(u.TestCase):
def test_mraa_version(self):
version = m.getVersion()
print("Version is: " + version)
self.assertIsNotNone(version)
self.assertNotEqual(version, "", "MRAA version is an empty string")
if __name__ == "__main__":
u.main()
| andreivasiliu2211/mraa | tests/mock/general_checks.py | Python | mit | 1,554 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading;
using System.Web;
using Examine.LuceneEngine.Config;
using Examine.LuceneEngine.Providers;
using Examine.Providers;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Umbraco.Core;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using UmbracoExamine.DataServices;
using Examine;
using System.IO;
using System.Xml.Linq;
using Lucene.Net.Store;
using UmbracoExamine.LocalStorage;
namespace UmbracoExamine
{
/// <summary>
/// An abstract provider containing the basic functionality to be able to query against
/// Umbraco data.
/// </summary>
public abstract class BaseUmbracoIndexer : LuceneIndexer
{
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
protected BaseUmbracoIndexer()
: base()
{
}
/// <summary>
/// Constructor to allow for creating an indexer at runtime
/// </summary>
/// <param name="indexerData"></param>
/// <param name="indexPath"></param>
/// <param name="dataService"></param>
/// <param name="analyzer"></param>
protected BaseUmbracoIndexer(IIndexCriteria indexerData, DirectoryInfo indexPath, IDataService dataService, Analyzer analyzer, bool async)
: base(indexerData, indexPath, analyzer, async)
{
DataService = dataService;
}
protected BaseUmbracoIndexer(IIndexCriteria indexerData, Lucene.Net.Store.Directory luceneDirectory, IDataService dataService, Analyzer analyzer, bool async)
: base(indexerData, luceneDirectory, analyzer, async)
{
DataService = dataService;
}
#endregion
/// <summary>
/// Used for unit tests
/// </summary>
internal static bool? DisableInitializationCheck = null;
private readonly LocalTempStorageIndexer _localTempStorageIndexer = new LocalTempStorageIndexer();
private BaseLuceneSearcher _internalTempStorageSearcher = null;
#region Properties
public bool UseTempStorage
{
get { return _localTempStorageIndexer.LuceneDirectory != null; }
}
public string TempStorageLocation
{
get
{
if (UseTempStorage == false) return string.Empty;
return _localTempStorageIndexer.TempPath;
}
}
/// <summary>
/// If true, the IndexingActionHandler will be run to keep the default index up to date.
/// </summary>
public bool EnableDefaultEventHandler { get; protected set; }
/// <summary>
/// Determines if the manager will call the indexing methods when content is saved or deleted as
/// opposed to cache being updated.
/// </summary>
public bool SupportUnpublishedContent { get; protected set; }
/// <summary>
/// The data service used for retreiving and submitting data to the cms
/// </summary>
public IDataService DataService { get; protected internal set; }
/// <summary>
/// the supported indexable types
/// </summary>
protected abstract IEnumerable<string> SupportedTypes { get; }
#endregion
#region Initialize
/// <summary>
/// Setup the properties for the indexer from the provider settings
/// </summary>
/// <param name="name"></param>
/// <param name="config"></param>
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
if (config["dataService"] != null && !string.IsNullOrEmpty(config["dataService"]))
{
//this should be a fully qualified type
var serviceType = Type.GetType(config["dataService"]);
DataService = (IDataService)Activator.CreateInstance(serviceType);
}
else if (DataService == null)
{
//By default, we will be using the UmbracoDataService
//generally this would only need to be set differently for unit testing
DataService = new UmbracoDataService();
}
DataService.LogService.LogLevel = LoggingLevel.Normal;
if (config["logLevel"] != null && !string.IsNullOrEmpty(config["logLevel"]))
{
try
{
var logLevel = (LoggingLevel)Enum.Parse(typeof(LoggingLevel), config["logLevel"]);
DataService.LogService.LogLevel = logLevel;
}
catch (ArgumentException)
{
//FAILED
DataService.LogService.LogLevel = LoggingLevel.Normal;
}
}
DataService.LogService.ProviderName = name;
EnableDefaultEventHandler = true; //set to true by default
bool enabled;
if (bool.TryParse(config["enableDefaultEventHandler"], out enabled))
{
EnableDefaultEventHandler = enabled;
}
DataService.LogService.AddVerboseLog(-1, string.Format("{0} indexer initializing", name));
base.Initialize(name, config);
if (config["useTempStorage"] != null)
{
var fsDir = base.GetLuceneDirectory() as FSDirectory;
if (fsDir != null)
{
//Use the temp storage directory which will store the index in the local/codegen folder, this is useful
// for websites that are running from a remove file server and file IO latency becomes an issue
var attemptUseTempStorage = config["useTempStorage"].TryConvertTo<LocalStorageType>();
if (attemptUseTempStorage)
{
var indexSet = IndexSets.Instance.Sets[IndexSetName];
var configuredPath = indexSet.IndexPath;
_localTempStorageIndexer.Initialize(config, configuredPath, fsDir, IndexingAnalyzer, attemptUseTempStorage.Result);
}
}
}
}
#endregion
/// <summary>
/// Used to aquire the internal searcher
/// </summary>
private readonly object _internalSearcherLocker = new object();
protected override BaseSearchProvider InternalSearcher
{
get
{
//if temp local storage is configured use that, otherwise return the default
if (UseTempStorage)
{
if (_internalTempStorageSearcher == null)
{
lock (_internalSearcherLocker)
{
if (_internalTempStorageSearcher == null)
{
_internalTempStorageSearcher = new LuceneSearcher(GetIndexWriter(), IndexingAnalyzer);
}
}
}
return _internalTempStorageSearcher;
}
return base.InternalSearcher;
}
}
public override Lucene.Net.Store.Directory GetLuceneDirectory()
{
//if temp local storage is configured use that, otherwise return the default
if (UseTempStorage)
{
return _localTempStorageIndexer.LuceneDirectory;
}
return base.GetLuceneDirectory();
}
protected override IndexWriter CreateIndexWriter()
{
//if temp local storage is configured use that, otherwise return the default
if (UseTempStorage)
{
var directory = GetLuceneDirectory();
return new IndexWriter(GetLuceneDirectory(), IndexingAnalyzer,
DeletePolicyTracker.Current.GetPolicy(directory),
IndexWriter.MaxFieldLength.UNLIMITED);
}
return base.CreateIndexWriter();
}
///// <summary>
///// Override to check if we can actually initialize.
///// </summary>
///// <returns></returns>
///// <remarks>
///// This check is required since the base examine lib will try to check this method on app startup. If the app
///// is not ready then we need to deal with it otherwise the base class will throw exceptions since we've bypassed initialization.
///// </remarks>
//public override bool IndexExists()
//{
// return base.IndexExists();
//}
/// <summary>
/// override to check if we can actually initialize.
/// </summary>
/// <remarks>
/// This check is required since the base examine lib will try to rebuild on startup
/// </remarks>
public override void RebuildIndex()
{
if (CanInitialize())
{
base.RebuildIndex();
}
}
/// <summary>
/// override to check if we can actually initialize.
/// </summary>
/// <remarks>
/// This check is required since the base examine lib will try to rebuild on startup
/// </remarks>
public override void IndexAll(string type)
{
if (CanInitialize())
{
base.IndexAll(type);
}
}
public override void ReIndexNode(XElement node, string type)
{
if (CanInitialize())
{
if (!SupportedTypes.Contains(type))
return;
base.ReIndexNode(node, type);
}
}
/// <summary>
/// override to check if we can actually initialize.
/// </summary>
/// <remarks>
/// This check is required since the base examine lib will try to rebuild on startup
/// </remarks>
public override void DeleteFromIndex(string nodeId)
{
if (CanInitialize())
{
base.DeleteFromIndex(nodeId);
}
}
#region Protected
/// <summary>
/// Returns true if the Umbraco application is in a state that we can initialize the examine indexes
/// </summary>
/// <returns></returns>
protected bool CanInitialize()
{
//check the DisableInitializationCheck and ensure that it is not set to true
if (!DisableInitializationCheck.HasValue || !DisableInitializationCheck.Value)
{
//We need to check if we actually can initialize, if not then don't continue
if (ApplicationContext.Current == null
|| !ApplicationContext.Current.IsConfigured
|| !ApplicationContext.Current.DatabaseContext.IsDatabaseConfigured)
{
return false;
}
}
return true;
}
/// <summary>
/// Ensures that the node being indexed is of a correct type and is a descendent of the parent id specified.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
protected override bool ValidateDocument(XElement node)
{
//check if this document is a descendent of the parent
if (IndexerData.ParentNodeId.HasValue && IndexerData.ParentNodeId.Value > 0)
if (!((string)node.Attribute("path")).Contains("," + IndexerData.ParentNodeId.Value.ToString() + ","))
return false;
return base.ValidateDocument(node);
}
/// <summary>
/// Reindexes all supported types
/// </summary>
protected override void PerformIndexRebuild()
{
foreach (var t in SupportedTypes)
{
IndexAll(t);
}
}
/// <summary>
/// Builds an xpath statement to query against Umbraco data for the index type specified, then
/// initiates the re-indexing of the data matched.
/// </summary>
/// <param name="type"></param>
protected override void PerformIndexAll(string type)
{
//NOTE: the logic below is ONLY used for published content, for media and members and non-published content, this method is overridden
// and we query directly against the umbraco service layer.
if (!SupportedTypes.Contains(type))
return;
var xPath = "//*[(number(@id) > 0 and (@isDoc or @nodeTypeAlias)){0}]"; //we'll add more filters to this below if needed
var sb = new StringBuilder();
//create the xpath statement to match node type aliases if specified
if (IndexerData.IncludeNodeTypes.Any())
{
sb.Append("(");
foreach (var field in IndexerData.IncludeNodeTypes)
{
//this can be used across both schemas
const string nodeTypeAlias = "(@nodeTypeAlias='{0}' or (count(@nodeTypeAlias)=0 and name()='{0}'))";
sb.Append(string.Format(nodeTypeAlias, field));
sb.Append(" or ");
}
sb.Remove(sb.Length - 4, 4); //remove last " or "
sb.Append(")");
}
//create the xpath statement to match all children of the current node.
if (IndexerData.ParentNodeId.HasValue && IndexerData.ParentNodeId.Value > 0)
{
if (sb.Length > 0)
sb.Append(" and ");
sb.Append("(");
sb.Append("contains(@path, '," + IndexerData.ParentNodeId.Value + ",')"); //if the path contains comma - id - comma then the nodes must be a child
sb.Append(")");
}
//create the full xpath statement to match the appropriate nodes. If there is a filter
//then apply it, otherwise just select all nodes.
var filter = sb.ToString();
xPath = string.Format(xPath, filter.Length > 0 ? " and " + filter : "");
//raise the event and set the xpath statement to the value returned
var args = new IndexingNodesEventArgs(IndexerData, xPath, type);
OnNodesIndexing(args);
if (args.Cancel)
{
return;
}
xPath = args.XPath;
DataService.LogService.AddVerboseLog(-1, string.Format("({0}) PerformIndexAll with XPATH: {1}", this.Name, xPath));
AddNodesToIndex(xPath, type);
}
/// <summary>
/// Returns an XDocument for the entire tree stored for the IndexType specified.
/// </summary>
/// <param name="xPath">The xpath to the node.</param>
/// <param name="type">The type of data to request from the data service.</param>
/// <returns>Either the Content or Media xml. If the type is not of those specified null is returned</returns>
protected virtual XDocument GetXDocument(string xPath, string type)
{
//TODO: We need to get rid of this! it will now only ever be called for published content - but we're keeping the other
// logic here for backwards compatibility in case inheritors are calling this for some reason.
if (type == IndexTypes.Content)
{
if (this.SupportUnpublishedContent)
{
return DataService.ContentService.GetLatestContentByXPath(xPath);
}
else
{
return DataService.ContentService.GetPublishedContentByXPath(xPath);
}
}
else if (type == IndexTypes.Media)
{
return DataService.MediaService.GetLatestMediaByXpath(xPath);
}
return null;
}
#endregion
#region Private
/// <summary>
/// Adds all nodes with the given xPath root.
/// </summary>
/// <param name="xPath">The x path.</param>
/// <param name="type">The type.</param>
private void AddNodesToIndex(string xPath, string type)
{
// Get all the nodes of nodeTypeAlias == nodeTypeAlias
XDocument xDoc = GetXDocument(xPath, type);
if (xDoc != null)
{
var rootNode = xDoc.Root;
AddNodesToIndex(rootNode.Elements(), type);
}
}
#endregion
}
}
| Nicholas-Westby/Umbraco-CMS | src/UmbracoExamine/BaseUmbracoIndexer.cs | C# | mit | 17,549 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.KeyVault.Models
{
using Azure;
using KeyVault;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The certificate operation update parameters.
/// </summary>
public partial class CertificateOperationUpdateParameter
{
/// <summary>
/// Initializes a new instance of the
/// CertificateOperationUpdateParameter class.
/// </summary>
public CertificateOperationUpdateParameter() { }
/// <summary>
/// Initializes a new instance of the
/// CertificateOperationUpdateParameter class.
/// </summary>
/// <param name="cancellationRequested">Indicates if cancellation was
/// requested on the certificate operation.</param>
public CertificateOperationUpdateParameter(bool cancellationRequested)
{
CancellationRequested = cancellationRequested;
}
/// <summary>
/// Gets or sets indicates if cancellation was requested on the
/// certificate operation.
/// </summary>
[JsonProperty(PropertyName = "cancellation_requested")]
public bool CancellationRequested { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
//Nothing to validate
}
}
}
| ScottHolden/azure-sdk-for-net | src/SDKs/KeyVault/dataPlane/Microsoft.Azure.KeyVault/Generated/Models/CertificateOperationUpdateParameter.cs | C# | mit | 1,828 |
// Type definitions for gravatar v1.8.0
// Project: https://github.com/emerleite/node-gravatar
// Definitions by: Denis Sokolov <https://github.com/denis-sokolov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace GravatarModule {
type Options = {
d?: string
default?: string
f?: string
forcedefault?: string
format?: string
protocol?: string
r?: string
rating?: string
s?: string
size?: string
}
function url(email: string, options?: Options, forceProtocol?: boolean): string;
}
export = GravatarModule;
| borisyankov/DefinitelyTyped | types/gravatar/index.d.ts | TypeScript | mit | 588 |
/* drivers/input/touchscreen/maxim_sti.c
*
* Maxim SmartTouch Imager Touchscreen Driver
*
* Copyright (c)2013 Maxim Integrated Products, Inc.
* Copyright (C) 2013, NVIDIA Corporation. All Rights Reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* Copyright (C) 2014 Sony Mobile Communications Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kmod.h>
#include <linux/kthread.h>
#include <linux/sched/rt.h>
#include <linux/spi/spi.h>
#include <linux/firmware.h>
#include <linux/crc16.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/input/evdt_helper.h>
#include <linux/regulator/consumer.h>
#include <linux/maxim_sti.h>
#include <asm/byteorder.h> /* MUST include this header to get byte order */
#ifdef CONFIG_OF
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#endif
/****************************************************************************\
* Custom features *
\****************************************************************************/
#define INPUT_DEVICES 1
#define INPUT_ENABLE_DISABLE 0
#define SUSPEND_POWER_OFF 0
#define CPU_BOOST 0
#define SONY_CPU_BOOST 0
#define FB_CALLBACK 1
#define HI02 1
#define CFG_FILE_NAME_MAX 64
#define FORCE_NO_DECONFIG 1
#if CPU_BOOST
#define INPUT_IDLE_PERIOD (msecs_to_jiffies(50))
#endif
#if FB_CALLBACK && defined(CONFIG_FB)
#include <linux/fb.h>
#endif
#define MXM_WAKEUP_GESTURE "wakeup_gesture"
/****************************************************************************\
* Device context structure, globals, and macros *
\****************************************************************************/
struct dev_data;
struct chip_access_method {
int (*read)(struct dev_data *dd, u16 address, u8 *buf, u16 len);
int (*write)(struct dev_data *dd, u16 address, u8 *buf, u16 len);
};
struct dev_data {
u8 *tx_buf;
u8 *rx_buf;
u8 send_fail_count;
u32 nl_seq;
u8 nl_mc_group_count;
bool nl_enabled;
bool start_fusion;
bool suspend_in_progress;
bool resume_in_progress;
bool expect_resume_ack;
bool eraser_active;
bool legacy_acceleration;
#if INPUT_ENABLE_DISABLE || FB_CALLBACK || FORCE_NO_DECONFIG
bool input_no_deconfig;
#endif
bool irq_registered;
u16 nirq_params;
u16 irq_param[MAX_IRQ_PARAMS];
pid_t fusion_process;
char input_phys[128];
struct input_dev *input_dev[INPUT_DEVICES];
struct completion suspend_resume;
struct chip_access_method chip;
struct spi_device *spi;
struct genl_family nl_family;
struct genl_ops *nl_ops;
struct genl_multicast_group *nl_mc_groups;
struct sk_buff *outgoing_skb;
struct sk_buff_head incoming_skb_queue;
struct task_struct *thread;
struct sched_param thread_sched;
struct list_head dev_list;
struct regulator *reg_avdd;
struct regulator *reg_dvdd;
void (*service_irq)(struct dev_data *dd);
#if CPU_BOOST
unsigned long last_irq_jiffies;
#endif
#if FB_CALLBACK
struct notifier_block fb_notifier;
#endif
struct kobject *parent;
char config_file[CFG_FILE_NAME_MAX];
u8 sysfs_created;
u16 chip_id;
u16 glove_enabled;
u16 gesture_en;
u16 charger_mode_en;
u16 lcd_fps;
u16 tf_ver;
u16 drv_ver;
u16 fw_ver;
u16 fw_protocol;
u32 tf_status;
bool idle;
bool resume_reset;
bool compatibility_mode;
bool pending_fps;
bool boost;
struct device_node *evdt_node;
u8 ew_input_device_id;
unsigned long int sysfs_update_type;
struct mutex sysfs_update_mutex;
struct mutex screen_status_mutex;
};
static unsigned short panel_id = 0x0000;
static struct list_head dev_list;
static spinlock_t dev_lock;
static void gesture_wake_detect(struct dev_data *dd);
static irqreturn_t irq_handler(int irq, void *context);
static void service_irq(struct dev_data *dd);
static void service_irq_legacy_acceleration(struct dev_data *dd);
#define ETF -2
#define ERROR(a, b...) pr_err("%s driver(ERROR:%s:%d): " a "\n", \
dd->nl_family.name, __func__, __LINE__, ##b)
#define INFO(a, b...) pr_info("%s driver: " a "\n", \
dd->nl_family.name, ##b)
/****************************************************************************\
* Chip access methods *
\****************************************************************************/
static inline int
spi_read_123(struct dev_data *dd, u16 address, u8 *buf, u16 len, bool add_len)
{
struct spi_message message;
struct spi_transfer transfer;
u16 *tx_buf = (u16 *)dd->tx_buf;
u16 *rx_buf = (u16 *)dd->rx_buf;
u16 words = len / sizeof(u16), header_len = 1;
u16 *ptr2 = rx_buf + 1;
#ifdef __LITTLE_ENDIAN
u16 *ptr1 = (u16 *)buf, i;
#endif
int ret;
if (tx_buf == NULL || rx_buf == NULL)
return -ENOMEM;
tx_buf[0] = (address << 1) | 0x0001;
#ifdef __LITTLE_ENDIAN
tx_buf[0] = (tx_buf[0] << 8) | (tx_buf[0] >> 8);
#endif
if (add_len) {
tx_buf[1] = words;
#ifdef __LITTLE_ENDIAN
tx_buf[1] = (tx_buf[1] << 8) | (tx_buf[1] >> 8);
#endif
ptr2++;
header_len++;
}
spi_message_init(&message);
memset(&transfer, 0, sizeof(transfer));
transfer.len = len + header_len * sizeof(u16);
transfer.tx_buf = tx_buf;
transfer.rx_buf = rx_buf;
spi_message_add_tail(&transfer, &message);
do {
ret = spi_sync(dd->spi, &message);
} while (ret == -EAGAIN);
#ifdef __LITTLE_ENDIAN
for (i = 0; i < words; i++)
ptr1[i] = (ptr2[i] << 8) | (ptr2[i] >> 8);
#else
memcpy(buf, ptr2, len);
#endif
return ret;
}
static inline int
spi_write_123(struct dev_data *dd, u16 address, u8 *buf, u16 len, bool add_len)
{
struct maxim_sti_pdata *pdata = dd->spi->dev.platform_data;
u16 *tx_buf = (u16 *)dd->tx_buf;
u16 words = len / sizeof(u16), header_len = 1;
#ifdef __LITTLE_ENDIAN
u16 i;
#endif
int ret;
if (tx_buf == NULL)
return -ENOMEM;
tx_buf[0] = address << 1;
if (add_len) {
tx_buf[1] = words;
header_len++;
}
memcpy(tx_buf + header_len, buf, len);
#ifdef __LITTLE_ENDIAN
for (i = 0; i < (words + header_len); i++)
tx_buf[i] = (tx_buf[i] << 8) | (tx_buf[i] >> 8);
#endif
do {
ret = spi_write(dd->spi, tx_buf,
len + header_len * sizeof(u16));
} while (ret == -EAGAIN);
memset(dd->tx_buf, 0xFF, pdata->tx_buf_size);
return ret;
}
/* ======================================================================== */
static int
spi_read_1(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
return spi_read_123(dd, address, buf, len, true);
}
static int
spi_write_1(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
return spi_write_123(dd, address, buf, len, true);
}
/* ======================================================================== */
static inline int
stop_legacy_acceleration(struct dev_data *dd)
{
u16 value = 0xDEAD, status, i;
int ret;
ret = spi_write_123(dd, 0x0003, (u8 *)&value,
sizeof(value), false);
if (ret < 0)
return -EPERM;
usleep_range(100, 120);
for (i = 0; i < 200; i++) {
ret = spi_read_123(dd, 0x0003, (u8 *)&status, sizeof(status),
false);
if (ret < 0)
return -EPERM;
if (status == 0xABCD)
return 0;
}
return -ETF;
}
static inline int
start_legacy_acceleration(struct dev_data *dd)
{
u16 value = 0xBEEF;
int ret;
ret = spi_write_123(dd, 0x0003, (u8 *)&value, sizeof(value), false);
usleep_range(100, 120);
return ret;
}
static inline int
spi_rw_2_poll_status(struct dev_data *dd)
{
u16 status, i;
int ret;
for (i = 0; i < 200; i++) {
ret = spi_read_123(dd, 0x0000, (u8 *)&status, sizeof(status),
false);
if (ret < 0)
return -EPERM;
if (status == 0xABCD)
return 0;
}
return -ETF;
}
static inline int
spi_read_2_page(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
u16 request[] = {0xFEDC, (address << 1) | 0x0001, len / sizeof(u16)};
int ret;
/* write read request header */
ret = spi_write_123(dd, 0x0000, (u8 *)request, sizeof(request),
false);
if (ret < 0)
return -EPERM;
/* poll status */
ret = spi_rw_2_poll_status(dd);
if (ret < 0)
return ret;
/* read data */
ret = spi_read_123(dd, 0x0004, (u8 *)buf, len, false);
return ret;
}
static inline int
spi_write_2_page(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
u16 page[254];
int ret;
page[0] = 0xFEDC;
page[1] = address << 1;
page[2] = len / sizeof(u16);
page[3] = 0x0000;
memcpy(page + 4, buf, len);
/* write data with write request header */
ret = spi_write_123(dd, 0x0000, (u8 *)page, len + 4 * sizeof(u16),
false);
if (ret < 0)
return -EPERM;
/* poll status */
return spi_rw_2_poll_status(dd);
}
static inline int
spi_rw_2(struct dev_data *dd, u16 address, u8 *buf, u16 len,
int (*func)(struct dev_data *dd, u16 address, u8 *buf, u16 len))
{
u16 rx_len, rx_limit = 250 * sizeof(u16), offset = 0;
int ret;
while (len > 0) {
rx_len = (len > rx_limit) ? rx_limit : len;
if (dd->legacy_acceleration)
stop_legacy_acceleration(dd);
ret = func(dd, address + (offset / sizeof(u16)), buf + offset,
rx_len);
if (dd->legacy_acceleration)
start_legacy_acceleration(dd);
if (ret < 0)
return ret;
offset += rx_len;
len -= rx_len;
}
return 0;
}
static int
spi_read_2(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
return spi_rw_2(dd, address, buf, len, spi_read_2_page);
}
static int
spi_write_2(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
return spi_rw_2(dd, address, buf, len, spi_write_2_page);
}
/* ======================================================================== */
static int
spi_read_3(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
return spi_read_123(dd, address, buf, len, false);
}
static int
spi_write_3(struct dev_data *dd, u16 address, u8 *buf, u16 len)
{
return spi_write_123(dd, address, buf, len, false);
}
/* ======================================================================== */
static struct chip_access_method chip_access_methods[] = {
{
.read = spi_read_1,
.write = spi_write_1,
},
{
.read = spi_read_2,
.write = spi_write_2,
},
{
.read = spi_read_3,
.write = spi_write_3,
},
};
static int
set_chip_access_method(struct dev_data *dd, u8 method)
{
if (method == 0 || method > ARRAY_SIZE(chip_access_methods))
return -EPERM;
memcpy(&dd->chip, &chip_access_methods[method - 1], sizeof(dd->chip));
return 0;
}
/* ======================================================================== */
static inline int
stop_legacy_acceleration_canned(struct dev_data *dd)
{
u16 value = dd->irq_param[18];
return dd->chip.write(dd, dd->irq_param[16], (u8 *)&value,
sizeof(value));
}
static inline int
start_legacy_acceleration_canned(struct dev_data *dd)
{
u16 value = dd->irq_param[17];
return dd->chip.write(dd, dd->irq_param[16], (u8 *)&value,
sizeof(value));
}
/* ======================================================================== */
#define FLASH_BLOCK_SIZE 64 /* flash write buffer in words */
#define FIRMWARE_SIZE 0xC000 /* fixed 48Kbytes */
static int bootloader_wait_ready(struct dev_data *dd)
{
u16 status, i;
for (i = 0; i < 15; i++) {
if (spi_read_3(dd, 0x00FF, (u8 *)&status,
sizeof(status)) != 0)
return -EPERM;
if (status == 0xABCC)
return 0;
if (i >= 3)
usleep_range(500, 700);
}
ERROR("unexpected status %04X", status);
return -EPERM;
}
static int bootloader_complete(struct dev_data *dd)
{
u16 value = 0x5432;
return spi_write_3(dd, 0x00FF, (u8 *)&value, sizeof(value));
}
static int bootloader_read_data(struct dev_data *dd, u16 *value)
{
u16 buffer[2];
if (spi_read_3(dd, 0x00FE, (u8 *)buffer, sizeof(buffer)) != 0)
return -EPERM;
if (buffer[1] != 0xABCC)
return -EPERM;
*value = buffer[0];
return bootloader_complete(dd);
}
static int bootloader_write_data(struct dev_data *dd, u16 value)
{
u16 buffer[2] = {value, 0x5432};
if (bootloader_wait_ready(dd) != 0)
return -EPERM;
return spi_write_3(dd, 0x00FE, (u8 *)buffer, sizeof(buffer));
}
static int bootloader_wait_command(struct dev_data *dd)
{
u16 value, i;
for (i = 0; i < 15; i++) {
if (bootloader_read_data(dd, &value) == 0 && value == 0x003E)
return 0;
if (i >= 3)
usleep_range(500, 700);
}
return -EPERM;
}
static int bootloader_enter(struct dev_data *dd)
{
int i;
u16 enter[3] = {0x0047, 0x00C7, 0x0007};
for (i = 0; i < 3; i++) {
if (spi_write_3(dd, 0x7F00, (u8 *)&enter[i],
sizeof(enter[i])) != 0)
return -EPERM;
}
if (bootloader_wait_command(dd) != 0)
return -EPERM;
return 0;
}
static int bootloader_exit(struct dev_data *dd)
{
u16 value = 0x0000;
if (bootloader_write_data(dd, 0x0001) != 0)
return -EPERM;
return spi_write_3(dd, 0x7F00, (u8 *)&value, sizeof(value));
}
static int bootloader_get_crc(struct dev_data *dd, u16 *crc16, u16 len)
{
u16 command[] = {0x0030, 0x0002, 0x0000, 0x0000, len & 0xFF,
len >> 8}, value[2], i;
for (i = 0; i < ARRAY_SIZE(command); i++)
if (bootloader_write_data(dd, command[i]) != 0)
return -EPERM;
msleep(200); /* wait 200ms for it to get done */
for (i = 0; i < 2; i++)
if (bootloader_read_data(dd, &value[i]) != 0)
return -EPERM;
if (bootloader_wait_command(dd) != 0)
return -EPERM;
*crc16 = (value[1] << 8) | value[0];
return 0;
}
static int bootloader_set_byte_mode(struct dev_data *dd)
{
u16 command[2] = {0x000A, 0x0000}, i;
for (i = 0; i < ARRAY_SIZE(command); i++)
if (bootloader_write_data(dd, command[i]) != 0)
return -EPERM;
if (bootloader_wait_command(dd) != 0)
return -EPERM;
return 0;
}
static int bootloader_erase_flash(struct dev_data *dd)
{
if (bootloader_write_data(dd, 0x0002) != 0)
return -EPERM;
msleep(60); /* wait 60ms */
if (bootloader_wait_command(dd) != 0)
return -EPERM;
return 0;
}
static int bootloader_write_flash(struct dev_data *dd, u16 *image, u16 len)
{
u16 command[] = {0x00F0, 0x0000, len >> 8, 0x0000, 0x0000};
u16 i, buffer[FLASH_BLOCK_SIZE];
for (i = 0; i < ARRAY_SIZE(command); i++)
if (bootloader_write_data(dd, command[i]) != 0)
return -EPERM;
for (i = 0; i < ((len / sizeof(u16)) / FLASH_BLOCK_SIZE); i++) {
if (bootloader_wait_ready(dd) != 0)
return -EPERM;
memcpy(buffer, (void *)(image + i * FLASH_BLOCK_SIZE),
sizeof(buffer));
if (spi_write_3(dd, ((i % 2) == 0) ? 0x0000 : 0x0040,
(u8 *)buffer, sizeof(buffer)) != 0)
return -EPERM;
if (bootloader_complete(dd) != 0)
return -EPERM;
}
usleep_range(10000, 11000);
if (bootloader_wait_command(dd) != 0)
return -EPERM;
return 0;
}
static int device_fw_load(struct dev_data *dd, const struct firmware *fw)
{
u16 fw_crc16, chip_crc16;
fw_crc16 = crc16(0, fw->data, fw->size);
INFO("firmware size (%d) CRC16(0x%04X)", (int)fw->size, fw_crc16);
if (bootloader_enter(dd) != 0) {
ERROR("failed to enter bootloader");
return -EPERM;
}
if (bootloader_get_crc(dd, &chip_crc16, fw->size) != 0) {
ERROR("failed to get CRC16 from the chip");
return -EPERM;
}
INFO("chip CRC16(0x%04X)", chip_crc16);
if (fw_crc16 != chip_crc16) {
INFO("will reprogram chip");
if (bootloader_erase_flash(dd) != 0) {
ERROR("failed to erase chip flash");
return -EPERM;
}
INFO("flash erase OK");
if (bootloader_set_byte_mode(dd) != 0) {
ERROR("failed to set byte mode");
return -EPERM;
}
INFO("byte mode OK");
if (bootloader_write_flash(dd, (u16 *)fw->data,
fw->size) != 0) {
ERROR("failed to write flash");
return -EPERM;
}
INFO("flash write OK");
if (bootloader_get_crc(dd, &chip_crc16, fw->size) != 0) {
ERROR("failed to get CRC16 from the chip");
return -EPERM;
}
if (fw_crc16 != chip_crc16) {
ERROR("failed to verify programming! (0x%04X)",
chip_crc16);
return -EPERM;
}
INFO("chip programmed successfully, new chip CRC16(0x%04X)",
chip_crc16);
}
if (bootloader_exit(dd) != 0) {
ERROR("failed to exit bootloader");
return -EPERM;
}
return 0;
}
static int fw_request_load(struct dev_data *dd)
{
const struct firmware *fw;
int ret;
ret = request_firmware(&fw, "maxim_fp35.bin", &dd->spi->dev);
if (ret || fw == NULL) {
ERROR("firmware request failed (%d,%p)", ret, fw);
return -EPERM;
}
if (fw->size != FIRMWARE_SIZE) {
release_firmware(fw);
ERROR("incoming firmware is of wrong size (%04X)",
(int)fw->size);
return -EPERM;
}
ret = device_fw_load(dd, fw);
if (ret != 0 && bootloader_exit(dd) != 0)
ERROR("failed to exit bootloader");
release_firmware(fw);
return ret;
}
/* ======================================================================== */
static void stop_idle_scan(struct dev_data *dd)
{
u16 value;
value = dd->irq_param[13];
(void)dd->chip.write(dd, dd->irq_param[19], (u8 *)&value,
sizeof(value));
}
static void stop_scan_canned(struct dev_data *dd)
{
u16 value[2], i;
if (dd->legacy_acceleration)
(void)stop_legacy_acceleration_canned(dd);
value[0] = dd->irq_param[13];
(void)dd->chip.write(dd, dd->irq_param[12], (u8 *)value,
sizeof(value[0]));
usleep_range(dd->irq_param[15], dd->irq_param[15] + 1000);
(void)dd->chip.read(dd, dd->irq_param[0], (u8 *)value,
sizeof(value));
(void)dd->chip.write(dd, dd->irq_param[0], (u8 *)value,
sizeof(value));
if (!dd->compatibility_mode) {
for (i = 28; i < 32; i++) {
value[0] = dd->irq_param[i];
(void)dd->chip.write(dd, dd->irq_param[27],
(u8 *)value, sizeof(value[0]));
}
value[0] = dd->irq_param[33];
(void)dd->chip.write(dd, dd->irq_param[32],
(u8 *)value, sizeof(value[0]));
usleep_range(500, 1000);
for (i = 28; i < 32; i++) {
value[0] = dd->irq_param[i];
(void)dd->chip.write(dd, dd->irq_param[27],
(u8 *)value, sizeof(value[0]));
}
value[0] = dd->irq_param[13];
(void)dd->chip.write(dd, dd->irq_param[32],
(u8 *)value, sizeof(value[0]));
}
}
#if !SUSPEND_POWER_OFF
static void start_scan_canned(struct dev_data *dd)
{
u16 value;
if (dd->legacy_acceleration) {
(void)start_legacy_acceleration_canned(dd);
} else {
value = dd->irq_param[14];
(void)dd->chip.write(dd, dd->irq_param[12], (u8 *)&value,
sizeof(value));
}
}
#endif
static void enable_gesture(struct dev_data *dd)
{
u16 value;
INFO("%s : start", __func__);
if (!dd->idle) {
stop_scan_canned(dd);
if (!dd->compatibility_mode) {
value = dd->irq_param[13];
(void)dd->chip.write(dd, dd->irq_param[34],
(u8 *)&value,
sizeof(value));
value = dd->irq_param[36];
(void)dd->chip.write(dd, dd->irq_param[35],
(u8 *)&value,
sizeof(value));
}
}
value = dd->irq_param[18];
(void)dd->chip.write(dd, dd->irq_param[16], (u8 *)&value,
sizeof(value));
value = dd->irq_param[20];
(void)dd->chip.write(dd, dd->irq_param[19], (u8 *)&value,
sizeof(value));
if (!dd->idle) {
value = dd->irq_param[26];
(void)dd->chip.write(dd, dd->irq_param[25], (u8 *)&value,
sizeof(value));
}
INFO("%s : end", __func__);
}
static void finish_gesture(struct dev_data *dd)
{
struct maxim_sti_pdata *pdata = dd->spi->dev.platform_data;
u16 value;
int ret;
u8 fail_count = 0;
INFO("%s : start", __func__);
value = dd->irq_param[21];
(void)dd->chip.write(dd, dd->irq_param[19], (u8 *)&value,
sizeof(value));
do {
msleep(20);
ret = dd->chip.read(dd, dd->irq_param[25], (u8 *)&value,
sizeof(value));
if (ret < 0 || fail_count >= 20) {
ERROR("failed to read control register (%d)", ret);
pdata->reset(pdata, 0);
msleep(20);
pdata->reset(pdata, 1);
return;
}
INFO("ctrl = 0x%04X", value);
fail_count++;
} while (value);
INFO("%s : end", __func__);
}
static int regulator_control(struct dev_data *dd, bool on)
{
int ret, tmp;
if (!dd->reg_avdd || !dd->reg_dvdd)
return -EINVAL;
if (on) {
ret = regulator_enable(dd->reg_dvdd);
if (ret < 0) {
ERROR("Failed to enable regulator dvdd: %d", ret);
return ret;
}
usleep_range(1000, 1020);
ret = regulator_enable(dd->reg_avdd);
if (ret < 0) {
ERROR("Failed to enable regulator avdd: %d", ret);
regulator_disable(dd->reg_dvdd);
return ret;
}
} else {
ret = regulator_disable(dd->reg_avdd);
if (ret < 0) {
ERROR("Failed to disable regulator avdd: %d", ret);
return ret;
}
ret = regulator_disable(dd->reg_dvdd);
if (ret < 0) {
ERROR("Failed to disable regulator dvdd: %d", ret);
tmp = regulator_enable(dd->reg_avdd);
return ret;
}
}
return 0;
}
static int regulator_init(struct dev_data *dd)
{
struct regulator *reg_avdd;
struct regulator *reg_dvdd;
reg_avdd = devm_regulator_get(&dd->spi->dev, "avdd");
if (IS_ERR(reg_avdd)) {
dev_err(&dd->spi->dev, "Failed to get avdd\n");
return PTR_ERR(reg_avdd);
} else {
dd->reg_avdd = reg_avdd;
}
reg_dvdd = devm_regulator_get(&dd->spi->dev, "dvdd");
if (IS_ERR(reg_dvdd)) {
dev_err(&dd->spi->dev, "Failed to get dvdd\n");
return PTR_ERR(reg_dvdd);
} else {
dd->reg_dvdd = reg_dvdd;
}
return 0;
}
#ifdef CONFIG_OF
#define MAXIM_STI_GPIO_ERROR(ret, gpio, op) \
do { \
if (ret < 0) { \
pr_err("%s: GPIO %d %s failed (%d)\n", __func__, gpio, op, \
ret); \
return ret; \
} \
} while (0)
int maxim_sti_gpio_init(struct device *dev, struct maxim_sti_pdata *pdata,
bool init)
{
int ret;
struct pinctrl *pinctrl;
struct pinctrl_state *irq_suspend;
struct pinctrl_state *irq_active;
struct pinctrl_state *reset_suspend;
struct pinctrl_state *reset_active;
pinctrl = devm_pinctrl_get(dev);
if (IS_ERR(pinctrl)) {
dev_err(dev, "%s: devm_pinctrl_get error\n",
__func__);
return -EINVAL;
}
if (init) {
irq_active = pinctrl_lookup_state(pinctrl, "irq_gpio-active");
if (IS_ERR(irq_active)) {
dev_err(dev, "%s: cannot lookup pinctrl\n",
__func__);
devm_pinctrl_put(pinctrl);
return -EINVAL;
}
ret = pinctrl_select_state(pinctrl, irq_active);
if (ret) {
dev_err(dev,
"%s: cannot select pinctrl state\n",
__func__);
devm_pinctrl_put(pinctrl);
return ret;
}
ret = gpio_request(pdata->gpio_irq, "maxim_sti_irq");
if (ret)
devm_pinctrl_put(pinctrl);
MAXIM_STI_GPIO_ERROR(ret, pdata->gpio_irq, "request");
ret = gpio_direction_input(pdata->gpio_irq);
if (ret) {
gpio_free(pdata->gpio_irq);
devm_pinctrl_put(pinctrl);
}
MAXIM_STI_GPIO_ERROR(ret, pdata->gpio_irq, "direction");
reset_active =
pinctrl_lookup_state(pinctrl, "reset_gpio-active");
if (IS_ERR(reset_active)) {
dev_err(dev, "%s: cannot lookup pinctrl\n",
__func__);
devm_pinctrl_put(pinctrl);
return -EINVAL;
}
ret = pinctrl_select_state(pinctrl, reset_active);
if (ret) {
dev_err(dev,
"%s: cannot select pinctrl state\n",
__func__);
devm_pinctrl_put(pinctrl);
return ret;
}
ret = gpio_request(pdata->gpio_reset, "maxim_sti_reset");
if (ret) {
gpio_free(pdata->gpio_irq);
devm_pinctrl_put(pinctrl);
}
MAXIM_STI_GPIO_ERROR(ret, pdata->gpio_reset, "request");
ret = gpio_direction_output(pdata->gpio_reset,
pdata->default_reset_state);
if (ret) {
gpio_free(pdata->gpio_irq);
gpio_free(pdata->gpio_reset);
devm_pinctrl_put(pinctrl);
}
MAXIM_STI_GPIO_ERROR(ret, pdata->gpio_reset, "direction");
} else {
irq_suspend = pinctrl_lookup_state(pinctrl, "irq_gpio-suspend");
if (IS_ERR(irq_active)) {
dev_err(dev, "%s: cannot lookup pinctrl\n",
__func__);
devm_pinctrl_put(pinctrl);
return -EINVAL;
}
ret = pinctrl_select_state(pinctrl, irq_suspend);
if (ret) {
dev_err(dev,
"%s: cannot select pinctrl state\n",
__func__);
devm_pinctrl_put(pinctrl);
return ret;
}
gpio_free(pdata->gpio_irq);
reset_suspend =
pinctrl_lookup_state(pinctrl, "reset_gpio-suspend");
if (IS_ERR(reset_suspend)) {
dev_err(dev, "%s: cannot lookup pinctrl\n",
__func__);
devm_pinctrl_put(pinctrl);
return -EINVAL;
}
ret = pinctrl_select_state(pinctrl, reset_suspend);
if (ret) {
dev_err(dev,
"%s: cannot select pinctrl state\n",
__func__);
devm_pinctrl_put(pinctrl);
return ret;
}
gpio_free(pdata->gpio_reset);
}
devm_pinctrl_put(pinctrl);
return 0;
}
void maxim_sti_gpio_reset(struct maxim_sti_pdata *pdata, int value)
{
gpio_set_value(pdata->gpio_reset, !!value);
}
int maxim_sti_gpio_irq(struct maxim_sti_pdata *pdata)
{
return gpio_get_value(pdata->gpio_irq);
}
/****************************************************************************\
* Device Tree Support
\****************************************************************************/
static int maxim_parse_dt(struct device *dev, struct maxim_sti_pdata *pdata)
{
struct device_node *np = dev->of_node;
u32 val;
const char *str;
int ret;
pdata->gpio_reset = of_get_named_gpio(np, "maxim_sti,reset-gpio", 0);
if (!gpio_is_valid(pdata->gpio_reset)) {
dev_err(dev, "%s: unable to read reset-gpio\n", __func__);
ret = -EPERM;
goto fail;
}
pdata->gpio_irq = of_get_named_gpio(np, "maxim_sti,irq-gpio", 0);
if (!gpio_is_valid(pdata->gpio_irq)) {
dev_err(dev, "%s: unable to read irq-gpio\n", __func__);
ret = -EPERM;
goto fail;
}
ret = of_property_read_u32(np, "maxim_sti,nl_mc_groups", &val);
if (ret) {
dev_err(dev, "%s: unable to read nl_mc_groups (%d)\n",
__func__, ret);
goto fail;
}
pdata->nl_mc_groups = (u8)val;
ret = of_property_read_u32(np, "maxim_sti,chip_access_method", &val);
if (ret) {
dev_err(dev, "%s: unable to read chip_access_method (%d)\n",
__func__, ret);
goto fail;
}
pdata->chip_access_method = (u8)val;
ret = of_property_read_u32(np, "maxim_sti,default_reset_state", &val);
if (ret) {
dev_err(dev, "%s: unable to read default_reset_state (%d)\n",
__func__, ret);
goto fail;
}
pdata->default_reset_state = (u8)val;
ret = of_property_read_u32(np, "maxim_sti,tx_buf_size", &val);
if (ret) {
dev_err(dev, "%s: unable to read tx_buf_size (%d)\n",
__func__, ret);
goto fail;
}
pdata->tx_buf_size = (u16)val;
ret = of_property_read_u32(np, "maxim_sti,rx_buf_size", &val);
if (ret) {
dev_err(dev, "%s: unable to read rx_buf_size (%d)\n",
__func__, ret);
goto fail;
}
pdata->rx_buf_size = (u16)val;
ret = of_property_read_string(np, "maxim_sti,touch_fusion", &str);
if (ret) {
dev_err(dev, "%s: unable to read touch_fusion location (%d)\n",
__func__, ret);
goto fail;
}
pdata->touch_fusion = (char *)str;
ret = of_property_read_string(np, "maxim_sti,config_file", &str);
if (ret) {
dev_err(dev, "%s: unable to read config_file location (%d)\n",
__func__, ret);
goto fail;
}
pdata->config_file = (char *)str;
ret = of_property_read_string(np, "maxim_sti,nl_family", &str);
if (ret) {
dev_err(dev, "%s: unable to read nl_family (%d)\n",
__func__, ret);
goto fail;
}
pdata->nl_family = (char *)str;
ret = of_property_read_string(np, "maxim_sti,fw_name", &str);
if (ret) {
dev_err(dev, "%s: unable to read fw_name (%d)\n",
__func__, ret);
}
pdata->fw_name = (char *)str;
ret = of_property_read_u32(np, "wakeup_gesture_support", &val);
if (ret) {
dev_err(dev, "%s: unable to read wakeup_gesture_support (%d)\n",
__func__, ret);
goto fail;
}
pdata->wakeup_gesture_support = (u16)val;
pdata->init = maxim_sti_gpio_init;
pdata->reset = maxim_sti_gpio_reset;
pdata->irq = maxim_sti_gpio_irq;
return 0;
fail:
return ret;
}
#endif
/****************************************************************************\
* Suspend/resume processing *
\****************************************************************************/
#ifdef CONFIG_PM_SLEEP
static int early_suspend(struct device *dev)
{
struct dev_data *dd = spi_get_drvdata(to_spi_device(dev));
#if SUSPEND_POWER_OFF
struct maxim_sti_pdata *pdata = dev->platform_data;
int ret;
#endif
INFO("%s : start", __func__);
if (dd->suspend_in_progress) {
INFO("%s : suspend in progress", __func__);
return 0;
}
dd->suspend_in_progress = true;
wake_up_process(dd->thread);
INFO("%s : waiting", __func__);
wait_for_completion(&dd->suspend_resume);
#if SUSPEND_POWER_OFF
/* reset-low and power-down */
pdata->reset(pdata, 0);
usleep_range(100, 120);
ret = regulator_control(dd, false);
if (ret < 0) {
pdata->reset(pdata, 1);
return ret;
}
#endif
INFO("%s : end", __func__);
return 0;
}
static int late_resume(struct device *dev)
{
struct dev_data *dd = spi_get_drvdata(to_spi_device(dev));
#if SUSPEND_POWER_OFF
struct maxim_sti_pdata *pdata = dev->platform_data;
int ret;
#endif
INFO("%s : start", __func__);
if (!dd->suspend_in_progress) {
INFO("%s : suspend not in progress", __func__);
return 0;
}
#if SUSPEND_POWER_OFF
/* power-up and reset-high */
ret = regulator_control(dd, true);
if (ret < 0)
return ret;
usleep_range(300, 400);
pdata->reset(pdata, 1);
#endif
dd->resume_in_progress = true;
wake_up_process(dd->thread);
INFO("%s : waiting", __func__);
wait_for_completion(&dd->suspend_resume);
INFO("%s : end", __func__);
return 0;
}
static int suspend(struct device *dev)
{
struct dev_data *dd = spi_get_drvdata(to_spi_device(dev));
if (dd->irq_registered && dd->gesture_en) {
disable_irq(dd->spi->irq);
enable_irq_wake(dd->spi->irq);
}
return 0;
}
static int resume(struct device *dev)
{
struct dev_data *dd = spi_get_drvdata(to_spi_device(dev));
if (dd->irq_registered && dd->gesture_en) {
disable_irq_wake(dd->spi->irq);
enable_irq(dd->spi->irq);
}
return 0;
}
static const struct dev_pm_ops pm_ops = {
.suspend = suspend,
.resume = resume,
};
#if INPUT_ENABLE_DISABLE
static int input_disable(struct input_dev *dev)
{
struct dev_data *dd = input_get_drvdata(dev);
return early_suspend(&dd->spi->dev);
}
static int input_enable(struct input_dev *dev)
{
struct dev_data *dd = input_get_drvdata(dev);
return late_resume(&dd->spi->dev);
}
#endif
#if FB_CALLBACK && defined(CONFIG_FB)
static int fb_notifier_callback(struct notifier_block *self,
unsigned long event, void *data)
{
struct fb_event *evdata = data;
int *blank;
struct dev_data *dd = container_of(self,
struct dev_data, fb_notifier);
if (evdata && evdata->data && event == FB_EVENT_BLANK) {
blank = evdata->data;
if (*blank == FB_BLANK_UNBLANK)
late_resume(&dd->spi->dev);
else if (*blank == FB_BLANK_POWERDOWN)
early_suspend(&dd->spi->dev);
}
return 0;
}
#endif
#endif
/****************************************************************************\
* Netlink processing *
\****************************************************************************/
static inline int
nl_msg_new(struct dev_data *dd, u8 dst)
{
dd->outgoing_skb = alloc_skb(NL_BUF_SIZE, GFP_KERNEL);
if (dd->outgoing_skb == NULL)
return -ENOMEM;
nl_msg_init(dd->outgoing_skb->data, dd->nl_family.id, dd->nl_seq++,
dst);
if (dd->nl_seq == 0)
dd->nl_seq++;
return 0;
}
static int
nl_callback_noop(struct sk_buff *skb, struct genl_info *info)
{
return 0;
}
static inline bool
nl_process_input_msg(struct dev_data *dd, struct sk_buff *skb)
{
struct nlattr *attr;
u16 msg_id;
void *msg;
struct dr_input *input_msg;
u8 i, inp;
attr = NL_ATTR_FIRST(skb->data);
if (attr->nla_type != DR_INPUT)
return false;
for (; attr < NL_ATTR_LAST(skb->data); attr = NL_ATTR_NEXT(attr)) {
msg_id = attr->nla_type;
msg = NL_ATTR_VAL(attr, void);
switch (msg_id) {
case DR_INPUT:
for (i = 0; i < INPUT_DEVICES; i++)
if (dd->input_dev[i] == NULL) {
ERROR("input device %d is NULL", i);
return true;
}
input_msg = msg;
if (input_msg->events == 0) {
if (dd->eraser_active) {
input_report_key(
dd->input_dev[INPUT_DEVICES - 1],
BTN_TOOL_RUBBER, 0);
dd->eraser_active = false;
}
for (i = 0; i < INPUT_DEVICES; i++) {
input_mt_sync(dd->input_dev[i]);
input_sync(dd->input_dev[i]);
}
} else {
for (i = 0; i < input_msg->events; i++) {
switch (input_msg->event[i].tool_type) {
case DR_INPUT_FINGER:
inp = 0;
input_report_abs(dd->input_dev[inp],
ABS_MT_TOOL_TYPE,
MT_TOOL_FINGER);
break;
case DR_INPUT_STYLUS:
inp = INPUT_DEVICES - 1;
input_report_abs(dd->input_dev[inp],
ABS_MT_TOOL_TYPE,
MT_TOOL_PEN);
break;
case DR_INPUT_ERASER:
inp = INPUT_DEVICES - 1;
input_report_key(dd->input_dev[inp],
BTN_TOOL_RUBBER, 1);
dd->eraser_active = true;
break;
default:
inp = 0;
ERROR("invalid input tool type (%d)",
input_msg->event[i].tool_type);
break;
}
input_report_abs(dd->input_dev[inp],
ABS_MT_TRACKING_ID,
input_msg->event[i].id);
input_report_abs(dd->input_dev[inp],
ABS_MT_POSITION_X,
input_msg->event[i].x);
input_report_abs(dd->input_dev[inp],
ABS_MT_POSITION_Y,
input_msg->event[i].y);
input_report_abs(dd->input_dev[inp],
ABS_MT_PRESSURE,
input_msg->event[i].z);
input_mt_sync(dd->input_dev[inp]);
}
for (i = 0; i < INPUT_DEVICES; i++)
input_sync(dd->input_dev[i]);
}
break;
default:
ERROR("unexpected message %d", msg_id);
break;
}
}
return true;
}
static inline bool
nl_process_driver_msg(struct dev_data *dd, u16 msg_id, u16 msg_len, void *msg)
{
struct maxim_sti_pdata *pdata = dd->spi->dev.platform_data;
struct dr_add_mc_group *add_mc_group_msg;
struct dr_echo_request *echo_msg;
struct fu_echo_response *echo_response;
struct dr_chip_read *read_msg;
struct fu_chip_read_result *read_result;
struct dr_chip_write *write_msg;
struct dr_chip_access_method *chip_access_method_msg;
struct dr_delay *delay_msg;
struct fu_irqline_status *irqline_status;
struct dr_config_irq *config_irq_msg;
struct dr_config_input *config_input_msg;
struct dr_config_watchdog *config_watchdog_msg;
struct dr_input *input_msg;
struct dr_legacy_acceleration *legacy_acceleration_msg;
struct dr_handshake *handshake_msg;
struct fu_handshake_response *handshake_response;
struct dr_config_fw *config_fw_msg;
struct dr_sysfs_ack *sysfs_ack_msg;
struct dr_idle *idle_msg;
struct dr_tf_status *tf_status_msg;
u8 i, inp, irq_edge;
int ret;
#if HI02
u16 read_value[2] = { 0 };
#endif
if (dd->expect_resume_ack && msg_id != DR_DECONFIG &&
msg_id != DR_RESUME_ACK)
return false;
switch (msg_id) {
case DR_ADD_MC_GROUP:
add_mc_group_msg = msg;
if (add_mc_group_msg->number >= pdata->nl_mc_groups) {
ERROR("invalid multicast group number %d (%d)",
add_mc_group_msg->number, pdata->nl_mc_groups);
return false;
}
if (dd->nl_mc_groups[add_mc_group_msg->number].id != 0)
return false;
dd->nl_ops[add_mc_group_msg->number].cmd =
add_mc_group_msg->number;
dd->nl_ops[add_mc_group_msg->number].doit = nl_callback_noop;
ret = genl_register_ops(&dd->nl_family,
&dd->nl_ops[add_mc_group_msg->number]);
if (ret < 0)
ERROR("failed to add multicast group op (%d)", ret);
GENL_COPY(dd->nl_mc_groups[add_mc_group_msg->number].name,
add_mc_group_msg->name);
ret = genl_register_mc_group(&dd->nl_family,
&dd->nl_mc_groups[add_mc_group_msg->number]);
if (ret < 0)
ERROR("failed to add multicast group (%d)", ret);
return false;
case DR_ECHO_REQUEST:
echo_msg = msg;
echo_response = nl_alloc_attr(dd->outgoing_skb->data,
FU_ECHO_RESPONSE,
sizeof(*echo_response));
if (echo_response == NULL)
goto alloc_attr_failure;
echo_response->cookie = echo_msg->cookie;
return true;
case DR_CHIP_READ:
read_msg = msg;
read_result = nl_alloc_attr(dd->outgoing_skb->data,
FU_CHIP_READ_RESULT,
sizeof(*read_result) + read_msg->length);
if (read_result == NULL)
goto alloc_attr_failure;
read_result->address = read_msg->address;
read_result->length = read_msg->length;
ret = dd->chip.read(dd, read_msg->address, read_result->data,
read_msg->length);
if (ret < 0)
ERROR("failed to read from chip (%d)", ret);
return true;
case DR_CHIP_WRITE:
write_msg = msg;
#if HI02
if (write_msg->address == dd->irq_param[12] &&
write_msg->data[0] == dd->irq_param[13]) {
ret = dd->chip.write(dd, write_msg->address,
write_msg->data,
write_msg->length);
if (ret < 0)
ERROR("failed to write chip (%d)", ret);
usleep_range(15000, 16000);
ret = dd->chip.read(dd, dd->irq_param[0],
(u8 *)read_value,
sizeof(read_value));
if (ret < 0)
ERROR("failed to read from chip (%d)", ret);
ret = dd->chip.write(dd, dd->irq_param[0],
(u8 *)read_value,
sizeof(read_value));
return false;
}
if (write_msg->address == dd->irq_param[0]) {
read_value[0] = ((u16 *)write_msg->data)[0];
ret = dd->chip.write(dd, write_msg->address,
(u8 *)read_value,
sizeof(read_value));
return false;
}
#endif
ret = dd->chip.write(dd, write_msg->address, write_msg->data,
write_msg->length);
if (ret < 0)
ERROR("failed to write chip (%d)", ret);
return false;
case DR_CHIP_RESET:
pdata->reset(pdata, ((struct dr_chip_reset *)msg)->state);
return false;
case DR_GET_IRQLINE:
irqline_status = nl_alloc_attr(dd->outgoing_skb->data,
FU_IRQLINE_STATUS,
sizeof(*irqline_status));
if (irqline_status == NULL)
goto alloc_attr_failure;
irqline_status->status = pdata->irq(pdata);
return true;
case DR_DELAY:
delay_msg = msg;
if (delay_msg->period > 1000)
msleep(delay_msg->period / 1000);
usleep_range(delay_msg->period % 1000,
(delay_msg->period % 1000) + 10);
return false;
case DR_CHIP_ACCESS_METHOD:
chip_access_method_msg = msg;
ret = set_chip_access_method(dd,
chip_access_method_msg->method);
if (ret < 0)
ERROR("failed to set chip access method (%d) (%d)",
ret, chip_access_method_msg->method);
return false;
case DR_CONFIG_IRQ:
config_irq_msg = msg;
if (config_irq_msg->irq_params > MAX_IRQ_PARAMS) {
ERROR("too many IRQ parameters");
return false;
}
dd->nirq_params = config_irq_msg->irq_params;
dd->compatibility_mode = dd->nirq_params <= OLD_NIRQ_PARAMS;
irq_edge = *((u8 *)msg + msg_len - 1);
memcpy(dd->irq_param, config_irq_msg->irq_param,
config_irq_msg->irq_params * sizeof(dd->irq_param[0]));
if (dd->irq_registered)
return false;
dd->service_irq = service_irq;
ret = request_irq(dd->spi->irq, irq_handler,
(irq_edge == DR_IRQ_RISING_EDGE) ?
IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING,
pdata->nl_family, dd);
if (ret < 0) {
ERROR("failed to request IRQ (%d)", ret);
} else {
dd->irq_registered = true;
wake_up_process(dd->thread);
}
return false;
case DR_CONFIG_INPUT:
config_input_msg = msg;
for (i = 0; i < INPUT_DEVICES; i++)
if (dd->input_dev[i] != NULL)
return false;
for (i = 0; i < INPUT_DEVICES; i++) {
dd->input_dev[i] = input_allocate_device();
if (dd->input_dev[i] == NULL) {
ERROR("failed to allocate input device");
continue;
}
snprintf(dd->input_phys, sizeof(dd->input_phys),
"%s/input%d", dev_name(&dd->spi->dev), i);
dd->input_dev[i]->name = pdata->nl_family;
dd->input_dev[i]->phys = dd->input_phys;
dd->input_dev[i]->id.bustype = BUS_SPI;
#if defined(CONFIG_PM_SLEEP) && INPUT_ENABLE_DISABLE
if (i == 0) {
dd->input_dev[i]->enable = input_enable;
dd->input_dev[i]->disable = input_disable;
dd->input_dev[i]->enabled = true;
input_set_drvdata(dd->input_dev[i], dd);
}
#endif
#if SONY_CPU_BOOST
if (i == 0)
input_set_capability(dd->input_dev[i], EV_SW,
SW_TOUCH_ACTIVITY);
#endif
__set_bit(EV_SYN, dd->input_dev[i]->evbit);
__set_bit(EV_ABS, dd->input_dev[i]->evbit);
if (i == (INPUT_DEVICES - 1)) {
__set_bit(EV_KEY, dd->input_dev[i]->evbit);
__set_bit(BTN_TOOL_RUBBER,
dd->input_dev[i]->keybit);
}
if (pdata->wakeup_gesture_support) {
dd->evdt_node = evdt_initialize(&dd->spi->dev,
dd->input_dev[i],
MXM_WAKEUP_GESTURE);
if (!dd->evdt_node) {
INFO("No wakeup_gesture dt");
} else {
INFO("%d - Touch Wakeup Feature OK", i);
dd->ew_input_device_id = i;
}
}
input_set_abs_params(dd->input_dev[i],
ABS_MT_POSITION_X, 0,
config_input_msg->x_range, 0, 0);
input_set_abs_params(dd->input_dev[i],
ABS_MT_POSITION_Y, 0,
config_input_msg->y_range, 0, 0);
input_set_abs_params(dd->input_dev[i],
ABS_MT_PRESSURE, 0, 0xFF, 0, 0);
input_set_abs_params(dd->input_dev[i],
ABS_MT_TRACKING_ID, 0,
MAX_INPUT_EVENTS, 0, 0);
if (i == (INPUT_DEVICES - 1))
input_set_abs_params(dd->input_dev[i],
ABS_MT_TOOL_TYPE, 0,
MT_TOOL_MAX, 0, 0);
else
input_set_abs_params(dd->input_dev[i],
ABS_MT_TOOL_TYPE, 0,
MT_TOOL_FINGER, 0, 0);
ret = input_register_device(dd->input_dev[i]);
if (ret < 0) {
input_free_device(dd->input_dev[i]);
dd->input_dev[i] = NULL;
ERROR("failed to register input device");
}
}
#if FB_CALLBACK && defined(CONFIG_FB)
dd->fb_notifier.notifier_call = fb_notifier_callback;
fb_register_client(&dd->fb_notifier);
#endif
/* create symlink */
if (dd->parent == NULL) {
dd->parent = dd->input_dev[0]->dev.kobj.parent;
ret = sysfs_create_link(dd->parent, &dd->spi->dev.kobj,
MAXIM_STI_NAME);
if (ret)
ERROR("sysfs_create_link error\n");
}
return false;
case DR_CONFIG_WATCHDOG:
config_watchdog_msg = msg;
dd->fusion_process = (pid_t)config_watchdog_msg->pid;
return false;
case DR_DECONFIG:
if (dd->irq_registered) {
free_irq(dd->spi->irq, dd);
dd->irq_registered = false;
}
stop_scan_canned(dd);
#if INPUT_ENABLE_DISABLE || FB_CALLBACK || FORCE_NO_DECONFIG
if (!dd->input_no_deconfig) {
#endif
if (dd->parent != NULL) {
sysfs_remove_link(
dd->input_dev[0]->dev.kobj.parent,
MAXIM_STI_NAME);
dd->parent = NULL;
}
for (i = 0; i < INPUT_DEVICES; i++) {
if (dd->input_dev[i] == NULL)
continue;
input_unregister_device(dd->input_dev[i]);
dd->input_dev[i] = NULL;
}
#if FB_CALLBACK && defined(CONFIG_FB)
fb_unregister_client(&dd->fb_notifier);
#endif
#if INPUT_ENABLE_DISABLE || FB_CALLBACK || FORCE_NO_DECONFIG
}
#endif
dd->expect_resume_ack = false;
dd->eraser_active = false;
dd->legacy_acceleration = false;
dd->service_irq = service_irq;
dd->fusion_process = (pid_t)0;
dd->sysfs_update_type = DR_SYSFS_UPDATE_NONE;
return false;
case DR_INPUT:
input_msg = msg;
if (input_msg->events == 0) {
if (dd->eraser_active) {
input_report_key(
dd->input_dev[INPUT_DEVICES - 1],
BTN_TOOL_RUBBER, 0);
dd->eraser_active = false;
}
for (i = 0; i < INPUT_DEVICES; i++) {
input_mt_sync(dd->input_dev[i]);
input_sync(dd->input_dev[i]);
}
} else {
for (i = 0; i < input_msg->events; i++) {
switch (input_msg->event[i].tool_type) {
case DR_INPUT_FINGER:
inp = 0;
input_report_abs(dd->input_dev[inp],
ABS_MT_TOOL_TYPE,
MT_TOOL_FINGER);
break;
case DR_INPUT_STYLUS:
inp = INPUT_DEVICES - 1;
input_report_abs(dd->input_dev[inp],
ABS_MT_TOOL_TYPE,
MT_TOOL_PEN);
break;
case DR_INPUT_ERASER:
inp = INPUT_DEVICES - 1;
input_report_key(dd->input_dev[inp],
BTN_TOOL_RUBBER, 1);
dd->eraser_active = true;
break;
default:
inp = 0;
ERROR("invalid input tool type (%d)",
input_msg->event[i].tool_type);
break;
}
input_report_abs(dd->input_dev[inp],
ABS_MT_TRACKING_ID,
input_msg->event[i].id);
input_report_abs(dd->input_dev[inp],
ABS_MT_POSITION_X,
input_msg->event[i].x);
input_report_abs(dd->input_dev[inp],
ABS_MT_POSITION_Y,
input_msg->event[i].y);
input_report_abs(dd->input_dev[inp],
ABS_MT_PRESSURE,
input_msg->event[i].z);
input_mt_sync(dd->input_dev[inp]);
}
for (i = 0; i < INPUT_DEVICES; i++)
input_sync(dd->input_dev[i]);
}
return false;
case DR_RESUME_ACK:
dd->expect_resume_ack = false;
if (dd->irq_registered && !dd->gesture_en)
enable_irq(dd->spi->irq);
return false;
case DR_LEGACY_FWDL:
ret = fw_request_load(dd);
if (ret < 0)
ERROR("firmware download failed (%d)", ret);
else
INFO("firmware download OK");
return false;
case DR_LEGACY_ACCELERATION:
legacy_acceleration_msg = msg;
if (legacy_acceleration_msg->enable) {
dd->service_irq = service_irq_legacy_acceleration;
start_legacy_acceleration(dd);
dd->legacy_acceleration = true;
} else {
stop_legacy_acceleration(dd);
dd->legacy_acceleration = false;
dd->service_irq = service_irq;
}
return false;
case DR_HANDSHAKE:
handshake_msg = msg;
dd->tf_ver = handshake_msg->tf_ver;
dd->chip_id = handshake_msg->chip_id;
dd->drv_ver = DRIVER_VERSION;
handshake_response = nl_alloc_attr(dd->outgoing_skb->data,
FU_HANDSHAKE_RESPONSE,
sizeof(*handshake_response));
if (handshake_response == NULL)
goto alloc_attr_failure;
handshake_response->driver_ver = dd->drv_ver;
handshake_response->panel_id = panel_id;
handshake_response->driver_protocol = DRIVER_PROTOCOL;
return true;
case DR_CONFIG_FW:
config_fw_msg = msg;
dd->fw_ver = config_fw_msg->fw_ver;
dd->fw_protocol = config_fw_msg->fw_protocol;
return false;
case DR_SYSFS_ACK:
sysfs_ack_msg = msg;
return false;
case DR_IDLE:
idle_msg = msg;
dd->idle = !!(idle_msg->idle);
dd->boost = dd->idle;
return false;
case DR_TF_STATUS:
tf_status_msg = msg;
dd->tf_status = tf_status_msg->tf_status;
return false;
default:
ERROR("unexpected message %d", msg_id);
return false;
}
alloc_attr_failure:
ERROR("failed to allocate response for msg_id %d", msg_id);
return false;
}
static int nl_process_msg(struct dev_data *dd, struct sk_buff *skb)
{
struct nlattr *attr;
bool send_reply = false;
int ret = 0, ret2;
/* process incoming message */
attr = NL_ATTR_FIRST(skb->data);
for (; attr < NL_ATTR_LAST(skb->data); attr = NL_ATTR_NEXT(attr)) {
if (nl_process_driver_msg(dd, attr->nla_type,
(attr->nla_len - NLA_HDRLEN),
NL_ATTR_VAL(attr, void)))
send_reply = true;
}
/* send back reply if requested */
if (send_reply) {
(void)skb_put(dd->outgoing_skb,
NL_SIZE(dd->outgoing_skb->data));
if (NL_SEQ(skb->data) == 0)
ret = genlmsg_unicast(&init_net,
dd->outgoing_skb,
NETLINK_CB(skb).portid);
else
ret = genlmsg_multicast(dd->outgoing_skb, 0,
dd->nl_mc_groups[MC_FUSION].id,
GFP_KERNEL);
if (ret < 0)
ERROR("could not reply to fusion (%d)", ret);
/* allocate new outgoing skb */
ret2 = nl_msg_new(dd, MC_FUSION);
if (ret2 < 0)
ERROR("could not allocate outgoing skb (%d)", ret2);
}
/* free incoming message */
kfree_skb(skb);
return ret;
}
static int
nl_callback_driver(struct sk_buff *skb, struct genl_info *info)
{
struct dev_data *dd;
struct sk_buff *skb2;
unsigned long flags;
/* locate device structure */
spin_lock_irqsave(&dev_lock, flags);
list_for_each_entry(dd, &dev_list, dev_list)
if (dd->nl_family.id == NL_TYPE(skb->data))
break;
spin_unlock_irqrestore(&dev_lock, flags);
if (&dd->dev_list == &dev_list)
return -ENODEV;
if (!dd->nl_enabled)
return -EAGAIN;
/* queue incoming skb and wake up processing thread */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2 == NULL) {
ERROR("failed to clone incoming skb");
return -ENOMEM;
} else {
if (nl_process_input_msg(dd, skb2)) {
kfree_skb(skb2);
return 0;
}
skb_queue_tail(&dd->incoming_skb_queue, skb2);
wake_up_process(dd->thread);
return 0;
}
}
static int
nl_callback_fusion(struct sk_buff *skb, struct genl_info *info)
{
struct dev_data *dd;
unsigned long flags;
/* locate device structure */
spin_lock_irqsave(&dev_lock, flags);
list_for_each_entry(dd, &dev_list, dev_list)
if (dd->nl_family.id == NL_TYPE(skb->data))
break;
spin_unlock_irqrestore(&dev_lock, flags);
if (&dd->dev_list == &dev_list)
return -ENODEV;
if (!dd->nl_enabled)
return -EAGAIN;
(void)genlmsg_multicast(skb_clone(skb, GFP_ATOMIC), 0,
dd->nl_mc_groups[MC_FUSION].id, GFP_ATOMIC);
return 0;
}
/****************************************************************************\
* Interrupt processing *
\****************************************************************************/
static irqreturn_t irq_handler(int irq, void *context)
{
struct dev_data *dd = context;
#if CPU_BOOST
/* implement CPU boost here
if (time_after(jiffies, dd->last_irq_jiffies + INPUT_IDLE_PERIOD))
...;
*/
dd->last_irq_jiffies = jiffies;
#endif
#if SONY_CPU_BOOST
if (dd->boost && likely(dd->input_dev[0])) {
input_event(dd->input_dev[0], EV_SW, SW_TOUCH_ACTIVITY, 1);
input_mt_sync(dd->input_dev[0]);
input_sync(dd->input_dev[0]);
input_event(dd->input_dev[0], EV_SW, SW_TOUCH_ACTIVITY, 0);
input_mt_sync(dd->input_dev[0]);
input_sync(dd->input_dev[0]);
dd->boost = false;
}
#endif
wake_up_process(dd->thread);
return IRQ_HANDLED;
}
static void gesture_wake_detect(struct dev_data *dd)
{
u16 status, value;
int ret = 0;
INFO("%s : start", __func__);
ret = dd->chip.read(dd, dd->irq_param[0],
(u8 *)&status, sizeof(status));
if (ret < 0) {
ERROR("can't read IRQ status (%d)", ret);
INFO("Error stat = 0x%04X", status);
return;
}
INFO("stat = 0x%04X", status);
if (status & dd->irq_param[10]) {
dd->resume_reset = true;
value = dd->irq_param[10];
(void)dd->chip.write(dd, dd->irq_param[0],
(u8 *)&value, sizeof(value));
} else if (status & dd->irq_param[18]) {
ret = dd->chip.read(dd, dd->irq_param[22],
(u8 *)&value, sizeof(value));
if (ret < 0)
ERROR("can't read MAXQ status (%d)", ret);
else {
INFO("Gesture = 0x%04X", value);
evdt_execute(dd->evdt_node,
dd->input_dev[dd->ew_input_device_id], value);
}
value = dd->irq_param[18];
(void)dd->chip.write(dd, dd->irq_param[0],
(u8 *)&value, sizeof(value));
}
INFO("%s : end", __func__);
}
static void service_irq_legacy_acceleration(struct dev_data *dd)
{
struct fu_async_data *async_data;
u16 len, rx_len = 0, offset = 0;
u16 buf[255], rx_limit = 250 * sizeof(u16);
int ret = 0, counter = 0;
INFO("%s : start", __func__);
async_data = nl_alloc_attr(dd->outgoing_skb->data, FU_ASYNC_DATA,
sizeof(*async_data) + dd->irq_param[4] +
2 * sizeof(u16));
if (async_data == NULL) {
ERROR("can't add data to async IRQ buffer");
return;
}
async_data->length = dd->irq_param[4] + 2 * sizeof(u16);
len = async_data->length;
async_data->address = 0;
while (len > 0) {
rx_len = (len > rx_limit) ? rx_limit : len;
ret = spi_read_123(dd, 0x0000, (u8 *)&buf,
rx_len + 4 * sizeof(u16), false);
if (ret < 0)
break;
if (buf[3] == 0xBABE) {
dd->legacy_acceleration = false;
dd->service_irq = service_irq;
nl_msg_init(dd->outgoing_skb->data, dd->nl_family.id,
dd->nl_seq - 1, MC_FUSION);
return;
}
if (rx_limit == rx_len)
usleep_range(200, 300);
if (buf[0] == 0x6060) {
ERROR("data not ready");
start_legacy_acceleration_canned(dd);
ret = -EBUSY;
break;
} else if (buf[0] == 0x8070) {
if (buf[1] == dd->irq_param[1] ||
buf[1] == dd->irq_param[2])
async_data->address = buf[1];
if (async_data->address +
offset / sizeof(u16) != buf[1]) {
ERROR("sequence number incorrect %04X", buf[1]);
start_legacy_acceleration_canned(dd);
ret = -EBUSY;
break;
}
}
counter++;
memcpy(async_data->data + offset, buf + 4, rx_len);
offset += rx_len;
len -= rx_len;
}
async_data->status = *(buf + rx_len / sizeof(u16) + 2);
if (ret < 0) {
ERROR("can't read IRQ buffer (%d)", ret);
nl_msg_init(dd->outgoing_skb->data, dd->nl_family.id,
dd->nl_seq - 1, MC_FUSION);
} else {
(void)skb_put(dd->outgoing_skb,
NL_SIZE(dd->outgoing_skb->data));
ret = genlmsg_multicast(dd->outgoing_skb, 0,
dd->nl_mc_groups[MC_FUSION].id,
GFP_KERNEL);
if (ret < 0) {
ERROR("can't send IRQ buffer %d", ret);
msleep(300);
if (++dd->send_fail_count >= 10 &&
dd->fusion_process != (pid_t)0) {
(void)kill_pid(
find_get_pid(dd->fusion_process),
SIGKILL, 1);
wake_up_process(dd->thread);
}
} else {
dd->send_fail_count = 0;
}
ret = nl_msg_new(dd, MC_FUSION);
if (ret < 0)
ERROR("could not allocate outgoing skb (%d)", ret);
}
INFO("%s : end", __func__);
}
static void service_irq(struct dev_data *dd)
{
struct fu_async_data *async_data;
u16 status, test, address[2], xbuf, value;
u16 clear[2] = { 0 };
bool read_buf[2] = {true, false};
int ret, ret2;
ret = dd->chip.read(dd, dd->irq_param[0], (u8 *)&status,
sizeof(status));
if (ret < 0) {
ERROR("can't read IRQ status (%d)", ret);
return;
}
if (dd->resume_reset) {
read_buf[0] = false;
clear[0] = dd->irq_param[10];
status = dd->irq_param[10];
dd->resume_reset = false;
} else if (status & dd->irq_param[10]) {
read_buf[0] = false;
clear[0] = dd->irq_param[10];
} else if (status & dd->irq_param[18]) {
test = status & (dd->irq_param[6] | dd->irq_param[7]);
if (test == 0)
return;
else if (test == (dd->irq_param[6] | dd->irq_param[7]))
xbuf = ((status & dd->irq_param[5]) == 0) ? 0 : 1;
else if (test == dd->irq_param[6])
xbuf = 0;
else if (test == dd->irq_param[7])
xbuf = 1;
else {
ERROR("unexpected IRQ handler case 0x%04X", status);
return;
}
read_buf[1] = true;
address[1] = xbuf ? dd->irq_param[2] : dd->irq_param[1];
address[0] = dd->irq_param[3];
clear[0] = xbuf ? dd->irq_param[7] : dd->irq_param[6];
clear[0] |= dd->irq_param[8];
clear[0] |= dd->irq_param[18];
value = dd->irq_param[17];
(void)dd->chip.write(dd, dd->irq_param[16], (u8 *)&value,
sizeof(value));
} else if (status & dd->irq_param[9]) {
test = status & (dd->irq_param[6] | dd->irq_param[7]);
if (test == (dd->irq_param[6] | dd->irq_param[7]))
xbuf = ((status & dd->irq_param[5]) != 0) ? 0 : 1;
else if (test == dd->irq_param[6])
xbuf = 0;
else if (test == dd->irq_param[7])
xbuf = 1;
else {
ERROR("unexpected IRQ handler case");
return;
}
read_buf[1] = true;
address[1] = xbuf ? dd->irq_param[2] : dd->irq_param[1];
address[0] = dd->irq_param[3];
clear[0] = dd->irq_param[6] | dd->irq_param[7] |
dd->irq_param[8] | dd->irq_param[9];
value = dd->irq_param[13];
(void)dd->chip.write(dd, dd->irq_param[12], (u8 *)&value,
sizeof(value));
} else {
test = status & (dd->irq_param[6] | dd->irq_param[7]);
if (test == 0)
return;
else if (test == (dd->irq_param[6] | dd->irq_param[7]))
xbuf = ((status & dd->irq_param[5]) == 0) ? 0 : 1;
else if (test == dd->irq_param[6])
xbuf = 0;
else if (test == dd->irq_param[7])
xbuf = 1;
else {
ERROR("unexpected IRQ handler case 0x%04X ", status);
return;
}
address[0] = xbuf ? dd->irq_param[2] : dd->irq_param[1];
clear[0] = xbuf ? dd->irq_param[7] : dd->irq_param[6];
clear[0] |= dd->irq_param[8];
}
async_data = nl_alloc_attr(dd->outgoing_skb->data, FU_ASYNC_DATA,
sizeof(*async_data) + dd->irq_param[4]);
if (async_data == NULL) {
ERROR("can't add data to async IRQ buffer 1");
return;
}
async_data->status = status;
if (read_buf[0]) {
async_data->address = address[0];
async_data->length = dd->irq_param[4];
ret = dd->chip.read(dd, address[0], async_data->data,
dd->irq_param[4]);
}
if (read_buf[1] && ret == 0) {
async_data = nl_alloc_attr(dd->outgoing_skb->data,
FU_ASYNC_DATA,
sizeof(*async_data) +
dd->irq_param[4]);
if (async_data == NULL) {
ERROR("can't add data to async IRQ buffer 2");
nl_msg_init(dd->outgoing_skb->data, dd->nl_family.id,
dd->nl_seq - 1, MC_FUSION);
return;
}
async_data->address = address[1];
async_data->length = dd->irq_param[4];
async_data->status = status;
ret = dd->chip.read(dd, address[1], async_data->data,
dd->irq_param[4]);
}
#if HI02
ret2 = dd->chip.write(dd, dd->irq_param[0], (u8 *)clear,
sizeof(clear));
#else
ret2 = dd->chip.write(dd, dd->irq_param[0], (u8 *)clear,
sizeof(clear[0]));
#endif
if (ret2 < 0)
ERROR("can't clear IRQ status (%d)", ret2);
if (ret < 0) {
ERROR("can't read IRQ buffer (%d)", ret);
nl_msg_init(dd->outgoing_skb->data, dd->nl_family.id,
dd->nl_seq - 1, MC_FUSION);
} else {
(void)skb_put(dd->outgoing_skb,
NL_SIZE(dd->outgoing_skb->data));
ret = genlmsg_multicast(dd->outgoing_skb, 0,
dd->nl_mc_groups[MC_FUSION].id,
GFP_KERNEL);
if (ret < 0) {
ERROR("can't send IRQ buffer %d", ret);
msleep(300);
if (read_buf[0] == false ||
(++dd->send_fail_count >= 10 &&
dd->fusion_process != (pid_t)0)) {
(void)kill_pid(
find_get_pid(dd->fusion_process),
SIGKILL, 1);
wake_up_process(dd->thread);
}
} else {
dd->send_fail_count = 0;
}
ret = nl_msg_new(dd, MC_FUSION);
if (ret < 0)
ERROR("could not allocate outgoing skb (%d)", ret);
}
}
static int send_sysfs_info(struct dev_data *dd)
{
struct fu_sysfs_info *sysfs_info;
int ret, ret2;
sysfs_info = nl_alloc_attr(dd->outgoing_skb->data,
FU_SYSFS_INFO,
sizeof(*sysfs_info));
if (sysfs_info == NULL) {
ERROR("Can't allocate sysfs_info");
return -EPERM;
}
sysfs_info->type = dd->sysfs_update_type;
sysfs_info->glove_value = dd->glove_enabled;
sysfs_info->charger_value = dd->charger_mode_en;
sysfs_info->lcd_fps_value = dd->lcd_fps;
(void)skb_put(dd->outgoing_skb,
NL_SIZE(dd->outgoing_skb->data));
ret = genlmsg_multicast(dd->outgoing_skb, 0,
dd->nl_mc_groups[MC_FUSION].id,
GFP_KERNEL);
if (ret < 0)
ERROR("could not reply to fusion (%d)", ret);
/* allocate new outgoing skb */
ret2 = nl_msg_new(dd, MC_FUSION);
if (ret2 < 0)
ERROR("could not allocate outgoing skb (%d)", ret2);
return ret;
}
/****************************************************************************\
* Processing thread *
\****************************************************************************/
static int processing_thread(void *arg)
{
struct dev_data *dd = arg;
struct maxim_sti_pdata *pdata = dd->spi->dev.platform_data;
struct sk_buff *skb;
char *argv[] = { pdata->touch_fusion, "daemon",
pdata->nl_family,
dd->config_file, NULL };
int ret, ret2;
bool fusion_dead;
INFO("%s : start", __func__);
sched_setscheduler(current, SCHED_FIFO, &dd->thread_sched);
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
/* ensure that we have outgoing skb */
if (dd->outgoing_skb == NULL)
if (nl_msg_new(dd, MC_FUSION) < 0) {
schedule();
continue;
}
/* priority 1: start up fusion process */
if (dd->fusion_process != (pid_t)0 && get_pid_task(
find_get_pid(dd->fusion_process),
PIDTYPE_PID) == NULL) {
stop_scan_canned(dd);
dd->start_fusion = true;
dd->fusion_process = (pid_t)0;
#if INPUT_ENABLE_DISABLE || FB_CALLBACK
dd->input_no_deconfig = true;
#endif
}
if (dd->start_fusion) {
do {
ret = call_usermodehelper(argv[0], argv, NULL,
UMH_WAIT_EXEC);
if (ret != 0)
msleep(100);
} while (ret != 0 && !kthread_should_stop());
/* reset-high */
pdata->reset(pdata, 1);
dd->start_fusion = false;
dd->tf_status |= TF_STATUS_BUSY;
#if FORCE_NO_DECONFIG
dd->input_no_deconfig = true;
INFO("FORCE_NO_DECONFIG is enable");
#endif
}
if (kthread_should_stop())
break;
/* priority 2: process pending Netlink messages */
while ((skb = skb_dequeue(&dd->incoming_skb_queue)) != NULL) {
if (kthread_should_stop())
break;
if (nl_process_msg(dd, skb) < 0)
skb_queue_purge(&dd->incoming_skb_queue);
if (dd->outgoing_skb == NULL)
continue;
}
if (kthread_should_stop())
break;
/* priority 3: suspend/resume */
if (dd->suspend_in_progress && !(dd->tf_status & TF_STATUS_BUSY)) {
if (dd->irq_registered) {
disable_irq(dd->spi->irq);
if (dd->gesture_en) {
enable_gesture(dd);
enable_irq(dd->spi->irq);
} else if (dd->compatibility_mode || !dd->idle)
stop_scan_canned(dd);
else
stop_idle_scan(dd);
}
complete(&dd->suspend_resume);
INFO("%s : complete", __func__);
dd->expect_resume_ack = true;
dd->resume_reset = false;
while (!dd->resume_in_progress) {
/* the line below is a MUST */
set_current_state(TASK_INTERRUPTIBLE);
if (dd->gesture_en && dd->irq_registered &&
pdata->irq(pdata) == 0)
gesture_wake_detect(dd);
schedule();
}
#if !SUSPEND_POWER_OFF
if (dd->irq_registered) {
if (dd->gesture_en)
finish_gesture(dd);
else if (dd->compatibility_mode || !dd->idle)
start_scan_canned(dd);
}
#endif
dd->resume_in_progress = false;
dd->suspend_in_progress = false;
complete(&dd->suspend_resume);
INFO("%s : complete", __func__);
fusion_dead = false;
dd->send_fail_count = 0;
do {
if (dd->fusion_process != (pid_t)0 &&
get_pid_task(find_get_pid(
dd->fusion_process),
PIDTYPE_PID) == NULL) {
fusion_dead = true;
break;
}
ret = nl_add_attr(dd->outgoing_skb->data,
FU_RESUME, NULL, 0);
if (ret < 0) {
ERROR("can't add data to resume "
"buffer");
nl_msg_init(dd->outgoing_skb->data,
dd->nl_family.id,
dd->nl_seq - 1, MC_FUSION);
msleep(100);
continue;
}
(void)skb_put(dd->outgoing_skb,
NL_SIZE(dd->outgoing_skb->data));
ret = genlmsg_multicast(dd->outgoing_skb, 0,
dd->nl_mc_groups[MC_FUSION].id,
GFP_KERNEL);
if (ret < 0) {
ERROR("can't send resume message %d",
ret);
msleep(100);
if (++dd->send_fail_count >= 10) {
fusion_dead = true;
ret = 0;
}
}
do {
ret2 = nl_msg_new(dd, MC_FUSION);
if (ret2 < 0) {
ERROR("could not allocate "
"outgoing skb (%d)",
ret2);
msleep(1000);
}
} while (ret2 != 0);
} while (ret != 0);
if (dd->send_fail_count >= 10 &&
dd->fusion_process != (pid_t)0)
(void)kill_pid(find_get_pid(dd->fusion_process),
SIGKILL, 1);
dd->send_fail_count = 0;
if (fusion_dead)
continue;
}
/* priority 4: update /sys/device information */
if (dd->sysfs_update_type != DR_SYSFS_UPDATE_NONE) {
if (!dd->expect_resume_ack) {
mutex_lock(&dd->sysfs_update_mutex);
if (send_sysfs_info(dd) < 0)
ERROR(
"Can not send sysfs update to touch fusion"
);
else
dd->sysfs_update_type = DR_SYSFS_UPDATE_NONE;
mutex_unlock(&dd->sysfs_update_mutex);
}
if (dd->outgoing_skb == NULL)
continue;
}
/* priority 5: service interrupt */
if (dd->irq_registered && !dd->expect_resume_ack &&
(pdata->irq(pdata) == 0 || dd->resume_reset))
dd->service_irq(dd);
if (dd->irq_registered && !dd->expect_resume_ack &&
pdata->irq(pdata) == 0)
continue;
/* nothing more to do; sleep */
schedule();
}
INFO("%s : end", __func__);
return 0;
}
/****************************************************************************\
* SYSFS interface *
\****************************************************************************/
static ssize_t chip_id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "0x%04X\n", dd->chip_id);
}
static ssize_t fw_ver_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "0x%04X\n", dd->fw_ver);
}
static ssize_t driver_ver_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "0x%04X\n", dd->drv_ver);
}
static ssize_t tf_ver_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "0x%04X\n", dd->tf_ver);
}
static ssize_t panel_id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "0x%04X\n", panel_id);
}
static ssize_t glove_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "%u\n", dd->glove_enabled);
}
static ssize_t glove_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
u32 temp;
mutex_lock(&dd->sysfs_update_mutex);
if (sscanf(buf, "%u", &temp) != 1) {
ERROR("Invalid (%s)", buf);
mutex_unlock(&dd->sysfs_update_mutex);
return -EINVAL;
}
dd->glove_enabled = !!temp;
set_bit(DR_SYSFS_UPDATE_BIT_GLOVE, &(dd->sysfs_update_type));
wake_up_process(dd->thread);
mutex_unlock(&dd->sysfs_update_mutex);
return strnlen(buf, PAGE_SIZE);
}
static ssize_t gesture_wakeup_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "%u\n", dd->gesture_en);
}
static ssize_t gesture_wakeup_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
u32 temp;
if (sscanf(buf, "%u", &temp) != 1) {
ERROR("Invalid (%s)", buf);
return -EINVAL;
}
dd->gesture_en = temp;
return strnlen(buf, PAGE_SIZE);
}
static ssize_t charger_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "%u\n", dd->charger_mode_en);
}
static ssize_t charger_mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
u32 temp;
mutex_lock(&dd->sysfs_update_mutex);
if (sscanf(buf, "%u", &temp) != 1) {
ERROR("Invalid (%s)", buf);
mutex_unlock(&dd->sysfs_update_mutex);
return -EINVAL;
}
if (temp > DR_WIRELESS_CHARGER) {
ERROR("Charger Mode Value Out of Range");
mutex_unlock(&dd->sysfs_update_mutex);
return -EINVAL;
}
dd->charger_mode_en = temp;
set_bit(DR_SYSFS_UPDATE_BIT_CHARGER, &(dd->sysfs_update_type));
wake_up_process(dd->thread);
mutex_unlock(&dd->sysfs_update_mutex);
return strnlen(buf, PAGE_SIZE);
}
static ssize_t info_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "chip id: 0x%04X driver ver: 0x%04X "
"fw ver: 0x%04X panel id: 0x%04X "
"tf ver: 0x%04X default loaded: %d",
dd->chip_id, dd->drv_ver, dd->fw_ver,
panel_id, dd->tf_ver,
(dd->tf_status & TF_STATUS_DEFAULT_LOADED));
}
static ssize_t screen_status_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
u32 temp;
mutex_lock(&dd->screen_status_mutex);
if (sscanf(buf, "%u", &temp) != 1) {
ERROR("Invalid (%s)", buf);
mutex_unlock(&dd->screen_status_mutex);
return -EINVAL;
}
if (temp) {
late_resume(dev);
if (dd->pending_fps) {
mutex_lock(&dd->sysfs_update_mutex);
set_bit(DR_SYSFS_UPDATE_BIT_LCD_FPS,
&(dd->sysfs_update_type));
wake_up_process(dd->thread);
dd->pending_fps = false;
mutex_unlock(&dd->sysfs_update_mutex);
}
} else
early_suspend(dev);
mutex_unlock(&dd->screen_status_mutex);
return strnlen(buf, PAGE_SIZE);
}
static ssize_t tf_status_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "0x%08X", dd->tf_status);
}
static ssize_t default_loaded_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "%d",
(dd->tf_status & TF_STATUS_DEFAULT_LOADED));
}
static ssize_t lcd_fps_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
return snprintf(buf, PAGE_SIZE, "%u\n", dd->lcd_fps);
}
static ssize_t lcd_fps_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
u32 temp;
mutex_lock(&dd->sysfs_update_mutex);
if (sscanf(buf, "%u", &temp) != 1) {
ERROR("Invalid (%s)", buf);
mutex_unlock(&dd->sysfs_update_mutex);
return -EINVAL;
}
dd->lcd_fps = temp;
dd->pending_fps = true;
mutex_unlock(&dd->sysfs_update_mutex);
return strnlen(buf, PAGE_SIZE);
}
static ssize_t lcd_fpks_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
u32 dfpks = dd->lcd_fps * 1000;
return snprintf(buf, PAGE_SIZE, "%u\n", dfpks);
}
static ssize_t lcd_fpks_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct dev_data *dd = spi_get_drvdata(spi);
char buf2[6];
int dfps, dfpks, rc;
rc = kstrtoint(buf, 10, &dfpks);
if (rc < 0) {
ERROR("Invalid (%s)", buf);
return -EINVAL;
}
dfps = dfpks / 1000;
rc = scnprintf(buf2, sizeof(buf2), "%d\n", dfps);
if (rc < 0) {
ERROR("Invalid (%d)", dfps);
return -EINVAL;
}
rc = lcd_fps_store(dev, attr, buf2, sizeof(buf2));
if (rc < 0) {
ERROR("Invalid (%s)", buf2);
return -EINVAL;
}
return strnlen(buf, PAGE_SIZE);
}
static struct device_attribute dev_attrs[] = {
__ATTR(fw_ver, S_IRUGO, fw_ver_show, NULL),
__ATTR(chip_id, S_IRUGO, chip_id_show, NULL),
__ATTR(tf_ver, S_IRUGO, tf_ver_show, NULL),
__ATTR(driver_ver, S_IRUGO, driver_ver_show, NULL),
__ATTR(panel_id, S_IRUGO, panel_id_show, NULL),
__ATTR(glove_en, S_IRUGO | S_IWUSR, glove_show, glove_store),
__ATTR(gesture_wakeup, S_IRUGO | S_IWUSR,
gesture_wakeup_show, gesture_wakeup_store),
__ATTR(charger_mode, S_IRUGO | S_IWUSR,
charger_mode_show, charger_mode_store),
__ATTR(info, S_IRUGO, info_show, NULL),
__ATTR(screen_status, S_IWUSR, NULL, screen_status_store),
__ATTR(tf_status, S_IRUGO, tf_status_show, NULL),
__ATTR(default_loaded, S_IRUGO, default_loaded_show, NULL),
__ATTR(lcd_fps, S_IRUGO | S_IWUSR, lcd_fps_show, lcd_fps_store),
__ATTR(lcd_fpks, S_IRUGO | S_IWUSR, lcd_fpks_show, lcd_fpks_store),
};
static int create_sysfs_entries(struct dev_data *dd)
{
int i, ret = 0;
for (i = 0; i < ARRAY_SIZE(dev_attrs); i++) {
ret = device_create_file(&dd->spi->dev, &dev_attrs[i]);
if (ret) {
for (; i >= 0; --i) {
device_remove_file(&dd->spi->dev,
&dev_attrs[i]);
dd->sysfs_created--;
}
break;
}
dd->sysfs_created++;
}
return ret;
}
static void remove_sysfs_entries(struct dev_data *dd)
{
int i;
for (i = 0; i < ARRAY_SIZE(dev_attrs); i++)
if (dd->sysfs_created && dd->sysfs_created--)
device_remove_file(&dd->spi->dev, &dev_attrs[i]);
}
/****************************************************************************\
* Driver initialization *
\****************************************************************************/
static int probe(struct spi_device *spi)
{
struct maxim_sti_pdata *pdata = spi->dev.platform_data;
struct dev_data *dd;
unsigned long flags;
int ret, i;
void *ptr;
#ifdef CONFIG_OF
if (pdata == NULL && spi->dev.of_node) {
pdata = devm_kzalloc(&spi->dev,
sizeof(struct maxim_sti_pdata), GFP_KERNEL);
if (!pdata) {
dev_err(&spi->dev, "failed to allocate memory\n");
return -ENOMEM;
}
ret = maxim_parse_dt(&spi->dev, pdata);
if (ret)
return ret;
spi->dev.platform_data = pdata;
}
#endif
/* validate platform data */
if (pdata == NULL || pdata->init == NULL || pdata->reset == NULL ||
pdata->irq == NULL || pdata->touch_fusion == NULL ||
pdata->config_file == NULL || pdata->nl_family == NULL ||
GENL_CHK(pdata->nl_family) ||
pdata->nl_mc_groups < MC_REQUIRED_GROUPS ||
pdata->chip_access_method == 0 ||
pdata->chip_access_method > ARRAY_SIZE(chip_access_methods) ||
pdata->default_reset_state > 1)
return -EINVAL;
/* device context: allocate structure */
dd = kzalloc(sizeof(*dd) + pdata->tx_buf_size + pdata->rx_buf_size +
sizeof(*dd->nl_ops) * pdata->nl_mc_groups +
sizeof(*dd->nl_mc_groups) * pdata->nl_mc_groups,
GFP_KERNEL);
if (dd == NULL)
return -ENOMEM;
/* device context: set up dynamic allocation pointers */
ptr = (void *)dd + sizeof(*dd);
if (pdata->tx_buf_size > 0) {
dd->tx_buf = ptr;
ptr += pdata->tx_buf_size;
}
if (pdata->rx_buf_size > 0) {
dd->rx_buf = ptr;
ptr += pdata->rx_buf_size;
}
dd->nl_ops = ptr;
ptr += sizeof(*dd->nl_ops) * pdata->nl_mc_groups;
dd->nl_mc_groups = ptr;
/* device context: initialize structure members */
spi_set_drvdata(spi, dd);
dd->spi = spi;
dd->nl_seq = 1;
init_completion(&dd->suspend_resume);
memset(dd->tx_buf, 0xFF, pdata->tx_buf_size);
(void)set_chip_access_method(dd, pdata->chip_access_method);
/* initialize regulators */
ret = regulator_init(dd);
if (ret < 0)
goto platform_failure;
/* Enable regulators */
ret = regulator_control(dd, true);
if (ret < 0)
goto platform_failure;
/* initialize platform */
ret = pdata->init(&spi->dev, pdata, true);
if (ret < 0)
goto platform_failure;
/* Netlink: initialize incoming skb queue */
skb_queue_head_init(&dd->incoming_skb_queue);
/* start processing thread */
dd->thread_sched.sched_priority = MAX_USER_RT_PRIO / 2;
dd->thread = kthread_run(processing_thread, dd, pdata->nl_family);
if (IS_ERR(dd->thread)) {
ret = PTR_ERR(dd->thread);
goto platform_failure;
}
/* Netlink: register GENL family */
dd->nl_family.id = GENL_ID_GENERATE;
dd->nl_family.version = NL_FAMILY_VERSION;
GENL_COPY(dd->nl_family.name, pdata->nl_family);
ret = genl_register_family(&dd->nl_family);
if (ret < 0)
goto nl_family_failure;
/* Netlink: register family ops */
for (i = 0; i < MC_REQUIRED_GROUPS; i++) {
dd->nl_ops[i].cmd = i;
dd->nl_ops[i].doit = nl_callback_noop;
}
dd->nl_ops[MC_DRIVER].doit = nl_callback_driver;
dd->nl_ops[MC_FUSION].doit = nl_callback_fusion;
for (i = 0; i < MC_REQUIRED_GROUPS; i++) {
ret = genl_register_ops(&dd->nl_family, &dd->nl_ops[i]);
if (ret < 0)
goto nl_failure;
}
/* Netlink: register family multicast groups */
GENL_COPY(dd->nl_mc_groups[MC_DRIVER].name, MC_DRIVER_NAME);
GENL_COPY(dd->nl_mc_groups[MC_FUSION].name, MC_FUSION_NAME);
for (i = 0; i < MC_REQUIRED_GROUPS; i++) {
ret = genl_register_mc_group(&dd->nl_family,
&dd->nl_mc_groups[i]);
if (ret < 0)
goto nl_failure;
}
dd->nl_mc_group_count = MC_REQUIRED_GROUPS;
/* Netlink: pre-allocate outgoing skb */
ret = nl_msg_new(dd, MC_FUSION);
if (ret < 0)
goto nl_failure;
/* Netlink: ready to start processing incoming messages */
dd->nl_enabled = true;
dd->sysfs_update_type = DR_SYSFS_UPDATE_NONE;
mutex_init(&dd->sysfs_update_mutex);
mutex_init(&dd->screen_status_mutex);
/* add us to the devices list */
spin_lock_irqsave(&dev_lock, flags);
list_add_tail(&dd->dev_list, &dev_list);
spin_unlock_irqrestore(&dev_lock, flags);
#if CPU_BOOST
dd->last_irq_jiffies = jiffies;
#endif
ret = create_sysfs_entries(dd);
if (ret) {
INFO("failed to create sysfs file");
goto sysfs_remove_group;
}
snprintf(dd->config_file, CFG_FILE_NAME_MAX,
pdata->config_file, panel_id);
/* start up Touch Fusion */
dd->start_fusion = true;
wake_up_process(dd->thread);
INFO("driver loaded; version 0x%04X; release date %s", DRIVER_VERSION,
DRIVER_RELEASE);
return 0;
sysfs_remove_group:
remove_sysfs_entries(dd);
nl_failure:
genl_unregister_family(&dd->nl_family);
nl_family_failure:
(void)kthread_stop(dd->thread);
platform_failure:
pdata->init(&spi->dev, pdata, false);
kfree(dd);
return ret;
}
static int remove(struct spi_device *spi)
{
struct maxim_sti_pdata *pdata = spi->dev.platform_data;
struct dev_data *dd = spi_get_drvdata(spi);
unsigned long flags;
u8 i;
if (dd->fusion_process != (pid_t)0)
(void)kill_pid(find_get_pid(dd->fusion_process), SIGKILL, 1);
if (dd->parent != NULL)
sysfs_remove_link(dd->input_dev[0]->dev.kobj.parent,
MAXIM_STI_NAME);
remove_sysfs_entries(dd);
/* BEWARE: tear-down sequence below is carefully staged: */
/* 1) first the feeder of Netlink messages to the processing thread */
/* is turned off */
/* 2) then the thread itself is shut down */
/* 3) then Netlink family is torn down since no one would be using */
/* it at this point */
/* 4) above step (3) insures that all Netlink senders are */
/* definitely gone and it is safe to free up outgoing skb buffer */
/* and incoming skb queue */
dd->nl_enabled = false;
(void)kthread_stop(dd->thread);
genl_unregister_family(&dd->nl_family);
kfree_skb(dd->outgoing_skb);
skb_queue_purge(&dd->incoming_skb_queue);
for (i = 0; i < INPUT_DEVICES; i++)
if (dd->input_dev[i])
input_unregister_device(dd->input_dev[i]);
#if FB_CALLBACK && defined(CONFIG_FB)
fb_unregister_client(&dd->fb_notifier);
#endif
if (dd->irq_registered)
free_irq(dd->spi->irq, dd);
stop_scan_canned(dd);
spin_lock_irqsave(&dev_lock, flags);
list_del(&dd->dev_list);
spin_unlock_irqrestore(&dev_lock, flags);
pdata->reset(pdata, 0);
usleep_range(100, 120);
regulator_control(dd, false);
pdata->init(&spi->dev, pdata, false);
kfree(dd);
INFO("driver unloaded");
return 0;
}
static void shutdown(struct spi_device *spi)
{
struct maxim_sti_pdata *pdata = spi->dev.platform_data;
struct dev_data *dd = spi_get_drvdata(spi);
pdata->reset(pdata, 0);
usleep_range(100, 120);
regulator_control(dd, false);
}
/****************************************************************************\
* Module initialization *
\****************************************************************************/
static const struct spi_device_id id[] = {
{ MAXIM_STI_NAME, 0 },
{ }
};
MODULE_DEVICE_TABLE(spi, id);
#ifdef CONFIG_OF
static struct of_device_id maxim_match_table[] = {
{ .compatible = "maxim,maxim_sti",},
{ },
};
#endif
static struct spi_driver driver = {
.probe = probe,
.remove = remove,
.shutdown = shutdown,
.id_table = id,
.driver = {
.name = MAXIM_STI_NAME,
#ifdef CONFIG_OF
.of_match_table = maxim_match_table,
#endif
.owner = THIS_MODULE,
#ifdef CONFIG_PM_SLEEP
.pm = &pm_ops,
#endif
},
};
static int __init maxim_sti_init(void)
{
INIT_LIST_HEAD(&dev_list);
spin_lock_init(&dev_lock);
return spi_register_driver(&driver);
}
static void __exit maxim_sti_exit(void)
{
spi_unregister_driver(&driver);
}
module_param(panel_id, ushort, S_IRUGO);
MODULE_PARM_DESC(panel_id, "Touch Panel ID Configuration");
module_init(maxim_sti_init);
module_exit(maxim_sti_exit);
MODULE_AUTHOR("Maxim Integrated Products, Inc.");
MODULE_DESCRIPTION("Maxim SmartTouch Imager Touchscreen Driver");
MODULE_LICENSE("GPL v2");
MODULE_VERSION(__stringify(DRIVER_VERSION));
| KuronekoDungeon/android_kernel_sony_msm | drivers/input/touchscreen/maxim_sti.c | C | gpl-2.0 | 83,497 |
/*
* linux/mm/memory_hotplug.c
*
* Copyright (C)
*/
#include <linux/stddef.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/interrupt.h>
#include <linux/pagemap.h>
#include <linux/compiler.h>
#include <linux/export.h>
#include <linux/pagevec.h>
#include <linux/writeback.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/cpu.h>
#include <linux/memory.h>
#include <linux/memory_hotplug.h>
#include <linux/highmem.h>
#include <linux/vmalloc.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/migrate.h>
#include <linux/page-isolation.h>
#include <linux/pfn.h>
#include <linux/suspend.h>
#include <linux/mm_inline.h>
#include <linux/firmware-map.h>
#include <linux/stop_machine.h>
#include <linux/hugetlb.h>
#include <linux/memblock.h>
#include <linux/bootmem.h>
#include <asm/tlbflush.h>
#include "internal.h"
/*
* online_page_callback contains pointer to current page onlining function.
* Initially it is generic_online_page(). If it is required it could be
* changed by calling set_online_page_callback() for callback registration
* and restore_online_page_callback() for generic callback restore.
*/
static void generic_online_page(struct page *page);
static online_page_callback_t online_page_callback = generic_online_page;
static DEFINE_MUTEX(online_page_callback_lock);
/* The same as the cpu_hotplug lock, but for memory hotplug. */
static struct {
struct task_struct *active_writer;
struct mutex lock; /* Synchronizes accesses to refcount, */
/*
* Also blocks the new readers during
* an ongoing mem hotplug operation.
*/
int refcount;
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map dep_map;
#endif
} mem_hotplug = {
.active_writer = NULL,
.lock = __MUTEX_INITIALIZER(mem_hotplug.lock),
.refcount = 0,
#ifdef CONFIG_DEBUG_LOCK_ALLOC
.dep_map = {.name = "mem_hotplug.lock" },
#endif
};
/* Lockdep annotations for get/put_online_mems() and mem_hotplug_begin/end() */
#define memhp_lock_acquire_read() lock_map_acquire_read(&mem_hotplug.dep_map)
#define memhp_lock_acquire() lock_map_acquire(&mem_hotplug.dep_map)
#define memhp_lock_release() lock_map_release(&mem_hotplug.dep_map)
void get_online_mems(void)
{
might_sleep();
if (mem_hotplug.active_writer == current)
return;
memhp_lock_acquire_read();
mutex_lock(&mem_hotplug.lock);
mem_hotplug.refcount++;
mutex_unlock(&mem_hotplug.lock);
}
void put_online_mems(void)
{
if (mem_hotplug.active_writer == current)
return;
mutex_lock(&mem_hotplug.lock);
if (WARN_ON(!mem_hotplug.refcount))
mem_hotplug.refcount++; /* try to fix things up */
if (!--mem_hotplug.refcount && unlikely(mem_hotplug.active_writer))
wake_up_process(mem_hotplug.active_writer);
mutex_unlock(&mem_hotplug.lock);
memhp_lock_release();
}
static void mem_hotplug_begin(void)
{
mem_hotplug.active_writer = current;
memhp_lock_acquire();
for (;;) {
mutex_lock(&mem_hotplug.lock);
if (likely(!mem_hotplug.refcount))
break;
__set_current_state(TASK_UNINTERRUPTIBLE);
mutex_unlock(&mem_hotplug.lock);
schedule();
}
}
static void mem_hotplug_done(void)
{
mem_hotplug.active_writer = NULL;
mutex_unlock(&mem_hotplug.lock);
memhp_lock_release();
}
/* add this memory to iomem resource */
static struct resource *register_memory_resource(u64 start, u64 size)
{
struct resource *res;
res = kzalloc(sizeof(struct resource), GFP_KERNEL);
BUG_ON(!res);
res->name = "System RAM";
res->start = start;
res->end = start + size - 1;
res->flags = IORESOURCE_MEM | IORESOURCE_BUSY;
if (request_resource(&iomem_resource, res) < 0) {
pr_debug("System RAM resource %pR cannot be added\n", res);
kfree(res);
res = NULL;
}
return res;
}
static void release_memory_resource(struct resource *res)
{
if (!res)
return;
release_resource(res);
kfree(res);
return;
}
#ifdef CONFIG_MEMORY_HOTPLUG_SPARSE
void get_page_bootmem(unsigned long info, struct page *page,
unsigned long type)
{
page->lru.next = (struct list_head *) type;
SetPagePrivate(page);
set_page_private(page, info);
atomic_inc(&page->_count);
}
void put_page_bootmem(struct page *page)
{
unsigned long type;
type = (unsigned long) page->lru.next;
BUG_ON(type < MEMORY_HOTPLUG_MIN_BOOTMEM_TYPE ||
type > MEMORY_HOTPLUG_MAX_BOOTMEM_TYPE);
if (atomic_dec_return(&page->_count) == 1) {
ClearPagePrivate(page);
set_page_private(page, 0);
INIT_LIST_HEAD(&page->lru);
free_reserved_page(page);
}
}
#ifdef CONFIG_HAVE_BOOTMEM_INFO_NODE
#ifndef CONFIG_SPARSEMEM_VMEMMAP
static void register_page_bootmem_info_section(unsigned long start_pfn)
{
unsigned long *usemap, mapsize, section_nr, i;
struct mem_section *ms;
struct page *page, *memmap;
section_nr = pfn_to_section_nr(start_pfn);
ms = __nr_to_section(section_nr);
/* Get section's memmap address */
memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
/*
* Get page for the memmap's phys address
* XXX: need more consideration for sparse_vmemmap...
*/
page = virt_to_page(memmap);
mapsize = sizeof(struct page) * PAGES_PER_SECTION;
mapsize = PAGE_ALIGN(mapsize) >> PAGE_SHIFT;
/* remember memmap's page */
for (i = 0; i < mapsize; i++, page++)
get_page_bootmem(section_nr, page, SECTION_INFO);
usemap = __nr_to_section(section_nr)->pageblock_flags;
page = virt_to_page(usemap);
mapsize = PAGE_ALIGN(usemap_size()) >> PAGE_SHIFT;
for (i = 0; i < mapsize; i++, page++)
get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
}
#else /* CONFIG_SPARSEMEM_VMEMMAP */
static void register_page_bootmem_info_section(unsigned long start_pfn)
{
unsigned long *usemap, mapsize, section_nr, i;
struct mem_section *ms;
struct page *page, *memmap;
if (!pfn_valid(start_pfn))
return;
section_nr = pfn_to_section_nr(start_pfn);
ms = __nr_to_section(section_nr);
memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
register_page_bootmem_memmap(section_nr, memmap, PAGES_PER_SECTION);
usemap = __nr_to_section(section_nr)->pageblock_flags;
page = virt_to_page(usemap);
mapsize = PAGE_ALIGN(usemap_size()) >> PAGE_SHIFT;
for (i = 0; i < mapsize; i++, page++)
get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
}
#endif /* !CONFIG_SPARSEMEM_VMEMMAP */
void register_page_bootmem_info_node(struct pglist_data *pgdat)
{
unsigned long i, pfn, end_pfn, nr_pages;
int node = pgdat->node_id;
struct page *page;
struct zone *zone;
nr_pages = PAGE_ALIGN(sizeof(struct pglist_data)) >> PAGE_SHIFT;
page = virt_to_page(pgdat);
for (i = 0; i < nr_pages; i++, page++)
get_page_bootmem(node, page, NODE_INFO);
zone = &pgdat->node_zones[0];
for (; zone < pgdat->node_zones + MAX_NR_ZONES - 1; zone++) {
if (zone_is_initialized(zone)) {
nr_pages = zone->wait_table_hash_nr_entries
* sizeof(wait_queue_head_t);
nr_pages = PAGE_ALIGN(nr_pages) >> PAGE_SHIFT;
page = virt_to_page(zone->wait_table);
for (i = 0; i < nr_pages; i++, page++)
get_page_bootmem(node, page, NODE_INFO);
}
}
pfn = pgdat->node_start_pfn;
end_pfn = pgdat_end_pfn(pgdat);
/* register section info */
for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
/*
* Some platforms can assign the same pfn to multiple nodes - on
* node0 as well as nodeN. To avoid registering a pfn against
* multiple nodes we check that this pfn does not already
* reside in some other nodes.
*/
if (pfn_valid(pfn) && (pfn_to_nid(pfn) == node))
register_page_bootmem_info_section(pfn);
}
}
#endif /* CONFIG_HAVE_BOOTMEM_INFO_NODE */
static void __meminit grow_zone_span(struct zone *zone, unsigned long start_pfn,
unsigned long end_pfn)
{
unsigned long old_zone_end_pfn;
zone_span_writelock(zone);
old_zone_end_pfn = zone_end_pfn(zone);
if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
zone->zone_start_pfn = start_pfn;
zone->spanned_pages = max(old_zone_end_pfn, end_pfn) -
zone->zone_start_pfn;
zone_span_writeunlock(zone);
}
static void resize_zone(struct zone *zone, unsigned long start_pfn,
unsigned long end_pfn)
{
zone_span_writelock(zone);
if (end_pfn - start_pfn) {
zone->zone_start_pfn = start_pfn;
zone->spanned_pages = end_pfn - start_pfn;
} else {
/*
* make it consist as free_area_init_core(),
* if spanned_pages = 0, then keep start_pfn = 0
*/
zone->zone_start_pfn = 0;
zone->spanned_pages = 0;
}
zone_span_writeunlock(zone);
}
static void fix_zone_id(struct zone *zone, unsigned long start_pfn,
unsigned long end_pfn)
{
enum zone_type zid = zone_idx(zone);
int nid = zone->zone_pgdat->node_id;
unsigned long pfn;
for (pfn = start_pfn; pfn < end_pfn; pfn++)
set_page_links(pfn_to_page(pfn), zid, nid, pfn);
}
/* Can fail with -ENOMEM from allocating a wait table with vmalloc() or
* alloc_bootmem_node_nopanic()/memblock_virt_alloc_node_nopanic() */
static int __ref ensure_zone_is_initialized(struct zone *zone,
unsigned long start_pfn, unsigned long num_pages)
{
if (!zone_is_initialized(zone))
return init_currently_empty_zone(zone, start_pfn, num_pages,
MEMMAP_HOTPLUG);
return 0;
}
static int __meminit move_pfn_range_left(struct zone *z1, struct zone *z2,
unsigned long start_pfn, unsigned long end_pfn)
{
int ret;
unsigned long flags;
unsigned long z1_start_pfn;
ret = ensure_zone_is_initialized(z1, start_pfn, end_pfn - start_pfn);
if (ret)
return ret;
pgdat_resize_lock(z1->zone_pgdat, &flags);
/* can't move pfns which are higher than @z2 */
if (end_pfn > zone_end_pfn(z2))
goto out_fail;
/* the move out part must be at the left most of @z2 */
if (start_pfn > z2->zone_start_pfn)
goto out_fail;
/* must included/overlap */
if (end_pfn <= z2->zone_start_pfn)
goto out_fail;
/* use start_pfn for z1's start_pfn if z1 is empty */
if (!zone_is_empty(z1))
z1_start_pfn = z1->zone_start_pfn;
else
z1_start_pfn = start_pfn;
resize_zone(z1, z1_start_pfn, end_pfn);
resize_zone(z2, end_pfn, zone_end_pfn(z2));
pgdat_resize_unlock(z1->zone_pgdat, &flags);
fix_zone_id(z1, start_pfn, end_pfn);
return 0;
out_fail:
pgdat_resize_unlock(z1->zone_pgdat, &flags);
return -1;
}
static int __meminit move_pfn_range_right(struct zone *z1, struct zone *z2,
unsigned long start_pfn, unsigned long end_pfn)
{
int ret;
unsigned long flags;
unsigned long z2_end_pfn;
ret = ensure_zone_is_initialized(z2, start_pfn, end_pfn - start_pfn);
if (ret)
return ret;
pgdat_resize_lock(z1->zone_pgdat, &flags);
/* can't move pfns which are lower than @z1 */
if (z1->zone_start_pfn > start_pfn)
goto out_fail;
/* the move out part mast at the right most of @z1 */
if (zone_end_pfn(z1) > end_pfn)
goto out_fail;
/* must included/overlap */
if (start_pfn >= zone_end_pfn(z1))
goto out_fail;
/* use end_pfn for z2's end_pfn if z2 is empty */
if (!zone_is_empty(z2))
z2_end_pfn = zone_end_pfn(z2);
else
z2_end_pfn = end_pfn;
resize_zone(z1, z1->zone_start_pfn, start_pfn);
resize_zone(z2, start_pfn, z2_end_pfn);
pgdat_resize_unlock(z1->zone_pgdat, &flags);
fix_zone_id(z2, start_pfn, end_pfn);
return 0;
out_fail:
pgdat_resize_unlock(z1->zone_pgdat, &flags);
return -1;
}
static void __meminit grow_pgdat_span(struct pglist_data *pgdat, unsigned long start_pfn,
unsigned long end_pfn)
{
unsigned long old_pgdat_end_pfn = pgdat_end_pfn(pgdat);
if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
pgdat->node_start_pfn = start_pfn;
pgdat->node_spanned_pages = max(old_pgdat_end_pfn, end_pfn) -
pgdat->node_start_pfn;
}
static int __meminit __add_zone(struct zone *zone, unsigned long phys_start_pfn)
{
struct pglist_data *pgdat = zone->zone_pgdat;
int nr_pages = PAGES_PER_SECTION;
int nid = pgdat->node_id;
int zone_type;
unsigned long flags;
int ret;
zone_type = zone - pgdat->node_zones;
ret = ensure_zone_is_initialized(zone, phys_start_pfn, nr_pages);
if (ret)
return ret;
pgdat_resize_lock(zone->zone_pgdat, &flags);
grow_zone_span(zone, phys_start_pfn, phys_start_pfn + nr_pages);
grow_pgdat_span(zone->zone_pgdat, phys_start_pfn,
phys_start_pfn + nr_pages);
pgdat_resize_unlock(zone->zone_pgdat, &flags);
memmap_init_zone(nr_pages, nid, zone_type,
phys_start_pfn, MEMMAP_HOTPLUG);
return 0;
}
static int __meminit __add_section(int nid, struct zone *zone,
unsigned long phys_start_pfn)
{
int ret;
if (pfn_valid(phys_start_pfn))
return -EEXIST;
ret = sparse_add_one_section(zone, phys_start_pfn);
if (ret < 0)
return ret;
ret = __add_zone(zone, phys_start_pfn);
if (ret < 0)
return ret;
return register_new_memory(nid, __pfn_to_section(phys_start_pfn));
}
/*
* Reasonably generic function for adding memory. It is
* expected that archs that support memory hotplug will
* call this function after deciding the zone to which to
* add the new pages.
*/
int __ref __add_pages(int nid, struct zone *zone, unsigned long phys_start_pfn,
unsigned long nr_pages)
{
unsigned long i;
int err = 0;
int start_sec, end_sec;
/* during initialize mem_map, align hot-added range to section */
start_sec = pfn_to_section_nr(phys_start_pfn);
end_sec = pfn_to_section_nr(phys_start_pfn + nr_pages - 1);
for (i = start_sec; i <= end_sec; i++) {
err = __add_section(nid, zone, i << PFN_SECTION_SHIFT);
/*
* EEXIST is finally dealt with by ioresource collision
* check. see add_memory() => register_memory_resource()
* Warning will be printed if there is collision.
*/
if (err && (err != -EEXIST))
break;
err = 0;
}
return err;
}
EXPORT_SYMBOL_GPL(__add_pages);
#ifdef CONFIG_MEMORY_HOTREMOVE
/* find the smallest valid pfn in the range [start_pfn, end_pfn) */
static int find_smallest_section_pfn(int nid, struct zone *zone,
unsigned long start_pfn,
unsigned long end_pfn)
{
struct mem_section *ms;
for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SECTION) {
ms = __pfn_to_section(start_pfn);
if (unlikely(!valid_section(ms)))
continue;
if (unlikely(pfn_to_nid(start_pfn) != nid))
continue;
if (zone && zone != page_zone(pfn_to_page(start_pfn)))
continue;
return start_pfn;
}
return 0;
}
/* find the biggest valid pfn in the range [start_pfn, end_pfn). */
static int find_biggest_section_pfn(int nid, struct zone *zone,
unsigned long start_pfn,
unsigned long end_pfn)
{
struct mem_section *ms;
unsigned long pfn;
/* pfn is the end pfn of a memory section. */
pfn = end_pfn - 1;
for (; pfn >= start_pfn; pfn -= PAGES_PER_SECTION) {
ms = __pfn_to_section(pfn);
if (unlikely(!valid_section(ms)))
continue;
if (unlikely(pfn_to_nid(pfn) != nid))
continue;
if (zone && zone != page_zone(pfn_to_page(pfn)))
continue;
return pfn;
}
return 0;
}
static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
unsigned long end_pfn)
{
unsigned long zone_start_pfn = zone->zone_start_pfn;
unsigned long z = zone_end_pfn(zone); /* zone_end_pfn namespace clash */
unsigned long zone_end_pfn = z;
unsigned long pfn;
struct mem_section *ms;
int nid = zone_to_nid(zone);
zone_span_writelock(zone);
if (zone_start_pfn == start_pfn) {
/*
* If the section is smallest section in the zone, it need
* shrink zone->zone_start_pfn and zone->zone_spanned_pages.
* In this case, we find second smallest valid mem_section
* for shrinking zone.
*/
pfn = find_smallest_section_pfn(nid, zone, end_pfn,
zone_end_pfn);
if (pfn) {
zone->zone_start_pfn = pfn;
zone->spanned_pages = zone_end_pfn - pfn;
}
} else if (zone_end_pfn == end_pfn) {
/*
* If the section is biggest section in the zone, it need
* shrink zone->spanned_pages.
* In this case, we find second biggest valid mem_section for
* shrinking zone.
*/
pfn = find_biggest_section_pfn(nid, zone, zone_start_pfn,
start_pfn);
if (pfn)
zone->spanned_pages = pfn - zone_start_pfn + 1;
}
/*
* The section is not biggest or smallest mem_section in the zone, it
* only creates a hole in the zone. So in this case, we need not
* change the zone. But perhaps, the zone has only hole data. Thus
* it check the zone has only hole or not.
*/
pfn = zone_start_pfn;
for (; pfn < zone_end_pfn; pfn += PAGES_PER_SECTION) {
ms = __pfn_to_section(pfn);
if (unlikely(!valid_section(ms)))
continue;
if (page_zone(pfn_to_page(pfn)) != zone)
continue;
/* If the section is current section, it continues the loop */
if (start_pfn == pfn)
continue;
/* If we find valid section, we have nothing to do */
zone_span_writeunlock(zone);
return;
}
/* The zone has no valid section */
zone->zone_start_pfn = 0;
zone->spanned_pages = 0;
zone_span_writeunlock(zone);
}
static void shrink_pgdat_span(struct pglist_data *pgdat,
unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long pgdat_start_pfn = pgdat->node_start_pfn;
unsigned long p = pgdat_end_pfn(pgdat); /* pgdat_end_pfn namespace clash */
unsigned long pgdat_end_pfn = p;
unsigned long pfn;
struct mem_section *ms;
int nid = pgdat->node_id;
if (pgdat_start_pfn == start_pfn) {
/*
* If the section is smallest section in the pgdat, it need
* shrink pgdat->node_start_pfn and pgdat->node_spanned_pages.
* In this case, we find second smallest valid mem_section
* for shrinking zone.
*/
pfn = find_smallest_section_pfn(nid, NULL, end_pfn,
pgdat_end_pfn);
if (pfn) {
pgdat->node_start_pfn = pfn;
pgdat->node_spanned_pages = pgdat_end_pfn - pfn;
}
} else if (pgdat_end_pfn == end_pfn) {
/*
* If the section is biggest section in the pgdat, it need
* shrink pgdat->node_spanned_pages.
* In this case, we find second biggest valid mem_section for
* shrinking zone.
*/
pfn = find_biggest_section_pfn(nid, NULL, pgdat_start_pfn,
start_pfn);
if (pfn)
pgdat->node_spanned_pages = pfn - pgdat_start_pfn + 1;
}
/*
* If the section is not biggest or smallest mem_section in the pgdat,
* it only creates a hole in the pgdat. So in this case, we need not
* change the pgdat.
* But perhaps, the pgdat has only hole data. Thus it check the pgdat
* has only hole or not.
*/
pfn = pgdat_start_pfn;
for (; pfn < pgdat_end_pfn; pfn += PAGES_PER_SECTION) {
ms = __pfn_to_section(pfn);
if (unlikely(!valid_section(ms)))
continue;
if (pfn_to_nid(pfn) != nid)
continue;
/* If the section is current section, it continues the loop */
if (start_pfn == pfn)
continue;
/* If we find valid section, we have nothing to do */
return;
}
/* The pgdat has no valid section */
pgdat->node_start_pfn = 0;
pgdat->node_spanned_pages = 0;
}
static void __remove_zone(struct zone *zone, unsigned long start_pfn)
{
struct pglist_data *pgdat = zone->zone_pgdat;
int nr_pages = PAGES_PER_SECTION;
int zone_type;
unsigned long flags;
zone_type = zone - pgdat->node_zones;
pgdat_resize_lock(zone->zone_pgdat, &flags);
shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
shrink_pgdat_span(pgdat, start_pfn, start_pfn + nr_pages);
pgdat_resize_unlock(zone->zone_pgdat, &flags);
}
static int __remove_section(struct zone *zone, struct mem_section *ms)
{
unsigned long start_pfn;
int scn_nr;
int ret = -EINVAL;
if (!valid_section(ms))
return ret;
ret = unregister_memory_section(ms);
if (ret)
return ret;
scn_nr = __section_nr(ms);
start_pfn = section_nr_to_pfn(scn_nr);
__remove_zone(zone, start_pfn);
sparse_remove_one_section(zone, ms);
return 0;
}
/**
* __remove_pages() - remove sections of pages from a zone
* @zone: zone from which pages need to be removed
* @phys_start_pfn: starting pageframe (must be aligned to start of a section)
* @nr_pages: number of pages to remove (must be multiple of section size)
*
* Generic helper function to remove section mappings and sysfs entries
* for the section of the memory we are removing. Caller needs to make
* sure that pages are marked reserved and zones are adjust properly by
* calling offline_pages().
*/
int __remove_pages(struct zone *zone, unsigned long phys_start_pfn,
unsigned long nr_pages)
{
unsigned long i;
int sections_to_remove;
resource_size_t start, size;
int ret = 0;
/*
* We can only remove entire sections
*/
BUG_ON(phys_start_pfn & ~PAGE_SECTION_MASK);
BUG_ON(nr_pages % PAGES_PER_SECTION);
start = phys_start_pfn << PAGE_SHIFT;
size = nr_pages * PAGE_SIZE;
ret = release_mem_region_adjustable(&iomem_resource, start, size);
if (ret) {
resource_size_t endres = start + size - 1;
pr_warn("Unable to release resource <%pa-%pa> (%d)\n",
&start, &endres, ret);
}
sections_to_remove = nr_pages / PAGES_PER_SECTION;
for (i = 0; i < sections_to_remove; i++) {
unsigned long pfn = phys_start_pfn + i*PAGES_PER_SECTION;
ret = __remove_section(zone, __pfn_to_section(pfn));
if (ret)
break;
}
return ret;
}
EXPORT_SYMBOL_GPL(__remove_pages);
#endif /* CONFIG_MEMORY_HOTREMOVE */
int set_online_page_callback(online_page_callback_t callback)
{
int rc = -EINVAL;
get_online_mems();
mutex_lock(&online_page_callback_lock);
if (online_page_callback == generic_online_page) {
online_page_callback = callback;
rc = 0;
}
mutex_unlock(&online_page_callback_lock);
put_online_mems();
return rc;
}
EXPORT_SYMBOL_GPL(set_online_page_callback);
int restore_online_page_callback(online_page_callback_t callback)
{
int rc = -EINVAL;
get_online_mems();
mutex_lock(&online_page_callback_lock);
if (online_page_callback == callback) {
online_page_callback = generic_online_page;
rc = 0;
}
mutex_unlock(&online_page_callback_lock);
put_online_mems();
return rc;
}
EXPORT_SYMBOL_GPL(restore_online_page_callback);
void __online_page_set_limits(struct page *page)
{
}
EXPORT_SYMBOL_GPL(__online_page_set_limits);
void __online_page_increment_counters(struct page *page)
{
adjust_managed_page_count(page, 1);
}
EXPORT_SYMBOL_GPL(__online_page_increment_counters);
void __online_page_free(struct page *page)
{
__free_reserved_page(page);
}
EXPORT_SYMBOL_GPL(__online_page_free);
static void generic_online_page(struct page *page)
{
__online_page_set_limits(page);
__online_page_increment_counters(page);
__online_page_free(page);
}
static int online_pages_range(unsigned long start_pfn, unsigned long nr_pages,
void *arg)
{
unsigned long i;
unsigned long onlined_pages = *(unsigned long *)arg;
struct page *page;
if (PageReserved(pfn_to_page(start_pfn)))
for (i = 0; i < nr_pages; i++) {
page = pfn_to_page(start_pfn + i);
(*online_page_callback)(page);
onlined_pages++;
}
*(unsigned long *)arg = onlined_pages;
return 0;
}
#ifdef CONFIG_MOVABLE_NODE
/*
* When CONFIG_MOVABLE_NODE, we permit onlining of a node which doesn't have
* normal memory.
*/
static bool can_online_high_movable(struct zone *zone)
{
return true;
}
#else /* CONFIG_MOVABLE_NODE */
/* ensure every online node has NORMAL memory */
static bool can_online_high_movable(struct zone *zone)
{
return node_state(zone_to_nid(zone), N_NORMAL_MEMORY);
}
#endif /* CONFIG_MOVABLE_NODE */
/* check which state of node_states will be changed when online memory */
static void node_states_check_changes_online(unsigned long nr_pages,
struct zone *zone, struct memory_notify *arg)
{
int nid = zone_to_nid(zone);
enum zone_type zone_last = ZONE_NORMAL;
/*
* If we have HIGHMEM or movable node, node_states[N_NORMAL_MEMORY]
* contains nodes which have zones of 0...ZONE_NORMAL,
* set zone_last to ZONE_NORMAL.
*
* If we don't have HIGHMEM nor movable node,
* node_states[N_NORMAL_MEMORY] contains nodes which have zones of
* 0...ZONE_MOVABLE, set zone_last to ZONE_MOVABLE.
*/
if (N_MEMORY == N_NORMAL_MEMORY)
zone_last = ZONE_MOVABLE;
/*
* if the memory to be online is in a zone of 0...zone_last, and
* the zones of 0...zone_last don't have memory before online, we will
* need to set the node to node_states[N_NORMAL_MEMORY] after
* the memory is online.
*/
if (zone_idx(zone) <= zone_last && !node_state(nid, N_NORMAL_MEMORY))
arg->status_change_nid_normal = nid;
else
arg->status_change_nid_normal = -1;
#ifdef CONFIG_HIGHMEM
/*
* If we have movable node, node_states[N_HIGH_MEMORY]
* contains nodes which have zones of 0...ZONE_HIGHMEM,
* set zone_last to ZONE_HIGHMEM.
*
* If we don't have movable node, node_states[N_NORMAL_MEMORY]
* contains nodes which have zones of 0...ZONE_MOVABLE,
* set zone_last to ZONE_MOVABLE.
*/
zone_last = ZONE_HIGHMEM;
if (N_MEMORY == N_HIGH_MEMORY)
zone_last = ZONE_MOVABLE;
if (zone_idx(zone) <= zone_last && !node_state(nid, N_HIGH_MEMORY))
arg->status_change_nid_high = nid;
else
arg->status_change_nid_high = -1;
#else
arg->status_change_nid_high = arg->status_change_nid_normal;
#endif
/*
* if the node don't have memory befor online, we will need to
* set the node to node_states[N_MEMORY] after the memory
* is online.
*/
if (!node_state(nid, N_MEMORY))
arg->status_change_nid = nid;
else
arg->status_change_nid = -1;
}
static void node_states_set_node(int node, struct memory_notify *arg)
{
if (arg->status_change_nid_normal >= 0)
node_set_state(node, N_NORMAL_MEMORY);
if (arg->status_change_nid_high >= 0)
node_set_state(node, N_HIGH_MEMORY);
node_set_state(node, N_MEMORY);
}
int __ref online_pages(unsigned long pfn, unsigned long nr_pages, int online_type)
{
unsigned long flags;
unsigned long onlined_pages = 0;
struct zone *zone;
int need_zonelists_rebuild = 0;
int nid;
int ret;
struct memory_notify arg;
mem_hotplug_begin();
/*
* This doesn't need a lock to do pfn_to_page().
* The section can't be removed here because of the
* memory_block->state_mutex.
*/
zone = page_zone(pfn_to_page(pfn));
ret = -EINVAL;
if ((zone_idx(zone) > ZONE_NORMAL ||
online_type == MMOP_ONLINE_MOVABLE) &&
!can_online_high_movable(zone))
goto out;
if (online_type == MMOP_ONLINE_KERNEL &&
zone_idx(zone) == ZONE_MOVABLE) {
if (move_pfn_range_left(zone - 1, zone, pfn, pfn + nr_pages))
goto out;
}
if (online_type == MMOP_ONLINE_MOVABLE &&
zone_idx(zone) == ZONE_MOVABLE - 1) {
if (move_pfn_range_right(zone, zone + 1, pfn, pfn + nr_pages))
goto out;
}
/* Previous code may changed the zone of the pfn range */
zone = page_zone(pfn_to_page(pfn));
arg.start_pfn = pfn;
arg.nr_pages = nr_pages;
node_states_check_changes_online(nr_pages, zone, &arg);
nid = pfn_to_nid(pfn);
ret = memory_notify(MEM_GOING_ONLINE, &arg);
ret = notifier_to_errno(ret);
if (ret) {
memory_notify(MEM_CANCEL_ONLINE, &arg);
goto out;
}
/*
* If this zone is not populated, then it is not in zonelist.
* This means the page allocator ignores this zone.
* So, zonelist must be updated after online.
*/
mutex_lock(&zonelists_mutex);
if (!populated_zone(zone)) {
need_zonelists_rebuild = 1;
build_all_zonelists(NULL, zone);
}
ret = walk_system_ram_range(pfn, nr_pages, &onlined_pages,
online_pages_range);
if (ret) {
if (need_zonelists_rebuild)
zone_pcp_reset(zone);
mutex_unlock(&zonelists_mutex);
printk(KERN_DEBUG "online_pages [mem %#010llx-%#010llx] failed\n",
(unsigned long long) pfn << PAGE_SHIFT,
(((unsigned long long) pfn + nr_pages)
<< PAGE_SHIFT) - 1);
memory_notify(MEM_CANCEL_ONLINE, &arg);
goto out;
}
zone->present_pages += onlined_pages;
pgdat_resize_lock(zone->zone_pgdat, &flags);
zone->zone_pgdat->node_present_pages += onlined_pages;
pgdat_resize_unlock(zone->zone_pgdat, &flags);
if (onlined_pages) {
node_states_set_node(zone_to_nid(zone), &arg);
if (need_zonelists_rebuild)
build_all_zonelists(NULL, NULL);
else
zone_pcp_update(zone);
}
mutex_unlock(&zonelists_mutex);
init_per_zone_wmark_min();
if (onlined_pages)
kswapd_run(zone_to_nid(zone));
vm_total_pages = nr_free_pagecache_pages();
writeback_set_ratelimit();
if (onlined_pages)
memory_notify(MEM_ONLINE, &arg);
out:
mem_hotplug_done();
return ret;
}
#endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */
static void reset_node_present_pages(pg_data_t *pgdat)
{
struct zone *z;
for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
z->present_pages = 0;
pgdat->node_present_pages = 0;
}
/* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
static pg_data_t __ref *hotadd_new_pgdat(int nid, u64 start)
{
struct pglist_data *pgdat;
unsigned long zones_size[MAX_NR_ZONES] = {0};
unsigned long zholes_size[MAX_NR_ZONES] = {0};
unsigned long start_pfn = PFN_DOWN(start);
pgdat = NODE_DATA(nid);
if (!pgdat) {
pgdat = arch_alloc_nodedata(nid);
if (!pgdat)
return NULL;
arch_refresh_nodedata(nid, pgdat);
} else {
/* Reset the nr_zones and classzone_idx to 0 before reuse */
pgdat->nr_zones = 0;
pgdat->classzone_idx = 0;
}
/* we can use NODE_DATA(nid) from here */
/* init node's zones as empty zones, we don't have any present pages.*/
free_area_init_node(nid, zones_size, start_pfn, zholes_size);
/*
* The node we allocated has no zone fallback lists. For avoiding
* to access not-initialized zonelist, build here.
*/
mutex_lock(&zonelists_mutex);
build_all_zonelists(pgdat, NULL);
mutex_unlock(&zonelists_mutex);
/*
* zone->managed_pages is set to an approximate value in
* free_area_init_core(), which will cause
* /sys/device/system/node/nodeX/meminfo has wrong data.
* So reset it to 0 before any memory is onlined.
*/
reset_node_managed_pages(pgdat);
/*
* When memory is hot-added, all the memory is in offline state. So
* clear all zones' present_pages because they will be updated in
* online_pages() and offline_pages().
*/
reset_node_present_pages(pgdat);
return pgdat;
}
static void rollback_node_hotadd(int nid, pg_data_t *pgdat)
{
arch_refresh_nodedata(nid, NULL);
arch_free_nodedata(pgdat);
return;
}
/**
* try_online_node - online a node if offlined
*
* called by cpu_up() to online a node without onlined memory.
*/
int try_online_node(int nid)
{
pg_data_t *pgdat;
int ret;
if (node_online(nid))
return 0;
mem_hotplug_begin();
pgdat = hotadd_new_pgdat(nid, 0);
if (!pgdat) {
pr_err("Cannot online node %d due to NULL pgdat\n", nid);
ret = -ENOMEM;
goto out;
}
node_set_online(nid);
ret = register_one_node(nid);
BUG_ON(ret);
if (pgdat->node_zonelists->_zonerefs->zone == NULL) {
mutex_lock(&zonelists_mutex);
build_all_zonelists(NULL, NULL);
mutex_unlock(&zonelists_mutex);
}
out:
mem_hotplug_done();
return ret;
}
static int check_hotplug_memory_range(u64 start, u64 size)
{
u64 start_pfn = PFN_DOWN(start);
u64 nr_pages = size >> PAGE_SHIFT;
/* Memory range must be aligned with section */
if ((start_pfn & ~PAGE_SECTION_MASK) ||
(nr_pages % PAGES_PER_SECTION) || (!nr_pages)) {
pr_err("Section-unaligned hotplug range: start 0x%llx, size 0x%llx\n",
(unsigned long long)start,
(unsigned long long)size);
return -EINVAL;
}
return 0;
}
/*
* If movable zone has already been setup, newly added memory should be check.
* If its address is higher than movable zone, it should be added as movable.
* Without this check, movable zone may overlap with other zone.
*/
static int should_add_memory_movable(int nid, u64 start, u64 size)
{
unsigned long start_pfn = start >> PAGE_SHIFT;
pg_data_t *pgdat = NODE_DATA(nid);
struct zone *movable_zone = pgdat->node_zones + ZONE_MOVABLE;
if (zone_is_empty(movable_zone))
return 0;
if (movable_zone->zone_start_pfn <= start_pfn)
return 1;
return 0;
}
int zone_for_memory(int nid, u64 start, u64 size, int zone_default)
{
if (should_add_memory_movable(nid, start, size))
return ZONE_MOVABLE;
return zone_default;
}
/* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
int __ref add_memory(int nid, u64 start, u64 size)
{
pg_data_t *pgdat = NULL;
bool new_pgdat;
bool new_node;
struct resource *res;
int ret;
ret = check_hotplug_memory_range(start, size);
if (ret)
return ret;
res = register_memory_resource(start, size);
ret = -EEXIST;
if (!res)
return ret;
{ /* Stupid hack to suppress address-never-null warning */
void *p = NODE_DATA(nid);
new_pgdat = !p;
}
mem_hotplug_begin();
new_node = !node_online(nid);
if (new_node) {
pgdat = hotadd_new_pgdat(nid, start);
ret = -ENOMEM;
if (!pgdat)
goto error;
}
/* call arch's memory hotadd */
ret = arch_add_memory(nid, start, size);
if (ret < 0)
goto error;
/* we online node here. we can't roll back from here. */
node_set_online(nid);
if (new_node) {
ret = register_one_node(nid);
/*
* If sysfs file of new node can't create, cpu on the node
* can't be hot-added. There is no rollback way now.
* So, check by BUG_ON() to catch it reluctantly..
*/
BUG_ON(ret);
}
/* create new memmap entry */
firmware_map_add_hotplug(start, start + size, "System RAM");
goto out;
error:
/* rollback pgdat allocation and others */
if (new_pgdat)
rollback_node_hotadd(nid, pgdat);
release_memory_resource(res);
out:
mem_hotplug_done();
return ret;
}
EXPORT_SYMBOL_GPL(add_memory);
#ifdef CONFIG_MEMORY_HOTREMOVE
/*
* A free page on the buddy free lists (not the per-cpu lists) has PageBuddy
* set and the size of the free page is given by page_order(). Using this,
* the function determines if the pageblock contains only free pages.
* Due to buddy contraints, a free page at least the size of a pageblock will
* be located at the start of the pageblock
*/
static inline int pageblock_free(struct page *page)
{
return PageBuddy(page) && page_order(page) >= pageblock_order;
}
/* Return the start of the next active pageblock after a given page */
static struct page *next_active_pageblock(struct page *page)
{
/* Ensure the starting page is pageblock-aligned */
BUG_ON(page_to_pfn(page) & (pageblock_nr_pages - 1));
/* If the entire pageblock is free, move to the end of free page */
if (pageblock_free(page)) {
int order;
/* be careful. we don't have locks, page_order can be changed.*/
order = page_order(page);
if ((order < MAX_ORDER) && (order >= pageblock_order))
return page + (1 << order);
}
return page + pageblock_nr_pages;
}
/* Checks if this range of memory is likely to be hot-removable. */
int is_mem_section_removable(unsigned long start_pfn, unsigned long nr_pages)
{
struct page *page = pfn_to_page(start_pfn);
struct page *end_page = page + nr_pages;
/* Check the starting page of each pageblock within the range */
for (; page < end_page; page = next_active_pageblock(page)) {
if (!is_pageblock_removable_nolock(page))
return 0;
cond_resched();
}
/* All pageblocks in the memory block are likely to be hot-removable */
return 1;
}
/*
* Confirm all pages in a range [start, end) is belongs to the same zone.
*/
int test_pages_in_a_zone(unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long pfn;
struct zone *zone = NULL;
struct page *page;
int i;
for (pfn = start_pfn;
pfn < end_pfn;
pfn += MAX_ORDER_NR_PAGES) {
i = 0;
/* This is just a CONFIG_HOLES_IN_ZONE check.*/
while ((i < MAX_ORDER_NR_PAGES) && !pfn_valid_within(pfn + i))
i++;
if (i == MAX_ORDER_NR_PAGES)
continue;
page = pfn_to_page(pfn + i);
if (zone && page_zone(page) != zone)
return 0;
zone = page_zone(page);
}
return 1;
}
/*
* Scan pfn range [start,end) to find movable/migratable pages (LRU pages
* and hugepages). We scan pfn because it's much easier than scanning over
* linked list. This function returns the pfn of the first found movable
* page if it's found, otherwise 0.
*/
static unsigned long scan_movable_pages(unsigned long start, unsigned long end)
{
unsigned long pfn;
struct page *page;
for (pfn = start; pfn < end; pfn++) {
if (pfn_valid(pfn)) {
page = pfn_to_page(pfn);
if (PageLRU(page))
return pfn;
if (PageHuge(page)) {
if (is_hugepage_active(page))
return pfn;
else
pfn = round_up(pfn + 1,
1 << compound_order(page)) - 1;
}
}
}
return 0;
}
#define NR_OFFLINE_AT_ONCE_PAGES (256)
static int
do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long pfn;
struct page *page;
int move_pages = NR_OFFLINE_AT_ONCE_PAGES;
int not_managed = 0;
int ret = 0;
LIST_HEAD(source);
for (pfn = start_pfn; pfn < end_pfn && move_pages > 0; pfn++) {
if (!pfn_valid(pfn))
continue;
page = pfn_to_page(pfn);
if (PageHuge(page)) {
struct page *head = compound_head(page);
pfn = page_to_pfn(head) + (1<<compound_order(head)) - 1;
if (compound_order(head) > PFN_SECTION_SHIFT) {
ret = -EBUSY;
break;
}
if (isolate_huge_page(page, &source))
move_pages -= 1 << compound_order(head);
continue;
}
if (!get_page_unless_zero(page))
continue;
/*
* We can skip free pages. And we can only deal with pages on
* LRU.
*/
ret = isolate_lru_page(page);
if (!ret) { /* Success */
put_page(page);
list_add_tail(&page->lru, &source);
move_pages--;
inc_zone_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
} else {
#ifdef CONFIG_DEBUG_VM
printk(KERN_ALERT "removing pfn %lx from LRU failed\n",
pfn);
dump_page(page, "failed to remove from LRU");
#endif
put_page(page);
/* Because we don't have big zone->lock. we should
check this again here. */
if (page_count(page)) {
not_managed++;
ret = -EBUSY;
break;
}
}
}
if (!list_empty(&source)) {
if (not_managed) {
putback_movable_pages(&source);
goto out;
}
/*
* alloc_migrate_target should be improooooved!!
* migrate_pages returns # of failed pages.
*/
ret = migrate_pages(&source, alloc_migrate_target, NULL, 0,
MIGRATE_SYNC, MR_MEMORY_HOTPLUG);
if (ret)
putback_movable_pages(&source);
}
out:
return ret;
}
/*
* remove from free_area[] and mark all as Reserved.
*/
static int
offline_isolated_pages_cb(unsigned long start, unsigned long nr_pages,
void *data)
{
__offline_isolated_pages(start, start + nr_pages);
return 0;
}
static void
offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
{
walk_system_ram_range(start_pfn, end_pfn - start_pfn, NULL,
offline_isolated_pages_cb);
}
/*
* Check all pages in range, recoreded as memory resource, are isolated.
*/
static int
check_pages_isolated_cb(unsigned long start_pfn, unsigned long nr_pages,
void *data)
{
int ret;
long offlined = *(long *)data;
ret = test_pages_isolated(start_pfn, start_pfn + nr_pages, true);
offlined = nr_pages;
if (!ret)
*(long *)data += offlined;
return ret;
}
static long
check_pages_isolated(unsigned long start_pfn, unsigned long end_pfn)
{
long offlined = 0;
int ret;
ret = walk_system_ram_range(start_pfn, end_pfn - start_pfn, &offlined,
check_pages_isolated_cb);
if (ret < 0)
offlined = (long)ret;
return offlined;
}
#ifdef CONFIG_MOVABLE_NODE
/*
* When CONFIG_MOVABLE_NODE, we permit offlining of a node which doesn't have
* normal memory.
*/
static bool can_offline_normal(struct zone *zone, unsigned long nr_pages)
{
return true;
}
#else /* CONFIG_MOVABLE_NODE */
/* ensure the node has NORMAL memory if it is still online */
static bool can_offline_normal(struct zone *zone, unsigned long nr_pages)
{
struct pglist_data *pgdat = zone->zone_pgdat;
unsigned long present_pages = 0;
enum zone_type zt;
for (zt = 0; zt <= ZONE_NORMAL; zt++)
present_pages += pgdat->node_zones[zt].present_pages;
if (present_pages > nr_pages)
return true;
present_pages = 0;
for (; zt <= ZONE_MOVABLE; zt++)
present_pages += pgdat->node_zones[zt].present_pages;
/*
* we can't offline the last normal memory until all
* higher memory is offlined.
*/
return present_pages == 0;
}
#endif /* CONFIG_MOVABLE_NODE */
static int __init cmdline_parse_movable_node(char *p)
{
#ifdef CONFIG_MOVABLE_NODE
/*
* Memory used by the kernel cannot be hot-removed because Linux
* cannot migrate the kernel pages. When memory hotplug is
* enabled, we should prevent memblock from allocating memory
* for the kernel.
*
* ACPI SRAT records all hotpluggable memory ranges. But before
* SRAT is parsed, we don't know about it.
*
* The kernel image is loaded into memory at very early time. We
* cannot prevent this anyway. So on NUMA system, we set any
* node the kernel resides in as un-hotpluggable.
*
* Since on modern servers, one node could have double-digit
* gigabytes memory, we can assume the memory around the kernel
* image is also un-hotpluggable. So before SRAT is parsed, just
* allocate memory near the kernel image to try the best to keep
* the kernel away from hotpluggable memory.
*/
memblock_set_bottom_up(true);
movable_node_enabled = true;
#else
pr_warn("movable_node option not supported\n");
#endif
return 0;
}
early_param("movable_node", cmdline_parse_movable_node);
/* check which state of node_states will be changed when offline memory */
static void node_states_check_changes_offline(unsigned long nr_pages,
struct zone *zone, struct memory_notify *arg)
{
struct pglist_data *pgdat = zone->zone_pgdat;
unsigned long present_pages = 0;
enum zone_type zt, zone_last = ZONE_NORMAL;
/*
* If we have HIGHMEM or movable node, node_states[N_NORMAL_MEMORY]
* contains nodes which have zones of 0...ZONE_NORMAL,
* set zone_last to ZONE_NORMAL.
*
* If we don't have HIGHMEM nor movable node,
* node_states[N_NORMAL_MEMORY] contains nodes which have zones of
* 0...ZONE_MOVABLE, set zone_last to ZONE_MOVABLE.
*/
if (N_MEMORY == N_NORMAL_MEMORY)
zone_last = ZONE_MOVABLE;
/*
* check whether node_states[N_NORMAL_MEMORY] will be changed.
* If the memory to be offline is in a zone of 0...zone_last,
* and it is the last present memory, 0...zone_last will
* become empty after offline , thus we can determind we will
* need to clear the node from node_states[N_NORMAL_MEMORY].
*/
for (zt = 0; zt <= zone_last; zt++)
present_pages += pgdat->node_zones[zt].present_pages;
if (zone_idx(zone) <= zone_last && nr_pages >= present_pages)
arg->status_change_nid_normal = zone_to_nid(zone);
else
arg->status_change_nid_normal = -1;
#ifdef CONFIG_HIGHMEM
/*
* If we have movable node, node_states[N_HIGH_MEMORY]
* contains nodes which have zones of 0...ZONE_HIGHMEM,
* set zone_last to ZONE_HIGHMEM.
*
* If we don't have movable node, node_states[N_NORMAL_MEMORY]
* contains nodes which have zones of 0...ZONE_MOVABLE,
* set zone_last to ZONE_MOVABLE.
*/
zone_last = ZONE_HIGHMEM;
if (N_MEMORY == N_HIGH_MEMORY)
zone_last = ZONE_MOVABLE;
for (; zt <= zone_last; zt++)
present_pages += pgdat->node_zones[zt].present_pages;
if (zone_idx(zone) <= zone_last && nr_pages >= present_pages)
arg->status_change_nid_high = zone_to_nid(zone);
else
arg->status_change_nid_high = -1;
#else
arg->status_change_nid_high = arg->status_change_nid_normal;
#endif
/*
* node_states[N_HIGH_MEMORY] contains nodes which have 0...ZONE_MOVABLE
*/
zone_last = ZONE_MOVABLE;
/*
* check whether node_states[N_HIGH_MEMORY] will be changed
* If we try to offline the last present @nr_pages from the node,
* we can determind we will need to clear the node from
* node_states[N_HIGH_MEMORY].
*/
for (; zt <= zone_last; zt++)
present_pages += pgdat->node_zones[zt].present_pages;
if (nr_pages >= present_pages)
arg->status_change_nid = zone_to_nid(zone);
else
arg->status_change_nid = -1;
}
static void node_states_clear_node(int node, struct memory_notify *arg)
{
if (arg->status_change_nid_normal >= 0)
node_clear_state(node, N_NORMAL_MEMORY);
if ((N_MEMORY != N_NORMAL_MEMORY) &&
(arg->status_change_nid_high >= 0))
node_clear_state(node, N_HIGH_MEMORY);
if ((N_MEMORY != N_HIGH_MEMORY) &&
(arg->status_change_nid >= 0))
node_clear_state(node, N_MEMORY);
}
static int __ref __offline_pages(unsigned long start_pfn,
unsigned long end_pfn, unsigned long timeout)
{
unsigned long pfn, nr_pages, expire;
long offlined_pages;
int ret, drain, retry_max, node;
unsigned long flags;
struct zone *zone;
struct memory_notify arg;
/* at least, alignment against pageblock is necessary */
if (!IS_ALIGNED(start_pfn, pageblock_nr_pages))
return -EINVAL;
if (!IS_ALIGNED(end_pfn, pageblock_nr_pages))
return -EINVAL;
/* This makes hotplug much easier...and readable.
we assume this for now. .*/
if (!test_pages_in_a_zone(start_pfn, end_pfn))
return -EINVAL;
mem_hotplug_begin();
zone = page_zone(pfn_to_page(start_pfn));
node = zone_to_nid(zone);
nr_pages = end_pfn - start_pfn;
ret = -EINVAL;
if (zone_idx(zone) <= ZONE_NORMAL && !can_offline_normal(zone, nr_pages))
goto out;
/* set above range as isolated */
ret = start_isolate_page_range(start_pfn, end_pfn,
MIGRATE_MOVABLE, true);
if (ret)
goto out;
arg.start_pfn = start_pfn;
arg.nr_pages = nr_pages;
node_states_check_changes_offline(nr_pages, zone, &arg);
ret = memory_notify(MEM_GOING_OFFLINE, &arg);
ret = notifier_to_errno(ret);
if (ret)
goto failed_removal;
pfn = start_pfn;
expire = jiffies + timeout;
drain = 0;
retry_max = 5;
repeat:
/* start memory hot removal */
ret = -EAGAIN;
if (time_after(jiffies, expire))
goto failed_removal;
ret = -EINTR;
if (signal_pending(current))
goto failed_removal;
ret = 0;
if (drain) {
lru_add_drain_all();
cond_resched();
drain_all_pages(zone);
}
pfn = scan_movable_pages(start_pfn, end_pfn);
if (pfn) { /* We have movable pages */
ret = do_migrate_range(pfn, end_pfn);
if (!ret) {
drain = 1;
goto repeat;
} else {
if (ret < 0)
if (--retry_max == 0)
goto failed_removal;
yield();
drain = 1;
goto repeat;
}
}
/* drain all zone's lru pagevec, this is asynchronous... */
lru_add_drain_all();
yield();
/* drain pcp pages, this is synchronous. */
drain_all_pages(zone);
/*
* dissolve free hugepages in the memory block before doing offlining
* actually in order to make hugetlbfs's object counting consistent.
*/
dissolve_free_huge_pages(start_pfn, end_pfn);
/* check again */
offlined_pages = check_pages_isolated(start_pfn, end_pfn);
if (offlined_pages < 0) {
ret = -EBUSY;
goto failed_removal;
}
printk(KERN_INFO "Offlined Pages %ld\n", offlined_pages);
/* Ok, all of our target is isolated.
We cannot do rollback at this point. */
offline_isolated_pages(start_pfn, end_pfn);
/* reset pagetype flags and makes migrate type to be MOVABLE */
undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
/* removal success */
adjust_managed_page_count(pfn_to_page(start_pfn), -offlined_pages);
zone->present_pages -= offlined_pages;
pgdat_resize_lock(zone->zone_pgdat, &flags);
zone->zone_pgdat->node_present_pages -= offlined_pages;
pgdat_resize_unlock(zone->zone_pgdat, &flags);
init_per_zone_wmark_min();
if (!populated_zone(zone)) {
zone_pcp_reset(zone);
mutex_lock(&zonelists_mutex);
build_all_zonelists(NULL, NULL);
mutex_unlock(&zonelists_mutex);
} else
zone_pcp_update(zone);
node_states_clear_node(node, &arg);
if (arg.status_change_nid >= 0)
kswapd_stop(node);
vm_total_pages = nr_free_pagecache_pages();
writeback_set_ratelimit();
memory_notify(MEM_OFFLINE, &arg);
mem_hotplug_done();
return 0;
failed_removal:
printk(KERN_INFO "memory offlining [mem %#010llx-%#010llx] failed\n",
(unsigned long long) start_pfn << PAGE_SHIFT,
((unsigned long long) end_pfn << PAGE_SHIFT) - 1);
memory_notify(MEM_CANCEL_OFFLINE, &arg);
/* pushback to free area */
undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
out:
mem_hotplug_done();
return ret;
}
int offline_pages(unsigned long start_pfn, unsigned long nr_pages)
{
return __offline_pages(start_pfn, start_pfn + nr_pages, 120 * HZ);
}
#endif /* CONFIG_MEMORY_HOTREMOVE */
/**
* walk_memory_range - walks through all mem sections in [start_pfn, end_pfn)
* @start_pfn: start pfn of the memory range
* @end_pfn: end pfn of the memory range
* @arg: argument passed to func
* @func: callback for each memory section walked
*
* This function walks through all present mem sections in range
* [start_pfn, end_pfn) and call func on each mem section.
*
* Returns the return value of func.
*/
int walk_memory_range(unsigned long start_pfn, unsigned long end_pfn,
void *arg, int (*func)(struct memory_block *, void *))
{
struct memory_block *mem = NULL;
struct mem_section *section;
unsigned long pfn, section_nr;
int ret;
for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
section_nr = pfn_to_section_nr(pfn);
if (!present_section_nr(section_nr))
continue;
section = __nr_to_section(section_nr);
/* same memblock? */
if (mem)
if ((section_nr >= mem->start_section_nr) &&
(section_nr <= mem->end_section_nr))
continue;
mem = find_memory_block_hinted(section, mem);
if (!mem)
continue;
ret = func(mem, arg);
if (ret) {
kobject_put(&mem->dev.kobj);
return ret;
}
}
if (mem)
kobject_put(&mem->dev.kobj);
return 0;
}
#ifdef CONFIG_MEMORY_HOTREMOVE
static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
{
int ret = !is_memblock_offlined(mem);
if (unlikely(ret)) {
phys_addr_t beginpa, endpa;
beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
endpa = PFN_PHYS(section_nr_to_pfn(mem->end_section_nr + 1))-1;
pr_warn("removing memory fails, because memory "
"[%pa-%pa] is onlined\n",
&beginpa, &endpa);
}
return ret;
}
static int check_cpu_on_node(pg_data_t *pgdat)
{
int cpu;
for_each_present_cpu(cpu) {
if (cpu_to_node(cpu) == pgdat->node_id)
/*
* the cpu on this node isn't removed, and we can't
* offline this node.
*/
return -EBUSY;
}
return 0;
}
static void unmap_cpu_on_node(pg_data_t *pgdat)
{
#ifdef CONFIG_ACPI_NUMA
int cpu;
for_each_possible_cpu(cpu)
if (cpu_to_node(cpu) == pgdat->node_id)
numa_clear_node(cpu);
#endif
}
static int check_and_unmap_cpu_on_node(pg_data_t *pgdat)
{
int ret;
ret = check_cpu_on_node(pgdat);
if (ret)
return ret;
/*
* the node will be offlined when we come here, so we can clear
* the cpu_to_node() now.
*/
unmap_cpu_on_node(pgdat);
return 0;
}
/**
* try_offline_node
*
* Offline a node if all memory sections and cpus of the node are removed.
*
* NOTE: The caller must call lock_device_hotplug() to serialize hotplug
* and online/offline operations before this call.
*/
void try_offline_node(int nid)
{
pg_data_t *pgdat = NODE_DATA(nid);
unsigned long start_pfn = pgdat->node_start_pfn;
unsigned long end_pfn = start_pfn + pgdat->node_spanned_pages;
unsigned long pfn;
int i;
for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
unsigned long section_nr = pfn_to_section_nr(pfn);
if (!present_section_nr(section_nr))
continue;
if (pfn_to_nid(pfn) != nid)
continue;
/*
* some memory sections of this node are not removed, and we
* can't offline node now.
*/
return;
}
if (check_and_unmap_cpu_on_node(pgdat))
return;
/*
* all memory/cpu of this node are removed, we can offline this
* node now.
*/
node_set_offline(nid);
unregister_one_node(nid);
/* free waittable in each zone */
for (i = 0; i < MAX_NR_ZONES; i++) {
struct zone *zone = pgdat->node_zones + i;
/*
* wait_table may be allocated from boot memory,
* here only free if it's allocated by vmalloc.
*/
if (is_vmalloc_addr(zone->wait_table)) {
vfree(zone->wait_table);
zone->wait_table = NULL;
}
}
}
EXPORT_SYMBOL(try_offline_node);
/**
* remove_memory
*
* NOTE: The caller must call lock_device_hotplug() to serialize hotplug
* and online/offline operations before this call, as required by
* try_offline_node().
*/
void __ref remove_memory(int nid, u64 start, u64 size)
{
int ret;
BUG_ON(check_hotplug_memory_range(start, size));
mem_hotplug_begin();
/*
* All memory blocks must be offlined before removing memory. Check
* whether all memory blocks in question are offline and trigger a BUG()
* if this is not the case.
*/
ret = walk_memory_range(PFN_DOWN(start), PFN_UP(start + size - 1), NULL,
check_memblock_offlined_cb);
if (ret)
BUG();
/* remove memmap entry */
firmware_map_remove(start, start + size, "System RAM");
arch_remove_memory(start, size);
try_offline_node(nid);
mem_hotplug_done();
}
EXPORT_SYMBOL_GPL(remove_memory);
#endif /* CONFIG_MEMORY_HOTREMOVE */
| allan888/Linux_anti_malware_file_system | mm/memory_hotplug.c | C | gpl-2.0 | 52,399 |
/***
* ASM XML Adapter
* Copyright (c) 2004, Eugene Kuleshov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm.xml;
import java.util.HashMap;
import java.util.Map;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Label;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.AbstractVisitor;
import org.xml.sax.ContentHandler;
import org.xml.sax.helpers.AttributesImpl;
/**
* A {@link MethodVisitor} that generates SAX 2.0 events from the visited
* method.
*
* @see org.objectweb.asm.xml.SAXClassAdapter
* @see org.objectweb.asm.xml.Processor
*
* @author Eugene Kuleshov
*/
public final class SAXCodeAdapter extends SAXAdapter implements MethodVisitor {
private Map labelNames;
/**
* Constructs a new {@link SAXCodeAdapter SAXCodeAdapter} object.
*
* @param h content handler that will be used to send SAX 2.0 events.
* @param access
*/
public SAXCodeAdapter(ContentHandler h, int access) {
super(h);
labelNames = new HashMap();
if ((access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE | Opcodes.ACC_NATIVE)) == 0)
{
addStart("code", new AttributesImpl());
}
}
public final void visitCode() {
}
public final void visitInsn(int opcode) {
addElement(AbstractVisitor.OPCODES[opcode], new AttributesImpl());
}
public final void visitIntInsn(int opcode, int operand) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "value", "value", "", Integer.toString(operand));
addElement(AbstractVisitor.OPCODES[opcode], attrs);
}
public final void visitVarInsn(int opcode, int var) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "var", "var", "", Integer.toString(var));
addElement(AbstractVisitor.OPCODES[opcode], attrs);
}
public final void visitTypeInsn(int opcode, String desc) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "desc", "desc", "", desc);
addElement(AbstractVisitor.OPCODES[opcode], attrs);
}
public final void visitFieldInsn(
int opcode,
String owner,
String name,
String desc)
{
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "owner", "owner", "", owner);
attrs.addAttribute("", "name", "name", "", name);
attrs.addAttribute("", "desc", "desc", "", desc);
addElement(AbstractVisitor.OPCODES[opcode], attrs);
}
public final void visitMethodInsn(
int opcode,
String owner,
String name,
String desc)
{
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "owner", "owner", "", owner);
attrs.addAttribute("", "name", "name", "", name);
attrs.addAttribute("", "desc", "desc", "", desc);
addElement(AbstractVisitor.OPCODES[opcode], attrs);
}
public final void visitJumpInsn(int opcode, Label label) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "label", "label", "", getLabel(label));
addElement(AbstractVisitor.OPCODES[opcode], attrs);
}
public final void visitLabel(Label label) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "name", "name", "", getLabel(label));
addElement("Label", attrs);
}
public final void visitLdcInsn(Object cst) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("",
"cst",
"cst",
"",
SAXClassAdapter.encode(cst.toString()));
attrs.addAttribute("",
"desc",
"desc",
"",
Type.getDescriptor(cst.getClass()));
addElement(AbstractVisitor.OPCODES[Opcodes.LDC], attrs);
}
public final void visitIincInsn(int var, int increment) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "var", "var", "", Integer.toString(var));
attrs.addAttribute("", "inc", "inc", "", Integer.toString(increment));
addElement(AbstractVisitor.OPCODES[Opcodes.IINC], attrs);
}
public final void visitTableSwitchInsn(
int min,
int max,
Label dflt,
Label[] labels)
{
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "min", "min", "", Integer.toString(min));
attrs.addAttribute("", "max", "max", "", Integer.toString(max));
attrs.addAttribute("", "dflt", "dflt", "", getLabel(dflt));
String o = AbstractVisitor.OPCODES[Opcodes.TABLESWITCH];
addStart(o, attrs);
for (int i = 0; i < labels.length; i++) {
AttributesImpl att2 = new AttributesImpl();
att2.addAttribute("", "name", "name", "", getLabel(labels[i]));
addElement("label", att2);
}
addEnd(o);
}
public final void visitLookupSwitchInsn(
Label dflt,
int[] keys,
Label[] labels)
{
AttributesImpl att = new AttributesImpl();
att.addAttribute("", "dflt", "dflt", "", getLabel(dflt));
String o = AbstractVisitor.OPCODES[Opcodes.LOOKUPSWITCH];
addStart(o, att);
for (int i = 0; i < labels.length; i++) {
AttributesImpl att2 = new AttributesImpl();
att2.addAttribute("", "name", "name", "", getLabel(labels[i]));
att2.addAttribute("", "key", "key", "", Integer.toString(keys[i]));
addElement("label", att2);
}
addEnd(o);
}
public final void visitMultiANewArrayInsn(String desc, int dims) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "desc", "desc", "", desc);
attrs.addAttribute("", "dims", "dims", "", Integer.toString(dims));
addElement(AbstractVisitor.OPCODES[Opcodes.MULTIANEWARRAY], attrs);
}
public final void visitTryCatchBlock(
Label start,
Label end,
Label handler,
String type)
{
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "start", "start", "", getLabel(start));
attrs.addAttribute("", "end", "end", "", getLabel(end));
attrs.addAttribute("", "handler", "handler", "", getLabel(handler));
if (type != null)
attrs.addAttribute("", "type", "type", "", type);
addElement("TryCatch", attrs);
}
public final void visitMaxs(int maxStack, int maxLocals) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("",
"maxStack",
"maxStack",
"",
Integer.toString(maxStack));
attrs.addAttribute("",
"maxLocals",
"maxLocals",
"",
Integer.toString(maxLocals));
addElement("Max", attrs);
addEnd("code");
}
public void visitLocalVariable(
String name,
String desc,
String signature,
Label start,
Label end,
int index)
{
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "name", "name", "", name);
attrs.addAttribute("", "desc", "desc", "", desc);
if (signature != null)
attrs.addAttribute("",
"signature",
"signature",
"",
SAXClassAdapter.encode(signature));
attrs.addAttribute("", "start", "start", "", getLabel(start));
attrs.addAttribute("", "end", "end", "", getLabel(end));
attrs.addAttribute("", "var", "var", "", Integer.toString(index));
addElement("LocalVar", attrs);
}
public final void visitLineNumber(int line, Label start) {
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "line", "line", "", Integer.toString(line));
attrs.addAttribute("", "start", "start", "", getLabel(start));
addElement("LineNumber", attrs);
}
public AnnotationVisitor visitAnnotationDefault() {
return new SAXAnnotationAdapter(getContentHandler(),
"annotationDefault",
0,
null,
null);
}
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return new SAXAnnotationAdapter(getContentHandler(),
"annotation",
visible ? 1 : -1,
null,
desc);
}
public AnnotationVisitor visitParameterAnnotation(
int parameter,
String desc,
boolean visible)
{
return new SAXAnnotationAdapter(getContentHandler(),
"parameterAnnotation",
visible ? 1 : -1,
parameter,
desc);
}
public void visitEnd() {
addEnd("method");
}
public final void visitAttribute(Attribute attr) {
// TODO Auto-generated SAXCodeAdapter.visitAttribute
}
private final String getLabel(Label label) {
String name = (String) labelNames.get(label);
if (name == null) {
name = Integer.toString(labelNames.size());
labelNames.put(label, name);
}
return name;
}
}
| taciano-perez/JamVM-PH | src/classpath/tools/external/asm/org/objectweb/asm/xml/SAXCodeAdapter.java | Java | gpl-2.0 | 11,030 |
/*
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8059100
* @summary Test that you can decrease NMT tracking level but not increase it.
* @key nmt
* @library /testlibrary /testlibrary/whitebox
* @build ChangeTrackingLevel
* @run main ClassFileInstaller sun.hotspot.WhiteBox
* sun.hotspot.WhiteBox$WhiteBoxPermission
* @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:NativeMemoryTracking=detail ChangeTrackingLevel
*/
import com.oracle.java.testlibrary.*;
import sun.hotspot.WhiteBox;
public class ChangeTrackingLevel {
public static WhiteBox wb = WhiteBox.getWhiteBox();
public static void main(String args[]) throws Exception {
boolean testChangeLevel = wb.NMTChangeTrackingLevel();
if (testChangeLevel) {
System.out.println("NMT level change test passed.");
} else {
// it also fails if the VM asserts.
throw new RuntimeException("NMT level change test failed");
}
}
};
| MyProgrammingStyle/hotspot | test/runtime/NMT/ChangeTrackingLevel.java | Java | gpl-2.0 | 2,062 |
/*
* This file is part of Invenio.
* Copyright (C) 2012 CERN.
*
* Invenio is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* Invenio is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Invenio; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Module with all functions related to refextract and BibEdit
*/
var refextract = (function() {
var dialogReferences;
function updateDialogLoading(title) {
/* Creates a loading dialog
@param title: title to be displayed on the dialog
*/
if (typeof dialogReferences !== "undefined") {
dialogReferences.dialogDiv.remove();
}
dialogReferences = createDialog(title, "Loading...", 750, 700, true);
}
function updateDialogRefextractResult(json) {
/* Receives JSON from the server and either:
- Shows an error dialog with the error message
- Updates the client representation of the record, updates the cache
file on the server and displays the new record on the interface
*/
var bibrecord = json['ref_bibrecord'];
var textmarc = json['ref_textmarc'];
var xmlrecord = json['ref_xmlrecord'];
if (!xmlrecord) {
dialogReferences.dialogDiv.remove();
dialogReferences = createDialog("Error", json["ref_msg"]);
dialogReferences.dialogDiv.dialog({
buttons: {
"Accept" : function() {
$( this ).remove();
}
}
});
}
/* References were extracted */
else {
addContentToDialog(dialogReferences, textmarc, "Do you want to apply the following references?");
dialogReferences.dialogDiv.dialog({
title: "Apply references",
buttons: {
"Apply references": function() {
/* Update global record with the updated version */
gRecord = bibrecord;
/* Update cache in the server to have the updated record */
createReq({recID: gRecID, recXML: xmlrecord, requestType: 'updateCacheRef'});
/* Redraw whole content table and enable submit button */
$('#bibEditTable').remove();
var unmarked_tags = getUnmarkedTags();
displayRecord();
setUnmarkedTags(unmarked_tags);
activateSubmitButton();
$( this ).remove();
},
Cancel: function() {
$( this ).remove();
}
}
});
}
}
function request_extract_from_url(url) {
/* create a request to extract references from the given URL
return: promise object to be resolved when request completes
*/
var requestExtractPromise = new $.Deferred();
createReq({ recID: gRecID,
url: url,
requestType: 'refextracturl'},
function(json) { requestExtractPromise.resolve(json); });
return requestExtractPromise;
}
function request_extract_from_text(txt) {
/* create a request to extract references from the given text
return: promise object to be resolved when request completes
*/
var requestExtractPromise = new $.Deferred();
createReq({ recID: gRecID,
requestType: 'refextract',
txt: txt },
function(json) { requestExtractPromise.resolve(json); });
return requestExtractPromise;
}
function request_extract_from_pdf() {
/* create a request to extract references from the PDF attached to the
record
return: promise object to be resolved when request completes
*/
var requestExtractPromise = new $.Deferred();
createReq({ recID: gRecID,
requestType: 'refextract'},
function(json) { requestExtractPromise.resolve(json); });
return requestExtractPromise;
}
function onRefExtractClick() {
/*
* Handle click on refextract from PDF button
*
*/
save_changes().done(function() {
var loading_title = "Extracting references from PDF";
updateDialogLoading(loading_title);
var extract_from_pdf_promise = request_extract_from_pdf();
extract_from_pdf_promise.done(updateDialogRefextractResult);
});
}
function onRefExtractURLClick() {
/*
* Handle click on refextract from URL button
*
*/
save_changes().done(function() {
var dialogContent = '<input type="text" id="input_extract_url" class="bibedit_input" placeholder="URL to extract references">';
dialogReferences = createDialog("Extract references from URL", dialogContent, 200, 500);
dialogReferences.contentParagraph.addClass('dialog-box-centered-no-margin');
dialogReferences.dialogDiv.dialog({
buttons: {
"Extract references": function() {
url = $("#input_extract_url").val();
if (url === "") {
return;
}
var loading_title = "Extracting references from URL";
updateDialogLoading(loading_title);
var extract_from_url_promise = request_extract_from_url(url);
extract_from_url_promise.done(updateDialogRefextractResult);
},
Cancel: function() {
$( this ).remove();
}
}});
});
}
function onRefExtractFreeTextClick() {
/*
* Handler for free text refextract button. Allows to paste references
* and process them using refextract on the server side.
*/
save_changes().done(function() {
/* Create the modal dialog that will contain the references */
var dialogContent = "Paste your references:<br/><textarea id='reffreetext' class='bibedit_input'></textarea>"
dialogReferences = createDialog("Paste references", dialogContent, 750, 700);
dialogReferences.dialogDiv.dialog({
buttons: {
"Extract references": function() {
var textReferences = $('#reffreetext').val();
if (textReferences === "") {
return;
}
var loading_title = "Extracting references from text";
updateDialogLoading(loading_title);
var extract_from_text_promise = request_extract_from_text(textReferences);
extract_from_text_promise.done(updateDialogRefextractResult);
},
Cancel: function() {
$( this ).remove();
}
}
});
});
}
/* Public methods */
return {
onRefExtractURLClick: onRefExtractURLClick,
onRefExtractFreeTextClick: onRefExtractFreeTextClick,
onRefExtractClick: onRefExtractClick
};
})(); | jmartinm/invenio | modules/bibedit/lib/bibedit_refextract.js | JavaScript | gpl-2.0 | 6,442 |
Fixes #{issue-number}.
### Changes proposed in this pull request
-
-
-
| modemlooper/taskbot | vendors/CMB2/.github/PULL_REQUEST_TEMPLATE.md | Markdown | gpl-2.0 | 82 |
<?php
/**
* Parse and evaluate a plural rule.
*
* http://unicode.org/reports/tr35/#Language_Plural_Rules
*
* @author Niklas Laxstrom, Tim Starling
*
* @copyright Copyright © 2010-2012, Niklas Laxström
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
* @file
* @since 1.20
*/
class CLDRPluralRuleEvaluator {
/**
* Evaluate a number against a set of plural rules. If a rule passes,
* return the index of plural rule.
*
* @param int The number to be evaluated against the rules
* @param array The associative array of plural rules in pluralform => rule format.
* @return int The index of the plural form which passed the evaluation
*/
public static function evaluate( $number, array $rules ) {
$rules = self::compile( $rules );
return self::evaluateCompiled( $number, $rules );
}
/**
* Convert a set of rules to a compiled form which is optimised for
* fast evaluation. The result will be an array of strings, and may be cached.
*
* @param $rules The rules to compile
* @return An array of compile rules.
*/
public static function compile( array $rules ) {
// We can't use array_map() for this because it generates a warning if
// there is an exception.
foreach ( $rules as &$rule ) {
$rule = CLDRPluralRuleConverter::convert( $rule );
}
return $rules;
}
/**
* Evaluate a compiled set of rules returned by compile(). Do not allow
* the user to edit the compiled form, or else PHP errors may result.
*/
public static function evaluateCompiled( $number, array $rules ) {
// The compiled form is RPN, with tokens strictly delimited by
// spaces, so this is a simple RPN evaluator.
foreach ( $rules as $i => $rule ) {
$stack = array();
$zero = ord( '0' );
$nine = ord( '9' );
foreach ( StringUtils::explode( ' ', $rule ) as $token ) {
$ord = ord( $token );
if ( $token === 'n' ) {
$stack[] = $number;
} elseif ( $ord >= $zero && $ord <= $nine ) {
$stack[] = intval( $token );
} else {
$right = array_pop( $stack );
$left = array_pop( $stack );
$result = self::doOperation( $token, $left, $right );
$stack[] = $result;
}
}
if ( $stack[0] ) {
return $i;
}
}
// None of the provided rules match. The number belongs to caregory
// 'other' which comes last.
return count( $rules );
}
/**
* Do a single operation
*
* @param $token string The token string
* @param $left The left operand. If it is an object, its state may be destroyed.
* @param $right The right operand
* @return mixed
*/
private static function doOperation( $token, $left, $right ) {
if ( in_array( $token, array( 'in', 'not-in', 'within', 'not-within' ) ) ) {
if ( !($right instanceof CLDRPluralRuleEvaluator_Range ) ) {
$right = new CLDRPluralRuleEvaluator_Range( $right );
}
}
switch ( $token ) {
case 'or':
return $left || $right;
case 'and':
return $left && $right;
case 'is':
return $left == $right;
case 'is-not':
return $left != $right;
case 'in':
return $right->isNumberIn( $left );
case 'not-in':
return !$right->isNumberIn( $left );
case 'within':
return $right->isNumberWithin( $left );
case 'not-within':
return !$right->isNumberWithin( $left );
case 'mod':
if ( is_int( $left ) ) {
return (int) fmod( $left, $right );
}
return fmod( $left, $right );
case ',':
if ( $left instanceof CLDRPluralRuleEvaluator_Range ) {
$range = $left;
} else {
$range = new CLDRPluralRuleEvaluator_Range( $left );
}
$range->add( $right );
return $range;
case '..':
return new CLDRPluralRuleEvaluator_Range( $left, $right );
default:
throw new CLDRPluralRuleError( "Invalid RPN token" );
}
}
}
/**
* Evaluator helper class representing a range list.
*/
class CLDRPluralRuleEvaluator_Range {
var $parts = array();
function __construct( $start, $end = false ) {
if ( $end === false ) {
$this->parts[] = $start;
} else {
$this->parts[] = array( $start, $end );
}
}
/**
* Determine if the given number is inside the range. If $integerConstraint
* is true, the number must additionally be an integer if it is to match
* any interval part.
*/
function isNumberIn( $number, $integerConstraint = true ) {
foreach ( $this->parts as $part ) {
if ( is_array( $part ) ) {
if ( ( !$integerConstraint || floor( $number ) === (float)$number )
&& $number >= $part[0] && $number <= $part[1] )
{
return true;
}
} else {
if ( $number == $part ) {
return true;
}
}
}
return false;
}
/**
* Readable alias for isNumberIn( $number, false ), and the implementation
* of the "within" operator.
*/
function isNumberWithin( $number ) {
return $this->isNumberIn( $number, false );
}
/**
* Add another part to this range. The supplied new part may either be a
* range object itself, or a single number.
*/
function add( $other ) {
if ( $other instanceof self ) {
$this->parts = array_merge( $this->parts, $other->parts );
} else {
$this->parts[] = $other;
}
}
/**
* For debugging
*/
function __toString() {
$s = 'Range(';
foreach ( $this->parts as $i => $part ) {
if ( $i ) {
$s .= ', ';
}
if ( is_array( $part ) ) {
$s .= $part[0] . '..' . $part[1];
} else {
$s .= $part;
}
}
$s .= ')';
return $s;
}
}
/**
* Helper class for converting rules to reverse polish notation (RPN).
*/
class CLDRPluralRuleConverter {
var $rule, $pos, $end;
var $operators = array();
var $operands = array();
/**
* Precedence levels. Note that there's no need to worry about associativity
* for the level 4 operators, since they return boolean and don't accept
* boolean inputs.
*/
static $precedence = array(
'or' => 2,
'and' => 3,
'is' => 4,
'is-not' => 4,
'in' => 4,
'not-in' => 4,
'within' => 4,
'not-within' => 4,
'mod' => 5,
',' => 6,
'..' => 7,
);
/**
* A character list defining whitespace, for use in strspn() etc.
*/
const WHITESPACE_CLASS = " \t\r\n";
/**
* Same for digits. Note that the grammar given in UTS #35 doesn't allow
* negative numbers or decimals.
*/
const NUMBER_CLASS = '0123456789';
/**
* An anchored regular expression which matches a word at the current offset.
*/
const WORD_REGEX = '/[a-zA-Z]+/A';
/**
* Convert a rule to RPN. This is the only public entry point.
*/
public static function convert( $rule ) {
$parser = new self( $rule );
return $parser->doConvert();
}
/**
* Private constructor.
*/
protected function __construct( $rule ) {
$this->rule = $rule;
$this->pos = 0;
$this->end = strlen( $rule );
}
/**
* Do the operation.
*/
protected function doConvert() {
$expectOperator = true;
// Iterate through all tokens, saving the operators and operands to a
// stack per Dijkstra's shunting yard algorithm.
while ( false !== ( $token = $this->nextToken() ) ) {
// In this grammar, there are only binary operators, so every valid
// rule string will alternate between operator and operand tokens.
$expectOperator = !$expectOperator;
if ( $token instanceof CLDRPluralRuleConverter_Expression ) {
// Operand
if ( $expectOperator ) {
$token->error( 'unexpected operand' );
}
$this->operands[] = $token;
continue;
} else {
// Operator
if ( !$expectOperator ) {
$token->error( 'unexpected operator' );
}
// Resolve higher precedence levels
$lastOp = end( $this->operators );
while ( $lastOp && self::$precedence[$token->name] <= self::$precedence[$lastOp->name] ) {
$this->doOperation( $lastOp, $this->operands );
array_pop( $this->operators );
$lastOp = end( $this->operators );
}
$this->operators[] = $token;
}
}
// Finish off the stack
while ( $op = array_pop( $this->operators ) ) {
$this->doOperation( $op, $this->operands );
}
// Make sure the result is sane. The first case is possible for an empty
// string input, the second should be unreachable.
if ( !count( $this->operands ) ) {
$this->error( 'condition expected' );
} elseif ( count( $this->operands ) > 1 ) {
$this->error( 'missing operator or too many operands' );
}
$value = $this->operands[0];
if ( $value->type !== 'boolean' ) {
$this->error( 'the result must have a boolean type' );
}
return $this->operands[0]->rpn;
}
/**
* Fetch the next token from the input string. Return it as a
* CLDRPluralRuleConverter_Fragment object.
*/
protected function nextToken() {
if ( $this->pos >= $this->end ) {
return false;
}
// Whitespace
$length = strspn( $this->rule, self::WHITESPACE_CLASS, $this->pos );
$this->pos += $length;
if ( $this->pos >= $this->end ) {
return false;
}
// Number
$length = strspn( $this->rule, self::NUMBER_CLASS, $this->pos );
if ( $length !== 0 ) {
$token = $this->newNumber( substr( $this->rule, $this->pos, $length ), $this->pos );
$this->pos += $length;
return $token;
}
// Comma
if ( $this->rule[$this->pos] === ',' ) {
$token = $this->newOperator( ',', $this->pos, 1 );
$this->pos ++;
return $token;
}
// Dot dot
if ( substr( $this->rule, $this->pos, 2 ) === '..' ) {
$token = $this->newOperator( '..', $this->pos, 2 );
$this->pos += 2;
return $token;
}
// Word
if ( !preg_match( self::WORD_REGEX, $this->rule, $m, 0, $this->pos ) ) {
$this->error( 'unexpected character "' . $this->rule[$this->pos] . '"' );
}
$word1 = strtolower( $m[0] );
$word2 = '';
$nextTokenPos = $this->pos + strlen( $word1 );
if ( $word1 === 'not' || $word1 === 'is' ) {
// Look ahead one word
$nextTokenPos += strspn( $this->rule, self::WHITESPACE_CLASS, $nextTokenPos );
if ( $nextTokenPos < $this->end
&& preg_match( self::WORD_REGEX, $this->rule, $m, 0, $nextTokenPos ) )
{
$word2 = strtolower( $m[0] );
$nextTokenPos += strlen( $word2 );
}
}
// Two-word operators like "is not" take precedence over single-word operators like "is"
if ( $word2 !== '' ) {
$bothWords = "{$word1}-{$word2}";
if ( isset( self::$precedence[$bothWords] ) ) {
$token = $this->newOperator( $bothWords, $this->pos, $nextTokenPos - $this->pos );
$this->pos = $nextTokenPos;
return $token;
}
}
// Single-word operators
if ( isset( self::$precedence[$word1] ) ) {
$token = $this->newOperator( $word1, $this->pos, strlen( $word1 ) );
$this->pos += strlen( $word1 );
return $token;
}
// The special numerical keyword "n"
if ( $word1 === 'n' ) {
$token = $this->newNumber( 'n', $this->pos );
$this->pos ++;
return $token;
}
$this->error( 'unrecognised word' );
}
/**
* For the binary operator $op, pop its operands off the stack and push
* a fragment with rpn and type members describing the result of that
* operation.
*/
protected function doOperation( $op ) {
if ( count( $this->operands ) < 2 ) {
$op->error( 'missing operand' );
}
$right = array_pop( $this->operands );
$left = array_pop( $this->operands );
$result = $op->operate( $left, $right );
$this->operands[] = $result;
}
/**
* Create a numerical expression object
*/
protected function newNumber( $text, $pos ) {
return new CLDRPluralRuleConverter_Expression( $this, 'number', $text, $pos, strlen( $text ) );
}
/**
* Create a binary operator
*/
protected function newOperator( $type, $pos, $length ) {
return new CLDRPluralRuleConverter_Operator( $this, $type, $pos, $length );
}
/**
* Throw an error
*/
protected function error( $message ) {
throw new CLDRPluralRuleError( $message );
}
}
/**
* Helper for CLDRPluralRuleConverter.
* The base class for operators and expressions, describing a region of the input string.
*/
class CLDRPluralRuleConverter_Fragment {
var $parser, $pos, $length, $end;
function __construct( $parser, $pos, $length ) {
$this->parser = $parser;
$this->pos = $pos;
$this->length = $length;
$this->end = $pos + $length;
}
public function error( $message ) {
$text = $this->getText();
throw new CLDRPluralRuleError( "$message at position " . ( $this->pos + 1 ) . ": \"$text\"" );
}
public function getText() {
return substr( $this->parser->rule, $this->pos, $this->length );
}
}
/**
* Helper for CLDRPluralRuleConverter.
* An expression object, representing a region of the input string (for error
* messages), the RPN notation used to evaluate it, and the result type for
* validation.
*/
class CLDRPluralRuleConverter_Expression extends CLDRPluralRuleConverter_Fragment {
var $type, $rpn;
function __construct( $parser, $type, $rpn, $pos, $length ) {
parent::__construct( $parser, $pos, $length );
$this->type = $type;
$this->rpn = $rpn;
}
public function isType( $type ) {
if ( $type === 'range' && ( $this->type === 'range' || $this->type === 'number' ) ) {
return true;
}
if ( $type === $this->type ) {
return true;
}
return false;
}
}
/**
* Helper for CLDRPluralRuleConverter.
* An operator object, representing a region of the input string (for error
* messages), and the binary operator at that location.
*/
class CLDRPluralRuleConverter_Operator extends CLDRPluralRuleConverter_Fragment {
var $name;
/**
* Each op type has three characters: left operand type, right operand type and result type
*
* b = boolean
* n = number
* r = range
*
* A number is a kind of range.
*/
static $opTypes = array(
'or' => 'bbb',
'and' => 'bbb',
'is' => 'nnb',
'is-not' => 'nnb',
'in' => 'nrb',
'not-in' => 'nrb',
'within' => 'nrb',
'not-within' => 'nrb',
'mod' => 'nnn',
',' => 'rrr',
'..' => 'nnr',
);
/**
* Map converting from the abbrevation to the full form.
*/
static $typeSpecMap = array(
'b' => 'boolean',
'n' => 'number',
'r' => 'range',
);
function __construct( $parser, $name, $pos, $length ) {
parent::__construct( $parser, $pos, $length );
$this->name = $name;
}
public function operate( $left, $right ) {
$typeSpec = self::$opTypes[$this->name];
$leftType = self::$typeSpecMap[$typeSpec[0]];
$rightType = self::$typeSpecMap[$typeSpec[1]];
$resultType = self::$typeSpecMap[$typeSpec[2]];
$start = min( $this->pos, $left->pos, $right->pos );
$end = max( $this->end, $left->end, $right->end );
$length = $end - $start;
$newExpr = new CLDRPluralRuleConverter_Expression( $this->parser, $resultType,
"{$left->rpn} {$right->rpn} {$this->name}",
$start, $length );
if ( !$left->isType( $leftType ) ) {
$newExpr->error( "invalid type for left operand: expected $leftType, got {$left->type}" );
}
if ( !$right->isType( $rightType ) ) {
$newExpr->error( "invalid type for right operand: expected $rightType, got {$right->type}" );
}
return $newExpr;
}
}
/**
* The exception class for all the classes in this file. This will be thrown
* back to the caller if there is any validation error.
*/
class CLDRPluralRuleError extends MWException {
function __construct( $message ) {
parent::__construct( 'CLDR plural rule error: ' . $message );
}
}
| hacklabcbba/wiki | languages/utils/CLDRPluralRuleEvaluator.php | PHP | gpl-2.0 | 15,203 |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8077504
* @summary Unsafe load can loose control dependency and cause crash
* @run main/othervm -XX:-BackgroundCompilation -XX:-UseOnStackReplacement TestUnsafeLoadControl
*
*/
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class TestUnsafeLoadControl {
private static final Unsafe UNSAFE;
static {
try {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
UNSAFE = (Unsafe) unsafeField.get(null);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
static int val;
static void test1(int[] a, boolean[] flags, boolean flag, long j) {
for (int i = 0; i < 10; i++) {
if (flags[i]) {
if (flag) {
long address = (j << 2) + UNSAFE.ARRAY_INT_BASE_OFFSET;
int v = UNSAFE.getInt(a, address);
val = v;
}
}
}
}
static int test2(int[] a, boolean[] flags, boolean flag, long j) {
int sum = 0;
for (int i = 0; i < 10; i++) {
if (flags[i]) {
if (flag) {
long address = (j << 2) + UNSAFE.ARRAY_INT_BASE_OFFSET;
int v = UNSAFE.getInt(a, address);
if (v == 0) {
sum++;
}
}
}
}
return sum;
}
static public void main(String[] args) {
boolean[] flags = new boolean[10];
for (int i = 0; i < flags.length; i++) {
flags[i] = true;
}
int[] array = new int[10];
for (int i = 0; i < 20000; i++) {
test1(array, flags, true, 0);
}
for (int i = 0; i < flags.length; i++) {
flags[i] = false;
}
test1(array, flags, true, Long.MAX_VALUE/4);
for (int i = 0; i < flags.length; i++) {
flags[i] = true;
}
for (int i = 0; i < 20000; i++) {
test2(array, flags, true, 0);
}
for (int i = 0; i < flags.length; i++) {
flags[i] = false;
}
test2(array, flags, true, Long.MAX_VALUE/4);
}
}
| apurtell/jdk8u-hotspot | test/compiler/unsafe/TestUnsafeLoadControl.java | Java | gpl-2.0 | 3,332 |
#ifndef _LINUX_MODULE_H
#define _LINUX_MODULE_H
/*
* Dynamic loading of modules into the kernel.
*
* Rewritten by Richard Henderson <[email protected]> Dec 1996
* Rewritten again by Rusty Russell, 2002
*/
#include <linux/list.h>
#include <linux/stat.h>
#include <linux/compiler.h>
#include <linux/cache.h>
#include <linux/kmod.h>
#include <linux/elf.h>
#include <linux/stringify.h>
#include <linux/kobject.h>
#include <linux/moduleparam.h>
#include <linux/tracepoint.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <asm/module.h>
/* In stripped ARM and x86-64 modules, ~ is surprisingly rare. */
#define MODULE_SIG_STRING "~Module signature appended~\n"
/* Not Yet Implemented */
#define MODULE_SUPPORTED_DEVICE(name)
#define MODULE_NAME_LEN MAX_PARAM_PREFIX_LEN
struct modversion_info
{
unsigned long crc;
char name[MODULE_NAME_LEN];
};
struct module;
struct module_kobject {
struct kobject kobj;
struct module *mod;
struct kobject *drivers_dir;
struct module_param_attrs *mp;
};
struct module_attribute {
struct attribute attr;
ssize_t (*show)(struct module_attribute *, struct module_kobject *,
char *);
ssize_t (*store)(struct module_attribute *, struct module_kobject *,
const char *, size_t count);
void (*setup)(struct module *, const char *);
int (*test)(struct module *);
void (*free)(struct module *);
};
struct module_version_attribute {
struct module_attribute mattr;
const char *module_name;
const char *version;
} __attribute__ ((__aligned__(sizeof(void *))));
extern ssize_t __modver_version_show(struct module_attribute *,
struct module_kobject *, char *);
extern struct module_attribute module_uevent;
/* These are either module local, or the kernel's dummy ones. */
extern int init_module(void);
extern void cleanup_module(void);
/* Archs provide a method of finding the correct exception table. */
struct exception_table_entry;
const struct exception_table_entry *
search_extable(const struct exception_table_entry *first,
const struct exception_table_entry *last,
unsigned long value);
void sort_extable(struct exception_table_entry *start,
struct exception_table_entry *finish);
void sort_main_extable(void);
void trim_init_extable(struct module *m);
#ifdef MODULE
#define MODULE_GENERIC_TABLE(gtype,name) \
extern const struct gtype##_id __mod_##gtype##_table \
__attribute__ ((unused, alias(__stringify(name))))
#else /* !MODULE */
#define MODULE_GENERIC_TABLE(gtype,name)
#endif
/* Generic info of form tag = "info" */
#define MODULE_INFO(tag, info) __MODULE_INFO(tag, tag, info)
/* For userspace: you can also call me... */
#define MODULE_ALIAS(_alias) MODULE_INFO(alias, _alias)
/*
* The following license idents are currently accepted as indicating free
* software modules
*
* "GPL" [GNU Public License v2 or later]
* "GPL v2" [GNU Public License v2]
* "GPL and additional rights" [GNU Public License v2 rights and more]
* "Dual BSD/GPL" [GNU Public License v2
* or BSD license choice]
* "Dual MIT/GPL" [GNU Public License v2
* or MIT license choice]
* "Dual MPL/GPL" [GNU Public License v2
* or Mozilla license choice]
*
* The following other idents are available
*
* "Proprietary" [Non free products]
*
* There are dual licensed components, but when running with Linux it is the
* GPL that is relevant so this is a non issue. Similarly LGPL linked with GPL
* is a GPL combined work.
*
* This exists for several reasons
* 1. So modinfo can show license info for users wanting to vet their setup
* is free
* 2. So the community can ignore bug reports including proprietary modules
* 3. So vendors can do likewise based on their own policies
*/
#define MODULE_LICENSE(_license) MODULE_INFO(license, _license)
/*
* Author(s), use "Name <email>" or just "Name", for multiple
* authors use multiple MODULE_AUTHOR() statements/lines.
*/
#define MODULE_AUTHOR(_author) MODULE_INFO(author, _author)
/* What your module does. */
#define MODULE_DESCRIPTION(_description) MODULE_INFO(description, _description)
#define MODULE_DEVICE_TABLE(type,name) \
MODULE_GENERIC_TABLE(type##_device,name)
/* Version of form [<epoch>:]<version>[-<extra-version>].
Or for CVS/RCS ID version, everything but the number is stripped.
<epoch>: A (small) unsigned integer which allows you to start versions
anew. If not mentioned, it's zero. eg. "2:1.0" is after
"1:2.0".
<version>: The <version> may contain only alphanumerics and the
character `.'. Ordered by numeric sort for numeric parts,
ascii sort for ascii parts (as per RPM or DEB algorithm).
<extraversion>: Like <version>, but inserted for local
customizations, eg "rh3" or "rusty1".
Using this automatically adds a checksum of the .c files and the
local headers in "srcversion".
*/
#if defined(MODULE) || !defined(CONFIG_SYSFS)
#define MODULE_VERSION(_version) MODULE_INFO(version, _version)
#else
#define MODULE_VERSION(_version) \
static struct module_version_attribute ___modver_attr = { \
.mattr = { \
.attr = { \
.name = "version", \
.mode = S_IRUGO, \
}, \
.show = __modver_version_show, \
}, \
.module_name = KBUILD_MODNAME, \
.version = _version, \
}; \
static const struct module_version_attribute \
__used __attribute__ ((__section__ ("__modver"))) \
* __moduleparam_const __modver_attr = &___modver_attr
#endif
/* Optional firmware file (or files) needed by the module
* format is simply firmware file name. Multiple firmware
* files require multiple MODULE_FIRMWARE() specifiers */
#define MODULE_FIRMWARE(_firmware) MODULE_INFO(firmware, _firmware)
/* Given an address, look for it in the exception tables */
const struct exception_table_entry *search_exception_tables(unsigned long add);
struct notifier_block;
#ifdef CONFIG_MODULES
extern int modules_disabled; /* for sysctl */
/* Get/put a kernel symbol (calls must be symmetric) */
void *__symbol_get(const char *symbol);
void *__symbol_get_gpl(const char *symbol);
#define symbol_get(x) ((typeof(&x))(__symbol_get(VMLINUX_SYMBOL_STR(x))))
/* modules using other modules: kdb wants to see this. */
struct module_use {
struct list_head source_list;
struct list_head target_list;
struct module *source, *target;
};
enum module_state {
MODULE_STATE_LIVE, /* Normal state. */
MODULE_STATE_COMING, /* Full formed, running module_init. */
MODULE_STATE_GOING, /* Going away. */
MODULE_STATE_UNFORMED, /* Still setting it up. */
};
/**
* struct module_ref - per cpu module reference counts
* @incs: number of module get on this cpu
* @decs: number of module put on this cpu
*
* We force an alignment on 8 or 16 bytes, so that alloc_percpu()
* put @incs/@decs in same cache line, with no extra memory cost,
* since alloc_percpu() is fine grained.
*/
struct module_ref {
unsigned long incs;
unsigned long decs;
} __attribute((aligned(2 * sizeof(unsigned long))));
struct mod_kallsyms {
Elf_Sym *symtab;
unsigned int num_symtab;
char *strtab;
};
struct module
{
enum module_state state;
/* Member of list of modules */
struct list_head list;
/* Unique handle for this module */
char name[MODULE_NAME_LEN];
/* Sysfs stuff. */
struct module_kobject mkobj;
struct module_attribute *modinfo_attrs;
const char *version;
const char *srcversion;
struct kobject *holders_dir;
/* Exported symbols */
const struct kernel_symbol *syms;
const unsigned long *crcs;
unsigned int num_syms;
/* Kernel parameters. */
struct kernel_param *kp;
unsigned int num_kp;
/* GPL-only exported symbols. */
unsigned int num_gpl_syms;
const struct kernel_symbol *gpl_syms;
const unsigned long *gpl_crcs;
#ifdef CONFIG_UNUSED_SYMBOLS
/* unused exported symbols. */
const struct kernel_symbol *unused_syms;
const unsigned long *unused_crcs;
unsigned int num_unused_syms;
/* GPL-only, unused exported symbols. */
unsigned int num_unused_gpl_syms;
const struct kernel_symbol *unused_gpl_syms;
const unsigned long *unused_gpl_crcs;
#endif
#ifdef CONFIG_MODULE_SIG
/* Signature was verified. */
bool sig_ok;
#endif
/* symbols that will be GPL-only in the near future. */
const struct kernel_symbol *gpl_future_syms;
const unsigned long *gpl_future_crcs;
unsigned int num_gpl_future_syms;
/* Exception table */
unsigned int num_exentries;
struct exception_table_entry *extable;
/* Startup function. */
int (*init)(void);
/* If this is non-NULL, vfree after init() returns */
void *module_init;
/* Here is the actual code + data, vfree'd on unload. */
void *module_core;
/* Here are the sizes of the init and core sections */
unsigned int init_size, core_size;
/* The size of the executable code in each section. */
unsigned int init_text_size, core_text_size;
/* Size of RO sections of the module (text+rodata) */
unsigned int init_ro_size, core_ro_size;
/* Arch-specific module values */
struct mod_arch_specific arch;
unsigned int taints; /* same bits as kernel:tainted */
#ifdef CONFIG_GENERIC_BUG
/* Support for BUG */
unsigned num_bugs;
struct list_head bug_list;
struct bug_entry *bug_table;
#endif
#ifdef CONFIG_KALLSYMS
/* Protected by RCU and/or module_mutex: use rcu_dereference() */
struct mod_kallsyms *kallsyms;
struct mod_kallsyms core_kallsyms;
/* Section attributes */
struct module_sect_attrs *sect_attrs;
/* Notes attributes */
struct module_notes_attrs *notes_attrs;
#endif
/* The command line arguments (may be mangled). People like
keeping pointers to this stuff */
char *args;
#ifdef CONFIG_SMP
/* Per-cpu data. */
void __percpu *percpu;
unsigned int percpu_size;
#endif
#ifdef CONFIG_TRACEPOINTS
unsigned int num_tracepoints;
struct tracepoint * const *tracepoints_ptrs;
#endif
#ifdef HAVE_JUMP_LABEL
struct jump_entry *jump_entries;
unsigned int num_jump_entries;
#endif
#ifdef CONFIG_TRACING
unsigned int num_trace_bprintk_fmt;
const char **trace_bprintk_fmt_start;
#endif
#ifdef CONFIG_EVENT_TRACING
struct ftrace_event_call **trace_events;
unsigned int num_trace_events;
#endif
#ifdef CONFIG_FTRACE_MCOUNT_RECORD
unsigned int num_ftrace_callsites;
unsigned long *ftrace_callsites;
#endif
#ifdef CONFIG_MODULE_UNLOAD
/* What modules depend on me? */
struct list_head source_list;
/* What modules do I depend on? */
struct list_head target_list;
/* Who is waiting for us to be unloaded */
struct task_struct *waiter;
/* Destruction function. */
void (*exit)(void);
struct module_ref __percpu *refptr;
#endif
#ifdef CONFIG_MODULE_EXTRA_COPY
void *raw_binary_ptr;
unsigned long raw_binary_size;
void *linked_binary_ptr;
unsigned long linked_binary_size;
#endif
#ifdef CONFIG_CONSTRUCTORS
/* Constructor functions. */
ctor_fn_t *ctors;
unsigned int num_ctors;
#endif
};
#ifndef MODULE_ARCH_INIT
#define MODULE_ARCH_INIT {}
#endif
extern struct mutex module_mutex;
/* FIXME: It'd be nice to isolate modules during init, too, so they
aren't used before they (may) fail. But presently too much code
(IDE & SCSI) require entry into the module during init.*/
static inline int module_is_live(struct module *mod)
{
return mod->state != MODULE_STATE_GOING;
}
struct module *__module_text_address(unsigned long addr);
struct module *__module_address(unsigned long addr);
bool is_module_address(unsigned long addr);
bool is_module_percpu_address(unsigned long addr);
bool is_module_text_address(unsigned long addr);
static inline int within_module_core(unsigned long addr, const struct module *mod)
{
return (unsigned long)mod->module_core <= addr &&
addr < (unsigned long)mod->module_core + mod->core_size;
}
static inline int within_module_init(unsigned long addr, const struct module *mod)
{
return (unsigned long)mod->module_init <= addr &&
addr < (unsigned long)mod->module_init + mod->init_size;
}
/* Search for module by name: must hold module_mutex. */
struct module *find_module(const char *name);
struct symsearch {
const struct kernel_symbol *start, *stop;
const unsigned long *crcs;
enum {
NOT_GPL_ONLY,
GPL_ONLY,
WILL_BE_GPL_ONLY,
} licence;
bool unused;
};
/* Search for an exported symbol by name. */
const struct kernel_symbol *find_symbol(const char *name,
struct module **owner,
const unsigned long **crc,
bool gplok,
bool warn);
/* Walk the exported symbol table */
bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
struct module *owner,
void *data), void *data);
/* Returns 0 and fills in value, defined and namebuf, or -ERANGE if
symnum out of range. */
int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
char *name, char *module_name, int *exported);
/* Look for this name: can be of form module:name. */
unsigned long module_kallsyms_lookup_name(const char *name);
int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
struct module *, unsigned long),
void *data);
extern void __module_put_and_exit(struct module *mod, long code)
__attribute__((noreturn));
#define module_put_and_exit(code) __module_put_and_exit(THIS_MODULE, code);
#ifdef CONFIG_MODULE_UNLOAD
unsigned long module_refcount(struct module *mod);
void __symbol_put(const char *symbol);
#define symbol_put(x) __symbol_put(VMLINUX_SYMBOL_STR(x))
void symbol_put_addr(void *addr);
/* Sometimes we know we already have a refcount, and it's easier not
to handle the error case (which only happens with rmmod --wait). */
extern void __module_get(struct module *module);
/* This is the Right Way to get a module: if it fails, it's being removed,
* so pretend it's not there. */
extern bool try_module_get(struct module *module);
extern void module_put(struct module *module);
#else /*!CONFIG_MODULE_UNLOAD*/
static inline int try_module_get(struct module *module)
{
return !module || module_is_live(module);
}
static inline void module_put(struct module *module)
{
}
static inline void __module_get(struct module *module)
{
}
#define symbol_put(x) do { } while(0)
#define symbol_put_addr(p) do { } while(0)
#endif /* CONFIG_MODULE_UNLOAD */
int ref_module(struct module *a, struct module *b);
/* This is a #define so the string doesn't get put in every .o file */
#define module_name(mod) \
({ \
struct module *__mod = (mod); \
__mod ? __mod->name : "kernel"; \
})
/* For kallsyms to ask for address resolution. namebuf should be at
* least KSYM_NAME_LEN long: a pointer to namebuf is returned if
* found, otherwise NULL. */
const char *module_address_lookup(unsigned long addr,
unsigned long *symbolsize,
unsigned long *offset,
char **modname,
char *namebuf);
int lookup_module_symbol_name(unsigned long addr, char *symname);
int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size, unsigned long *offset, char *modname, char *name);
/* For extable.c to search modules' exception tables. */
const struct exception_table_entry *search_module_extables(unsigned long addr);
int register_module_notifier(struct notifier_block * nb);
int unregister_module_notifier(struct notifier_block * nb);
extern void print_modules(void);
#else /* !CONFIG_MODULES... */
/* Given an address, look for it in the exception tables. */
static inline const struct exception_table_entry *
search_module_extables(unsigned long addr)
{
return NULL;
}
static inline struct module *__module_address(unsigned long addr)
{
return NULL;
}
static inline struct module *__module_text_address(unsigned long addr)
{
return NULL;
}
static inline bool is_module_address(unsigned long addr)
{
return false;
}
static inline bool is_module_percpu_address(unsigned long addr)
{
return false;
}
static inline bool is_module_text_address(unsigned long addr)
{
return false;
}
/* Get/put a kernel symbol (calls should be symmetric) */
#define symbol_get(x) ({ extern typeof(x) x __attribute__((weak)); &(x); })
#define symbol_put(x) do { } while(0)
#define symbol_put_addr(x) do { } while(0)
static inline void __module_get(struct module *module)
{
}
static inline int try_module_get(struct module *module)
{
return 1;
}
static inline void module_put(struct module *module)
{
}
#define module_name(mod) "kernel"
/* For kallsyms to ask for address resolution. NULL means not found. */
static inline const char *module_address_lookup(unsigned long addr,
unsigned long *symbolsize,
unsigned long *offset,
char **modname,
char *namebuf)
{
return NULL;
}
static inline int lookup_module_symbol_name(unsigned long addr, char *symname)
{
return -ERANGE;
}
static inline int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size, unsigned long *offset, char *modname, char *name)
{
return -ERANGE;
}
static inline int module_get_kallsym(unsigned int symnum, unsigned long *value,
char *type, char *name,
char *module_name, int *exported)
{
return -ERANGE;
}
static inline unsigned long module_kallsyms_lookup_name(const char *name)
{
return 0;
}
static inline int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
struct module *,
unsigned long),
void *data)
{
return 0;
}
static inline int register_module_notifier(struct notifier_block * nb)
{
/* no events will happen anyway, so this can always succeed */
return 0;
}
static inline int unregister_module_notifier(struct notifier_block * nb)
{
return 0;
}
#define module_put_and_exit(code) do_exit(code)
static inline void print_modules(void)
{
}
#endif /* CONFIG_MODULES */
#ifdef CONFIG_SYSFS
extern struct kset *module_kset;
extern struct kobj_type module_ktype;
extern int module_sysfs_initialized;
#endif /* CONFIG_SYSFS */
#define symbol_request(x) try_then_request_module(symbol_get(x), "symbol:" #x)
/* BELOW HERE ALL THESE ARE OBSOLETE AND WILL VANISH */
#define __MODULE_STRING(x) __stringify(x)
#ifdef CONFIG_DEBUG_SET_MODULE_RONX
extern void set_all_modules_text_rw(void);
extern void set_all_modules_text_ro(void);
#else
static inline void set_all_modules_text_rw(void) { }
static inline void set_all_modules_text_ro(void) { }
#endif
#ifdef CONFIG_GENERIC_BUG
void module_bug_finalize(const Elf_Ehdr *, const Elf_Shdr *,
struct module *);
void module_bug_cleanup(struct module *);
#else /* !CONFIG_GENERIC_BUG */
static inline void module_bug_finalize(const Elf_Ehdr *hdr,
const Elf_Shdr *sechdrs,
struct module *mod)
{
}
static inline void module_bug_cleanup(struct module *mod) {}
#endif /* CONFIG_GENERIC_BUG */
#endif /* _LINUX_MODULE_H */
| scanno/android_kernel_motorola_msm8992 | include/linux/module.h | C | gpl-2.0 | 18,582 |
#ifndef _ORC_RULE_H_
#define _ORC_RULE_H_
#include <orc/orcutils.h>
#include <orc/orclimits.h>
#include <orc/orcopcode.h>
ORC_BEGIN_DECLS
typedef struct _OrcRule OrcRule;
typedef struct _OrcRuleSet OrcRuleSet;
typedef void (*OrcRuleEmitFunc)(OrcCompiler *p, void *user, OrcInstruction *insn);
/**
* OrcRule:
*
* The OrcRule structure has no public members
*/
struct _OrcRule {
/*< private >*/
OrcRuleEmitFunc emit;
void *emit_user;
};
/**
* OrcRuleSet:
*
* The OrcRuleSet structure has no public members
*/
struct _OrcRuleSet {
/*< private >*/
int opcode_major;
int required_target_flags;
OrcRule *rules;
int n_rules;
};
OrcRuleSet * orc_rule_set_new (OrcOpcodeSet *opcode_set, OrcTarget *target,
unsigned int required_flags);
void orc_rule_register (OrcRuleSet *rule_set, const char *opcode_name,
OrcRuleEmitFunc emit, void *emit_user);
ORC_END_DECLS
#endif
| dulton/vlc-2.1.4.32.subproject-2013-update2 | win32/include/orc-0.4/orc/orcrule.h | C | gpl-2.0 | 905 |
<?php
/**
* @package Joomla.Administrator
* @subpackage Template.hathor
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');
JHtml::_('behavior.multiselect');
$user = JFactory::getUser();
$userId = $user->get('id');
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
?>
<form action="<?php echo JRoute::_('index.php?option=com_banners&view=clients'); ?>" method="post" name="adminForm" id="adminForm">
<?php if (!empty( $this->sidebar)) : ?>
<div id="j-sidebar-container" class="span2">
<?php echo $this->sidebar; ?>
</div>
<div id="j-main-container" class="span10">
<?php else : ?>
<div id="j-main-container">
<?php endif;?>
<fieldset id="filter-bar">
<legend class="element-invisible"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></legend>
<div class="filter-search">
<label class="filter-search-lbl" for="filter_search"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></label>
<input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" title="<?php echo JText::_('COM_BANNERS_SEARCH_IN_TITLE'); ?>" />
<button type="submit"><?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?></button>
<button type="button" onclick="document.getElementById('filter_search').value='';this.form.submit();"><?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?></button>
</div>
<div class="filter-select">
<label class="selectlabel" for="filter_state">
<?php echo JText::_('JOPTION_SELECT_PUBLISHED'); ?>
</label>
<select name="filter_state" id="filter_state">
<option value=""><?php echo JText::_('JOPTION_SELECT_PUBLISHED');?></option>
<?php echo JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), 'value', 'text', $this->state->get('filter.state'), true);?>
</select>
<button type="submit" id="filter-go">
<?php echo JText::_('JSUBMIT'); ?></button>
</div>
</fieldset>
<div class="clr"> </div>
<table class="adminlist">
<thead>
<tr>
<th class="checkmark-col">
<input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" />
</th>
<th>
<?php echo JHtml::_('grid.sort', 'COM_BANNERS_HEADING_CLIENT', 'name', $listDirn, $listOrder); ?>
</th>
<th class="width-30">
<?php echo JHtml::_('grid.sort', 'COM_BANNERS_HEADING_CONTACT', 'contact', $listDirn, $listOrder); ?>
</th>
<th class="nowrap state-col">
<?php echo JHtml::_('grid.sort', 'JSTATUS', 'state', $listDirn, $listOrder); ?>
</th>
<th class="width-5">
<?php echo JHtml::_('grid.sort', 'COM_BANNERS_HEADING_ACTIVE', 'nbanners', $listDirn, $listOrder); ?>
</th>
<th class="nowrap width-5">
<?php echo JText::_('COM_BANNERS_HEADING_METAKEYWORDS'); ?>
</th>
<th class="width-10">
<?php echo JText::_('COM_BANNERS_HEADING_PURCHASETYPE'); ?>
</th>
<th class="nowrap id-col">
<?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'id', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->items as $i => $item) :
$ordering = ($listOrder == 'ordering');
$canCreate = $user->authorise('core.create', 'com_banners');
$canEdit = $user->authorise('core.edit', 'com_banners');
$canCheckin = $user->authorise('core.manage', 'com_checkin') || $item->checked_out == $user->get('id') || $item->checked_out == 0;
$canChange = $user->authorise('core.edit.state', 'com_banners') && $canCheckin;
?>
<tr class="row<?php echo $i % 2; ?>">
<td class="center">
<?php echo JHtml::_('grid.id', $i, $item->id); ?>
</td>
<td>
<?php if ($item->checked_out) : ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'clients.', $canCheckin); ?>
<?php endif; ?>
<?php if ($canEdit) : ?>
<a href="<?php echo JRoute::_('index.php?option=com_banners&task=client.edit&id='.(int) $item->id); ?>">
<?php echo $this->escape($item->name); ?></a>
<?php else : ?>
<?php echo $this->escape($item->name); ?>
<?php endif; ?>
</td>
<td class="center">
<?php echo $item->contact;?>
</td>
<td class="center">
<?php echo JHtml::_('jgrid.published', $item->state, $i, 'clients.', $canChange);?>
</td>
<td class="center">
<?php echo $item->nbanners; ?>
</td>
<td>
<?php echo $item->metakey; ?>
</td>
<td class="center">
<?php if ($item->purchase_type < 0):?>
<?php echo JText::sprintf('COM_BANNERS_DEFAULT', JText::_('COM_BANNERS_FIELD_VALUE_'.$this->state->params->get('purchase_type')));?>
<?php else:?>
<?php echo JText::_('COM_BANNERS_FIELD_VALUE_'.$item->purchase_type);?>
<?php endif;?>
</td>
<td class="center">
<?php echo $item->id; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php echo $this->pagination->getListFooter(); ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" />
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
| IOC/joomla3 | administrator/templates/hathor/html/com_banners/clients/default.php | PHP | gpl-2.0 | 5,571 |
/*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2017-2020 Broadcom. All Rights Reserved. The term *
* “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. *
* Copyright (C) 2004-2013 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.broadcom.com *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of version 2 of the GNU General *
* Public License as published by the Free Software Foundation. *
* This program is distributed in the hope that it will be useful. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
#define FC_MAX_HOLD_RSCN 32 /* max number of deferred RSCNs */
#define FC_MAX_NS_RSP 64512 /* max size NameServer rsp */
#define FC_MAXLOOP 126 /* max devices supported on a fc loop */
#define LPFC_DISC_FLOGI_TMO 10 /* Discovery FLOGI ratov */
/* This is the protocol dependent definition for a Node List Entry.
* This is used by Fibre Channel protocol to support FCP.
*/
/* worker thread events */
enum lpfc_work_type {
LPFC_EVT_ONLINE,
LPFC_EVT_OFFLINE_PREP,
LPFC_EVT_OFFLINE,
LPFC_EVT_WARM_START,
LPFC_EVT_KILL,
LPFC_EVT_ELS_RETRY,
LPFC_EVT_DEV_LOSS,
LPFC_EVT_FASTPATH_MGMT_EVT,
LPFC_EVT_RESET_HBA,
LPFC_EVT_RECOVER_PORT
};
/* structure used to queue event to the discovery tasklet */
struct lpfc_work_evt {
struct list_head evt_listp;
void *evt_arg1;
void *evt_arg2;
enum lpfc_work_type evt;
};
struct lpfc_scsi_check_condition_event;
struct lpfc_scsi_varqueuedepth_event;
struct lpfc_scsi_event_header;
struct lpfc_fabric_event_header;
struct lpfc_fcprdchkerr_event;
/* structure used for sending events from fast path */
struct lpfc_fast_path_event {
struct lpfc_work_evt work_evt;
struct lpfc_vport *vport;
union {
struct lpfc_scsi_check_condition_event check_cond_evt;
struct lpfc_scsi_varqueuedepth_event queue_depth_evt;
struct lpfc_scsi_event_header scsi_evt;
struct lpfc_fabric_event_header fabric_evt;
struct lpfc_fcprdchkerr_event read_check_error;
} un;
};
#define LPFC_SLI4_MAX_XRI 1024 /* Used to make the ndlp's xri_bitmap */
#define XRI_BITMAP_ULONGS (LPFC_SLI4_MAX_XRI / BITS_PER_LONG)
struct lpfc_node_rrqs {
unsigned long xri_bitmap[XRI_BITMAP_ULONGS];
};
struct lpfc_nodelist {
struct list_head nlp_listp;
struct lpfc_name nlp_portname;
struct lpfc_name nlp_nodename;
spinlock_t lock; /* Node management lock */
uint32_t nlp_flag; /* entry flags */
uint32_t nlp_DID; /* FC D_ID of entry */
uint32_t nlp_last_elscmd; /* Last ELS cmd sent */
uint16_t nlp_type;
#define NLP_FC_NODE 0x1 /* entry is an FC node */
#define NLP_FABRIC 0x4 /* entry rep a Fabric entity */
#define NLP_FCP_TARGET 0x8 /* entry is an FCP target */
#define NLP_FCP_INITIATOR 0x10 /* entry is an FCP Initiator */
#define NLP_NVME_TARGET 0x20 /* entry is a NVME Target */
#define NLP_NVME_INITIATOR 0x40 /* entry is a NVME Initiator */
#define NLP_NVME_DISCOVERY 0x80 /* entry has NVME disc srvc */
uint16_t nlp_fc4_type; /* FC types node supports. */
/* Assigned from GID_FF, only
* FCP (0x8) and NVME (0x28)
* supported.
*/
#define NLP_FC4_NONE 0x0
#define NLP_FC4_FCP 0x1 /* FC4 Type FCP (value x8)) */
#define NLP_FC4_NVME 0x2 /* FC4 TYPE NVME (value x28) */
uint16_t nlp_rpi;
uint16_t nlp_state; /* state transition indicator */
uint16_t nlp_prev_state; /* state transition indicator */
uint16_t nlp_xri; /* output exchange id for RPI */
uint16_t nlp_sid; /* scsi id */
#define NLP_NO_SID 0xffff
uint16_t nlp_maxframe; /* Max RCV frame size */
uint8_t nlp_class_sup; /* Supported Classes */
uint8_t nlp_retry; /* used for ELS retries */
uint8_t nlp_fcp_info; /* class info, bits 0-3 */
#define NLP_FCP_2_DEVICE 0x10 /* FCP-2 device */
u8 nlp_nvme_info; /* NVME NSLER Support */
#define NLP_NVME_NSLER 0x1 /* NVME NSLER device */
struct timer_list nlp_delayfunc; /* Used for delayed ELS cmds */
struct lpfc_hba *phba;
struct fc_rport *rport; /* scsi_transport_fc port structure */
struct lpfc_nvme_rport *nrport; /* nvme transport rport struct. */
struct lpfc_vport *vport;
struct lpfc_work_evt els_retry_evt;
struct lpfc_work_evt dev_loss_evt;
struct lpfc_work_evt recovery_evt;
struct kref kref;
atomic_t cmd_pending;
uint32_t cmd_qdepth;
unsigned long last_change_time;
unsigned long *active_rrqs_xri_bitmap;
struct lpfc_scsicmd_bkt *lat_data; /* Latency data */
uint32_t fc4_prli_sent;
uint32_t fc4_xpt_flags;
#define NLP_WAIT_FOR_UNREG 0x1
#define SCSI_XPT_REGD 0x2
#define NVME_XPT_REGD 0x4
uint32_t nvme_fb_size; /* NVME target's supported byte cnt */
#define NVME_FB_BIT_SHIFT 9 /* PRLI Rsp first burst in 512B units. */
uint32_t nlp_defer_did;
};
struct lpfc_node_rrq {
struct list_head list;
uint16_t xritag;
uint16_t send_rrq;
uint16_t rxid;
uint32_t nlp_DID; /* FC D_ID of entry */
struct lpfc_vport *vport;
struct lpfc_nodelist *ndlp;
unsigned long rrq_stop_time;
};
#define lpfc_ndlp_check_qdepth(phba, ndlp) \
(ndlp->cmd_qdepth < phba->sli4_hba.max_cfg_param.max_xri)
/* Defines for nlp_flag (uint32) */
#define NLP_IGNR_REG_CMPL 0x00000001 /* Rcvd rscn before we cmpl reg login */
#define NLP_REG_LOGIN_SEND 0x00000002 /* sent reglogin to adapter */
#define NLP_RELEASE_RPI 0x00000004 /* Release RPI to free pool */
#define NLP_SUPPRESS_RSP 0x00000010 /* Remote NPort supports suppress rsp */
#define NLP_PLOGI_SND 0x00000020 /* sent PLOGI request for this entry */
#define NLP_PRLI_SND 0x00000040 /* sent PRLI request for this entry */
#define NLP_ADISC_SND 0x00000080 /* sent ADISC request for this entry */
#define NLP_LOGO_SND 0x00000100 /* sent LOGO request for this entry */
#define NLP_RNID_SND 0x00000400 /* sent RNID request for this entry */
#define NLP_ELS_SND_MASK 0x000007e0 /* sent ELS request for this entry */
#define NLP_NVMET_RECOV 0x00001000 /* NVMET auditing node for recovery. */
#define NLP_FCP_PRLI_RJT 0x00002000 /* Rport does not support FCP PRLI. */
#define NLP_UNREG_INP 0x00008000 /* UNREG_RPI cmd is in progress */
#define NLP_DROPPED 0x00010000 /* Init ref count has been dropped */
#define NLP_DELAY_TMO 0x00020000 /* delay timeout is running for node */
#define NLP_NPR_2B_DISC 0x00040000 /* node is included in num_disc_nodes */
#define NLP_RCV_PLOGI 0x00080000 /* Rcv'ed PLOGI from remote system */
#define NLP_LOGO_ACC 0x00100000 /* Process LOGO after ACC completes */
#define NLP_TGT_NO_SCSIID 0x00200000 /* good PRLI but no binding for scsid */
#define NLP_ISSUE_LOGO 0x00400000 /* waiting to issue a LOGO */
#define NLP_IN_DEV_LOSS 0x00800000 /* devloss in progress */
#define NLP_ACC_REGLOGIN 0x01000000 /* Issue Reg Login after successful
ACC */
#define NLP_NPR_ADISC 0x02000000 /* Issue ADISC when dq'ed from
NPR list */
#define NLP_RM_DFLT_RPI 0x04000000 /* need to remove leftover dflt RPI */
#define NLP_NODEV_REMOVE 0x08000000 /* Defer removal till discovery ends */
#define NLP_TARGET_REMOVE 0x10000000 /* Target remove in process */
#define NLP_SC_REQ 0x20000000 /* Target requires authentication */
#define NLP_FIRSTBURST 0x40000000 /* Target supports FirstBurst */
#define NLP_RPI_REGISTERED 0x80000000 /* nlp_rpi is valid */
/* There are 4 different double linked lists nodelist entries can reside on.
* The Port Login (PLOGI) list and Address Discovery (ADISC) list are used
* when Link Up discovery or Registered State Change Notification (RSCN)
* processing is needed. Each list holds the nodes that require a PLOGI or
* ADISC Extended Link Service (ELS) request. These lists keep track of the
* nodes affected by an RSCN, or a Link Up (Typically, all nodes are effected
* by Link Up) event. The unmapped_list contains all nodes that have
* successfully logged into at the Fibre Channel level. The
* mapped_list will contain all nodes that are mapped FCP targets.
*
* The bind list is a list of undiscovered (potentially non-existent) nodes
* that we have saved binding information on. This information is used when
* nodes transition from the unmapped to the mapped list.
*/
/* Defines for nlp_state */
#define NLP_STE_UNUSED_NODE 0x0 /* node is just allocated */
#define NLP_STE_PLOGI_ISSUE 0x1 /* PLOGI was sent to NL_PORT */
#define NLP_STE_ADISC_ISSUE 0x2 /* ADISC was sent to NL_PORT */
#define NLP_STE_REG_LOGIN_ISSUE 0x3 /* REG_LOGIN was issued for NL_PORT */
#define NLP_STE_PRLI_ISSUE 0x4 /* PRLI was sent to NL_PORT */
#define NLP_STE_LOGO_ISSUE 0x5 /* LOGO was sent to NL_PORT */
#define NLP_STE_UNMAPPED_NODE 0x6 /* PRLI completed from NL_PORT */
#define NLP_STE_MAPPED_NODE 0x7 /* Identified as a FCP Target */
#define NLP_STE_NPR_NODE 0x8 /* NPort disappeared */
#define NLP_STE_MAX_STATE 0x9
#define NLP_STE_FREED_NODE 0xff /* node entry was freed to MEM_NLP */
/* For UNUSED_NODE state, the node has just been allocated.
* For PLOGI_ISSUE and REG_LOGIN_ISSUE, the node is on
* the PLOGI list. For REG_LOGIN_COMPL, the node is taken off the PLOGI list
* and put on the unmapped list. For ADISC processing, the node is taken off
* the ADISC list and placed on either the mapped or unmapped list (depending
* on its previous state). Once on the unmapped list, a PRLI is issued and the
* state changed to PRLI_ISSUE. When the PRLI completion occurs, the state is
* changed to PRLI_COMPL. If the completion indicates a mapped
* node, the node is taken off the unmapped list. The binding list is checked
* for a valid binding, or a binding is automatically assigned. If binding
* assignment is unsuccessful, the node is left on the unmapped list. If
* binding assignment is successful, the associated binding list entry (if
* any) is removed, and the node is placed on the mapped list.
*/
/*
* For a Link Down, all nodes on the ADISC, PLOGI, unmapped or mapped
* lists will receive a DEVICE_RECOVERY event. If the linkdown or devloss timers
* expire, all effected nodes will receive a DEVICE_RM event.
*/
/*
* For a Link Up or RSCN, all nodes will move from the mapped / unmapped lists
* to either the ADISC or PLOGI list. After a Nameserver query or ALPA loopmap
* check, additional nodes may be added (DEVICE_ADD) or removed (DEVICE_RM) to /
* from the PLOGI or ADISC lists. Once the PLOGI and ADISC lists are populated,
* we will first process the ADISC list. 32 entries are processed initially and
* ADISC is initited for each one. Completions / Events for each node are
* funnelled thru the state machine. As each node finishes ADISC processing, it
* starts ADISC for any nodes waiting for ADISC processing. If no nodes are
* waiting, and the ADISC list count is identically 0, then we are done. For
* Link Up discovery, since all nodes on the PLOGI list are UNREG_LOGIN'ed, we
* can issue a CLEAR_LA and reenable Link Events. Next we will process the PLOGI
* list. 32 entries are processed initially and PLOGI is initited for each one.
* Completions / Events for each node are funnelled thru the state machine. As
* each node finishes PLOGI processing, it starts PLOGI for any nodes waiting
* for PLOGI processing. If no nodes are waiting, and the PLOGI list count is
* identically 0, then we are done. We have now completed discovery / RSCN
* handling. Upon completion, ALL nodes should be on either the mapped or
* unmapped lists.
*/
/* Defines for Node List Entry Events that could happen */
#define NLP_EVT_RCV_PLOGI 0x0 /* Rcv'd an ELS PLOGI command */
#define NLP_EVT_RCV_PRLI 0x1 /* Rcv'd an ELS PRLI command */
#define NLP_EVT_RCV_LOGO 0x2 /* Rcv'd an ELS LOGO command */
#define NLP_EVT_RCV_ADISC 0x3 /* Rcv'd an ELS ADISC command */
#define NLP_EVT_RCV_PDISC 0x4 /* Rcv'd an ELS PDISC command */
#define NLP_EVT_RCV_PRLO 0x5 /* Rcv'd an ELS PRLO command */
#define NLP_EVT_CMPL_PLOGI 0x6 /* Sent an ELS PLOGI command */
#define NLP_EVT_CMPL_PRLI 0x7 /* Sent an ELS PRLI command */
#define NLP_EVT_CMPL_LOGO 0x8 /* Sent an ELS LOGO command */
#define NLP_EVT_CMPL_ADISC 0x9 /* Sent an ELS ADISC command */
#define NLP_EVT_CMPL_REG_LOGIN 0xa /* REG_LOGIN mbox cmd completed */
#define NLP_EVT_DEVICE_RM 0xb /* Device not found in NS / ALPAmap */
#define NLP_EVT_DEVICE_RECOVERY 0xc /* Device existence unknown */
#define NLP_EVT_MAX_EVENT 0xd
#define NLP_EVT_NOTHING_PENDING 0xff
| GuillaumeSeren/linux | drivers/scsi/lpfc/lpfc_disc.h | C | gpl-2.0 | 13,615 |
/*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would 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 the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_dir2.h"
#include "xfs_trans.h"
#include "xfs_dmapi.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_alloc.h"
#include "xfs_btree.h"
#include "xfs_attr_sf.h"
#include "xfs_dir2_sf.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_error.h"
#include "xfs_rw.h"
#include "xfs_ioctl32.h"
#include <linux/dcache.h>
#include <linux/smp_lock.h>
static struct vm_operations_struct xfs_file_vm_ops;
#ifdef CONFIG_XFS_DMAPI
static struct vm_operations_struct xfs_dmapi_file_vm_ops;
#endif
STATIC_INLINE ssize_t
__xfs_file_read(
struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs,
int ioflags,
loff_t pos)
{
struct file *file = iocb->ki_filp;
bhv_vnode_t *vp = vn_from_inode(file->f_path.dentry->d_inode);
BUG_ON(iocb->ki_pos != pos);
if (unlikely(file->f_flags & O_DIRECT))
ioflags |= IO_ISDIRECT;
return bhv_vop_read(vp, iocb, iov, nr_segs, &iocb->ki_pos,
ioflags, NULL);
}
STATIC ssize_t
xfs_file_aio_read(
struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs,
loff_t pos)
{
return __xfs_file_read(iocb, iov, nr_segs, IO_ISAIO, pos);
}
STATIC ssize_t
xfs_file_aio_read_invis(
struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs,
loff_t pos)
{
return __xfs_file_read(iocb, iov, nr_segs, IO_ISAIO|IO_INVIS, pos);
}
STATIC_INLINE ssize_t
__xfs_file_write(
struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs,
int ioflags,
loff_t pos)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
bhv_vnode_t *vp = vn_from_inode(inode);
BUG_ON(iocb->ki_pos != pos);
if (unlikely(file->f_flags & O_DIRECT))
ioflags |= IO_ISDIRECT;
return bhv_vop_write(vp, iocb, iov, nr_segs, &iocb->ki_pos,
ioflags, NULL);
}
STATIC ssize_t
xfs_file_aio_write(
struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs,
loff_t pos)
{
return __xfs_file_write(iocb, iov, nr_segs, IO_ISAIO, pos);
}
STATIC ssize_t
xfs_file_aio_write_invis(
struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs,
loff_t pos)
{
return __xfs_file_write(iocb, iov, nr_segs, IO_ISAIO|IO_INVIS, pos);
}
STATIC ssize_t
xfs_file_splice_read(
struct file *infilp,
loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len,
unsigned int flags)
{
return bhv_vop_splice_read(vn_from_inode(infilp->f_path.dentry->d_inode),
infilp, ppos, pipe, len, flags, 0, NULL);
}
STATIC ssize_t
xfs_file_splice_read_invis(
struct file *infilp,
loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len,
unsigned int flags)
{
return bhv_vop_splice_read(vn_from_inode(infilp->f_path.dentry->d_inode),
infilp, ppos, pipe, len, flags, IO_INVIS,
NULL);
}
STATIC ssize_t
xfs_file_splice_write(
struct pipe_inode_info *pipe,
struct file *outfilp,
loff_t *ppos,
size_t len,
unsigned int flags)
{
return bhv_vop_splice_write(vn_from_inode(outfilp->f_path.dentry->d_inode),
pipe, outfilp, ppos, len, flags, 0, NULL);
}
STATIC ssize_t
xfs_file_splice_write_invis(
struct pipe_inode_info *pipe,
struct file *outfilp,
loff_t *ppos,
size_t len,
unsigned int flags)
{
return bhv_vop_splice_write(vn_from_inode(outfilp->f_path.dentry->d_inode),
pipe, outfilp, ppos, len, flags, IO_INVIS,
NULL);
}
STATIC int
xfs_file_open(
struct inode *inode,
struct file *filp)
{
if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
return -EFBIG;
return -bhv_vop_open(vn_from_inode(inode), NULL);
}
STATIC int
xfs_file_close(
struct file *filp,
fl_owner_t id)
{
return -bhv_vop_close(vn_from_inode(filp->f_path.dentry->d_inode), 0,
file_count(filp) > 1 ? L_FALSE : L_TRUE, NULL);
}
STATIC int
xfs_file_release(
struct inode *inode,
struct file *filp)
{
bhv_vnode_t *vp = vn_from_inode(inode);
if (vp)
return -bhv_vop_release(vp);
return 0;
}
STATIC int
xfs_file_fsync(
struct file *filp,
struct dentry *dentry,
int datasync)
{
bhv_vnode_t *vp = vn_from_inode(dentry->d_inode);
int flags = FSYNC_WAIT;
if (datasync)
flags |= FSYNC_DATA;
if (VN_TRUNC(vp))
VUNTRUNCATE(vp);
return -bhv_vop_fsync(vp, flags, NULL, (xfs_off_t)0, (xfs_off_t)-1);
}
#ifdef CONFIG_XFS_DMAPI
STATIC int
xfs_vm_fault(
struct vm_area_struct *vma,
struct vm_fault *vmf)
{
struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
bhv_vnode_t *vp = vn_from_inode(inode);
ASSERT_ALWAYS(vp->v_vfsp->vfs_flag & VFS_DMI);
if (XFS_SEND_MMAP(XFS_VFSTOM(vp->v_vfsp), vma, 0))
return VM_FAULT_SIGBUS;
return filemap_fault(vma, vmf);
}
#endif /* CONFIG_XFS_DMAPI */
STATIC int
xfs_file_readdir(
struct file *filp,
void *dirent,
filldir_t filldir)
{
int error = 0;
bhv_vnode_t *vp = vn_from_inode(filp->f_path.dentry->d_inode);
uio_t uio;
iovec_t iov;
int eof = 0;
caddr_t read_buf;
int namelen, size = 0;
size_t rlen = PAGE_CACHE_SIZE;
xfs_off_t start_offset, curr_offset;
xfs_dirent_t *dbp = NULL;
/* Try fairly hard to get memory */
do {
if ((read_buf = kmalloc(rlen, GFP_KERNEL)))
break;
rlen >>= 1;
} while (rlen >= 1024);
if (read_buf == NULL)
return -ENOMEM;
uio.uio_iov = &iov;
uio.uio_segflg = UIO_SYSSPACE;
curr_offset = filp->f_pos;
if (filp->f_pos != 0x7fffffff)
uio.uio_offset = filp->f_pos;
else
uio.uio_offset = 0xffffffff;
while (!eof) {
uio.uio_resid = iov.iov_len = rlen;
iov.iov_base = read_buf;
uio.uio_iovcnt = 1;
start_offset = uio.uio_offset;
error = bhv_vop_readdir(vp, &uio, NULL, &eof);
if ((uio.uio_offset == start_offset) || error) {
size = 0;
break;
}
size = rlen - uio.uio_resid;
dbp = (xfs_dirent_t *)read_buf;
while (size > 0) {
namelen = strlen(dbp->d_name);
if (filldir(dirent, dbp->d_name, namelen,
(loff_t) curr_offset & 0x7fffffff,
(ino_t) dbp->d_ino,
DT_UNKNOWN)) {
goto done;
}
size -= dbp->d_reclen;
curr_offset = (loff_t)dbp->d_off /* & 0x7fffffff */;
dbp = (xfs_dirent_t *)((char *)dbp + dbp->d_reclen);
}
}
done:
if (!error) {
if (size == 0)
filp->f_pos = uio.uio_offset & 0x7fffffff;
else if (dbp)
filp->f_pos = curr_offset;
}
kfree(read_buf);
return -error;
}
STATIC int
xfs_file_mmap(
struct file *filp,
struct vm_area_struct *vma)
{
vma->vm_ops = &xfs_file_vm_ops;
vma->vm_flags |= VM_CAN_NONLINEAR;
#ifdef CONFIG_XFS_DMAPI
if (vn_from_inode(filp->f_path.dentry->d_inode)->v_vfsp->vfs_flag & VFS_DMI)
vma->vm_ops = &xfs_dmapi_file_vm_ops;
#endif /* CONFIG_XFS_DMAPI */
file_accessed(filp);
return 0;
}
STATIC long
xfs_file_ioctl(
struct file *filp,
unsigned int cmd,
unsigned long p)
{
int error;
struct inode *inode = filp->f_path.dentry->d_inode;
bhv_vnode_t *vp = vn_from_inode(inode);
error = bhv_vop_ioctl(vp, inode, filp, 0, cmd, (void __user *)p);
VMODIFY(vp);
/* NOTE: some of the ioctl's return positive #'s as a
* byte count indicating success, such as
* readlink_by_handle. So we don't "sign flip"
* like most other routines. This means true
* errors need to be returned as a negative value.
*/
return error;
}
STATIC long
xfs_file_ioctl_invis(
struct file *filp,
unsigned int cmd,
unsigned long p)
{
int error;
struct inode *inode = filp->f_path.dentry->d_inode;
bhv_vnode_t *vp = vn_from_inode(inode);
error = bhv_vop_ioctl(vp, inode, filp, IO_INVIS, cmd, (void __user *)p);
VMODIFY(vp);
/* NOTE: some of the ioctl's return positive #'s as a
* byte count indicating success, such as
* readlink_by_handle. So we don't "sign flip"
* like most other routines. This means true
* errors need to be returned as a negative value.
*/
return error;
}
#ifdef CONFIG_XFS_DMAPI
#ifdef HAVE_VMOP_MPROTECT
STATIC int
xfs_vm_mprotect(
struct vm_area_struct *vma,
unsigned int newflags)
{
bhv_vnode_t *vp = vn_from_inode(vma->vm_file->f_path.dentry->d_inode);
int error = 0;
if (vp->v_vfsp->vfs_flag & VFS_DMI) {
if ((vma->vm_flags & VM_MAYSHARE) &&
(newflags & VM_WRITE) && !(vma->vm_flags & VM_WRITE)) {
xfs_mount_t *mp = XFS_VFSTOM(vp->v_vfsp);
error = XFS_SEND_MMAP(mp, vma, VM_WRITE);
}
}
return error;
}
#endif /* HAVE_VMOP_MPROTECT */
#endif /* CONFIG_XFS_DMAPI */
#ifdef HAVE_FOP_OPEN_EXEC
/* If the user is attempting to execute a file that is offline then
* we have to trigger a DMAPI READ event before the file is marked as busy
* otherwise the invisible I/O will not be able to write to the file to bring
* it back online.
*/
STATIC int
xfs_file_open_exec(
struct inode *inode)
{
bhv_vnode_t *vp = vn_from_inode(inode);
if (unlikely(vp->v_vfsp->vfs_flag & VFS_DMI)) {
xfs_mount_t *mp = XFS_VFSTOM(vp->v_vfsp);
xfs_inode_t *ip = xfs_vtoi(vp);
if (!ip)
return -EINVAL;
if (DM_EVENT_ENABLED(vp->v_vfsp, ip, DM_EVENT_READ))
return -XFS_SEND_DATA(mp, DM_EVENT_READ, vp,
0, 0, 0, NULL);
}
return 0;
}
#endif /* HAVE_FOP_OPEN_EXEC */
const struct file_operations xfs_file_operations = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.write = do_sync_write,
.aio_read = xfs_file_aio_read,
.aio_write = xfs_file_aio_write,
.splice_read = xfs_file_splice_read,
.splice_write = xfs_file_splice_write,
.unlocked_ioctl = xfs_file_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = xfs_file_compat_ioctl,
#endif
.mmap = xfs_file_mmap,
.open = xfs_file_open,
.flush = xfs_file_close,
.release = xfs_file_release,
.fsync = xfs_file_fsync,
#ifdef HAVE_FOP_OPEN_EXEC
.open_exec = xfs_file_open_exec,
#endif
};
const struct file_operations xfs_invis_file_operations = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.write = do_sync_write,
.aio_read = xfs_file_aio_read_invis,
.aio_write = xfs_file_aio_write_invis,
.splice_read = xfs_file_splice_read_invis,
.splice_write = xfs_file_splice_write_invis,
.unlocked_ioctl = xfs_file_ioctl_invis,
#ifdef CONFIG_COMPAT
.compat_ioctl = xfs_file_compat_invis_ioctl,
#endif
.mmap = xfs_file_mmap,
.open = xfs_file_open,
.flush = xfs_file_close,
.release = xfs_file_release,
.fsync = xfs_file_fsync,
};
const struct file_operations xfs_dir_file_operations = {
.read = generic_read_dir,
.readdir = xfs_file_readdir,
.unlocked_ioctl = xfs_file_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = xfs_file_compat_ioctl,
#endif
.fsync = xfs_file_fsync,
};
static struct vm_operations_struct xfs_file_vm_ops = {
.fault = filemap_fault,
};
#ifdef CONFIG_XFS_DMAPI
static struct vm_operations_struct xfs_dmapi_file_vm_ops = {
.fault = xfs_vm_fault,
#ifdef HAVE_VMOP_MPROTECT
.mprotect = xfs_vm_mprotect,
#endif
};
#endif /* CONFIG_XFS_DMAPI */
| ghmajx/asuswrt-merlin | release/src-rt/linux/linux-2.6/fs/xfs/linux-2.6/xfs_file.c | C | gpl-2.0 | 11,521 |
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* 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. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
if (is_admin() === false) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}
$transport = mres($_POST['transport']);
require_once $config['install_dir'].'/includes/alerts.inc.php';
$tmp = array(dbFetchRow('select device_id,hostname from devices order by device_id asc limit 1'));
$tmp['contacts'] = GetContacts($tmp);
$obj = array(
"hostname" => $tmp[0]['hostname'],
"device_id" => $tmp[0]['device_id'],
"title" => "Testing transport from ".$config['project_name'],
"elapsed" => "11s",
"id" => "000",
"faults" => false,
"uid" => "000",
"severity" => "critical",
"rule" => "%macros.device = 1",
"name" => "Test-Rule",
"timestamp" => date("Y-m-d H:i:s"),
"contacts" => $tmp['contacts'],
"state" => "1",
"msg" => "This is a test alert",
);
$status = 'error';
if (file_exists($config['install_dir']."/includes/alerts/transport.".$transport.".php")) {
$opts = $config['alert']['transports'][$transport];
if ($opts) {
eval('$tmp = function($obj,$opts) { global $config; '.file_get_contents($config['install_dir'].'/includes/alerts/transport.'.$transport.'.php').' return false; };');
$tmp = $tmp($obj,$opts);
if ($tmp) {
$status = 'ok';
}
}
}
header('Content-type: application/json');
echo _json_encode(array('status' => $status));
| cschoonover91/librenms | html/includes/forms/test-transport.inc.php | PHP | gpl-3.0 | 1,885 |
<?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/>.
/**
* External message API
*
* @package core_message
* @category external
* @copyright 2011 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once("$CFG->libdir/externallib.php");
/**
* Message external functions
*
* @package core_message
* @category external
* @copyright 2011 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.2
*/
class core_message_external extends external_api {
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function send_instant_messages_parameters() {
return new external_function_parameters(
array(
'messages' => new external_multiple_structure(
new external_single_structure(
array(
'touserid' => new external_value(PARAM_INT, 'id of the user to send the private message'),
'text' => new external_value(PARAM_RAW, 'the text of the message'),
'textformat' => new external_format_value('text', VALUE_DEFAULT),
'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own client id for the message. If this id is provided, the fail message id will be returned to you', VALUE_OPTIONAL),
)
)
)
)
);
}
/**
* Send private messages from the current USER to other users
*
* @param array $messages An array of message to send.
* @return array
* @since Moodle 2.2
*/
public static function send_instant_messages($messages = array()) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/message/lib.php");
//check if messaging is enabled
if (!$CFG->messaging) {
throw new moodle_exception('disabled', 'message');
}
// Ensure the current user is allowed to run this function
$context = get_context_instance(CONTEXT_SYSTEM);
self::validate_context($context);
require_capability('moodle/site:sendmessage', $context);
$params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));
//retrieve all tousers of the messages
$receivers = array();
foreach($params['messages'] as $message) {
$receivers[] = $message['touserid'];
}
list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers, SQL_PARAMS_NAMED, 'userid_');
$tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);
$blocklist = array();
$contactlist = array();
$sqlparams['contactid'] = $USER->id;
$rs = $DB->get_recordset_sql("SELECT *
FROM {message_contacts}
WHERE userid $sqluserids
AND contactid = :contactid", $sqlparams);
foreach ($rs as $record) {
if ($record->blocked) {
// $record->userid is blocking current user
$blocklist[$record->userid] = true;
} else {
// $record->userid have current user as contact
$contactlist[$record->userid] = true;
}
}
$rs->close();
$canreadallmessages = has_capability('moodle/site:readallmessages', $context);
$resultmessages = array();
foreach ($params['messages'] as $message) {
$resultmsg = array(); //the infos about the success of the operation
//we are going to do some checking
//code should match /messages/index.php checks
$success = true;
//check the user exists
if (empty($tousers[$message['touserid']])) {
$success = false;
$errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
}
//check that the touser is not blocking the current user
if ($success and !empty($blocklist[$message['touserid']]) and !$canreadallmessages) {
$success = false;
$errormessage = get_string('userisblockingyou', 'message');
}
// Check if the user is a contact
//TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
$blocknoncontacts = get_user_preferences('message_blocknoncontacts', NULL, $message['touserid']);
// message_blocknoncontacts option is on and current user is not in contact list
if ($success && empty($contactlist[$message['touserid']]) && !empty($blocknoncontacts)) {
// The user isn't a contact and they have selected to block non contacts so this message won't be sent.
$success = false;
$errormessage = get_string('userisblockingyounoncontact', 'message');
}
//now we can send the message (at least try)
if ($success) {
//TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object
$success = message_post_message($USER, $tousers[$message['touserid']],
$message['text'], external_validate_format($message['textformat']));
}
//build the resultmsg
if (isset($message['clientmsgid'])) {
$resultmsg['clientmsgid'] = $message['clientmsgid'];
}
if ($success) {
$resultmsg['msgid'] = $success;
} else {
// WARNINGS: for backward compatibility we return this errormessage.
// We should have thrown exceptions as these errors prevent results to be returned.
// See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
$resultmsg['msgid'] = -1;
$resultmsg['errormessage'] = $errormessage;
}
$resultmessages[] = $resultmsg;
}
return $resultmessages;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.2
*/
public static function send_instant_messages_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'msgid' => new external_value(PARAM_INT, 'test this to know if it succeeds: id of the created message if it succeeded, -1 when failed'),
'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the message', VALUE_OPTIONAL),
'errormessage' => new external_value(PARAM_TEXT, 'error message - if it failed', VALUE_OPTIONAL)
)
)
);
}
}
/**
* Deprecated message external functions
*
* @package core_message
* @copyright 2011 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.1
* @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
* @todo MDL-31194 This will be deleted in Moodle 2.5.
* @see core_notes_external
*/
class moodle_message_external extends external_api {
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.1
* @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
* @todo MDL-31194 This will be deleted in Moodle 2.5.
* @see core_message_external::send_instant_messages_parameters()
*/
public static function send_instantmessages_parameters() {
return core_message_external::send_instant_messages_parameters();
}
/**
* Send private messages from the current USER to other users
*
* @param array $messages An array of message to send.
* @return array
* @since Moodle 2.1
* @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
* @todo MDL-31194 This will be deleted in Moodle 2.5.
* @see core_message_external::send_instant_messages()
*/
public static function send_instantmessages($messages = array()) {
return core_message_external::send_instant_messages($messages);
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.1
* @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
* @todo MDL-31194 This will be deleted in Moodle 2.5.
* @see core_message_external::send_instant_messages_returns()
*/
public static function send_instantmessages_returns() {
return core_message_external::send_instant_messages_returns();
}
}
| bhaumik25php/ready2study | message/externallib.php | PHP | gpl-3.0 | 9,792 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "GAMGInterfaceField.H"
// * * * * * * * * * * * * * * * * Selectors * * * * * * * * * * * * * * * * //
Foam::autoPtr<Foam::GAMGInterfaceField> Foam::GAMGInterfaceField::New
(
const GAMGInterface& GAMGCp,
const lduInterfaceField& fineInterface
)
{
const word coupleType(fineInterface.interfaceFieldType());
lduInterfaceFieldConstructorTable::iterator cstrIter =
lduInterfaceFieldConstructorTablePtr_->find(coupleType);
if (cstrIter == lduInterfaceFieldConstructorTablePtr_->end())
{
FatalErrorIn
(
"GAMGInterfaceField::New"
"(const GAMGInterface& GAMGCp, "
"const lduInterfaceField& fineInterface)"
) << "Unknown GAMGInterfaceField type "
<< coupleType << nl
<< "Valid GAMGInterfaceField types are :"
<< lduInterfaceFieldConstructorTablePtr_->sortedToc()
<< exit(FatalError);
}
return autoPtr<GAMGInterfaceField>(cstrIter()(GAMGCp, fineInterface));
}
Foam::autoPtr<Foam::GAMGInterfaceField> Foam::GAMGInterfaceField::New
(
const GAMGInterface& GAMGCp,
const bool doTransform,
const int rank
)
{
const word coupleType(GAMGCp.type());
lduInterfaceConstructorTable::iterator cstrIter =
lduInterfaceConstructorTablePtr_->find(coupleType);
if (cstrIter == lduInterfaceConstructorTablePtr_->end())
{
FatalErrorIn
(
"GAMGInterfaceField::New"
"(const word&, const GAMGInterface&, const bool, const int)"
) << "Unknown GAMGInterfaceField type "
<< coupleType << nl
<< "Valid GAMGInterfaceField types are :"
<< lduInterfaceConstructorTablePtr_->sortedToc()
<< exit(FatalError);
}
return autoPtr<GAMGInterfaceField>(cstrIter()(GAMGCp, doTransform, rank));
}
// ************************************************************************* //
| adrcad/OpenFOAM-2.3.x | src/OpenFOAM/matrices/lduMatrix/solvers/GAMG/interfaceFields/GAMGInterfaceField/GAMGInterfaceFieldNew.C | C++ | gpl-3.0 | 3,097 |
from nose.tools import eq_, ok_
from kuma.core.urlresolvers import reverse
from kuma.core.tests import KumaTestCase, override_constance_settings
class HomeTests(KumaTestCase):
def test_google_analytics(self):
url = reverse('home')
with override_constance_settings(GOOGLE_ANALYTICS_ACCOUNT='0'):
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
ok_('ga(\'create' not in r.content)
with override_constance_settings(GOOGLE_ANALYTICS_ACCOUNT='UA-99999999-9'):
r = self.client.get(url, follow=True)
eq_(200, r.status_code)
ok_('ga(\'create' in r.content)
| biswajitsahu/kuma | kuma/landing/test_templates.py | Python | mpl-2.0 | 668 |
# Copyright (c) 2010-2013 by Yaco Sistemas <[email protected]> or <[email protected]>
#
# This program 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.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this programe. If not, see <http://www.gnu.org/licenses/>.
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
INPLACEEDIT_EDIT_EMPTY_VALUE = (getattr(settings, 'INPLACEEDIT_EDIT_EMPTY_VALUE', None) and
_(settings.INPLACEEDIT_EDIT_EMPTY_VALUE) or _('Doubleclick to edit'))
INPLACEEDIT_AUTO_SAVE = getattr(settings, 'INPLACEEDIT_AUTO_SAVE', False)
INPLACEEDIT_EVENT = getattr(settings, 'INPLACEEDIT_EVENT', 'dblclick')
INPLACEEDIT_DISABLE_CLICK = getattr(settings, 'INPLACEEDIT_DISABLE_CLICK', True)
INPLACEEDIT_EDIT_MESSAGE_TRANSLATION = (getattr(settings, 'INPLACEEDIT_EDIT_MESSAGE_TRANSLATION', None) and
_(settings.INPLACEEDIT_EDIT_MESSAGE_TRANSLATION) or _('Write a translation'))
INPLACEEDIT_SUCCESS_TEXT = (getattr(settings, 'INPLACEEDIT_SUCCESS_TEXT', None) and
_(settings.INPLACEEDIT_SUCCESS_TEXT) or _('Successfully saved'))
INPLACEEDIT_UNSAVED_TEXT = (getattr(settings, 'INPLACEEDIT_UNSAVED_TEXT', None) and
_(settings.INPLACEEDIT_UNSAVED_TEXT) or _('You have unsaved changes!'))
INPLACE_ENABLE_CLASS = getattr(settings, 'INPLACE_ENABLE_CLASS', 'enable')
DEFAULT_INPLACE_EDIT_OPTIONS = getattr(settings, "DEFAULT_INPLACE_EDIT_OPTIONS", {})
DEFAULT_INPLACE_EDIT_OPTIONS_ONE_BY_ONE = getattr(settings, 'DEFAULT_INPLACE_EDIT_OPTIONS_ONE_BY_ONE', False)
ADAPTOR_INPLACEEDIT_EDIT = getattr(settings, 'ADAPTOR_INPLACEEDIT_EDIT', None)
ADAPTOR_INPLACEEDIT = getattr(settings, 'ADAPTOR_INPLACEEDIT', {})
INPLACE_GET_FIELD_URL = getattr(settings, 'INPLACE_GET_FIELD_URL', None)
INPLACE_SAVE_URL = getattr(settings, 'INPLACE_SAVE_URL', None)
INPLACE_FIELD_TYPES = getattr(settings, 'INPLACE_FIELD_TYPES', 'input, select, textarea')
INPLACE_FOCUS_WHEN_EDITING = getattr(settings, 'INPLACE_FOCUS_WHEN_EDITING', True)
| nirmeshk/oh-mainline | vendor/packages/django-inplaceedit/inplaceeditform/settings.py | Python | agpl-3.0 | 2,568 |
CREATE VIEW BRANCHES_VIEW_TOPICS AS
SELECT
acl_entry.id, BRANCHES.BRANCH_ID, GROUPS.GROUP_ID
FROM
acl_entry, acl_object_identity, acl_class ,acl_sid, BRANCHES, GROUPS
WHERE
acl_entry.mask=6
AND acl_entry.granting=1
AND acl_object_identity.id=acl_entry.acl_object_identity
AND acl_class.id=acl_object_identity.object_id_class
AND acl_class.class='BRANCH'
AND BRANCHES.BRANCH_ID=acl_object_identity.object_id_identity
AND acl_entry.sid=acl_sid.id
AND acl_sid.sid LIKE 'usergroup:%'
AND GROUPS.GROUP_ID=SUBSTRING(acl_sid.sid,LENGTH('usergroup:')+1); | illerax/jcommune | jcommune-model/src/main/resources/org/jtalks/jcommune/migrations/V30__Views.sql | SQL | lgpl-2.1 | 608 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
internal sealed class DesktopMetadataReferenceResolver : MetadataFileReferenceResolver
{
private readonly MetadataFileReferenceResolver _pathResolver;
private readonly NuGetPackageResolver _packageResolver;
private readonly GacFileResolver _gacFileResolver;
internal DesktopMetadataReferenceResolver(
MetadataFileReferenceResolver pathResolver,
NuGetPackageResolver packageResolver,
GacFileResolver gacFileResolver)
{
_pathResolver = pathResolver;
_packageResolver = packageResolver;
_gacFileResolver = gacFileResolver;
}
public override ImmutableArray<string> SearchPaths
{
get { return _pathResolver.SearchPaths; }
}
public override string BaseDirectory
{
get { return _pathResolver.BaseDirectory; }
}
internal override MetadataFileReferenceResolver WithSearchPaths(ImmutableArray<string> searchPaths)
{
return new DesktopMetadataReferenceResolver(_pathResolver.WithSearchPaths(searchPaths), _packageResolver, _gacFileResolver);
}
internal override MetadataFileReferenceResolver WithBaseDirectory(string baseDirectory)
{
return new DesktopMetadataReferenceResolver(_pathResolver.WithBaseDirectory(baseDirectory), _packageResolver, _gacFileResolver);
}
public override string ResolveReference(string reference, string baseFilePath)
{
if (PathUtilities.IsFilePath(reference))
{
return _pathResolver.ResolveReference(reference, baseFilePath);
}
if (_packageResolver != null)
{
string path = _packageResolver.ResolveNuGetPackage(reference);
if (path != null && PortableShim.File.Exists(path))
{
return path;
}
}
if (_gacFileResolver != null)
{
return _gacFileResolver.ResolveReference(reference);
}
return null;
}
public override bool Equals(object obj)
{
var other = obj as DesktopMetadataReferenceResolver;
return (other != null) &&
object.Equals(_pathResolver, other._pathResolver) &&
object.Equals(_packageResolver, other._packageResolver) &&
object.Equals(_gacFileResolver, other._gacFileResolver);
}
public override int GetHashCode()
{
int result = _pathResolver.GetHashCode();
if (_packageResolver != null)
{
result = Hash.Combine(result, _packageResolver.GetHashCode());
}
if (_gacFileResolver != null)
{
result = Hash.Combine(result, _gacFileResolver.GetHashCode());
}
return result;
}
}
}
| KevinRansom/roslyn | src/Scripting/Core/DesktopMetadataReferenceResolver.cs | C# | apache-2.0 | 3,263 |
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// ************************************************************
// DO NOT EDIT.
// THIS FILE IS AUTO-GENERATED BY codecgen.
// ************************************************************
package v1beta1
import (
"errors"
"fmt"
codec1978 "github.com/ugorji/go/codec"
pkg1_v1 "k8s.io/client-go/pkg/api/v1"
pkg2_v1 "k8s.io/client-go/pkg/apis/meta/v1"
pkg3_types "k8s.io/client-go/pkg/types"
"reflect"
"runtime"
time "time"
)
const (
// ----- content types ----
codecSelferC_UTF81234 = 1
codecSelferC_RAW1234 = 0
// ----- value types used ----
codecSelferValueTypeArray1234 = 10
codecSelferValueTypeMap1234 = 9
// ----- containerStateValues ----
codecSelfer_containerMapKey1234 = 2
codecSelfer_containerMapValue1234 = 3
codecSelfer_containerMapEnd1234 = 4
codecSelfer_containerArrayElem1234 = 6
codecSelfer_containerArrayEnd1234 = 7
)
var (
codecSelferBitsize1234 = uint8(reflect.TypeOf(uint(0)).Bits())
codecSelferOnlyMapOrArrayEncodeToStructErr1234 = errors.New(`only encoded map or array can be decoded into a struct`)
)
type codecSelfer1234 struct{}
func init() {
if codec1978.GenVersion != 5 {
_, file, _, _ := runtime.Caller(0)
err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v",
5, codec1978.GenVersion, file)
panic(err)
}
if false { // reference the types, but skip this branch at build/run time
var v0 pkg1_v1.LocalObjectReference
var v1 pkg2_v1.Time
var v2 pkg3_types.UID
var v3 time.Time
_, _, _, _ = v0, v1, v2, v3
}
}
func (x *ServerAddressByClientCIDR) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
if x == nil {
r.EncodeNil()
} else {
yym1 := z.EncBinary()
_ = yym1
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
yysep2 := !z.EncBinary()
yy2arr2 := z.EncBasicHandle().StructToArray
var yyq2 [2]bool
_, _, _ = yysep2, yyq2, yy2arr2
const yyr2 bool = false
var yynn2 int
if yyr2 || yy2arr2 {
r.EncodeArrayStart(2)
} else {
yynn2 = 2
for _, b := range yyq2 {
if b {
yynn2++
}
}
r.EncodeMapStart(yynn2)
yynn2 = 0
}
if yyr2 || yy2arr2 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
yym4 := z.EncBinary()
_ = yym4
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.ClientCIDR))
}
} else {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("clientCIDR"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym5 := z.EncBinary()
_ = yym5
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.ClientCIDR))
}
}
if yyr2 || yy2arr2 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
yym7 := z.EncBinary()
_ = yym7
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.ServerAddress))
}
} else {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("serverAddress"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym8 := z.EncBinary()
_ = yym8
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.ServerAddress))
}
}
if yyr2 || yy2arr2 {
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
z.EncSendContainerState(codecSelfer_containerMapEnd1234)
}
}
}
}
func (x *ServerAddressByClientCIDR) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym9 := z.DecBinary()
_ = yym9
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
yyct10 := r.ContainerType()
if yyct10 == codecSelferValueTypeMap1234 {
yyl10 := r.ReadMapStart()
if yyl10 == 0 {
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
} else {
x.codecDecodeSelfFromMap(yyl10, d)
}
} else if yyct10 == codecSelferValueTypeArray1234 {
yyl10 := r.ReadArrayStart()
if yyl10 == 0 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
x.codecDecodeSelfFromArray(yyl10, d)
}
} else {
panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234)
}
}
}
func (x *ServerAddressByClientCIDR) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yys11Slc = z.DecScratchBuffer() // default slice to decode into
_ = yys11Slc
var yyhl11 bool = l >= 0
for yyj11 := 0; ; yyj11++ {
if yyhl11 {
if yyj11 >= l {
break
}
} else {
if r.CheckBreak() {
break
}
}
z.DecSendContainerState(codecSelfer_containerMapKey1234)
yys11Slc = r.DecodeBytes(yys11Slc, true, true)
yys11 := string(yys11Slc)
z.DecSendContainerState(codecSelfer_containerMapValue1234)
switch yys11 {
case "clientCIDR":
if r.TryDecodeAsNil() {
x.ClientCIDR = ""
} else {
x.ClientCIDR = string(r.DecodeString())
}
case "serverAddress":
if r.TryDecodeAsNil() {
x.ServerAddress = ""
} else {
x.ServerAddress = string(r.DecodeString())
}
default:
z.DecStructFieldNotFound(-1, yys11)
} // end switch yys11
} // end for yyj11
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
}
func (x *ServerAddressByClientCIDR) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yyj14 int
var yyb14 bool
var yyhl14 bool = l >= 0
yyj14++
if yyhl14 {
yyb14 = yyj14 > l
} else {
yyb14 = r.CheckBreak()
}
if yyb14 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.ClientCIDR = ""
} else {
x.ClientCIDR = string(r.DecodeString())
}
yyj14++
if yyhl14 {
yyb14 = yyj14 > l
} else {
yyb14 = r.CheckBreak()
}
if yyb14 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.ServerAddress = ""
} else {
x.ServerAddress = string(r.DecodeString())
}
for {
yyj14++
if yyhl14 {
yyb14 = yyj14 > l
} else {
yyb14 = r.CheckBreak()
}
if yyb14 {
break
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
z.DecStructFieldNotFound(yyj14-1, "")
}
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x *ClusterSpec) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
if x == nil {
r.EncodeNil()
} else {
yym17 := z.EncBinary()
_ = yym17
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
yysep18 := !z.EncBinary()
yy2arr18 := z.EncBasicHandle().StructToArray
var yyq18 [2]bool
_, _, _ = yysep18, yyq18, yy2arr18
const yyr18 bool = false
yyq18[1] = x.SecretRef != nil
var yynn18 int
if yyr18 || yy2arr18 {
r.EncodeArrayStart(2)
} else {
yynn18 = 1
for _, b := range yyq18 {
if b {
yynn18++
}
}
r.EncodeMapStart(yynn18)
yynn18 = 0
}
if yyr18 || yy2arr18 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if x.ServerAddressByClientCIDRs == nil {
r.EncodeNil()
} else {
yym20 := z.EncBinary()
_ = yym20
if false {
} else {
h.encSliceServerAddressByClientCIDR(([]ServerAddressByClientCIDR)(x.ServerAddressByClientCIDRs), e)
}
}
} else {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("serverAddressByClientCIDRs"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
if x.ServerAddressByClientCIDRs == nil {
r.EncodeNil()
} else {
yym21 := z.EncBinary()
_ = yym21
if false {
} else {
h.encSliceServerAddressByClientCIDR(([]ServerAddressByClientCIDR)(x.ServerAddressByClientCIDRs), e)
}
}
}
if yyr18 || yy2arr18 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq18[1] {
if x.SecretRef == nil {
r.EncodeNil()
} else {
x.SecretRef.CodecEncodeSelf(e)
}
} else {
r.EncodeNil()
}
} else {
if yyq18[1] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("secretRef"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
if x.SecretRef == nil {
r.EncodeNil()
} else {
x.SecretRef.CodecEncodeSelf(e)
}
}
}
if yyr18 || yy2arr18 {
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
z.EncSendContainerState(codecSelfer_containerMapEnd1234)
}
}
}
}
func (x *ClusterSpec) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym23 := z.DecBinary()
_ = yym23
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
yyct24 := r.ContainerType()
if yyct24 == codecSelferValueTypeMap1234 {
yyl24 := r.ReadMapStart()
if yyl24 == 0 {
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
} else {
x.codecDecodeSelfFromMap(yyl24, d)
}
} else if yyct24 == codecSelferValueTypeArray1234 {
yyl24 := r.ReadArrayStart()
if yyl24 == 0 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
x.codecDecodeSelfFromArray(yyl24, d)
}
} else {
panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234)
}
}
}
func (x *ClusterSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yys25Slc = z.DecScratchBuffer() // default slice to decode into
_ = yys25Slc
var yyhl25 bool = l >= 0
for yyj25 := 0; ; yyj25++ {
if yyhl25 {
if yyj25 >= l {
break
}
} else {
if r.CheckBreak() {
break
}
}
z.DecSendContainerState(codecSelfer_containerMapKey1234)
yys25Slc = r.DecodeBytes(yys25Slc, true, true)
yys25 := string(yys25Slc)
z.DecSendContainerState(codecSelfer_containerMapValue1234)
switch yys25 {
case "serverAddressByClientCIDRs":
if r.TryDecodeAsNil() {
x.ServerAddressByClientCIDRs = nil
} else {
yyv26 := &x.ServerAddressByClientCIDRs
yym27 := z.DecBinary()
_ = yym27
if false {
} else {
h.decSliceServerAddressByClientCIDR((*[]ServerAddressByClientCIDR)(yyv26), d)
}
}
case "secretRef":
if r.TryDecodeAsNil() {
if x.SecretRef != nil {
x.SecretRef = nil
}
} else {
if x.SecretRef == nil {
x.SecretRef = new(pkg1_v1.LocalObjectReference)
}
x.SecretRef.CodecDecodeSelf(d)
}
default:
z.DecStructFieldNotFound(-1, yys25)
} // end switch yys25
} // end for yyj25
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
}
func (x *ClusterSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yyj29 int
var yyb29 bool
var yyhl29 bool = l >= 0
yyj29++
if yyhl29 {
yyb29 = yyj29 > l
} else {
yyb29 = r.CheckBreak()
}
if yyb29 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.ServerAddressByClientCIDRs = nil
} else {
yyv30 := &x.ServerAddressByClientCIDRs
yym31 := z.DecBinary()
_ = yym31
if false {
} else {
h.decSliceServerAddressByClientCIDR((*[]ServerAddressByClientCIDR)(yyv30), d)
}
}
yyj29++
if yyhl29 {
yyb29 = yyj29 > l
} else {
yyb29 = r.CheckBreak()
}
if yyb29 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
if x.SecretRef != nil {
x.SecretRef = nil
}
} else {
if x.SecretRef == nil {
x.SecretRef = new(pkg1_v1.LocalObjectReference)
}
x.SecretRef.CodecDecodeSelf(d)
}
for {
yyj29++
if yyhl29 {
yyb29 = yyj29 > l
} else {
yyb29 = r.CheckBreak()
}
if yyb29 {
break
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
z.DecStructFieldNotFound(yyj29-1, "")
}
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x ClusterConditionType) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
yym33 := z.EncBinary()
_ = yym33
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x))
}
}
func (x *ClusterConditionType) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym34 := z.DecBinary()
_ = yym34
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
*((*string)(x)) = r.DecodeString()
}
}
func (x *ClusterCondition) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
if x == nil {
r.EncodeNil()
} else {
yym35 := z.EncBinary()
_ = yym35
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
yysep36 := !z.EncBinary()
yy2arr36 := z.EncBasicHandle().StructToArray
var yyq36 [6]bool
_, _, _ = yysep36, yyq36, yy2arr36
const yyr36 bool = false
yyq36[2] = true
yyq36[3] = true
yyq36[4] = x.Reason != ""
yyq36[5] = x.Message != ""
var yynn36 int
if yyr36 || yy2arr36 {
r.EncodeArrayStart(6)
} else {
yynn36 = 2
for _, b := range yyq36 {
if b {
yynn36++
}
}
r.EncodeMapStart(yynn36)
yynn36 = 0
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
x.Type.CodecEncodeSelf(e)
} else {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("type"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
x.Type.CodecEncodeSelf(e)
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
yym39 := z.EncBinary()
_ = yym39
if false {
} else if z.HasExtensions() && z.EncExt(x.Status) {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Status))
}
} else {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("status"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym40 := z.EncBinary()
_ = yym40
if false {
} else if z.HasExtensions() && z.EncExt(x.Status) {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Status))
}
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq36[2] {
yy42 := &x.LastProbeTime
yym43 := z.EncBinary()
_ = yym43
if false {
} else if z.HasExtensions() && z.EncExt(yy42) {
} else if yym43 {
z.EncBinaryMarshal(yy42)
} else if !yym43 && z.IsJSONHandle() {
z.EncJSONMarshal(yy42)
} else {
z.EncFallback(yy42)
}
} else {
r.EncodeNil()
}
} else {
if yyq36[2] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("lastProbeTime"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yy44 := &x.LastProbeTime
yym45 := z.EncBinary()
_ = yym45
if false {
} else if z.HasExtensions() && z.EncExt(yy44) {
} else if yym45 {
z.EncBinaryMarshal(yy44)
} else if !yym45 && z.IsJSONHandle() {
z.EncJSONMarshal(yy44)
} else {
z.EncFallback(yy44)
}
}
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq36[3] {
yy47 := &x.LastTransitionTime
yym48 := z.EncBinary()
_ = yym48
if false {
} else if z.HasExtensions() && z.EncExt(yy47) {
} else if yym48 {
z.EncBinaryMarshal(yy47)
} else if !yym48 && z.IsJSONHandle() {
z.EncJSONMarshal(yy47)
} else {
z.EncFallback(yy47)
}
} else {
r.EncodeNil()
}
} else {
if yyq36[3] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("lastTransitionTime"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yy49 := &x.LastTransitionTime
yym50 := z.EncBinary()
_ = yym50
if false {
} else if z.HasExtensions() && z.EncExt(yy49) {
} else if yym50 {
z.EncBinaryMarshal(yy49)
} else if !yym50 && z.IsJSONHandle() {
z.EncJSONMarshal(yy49)
} else {
z.EncFallback(yy49)
}
}
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq36[4] {
yym52 := z.EncBinary()
_ = yym52
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Reason))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq36[4] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("reason"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym53 := z.EncBinary()
_ = yym53
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Reason))
}
}
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq36[5] {
yym55 := z.EncBinary()
_ = yym55
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Message))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq36[5] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("message"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym56 := z.EncBinary()
_ = yym56
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Message))
}
}
}
if yyr36 || yy2arr36 {
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
z.EncSendContainerState(codecSelfer_containerMapEnd1234)
}
}
}
}
func (x *ClusterCondition) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym57 := z.DecBinary()
_ = yym57
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
yyct58 := r.ContainerType()
if yyct58 == codecSelferValueTypeMap1234 {
yyl58 := r.ReadMapStart()
if yyl58 == 0 {
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
} else {
x.codecDecodeSelfFromMap(yyl58, d)
}
} else if yyct58 == codecSelferValueTypeArray1234 {
yyl58 := r.ReadArrayStart()
if yyl58 == 0 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
x.codecDecodeSelfFromArray(yyl58, d)
}
} else {
panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234)
}
}
}
func (x *ClusterCondition) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yys59Slc = z.DecScratchBuffer() // default slice to decode into
_ = yys59Slc
var yyhl59 bool = l >= 0
for yyj59 := 0; ; yyj59++ {
if yyhl59 {
if yyj59 >= l {
break
}
} else {
if r.CheckBreak() {
break
}
}
z.DecSendContainerState(codecSelfer_containerMapKey1234)
yys59Slc = r.DecodeBytes(yys59Slc, true, true)
yys59 := string(yys59Slc)
z.DecSendContainerState(codecSelfer_containerMapValue1234)
switch yys59 {
case "type":
if r.TryDecodeAsNil() {
x.Type = ""
} else {
x.Type = ClusterConditionType(r.DecodeString())
}
case "status":
if r.TryDecodeAsNil() {
x.Status = ""
} else {
x.Status = pkg1_v1.ConditionStatus(r.DecodeString())
}
case "lastProbeTime":
if r.TryDecodeAsNil() {
x.LastProbeTime = pkg2_v1.Time{}
} else {
yyv62 := &x.LastProbeTime
yym63 := z.DecBinary()
_ = yym63
if false {
} else if z.HasExtensions() && z.DecExt(yyv62) {
} else if yym63 {
z.DecBinaryUnmarshal(yyv62)
} else if !yym63 && z.IsJSONHandle() {
z.DecJSONUnmarshal(yyv62)
} else {
z.DecFallback(yyv62, false)
}
}
case "lastTransitionTime":
if r.TryDecodeAsNil() {
x.LastTransitionTime = pkg2_v1.Time{}
} else {
yyv64 := &x.LastTransitionTime
yym65 := z.DecBinary()
_ = yym65
if false {
} else if z.HasExtensions() && z.DecExt(yyv64) {
} else if yym65 {
z.DecBinaryUnmarshal(yyv64)
} else if !yym65 && z.IsJSONHandle() {
z.DecJSONUnmarshal(yyv64)
} else {
z.DecFallback(yyv64, false)
}
}
case "reason":
if r.TryDecodeAsNil() {
x.Reason = ""
} else {
x.Reason = string(r.DecodeString())
}
case "message":
if r.TryDecodeAsNil() {
x.Message = ""
} else {
x.Message = string(r.DecodeString())
}
default:
z.DecStructFieldNotFound(-1, yys59)
} // end switch yys59
} // end for yyj59
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
}
func (x *ClusterCondition) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yyj68 int
var yyb68 bool
var yyhl68 bool = l >= 0
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Type = ""
} else {
x.Type = ClusterConditionType(r.DecodeString())
}
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Status = ""
} else {
x.Status = pkg1_v1.ConditionStatus(r.DecodeString())
}
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.LastProbeTime = pkg2_v1.Time{}
} else {
yyv71 := &x.LastProbeTime
yym72 := z.DecBinary()
_ = yym72
if false {
} else if z.HasExtensions() && z.DecExt(yyv71) {
} else if yym72 {
z.DecBinaryUnmarshal(yyv71)
} else if !yym72 && z.IsJSONHandle() {
z.DecJSONUnmarshal(yyv71)
} else {
z.DecFallback(yyv71, false)
}
}
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.LastTransitionTime = pkg2_v1.Time{}
} else {
yyv73 := &x.LastTransitionTime
yym74 := z.DecBinary()
_ = yym74
if false {
} else if z.HasExtensions() && z.DecExt(yyv73) {
} else if yym74 {
z.DecBinaryUnmarshal(yyv73)
} else if !yym74 && z.IsJSONHandle() {
z.DecJSONUnmarshal(yyv73)
} else {
z.DecFallback(yyv73, false)
}
}
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Reason = ""
} else {
x.Reason = string(r.DecodeString())
}
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Message = ""
} else {
x.Message = string(r.DecodeString())
}
for {
yyj68++
if yyhl68 {
yyb68 = yyj68 > l
} else {
yyb68 = r.CheckBreak()
}
if yyb68 {
break
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
z.DecStructFieldNotFound(yyj68-1, "")
}
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x *ClusterStatus) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
if x == nil {
r.EncodeNil()
} else {
yym77 := z.EncBinary()
_ = yym77
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
yysep78 := !z.EncBinary()
yy2arr78 := z.EncBasicHandle().StructToArray
var yyq78 [3]bool
_, _, _ = yysep78, yyq78, yy2arr78
const yyr78 bool = false
yyq78[0] = len(x.Conditions) != 0
yyq78[1] = len(x.Zones) != 0
yyq78[2] = x.Region != ""
var yynn78 int
if yyr78 || yy2arr78 {
r.EncodeArrayStart(3)
} else {
yynn78 = 0
for _, b := range yyq78 {
if b {
yynn78++
}
}
r.EncodeMapStart(yynn78)
yynn78 = 0
}
if yyr78 || yy2arr78 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq78[0] {
if x.Conditions == nil {
r.EncodeNil()
} else {
yym80 := z.EncBinary()
_ = yym80
if false {
} else {
h.encSliceClusterCondition(([]ClusterCondition)(x.Conditions), e)
}
}
} else {
r.EncodeNil()
}
} else {
if yyq78[0] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("conditions"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
if x.Conditions == nil {
r.EncodeNil()
} else {
yym81 := z.EncBinary()
_ = yym81
if false {
} else {
h.encSliceClusterCondition(([]ClusterCondition)(x.Conditions), e)
}
}
}
}
if yyr78 || yy2arr78 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq78[1] {
if x.Zones == nil {
r.EncodeNil()
} else {
yym83 := z.EncBinary()
_ = yym83
if false {
} else {
z.F.EncSliceStringV(x.Zones, false, e)
}
}
} else {
r.EncodeNil()
}
} else {
if yyq78[1] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("zones"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
if x.Zones == nil {
r.EncodeNil()
} else {
yym84 := z.EncBinary()
_ = yym84
if false {
} else {
z.F.EncSliceStringV(x.Zones, false, e)
}
}
}
}
if yyr78 || yy2arr78 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq78[2] {
yym86 := z.EncBinary()
_ = yym86
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Region))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq78[2] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("region"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym87 := z.EncBinary()
_ = yym87
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Region))
}
}
}
if yyr78 || yy2arr78 {
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
z.EncSendContainerState(codecSelfer_containerMapEnd1234)
}
}
}
}
func (x *ClusterStatus) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym88 := z.DecBinary()
_ = yym88
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
yyct89 := r.ContainerType()
if yyct89 == codecSelferValueTypeMap1234 {
yyl89 := r.ReadMapStart()
if yyl89 == 0 {
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
} else {
x.codecDecodeSelfFromMap(yyl89, d)
}
} else if yyct89 == codecSelferValueTypeArray1234 {
yyl89 := r.ReadArrayStart()
if yyl89 == 0 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
x.codecDecodeSelfFromArray(yyl89, d)
}
} else {
panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234)
}
}
}
func (x *ClusterStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yys90Slc = z.DecScratchBuffer() // default slice to decode into
_ = yys90Slc
var yyhl90 bool = l >= 0
for yyj90 := 0; ; yyj90++ {
if yyhl90 {
if yyj90 >= l {
break
}
} else {
if r.CheckBreak() {
break
}
}
z.DecSendContainerState(codecSelfer_containerMapKey1234)
yys90Slc = r.DecodeBytes(yys90Slc, true, true)
yys90 := string(yys90Slc)
z.DecSendContainerState(codecSelfer_containerMapValue1234)
switch yys90 {
case "conditions":
if r.TryDecodeAsNil() {
x.Conditions = nil
} else {
yyv91 := &x.Conditions
yym92 := z.DecBinary()
_ = yym92
if false {
} else {
h.decSliceClusterCondition((*[]ClusterCondition)(yyv91), d)
}
}
case "zones":
if r.TryDecodeAsNil() {
x.Zones = nil
} else {
yyv93 := &x.Zones
yym94 := z.DecBinary()
_ = yym94
if false {
} else {
z.F.DecSliceStringX(yyv93, false, d)
}
}
case "region":
if r.TryDecodeAsNil() {
x.Region = ""
} else {
x.Region = string(r.DecodeString())
}
default:
z.DecStructFieldNotFound(-1, yys90)
} // end switch yys90
} // end for yyj90
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
}
func (x *ClusterStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yyj96 int
var yyb96 bool
var yyhl96 bool = l >= 0
yyj96++
if yyhl96 {
yyb96 = yyj96 > l
} else {
yyb96 = r.CheckBreak()
}
if yyb96 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Conditions = nil
} else {
yyv97 := &x.Conditions
yym98 := z.DecBinary()
_ = yym98
if false {
} else {
h.decSliceClusterCondition((*[]ClusterCondition)(yyv97), d)
}
}
yyj96++
if yyhl96 {
yyb96 = yyj96 > l
} else {
yyb96 = r.CheckBreak()
}
if yyb96 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Zones = nil
} else {
yyv99 := &x.Zones
yym100 := z.DecBinary()
_ = yym100
if false {
} else {
z.F.DecSliceStringX(yyv99, false, d)
}
}
yyj96++
if yyhl96 {
yyb96 = yyj96 > l
} else {
yyb96 = r.CheckBreak()
}
if yyb96 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Region = ""
} else {
x.Region = string(r.DecodeString())
}
for {
yyj96++
if yyhl96 {
yyb96 = yyj96 > l
} else {
yyb96 = r.CheckBreak()
}
if yyb96 {
break
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
z.DecStructFieldNotFound(yyj96-1, "")
}
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x *Cluster) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
if x == nil {
r.EncodeNil()
} else {
yym102 := z.EncBinary()
_ = yym102
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
yysep103 := !z.EncBinary()
yy2arr103 := z.EncBasicHandle().StructToArray
var yyq103 [5]bool
_, _, _ = yysep103, yyq103, yy2arr103
const yyr103 bool = false
yyq103[0] = x.Kind != ""
yyq103[1] = x.APIVersion != ""
yyq103[2] = true
yyq103[3] = true
yyq103[4] = true
var yynn103 int
if yyr103 || yy2arr103 {
r.EncodeArrayStart(5)
} else {
yynn103 = 0
for _, b := range yyq103 {
if b {
yynn103++
}
}
r.EncodeMapStart(yynn103)
yynn103 = 0
}
if yyr103 || yy2arr103 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq103[0] {
yym105 := z.EncBinary()
_ = yym105
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Kind))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq103[0] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("kind"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym106 := z.EncBinary()
_ = yym106
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Kind))
}
}
}
if yyr103 || yy2arr103 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq103[1] {
yym108 := z.EncBinary()
_ = yym108
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq103[1] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("apiVersion"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym109 := z.EncBinary()
_ = yym109
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion))
}
}
}
if yyr103 || yy2arr103 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq103[2] {
yy111 := &x.ObjectMeta
yy111.CodecEncodeSelf(e)
} else {
r.EncodeNil()
}
} else {
if yyq103[2] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("metadata"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yy112 := &x.ObjectMeta
yy112.CodecEncodeSelf(e)
}
}
if yyr103 || yy2arr103 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq103[3] {
yy114 := &x.Spec
yy114.CodecEncodeSelf(e)
} else {
r.EncodeNil()
}
} else {
if yyq103[3] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("spec"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yy115 := &x.Spec
yy115.CodecEncodeSelf(e)
}
}
if yyr103 || yy2arr103 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq103[4] {
yy117 := &x.Status
yy117.CodecEncodeSelf(e)
} else {
r.EncodeNil()
}
} else {
if yyq103[4] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("status"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yy118 := &x.Status
yy118.CodecEncodeSelf(e)
}
}
if yyr103 || yy2arr103 {
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
z.EncSendContainerState(codecSelfer_containerMapEnd1234)
}
}
}
}
func (x *Cluster) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym119 := z.DecBinary()
_ = yym119
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
yyct120 := r.ContainerType()
if yyct120 == codecSelferValueTypeMap1234 {
yyl120 := r.ReadMapStart()
if yyl120 == 0 {
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
} else {
x.codecDecodeSelfFromMap(yyl120, d)
}
} else if yyct120 == codecSelferValueTypeArray1234 {
yyl120 := r.ReadArrayStart()
if yyl120 == 0 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
x.codecDecodeSelfFromArray(yyl120, d)
}
} else {
panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234)
}
}
}
func (x *Cluster) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yys121Slc = z.DecScratchBuffer() // default slice to decode into
_ = yys121Slc
var yyhl121 bool = l >= 0
for yyj121 := 0; ; yyj121++ {
if yyhl121 {
if yyj121 >= l {
break
}
} else {
if r.CheckBreak() {
break
}
}
z.DecSendContainerState(codecSelfer_containerMapKey1234)
yys121Slc = r.DecodeBytes(yys121Slc, true, true)
yys121 := string(yys121Slc)
z.DecSendContainerState(codecSelfer_containerMapValue1234)
switch yys121 {
case "kind":
if r.TryDecodeAsNil() {
x.Kind = ""
} else {
x.Kind = string(r.DecodeString())
}
case "apiVersion":
if r.TryDecodeAsNil() {
x.APIVersion = ""
} else {
x.APIVersion = string(r.DecodeString())
}
case "metadata":
if r.TryDecodeAsNil() {
x.ObjectMeta = pkg1_v1.ObjectMeta{}
} else {
yyv124 := &x.ObjectMeta
yyv124.CodecDecodeSelf(d)
}
case "spec":
if r.TryDecodeAsNil() {
x.Spec = ClusterSpec{}
} else {
yyv125 := &x.Spec
yyv125.CodecDecodeSelf(d)
}
case "status":
if r.TryDecodeAsNil() {
x.Status = ClusterStatus{}
} else {
yyv126 := &x.Status
yyv126.CodecDecodeSelf(d)
}
default:
z.DecStructFieldNotFound(-1, yys121)
} // end switch yys121
} // end for yyj121
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
}
func (x *Cluster) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yyj127 int
var yyb127 bool
var yyhl127 bool = l >= 0
yyj127++
if yyhl127 {
yyb127 = yyj127 > l
} else {
yyb127 = r.CheckBreak()
}
if yyb127 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Kind = ""
} else {
x.Kind = string(r.DecodeString())
}
yyj127++
if yyhl127 {
yyb127 = yyj127 > l
} else {
yyb127 = r.CheckBreak()
}
if yyb127 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.APIVersion = ""
} else {
x.APIVersion = string(r.DecodeString())
}
yyj127++
if yyhl127 {
yyb127 = yyj127 > l
} else {
yyb127 = r.CheckBreak()
}
if yyb127 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.ObjectMeta = pkg1_v1.ObjectMeta{}
} else {
yyv130 := &x.ObjectMeta
yyv130.CodecDecodeSelf(d)
}
yyj127++
if yyhl127 {
yyb127 = yyj127 > l
} else {
yyb127 = r.CheckBreak()
}
if yyb127 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Spec = ClusterSpec{}
} else {
yyv131 := &x.Spec
yyv131.CodecDecodeSelf(d)
}
yyj127++
if yyhl127 {
yyb127 = yyj127 > l
} else {
yyb127 = r.CheckBreak()
}
if yyb127 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Status = ClusterStatus{}
} else {
yyv132 := &x.Status
yyv132.CodecDecodeSelf(d)
}
for {
yyj127++
if yyhl127 {
yyb127 = yyj127 > l
} else {
yyb127 = r.CheckBreak()
}
if yyb127 {
break
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
z.DecStructFieldNotFound(yyj127-1, "")
}
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x *ClusterList) CodecEncodeSelf(e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
if x == nil {
r.EncodeNil()
} else {
yym133 := z.EncBinary()
_ = yym133
if false {
} else if z.HasExtensions() && z.EncExt(x) {
} else {
yysep134 := !z.EncBinary()
yy2arr134 := z.EncBasicHandle().StructToArray
var yyq134 [4]bool
_, _, _ = yysep134, yyq134, yy2arr134
const yyr134 bool = false
yyq134[0] = x.Kind != ""
yyq134[1] = x.APIVersion != ""
yyq134[2] = true
var yynn134 int
if yyr134 || yy2arr134 {
r.EncodeArrayStart(4)
} else {
yynn134 = 1
for _, b := range yyq134 {
if b {
yynn134++
}
}
r.EncodeMapStart(yynn134)
yynn134 = 0
}
if yyr134 || yy2arr134 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq134[0] {
yym136 := z.EncBinary()
_ = yym136
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Kind))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq134[0] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("kind"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym137 := z.EncBinary()
_ = yym137
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.Kind))
}
}
}
if yyr134 || yy2arr134 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq134[1] {
yym139 := z.EncBinary()
_ = yym139
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion))
}
} else {
r.EncodeString(codecSelferC_UTF81234, "")
}
} else {
if yyq134[1] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("apiVersion"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yym140 := z.EncBinary()
_ = yym140
if false {
} else {
r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion))
}
}
}
if yyr134 || yy2arr134 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if yyq134[2] {
yy142 := &x.ListMeta
yym143 := z.EncBinary()
_ = yym143
if false {
} else if z.HasExtensions() && z.EncExt(yy142) {
} else {
z.EncFallback(yy142)
}
} else {
r.EncodeNil()
}
} else {
if yyq134[2] {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("metadata"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
yy144 := &x.ListMeta
yym145 := z.EncBinary()
_ = yym145
if false {
} else if z.HasExtensions() && z.EncExt(yy144) {
} else {
z.EncFallback(yy144)
}
}
}
if yyr134 || yy2arr134 {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
if x.Items == nil {
r.EncodeNil()
} else {
yym147 := z.EncBinary()
_ = yym147
if false {
} else {
h.encSliceCluster(([]Cluster)(x.Items), e)
}
}
} else {
z.EncSendContainerState(codecSelfer_containerMapKey1234)
r.EncodeString(codecSelferC_UTF81234, string("items"))
z.EncSendContainerState(codecSelfer_containerMapValue1234)
if x.Items == nil {
r.EncodeNil()
} else {
yym148 := z.EncBinary()
_ = yym148
if false {
} else {
h.encSliceCluster(([]Cluster)(x.Items), e)
}
}
}
if yyr134 || yy2arr134 {
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
z.EncSendContainerState(codecSelfer_containerMapEnd1234)
}
}
}
}
func (x *ClusterList) CodecDecodeSelf(d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yym149 := z.DecBinary()
_ = yym149
if false {
} else if z.HasExtensions() && z.DecExt(x) {
} else {
yyct150 := r.ContainerType()
if yyct150 == codecSelferValueTypeMap1234 {
yyl150 := r.ReadMapStart()
if yyl150 == 0 {
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
} else {
x.codecDecodeSelfFromMap(yyl150, d)
}
} else if yyct150 == codecSelferValueTypeArray1234 {
yyl150 := r.ReadArrayStart()
if yyl150 == 0 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
} else {
x.codecDecodeSelfFromArray(yyl150, d)
}
} else {
panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234)
}
}
}
func (x *ClusterList) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yys151Slc = z.DecScratchBuffer() // default slice to decode into
_ = yys151Slc
var yyhl151 bool = l >= 0
for yyj151 := 0; ; yyj151++ {
if yyhl151 {
if yyj151 >= l {
break
}
} else {
if r.CheckBreak() {
break
}
}
z.DecSendContainerState(codecSelfer_containerMapKey1234)
yys151Slc = r.DecodeBytes(yys151Slc, true, true)
yys151 := string(yys151Slc)
z.DecSendContainerState(codecSelfer_containerMapValue1234)
switch yys151 {
case "kind":
if r.TryDecodeAsNil() {
x.Kind = ""
} else {
x.Kind = string(r.DecodeString())
}
case "apiVersion":
if r.TryDecodeAsNil() {
x.APIVersion = ""
} else {
x.APIVersion = string(r.DecodeString())
}
case "metadata":
if r.TryDecodeAsNil() {
x.ListMeta = pkg2_v1.ListMeta{}
} else {
yyv154 := &x.ListMeta
yym155 := z.DecBinary()
_ = yym155
if false {
} else if z.HasExtensions() && z.DecExt(yyv154) {
} else {
z.DecFallback(yyv154, false)
}
}
case "items":
if r.TryDecodeAsNil() {
x.Items = nil
} else {
yyv156 := &x.Items
yym157 := z.DecBinary()
_ = yym157
if false {
} else {
h.decSliceCluster((*[]Cluster)(yyv156), d)
}
}
default:
z.DecStructFieldNotFound(-1, yys151)
} // end switch yys151
} // end for yyj151
z.DecSendContainerState(codecSelfer_containerMapEnd1234)
}
func (x *ClusterList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
var yyj158 int
var yyb158 bool
var yyhl158 bool = l >= 0
yyj158++
if yyhl158 {
yyb158 = yyj158 > l
} else {
yyb158 = r.CheckBreak()
}
if yyb158 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Kind = ""
} else {
x.Kind = string(r.DecodeString())
}
yyj158++
if yyhl158 {
yyb158 = yyj158 > l
} else {
yyb158 = r.CheckBreak()
}
if yyb158 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.APIVersion = ""
} else {
x.APIVersion = string(r.DecodeString())
}
yyj158++
if yyhl158 {
yyb158 = yyj158 > l
} else {
yyb158 = r.CheckBreak()
}
if yyb158 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.ListMeta = pkg2_v1.ListMeta{}
} else {
yyv161 := &x.ListMeta
yym162 := z.DecBinary()
_ = yym162
if false {
} else if z.HasExtensions() && z.DecExt(yyv161) {
} else {
z.DecFallback(yyv161, false)
}
}
yyj158++
if yyhl158 {
yyb158 = yyj158 > l
} else {
yyb158 = r.CheckBreak()
}
if yyb158 {
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
return
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
if r.TryDecodeAsNil() {
x.Items = nil
} else {
yyv163 := &x.Items
yym164 := z.DecBinary()
_ = yym164
if false {
} else {
h.decSliceCluster((*[]Cluster)(yyv163), d)
}
}
for {
yyj158++
if yyhl158 {
yyb158 = yyj158 > l
} else {
yyb158 = r.CheckBreak()
}
if yyb158 {
break
}
z.DecSendContainerState(codecSelfer_containerArrayElem1234)
z.DecStructFieldNotFound(yyj158-1, "")
}
z.DecSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x codecSelfer1234) encSliceServerAddressByClientCIDR(v []ServerAddressByClientCIDR, e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
r.EncodeArrayStart(len(v))
for _, yyv165 := range v {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
yy166 := &yyv165
yy166.CodecEncodeSelf(e)
}
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x codecSelfer1234) decSliceServerAddressByClientCIDR(v *[]ServerAddressByClientCIDR, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yyv167 := *v
yyh167, yyl167 := z.DecSliceHelperStart()
var yyc167 bool
if yyl167 == 0 {
if yyv167 == nil {
yyv167 = []ServerAddressByClientCIDR{}
yyc167 = true
} else if len(yyv167) != 0 {
yyv167 = yyv167[:0]
yyc167 = true
}
} else if yyl167 > 0 {
var yyrr167, yyrl167 int
var yyrt167 bool
if yyl167 > cap(yyv167) {
yyrg167 := len(yyv167) > 0
yyv2167 := yyv167
yyrl167, yyrt167 = z.DecInferLen(yyl167, z.DecBasicHandle().MaxInitLen, 32)
if yyrt167 {
if yyrl167 <= cap(yyv167) {
yyv167 = yyv167[:yyrl167]
} else {
yyv167 = make([]ServerAddressByClientCIDR, yyrl167)
}
} else {
yyv167 = make([]ServerAddressByClientCIDR, yyrl167)
}
yyc167 = true
yyrr167 = len(yyv167)
if yyrg167 {
copy(yyv167, yyv2167)
}
} else if yyl167 != len(yyv167) {
yyv167 = yyv167[:yyl167]
yyc167 = true
}
yyj167 := 0
for ; yyj167 < yyrr167; yyj167++ {
yyh167.ElemContainerState(yyj167)
if r.TryDecodeAsNil() {
yyv167[yyj167] = ServerAddressByClientCIDR{}
} else {
yyv168 := &yyv167[yyj167]
yyv168.CodecDecodeSelf(d)
}
}
if yyrt167 {
for ; yyj167 < yyl167; yyj167++ {
yyv167 = append(yyv167, ServerAddressByClientCIDR{})
yyh167.ElemContainerState(yyj167)
if r.TryDecodeAsNil() {
yyv167[yyj167] = ServerAddressByClientCIDR{}
} else {
yyv169 := &yyv167[yyj167]
yyv169.CodecDecodeSelf(d)
}
}
}
} else {
yyj167 := 0
for ; !r.CheckBreak(); yyj167++ {
if yyj167 >= len(yyv167) {
yyv167 = append(yyv167, ServerAddressByClientCIDR{}) // var yyz167 ServerAddressByClientCIDR
yyc167 = true
}
yyh167.ElemContainerState(yyj167)
if yyj167 < len(yyv167) {
if r.TryDecodeAsNil() {
yyv167[yyj167] = ServerAddressByClientCIDR{}
} else {
yyv170 := &yyv167[yyj167]
yyv170.CodecDecodeSelf(d)
}
} else {
z.DecSwallow()
}
}
if yyj167 < len(yyv167) {
yyv167 = yyv167[:yyj167]
yyc167 = true
} else if yyj167 == 0 && yyv167 == nil {
yyv167 = []ServerAddressByClientCIDR{}
yyc167 = true
}
}
yyh167.End()
if yyc167 {
*v = yyv167
}
}
func (x codecSelfer1234) encSliceClusterCondition(v []ClusterCondition, e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
r.EncodeArrayStart(len(v))
for _, yyv171 := range v {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
yy172 := &yyv171
yy172.CodecEncodeSelf(e)
}
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x codecSelfer1234) decSliceClusterCondition(v *[]ClusterCondition, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yyv173 := *v
yyh173, yyl173 := z.DecSliceHelperStart()
var yyc173 bool
if yyl173 == 0 {
if yyv173 == nil {
yyv173 = []ClusterCondition{}
yyc173 = true
} else if len(yyv173) != 0 {
yyv173 = yyv173[:0]
yyc173 = true
}
} else if yyl173 > 0 {
var yyrr173, yyrl173 int
var yyrt173 bool
if yyl173 > cap(yyv173) {
yyrg173 := len(yyv173) > 0
yyv2173 := yyv173
yyrl173, yyrt173 = z.DecInferLen(yyl173, z.DecBasicHandle().MaxInitLen, 112)
if yyrt173 {
if yyrl173 <= cap(yyv173) {
yyv173 = yyv173[:yyrl173]
} else {
yyv173 = make([]ClusterCondition, yyrl173)
}
} else {
yyv173 = make([]ClusterCondition, yyrl173)
}
yyc173 = true
yyrr173 = len(yyv173)
if yyrg173 {
copy(yyv173, yyv2173)
}
} else if yyl173 != len(yyv173) {
yyv173 = yyv173[:yyl173]
yyc173 = true
}
yyj173 := 0
for ; yyj173 < yyrr173; yyj173++ {
yyh173.ElemContainerState(yyj173)
if r.TryDecodeAsNil() {
yyv173[yyj173] = ClusterCondition{}
} else {
yyv174 := &yyv173[yyj173]
yyv174.CodecDecodeSelf(d)
}
}
if yyrt173 {
for ; yyj173 < yyl173; yyj173++ {
yyv173 = append(yyv173, ClusterCondition{})
yyh173.ElemContainerState(yyj173)
if r.TryDecodeAsNil() {
yyv173[yyj173] = ClusterCondition{}
} else {
yyv175 := &yyv173[yyj173]
yyv175.CodecDecodeSelf(d)
}
}
}
} else {
yyj173 := 0
for ; !r.CheckBreak(); yyj173++ {
if yyj173 >= len(yyv173) {
yyv173 = append(yyv173, ClusterCondition{}) // var yyz173 ClusterCondition
yyc173 = true
}
yyh173.ElemContainerState(yyj173)
if yyj173 < len(yyv173) {
if r.TryDecodeAsNil() {
yyv173[yyj173] = ClusterCondition{}
} else {
yyv176 := &yyv173[yyj173]
yyv176.CodecDecodeSelf(d)
}
} else {
z.DecSwallow()
}
}
if yyj173 < len(yyv173) {
yyv173 = yyv173[:yyj173]
yyc173 = true
} else if yyj173 == 0 && yyv173 == nil {
yyv173 = []ClusterCondition{}
yyc173 = true
}
}
yyh173.End()
if yyc173 {
*v = yyv173
}
}
func (x codecSelfer1234) encSliceCluster(v []Cluster, e *codec1978.Encoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperEncoder(e)
_, _, _ = h, z, r
r.EncodeArrayStart(len(v))
for _, yyv177 := range v {
z.EncSendContainerState(codecSelfer_containerArrayElem1234)
yy178 := &yyv177
yy178.CodecEncodeSelf(e)
}
z.EncSendContainerState(codecSelfer_containerArrayEnd1234)
}
func (x codecSelfer1234) decSliceCluster(v *[]Cluster, d *codec1978.Decoder) {
var h codecSelfer1234
z, r := codec1978.GenHelperDecoder(d)
_, _, _ = h, z, r
yyv179 := *v
yyh179, yyl179 := z.DecSliceHelperStart()
var yyc179 bool
if yyl179 == 0 {
if yyv179 == nil {
yyv179 = []Cluster{}
yyc179 = true
} else if len(yyv179) != 0 {
yyv179 = yyv179[:0]
yyc179 = true
}
} else if yyl179 > 0 {
var yyrr179, yyrl179 int
var yyrt179 bool
if yyl179 > cap(yyv179) {
yyrg179 := len(yyv179) > 0
yyv2179 := yyv179
yyrl179, yyrt179 = z.DecInferLen(yyl179, z.DecBasicHandle().MaxInitLen, 352)
if yyrt179 {
if yyrl179 <= cap(yyv179) {
yyv179 = yyv179[:yyrl179]
} else {
yyv179 = make([]Cluster, yyrl179)
}
} else {
yyv179 = make([]Cluster, yyrl179)
}
yyc179 = true
yyrr179 = len(yyv179)
if yyrg179 {
copy(yyv179, yyv2179)
}
} else if yyl179 != len(yyv179) {
yyv179 = yyv179[:yyl179]
yyc179 = true
}
yyj179 := 0
for ; yyj179 < yyrr179; yyj179++ {
yyh179.ElemContainerState(yyj179)
if r.TryDecodeAsNil() {
yyv179[yyj179] = Cluster{}
} else {
yyv180 := &yyv179[yyj179]
yyv180.CodecDecodeSelf(d)
}
}
if yyrt179 {
for ; yyj179 < yyl179; yyj179++ {
yyv179 = append(yyv179, Cluster{})
yyh179.ElemContainerState(yyj179)
if r.TryDecodeAsNil() {
yyv179[yyj179] = Cluster{}
} else {
yyv181 := &yyv179[yyj179]
yyv181.CodecDecodeSelf(d)
}
}
}
} else {
yyj179 := 0
for ; !r.CheckBreak(); yyj179++ {
if yyj179 >= len(yyv179) {
yyv179 = append(yyv179, Cluster{}) // var yyz179 Cluster
yyc179 = true
}
yyh179.ElemContainerState(yyj179)
if yyj179 < len(yyv179) {
if r.TryDecodeAsNil() {
yyv179[yyj179] = Cluster{}
} else {
yyv182 := &yyv179[yyj179]
yyv182.CodecDecodeSelf(d)
}
} else {
z.DecSwallow()
}
}
if yyj179 < len(yyv179) {
yyv179 = yyv179[:yyj179]
yyc179 = true
} else if yyj179 == 0 && yyv179 == nil {
yyv179 = []Cluster{}
yyc179 = true
}
}
yyh179.End()
if yyc179 {
*v = yyv179
}
}
| luomiao/kops | vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/pkg/federation/apis/federation/v1beta1/types.generated.go | GO | apache-2.0 | 56,435 |
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.vfs.PathFragment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link RelativePackageNameResolver}.
*/
@RunWith(JUnit4.class)
public class RelativePackageNameResolverTest {
private RelativePackageNameResolver resolver;
@Test
public void testRelativePackagesBelowOneLevelWork() throws Exception {
createResolver("foo", true);
assertResolvesTo("bar", "foo/bar");
createResolver("foo/bar", true);
assertResolvesTo("pear", "foo/bar/pear");
}
@Test
public void testRelativePackagesBelowTwoLevelsWork() throws Exception {
createResolver("foo/bar", true);
assertResolvesTo("pear", "foo/bar/pear");
}
@Test
public void testRelativePackagesAboveOneLevelWork() throws Exception {
createResolver("foo", true);
assertResolvesTo("../bar", "bar");
}
@Test
public void testRelativePackagesAboveTwoLevelsWork() throws Exception {
createResolver("foo/bar", true);
assertResolvesTo("../../apple", "apple");
}
@Test
public void testSimpleAbsolutePackagesWork() throws Exception {
createResolver("foo", true);
assertResolvesTo("//foo", "foo");
assertResolvesTo("//foo/bar", "foo/bar");
}
@Test
public void testBuildNotRemoved() throws Exception {
createResolver("foo", false);
assertResolvesTo("bar/BUILD", "foo/bar/BUILD");
}
@Test
public void testBuildRemoved() throws Exception {
createResolver("foo", true);
assertResolvesTo("bar/BUILD", "foo/bar");
}
@Test
public void testEmptyOffset() throws Exception {
createResolver("", true);
assertResolvesTo("bar", "bar");
assertResolvesTo("bar/qux", "bar/qux");
}
@Test
public void testTooFarUpwardsOneLevelThrows() throws Exception {
createResolver("foo", true);
try {
resolver.resolve("../../bar");
fail("InvalidPackageNameException expected");
} catch (InvalidPackageNameException e) {
// good
}
}
@Test
public void testTooFarUpwardsTwoLevelsThrows() throws Exception {
createResolver("foo/bar", true);
assertResolvesTo("../../orange", "orange");
try {
resolver.resolve("../../../orange");
fail("InvalidPackageNameException expected");
} catch (InvalidPackageNameException e) {
// good
}
}
private void createResolver(String offset, boolean discardBuild) {
resolver = new RelativePackageNameResolver(new PathFragment(offset), discardBuild);
}
private void assertResolvesTo(String relative, String expectedAbsolute) throws Exception {
String result = resolver.resolve(relative);
assertEquals(expectedAbsolute, result);
}
}
| hhclam/bazel | src/test/java/com/google/devtools/build/lib/packages/RelativePackageNameResolverTest.java | Java | apache-2.0 | 3,458 |
<?php
/*
* Copyright 2014 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.
*/
class Google_Service_Dns_DnsKeysListResponse extends Google_Collection
{
protected $collection_key = 'dnsKeys';
protected $dnsKeysType = 'Google_Service_Dns_DnsKey';
protected $dnsKeysDataType = 'array';
protected $headerType = 'Google_Service_Dns_ResponseHeader';
protected $headerDataType = '';
public $kind;
public $nextPageToken;
/**
* @param Google_Service_Dns_DnsKey
*/
public function setDnsKeys($dnsKeys)
{
$this->dnsKeys = $dnsKeys;
}
/**
* @return Google_Service_Dns_DnsKey
*/
public function getDnsKeys()
{
return $this->dnsKeys;
}
/**
* @param Google_Service_Dns_ResponseHeader
*/
public function setHeader(Google_Service_Dns_ResponseHeader $header)
{
$this->header = $header;
}
/**
* @return Google_Service_Dns_ResponseHeader
*/
public function getHeader()
{
return $this->header;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
| drthomas21/WordPress_Tutorial | wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/Dns/DnsKeysListResponse.php | PHP | apache-2.0 | 1,789 |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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 net.java.sip.communicator.plugin.desktoputil;
import java.awt.image.*;
import java.lang.reflect.*;
import java.net.*;
import java.security.cert.*;
import javax.imageio.*;
import javax.swing.*;
import net.java.sip.communicator.service.browserlauncher.*;
import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.service.credentialsstorage.*;
import net.java.sip.communicator.service.globaldisplaydetails.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.keybindings.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.audionotifier.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.fileaccess.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.resources.*;
import org.osgi.framework.*;
public class DesktopUtilActivator
implements BundleActivator,
VerifyCertificateDialogService
{
/**
* The <tt>Logger</tt> used by the <tt>SwingUtilActivator</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(DesktopUtilActivator.class);
private static ConfigurationService configurationService;
private static ResourceManagementService resourceService;
private static KeybindingsService keybindingsService;
private static BrowserLauncherService browserLauncherService;
private static UIService uiService;
private static AccountManager accountManager;
private static FileAccessService fileAccessService;
private static MediaService mediaService;
private static AudioNotifierService audioNotifierService;
private static GlobalDisplayDetailsService globalDisplayDetailsService;
static BundleContext bundleContext;
/**
* Calls <tt>Thread.setUncaughtExceptionHandler()</tt>
*
* @param context The execution context of the bundle being started
* (unused).
* @throws Exception If this method throws an exception, this bundle is
* marked as stopped and the Framework will remove this bundle's
* listeners, unregister all services registered by this bundle, and
* release all services used by this bundle.
*/
public void start(BundleContext context) throws Exception
{
bundleContext = context;
// register the VerifyCertificateDialogService
bundleContext.registerService(
VerifyCertificateDialogService.class.getName(),
this,
null);
bundleContext.registerService(
MasterPasswordInputService.class.getName(),
new MasterPasswordInputService()
{
public String showInputDialog(boolean prevSuccess)
{
return MasterPasswordInputDialog.showInput(prevSuccess);
}
},
null);
bundleContext.registerService(
AuthenticationWindowService.class.getName(),
new AuthenticationWindowService()
{
public AuthenticationWindow create(
String userName,
char[] password,
String server,
boolean isUserNameEditable,
boolean isRememberPassword,
Object icon,
String windowTitle,
String windowText,
String usernameLabelText,
String passwordLabelText,
String errorMessage,
String signupLink)
{
ImageIcon imageIcon = null;
if(icon instanceof ImageIcon)
imageIcon = (ImageIcon)icon;
AuthenticationWindowCreator creator
= new AuthenticationWindowCreator(
userName,
password,
server,
isUserNameEditable,
isRememberPassword,
imageIcon,
windowTitle,
windowText,
usernameLabelText,
passwordLabelText,
errorMessage,
signupLink);
try
{
SwingUtilities.invokeAndWait(creator);
}
catch(InterruptedException e)
{
logger.error("Error creating dialog", e);
}
catch(InvocationTargetException e)
{
logger.error("Error creating dialog", e);
}
return creator.authenticationWindow;
}
},
null);
}
/**
* Doesn't do anything.
*
* @param context The execution context of the bundle being stopped.
* @throws Exception If this method throws an exception, the bundle is
* still marked as stopped, and the Framework will remove the bundle's
* listeners, unregister all services registered by the bundle, and
* release all services used by the bundle.
*/
public void stop(BundleContext context)
throws Exception
{
}
/**
* Returns the <tt>ConfigurationService</tt> currently registered.
*
* @return the <tt>ConfigurationService</tt>
*/
public static ConfigurationService getConfigurationService()
{
if (configurationService == null)
{
configurationService
= ServiceUtils.getService(
bundleContext,
ConfigurationService.class);
}
return configurationService;
}
/**
* Returns the service giving access to all application resources.
*
* @return the service giving access to all application resources.
*/
public static ResourceManagementService getResources()
{
if (resourceService == null)
{
resourceService
= ResourceManagementServiceUtils.getService(bundleContext);
}
return resourceService;
}
/**
* Returns the image corresponding to the given <tt>imageID</tt>.
*
* @param imageID the identifier of the image
* @return the image corresponding to the given <tt>imageID</tt>
*/
public static BufferedImage getImage(String imageID)
{
BufferedImage image = null;
URL path = getResources().getImageURL(imageID);
if (path == null)
return null;
try
{
image = ImageIO.read(path);
}
catch (Exception exc)
{
logger.error("Failed to load image:" + path, exc);
}
return image;
}
/**
* Returns the <tt>KeybindingsService</tt> currently registered.
*
* @return the <tt>KeybindingsService</tt>
*/
public static KeybindingsService getKeybindingsService()
{
if (keybindingsService == null)
{
keybindingsService
= ServiceUtils.getService(
bundleContext,
KeybindingsService.class);
}
return keybindingsService;
}
/**
* Returns the <tt>BrowserLauncherService</tt> obtained from the bundle
* context.
* @return the <tt>BrowserLauncherService</tt> obtained from the bundle
* context
*/
public static BrowserLauncherService getBrowserLauncher()
{
if (browserLauncherService == null)
{
browserLauncherService
= ServiceUtils.getService(
bundleContext,
BrowserLauncherService.class);
}
return browserLauncherService;
}
/**
* Gets the <tt>UIService</tt> instance registered in the
* <tt>BundleContext</tt> of the <tt>UtilActivator</tt>.
*
* @return the <tt>UIService</tt> instance registered in the
* <tt>BundleContext</tt> of the <tt>UtilActivator</tt>
*/
public static UIService getUIService()
{
if (uiService == null)
uiService = ServiceUtils.getService(bundleContext, UIService.class);
return uiService;
}
/**
* Creates the dialog.
*
* @param certs the certificates list
* @param title The title of the dialog; when null the resource
* <tt>service.gui.CERT_DIALOG_TITLE</tt> is loaded and used.
* @param message A text that describes why the verification failed.
*/
public VerifyCertificateDialog createDialog(
Certificate[] certs, String title, String message)
{
VerifyCertificateDialogCreator creator
= new VerifyCertificateDialogCreator(certs, title, message);
try
{
SwingUtilities.invokeAndWait(creator);
}
catch(InterruptedException e)
{
logger.error("Error creating dialog", e);
}
catch(InvocationTargetException e)
{
logger.error("Error creating dialog", e);
}
return creator.dialog;
}
/**
* Returns the <tt>AccountManager</tt> obtained from the bundle context.
* @return the <tt>AccountManager</tt> obtained from the bundle context
*/
public static AccountManager getAccountManager()
{
if(accountManager == null)
{
accountManager
= ServiceUtils.getService(bundleContext, AccountManager.class);
}
return accountManager;
}
/**
* Returns the <tt>FileAccessService</tt> obtained from the bundle context.
*
* @return the <tt>FileAccessService</tt> obtained from the bundle context
*/
public static FileAccessService getFileAccessService()
{
if (fileAccessService == null)
{
fileAccessService
= ServiceUtils.getService(
bundleContext,
FileAccessService.class);
}
return fileAccessService;
}
/**
* Returns an instance of the <tt>MediaService</tt> obtained from the
* bundle context.
* @return an instance of the <tt>MediaService</tt> obtained from the
* bundle context
*/
public static MediaService getMediaService()
{
if (mediaService == null)
{
mediaService
= ServiceUtils.getService(bundleContext, MediaService.class);
}
return mediaService;
}
/**
* Returns the <tt>AudioNotifierService</tt> obtained from the bundle
* context.
* @return the <tt>AudioNotifierService</tt> obtained from the bundle
* context
*/
public static AudioNotifierService getAudioNotifier()
{
if (audioNotifierService == null)
{
audioNotifierService
= ServiceUtils.getService(
bundleContext,
AudioNotifierService.class);
}
return audioNotifierService;
}
/**
* Returns the <tt>GlobalDisplayDetailsService</tt> obtained from the bundle
* context.
*
* @return the <tt>GlobalDisplayDetailsService</tt> obtained from the bundle
* context
*/
public static GlobalDisplayDetailsService getGlobalDisplayDetailsService()
{
if (globalDisplayDetailsService == null)
{
globalDisplayDetailsService
= ServiceUtils.getService(
bundleContext,
GlobalDisplayDetailsService.class);
}
return globalDisplayDetailsService;
}
/**
* Runnable to create verify dialog.
*/
private class VerifyCertificateDialogCreator
implements Runnable
{
/**
* Certs.
*/
private final Certificate[] certs;
/**
* Dialog title.
*/
private final String title;
/**
* Dialog message.
*/
private final String message;
/**
* The result dialog.
*/
VerifyCertificateDialogImpl dialog = null;
/**
* Constructs.
* @param certs the certificates list
* @param title The title of the dialog; when null the resource
* <tt>service.gui.CERT_DIALOG_TITLE</tt> is loaded and used.
* @param message A text that describes why the verification failed.
*/
private VerifyCertificateDialogCreator(
Certificate[] certs, String title, String message)
{
this.certs = certs;
this.title = title;
this.message = message;
}
@Override
public void run()
{
dialog = new VerifyCertificateDialogImpl(certs, title, message);
}
}
/**
* Runnable to create auth window.
*/
private class AuthenticationWindowCreator
implements Runnable
{
String userName;
char[] password;
String server;
boolean isUserNameEditable;
boolean isRememberPassword;
String windowTitle;
String windowText;
String usernameLabelText;
String passwordLabelText;
String errorMessage;
String signupLink;
ImageIcon imageIcon;
AuthenticationWindowService.AuthenticationWindow authenticationWindow;
/**
* Creates an instance of the <tt>AuthenticationWindow</tt>
* implementation.
*
* @param server the server name
* @param isUserNameEditable indicates if the user name is editable
* @param imageIcon the icon to display on the left of
* the authentication window
* @param windowTitle customized window title
* @param windowText customized window text
* @param usernameLabelText customized username field label text
* @param passwordLabelText customized password field label text
* @param errorMessage an error message if this dialog is shown
* to indicate the user that something went wrong
* @param signupLink an URL that allows the user to sign up
*/
public AuthenticationWindowCreator(String userName,
char[] password,
String server,
boolean isUserNameEditable,
boolean isRememberPassword,
ImageIcon imageIcon,
String windowTitle,
String windowText,
String usernameLabelText,
String passwordLabelText,
String errorMessage,
String signupLink)
{
this.userName = userName;
this.password = password;
this.server = server;
this.isUserNameEditable = isUserNameEditable;
this.isRememberPassword = isRememberPassword;
this.windowTitle = windowTitle;
this.windowText = windowText;
this.usernameLabelText = usernameLabelText;
this.passwordLabelText = passwordLabelText;
this.errorMessage = errorMessage;
this.signupLink = signupLink;
this.imageIcon = imageIcon;
}
@Override
public void run()
{
authenticationWindow
= new net.java.sip.communicator.plugin.desktoputil
.AuthenticationWindow(
userName, password,
server,
isUserNameEditable, isRememberPassword,
imageIcon,
windowTitle, windowText,
usernameLabelText, passwordLabelText,
errorMessage,
signupLink);
}
}
}
| gpolitis/jitsi | src/net/java/sip/communicator/plugin/desktoputil/DesktopUtilActivator.java | Java | apache-2.0 | 17,284 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.http.netty4;
import io.netty.channel.Channel;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.core.CompletableContext;
import org.elasticsearch.http.HttpChannel;
import org.elasticsearch.http.HttpResponse;
import org.elasticsearch.transport.netty4.Netty4TcpChannel;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class Netty4HttpChannel implements HttpChannel {
private final Channel channel;
private final CompletableContext<Void> closeContext = new CompletableContext<>();
Netty4HttpChannel(Channel channel) {
this.channel = channel;
Netty4TcpChannel.addListener(this.channel.closeFuture(), closeContext);
}
@Override
public void sendResponse(HttpResponse response, ActionListener<Void> listener) {
channel.writeAndFlush(response, Netty4TcpChannel.addPromise(listener, channel));
}
@Override
public InetSocketAddress getLocalAddress() {
return castAddressOrNull(channel.localAddress());
}
@Override
public InetSocketAddress getRemoteAddress() {
return castAddressOrNull(channel.remoteAddress());
}
private static InetSocketAddress castAddressOrNull(SocketAddress socketAddress) {
if (socketAddress instanceof InetSocketAddress) {
return (InetSocketAddress) socketAddress;
} else {
return null;
}
}
@Override
public void addCloseListener(ActionListener<Void> listener) {
closeContext.addListener(ActionListener.toBiConsumer(listener));
}
@Override
public boolean isOpen() {
return channel.isOpen();
}
@Override
public void close() {
channel.close();
}
public Channel getNettyChannel() {
return channel;
}
@Override
public String toString() {
return "Netty4HttpChannel{" + "localAddress=" + getLocalAddress() + ", remoteAddress=" + getRemoteAddress() + '}';
}
}
| GlenRSmith/elasticsearch | modules/transport-netty4/src/main/java/org/elasticsearch/http/netty4/Netty4HttpChannel.java | Java | apache-2.0 | 2,353 |
/*******************************************************************************
*
* Copyright (c) 2013, 2014 Intel Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* The Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* David Navarro, Intel Corporation - initial API and implementation
* Julien Vermillard, Sierra Wireless
* Bosch Software Innovations GmbH - Please refer to git log
* Pascal Rieux - Please refer to git log
*
*******************************************************************************/
/*
* Resources:
*
* Name | ID | Operations | Instances | Mandatory | Type | Range | Units |
* Short ID | 0 | R | Single | Yes | Integer | 1-65535 | |
* Lifetime | 1 | R/W | Single | Yes | Integer | | s |
* Default Min Period | 2 | R/W | Single | No | Integer | | s |
* Default Max Period | 3 | R/W | Single | No | Integer | | s |
* Disable | 4 | E | Single | No | | | |
* Disable Timeout | 5 | R/W | Single | No | Integer | | s |
* Notification Storing | 6 | R/W | Single | Yes | Boolean | | |
* Binding | 7 | R/W | Single | Yes | String | | |
* Registration Update | 8 | E | Single | Yes | | | |
*
*/
#include <protocols/liblwm2m.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _server_instance_
{
struct _server_instance_ * next; // matches lwm2m_list_t::next
uint16_t instanceId; // matches lwm2m_list_t::id
uint16_t shortServerId;
uint32_t lifetime;
bool storing;
char binding[4];
} server_instance_t;
static uint8_t prv_get_value(lwm2m_data_t * dataP,
server_instance_t * targetP)
{
switch (dataP->id)
{
case LWM2M_SERVER_SHORT_ID_ID:
lwm2m_data_encode_int(targetP->shortServerId, dataP);
return COAP_205_CONTENT;
case LWM2M_SERVER_LIFETIME_ID:
lwm2m_data_encode_int(targetP->lifetime, dataP);
return COAP_205_CONTENT;
case LWM2M_SERVER_DISABLE_ID:
return COAP_405_METHOD_NOT_ALLOWED;
case LWM2M_SERVER_STORING_ID:
lwm2m_data_encode_bool(targetP->storing, dataP);
return COAP_205_CONTENT;
case LWM2M_SERVER_BINDING_ID:
lwm2m_data_encode_string(targetP->binding, dataP);
return COAP_205_CONTENT;
case LWM2M_SERVER_UPDATE_ID:
return COAP_405_METHOD_NOT_ALLOWED;
default:
return COAP_404_NOT_FOUND;
}
}
static uint8_t prv_server_read(uint16_t instanceId,
int * numDataP,
lwm2m_data_t ** dataArrayP,
lwm2m_object_t * objectP)
{
server_instance_t * targetP;
uint8_t result;
int i;
targetP = (server_instance_t *)lwm2m_list_find(objectP->instanceList, instanceId);
if (NULL == targetP) return COAP_404_NOT_FOUND;
// is the server asking for the full instance ?
if (*numDataP == 0)
{
uint16_t resList[] = {
LWM2M_SERVER_SHORT_ID_ID,
LWM2M_SERVER_LIFETIME_ID,
LWM2M_SERVER_STORING_ID,
LWM2M_SERVER_BINDING_ID
};
int nbRes = sizeof(resList)/sizeof(uint16_t);
*dataArrayP = lwm2m_data_new(nbRes);
if (*dataArrayP == NULL) return COAP_500_INTERNAL_SERVER_ERROR;
*numDataP = nbRes;
for (i = 0 ; i < nbRes ; i++)
{
(*dataArrayP)[i].id = resList[i];
}
}
i = 0;
do
{
result = prv_get_value((*dataArrayP) + i, targetP);
i++;
} while (i < *numDataP && result == COAP_205_CONTENT);
return result;
}
static uint8_t prv_server_discover(uint16_t instanceId,
int * numDataP,
lwm2m_data_t ** dataArrayP,
lwm2m_object_t * objectP)
{
uint8_t result;
int i;
result = COAP_205_CONTENT;
// is the server asking for the full object ?
if (*numDataP == 0)
{
uint16_t resList[] = {
LWM2M_SERVER_SHORT_ID_ID,
LWM2M_SERVER_LIFETIME_ID,
LWM2M_SERVER_MIN_PERIOD_ID,
LWM2M_SERVER_MAX_PERIOD_ID,
LWM2M_SERVER_DISABLE_ID,
LWM2M_SERVER_TIMEOUT_ID,
LWM2M_SERVER_STORING_ID,
LWM2M_SERVER_BINDING_ID,
LWM2M_SERVER_UPDATE_ID
};
int nbRes = sizeof(resList)/sizeof(uint16_t);
*dataArrayP = lwm2m_data_new(nbRes);
if (*dataArrayP == NULL) return COAP_500_INTERNAL_SERVER_ERROR;
*numDataP = nbRes;
for (i = 0 ; i < nbRes ; i++)
{
(*dataArrayP)[i].id = resList[i];
}
}
else
{
for (i = 0; i < *numDataP && result == COAP_205_CONTENT; i++)
{
switch ((*dataArrayP)[i].id)
{
case LWM2M_SERVER_SHORT_ID_ID:
case LWM2M_SERVER_LIFETIME_ID:
case LWM2M_SERVER_MIN_PERIOD_ID:
case LWM2M_SERVER_MAX_PERIOD_ID:
case LWM2M_SERVER_DISABLE_ID:
case LWM2M_SERVER_TIMEOUT_ID:
case LWM2M_SERVER_STORING_ID:
case LWM2M_SERVER_BINDING_ID:
case LWM2M_SERVER_UPDATE_ID:
break;
default:
result = COAP_404_NOT_FOUND;
}
}
}
return result;
}
static uint8_t prv_set_int_value(lwm2m_data_t * dataArray,
uint32_t * data)
{
uint8_t result;
int64_t value;
if (1 == lwm2m_data_decode_int(dataArray, &value))
{
if (value >= 0 && value <= 0xFFFFFFFF)
{
*data = value;
result = COAP_204_CHANGED;
}
else
{
result = COAP_406_NOT_ACCEPTABLE;
}
}
else
{
result = COAP_400_BAD_REQUEST;
}
return result;
}
static uint8_t prv_server_write(uint16_t instanceId,
int numData,
lwm2m_data_t * dataArray,
lwm2m_object_t * objectP)
{
server_instance_t * targetP;
int i;
uint8_t result;
targetP = (server_instance_t *)lwm2m_list_find(objectP->instanceList, instanceId);
if (NULL == targetP)
{
return COAP_404_NOT_FOUND;
}
i = 0;
do
{
switch (dataArray[i].id)
{
case LWM2M_SERVER_SHORT_ID_ID:
{
uint32_t value;
result = prv_set_int_value(dataArray + i, &value);
if (COAP_204_CHANGED == result)
{
if (0 < value && value <= 0xFFFF)
{
targetP->shortServerId = value;
}
else
{
result = COAP_406_NOT_ACCEPTABLE;
}
}
}
break;
case LWM2M_SERVER_LIFETIME_ID:
result = prv_set_int_value(dataArray + i, (uint32_t *)&(targetP->lifetime));
break;
case LWM2M_SERVER_DISABLE_ID:
result = COAP_405_METHOD_NOT_ALLOWED;
break;
case LWM2M_SERVER_STORING_ID:
{
bool value;
if (1 == lwm2m_data_decode_bool(dataArray + i, &value))
{
targetP->storing = value;
result = COAP_204_CHANGED;
}
else
{
result = COAP_400_BAD_REQUEST;
}
}
break;
case LWM2M_SERVER_BINDING_ID:
if ((dataArray[i].type == LWM2M_TYPE_STRING || dataArray[i].type == LWM2M_TYPE_OPAQUE)
&& dataArray[i].value.asBuffer.length > 0 && dataArray[i].value.asBuffer.length <= 3
&& (strncmp((char*)dataArray[i].value.asBuffer.buffer, "U", dataArray[i].value.asBuffer.length) == 0
|| strncmp((char*)dataArray[i].value.asBuffer.buffer, "UQ", dataArray[i].value.asBuffer.length) == 0
|| strncmp((char*)dataArray[i].value.asBuffer.buffer, "S", dataArray[i].value.asBuffer.length) == 0
|| strncmp((char*)dataArray[i].value.asBuffer.buffer, "SQ", dataArray[i].value.asBuffer.length) == 0
|| strncmp((char*)dataArray[i].value.asBuffer.buffer, "US", dataArray[i].value.asBuffer.length) == 0
|| strncmp((char*)dataArray[i].value.asBuffer.buffer, "UQS", dataArray[i].value.asBuffer.length) == 0))
{
strncpy(targetP->binding, (char*)dataArray[i].value.asBuffer.buffer, dataArray[i].value.asBuffer.length);
result = COAP_204_CHANGED;
}
else
{
result = COAP_400_BAD_REQUEST;
}
break;
case LWM2M_SERVER_UPDATE_ID:
result = COAP_405_METHOD_NOT_ALLOWED;
break;
default:
return COAP_404_NOT_FOUND;
}
i++;
} while (i < numData && result == COAP_204_CHANGED);
return result;
}
static uint8_t prv_server_execute(uint16_t instanceId,
uint16_t resourceId,
uint8_t * buffer,
int length,
lwm2m_object_t * objectP)
{
server_instance_t * targetP;
targetP = (server_instance_t *)lwm2m_list_find(objectP->instanceList, instanceId);
if (NULL == targetP) return COAP_404_NOT_FOUND;
switch (resourceId)
{
case LWM2M_SERVER_DISABLE_ID:
// executed in core, if COAP_204_CHANGED is returned
return COAP_204_CHANGED;
case LWM2M_SERVER_UPDATE_ID:
// executed in core, if COAP_204_CHANGED is returned
return COAP_204_CHANGED;
default:
return COAP_405_METHOD_NOT_ALLOWED;
}
}
static uint8_t prv_server_delete(uint16_t id,
lwm2m_object_t * objectP)
{
server_instance_t * serverInstance;
objectP->instanceList = lwm2m_list_remove(objectP->instanceList, id, (lwm2m_list_t **)&serverInstance);
if (NULL == serverInstance) return COAP_404_NOT_FOUND;
lwm2m_free(serverInstance);
return COAP_202_DELETED;
}
static uint8_t prv_server_create(uint16_t instanceId,
int numData,
lwm2m_data_t * dataArray,
lwm2m_object_t * objectP)
{
server_instance_t * serverInstance;
uint8_t result;
serverInstance = (server_instance_t *)lwm2m_malloc(sizeof(server_instance_t));
if (NULL == serverInstance) return COAP_500_INTERNAL_SERVER_ERROR;
memset(serverInstance, 0, sizeof(server_instance_t));
serverInstance->instanceId = instanceId;
objectP->instanceList = LWM2M_LIST_ADD(objectP->instanceList, serverInstance);
result = prv_server_write(instanceId, numData, dataArray, objectP);
if (result != COAP_204_CHANGED)
{
(void)prv_server_delete(instanceId, objectP);
}
else
{
result = COAP_201_CREATED;
}
return result;
}
lwm2m_object_t * get_server_object()
{
lwm2m_object_t * serverObj;
serverObj = (lwm2m_object_t *)lwm2m_malloc(sizeof(lwm2m_object_t));
if (NULL != serverObj)
{
server_instance_t * serverInstance;
memset(serverObj, 0, sizeof(lwm2m_object_t));
serverObj->objID = 1;
// Manually create an hardcoded server
serverInstance = (server_instance_t *)lwm2m_malloc(sizeof(server_instance_t));
if (NULL == serverInstance)
{
lwm2m_free(serverObj);
return NULL;
}
memset(serverInstance, 0, sizeof(server_instance_t));
serverInstance->instanceId = 0;
serverInstance->shortServerId = 123;
serverInstance->lifetime = 300;
serverInstance->storing = false;
serverInstance->binding[0] = 'U';
serverObj->instanceList = LWM2M_LIST_ADD(serverObj->instanceList, serverInstance);
serverObj->readFunc = prv_server_read;
serverObj->writeFunc = prv_server_write;
serverObj->createFunc = prv_server_create;
serverObj->deleteFunc = prv_server_delete;
serverObj->executeFunc = prv_server_execute;
serverObj->discoverFunc = prv_server_discover;
}
return serverObj;
}
void free_server_object(lwm2m_object_t * object)
{
while (object->instanceList != NULL)
{
server_instance_t * serverInstance = (server_instance_t *)object->instanceList;
object->instanceList = object->instanceList->next;
lwm2m_free(serverInstance);
}
lwm2m_free(object);
}
| an4967/TizenRT | external/wakaama/examples/lightclient/object_server.c | C | apache-2.0 | 13,363 |
---
license: >
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.
title: Amazon Fire OS Webansichten für
---
# Amazon Fire OS Webansichten für
Beginnend mit 3.0.0, können Sie Cordova als Komponente in Amazon-Feuer-OS-Anwendungen. Amazon Fire OS bezieht sich auf diese Komponente als `CordovaWebView` . `CordovaWebView`erweitert Amazon WebView, die auf der open-Source-Projekt Chromium basiert. Durch die Nutzung dieser Funktion, können Ihre Webanwendungen der neuesten HTML5-Web-Standards, die in einem modernen Web-Runtime-Engine ausgeführt nutzen.
## Voraussetzungen
* Cordova 3.0.0 oder größer
* Android SDK aktualisiert, um neuesten SDK
* Amazon WebView SDK
## Anleitung zur Verwendung von CordovaWebView in einem Amazon-Feuer-OS-Projekt
1. Download [Amazon WebView SDK][1] zu erweitern, und kopieren Sie die awv_interface.jar in `/framework/libs` Verzeichnis. Erstellen einer Libs / Ordner, wenn es nicht vorhanden ist.
2. `cd`in `/framework` und `ant jar` baut die Cordova-Jar. Es schafft die .jar-Datei als `cordova-x.x.x.jar` in das `/framework` Verzeichnis.
3. Bearbeiten der Anwendung `main.xml` Datei (unter `/res/layout` ) mit folgenden Aussehen der `layout_height` , `layout_width` und `id` Ihrer Anwendung angepasst:
<org.apache.cordova.CordovaWebView
android:id="@+id/tutorialView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
4. Ihre Aktivität ändern, sodass es implementiert die `CordovaInterface` . Sie sollten die enthaltenen Methoden implementieren. Vielleicht möchten Sie Kopieren von `/framework/src/org/apache/cordova/CordovaActivity.java` , oder setzen sie auf eigene Faust. Das folgende Codefragment zeigt eine einfache Anwendung, die die Schnittstelle verwendet. Beachten Sie, wie die referenzierten anzeigen-Id entspricht der `id` in das XML-Fragment oben angegebene Attribut:
public class CordovaViewTestActivity extends Activity implements CordovaInterface {
CordovaWebView cwv;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cwv = (CordovaWebView) findViewById(R.id.tutorialView);
Config.init(this);
cwv.loadUrl(Config.getStartUrl());
}
[1]: https://developer.amazon.com/sdk/fire/IntegratingAWV.html#installawv
Wenn Sie die Kamera verwenden, sollten Sie dies auch implementieren:
@Override
public void setActivityResultCallback(CordovaPlugin plugin) {
this.activityResultCallback = plugin;
}
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method is called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
@Override
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
CordovaPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
Denken Sie daran, den Threadpool hinzufügen, sonst die Plugins keine Threads ausgeführt:
@Override
public ExecutorService getThreadPool() {
return threadPool;
}
1. Kopieren Sie Ihre Anwendung HTML und JavaScript-Dateien zu Ihrem Amazon-Feuer-OS-Projekts `/assets/www` Verzeichnis.
2. Kopie `config.xml` von `/framework/res/xml` zu Ihrem Projekts `/res/xml` Verzeichnis. | Icenium/cordova-docs | www/docs/de/3.5.0/guide/platforms/amazonfireos/webview.md | Markdown | apache-2.0 | 5,923 |
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/framework/variant_encode_decode.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/gather_functor.h"
#include "tensorflow/core/platform/mem.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/util.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
template <typename Device, typename T, typename Index>
class GatherOp : public OpKernel {
public:
// QUESTION: It'd be nice to support DT_INT16, DT_UINT8,
// etc. here for the type of the second input argument. Should
// we have the framework do some sort of integer promotion
// automatically, or should that be something that users have to
// do explicitly with a conversion operator in the graph?
explicit GatherOp(OpKernelConstruction* c) : OpKernel(c) {}
void Compute(OpKernelContext* c) override {
const Tensor& params = c->input(0);
const Tensor& indices = c->input(1);
OP_REQUIRES(
c, TensorShapeUtils::IsVectorOrHigher(params.shape()),
errors::InvalidArgument("params must be at least 1 dimensional"));
// GatherV2 added an axis argument. For backwards compatibility with Gather,
// fall back to axis 0 if the op does not have an axis input.
int64 axis = 0;
if (c->num_inputs() == 3) {
const Tensor& axis_tensor = c->input(2);
OP_REQUIRES(c, TensorShapeUtils::IsScalar(axis_tensor.shape()),
errors::InvalidArgument("axis must be scalar"));
if (axis_tensor.dtype() == DT_INT32) {
axis = axis_tensor.scalar<int32>()();
} else if (axis_tensor.dtype() == DT_INT64) {
axis = axis_tensor.scalar<int64>()();
} else {
OP_REQUIRES(c, false,
errors::InvalidArgument("axis must be int32 or int64."));
}
}
OP_REQUIRES(
c, axis >= -params.dims() && axis < params.dims(),
errors::InvalidArgument("Expected axis in the range [", -params.dims(),
", ", params.dims(), "), but got ", axis));
if (axis < 0) {
axis = params.dims() + axis;
}
// Check that we have enough index space
const int64 gather_dim_size = params.dim_size(axis);
const int64 N = indices.NumElements();
OP_REQUIRES(
c, gather_dim_size <= std::numeric_limits<Index>::max(),
errors::InvalidArgument("params.shape[", axis, "] too large for ",
DataTypeString(DataTypeToEnum<Index>::v()),
" indexing: ", gather_dim_size, " > ",
std::numeric_limits<Index>::max()));
// The result shape is params.shape[0:axis] + indices.shape +
// params.shape[axis + 1:].
TensorShape result_shape;
int64 outer_size = 1;
int64 inner_size = 1;
for (int i = 0; i < axis; i++) {
result_shape.AddDim(params.dim_size(i));
outer_size *= params.dim_size(i);
}
result_shape.AppendShape(indices.shape());
for (int i = axis + 1; i < params.dims(); i++) {
result_shape.AddDim(params.dim_size(i));
inner_size *= params.dim_size(i);
}
Tensor* out = nullptr;
OP_REQUIRES_OK(c, c->allocate_output(0, result_shape, &out));
if (N > 0 && outer_size > 0 && inner_size > 0) {
auto params_flat =
params.shaped<T, 3>({outer_size, gather_dim_size, inner_size});
auto indices_flat = indices.flat<Index>();
auto out_flat = out->shaped<T, 3>({outer_size, N, inner_size});
functor::GatherFunctor<Device, T, Index> functor;
int64 bad_i = functor(c, params_flat, indices_flat, out_flat);
OP_REQUIRES(
c, bad_i < 0,
errors::InvalidArgument(
"indices", SliceDebugString(indices.shape(), bad_i), " = ",
indices_flat(bad_i), " is not in [0, ", gather_dim_size, ")"));
}
}
};
#define REGISTER_GATHER_FULL(dev, type, index_type) \
REGISTER_KERNEL_BUILDER(Name("Gather") \
.Device(DEVICE_##dev) \
.TypeConstraint<type>("Tparams") \
.TypeConstraint<index_type>("Tindices"), \
GatherOp<dev##Device, type, index_type>); \
REGISTER_KERNEL_BUILDER(Name("GatherV2") \
.Device(DEVICE_##dev) \
.TypeConstraint<type>("Tparams") \
.TypeConstraint<index_type>("Tindices") \
.HostMemory("axis"), \
GatherOp<dev##Device, type, index_type>)
#define REGISTER_GATHER_ALL_INDICES(dev, type) \
REGISTER_GATHER_FULL(dev, type, int32); \
REGISTER_GATHER_FULL(dev, type, int64)
#define REGISTER_GATHER_CPU(type) REGISTER_GATHER_ALL_INDICES(CPU, type)
// Registration of the CPU implementations.
TF_CALL_ALL_TYPES(REGISTER_GATHER_CPU);
TF_CALL_QUANTIZED_TYPES(REGISTER_GATHER_CPU);
TF_CALL_quint16(REGISTER_GATHER_CPU);
TF_CALL_qint16(REGISTER_GATHER_CPU);
TF_CALL_uint32(REGISTER_GATHER_CPU);
TF_CALL_uint64(REGISTER_GATHER_CPU);
#undef REGISTER_GATHER_CPU
#if GOOGLE_CUDA
// Registration of the GPU implementations.
#define REGISTER_GATHER_GPU(type) REGISTER_GATHER_ALL_INDICES(GPU, type)
TF_CALL_int64(REGISTER_GATHER_GPU);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GATHER_GPU);
TF_CALL_complex64(REGISTER_GATHER_GPU);
TF_CALL_complex128(REGISTER_GATHER_GPU);
#undef REGISTER_GATHER_GPU
#endif // GOOGLE_CUDA
#undef REGISTER_GATHER_ALL_INDICES
#undef REGISTER_GATHER_FULL
} // namespace tensorflow
| nburn42/tensorflow | tensorflow/core/kernels/gather_op.cc | C++ | apache-2.0 | 6,663 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This class helps to remember what domains may be needed to be resolved when a
// navigation takes place to a given URL. This information is gathered when a
// navigation to a subresource identifies a referring URL.
// When future navigations take place to known referrer sites, then we
// speculatively either pre-warm a TCP/IP conneciton, or at a minimum, resolve
// the host name via DNS.
// All access to this class is performed via the Predictor class, which only
// operates on the IO thread.
#ifndef CHROME_BROWSER_NET_REFERRER_H_
#define CHROME_BROWSER_NET_REFERRER_H_
#include <map>
#include "base/basictypes.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "net/base/host_port_pair.h"
namespace base {
class Value;
}
namespace chrome_browser_net {
//------------------------------------------------------------------------------
// For each hostname in a Referrer, we have a ReferrerValue. It indicates
// exactly how much value (re: latency reduction, or connection use) has
// resulted from having this entry.
class ReferrerValue {
public:
ReferrerValue();
// Used during deserialization.
void SetSubresourceUseRate(double rate) { subresource_use_rate_ = rate; }
base::Time birth_time() const { return birth_time_; }
// Record the fact that we navigated to the associated subresource URL. This
// will increase the value of the expected subresource_use_rate_
void SubresourceIsNeeded();
// Record the fact that the referrer of this subresource was observed. This
// will diminish the expected subresource_use_rate_ (and will only be
// counteracted later if we really needed this subresource as a consequence
// of our associated referrer.)
void ReferrerWasObserved();
int64 navigation_count() const { return navigation_count_; }
double subresource_use_rate() const { return subresource_use_rate_; }
int64 preconnection_count() const { return preconnection_count_; }
void IncrementPreconnectionCount() { ++preconnection_count_; }
int64 preresolution_count() const { return preresolution_count_; }
void preresolution_increment() { ++preresolution_count_; }
// Reduce the subresource_use_rate_ by the supplied factor, and return true
// if the result is still greater than the given threshold.
bool Trim(double reduce_rate, double threshold);
private:
const base::Time birth_time_;
// The number of times this item was navigated to with the fixed referrer.
int64 navigation_count_;
// The number of times this item was preconnected as a consequence of its
// referrer.
int64 preconnection_count_;
// The number of times this item was pre-resolved (via DNS) as a consequence
// of its referrer.
int64 preresolution_count_;
// A smoothed estimate of the expected number of connections that will be made
// to this subresource.
double subresource_use_rate_;
};
//------------------------------------------------------------------------------
// A list of domain names to pre-resolve. The names are the keys to this map,
// and the values indicate the amount of benefit derived from having each name
// around.
typedef std::map<GURL, ReferrerValue> SubresourceMap;
//------------------------------------------------------------------------------
// There is one Referrer instance for each hostname that has acted as an HTTP
// referer (note mispelling is intentional) for a hostname that was otherwise
// unexpectedly navgated towards ("unexpected" in the sense that the hostname
// was probably needed as a subresource of a page, and was not otherwise
// predictable until the content with the reference arrived). Most typically,
// an outer page was a page fetched by the user, and this instance lists names
// in SubresourceMap which are subresources and that were needed to complete the
// rendering of the outer page.
class Referrer : public SubresourceMap {
public:
Referrer();
void IncrementUseCount() { ++use_count_; }
int64 use_count() const { return use_count_; }
// Add the indicated url to the list that are resolved via DNS when the user
// navigates to this referrer. Note that if the list is long, an entry may be
// discarded to make room for this insertion.
void SuggestHost(const GURL& url);
// Trim the Referrer, by first diminishing (scaling down) the subresource
// use expectation for each ReferredValue.
// Returns true if expected use rate is greater than the threshold.
bool Trim(double reduce_rate, double threshold);
// Provide methods for persisting, and restoring contents into a Value class.
base::Value* Serialize() const;
void Deserialize(const base::Value& referrers);
private:
// Helper function for pruning list. Metric for usefulness is "large accrued
// value," in the form of latency_ savings associated with a host name. We
// also give credit for a name being newly added, by scalling latency per
// lifetime (time since birth). For instance, when two names have accrued
// the same latency_ savings, the older one is less valuable as it didn't
// accrue savings as quickly.
void DeleteLeastUseful();
// The number of times this referer had its subresources scanned for possible
// preconnection or DNS preresolution.
int64 use_count_;
// We put these into a std::map<>, so we need copy constructors.
// DISALLOW_COPY_AND_ASSIGN(Referrer);
// TODO(jar): Consider optimization to use pointers to these instances, and
// avoid deep copies during re-alloc of the containing map.
};
} // namespace chrome_browser_net
#endif // CHROME_BROWSER_NET_REFERRER_H_
| plxaye/chromium | src/chrome/browser/net/referrer.h | C | apache-2.0 | 5,756 |
# Tomcat Container
The Tomcat Container allows servlet 2 and 3 web applications to be run. These applications are run as the root web application in a Tomcat container.
<table>
<tr>
<td><strong>Detection Criterion</strong></td><td>Existence of a <tt>WEB-INF/</tt> folder in the application directory and <a href="container-java_main.md">Java Main</a> not detected</td>
</tr>
<tr>
<td><strong>Tags</strong></td>
<td><tt>tomcat-instance=⟨version⟩</tt>, <tt>tomcat-lifecycle-support=⟨version⟩</tt>, <tt>tomcat-logging-support=⟨version⟩</tt> <tt>tomcat-redis-store=⟨version⟩</tt> <i>(optional)</i></td>
</tr>
</table>
Tags are printed to standard output by the buildpack detect script
If the application uses Spring, [Spring profiles][] can be specified by setting the [`SPRING_PROFILES_ACTIVE`][] environment variable. This is automatically detected and used by Spring. The Spring Auto-reconfiguration Framework will specify the `cloud` profile in addition to any others.
## Configuration
For general information on configuring the buildpack, refer to [Configuration and Extension][].
The container can be configured by modifying the [`config/tomcat.yml`][] file in the buildpack fork. The container uses the [`Repository` utility support][repositories] and so it supports the [version syntax][] defined there.
| Name | Description
| ---- | -----------
| `lifecycle_support.repository_root` | The URL of the Tomcat Lifecycle Support repository index ([details][repositories]).
| `lifecycle_support.version` | The version of Tomcat Lifecycle Support to use. Candidate versions can be found in [this listing](http://download.pivotal.io.s3.amazonaws.com/tomcat-lifecycle-support/index.yml).
| `logging_support.repository_root` | The URL of the Tomcat Logging Support repository index ([details][repositories]).
| `logging_support.version` | The version of Tomcat Logging Support to use. Candidate versions can be found in [this listing](http://download.pivotal.io.s3.amazonaws.com/tomcat-logging-support/index.yml).
| `access_logging_support.repository_root` | The URL of the Tomcat Access Logging Support repository index ([details][repositories]).
| `access_logging_support.version` | The version of Tomcat Access Logging Support to use. Candidate versions can be found in [this listing](http://download.pivotal.io.s3.amazonaws.com/tomcat-access-logging-support/index.yml).
| `access_logging_support.access_logging` | Set to `enabled` to turn on the access logging support. Default is `disabled`.
| `redis_store.connection_pool_size` | The Redis connection pool size. Note that this is per-instance, not per-application.
| `redis_store.database` | The Redis database to connect to.
| `redis_store.repository_root` | The URL of the Redis Store repository index ([details][repositories]).
| `redis_store.timeout` | The Redis connection timeout (in milliseconds).
| `redis_store.version` | The version of Redis Store to use. Candidate versions can be found in [this listing](http://download.pivotal.io.s3.amazonaws.com/redis-store/index.yml).
| `tomcat.repository_root` | The URL of the Tomcat repository index ([details][repositories]).
| `tomcat.version` | The version of Tomcat to use. Candidate versions can be found in [this listing](http://download.pivotal.io.s3.amazonaws.com/tomcat/index.yml).
### Additional Resources
The container can also be configured by overlaying a set of resources on the default distribution. To do this, add files to the `resources/tomcat` directory in the buildpack fork. For example, to override the default `logging.properties` add your custom file to `resources/tomcat/conf/logging.properties`.
## Session Replication
By default, the Tomcat instance is configured to store all Sessions and their data in memory. Under certain cirmcumstances it my be appropriate to persist the Sessions and their data to a repository. When this is the case (small amounts of data that should survive the failure of any individual instance), the buildpack can automatically configure Tomcat to do so.
### Redis
To enable Redis-based session replication, simply bind a Redis service containing a name, label, or tag that has `session-replication` as a substring.
## Supporting Functionality
Additional supporting functionality can be found in the [`java-buildpack-support`][] Git repository.
[Configuration and Extension]: ../README.md#configuration-and-extension
[`config/tomcat.yml`]: ../config/tomcat.yml
[`java-buildpack-support`]: https://github.com/cloudfoundry/java-buildpack-support
[repositories]: extending-repositories.md
[Spring profiles]:http://blog.springsource.com/2011/02/14/spring-3-1-m1-introducing-profile/
[`SPRING_PROFILES_ACTIVE`]: http://docs.spring.io/spring/docs/4.0.0.RELEASE/javadoc-api/org/springframework/core/env/AbstractEnvironment.html#ACTIVE_PROFILES_PROPERTY_NAME
[version syntax]: extending-repositories.md#version-syntax-and-ordering
| celkins/dropwizard-buildpack | docs/container-tomcat.md | Markdown | apache-2.0 | 4,961 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.twitter.consumer;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.twitter.TwitterEndpoint;
import org.apache.camel.impl.DefaultConsumer;
/**
* Camel DirectConsumer implementation.
*/
@Deprecated
public class TwitterConsumerDirect extends DefaultConsumer {
private final AbstractTwitterConsumerHandler twitter4jConsumer;
public TwitterConsumerDirect(TwitterEndpoint endpoint, Processor processor, AbstractTwitterConsumerHandler twitter4jConsumer) {
super(endpoint, processor);
this.twitter4jConsumer = twitter4jConsumer;
}
@Override
protected void doStart() throws Exception {
super.doStart();
List<Exchange> exchanges = twitter4jConsumer.directConsume();
for (int i = 0; i < exchanges.size(); i++) {
getProcessor().process(exchanges.get(i));
}
}
}
| curso007/camel | components/camel-twitter/src/main/java/org/apache/camel/component/twitter/consumer/TwitterConsumerDirect.java | Java | apache-2.0 | 1,759 |
package org.nutz.resource;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.nutz.conf.NutConf;
import static org.junit.Assert.*;
/**
* 配置器
* @author juqkai([email protected])
*
*/
public class NutConfigTest {
@Before
public void init(){
NutConf.clear();
}
@Test
public void nullConfigTest(){
//加载nutz配置
NutConf.load();
}
@Test
public void simpleNullTypeTest(){
NutConf.load("config/test.js");
Map<?, ?> conf = (Map<?, ?>) NutConf.get("TEST");
assertEquals("jk", conf.get("name"));
}
@Test
public void simpleTest(){
NutConf.load("config/test.js");
Map<?, ?> conf = (Map<?, ?>) NutConf.get("TEST", Map.class);
assertEquals("jk", conf.get("name"));
}
@Test
public void pathTest(){
NutConf.load("config");
Map<?, ?> conf = (Map<?, ?>) NutConf.get("TEST", Map.class);
assertEquals("jk", conf.get("name"));
}
@Test
public void loadDefaultConfigTest(){
NutConf.load("org/nutz/conf/NutzDefaultConfig.js");
Map<?, ?> conf = (Map<?, ?>) NutConf.get("TEST", Map.class);
assertNull(conf);
}
@Test
public void includeTest(){
NutConf.load("config/include.js");
Map<?, ?> conf = (Map<?, ?>) NutConf.get("TEST", Map.class);
assertEquals("jk", conf.get("name"));
}
}
| dxxfire/nutz | test/org/nutz/resource/NutConfigTest.java | Java | apache-2.0 | 1,465 |
cask 'quassel' do
version '0.12.2'
sha256 '4dd932e5e7a0908886427fc012886a76bbf1691cdd8832a67cdbc11a10be3682'
url "http://quassel-irc.org/pub/QuasselMono_MacOSX-x86_64_#{version}.dmg"
name 'Quassel IRC'
homepage 'http://quassel-irc.org'
license :gpl
app 'Quassel.app'
end
| codeurge/homebrew-cask | Casks/quassel.rb | Ruby | bsd-2-clause | 287 |
import time
from urllib.parse import urlencode, urlparse
from wptserve.utils import isomorphic_decode, isomorphic_encode
def main(request, response):
stashed_data = {b'count': 0, b'preflight': b"0"}
status = 302
headers = [(b"Content-Type", b"text/plain"),
(b"Cache-Control", b"no-cache"),
(b"Pragma", b"no-cache")]
if b"Origin" in request.headers:
headers.append((b"Access-Control-Allow-Origin", request.headers.get(b"Origin", b"")))
headers.append((b"Access-Control-Allow-Credentials", b"true"))
else:
headers.append((b"Access-Control-Allow-Origin", b"*"))
token = None
if b"token" in request.GET:
token = request.GET.first(b"token")
data = request.server.stash.take(token)
if data:
stashed_data = data
if request.method == u"OPTIONS":
if b"allow_headers" in request.GET:
headers.append((b"Access-Control-Allow-Headers", request.GET[b'allow_headers']))
stashed_data[b'preflight'] = b"1"
#Preflight is not redirected: return 200
if not b"redirect_preflight" in request.GET:
if token:
request.server.stash.put(request.GET.first(b"token"), stashed_data)
return 200, headers, u""
if b"redirect_status" in request.GET:
status = int(request.GET[b'redirect_status'])
stashed_data[b'count'] += 1
if b"location" in request.GET:
url = isomorphic_decode(request.GET[b'location'])
if b"simple" not in request.GET:
scheme = urlparse(url).scheme
if scheme == u"" or scheme == u"http" or scheme == u"https":
url += u"&" if u'?' in url else u"?"
#keep url parameters in location
url_parameters = {}
for item in request.GET.items():
url_parameters[isomorphic_decode(item[0])] = isomorphic_decode(item[1][0])
url += urlencode(url_parameters)
#make sure location changes during redirection loop
url += u"&count=" + str(stashed_data[b'count'])
headers.append((b"Location", isomorphic_encode(url)))
if b"redirect_referrerpolicy" in request.GET:
headers.append((b"Referrer-Policy", request.GET[b'redirect_referrerpolicy']))
if b"delay" in request.GET:
time.sleep(float(request.GET.first(b"delay", 0)) / 1E3)
if token:
request.server.stash.put(request.GET.first(b"token"), stashed_data)
if b"max_count" in request.GET:
max_count = int(request.GET[b'max_count'])
#stop redirecting and return count
if stashed_data[b'count'] > max_count:
# -1 because the last is not a redirection
return str(stashed_data[b'count'] - 1)
return status, headers, u""
| scheib/chromium | third_party/blink/web_tests/external/wpt/fetch/api/resources/redirect.py | Python | bsd-3-clause | 2,859 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SEARCH_ENGINES_TESTING_SEARCH_TERMS_DATA_H_
#define COMPONENTS_SEARCH_ENGINES_TESTING_SEARCH_TERMS_DATA_H_
#include "components/search_engines/search_terms_data.h"
class TestingSearchTermsData : public SearchTermsData {
public:
explicit TestingSearchTermsData(const std::string& google_base_url);
~TestingSearchTermsData() override;
std::string GoogleBaseURLValue() const override;
base::string16 GetRlzParameterValue(bool from_app_list) const override;
std::string GetSearchClient() const override;
std::string GoogleImageSearchSource() const override;
bool EnableAnswersInSuggest() const override;
bool IsShowingSearchTermsOnSearchResultsPages() const override;
int OmniboxStartMargin() const override;
void set_google_base_url(const std::string& google_base_url) {
google_base_url_ = google_base_url;
}
void set_search_client(const std::string& search_client) {
search_client_ = search_client;
}
void set_enable_answers_in_suggest(bool enable_answers_in_suggest) {
enable_answers_in_suggest_ = enable_answers_in_suggest;
}
void set_is_showing_search_terms_on_search_results_pages(bool value) {
is_showing_search_terms_on_search_results_pages_ = value;
}
void set_omnibox_start_margin(int omnibox_start_margin) {
omnibox_start_margin_ = omnibox_start_margin;
}
private:
std::string google_base_url_;
std::string search_client_;
bool enable_answers_in_suggest_;
bool is_showing_search_terms_on_search_results_pages_;
int omnibox_start_margin_;
DISALLOW_COPY_AND_ASSIGN(TestingSearchTermsData);
};
#endif // COMPONENTS_SEARCH_ENGINES_TESTING_SEARCH_TERMS_DATA_H_
| jaruba/chromium.src | components/search_engines/testing_search_terms_data.h | C | bsd-3-clause | 1,828 |
# Compojure Benchmarking Test
This is the [Aleph](https;//github.com/ztellman/aleph) portion of a [benchmarking test suite](../) comparing a variety of web development platforms.
### JSON Encoding Test
* [JSON test source](hello/src/hello/handler.clj)
## Infrastructure Software Versions
The dependencies are documented in [project.clj](hello/project.clj),
but the main ones are:
* [Aleph 0.4.0](https://github.com/ztellman/aleph)
* [Clojure 1.7.0-beta2](http://clojure.org/)
* [Cheshire 5.4.0](https://github.com/dakrone/cheshire), which in turn uses [Jackson](http://jackson.codehaus.org/)
## Test URLs
### JSON Encoding Test
http://localhost/json
### Plaintext Test
http://localhost/plaintext
| lcp0578/FrameworkBenchmarks | frameworks/Clojure/aleph/README.md | Markdown | bsd-3-clause | 705 |
# powerSaveBlocker
`powerSaveBlocker`モジュールは、省電力(スリープ)モードからシステムをブロックするのに使用され、それ故にアプリがシステムと画面をアクティブに維持することができます。
例:
```javascript
const powerSaveBlocker = require('electron').powerSaveBlocker;
var id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id));
powerSaveBlocker.stop(id);
```
## メソッド
`powerSaveBlocker`モジュールは次のメソッドを持ちます:
### `powerSaveBlocker.start(type)`
* `type` String - パワーセーブのブロック種類です。
* `prevent-app-suspension` - アプリケーションがサスペンドになるのを防ぎます。システムのアクティブ状態を維持できますが、画面をオフにすることができます。使用例:ファイルのダウンロードまたは音楽の再生
* `prevent-display-sleep`- ディスプレイがスリープになるのを防ぎます。システムと画面のアクティブ状態を維持できます。使用例:ビデオ再生
省電力モードに入るのを防止するシステムを開始します。パワーセーブブロッカーを確認する数字を返します。
**Note:** `prevent-display-sleep`は`prevent-app-suspension`より高い優先権を持ちます。最も優先権が高いタイプのみが影響します。言い換えれば。`prevent-display-sleep`はいつも`prevent-app-suspension`より高い優先権をもちます。
例えば、APIが`prevent-app-suspension`を要求するAをコールし、ほかのAPIが`prevent-display-sleep`を要求するBをコールすると、`prevent-display-sleep`はBのリクエストが止まるまで使われ、そのあと`prevent-app-suspension`が使われます。
### `powerSaveBlocker.stop(id)`
* `id` Integer - `powerSaveBlocker.start`によって、パワーセーブブロッカーIDが返されます。
指定したパワーセーブブロッカーを停止します。
### `powerSaveBlocker.isStarted(id)`
* `id` Integer - `powerSaveBlocker.start`によって、パワーセーブブロッカーIDが返されます。
`powerSaveBlocker`が開始したかどうかのブーリアン値を返します。
| simongregory/electron | docs-translations/jp/api/power-save-blocker.md | Markdown | mit | 2,317 |
require 'spec_helper'
describe 'Gitlab::Popen', no_db: true do
let (:path) { Rails.root.join('tmp').to_s }
before do
@klass = Class.new(Object)
@klass.send(:include, Gitlab::Popen)
end
context 'zero status' do
before do
@output, @status = @klass.new.popen('ls', path)
end
it { @status.should be_zero }
it { @output.should include('cache') }
end
context 'non-zero status' do
before do
@output, @status = @klass.new.popen('cat NOTHING', path)
end
it { @status.should == 1 }
it { @output.should include('No such file or directory') }
end
end
| lbt/gitlabhq | spec/lib/popen_spec.rb | Ruby | mit | 612 |
<?php
namespace Kunstmaan\LeadGenerationBundle\Service;
use Doctrine\ORM\EntityManager;
use Kunstmaan\LeadGenerationBundle\Entity\Popup\AbstractPopup;
class PopupManager
{
/**
* @var array|null
*/
private $popups = null;
/**
* @var EntityManager $em
*/
private $em;
/**
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* Get a list of popup definitions.
*
* @return array
*/
public function getPopups()
{
if (is_null($this->popups)) {
$this->popups = $this->em->getRepository('KunstmaanLeadGenerationBundle:Popup\AbstractPopup')->findAll();
}
return $this->popups;
}
/**
* Get a list of unique javascript files that should be included in the html.
*
* @return array
*/
public function getUniqueJsIncludes()
{
$includes = array();
foreach ($this->getPopups() as $popup) {
foreach ($popup->getRules() as $rule) {
$includes[] = $rule->getJsFilePath();
}
}
return array_unique($includes);
}
/**
* @param AbstractPopup $popup
* @return array
*/
public function getAvailableRules(AbstractPopup $popup)
{
if (!is_null($popup->getAvailableRules())) {
return $popup->getAvailableRules();
} else {
return array(
'Kunstmaan\LeadGenerationBundle\Entity\Rule\AfterXSecondsRule',
'Kunstmaan\LeadGenerationBundle\Entity\Rule\AfterXScrollPercentRule',
'Kunstmaan\LeadGenerationBundle\Entity\Rule\MaxXTimesRule',
'Kunstmaan\LeadGenerationBundle\Entity\Rule\RecurringEveryXTimeRule',
'Kunstmaan\LeadGenerationBundle\Entity\Rule\UrlBlacklistRule',
'Kunstmaan\LeadGenerationBundle\Entity\Rule\UrlWhitelistRule',
'Kunstmaan\LeadGenerationBundle\Entity\Rule\OnExitIntentRule'
);
}
}
}
| iBenito/KunstmaanBundlesCMS | src/Kunstmaan/LeadGenerationBundle/Service/PopupManager.php | PHP | mit | 2,079 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Controller_Register extends Controller {
public $helpers = array('form', 'html');
public function __construct() {
if(!ENABLE_REGISTRATION) {
$cont = Loader::controller('/page_not_found');
$cont->view();
$this->render("/page_not_found");
}
parent::__construct();
Loader::model('user_attributes');
$u = new User();
$this->set('u', $u);
/*
if (USER_REGISTRATION_WITH_EMAIL_ADDRESS) {
$this->set('displayUserName', false);
} else {
$this->set('displayUserName', true);
}*/
$this->set('displayUserName', true);
}
public function forward($cID = 0) {
$this->set('rcID', Loader::helper('security')->sanitizeInt($cID));
}
public function do_register() {
$registerData['success']=0;
$userHelper = Loader::helper('concrete/user');
$e = Loader::helper('validation/error');
$ip = Loader::helper('validation/ip');
$txt = Loader::helper('text');
$vals = Loader::helper('validation/strings');
$valc = Loader::helper('concrete/validation');
$username = $_POST['uName'];
$password = $_POST['uPassword'];
$passwordConfirm = $_POST['uPasswordConfirm'];
// clean the username
$username = trim($username);
$username = preg_replace("/ +/", " ", $username);
if (!$ip->check()) {
$e->add($ip->getErrorMessage());
}
if (ENABLE_REGISTRATION_CAPTCHA) {
$captcha = Loader::helper('validation/captcha');
if (!$captcha->check()) {
$e->add(t("Incorrect image validation code. Please check the image and re-enter the letters or numbers as necessary."));
}
}
if (!$vals->email($_POST['uEmail'])) {
$e->add(t('Invalid email address provided.'));
} else if (!$valc->isUniqueEmail($_POST['uEmail'])) {
$e->add(t("The email address %s is already in use. Please choose another.", $_POST['uEmail']));
}
//if (USER_REGISTRATION_WITH_EMAIL_ADDRESS == false) {
if (strlen($username) < USER_USERNAME_MINIMUM) {
$e->add(t('A username must be at least %s characters long.', USER_USERNAME_MINIMUM));
}
if (strlen($username) > USER_USERNAME_MAXIMUM) {
$e->add(t('A username cannot be more than %s characters long.', USER_USERNAME_MAXIMUM));
}
if (strlen($username) >= USER_USERNAME_MINIMUM && !$valc->username($username)) {
if(USER_USERNAME_ALLOW_SPACES) {
$e->add(t('A username may only contain letters, numbers and spaces.'));
} else {
$e->add(t('A username may only contain letters or numbers.'));
}
}
if (!$valc->isUniqueUsername($username)) {
$e->add(t("The username %s already exists. Please choose another", $username));
}
//}
if ($username == USER_SUPER) {
$e->add(t('Invalid Username'));
}
/*
if ((strlen($password) < USER_PASSWORD_MINIMUM) || (strlen($password) > USER_PASSWORD_MAXIMUM)) {
$e->add(t('A password must be between %s and %s characters', USER_PASSWORD_MINIMUM, USER_PASSWORD_MAXIMUM));
}
if (strlen($password) >= USER_PASSWORD_MINIMUM && !$valc->password($password)) {
$e->add(t('A password may not contain ", \', >, <, or any spaces.'));
}
*/
$userHelper->validNewPassword($password,$e);
if ($password) {
if ($password != $passwordConfirm) {
$e->add(t('The two passwords provided do not match.'));
}
}
$aks = UserAttributeKey::getRegistrationList();
foreach($aks as $uak) {
if ($uak->isAttributeKeyRequiredOnRegister()) {
$e1 = $uak->validateAttributeForm();
if ($e1 == false) {
$e->add(t('The field "%s" is required', $uak->getAttributeKeyDisplayName()));
} else if ($e1 instanceof ValidationErrorHelper) {
$e->add($e1);
}
}
}
if (!$e->has()) {
// do the registration
$data = $_POST;
$data['uName'] = $username;
$data['uPassword'] = $password;
$data['uPasswordConfirm'] = $passwordConfirm;
$process = UserInfo::register($data);
if (is_object($process)) {
foreach($aks as $uak) {
$uak->saveAttributeForm($process);
}
if (REGISTER_NOTIFICATION) { //do we notify someone if a new user is added?
$mh = Loader::helper('mail');
if(EMAIL_ADDRESS_REGISTER_NOTIFICATION) {
$mh->to(EMAIL_ADDRESS_REGISTER_NOTIFICATION);
} else {
$adminUser = UserInfo::getByID(USER_SUPER_ID);
if (is_object($adminUser)) {
$mh->to($adminUser->getUserEmail());
}
}
$mh->addParameter('uID', $process->getUserID());
$mh->addParameter('user', $process);
$mh->addParameter('uName', $process->getUserName());
$mh->addParameter('uEmail', $process->getUserEmail());
$attribs = UserAttributeKey::getRegistrationList();
$attribValues = array();
foreach($attribs as $ak) {
$attribValues[] = $ak->getAttributeKeyDisplayName('text') . ': ' . $process->getAttribute($ak->getAttributeKeyHandle(), 'display');
}
$mh->addParameter('attribs', $attribValues);
if (defined('EMAIL_ADDRESS_REGISTER_NOTIFICATION_FROM')) {
$mh->from(EMAIL_ADDRESS_REGISTER_NOTIFICATION_FROM, t('Website Registration Notification'));
} else {
$adminUser = UserInfo::getByID(USER_SUPER_ID);
if (is_object($adminUser)) {
$mh->from($adminUser->getUserEmail(), t('Website Registration Notification'));
}
}
if(REGISTRATION_TYPE == 'manual_approve') {
$mh->load('user_register_approval_required');
} else {
$mh->load('user_register');
}
$mh->sendMail();
}
// now we log the user in
if (USER_REGISTRATION_WITH_EMAIL_ADDRESS) {
$u = new User($_POST['uEmail'], $_POST['uPassword']);
} else {
$u = new User($_POST['uName'], $_POST['uPassword']);
}
// if this is successful, uID is loaded into session for this user
$rcID = $this->post('rcID');
$nh = Loader::helper('validation/numbers');
if (!$nh->integer($rcID)) {
$rcID = 0;
}
// now we check whether we need to validate this user's email address
if (defined("USER_VALIDATE_EMAIL") && USER_VALIDATE_EMAIL) {
if (USER_VALIDATE_EMAIL > 0) {
$uHash = $process->setupValidation();
$mh = Loader::helper('mail');
if (defined('EMAIL_ADDRESS_VALIDATE')) {
$mh->from(EMAIL_ADDRESS_VALIDATE, t('Validate Email Address'));
}
$mh->addParameter('uEmail', $_POST['uEmail']);
$mh->addParameter('uHash', $uHash);
$mh->to($_POST['uEmail']);
$mh->load('validate_user_email');
$mh->sendMail();
//$this->redirect('/register', 'register_success_validate', $rcID);
$redirectMethod='register_success_validate';
$registerData['msg']= join('<br><br>',$this->getRegisterSuccessValidateMsgs());
$u->logout();
}
} else if(defined('USER_REGISTRATION_APPROVAL_REQUIRED') && USER_REGISTRATION_APPROVAL_REQUIRED) {
$ui = UserInfo::getByID($u->getUserID());
$ui->deactivate();
//$this->redirect('/register', 'register_pending', $rcID);
$redirectMethod='register_pending';
$registerData['msg']=$this->getRegisterPendingMsg();
$u->logout();
}
if (!$u->isError()) {
//$this->redirect('/register', 'register_success', $rcID);
if(!$redirectMethod){
$redirectMethod='register_success';
$registerData['msg']=$this->getRegisterSuccessMsg();
}
$registerData['uID']=intval($u->uID);
}
$registerData['success']=1;
if($_REQUEST['format']!='JSON')
$this->redirect('/register', $redirectMethod, $rcID);
}
} else {
$ip->logSignupRequest();
if ($ip->signupRequestThreshholdReached()) {
$ip->createIPBan();
}
$this->set('error', $e);
$registerData['errors'] = $e->getList();
}
if( $_REQUEST['format']=='JSON' ){
$jsonHelper=Loader::helper('json');
echo $jsonHelper->encode($registerData);
die;
}
}
public function register_success_validate($rcID = 0) {
$this->set('rcID', $rcID);
$this->set('success', 'validate');
$this->set('successMsg', $this->getRegisterSuccessValidateMsgs() );
}
public function register_success($rcID = 0) {
$this->set('rcID', $rcID);
$this->set('success', 'registered');
$this->set('successMsg', $this->getRegisterSuccessMsg() );
}
public function register_pending() {
$this->set('rcID', $rcID);
$this->set('success', 'pending');
$this->set('successMsg', $this->getRegisterPendingMsg() );
}
public function getRegisterSuccessMsg(){
return t('Your account has been created, and you are now logged in.');
}
public function getRegisterSuccessValidateMsgs(){
$msgs=array();
$msgs[]= t('You are registered but you need to validate your email address. Some or all functionality on this site will be limited until you do so.');
$msgs[]= t('An email has been sent to your email address. Click on the URL contained in the email to validate your email address.');
return $msgs;
}
public function getRegisterPendingMsg(){
return t('You are registered but a site administrator must review your account, you will not be able to login until your account has been approved.');
}
}
?>
| win-k/CMSTV | concrete5/concrete/core/controllers/single_pages/register.php | PHP | mit | 9,166 |
<?php
namespace AlgoliaSearch;
class SynonymType
{
const SYNONYM = 0;
const SYNONYM_ONEWAY = 1;
const PLACEHOLDER = 2;
const ALTCORRECTION_1 = 3;
const ALTCORRECTION_2 = 4;
public static function getSynonymsTypeString($synonymType)
{
if ($synonymType == self::SYNONYM) {
return 'synonym';
}
if ($synonymType == self::SYNONYM_ONEWAY) {
return 'oneWaySynonym';
}
if ($synonymType == self::PLACEHOLDER) {
return 'placeholder';
}
if ($synonymType == self::ALTCORRECTION_1) {
return 'altCorrection1';
}
if ($synonymType == self::ALTCORRECTION_2) {
return 'altCorrection2';
}
return;
}
}
| Uminks/Restaurant-Manager | vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/SynonymType.php | PHP | mit | 770 |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.models.datamodel.rule;
public class ExpressionVariable extends ExpressionPart {
private String factType;
public ExpressionVariable() {
}
public ExpressionVariable( String fieldName,
String fieldClassType,
String fieldGenericType ) {
super( fieldName, fieldClassType, fieldGenericType );
}
public ExpressionVariable( String binding,
String factType ) {
super( binding,
factType,
factType );
if ( binding == null || binding.isEmpty() ) {
throw new RuntimeException( "the fact is not bounded: " + factType );
}
this.factType = factType;
}
public String getFactType() {
return factType;
}
@Override
public void accept( ExpressionVisitor visitor ) {
visitor.visit( this );
}
@Override
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
if ( !super.equals( o ) ) {
return false;
}
ExpressionVariable that = (ExpressionVariable) o;
if ( factType != null ? !factType.equals( that.factType ) : that.factType != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = ~~result;
result = 31 * result + ( factType != null ? factType.hashCode() : 0 );
result = ~~result;
return result;
}
}
| rokn/Count_Words_2015 | testing/drools-master/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/rule/ExpressionVariable.java | Java | mit | 2,314 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml;
using System.Xml.Schema;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
public class XsdDataContractExporter
{
private ExportOptions _options;
private XmlSchemaSet _schemas;
private DataContractSet _dataContractSet;
public XsdDataContractExporter()
{
}
public XsdDataContractExporter(XmlSchemaSet schemas)
{
this._schemas = schemas;
}
public ExportOptions Options
{
get { return _options; }
set { _options = value; }
}
public XmlSchemaSet Schemas
{
get
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_SchemaImporter);
}
}
XmlSchemaSet GetSchemaSet()
{
if (_schemas == null)
{
_schemas = new XmlSchemaSet();
_schemas.XmlResolver = null;
}
return _schemas;
}
DataContractSet DataContractSet
{
get
{
// On full framework , we set _dataContractSet = Options.GetSurrogate());
// But Options.GetSurrogate() is not available on NetCore because IDataContractSurrogate
// is not in NetStandard.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_IDataContractSurrogate);
}
}
void TraceExportBegin()
{
}
void TraceExportEnd()
{
}
void TraceExportError(Exception exception)
{
}
public void Export(ICollection<Assembly> assemblies)
{
if (assemblies == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies)));
TraceExportBegin();
DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
try
{
foreach (Assembly assembly in assemblies)
{
if (assembly == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, nameof(assemblies))));
Type[] types = assembly.GetTypes();
for (int j = 0; j < types.Length; j++)
CheckAndAddType(types[j]);
}
Export();
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
_dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
TraceExportEnd();
}
public void Export(ICollection<Type> types)
{
if (types == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types)));
TraceExportBegin();
DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
try
{
foreach (Type type in types)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullType, nameof(types))));
AddType(type);
}
Export();
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
_dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
TraceExportEnd();
}
public void Export(Type type)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
TraceExportBegin();
DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
try
{
AddType(type);
Export();
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
_dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
TraceExportEnd();
}
public XmlQualifiedName GetSchemaTypeName(Type type)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
type = GetSurrogatedType(type);
DataContract dataContract = DataContract.GetDataContract(type);
DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType);
XmlDataContract xmlDataContract = dataContract as XmlDataContract;
if (xmlDataContract != null && xmlDataContract.IsAnonymous)
return XmlQualifiedName.Empty;
return dataContract.StableName;
}
public XmlSchemaType GetSchemaType(Type type)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
type = GetSurrogatedType(type);
DataContract dataContract = DataContract.GetDataContract(type);
DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType);
XmlDataContract xmlDataContract = dataContract as XmlDataContract;
if (xmlDataContract != null && xmlDataContract.IsAnonymous)
return xmlDataContract.XsdType;
return null;
}
public XmlQualifiedName GetRootElementName(Type type)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
type = GetSurrogatedType(type);
DataContract dataContract = DataContract.GetDataContract(type);
DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType);
if (dataContract.HasRoot)
{
return new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value);
}
else
{
return null;
}
}
private Type GetSurrogatedType(Type type)
{
#if SUPPORT_SURROGATE
IDataContractSurrogate dataContractSurrogate;
if (options != null && (dataContractSurrogate = Options.GetSurrogate()) != null)
type = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, type);
#endif
return type;
}
private void CheckAndAddType(Type type)
{
type = GetSurrogatedType(type);
if (!type.ContainsGenericParameters && DataContract.IsTypeSerializable(type))
AddType(type);
}
private void AddType(Type type)
{
DataContractSet.Add(type);
}
private void Export()
{
AddKnownTypes();
SchemaExporter schemaExporter = new SchemaExporter(GetSchemaSet(), DataContractSet);
schemaExporter.Export();
}
private void AddKnownTypes()
{
if (Options != null)
{
Collection<Type> knownTypes = Options.KnownTypes;
if (knownTypes != null)
{
for (int i = 0; i < knownTypes.Count; i++)
{
Type type = knownTypes[i];
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.CannotExportNullKnownType));
AddType(type);
}
}
}
}
public bool CanExport(ICollection<Assembly> assemblies)
{
if (assemblies == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies)));
DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
try
{
foreach (Assembly assembly in assemblies)
{
if (assembly == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, nameof(assemblies))));
Type[] types = assembly.GetTypes();
for (int j = 0; j < types.Length; j++)
CheckAndAddType(types[j]);
}
AddKnownTypes();
return true;
}
catch (InvalidDataContractException)
{
_dataContractSet = oldValue;
return false;
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
_dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
}
public bool CanExport(ICollection<Type> types)
{
if (types == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types)));
DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
try
{
foreach (Type type in types)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullType, nameof(types))));
AddType(type);
}
AddKnownTypes();
return true;
}
catch (InvalidDataContractException)
{
_dataContractSet = oldValue;
return false;
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
_dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
}
public bool CanExport(Type type)
{
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
try
{
AddType(type);
AddKnownTypes();
return true;
}
catch (InvalidDataContractException)
{
_dataContractSet = oldValue;
return false;
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
_dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
}
#if USE_REFEMIT
//Returns warnings
public IList<string> GenerateCode(IList<Assembly> assemblies)
{
if (assemblies == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies)));
List<string> warnings = new List<string>();
DataContractSet oldValue = (dataContractSet == null) ? null : new DataContractSet(dataContractSet);
try
{
for (int i=0; i < assemblies.Count; i++)
{
Assembly assembly = assemblies[i];
if (assembly == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullAssembly, "assemblies")));
Type[] types = assembly.GetTypes();
for (int j=0; j < types.Length; j++)
{
try
{
CheckAndAddType(types[j]);
}
catch (Exception ex)
{
warnings.Add("Error on exporting Type " + DataContract.GetClrTypeFullName(types[j]) + ". " + ex.Message);
}
}
}
foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in dataContractSet)
{
DataContract dataContract = pair.Value;
if (dataContract is ClassDataContract)
{
try
{
XmlFormatClassWriterDelegate writerMethod = ((ClassDataContract)dataContract).XmlFormatWriterDelegate;
XmlFormatClassReaderDelegate readerMethod = ((ClassDataContract)dataContract).XmlFormatReaderDelegate;
}
catch (Exception ex)
{
warnings.Add("Error on exporting Type " + dataContract.UnderlyingType + ". " + ex.Message);
}
}
else if (dataContract is CollectionDataContract)
{
try
{
XmlFormatCollectionWriterDelegate writerMethod = ((CollectionDataContract)dataContract).XmlFormatWriterDelegate;
XmlFormatCollectionReaderDelegate readerMethod = ((CollectionDataContract)dataContract).XmlFormatReaderDelegate;
}
catch (Exception ex)
{
warnings.Add("Error on exporting Type " + dataContract.UnderlyingType + ". " + ex.Message);
}
}
}
return warnings;
}
catch (Exception ex)
{
if (DiagnosticUtility.IsFatal(ex))
{
throw;
}
dataContractSet = oldValue;
TraceExportError(ex);
throw;
}
}
#endif
}
}
| BrennanConroy/corefx | src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs | C# | mit | 15,805 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.