answer
stringlengths 15
1.25M
|
|---|
var getColors = require('../getColors');
var randomBetween = require('../randomBetween');
module.exports = function(canvas, opt) {
var ctx = canvas.getContext('2d');
var colors = getColors(randomBetween(1, 4));
colors.forEach(function(color) {
ctx.beginPath();
ctx.moveTo(randomBetween(0, opt.width), randomBetween(0, opt.height));
ctx.bezierCurveTo(randomBetween(0, opt.height), randomBetween(0, opt.height), randomBetween(0, opt.width), randomBetween(0, opt.height), randomBetween(0, opt.width), randomBetween(0, opt.height));
ctx.fillStyle = ctx.strokeStyle = color.css;
ctx.lineWidth = randomBetween(2, 5);
return ctx.stroke();
});
return canvas;
};
|
from django.conf.urls import patterns, include, url
from settings import STATIC_ROOT, GRAPHITE_API_PREFIX, CONTENT_DIR
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns(
'',
# These views are needed for the <API key> debug interface
# to be able to log in and out. The URL path doesn't matter, rest_framework
# finds the views by name.
url(r'^api/rest_framework/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', 'calamari_web.views.home'),
url(r'^api/v1/', include('calamari_rest.urls.v1')),
url(r'^api/v2/', include('calamari_rest.urls.v2')),
url(r'^admin/(?P<path>.*)$', 'calamari_web.views.serve_dir_or_index',
{'document_root': '%s/admin/' % STATIC_ROOT}),
url(r'^manage/(?P<path>.*)$', 'calamari_web.views.serve_dir_or_index',
{'document_root': '%s/manage/' % STATIC_ROOT}),
url(r'^login/$', 'django.views.static.serve',
{'document_root': '%s/login/' % STATIC_ROOT, 'path': "index.html"}),
url(r'^login/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/login/' % STATIC_ROOT}),
url(r'^bootstrap$', 'calamari_web.views.bootstrap', name='bootstrap'),
url(r'^dashboard/(?P<path>.*)$', 'calamari_web.views.dashboard',
{'document_root': '%s/dashboard/' % STATIC_ROOT},
name='dashboard'),
url(r'^render/?', include('graphite.render.urls')),
url(r'^metrics/?', include('graphite.metrics.urls')),
url(r'^%s/dashboard/?' % GRAPHITE_API_PREFIX.lstrip('/'), include('graphite.dashboard.urls')),
# XXX this is a hack to make graphite visible where the 1.x GUI expects it,
url(r'^graphite/render/?', include('graphite.render.urls')),
url(r'^graphite/metrics/?', include('graphite.metrics.urls')),
# XXX this is a hack to make graphite dashboard work in dev mode (full installation
# serves this part with apache)
url('^content/(?P<path>.*)$', 'django.views.static.serve', {'document_root': CONTENT_DIR}),
# XXX this is a hack to serve apt repo in dev mode (Full installation serves this with apache)
url(r'^static/ubuntu/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/ubuntu/' % STATIC_ROOT}),
)
# Graphite dashboard client code is not CSRF enabled, but we have
# global CSRF protection enabled. Make exceptions for the views
# that the graphite dashboard wants to POST to.
from django.views.decorators.csrf import csrf_exempt
# By default graphite views are visible to anyone who asks:
# we only want to allow logged in users to access graphite
# API.
from django.contrib.auth.decorators import login_required
def patch_views(mod):
for url_pattern in mod.urlpatterns:
cb = url_pattern.callback
url_pattern._callback = csrf_exempt(login_required(cb))
import graphite.metrics.urls
import graphite.dashboard.urls
patch_views(graphite.metrics.urls)
patch_views(graphite.dashboard.urls)
# Explicitly reset to default or graphite hijacks it
handler500 = 'django.views.defaults.bad_request'
|
import <API key> from "@enhavo/app/<API key>";
import * as $ from "jquery";
import "slick-carousel";
export default class GalleryBlock implements <API key>
{
public init(element: HTMLElement)
{
if($('[data-hero-slider]').length > 0) {
$(element).find('[data-hero-slider]').slick({
nextArrow: '<div class="arrow next"></div>',
prevArrow: '<div class="arrow prev"></div>',
fade: true,
dots:true
});
}
}
}
|
package org.knowm.xchange.currency;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.<API key>;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* @author timmolter
*/
public class <API key> extends JsonSerializer<CurrencyPair> {
@Override
public void serialize(CurrencyPair currencyPair, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException, <API key> {
// jsonGenerator.writeStartObject();
jsonGenerator.writeString(currencyPair.toString());
// jsonGenerator.writeEndObject();
}
}
|
// Use of this source code is governed by a BSD-style
package planbuilder
import (
"errors"
"github.com/youtube/vitess/go/vt/sqlparser"
"github.com/youtube/vitess/go/vt/vtgate/engine"
"github.com/youtube/vitess/go/vt/vtgate/vindexes"
)
// buildSelectPlan is the new function to build a Select plan.
func buildSelectPlan(sel *sqlparser.Select, vschema VSchema) (primitive engine.Primitive, err error) {
bindvars := getBindvars(sel)
builder, err := processSelect(sel, vschema, nil)
if err != nil {
return nil, err
}
jt := newJointab(bindvars)
err = builder.Wireup(builder, jt)
if err != nil {
return nil, err
}
return builder.Primitive(), nil
}
// getBindvars returns a map of the bind vars referenced in the statement.
func getBindvars(node sqlparser.SQLNode) map[string]struct{} {
bindvars := make(map[string]struct{})
_ = sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch node := node.(type) {
case sqlparser.ValArg:
bindvars[string(node[1:])] = struct{}{}
case sqlparser.ListArg:
bindvars[string(node[2:])] = struct{}{}
}
return true, nil
}, node)
return bindvars
}
// processSelect builds a primitive tree for the given query or subquery.
func processSelect(sel *sqlparser.Select, vschema VSchema, outer builder) (builder, error) {
bldr, err := processTableExprs(sel.From, vschema)
if err != nil {
return nil, err
}
if outer != nil {
bldr.Symtab().Outer = outer.Symtab()
}
if sel.Where != nil {
err = pushFilter(sel.Where.Expr, bldr, sqlparser.WhereStr)
if err != nil {
return nil, err
}
}
err = pushSelectExprs(sel, bldr)
if err != nil {
return nil, err
}
if sel.Having != nil {
err = pushFilter(sel.Having.Expr, bldr, sqlparser.HavingStr)
if err != nil {
return nil, err
}
}
err = pushOrderBy(sel.OrderBy, bldr)
if err != nil {
return nil, err
}
err = pushLimit(sel.Limit, bldr)
if err != nil {
return nil, err
}
bldr.PushMisc(sel)
return bldr, nil
}
// pushFilter identifies the target route for the specified bool expr,
// pushes it down, and updates the route info if the new constraint improves
// the primitive. This function can push to a WHERE or HAVING clause.
func pushFilter(boolExpr sqlparser.BoolExpr, bldr builder, whereType string) error {
filters := splitAndExpression(nil, boolExpr)
reorderBySubquery(filters)
for _, filter := range filters {
rb, err := findRoute(filter, bldr)
if err != nil {
return err
}
err = rb.PushFilter(filter, whereType)
if err != nil {
return err
}
}
return nil
}
// reorderBySubquery reorders the filters by pushing subqueries
// to the end. This allows the non-subquery filters to be
// pushed first because they can potentially improve the routing
// plan, which can later allow a filter containing a subquery
// to successfully merge with the corresponding route.
func reorderBySubquery(filters []sqlparser.BoolExpr) {
max := len(filters)
for i := 0; i < max; i++ {
if !hasSubquery(filters[i]) {
continue
}
saved := filters[i]
for j := i; j < len(filters)-1; j++ {
filters[j] = filters[j+1]
}
filters[len(filters)-1] = saved
max
}
}
// pushSelectExprs identifies the target route for the
// select expressions and pushes them down.
func pushSelectExprs(sel *sqlparser.Select, bldr builder) error {
err := checkAggregates(sel, bldr)
if err != nil {
return err
}
if sel.Distinct != "" {
// We know it's a route, but this may change
// in the distant future.
bldr.(*route).MakeDistinct()
}
colsyms, err := pushSelectRoutes(sel.SelectExprs, bldr)
if err != nil {
return err
}
bldr.Symtab().Colsyms = colsyms
err = pushGroupBy(sel.GroupBy, bldr)
if err != nil {
return err
}
return nil
}
// checkAggregates returns an error if the select statement
// has aggregates that cannot be pushed down due to a complex
// plan.
func checkAggregates(sel *sqlparser.Select, bldr builder) error {
hasAggregates := false
if sel.Distinct != "" {
hasAggregates = true
} else {
_ = sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch node := node.(type) {
case *sqlparser.FuncExpr:
if node.IsAggregate() {
hasAggregates = true
return false, errors.New("dummy")
}
}
return true, nil
}, sel.SelectExprs)
}
if !hasAggregates {
return nil
}
// Check if we can allow aggregates.
rb, ok := bldr.(*route)
if !ok {
return errors.New("unsupported: complex join with aggregates")
}
if rb.IsSingle() {
return nil
}
// It's a scatter rb. We can allow aggregates if there is a unique
// vindex in the select list.
for _, selectExpr := range sel.SelectExprs {
switch selectExpr := selectExpr.(type) {
case *sqlparser.NonStarExpr:
vindex := bldr.Symtab().Vindex(selectExpr.Expr, rb, true)
if vindex != nil && vindexes.IsUnique(vindex) {
return nil
}
}
}
return errors.New("unsupported: scatter with aggregates")
}
// pusheSelectRoutes is a convenience function that pushes all the select
// expressions and returns the list of colsyms generated for it.
func pushSelectRoutes(selectExprs sqlparser.SelectExprs, bldr builder) ([]*colsym, error) {
colsyms := make([]*colsym, len(selectExprs))
for i, node := range selectExprs {
switch node := node.(type) {
case *sqlparser.NonStarExpr:
rb, err := findRoute(node.Expr, bldr)
if err != nil {
return nil, err
}
colsyms[i], _, err = bldr.PushSelect(node, rb)
if err != nil {
return nil, err
}
case *sqlparser.StarExpr:
// We'll allow select * for simple routes.
rb, ok := bldr.(*route)
if !ok {
return nil, errors.New("unsupported: '*' expression in complex join")
}
// We can push without validating the reference because
// MySQL will fail if it's invalid.
colsyms[i] = rb.PushStar(node)
case sqlparser.Nextval:
// For now, this is only supported as an implicit feature
// for auto_inc in inserts.
return nil, errors.New("unsupported: NEXT VALUE construct")
}
}
return colsyms, nil
}
|
#include "<API key>.h"
#include "<API key>.h"
<API key> *sRequestProxy;
static sem_t sem_heard2;
class <API key> : public <API key>
{
public:
void readData ( const <API key> v ) {
fprintf(stderr, "heard an s: %lld\n", (long long)v.data);
//sRequestProxy->say2(v, 2*v);
}
void writeDone ( const uint8_t v ) {
sem_post(&sem_heard2);
//fprintf(stderr, "heard an s2: %ld %ld\n", a, b);
}
<API key>(unsigned int id, <API key> *item, void *param) : <API key>(id, item, param) {}
};
//sem_wait(&sem_heard2);
int main(int argc, const char **argv)
{
<API key> sIndication(<API key>, &transportSocketInit, NULL);
sRequestProxy = new <API key>(<API key>, &transportSocketInit, NULL);
int v = 42;
fprintf(stderr, "Saying %d\n", v);
//call_say(v);
portal_disconnect(&sRequestProxy->pint);
return 0;
}
|
package org.bouncycastle.cms.jcajce;
import java.security.<API key>;
import java.security.<API key>;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.<API key>;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.<API key>;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.cms.<API key>;
import org.bouncycastle.asn1.cms.<API key>;
import org.bouncycastle.asn1.cms.<API key>;
import org.bouncycastle.asn1.cms.ecc.<API key>;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.<API key>;
import org.bouncycastle.cms.CMSAlgorithm;
import org.bouncycastle.cms.<API key>;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.<API key>;
import org.bouncycastle.jce.spec.MQVPrivateKeySpec;
import org.bouncycastle.jce.spec.MQVPublicKeySpec;
import org.bouncycastle.operator.GenericKey;
public class <API key>
extends <API key>
{
private List recipientIDs = new ArrayList();
private List recipientKeys = new ArrayList();
private PublicKey senderPublicKey;
private PrivateKey senderPrivateKey;
private EnvelopedDataHelper helper = new EnvelopedDataHelper(new <API key>());
private SecureRandom random;
private KeyPair ephemeralKP;
public <API key>(<API key> keyAgreementOID, PrivateKey senderPrivateKey, PublicKey senderPublicKey, <API key> keyEncryptionOID)
{
super(keyAgreementOID, <API key>.getInstance(senderPublicKey.getEncoded()), keyEncryptionOID);
this.senderPublicKey = senderPublicKey;
this.senderPrivateKey = senderPrivateKey;
}
public <API key> setProvider(Provider provider)
{
this.helper = new EnvelopedDataHelper(new <API key>(provider));
return this;
}
public <API key> setProvider(String providerName)
{
this.helper = new EnvelopedDataHelper(new <API key>(providerName));
return this;
}
public <API key> setSecureRandom(SecureRandom random)
{
this.random = random;
return this;
}
/**
* Add a recipient based on the passed in certificate's public key and its issuer and serial number.
*
* @param recipientCert recipient's certificate
* @return the current instance.
* @throws <API key> if the necessary data cannot be extracted from the certificate.
*/
public <API key> addRecipient(X509Certificate recipientCert)
throws <API key>
{
recipientIDs.add(new <API key>(CMSUtils.<API key>(recipientCert)));
recipientKeys.add(recipientCert.getPublicKey());
return this;
}
/**
* Add a recipient identified by the passed in subjectKeyID and the for the passed in public key.
*
* @param subjectKeyID identifier actual recipient will use to match the private key.
* @param publicKey the public key for encrypting the secret key.
* @return the current instance.
* @throws <API key>
*/
public <API key> addRecipient(byte[] subjectKeyID, PublicKey publicKey)
throws <API key>
{
recipientIDs.add(new <API key>(new <API key>(subjectKeyID)));
recipientKeys.add(publicKey);
return this;
}
public ASN1Sequence <API key>(AlgorithmIdentifier keyAgreeAlgorithm, AlgorithmIdentifier <API key>, GenericKey <API key>)
throws CMSException
{
init(keyAgreeAlgorithm.getAlgorithm());
PrivateKey senderPrivateKey = this.senderPrivateKey;
<API key> keyAgreementOID = keyAgreeAlgorithm.getAlgorithm();
if (keyAgreementOID.getId().equals(<API key>.ECMQV_SHA1KDF))
{
senderPrivateKey = new MQVPrivateKeySpec(
senderPrivateKey, ephemeralKP.getPrivate(), ephemeralKP.getPublic());
}
ASN1EncodableVector <API key> = new ASN1EncodableVector();
for (int i = 0; i != recipientIDs.size(); i++)
{
PublicKey recipientPublicKey = (PublicKey)recipientKeys.get(i);
<API key> karId = (<API key>)recipientIDs.get(i);
if (keyAgreementOID.getId().equals(<API key>.ECMQV_SHA1KDF))
{
recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey);
}
try
{
// Use key agreement to choose a wrap key for this recipient
KeyAgreement keyAgreement = helper.createKeyAgreement(keyAgreementOID);
keyAgreement.init(senderPrivateKey, random);
keyAgreement.doPhase(recipientPublicKey, true);
SecretKey keyEncryptionKey = keyAgreement.generateSecret(<API key>.getAlgorithm().getId());
// Wrap the content encryption key with the agreement key
Cipher keyEncryptionCipher = helper.createCipher(<API key>.getAlgorithm());
keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random);
byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(<API key>));
ASN1OctetString encryptedKey = new DEROctetString(encryptedKeyBytes);
<API key>.add(new <API key>(karId, encryptedKey));
}
catch (<API key> e)
{
throw new CMSException("cannot perform agreement step: " + e.getMessage(), e);
}
}
return new DERSequence(<API key>);
}
protected ASN1Encodable <API key>(AlgorithmIdentifier keyAgreeAlg)
throws CMSException
{
init(keyAgreeAlg.getAlgorithm());
if (ephemeralKP != null)
{
return new <API key>(
<API key>(<API key>.getInstance(ephemeralKP.getPublic().getEncoded())), null);
}
return null;
}
private void init(<API key> keyAgreementOID)
throws CMSException
{
if (random == null)
{
random = new SecureRandom();
}
if (keyAgreementOID.equals(CMSAlgorithm.ECMQV_SHA1KDF))
{
if (ephemeralKP == null)
{
try
{
ECParameterSpec ecParamSpec = ((ECPublicKey)senderPublicKey).getParams();
KeyPairGenerator ephemKPG = helper.<API key>(keyAgreementOID);
ephemKPG.initialize(ecParamSpec, random);
ephemeralKP = ephemKPG.generateKeyPair();
}
catch (<API key> e)
{
throw new CMSException(
"cannot determine MQV ephemeral key pair parameters from public key: " + e);
}
}
}
}
}
|
#nullable enable
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class <API key>
{
public static string GetFullText(this IEnumerable<SymbolDisplayPart> parts)
=> string.Join(string.Empty, parts.Select(p => p.ToString()));
public static void AddLineBreak(this IList<SymbolDisplayPart> parts, string text = "\r\n")
=> parts.Add(new SymbolDisplayPart(<API key>.LineBreak, null, text));
public static void AddMethodName(this IList<SymbolDisplayPart> parts, string text)
=> parts.Add(new SymbolDisplayPart(<API key>.MethodName, null, text));
public static void AddPunctuation(this IList<SymbolDisplayPart> parts, string text)
=> parts.Add(new SymbolDisplayPart(<API key>.Punctuation, null, text));
public static void AddSpace(this IList<SymbolDisplayPart> parts, string text = " ")
=> parts.Add(new SymbolDisplayPart(<API key>.Space, null, text));
public static void AddText(this IList<SymbolDisplayPart> parts, string text)
=> parts.Add(new SymbolDisplayPart(<API key>.Text, null, text));
}
}
|
var assert = require('assert');
describe('integral test', function() {
it('Process result must be equal to expected.css', function() {
var config = this.Comb.getConfig('csscomb');
this.comb.configure(config);
this.shouldBeEqual('integral.css', 'integral.expected.css');
});
it('Issue 252', function() {
var config = this.Comb.getConfig('csscomb');
this.comb.configure(config);
this.shouldBeEqual('issue-252.sass', 'issue-252.expected.sass');
});
it('Issue 374', function() {
var config = this.Comb.getConfig('csscomb');
this.comb.configure(config);
this.shouldBeEqual('issue-374.css');
});
it('Should detect everything in integral test', function() {
var input = this.readFile('integral.expected.css');
// Clone the required config object, otherwise other tests would fail
var expected = JSON.parse(JSON.stringify(this.Comb.getConfig('csscomb')));
delete expected['sort-order'];
delete expected['exclude'];
this.shouldDetect(undefined, input, expected);
});
});
|
import test from '../../';
test(t => {
t.pass();
});
|
/*
W3C Sample Code Library libwww NNTP REQUEST STREAM
!NNTP Request Stream!
*/
/*
The NNTP Request stream generates a NNTP request header and writes it
to the target which is normally a HTWriter stream.
This module is implemented by HTNewsRq.c, and
it is a part of the W3C
Sample Code Library.
*/
#ifndef HTNEWSREQ_H
#define HTNEWSREQ_H
#include "HTStream.h"
#include "HTAccess.h"
/*
(Streams Definition)
This stream makes a HTNews request header before it goes into
transparent mode.
*/
extern HTStream * HTNewsPost_new (HTRequest * request, HTStream * target);
#endif
/*
@(#) $Id: HTNewsRq.html,v 2.5 1998/05/14 02:10:53 frystyk Exp $
*/
|
<?php
namespace Mage\Review\Test\Constraint;
use Magento\Mtf\Constraint\AbstractConstraint;
use Magento\Mtf\ObjectManager;
use Mage\Catalog\Test\Page\Product\CatalogProductView;
/**
* Assert that product don't have a review on product page.
*/
class <API key> extends AbstractConstraint
{
/* tags */
const SEVERITY = 'low';
/* end tags */
/**
* Verify message for assert.
*/
const NO_REVIEW_LINK_TEXT = 'Be the first to review this product';
/**
* Catalog product view page.
*
* @var CatalogProductView
*/
protected $catalogProductView;
/**
* @constructor
* @param ObjectManager $objectManager
* @param CatalogProductView $catalogProductView
*/
public function __construct(ObjectManager $objectManager, CatalogProductView $catalogProductView)
{
parent::__construct($objectManager);
$this->catalogProductView = $catalogProductView;
}
/**
* Assert that product doesn't have a review on product page.
*
* @return void
*/
public function processAssert()
{
$this->catalogProductView->getViewBlock()-><API key>('Reviews');
\<API key>::assertFalse(
$this->catalogProductView->getReviewsBlock()-><API key>(),
'No reviews below the form required.'
);
\<API key>::assertEquals(
self::NO_REVIEW_LINK_TEXT,
trim($this->catalogProductView->getReviewsBlock()->getAddReviewLink()->getText()),
sprintf('"%s" link is not available', self::NO_REVIEW_LINK_TEXT)
);
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString()
{
return 'Product do not have a review on product page.';
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Batch;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Routing;
using System.Web.OData.Routing.Conventions;
using Microsoft.OData.Client;
using Microsoft.OData.Core;
using Microsoft.OData.Edm;
using Nuwa;
using WebStack.QA.Common.WebHost;
using WebStack.QA.Test.OData.Common;
using WebStack.QA.Test.OData.Common.Controllers;
using WebStack.QA.Test.OData.ModelBuilder;
using Xunit;
namespace WebStack.QA.Test.OData.Batch.Tests.DataServicesClient
{
public class <API key>
{
public int Id { get; set; }
public string Name { get; set; }
public IList<<API key>> Orders { get; set; }
}
public class <API key>
{
public int Id { get; set; }
public DateTimeOffset PurchaseDate { get; set; }
}
public class <API key> : <API key><<API key>, int>
{
private static bool _initialized;
public <API key>()
: base("Id")
{
if (!_initialized)
{
IList<<API key>> customers = Enumerable.Range(0, 10).Select(i =>
new <API key>
{
Id = i,
Name = string.Format("Name {0}", i)
}).ToList();
foreach (<API key> customer in customers)
{
LocalTable.AddOrUpdate(customer.Id, customer, (key, oldEntity) => oldEntity);
}
_initialized = true;
}
}
protected override Task<<API key>> CreateEntityAsync(<API key> entity)
{
if (entity.Id < 0)
{
throw new <API key>(Request.CreateResponse(HttpStatusCode.BadRequest));
}
return base.CreateEntityAsync(entity);
}
[EnableQuery]
public IQueryable<<API key>> OddCustomers()
{
return base.LocalTable.Where(x => x.Key % 2 == 1).Select(x => x.Value).AsQueryable();
}
public Task CreateRef([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
{
return Task.FromResult(Request.CreateResponse(HttpStatusCode.NoContent));
}
}
public class <API key> : <API key><<API key>, int>
{
public <API key>()
: base("Id")
{
}
}
[NuwaFramework]
[<API key>(MessageLog = false)]
[NuwaTrace(typeof(<API key>))]
public class CUDBatchTests : IODataTestBase
{
private string baseAddress = null;
[NuwaBaseAddress]
public string BaseAddress
{
get
{
return baseAddress;
}
set
{
if (!string.IsNullOrEmpty(value))
{
this.baseAddress = value.Replace("localhost", Environment.MachineName);
}
}
}
[NuwaHttpClient]
public HttpClient Client { get; set; }
[NuwaConfiguration]
public static void UpdateConfiguration(HttpConfiguration configuration)
{
HttpServer server = configuration.Properties["Nuwa.HttpServerKey"] as HttpServer;
configuration.<API key> = <API key>.Always;
configuration.<API key>(
"batch",
"UnbufferedBatch",
GetEdmModel(),
new <API key>(),
<API key>.CreateDefault(),
new <API key>(server));
}
protected static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new <API key>();
<API key><<API key>> customers = builder.EntitySet<<API key>>("<API key>");
<API key><<API key>> orders = builder.EntitySet<<API key>>("<API key>");
customers.EntityType.Collection.Action("OddCustomers").<API key><<API key>>("<API key>");
builder.<API key> = builder.DataServiceVersion;
return builder.GetEdmModel();
}
[NuwaWebConfig]
public static void UpdateWebConfig(WebConfigHelper webConfig)
{
webConfig.AddAppSection("aspnet:<API key>", "true");
}
[Fact]
public async Task <API key>()
{
Uri serviceUrl = new Uri(BaseAddress + "/UnbufferedBatch");
var client = new <API key>.Container(serviceUrl);
client.Format.UseJson();
IEnumerable<<API key>.<API key>> customers =
await client.<API key>.ExecuteAsync();
var customersList = customers.ToList();
<API key>.<API key> customerToDelete = customersList[0];
client.DeleteObject(customerToDelete);
<API key>.<API key> customerToUpdate = customersList[1];
customerToUpdate.Name = "Updated customer name";
client.UpdateObject(customerToUpdate);
<API key>.<API key> customerToAdd =
new <API key>.<API key> { Id = 10, Name = "Customer 10" };
client.<API key>(customerToAdd);
var response = await client.SaveChangesAsync(SaveChangesOptions.<API key>);
var newClient = new <API key>.Container(serviceUrl);
IEnumerable<<API key>.<API key>> changedCustomers =
await newClient.<API key>.ExecuteAsync();
var changedCustomerList = changedCustomers.ToList();
Assert.False(changedCustomerList.Any(x => x.Id == customerToDelete.Id));
Assert.Equal(customerToUpdate.Name, changedCustomerList.Single(x => x.Id == customerToUpdate.Id).Name);
Assert.Single(changedCustomerList, x => x.Id == 10);
}
[Fact]
public async Task <API key>()
{
// Arrange
var requestUri = string.Format("{0}/UnbufferedBatch/$batch", this.BaseAddress);
Uri address = new Uri(this.BaseAddress, UriKind.Absolute);
string host = address.Host;
string <API key> = "<API key>";
string relativeToHostUri = address.LocalPath.TrimEnd(new char[]{'/'}) + "/UnbufferedBatch/<API key>";
string absoluteUri = this.BaseAddress + "/UnbufferedBatch/<API key>";
// Act
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Headers.Accept.Add(<API key>.Parse("multipart/mixed"));
HttpContent content = new StringContent(@"
--<API key>
Content-Type: multipart/mixed; boundary=<API key>
--<API key>
Content-Type: application/http
<API key>: binary
Content-ID: 2
POST " + <API key> + @" HTTP/1.1
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Content-Type: application/json;odata.metadata=minimal
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8
{'Id':1,'Name':'MyName1'}
--<API key>
Content-Type: application/http
<API key>: binary
Content-ID: 3
POST " + relativeToHostUri + @" HTTP/1.1
Host: " + host + @"
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8
Content-Type: application/json;odata.metadata=minimal
{'Id':2,'Name':'MyName2'}
--<API key>
Content-Type: application/http
<API key>: binary
Content-ID: 4
POST " + absoluteUri + @" HTTP/1.1
OData-Version: 4.0;NetFx
OData-MaxVersion: 4.0;NetFx
Accept: application/json;odata.metadata=minimal
Accept-Charset: UTF-8
Content-Type: application/json;odata.metadata=minimal
{'Id':3,'Name':'MyName3'}
--<API key>--
--<API key>--
");
content.Headers.ContentType = <API key>.Parse("multipart/mixed; boundary=<API key>");
request.Content = content;
HttpResponseMessage response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = response.Content.ReadAsStreamAsync().Result;
<API key> <API key> = new ODataMessageWrapper(stream, response.Content.Headers);
int subResponseCount = 0;
using (var messageReader = new ODataMessageReader(<API key>, new <API key>(), GetEdmModel()))
{
var batchReader = messageReader.<API key>();
while (batchReader.Read())
{
switch (batchReader.State)
{
case <API key>.Operation:
var operationMessage = batchReader.<API key>();
subResponseCount++;
Assert.Equal(201, operationMessage.StatusCode);
break;
}
}
}
Assert.Equal(3, subResponseCount);
}
}
[NuwaFramework]
[<API key>(MessageLog = false)]
[NuwaTrace(typeof(<API key>))]
public class QueryBatchTests : IODataTestBase
{
private string baseAddress = null;
[NuwaBaseAddress]
public string BaseAddress
{
get
{
return baseAddress;
}
set
{
if (!string.IsNullOrEmpty(value))
{
this.baseAddress = value.Replace("localhost", Environment.MachineName);
}
}
}
[NuwaHttpClient]
public HttpClient Client { get; set; }
[NuwaConfiguration]
public static void UpdateConfiguration(HttpConfiguration configuration)
{
HttpServer server = configuration.Properties["Nuwa.HttpServerKey"] as HttpServer;
configuration.<API key> = <API key>.Always;
configuration.<API key>(
"batch",
"UnbufferedBatch",
GetEdmModel(),
new <API key>(),
<API key>.CreateDefault(),
new <API key>(server));
}
protected static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new <API key>();
<API key><<API key>> customers = builder.EntitySet<<API key>>("<API key>");
<API key><<API key>> orders = builder.EntitySet<<API key>>("<API key>");
customers.EntityType.Collection.Action("OddCustomers").<API key><<API key>>("<API key>");
builder.<API key> = builder.DataServiceVersion;
return builder.GetEdmModel();
}
[NuwaWebConfig]
public static void UpdateWebConfig(WebConfigHelper webConfig)
{
webConfig.AddAppSection("aspnet:<API key>", "true");
}
[Fact]
public void <API key>()
{
Uri serviceUrl = new Uri(BaseAddress + "/UnbufferedBatch");
<API key>.Container client = new <API key>.Container(serviceUrl);
client.Format.UseJson();
Uri customersRequestUri = new Uri(BaseAddress + "/UnbufferedBatch/<API key>");
DataServiceRequest<<API key>.<API key>> customersRequest = new DataServiceRequest<<API key>.<API key>>(customersRequestUri);
Uri <API key> = new Uri(BaseAddress + "/UnbufferedBatch/<API key>(0)");
DataServiceRequest<<API key>.<API key>> <API key> = new DataServiceRequest<<API key>.<API key>>(<API key>);
DataServiceResponse batchResponse = client.ExecuteBatchAsync(customersRequest, <API key>).Result;
if (batchResponse.IsBatchResponse)
{
Assert.Equal(200, batchResponse.BatchStatusCode);
}
foreach (<API key> response in batchResponse)
{
Assert.Equal(200, response.StatusCode);
if (response.Query.RequestUri == customersRequestUri)
{
Assert.Equal(10, response.Cast<<API key>.<API key>>().Count());
continue;
}
if (response.Query.RequestUri == <API key>)
{
Assert.Equal(1, response.Cast<<API key>.<API key>>().Count());
continue;
}
}
}
}
[NuwaFramework]
[<API key>(MessageLog = false)]
[NuwaTrace(typeof(<API key>))]
public class ErrorsBatchTests : IODataTestBase
{
private string baseAddress = null;
[NuwaBaseAddress]
public string BaseAddress
{
get
{
return baseAddress;
}
set
{
if (!string.IsNullOrEmpty(value))
{
this.baseAddress = value.Replace("localhost", Environment.MachineName);
}
}
}
[NuwaHttpClient]
public HttpClient Client { get; set; }
[NuwaConfiguration]
public static void UpdateConfiguration(HttpConfiguration configuration)
{
HttpServer server = configuration.Properties["Nuwa.HttpServerKey"] as HttpServer;
configuration.<API key> = <API key>.Always;
configuration.<API key>(
"batch",
"UnbufferedBatch",
GetEdmModel(),
new <API key>(),
<API key>.CreateDefault(),
new <API key>(server));
}
protected static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new <API key>();
<API key><<API key>> customers = builder.EntitySet<<API key>>("<API key>");
<API key><<API key>> orders = builder.EntitySet<<API key>>("<API key>");
customers.EntityType.Collection.Action("OddCustomers").<API key><<API key>>("<API key>");
builder.<API key> = builder.DataServiceVersion;
return builder.GetEdmModel();
}
[NuwaWebConfig]
public static void UpdateWebConfig(WebConfigHelper webConfig)
{
webConfig.AddAppSection("aspnet:<API key>", "true");
}
[Fact]
public void <API key>()
{
Uri serviceUrl = new Uri(BaseAddress + "/UnbufferedBatch");
<API key>.Container client = new <API key>.Container(serviceUrl);
client.Format.UseJson();
<API key>.<API key> validCustomer = new <API key>.<API key>()
{
Id = 10,
Name = "Customer 10"
};
<API key>.<API key> invalidCustomer = new <API key>.<API key>()
{
Id = -1,
Name = "Customer -1"
};
client.<API key>(validCustomer);
client.<API key>(invalidCustomer);
var aggregateException = Assert.Throws<AggregateException>(() =>
{
DataServiceResponse response = client.SaveChangesAsync(SaveChangesOptions.<API key>).Result;
});
var exception = aggregateException.InnerExceptions.SingleOrDefault() as <API key>;
Assert.NotNull(exception);
Assert.Equal(200, exception.Response.BatchStatusCode);
Assert.Equal(1, exception.Response.Count());
}
}
[NuwaFramework]
[<API key>(MessageLog = false)]
[NuwaTrace(typeof(<API key>))]
public class LinksBatchTests : IODataTestBase
{
private string baseAddress = null;
[NuwaBaseAddress]
public string BaseAddress
{
get
{
return baseAddress;
}
set
{
if (!string.IsNullOrEmpty(value))
{
this.baseAddress = value.Replace("localhost", Environment.MachineName);
}
}
}
[NuwaHttpClient]
public HttpClient Client { get; set; }
[NuwaConfiguration]
public static void UpdateConfiguration(HttpConfiguration configuration)
{
HttpServer server = configuration.Properties["Nuwa.HttpServerKey"] as HttpServer;
configuration.<API key> = <API key>.Always;
configuration.<API key>(
"batch",
"UnbufferedBatch",
GetEdmModel(),
new <API key>(),
<API key>.CreateDefault(),
new <API key>(server));
}
protected static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new <API key>();
<API key><<API key>> customers = builder.EntitySet<<API key>>("<API key>");
<API key><<API key>> orders = builder.EntitySet<<API key>>("<API key>");
customers.EntityType.Collection.Action("OddCustomers").<API key><<API key>>("<API key>");
builder.<API key> = builder.DataServiceVersion;
return builder.GetEdmModel();
}
[NuwaWebConfig]
public static void UpdateWebConfig(WebConfigHelper webConfig)
{
webConfig.AddAppSection("aspnet:<API key>", "true");
}
[Fact]
public virtual void <API key>()
{
Uri serviceUrl = new Uri(BaseAddress + "/UnbufferedBatch");
<API key>.Container client = new <API key>.Container(serviceUrl);
client.Format.UseJson();
<API key>.<API key> customer = client.<API key>.ExecuteAsync().Result.First();
<API key>.<API key> order = new <API key>.<API key>() { Id = 0, PurchaseDate = DateTime.Now };
client.<API key>(order);
client.AddLink(customer, "Orders", order);
client.SaveChangesAsync(SaveChangesOptions.<API key>).Wait();
}
}
[NuwaFramework]
[<API key>(MessageLog = false)]
[NuwaTrace(typeof(<API key>))]
public class <API key> : IODataTestBase
{
private string baseAddress = null;
[NuwaBaseAddress]
public string BaseAddress
{
get
{
return baseAddress;
}
set
{
if (!string.IsNullOrEmpty(value))
{
this.baseAddress = value.Replace("localhost", Environment.MachineName);
}
}
}
[NuwaHttpClient]
public HttpClient Client { get; set; }
[NuwaConfiguration]
public static void UpdateConfiguration(HttpConfiguration configuration)
{
HttpServer server = configuration.Properties["Nuwa.HttpServerKey"] as HttpServer;
configuration.<API key> = <API key>.Always;
configuration.<API key>(
"batch",
"UnbufferedBatch",
GetEdmModel(),
new <API key>(),
<API key>.CreateDefault(),
new <API key>(server));
configuration.<API key>();
}
protected static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new <API key>();
<API key><<API key>> customers = builder.EntitySet<<API key>>("<API key>");
<API key><<API key>> orders = builder.EntitySet<<API key>>("<API key>");
customers.EntityType.Collection.Action("OddCustomers").<API key><<API key>>("<API key>");
builder.<API key> = builder.DataServiceVersion;
return builder.GetEdmModel();
}
[NuwaWebConfig]
public static void UpdateWebConfig(WebConfigHelper webConfig)
{
webConfig.AddAppSection("aspnet:<API key>", "true");
}
[Fact]
public async Task <API key>()
{
// Arrange
var requestUri = string.Format("{0}/UnbufferedBatch/$batch", this.BaseAddress);
string absoluteUri = this.BaseAddress + "/UnbufferedBatch/<API key>";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Headers.Accept.Add(<API key>.Parse("multipart/mixed"));
HttpContent content = new StringContent(
@"--<API key>
Content-Type: application/http
<API key>: binary
GET " + absoluteUri + @"(0) HTTP/1.1
--<API key>
Content-Type: application/http
<API key>: binary
GET " + absoluteUri + @"(-1) HTTP/1.1
--<API key>
Content-Type: application/http
<API key>: binary
GET " + absoluteUri + @"(1) HTTP/1.1
--<API key>--
");
content.Headers.ContentType = <API key>.Parse("multipart/mixed; boundary=<API key>");
request.Content = content;
// Act
HttpResponseMessage response = await Client.SendAsync(request);
var stream = response.Content.ReadAsStreamAsync().Result;
<API key> <API key> = new ODataMessageWrapper(stream, response.Content.Headers);
int subResponseCount = 0;
// Assert
using (var messageReader = new ODataMessageReader(<API key>, new <API key>(), GetEdmModel()))
{
var batchReader = messageReader.<API key>();
while (batchReader.Read())
{
switch (batchReader.State)
{
case <API key>.Operation:
var operationMessage = batchReader.<API key>();
subResponseCount++;
if (subResponseCount == 2)
{
Assert.Equal(500, operationMessage.StatusCode);
}
else
{
Assert.Equal(200, operationMessage.StatusCode);
}
break;
}
}
}
Assert.Equal(2, subResponseCount);
}
[Fact]
public async Task <API key>()
{
// Arrange
var requestUri = string.Format("{0}/UnbufferedBatch/$batch", this.BaseAddress);
string absoluteUri = this.BaseAddress + "/UnbufferedBatch/<API key>";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Headers.Accept.Add(<API key>.Parse("multipart/mixed"));
request.Headers.Add("prefer", "odata.continue-on-error");
HttpContent content = new StringContent(
@"--<API key>
Content-Type: application/http
<API key>: binary
GET " + absoluteUri + @"(0) HTTP/1.1
--<API key>
Content-Type: application/http
<API key>: binary
GET " + absoluteUri + @"(-1) HTTP/1.1
--<API key>
Content-Type: application/http
<API key>: binary
GET " + absoluteUri + @"(1) HTTP/1.1
--<API key>--
");
content.Headers.ContentType = <API key>.Parse("multipart/mixed; boundary=<API key>");
request.Content = content;
// Act
HttpResponseMessage response = await Client.SendAsync(request);
var stream = response.Content.ReadAsStreamAsync().Result;
<API key> <API key> = new ODataMessageWrapper(stream, response.Content.Headers);
int subResponseCount = 0;
// Assert
using (var messageReader = new ODataMessageReader(<API key>, new <API key>(), GetEdmModel()))
{
var batchReader = messageReader.<API key>();
while (batchReader.Read())
{
switch (batchReader.State)
{
case <API key>.Operation:
var operationMessage = batchReader.<API key>();
subResponseCount++;
if (subResponseCount == 2)
{
Assert.Equal(500, operationMessage.StatusCode);
}
else
{
Assert.Equal(200, operationMessage.StatusCode);
}
break;
}
}
}
Assert.Equal(3, subResponseCount);
}
}
}
|
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Core.UnitTests;
using NUnit.Framework;
namespace Xamarin.Forms.Xaml.UnitTests
{
public partial class <API key> : ContentPage
{
public <API key> ()
{
InitializeComponent ();
}
public <API key> (bool useCompiledXaml)
{
//this stub will be replaced at compile time
}
[TestFixture]
public class Tests
{
[SetUp]
public void Setup ()
{
Device.PlatformServices = new <API key> ();
}
[TestCase (false)]
[TestCase (true)]
public void ConstantConstraint (bool useCompiledXaml)
{
var layout = new <API key> (useCompiledXaml);
var label = layout.constantConstraint;
var constraint = RelativeLayout.GetWidthConstraint (label);
Assert.NotNull (constraint);
Assert.AreEqual (42, constraint.Compute (null));
}
[TestCase (false)]
[TestCase (true)]
public void <API key> (bool useCompiledXaml)
{
var layout = new <API key> (useCompiledXaml);
layout.relativeLayout.Layout (new Rectangle (0, 0, 200, 200));
var label = layout.<API key>;
var constraint = RelativeLayout.GetWidthConstraint (label);
Assert.NotNull (constraint);
Assert.AreEqual (102, constraint.Compute (layout.relativeLayout));
}
[TestCase (false)]
[TestCase (true)]
public void <API key> (bool useCompiledXaml)
{
var layout = new <API key> (useCompiledXaml) {
IsPlatformEnabled = true
};
layout.relativeLayout.Layout (new Rectangle (0, 0, 200, 100));
layout.foo.Layout (new Rectangle (5, 5, 190, 25));
var label = layout.<API key>;
var constraint = RelativeLayout.GetWidthConstraint (label);
Assert.NotNull (constraint);
Assert.AreEqual (97, constraint.Compute (layout.relativeLayout));
}
}
}
}
|
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number): number {
return 5;
}
export default [
'qu-EC',
[
['a.m.', 'p.m.'],
,
],
,
[
['D', 'L', 'M', 'X', 'J', 'V', 'S'], ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sab'],
['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sab']
],
,
[
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Set', 'Oct', 'Nov', 'Dic'],
[
'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre',
'Octubre', 'Noviembre', 'Diciembre'
]
],
,
[
['BCE', 'dC'],
['BCE', 'd.C.'],
],
1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM, y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', , '{0} {1}', '{1} {0}'],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['
];
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Tue Dec 16 10:59:47 NZDT 2014 -->
<title>Instance</title>
<meta name="date" content="2014-12-16">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Instance";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../weka/core/GlobalInfoJavadoc.html" title="class in weka.core"><span class="strong">Prev Class</span></a></li>
<li><a href="../../weka/core/InstanceComparator.html" title="class in weka.core"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?weka/core/Instance.html" target="_top">Frames</a></li>
<li><a href="Instance.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">weka.core</div>
<h2 title="Class Instance" class="title">Class Instance</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>weka.core.Instance</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, <a href="../../weka/core/Copyable.html" title="interface in weka.core">Copyable</a>, <a href="../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</a></dd>
</dl>
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../weka/associations/tertius/IndividualInstance.html" title="class in weka.associations.tertius">IndividualInstance</a>, <a href="../../weka/core/SparseInstance.html" title="class in weka.core">SparseInstance</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">Instance</span>
extends java.lang.Object
implements <a href="../../weka/core/Copyable.html" title="interface in weka.core">Copyable</a>, java.io.Serializable, <a href="../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</a></pre>
<div class="block">Class for handling an instance. All values (numeric, date, nominal, string
or relational) are internally stored as floating-point numbers. If an
attribute is nominal (or a string or relational), the stored value is the
index of the corresponding nominal (or string or relational) value in the
attribute's definition. We have chosen this approach in favor of a more
elegant object-oriented approach because it is much faster. <p>
Typical usage (code from the main() method of this class): <p>
<code>
<br>
// Create empty instance with three attribute values <br>
Instance inst = new Instance(3); <br><br>
// Set instance's values for the attributes "length", "weight", and "position"<br>
inst.setValue(length, 5.3); <br>
inst.setValue(weight, 300); <br>
inst.setValue(position, "first"); <br><br>
// Set instance's dataset to be the dataset "race" <br>
inst.setDataset(race); <br><br>
// Print the instance <br>
System.out.println("The instance: " + inst); <br>
<br>
</code><p>
All methods that change an instance are safe, ie. a change of an
instance does not affect any other instances. All methods that
change an instance's attribute values clone the attribute value
vector before it is changed. If your application heavily modifies
instance values, it may be faster to create a new instance from scratch.</div>
<dl><dt><span class="strong">Version:</span></dt>
<dd>$Revision: 9140 $</dd>
<dt><span class="strong">Author:</span></dt>
<dd>Eibe Frank ([email protected])</dd>
<dt><span class="strong">See Also:</span></dt><dd><a href="../../serialized-form.html#weka.core.Instance">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../weka/core/Instance.html#Instance(double,%20double[])">Instance</a></strong>(double weight,
double[] attValues)</code>
<div class="block">Constructor that inititalizes instance variable with given
values.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../weka/core/Instance.html#Instance(weka.core.Instance)">Instance</a></strong>(<a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> instance)</code>
<div class="block">Constructor that copies the attribute values and the weight from
the given instance.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../weka/core/Instance.html#Instance(int)">Instance</a></strong>(int numAttributes)</code>
<div class="block">Constructor of an instance that sets weight to one, all values to
be missing, and the reference to the dataset to null.</div>
</td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#attribute(int)">attribute</a></strong>(int index)</code>
<div class="block">Returns the attribute with the given index.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#attributeSparse(int)">attributeSparse</a></strong>(int indexOfIndex)</code>
<div class="block">Returns the attribute with the given index.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#classAttribute()">classAttribute</a></strong>()</code>
<div class="block">Returns class attribute.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#classIndex()">classIndex</a></strong>()</code>
<div class="block">Returns the class attribute's index.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#classIsMissing()">classIsMissing</a></strong>()</code>
<div class="block">Tests if an instance's class is missing.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#classValue()">classValue</a></strong>()</code>
<div class="block">Returns an instance's class value in internal format.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Object</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#copy()">copy</a></strong>()</code>
<div class="block">Produces a shallow copy of this instance.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#dataset()">dataset</a></strong>()</code>
<div class="block">Returns the dataset this instance has access to.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#deleteAttributeAt(int)">deleteAttributeAt</a></strong>(int position)</code>
<div class="block">Deletes an attribute at the given position (0 to
numAttributes() - 1).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.Enumeration</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#enumerateAttributes()">enumerateAttributes</a></strong>()</code>
<div class="block">Returns an enumeration of all the attributes.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#equalHeaders(weka.core.Instance)">equalHeaders</a></strong>(<a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> inst)</code>
<div class="block">Tests if the headers of two instances are equivalent.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#getRevision()">getRevision</a></strong>()</code>
<div class="block">Returns the revision string.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#hasMissingValue()">hasMissingValue</a></strong>()</code>
<div class="block">Tests whether an instance has a missing value.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#index(int)">index</a></strong>(int position)</code>
<div class="block">Returns the index of the attribute stored at the given position.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#insertAttributeAt(int)">insertAttributeAt</a></strong>(int position)</code>
<div class="block">Inserts an attribute at the given position (0 to
numAttributes()).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#isMissing(weka.core.Attribute)">isMissing</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</code>
<div class="block">Tests if a specific value is "missing".</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#isMissing(int)">isMissing</a></strong>(int attIndex)</code>
<div class="block">Tests if a specific value is "missing".</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#isMissingSparse(int)">isMissingSparse</a></strong>(int indexOfIndex)</code>
<div class="block">Tests if a specific value is "missing".</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static boolean</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#isMissingValue(double)">isMissingValue</a></strong>(double val)</code>
<div class="block">Tests if the given value codes "missing".</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#main(java.lang.String[])">main</a></strong>(java.lang.String[] options)</code>
<div class="block">Main method for testing this class.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#mergeInstance(weka.core.Instance)">mergeInstance</a></strong>(<a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> inst)</code>
<div class="block">Merges this instance with the given instance and returns
the result.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static double</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#missingValue()">missingValue</a></strong>()</code>
<div class="block">Returns the double that codes "missing".</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#numAttributes()">numAttributes</a></strong>()</code>
<div class="block">Returns the number of attributes.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#numClasses()">numClasses</a></strong>()</code>
<div class="block">Returns the number of class labels.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#numValues()">numValues</a></strong>()</code>
<div class="block">Returns the number of values present.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#relationalValue(weka.core.Attribute)">relationalValue</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</code>
<div class="block">Returns the relational value of a relational attribute.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a></code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#relationalValue(int)">relationalValue</a></strong>(int attIndex)</code>
<div class="block">Returns the relational value of a relational attribute.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#<API key>(double[])"><API key></a></strong>(double[] array)</code>
<div class="block">Replaces all missing values in the instance with the
values contained in the given array.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setClassMissing()">setClassMissing</a></strong>()</code>
<div class="block">Sets the class value of an instance to be "missing".</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setClassValue(double)">setClassValue</a></strong>(double value)</code>
<div class="block">Sets the class value of an instance to the given value (internal
floating-point format).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setClassValue(java.lang.String)">setClassValue</a></strong>(java.lang.String value)</code>
<div class="block">Sets the class value of an instance to the given value.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setDataset(weka.core.Instances)">setDataset</a></strong>(<a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a> instances)</code>
<div class="block">Sets the reference to the dataset.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setMissing(weka.core.Attribute)">setMissing</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</code>
<div class="block">Sets a specific value to be "missing".</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setMissing(int)">setMissing</a></strong>(int attIndex)</code>
<div class="block">Sets a specific value to be "missing".</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setValue(weka.core.Attribute,%20double)">setValue</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att,
double value)</code>
<div class="block">Sets a specific value in the instance to the given value
(internal floating-point format).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setValue(weka.core.Attribute,%20java.lang.String)">setValue</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att,
java.lang.String value)</code>
<div class="block">Sets a value of an nominal or string attribute to the given
value.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setValue(int,%20double)">setValue</a></strong>(int attIndex,
double value)</code>
<div class="block">Sets a specific value in the instance to the given value
(internal floating-point format).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setValue(int,%20java.lang.String)">setValue</a></strong>(int attIndex,
java.lang.String value)</code>
<div class="block">Sets a value of a nominal or string attribute to the given
value.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setValueSparse(int,%20double)">setValueSparse</a></strong>(int indexOfIndex,
double value)</code>
<div class="block">Sets a specific value in the instance to the given value
(internal floating-point format).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#setWeight(double)">setWeight</a></strong>(double weight)</code>
<div class="block">Sets the weight of an instance.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#stringValue(weka.core.Attribute)">stringValue</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</code>
<div class="block">Returns the value of a nominal, string, date, or relational attribute
for the instance as a string.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#stringValue(int)">stringValue</a></strong>(int attIndex)</code>
<div class="block">Returns the value of a nominal, string, date, or relational attribute
for the instance as a string.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double[]</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#toDoubleArray()">toDoubleArray</a></strong>()</code>
<div class="block">Returns the values of each attribute as an array of doubles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#toString()">toString</a></strong>()</code>
<div class="block">Returns the description of one instance.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#toString(weka.core.Attribute)">toString</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</code>
<div class="block">Returns the description of one value of the instance as a
string.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#toString(int)">toString</a></strong>(int attIndex)</code>
<div class="block">Returns the description of one value of the instance as a
string.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#value(weka.core.Attribute)">value</a></strong>(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</code>
<div class="block">Returns an instance's attribute value in internal format.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#value(int)">value</a></strong>(int attIndex)</code>
<div class="block">Returns an instance's attribute value in internal format.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#valueSparse(int)">valueSparse</a></strong>(int indexOfIndex)</code>
<div class="block">Returns an instance's attribute value in internal format.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../weka/core/Instance.html#weight()">weight</a></strong>()</code>
<div class="block">Returns the instance's weight.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="Instance(weka.core.Instance)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>Instance</h4>
<pre>public Instance(<a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> instance)</pre>
<div class="block">Constructor that copies the attribute values and the weight from
the given instance. Reference to the dataset is set to null.
(ie. the instance doesn't have access to information about the
attribute types)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>instance</code> - the instance from which the attribute
values and the weight are to be copied</dd></dl>
</li>
</ul>
<a name="Instance(double, double[])">
</a>
<ul class="blockList">
<li class="blockList">
<h4>Instance</h4>
<pre>public Instance(double weight,
double[] attValues)</pre>
<div class="block">Constructor that inititalizes instance variable with given
values. Reference to the dataset is set to null. (ie. the instance
doesn't have access to information about the attribute types)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>weight</code> - the instance's weight</dd><dd><code>attValues</code> - a vector of attribute values</dd></dl>
</li>
</ul>
<a name="Instance(int)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Instance</h4>
<pre>public Instance(int numAttributes)</pre>
<div class="block">Constructor of an instance that sets weight to one, all values to
be missing, and the reference to the dataset to null. (ie. the instance
doesn't have access to information about the attribute types)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>numAttributes</code> - the size of the instance</dd></dl>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="attribute(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>attribute</h4>
<pre>public <a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> attribute(int index)</pre>
<div class="block">Returns the attribute with the given index.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>index</code> - the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the attribute at the given position</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if instance doesn't have access to a
dataset</dd></dl>
</li>
</ul>
<a name="attributeSparse(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>attributeSparse</h4>
<pre>public <a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> attributeSparse(int indexOfIndex)</pre>
<div class="block">Returns the attribute with the given index. Does the same
thing as attribute().</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>indexOfIndex</code> - the index of the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the attribute at the given position</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if instance doesn't have access to a
dataset</dd></dl>
</li>
</ul>
<a name="classAttribute()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>classAttribute</h4>
<pre>public <a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> classAttribute()</pre>
<div class="block">Returns class attribute.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the class attribute</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the class is not set or the
instance doesn't have access to a dataset</dd></dl>
</li>
</ul>
<a name="classIndex()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>classIndex</h4>
<pre>public int classIndex()</pre>
<div class="block">Returns the class attribute's index.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the class index as an integer</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if instance doesn't have access to a dataset</dd></dl>
</li>
</ul>
<a name="classIsMissing()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>classIsMissing</h4>
<pre>public boolean classIsMissing()</pre>
<div class="block">Tests if an instance's class is missing.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>true if the instance's class is missing</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the class is not set or the instance doesn't
have access to a dataset</dd></dl>
</li>
</ul>
<a name="classValue()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>classValue</h4>
<pre>public double classValue()</pre>
<div class="block">Returns an instance's class value in internal format. (ie. as a
floating-point number)</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the corresponding value as a double (If the
corresponding attribute is nominal (or a string) then it returns the
value's index as a double).</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the class is not set or the instance doesn't
have access to a dataset</dd></dl>
</li>
</ul>
<a name="copy()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>copy</h4>
<pre>public java.lang.Object copy()</pre>
<div class="block">Produces a shallow copy of this instance. The copy has
access to the same dataset. (if you want to make a copy
that doesn't have access to the dataset, use
<code>new Instance(instance)</code></div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../weka/core/Copyable.html#copy()">copy</a></code> in interface <code><a href="../../weka/core/Copyable.html" title="interface in weka.core">Copyable</a></code></dd>
<dt><span class="strong">Returns:</span></dt><dd>the shallow copy</dd></dl>
</li>
</ul>
<a name="dataset()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>dataset</h4>
<pre>public <a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a> dataset()</pre>
<div class="block">Returns the dataset this instance has access to. (ie. obtains
information about attribute types from) Null if the instance
doesn't have access to a dataset.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the dataset the instance has accesss to</dd></dl>
</li>
</ul>
<a name="deleteAttributeAt(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>deleteAttributeAt</h4>
<pre>public void deleteAttributeAt(int position)</pre>
<div class="block">Deletes an attribute at the given position (0 to
numAttributes() - 1). Only succeeds if the instance does not
have access to any dataset because otherwise inconsistencies
could be introduced.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>position</code> - the attribute's position</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.RuntimeException</code> - if the instance has access to a
dataset</dd></dl>
</li>
</ul>
<a name="enumerateAttributes()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>enumerateAttributes</h4>
<pre>public java.util.Enumeration enumerateAttributes()</pre>
<div class="block">Returns an enumeration of all the attributes.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>enumeration of all the attributes</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the instance doesn't
have access to a dataset</dd></dl>
</li>
</ul>
<a name="equalHeaders(weka.core.Instance)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>equalHeaders</h4>
<pre>public boolean equalHeaders(<a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> inst)</pre>
<div class="block">Tests if the headers of two instances are equivalent.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>inst</code> - another instance</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if the header of the given instance is
equivalent to this instance's header</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if instance doesn't have access to any
dataset</dd></dl>
</li>
</ul>
<a name="hasMissingValue()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasMissingValue</h4>
<pre>public boolean hasMissingValue()</pre>
<div class="block">Tests whether an instance has a missing value. Skips the class attribute if set.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>true if instance has a missing value.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if instance doesn't have access to any
dataset</dd></dl>
</li>
</ul>
<a name="index(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>index</h4>
<pre>public int index(int position)</pre>
<div class="block">Returns the index of the attribute stored at the given position.
Just returns the given value.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>position</code> - the position</dd>
<dt><span class="strong">Returns:</span></dt><dd>the index of the attribute stored at the given position</dd></dl>
</li>
</ul>
<a name="insertAttributeAt(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>insertAttributeAt</h4>
<pre>public void insertAttributeAt(int position)</pre>
<div class="block">Inserts an attribute at the given position (0 to
numAttributes()). Only succeeds if the instance does not
have access to any dataset because otherwise inconsistencies
could be introduced.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>position</code> - the attribute's position</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.RuntimeException</code> - if the instance has accesss to a
dataset</dd>
<dd><code>java.lang.<API key></code> - if the position is out of range</dd></dl>
</li>
</ul>
<a name="isMissing(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>isMissing</h4>
<pre>public boolean isMissing(int attIndex)</pre>
<div class="block">Tests if a specific value is "missing".</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if the value is "missing"</dd></dl>
</li>
</ul>
<a name="isMissingSparse(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>isMissingSparse</h4>
<pre>public boolean isMissingSparse(int indexOfIndex)</pre>
<div class="block">Tests if a specific value is "missing". Does
the same thing as isMissing() if applied to an Instance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>indexOfIndex</code> - the index of the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if the value is "missing"</dd></dl>
</li>
</ul>
<a name="isMissing(weka.core.Attribute)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>isMissing</h4>
<pre>public boolean isMissing(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</pre>
<div class="block">Tests if a specific value is "missing".
The given attribute has to belong to a dataset.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if the value is "missing"</dd></dl>
</li>
</ul>
<a name="isMissingValue(double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>isMissingValue</h4>
<pre>public static boolean isMissingValue(double val)</pre>
<div class="block">Tests if the given value codes "missing".</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>val</code> - the value to be tested</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if val codes "missing"</dd></dl>
</li>
</ul>
<a name="mergeInstance(weka.core.Instance)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>mergeInstance</h4>
<pre>public <a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> mergeInstance(<a href="../../weka/core/Instance.html" title="class in weka.core">Instance</a> inst)</pre>
<div class="block">Merges this instance with the given instance and returns
the result. Dataset is set to null.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>inst</code> - the instance to be merged with this one</dd>
<dt><span class="strong">Returns:</span></dt><dd>the merged instances</dd></dl>
</li>
</ul>
<a name="missingValue()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>missingValue</h4>
<pre>public static double missingValue()</pre>
<div class="block">Returns the double that codes "missing".</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the double that codes "missing"</dd></dl>
</li>
</ul>
<a name="numAttributes()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>numAttributes</h4>
<pre>public int numAttributes()</pre>
<div class="block">Returns the number of attributes.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the number of attributes as an integer</dd></dl>
</li>
</ul>
<a name="numClasses()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>numClasses</h4>
<pre>public int numClasses()</pre>
<div class="block">Returns the number of class labels.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the number of class labels as an integer if the
class attribute is nominal, 1 otherwise.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if instance doesn't have access to any
dataset</dd></dl>
</li>
</ul>
<a name="numValues()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>numValues</h4>
<pre>public int numValues()</pre>
<div class="block">Returns the number of values present. Always the same as numAttributes().</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the number of values</dd></dl>
</li>
</ul>
<a name="<API key>(double[])">
</a>
<ul class="blockList">
<li class="blockList">
<h4><API key></h4>
<pre>public void <API key>(double[] array)</pre>
<div class="block">Replaces all missing values in the instance with the
values contained in the given array. A deep copy of
the vector of attribute values is performed before the
values are replaced.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>array</code> - containing the means and modes</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.<API key></code> - if numbers of attributes are unequal</dd></dl>
</li>
</ul>
<a name="setClassMissing()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setClassMissing</h4>
<pre>public void setClassMissing()</pre>
<div class="block">Sets the class value of an instance to be "missing". A deep copy of
the vector of attribute values is performed before the
value is set to be missing.</div>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the class is not set</dd>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the instance doesn't
have access to a dataset</dd></dl>
</li>
</ul>
<a name="setClassValue(double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setClassValue</h4>
<pre>public void setClassValue(double value)</pre>
<div class="block">Sets the class value of an instance to the given value (internal
floating-point format). A deep copy of the vector of attribute
values is performed before the value is set.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - the new attribute value (If the corresponding
attribute is nominal (or a string) then this is the new value's
index as a double).</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the class is not set</dd>
<dd><code><API key></code> - if the instance doesn't
have access to a dataset</dd></dl>
</li>
</ul>
<a name="setClassValue(java.lang.String)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setClassValue</h4>
<pre>public final void setClassValue(java.lang.String value)</pre>
<div class="block">Sets the class value of an instance to the given value. A deep
copy of the vector of attribute values is performed before the
value is set.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - the new class value (If the class
is a string attribute and the value can't be found,
the value is added to the attribute).</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the class is not set</dd>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the dataset is not set</dd>
<dd><code>java.lang.<API key></code> - if the attribute is not
nominal or a string, or the value couldn't be found for a nominal
attribute</dd></dl>
</li>
</ul>
<a name="setDataset(weka.core.Instances)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDataset</h4>
<pre>public final void setDataset(<a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a> instances)</pre>
<div class="block">Sets the reference to the dataset. Does not check if the instance
is compatible with the dataset. Note: the dataset does not know
about this instance. If the structure of the dataset's header
gets changed, this instance will not be adjusted automatically.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>instances</code> - the reference to the dataset</dd></dl>
</li>
</ul>
<a name="setMissing(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setMissing</h4>
<pre>public final void setMissing(int attIndex)</pre>
<div class="block">Sets a specific value to be "missing". Performs a deep copy
of the vector of attribute values before the value is set to
be missing.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd></dl>
</li>
</ul>
<a name="setMissing(weka.core.Attribute)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setMissing</h4>
<pre>public final void setMissing(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</pre>
<div class="block">Sets a specific value to be "missing". Performs a deep copy
of the vector of attribute values before the value is set to
be missing. The given attribute has to belong to a dataset.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd></dl>
</li>
</ul>
<a name="setValue(int, double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setValue</h4>
<pre>public void setValue(int attIndex,
double value)</pre>
<div class="block">Sets a specific value in the instance to the given value
(internal floating-point format). Performs a deep copy
of the vector of attribute values before the value is set.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd><dd><code>value</code> - the new attribute value (If the corresponding
attribute is nominal (or a string) then this is the new value's
index as a double).</dd></dl>
</li>
</ul>
<a name="setValueSparse(int, double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setValueSparse</h4>
<pre>public void setValueSparse(int indexOfIndex,
double value)</pre>
<div class="block">Sets a specific value in the instance to the given value
(internal floating-point format). Performs a deep copy
of the vector of attribute values before the value is set.
Does exactly the same thing as setValue().</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>indexOfIndex</code> - the index of the attribute's index</dd><dd><code>value</code> - the new attribute value (If the corresponding
attribute is nominal (or a string) then this is the new value's
index as a double).</dd></dl>
</li>
</ul>
<a name="setValue(int, java.lang.String)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setValue</h4>
<pre>public final void setValue(int attIndex,
java.lang.String value)</pre>
<div class="block">Sets a value of a nominal or string attribute to the given
value. Performs a deep copy of the vector of attribute values
before the value is set.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd><dd><code>value</code> - the new attribute value (If the attribute
is a string attribute and the value can't be found,
the value is added to the attribute).</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the dataset is not set</dd>
<dd><code>java.lang.<API key></code> - if the selected
attribute is not nominal or a string, or the supplied value couldn't
be found for a nominal attribute</dd></dl>
</li>
</ul>
<a name="setValue(weka.core.Attribute, double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setValue</h4>
<pre>public final void setValue(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att,
double value)</pre>
<div class="block">Sets a specific value in the instance to the given value
(internal floating-point format). Performs a deep copy of the
vector of attribute values before the value is set, so if you are
planning on calling setValue many times it may be faster to
create a new instance using toDoubleArray. The given attribute
has to belong to a dataset.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd><dd><code>value</code> - the new attribute value (If the corresponding
attribute is nominal (or a string) then this is the new value's
index as a double).</dd></dl>
</li>
</ul>
<a name="setValue(weka.core.Attribute, java.lang.String)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setValue</h4>
<pre>public final void setValue(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att,
java.lang.String value)</pre>
<div class="block">Sets a value of an nominal or string attribute to the given
value. Performs a deep copy of the vector of attribute values
before the value is set, so if you are planning on calling setValue many
times it may be faster to create a new instance using toDoubleArray.
The given attribute has to belong to a dataset.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd><dd><code>value</code> - the new attribute value (If the attribute
is a string attribute and the value can't be found,
the value is added to the attribute).</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.<API key></code> - if the the attribute is not
nominal or a string, or the value couldn't be found for a nominal
attribute</dd></dl>
</li>
</ul>
<a name="setWeight(double)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setWeight</h4>
<pre>public final void setWeight(double weight)</pre>
<div class="block">Sets the weight of an instance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>weight</code> - the weight</dd></dl>
</li>
</ul>
<a name="relationalValue(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>relationalValue</h4>
<pre>public final <a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a> relationalValue(int attIndex)</pre>
<div class="block">Returns the relational value of a relational attribute.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the corresponding relation as an Instances object</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.<API key></code> - if the attribute is not a
relation-valued attribute</dd>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the instance doesn't belong
to a dataset.</dd></dl>
</li>
</ul>
<a name="relationalValue(weka.core.Attribute)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>relationalValue</h4>
<pre>public final <a href="../../weka/core/Instances.html" title="class in weka.core">Instances</a> relationalValue(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</pre>
<div class="block">Returns the relational value of a relational attribute.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd>
<dt><span class="strong">Returns:</span></dt><dd>the corresponding relation as an Instances object</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.<API key></code> - if the attribute is not a
relation-valued attribute</dd>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the instance doesn't belong
to a dataset.</dd></dl>
</li>
</ul>
<a name="stringValue(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>stringValue</h4>
<pre>public final java.lang.String stringValue(int attIndex)</pre>
<div class="block">Returns the value of a nominal, string, date, or relational attribute
for the instance as a string.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the value as a string</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.<API key></code> - if the attribute is not a nominal,
string, date, or relation-valued attribute.</dd>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the instance doesn't belong
to a dataset.</dd></dl>
</li>
</ul>
<a name="stringValue(weka.core.Attribute)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>stringValue</h4>
<pre>public final java.lang.String stringValue(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</pre>
<div class="block">Returns the value of a nominal, string, date, or relational attribute
for the instance as a string.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd>
<dt><span class="strong">Returns:</span></dt><dd>the value as a string</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.<API key></code> - if the attribute is not a nominal,
string, date, or relation-valued attribute.</dd>
<dd><code><a href="../../weka/core/<API key>.html" title="class in weka.core"><API key></a></code> - if the instance doesn't belong
to a dataset.</dd></dl>
</li>
</ul>
<a name="toDoubleArray()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toDoubleArray</h4>
<pre>public double[] toDoubleArray()</pre>
<div class="block">Returns the values of each attribute as an array of doubles.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing all the instance attribute values</dd></dl>
</li>
</ul>
<a name="toString()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<div class="block">Returns the description of one instance. If the instance
doesn't have access to a dataset, it returns the internal
floating-point values. Quotes string
values that contain whitespace characters.</div>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
<dt><span class="strong">Returns:</span></dt><dd>the instance's description as a string</dd></dl>
</li>
</ul>
<a name="toString(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public final java.lang.String toString(int attIndex)</pre>
<div class="block">Returns the description of one value of the instance as a
string. If the instance doesn't have access to a dataset, it
returns the internal floating-point value. Quotes string
values that contain whitespace characters, or if they
are a question mark.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the value's description as a string</dd></dl>
</li>
</ul>
<a name="toString(weka.core.Attribute)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public final java.lang.String toString(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</pre>
<div class="block">Returns the description of one value of the instance as a
string. If the instance doesn't have access to a dataset it
returns the internal floating-point value. Quotes string
values that contain whitespace characters, or if they
are a question mark.
The given attribute has to belong to a dataset.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd>
<dt><span class="strong">Returns:</span></dt><dd>the value's description as a string</dd></dl>
</li>
</ul>
<a name="value(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>value</h4>
<pre>public double value(int attIndex)</pre>
<div class="block">Returns an instance's attribute value in internal format.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attIndex</code> - the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the specified value as a double (If the corresponding
attribute is nominal (or a string) then it returns the value's index as a
double).</dd></dl>
</li>
</ul>
<a name="valueSparse(int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueSparse</h4>
<pre>public double valueSparse(int indexOfIndex)</pre>
<div class="block">Returns an instance's attribute value in internal format.
Does exactly the same thing as value() if applied to an Instance.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>indexOfIndex</code> - the index of the attribute's index</dd>
<dt><span class="strong">Returns:</span></dt><dd>the specified value as a double (If the corresponding
attribute is nominal (or a string) then it returns the value's index as a
double).</dd></dl>
</li>
</ul>
<a name="value(weka.core.Attribute)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>value</h4>
<pre>public double value(<a href="../../weka/core/Attribute.html" title="class in weka.core">Attribute</a> att)</pre>
<div class="block">Returns an instance's attribute value in internal format.
The given attribute has to belong to a dataset.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>att</code> - the attribute</dd>
<dt><span class="strong">Returns:</span></dt><dd>the specified value as a double (If the corresponding
attribute is nominal (or a string) then it returns the value's index as a
double).</dd></dl>
</li>
</ul>
<a name="weight()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>weight</h4>
<pre>public final double weight()</pre>
<div class="block">Returns the instance's weight.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the instance's weight as a double</dd></dl>
</li>
</ul>
<a name="main(java.lang.String[])">
</a>
<ul class="blockList">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(java.lang.String[] options)</pre>
<div class="block">Main method for testing this class.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>options</code> - the commandline options - ignored</dd></dl>
</li>
</ul>
<a name="getRevision()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getRevision</h4>
<pre>public java.lang.String getRevision()</pre>
<div class="block">Returns the revision string.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../weka/core/RevisionHandler.html#getRevision()">getRevision</a></code> in interface <code><a href="../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</a></code></dd>
<dt><span class="strong">Returns:</span></dt><dd>the revision</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../weka/core/GlobalInfoJavadoc.html" title="class in weka.core"><span class="strong">Prev Class</span></a></li>
<li><a href="../../weka/core/InstanceComparator.html" title="class in weka.core"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?weka/core/Instance.html" target="_top">Frames</a></li>
<li><a href="Instance.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
#nullable enable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.<API key>
{
internal abstract partial class <API key>
{
private class <API key> : <API key>
{
private readonly <API key> _codeFixProvider;
public <API key>(<API key> codeFixProvider)
=> _codeFixProvider = codeFixProvider;
protected override string CodeActionTitle
=> FeaturesResources.<API key>;
protected override Task<SyntaxNode?> <API key>(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
=> _codeFixProvider.FixAllAsync(document, diagnostics, fixAllContext.<API key>, fixAllContext.CancellationToken).AsNullable();
}
}
}
|
#include "efx.h"
#include "efx_impl.h"
#if EFSYS_OPT_BOOTCFG
/*
* Maximum size of BOOTCFG block across all nics as understood by SFCgPXE.
* NOTE: This is larger than the Medford per-PF bootcfg sector.
*/
#define BOOTCFG_MAX_SIZE 0x1000
/* Medford per-PF bootcfg sector */
#define BOOTCFG_PER_PF 0x800
#define BOOTCFG_PF_COUNT 16
#define DHCP_OPT_HAS_VALUE(opt) \
(((opt) > EFX_DHCP_PAD) && ((opt) < EFX_DHCP_END))
#define DHCP_MAX_VALUE 255
#define DHCP_ENCAPSULATOR(encap_opt) ((encap_opt) >> 8)
#define DHCP_ENCAPSULATED(encap_opt) ((encap_opt) & 0xff)
#define DHCP_IS_ENCAP_OPT(opt) DHCP_OPT_HAS_VALUE(DHCP_ENCAPSULATOR(opt))
typedef struct efx_dhcp_tag_hdr_s {
uint8_t tag;
uint8_t length;
} efx_dhcp_tag_hdr_t;
/*
* Length calculations for tags with value field. PAD and END
* have a fixed length of 1, with no length or value field.
*/
#define <API key>(hdr) \
(sizeof (efx_dhcp_tag_hdr_t) + (hdr)->length)
#define DHCP_NEXT_TAG(hdr) \
((efx_dhcp_tag_hdr_t *)(((uint8_t *)(hdr)) + \
<API key>((hdr))))
#define <API key>(payload_len) \
((payload_len) + sizeof (efx_dhcp_tag_hdr_t))
/* Report the layout of bootcfg sectors in NVRAM partition. */
__checkReturn efx_rc_t
<API key>(
__in efx_nic_t *enp,
__in uint32_t pf,
__out_opt uint32_t *sector_countp,
__out size_t *offsetp,
__out size_t *max_sizep)
{
uint32_t count;
size_t max_size;
size_t offset;
int rc;
switch (enp->en_family) {
#if EFSYS_OPT_SIENA
case EFX_FAMILY_SIENA:
max_size = BOOTCFG_MAX_SIZE;
offset = 0;
count = 1;
break;
#endif /* EFSYS_OPT_SIENA */
#if <API key>
case <API key>:
max_size = BOOTCFG_MAX_SIZE;
offset = 0;
count = 1;
break;
#endif /* <API key> */
#if EFSYS_OPT_MEDFORD
case EFX_FAMILY_MEDFORD: {
/* Shared partition (array indexed by PF) */
max_size = BOOTCFG_PER_PF;
count = BOOTCFG_PF_COUNT;
if (pf >= count) {
rc = EINVAL;
goto fail2;
}
offset = max_size * pf;
break;
}
#endif /* EFSYS_OPT_MEDFORD */
#if EFSYS_OPT_MEDFORD2
case EFX_FAMILY_MEDFORD2: {
/* Shared partition (array indexed by PF) */
max_size = BOOTCFG_PER_PF;
count = BOOTCFG_PF_COUNT;
if (pf >= count) {
rc = EINVAL;
goto fail3;
}
offset = max_size * pf;
break;
}
#endif /* EFSYS_OPT_MEDFORD2 */
default:
EFSYS_ASSERT(0);
rc = ENOTSUP;
goto fail1;
}
EFSYS_ASSERT3U(max_size, <=, BOOTCFG_MAX_SIZE);
if (sector_countp != NULL)
*sector_countp = count;
*offsetp = offset;
*max_sizep = max_size;
return (0);
#if EFSYS_OPT_MEDFORD2
fail3:
EFSYS_PROBE(fail3);
#endif
#if EFSYS_OPT_MEDFORD
fail2:
EFSYS_PROBE(fail2);
#endif
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
__checkReturn uint8_t
efx_dhcp_csum(
__in_bcount(size) uint8_t const *data,
__in size_t size)
{
unsigned int pos;
uint8_t checksum = 0;
for (pos = 0; pos < size; pos++)
checksum += data[pos];
return (checksum);
}
__checkReturn efx_rc_t
efx_dhcp_verify(
__in_bcount(size) uint8_t const *data,
__in size_t size,
__out_opt size_t *usedp)
{
size_t offset = 0;
size_t used = 0;
efx_rc_t rc;
/* Start parsing tags immediately after the checksum */
for (offset = 1; offset < size; ) {
uint8_t tag;
uint8_t length;
/* Consume tag */
tag = data[offset];
if (tag == EFX_DHCP_END) {
offset++;
used = offset;
break;
}
if (tag == EFX_DHCP_PAD) {
offset++;
continue;
}
/* Consume length */
if (offset + 1 >= size) {
rc = ENOSPC;
goto fail1;
}
length = data[offset + 1];
/* Consume *length */
if (offset + 1 + length >= size) {
rc = ENOSPC;
goto fail2;
}
offset += 2 + length;
used = offset;
}
/* Checksum the entire sector, including bytes after any EFX_DHCP_END */
if (efx_dhcp_csum(data, size) != 0) {
rc = EINVAL;
goto fail3;
}
if (usedp != NULL)
*usedp = used;
return (0);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Walk the entire tag set looking for option. The sought option may be
* encapsulated. ENOENT indicates the walk completed without finding the
* option. If we run out of buffer during the walk the function will return
* ENOSPC.
*/
static efx_rc_t
efx_dhcp_walk_tags(
__deref_inout uint8_t **tagpp,
__inout size_t *buffer_sizep,
__in uint16_t opt)
{
efx_rc_t rc = 0;
boolean_t is_encap = B_FALSE;
if (DHCP_IS_ENCAP_OPT(opt)) {
/*
* Look for the encapsulator and, if found, limit ourselves
* to its payload. If it's not found then the entire tag
* cannot be found, so the encapsulated opt search is
* skipped.
*/
rc = efx_dhcp_walk_tags(tagpp, buffer_sizep,
DHCP_ENCAPSULATOR(opt));
if (rc == 0) {
*buffer_sizep = ((efx_dhcp_tag_hdr_t *)*tagpp)->length;
(*tagpp) += sizeof (efx_dhcp_tag_hdr_t);
}
opt = DHCP_ENCAPSULATED(opt);
is_encap = B_TRUE;
}
EFSYS_ASSERT(!DHCP_IS_ENCAP_OPT(opt));
while (rc == 0) {
size_t size;
if (*buffer_sizep == 0) {
rc = ENOSPC;
goto fail1;
}
if (DHCP_ENCAPSULATED(**tagpp) == opt)
break;
if ((**tagpp) == EFX_DHCP_END) {
rc = ENOENT;
break;
} else if ((**tagpp) == EFX_DHCP_PAD) {
size = 1;
} else {
if (*buffer_sizep < sizeof (efx_dhcp_tag_hdr_t)) {
rc = ENOSPC;
goto fail2;
}
size =
<API key>((efx_dhcp_tag_hdr_t *)*tagpp);
}
if (size > *buffer_sizep) {
rc = ENOSPC;
goto fail3;
}
(*tagpp) += size;
(*buffer_sizep) -= size;
if ((*buffer_sizep == 0) && is_encap) {
/* Search within encapulator tag finished */
rc = ENOENT;
break;
}
}
/*
* Returns 0 if found otherwise ENOENT indicating search finished
* correctly
*/
return (rc);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Locate value buffer for option in the given buffer.
* Returns 0 if found, ENOENT indicating search finished
* correctly, otherwise search failed before completion.
*/
__checkReturn efx_rc_t
efx_dhcp_find_tag(
__in_bcount(buffer_length) uint8_t *bufferp,
__in size_t buffer_length,
__in uint16_t opt,
__deref_out uint8_t **valuepp,
__out size_t *value_lengthp)
{
efx_rc_t rc;
uint8_t *tagp = bufferp;
size_t len = buffer_length;
rc = efx_dhcp_walk_tags(&tagp, &len, opt);
if (rc == 0) {
efx_dhcp_tag_hdr_t *hdrp;
hdrp = (efx_dhcp_tag_hdr_t *)tagp;
*valuepp = (uint8_t *)(&hdrp[1]);
*value_lengthp = hdrp->length;
} else if (rc != ENOENT) {
goto fail1;
}
return (rc);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Locate the end tag in the given buffer.
* Returns 0 if found, ENOENT indicating search finished
* correctly but end tag was not found; otherwise search
* failed before completion.
*/
__checkReturn efx_rc_t
efx_dhcp_find_end(
__in_bcount(buffer_length) uint8_t *bufferp,
__in size_t buffer_length,
__deref_out uint8_t **endpp)
{
efx_rc_t rc;
uint8_t *endp = bufferp;
size_t len = buffer_length;
rc = efx_dhcp_walk_tags(&endp, &len, EFX_DHCP_END);
if (rc == 0)
*endpp = endp;
else if (rc != ENOENT)
goto fail1;
return (rc);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Delete the given tag from anywhere in the buffer. Copes with
* encapsulated tags, and updates or deletes the encapsulating opt as
* necessary.
*/
__checkReturn efx_rc_t
efx_dhcp_delete_tag(
__inout_bcount(buffer_length) uint8_t *bufferp,
__in size_t buffer_length,
__in uint16_t opt)
{
efx_rc_t rc;
efx_dhcp_tag_hdr_t *hdrp;
size_t len;
uint8_t *startp;
uint8_t *endp;
len = buffer_length;
startp = bufferp;
if (!DHCP_OPT_HAS_VALUE(DHCP_ENCAPSULATED(opt))) {
rc = EINVAL;
goto fail1;
}
rc = efx_dhcp_walk_tags(&startp, &len, opt);
if (rc != 0)
goto fail1;
hdrp = (efx_dhcp_tag_hdr_t *)startp;
if (DHCP_IS_ENCAP_OPT(opt)) {
uint8_t tag_length = <API key>(hdrp);
uint8_t *encapp = bufferp;
efx_dhcp_tag_hdr_t *encap_hdrp;
len = buffer_length;
rc = efx_dhcp_walk_tags(&encapp, &len,
DHCP_ENCAPSULATOR(opt));
if (rc != 0)
goto fail2;
encap_hdrp = (efx_dhcp_tag_hdr_t *)encapp;
if (encap_hdrp->length > tag_length) {
encap_hdrp->length = (uint8_t)(
(size_t)encap_hdrp->length - tag_length);
} else {
/* delete the encapsulating tag */
hdrp = encap_hdrp;
}
}
startp = (uint8_t *)hdrp;
endp = (uint8_t *)DHCP_NEXT_TAG(hdrp);
if (startp < bufferp) {
rc = EINVAL;
goto fail3;
}
if (endp > &bufferp[buffer_length]) {
rc = EINVAL;
goto fail4;
}
memmove(startp, endp,
buffer_length - (endp - bufferp));
return (0);
fail4:
EFSYS_PROBE(fail4);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Write the tag header into write_pointp and optionally copies the payload
* into the space following.
*/
static void
efx_dhcp_write_tag(
__in uint8_t *write_pointp,
__in uint16_t opt,
__in_bcount_opt(value_length)
uint8_t *valuep,
__in size_t value_length)
{
efx_dhcp_tag_hdr_t *hdrp = (efx_dhcp_tag_hdr_t *)write_pointp;
hdrp->tag = DHCP_ENCAPSULATED(opt);
hdrp->length = (uint8_t)value_length;
if ((value_length > 0) && (valuep != NULL))
memcpy(&hdrp[1], valuep, value_length);
}
/*
* Add the given tag to the end of the buffer. Copes with creating an
* encapsulated tag, and updates or creates the encapsulating opt as
* necessary.
*/
__checkReturn efx_rc_t
efx_dhcp_add_tag(
__inout_bcount(buffer_length) uint8_t *bufferp,
__in size_t buffer_length,
__in uint16_t opt,
__in_bcount_opt(value_length) uint8_t *valuep,
__in size_t value_length)
{
efx_rc_t rc;
efx_dhcp_tag_hdr_t *encap_hdrp = NULL;
uint8_t *insert_pointp = NULL;
uint8_t *endp;
size_t available_space;
size_t added_length;
size_t search_size;
uint8_t *searchp;
if (!DHCP_OPT_HAS_VALUE(DHCP_ENCAPSULATED(opt))) {
rc = EINVAL;
goto fail1;
}
if (value_length > DHCP_MAX_VALUE) {
rc = EINVAL;
goto fail2;
}
if ((value_length > 0) && (valuep == NULL)) {
rc = EINVAL;
goto fail3;
}
endp = bufferp;
available_space = buffer_length;
rc = efx_dhcp_walk_tags(&endp, &available_space, EFX_DHCP_END);
if (rc != 0)
goto fail4;
searchp = bufferp;
search_size = buffer_length;
if (DHCP_IS_ENCAP_OPT(opt)) {
rc = efx_dhcp_walk_tags(&searchp, &search_size,
DHCP_ENCAPSULATOR(opt));
if (rc == 0) {
encap_hdrp = (efx_dhcp_tag_hdr_t *)searchp;
/* Check encapsulated tag is not present */
search_size = encap_hdrp->length;
rc = efx_dhcp_walk_tags(&searchp, &search_size,
opt);
if (rc != ENOENT) {
rc = EINVAL;
goto fail5;
}
/* Check encapsulator will not overflow */
if (((size_t)encap_hdrp->length +
<API key>(value_length)) >
DHCP_MAX_VALUE) {
rc = E2BIG;
goto fail6;
}
/* Insert at start of existing encapsulator */
insert_pointp = (uint8_t *)&encap_hdrp[1];
opt = DHCP_ENCAPSULATED(opt);
} else if (rc == ENOENT) {
encap_hdrp = NULL;
} else {
goto fail7;
}
} else {
/* Check unencapsulated tag is not present */
rc = efx_dhcp_walk_tags(&searchp, &search_size,
opt);
if (rc != ENOENT) {
rc = EINVAL;
goto fail8;
}
}
if (insert_pointp == NULL) {
/* Insert at end of existing tags */
insert_pointp = endp;
}
/* Includes the new encapsulator tag hdr if required */
added_length = <API key>(value_length) +
(DHCP_IS_ENCAP_OPT(opt) ? sizeof (efx_dhcp_tag_hdr_t) : 0);
if (available_space <= added_length) {
rc = ENOMEM;
goto fail9;
}
memmove(insert_pointp + added_length, insert_pointp,
available_space - added_length);
if (DHCP_IS_ENCAP_OPT(opt)) {
/* Create new encapsulator header */
added_length -= sizeof (efx_dhcp_tag_hdr_t);
efx_dhcp_write_tag(insert_pointp,
DHCP_ENCAPSULATOR(opt), NULL, added_length);
insert_pointp += sizeof (efx_dhcp_tag_hdr_t);
} else if (encap_hdrp)
/* Modify existing encapsulator header */
encap_hdrp->length +=
((uint8_t)<API key>(value_length));
efx_dhcp_write_tag(insert_pointp, opt, valuep, value_length);
return (0);
fail9:
EFSYS_PROBE(fail9);
fail8:
EFSYS_PROBE(fail8);
fail7:
EFSYS_PROBE(fail7);
fail6:
EFSYS_PROBE(fail6);
fail5:
EFSYS_PROBE(fail5);
fail4:
EFSYS_PROBE(fail4);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Update an existing tag to the new value. Copes with encapsulated
* tags, and updates the encapsulating opt as necessary.
*/
__checkReturn efx_rc_t
efx_dhcp_update_tag(
__inout_bcount(buffer_length) uint8_t *bufferp,
__in size_t buffer_length,
__in uint16_t opt,
__in uint8_t *value_locationp,
__in_bcount_opt(value_length) uint8_t *valuep,
__in size_t value_length)
{
efx_rc_t rc;
uint8_t *write_pointp = value_locationp - sizeof (efx_dhcp_tag_hdr_t);
efx_dhcp_tag_hdr_t *hdrp = (efx_dhcp_tag_hdr_t *)write_pointp;
efx_dhcp_tag_hdr_t *encap_hdrp = NULL;
size_t old_length;
if (!DHCP_OPT_HAS_VALUE(DHCP_ENCAPSULATED(opt))) {
rc = EINVAL;
goto fail1;
}
if (value_length > DHCP_MAX_VALUE) {
rc = EINVAL;
goto fail2;
}
if ((value_length > 0) && (valuep == NULL)) {
rc = EINVAL;
goto fail3;
}
old_length = hdrp->length;
if (old_length < value_length) {
uint8_t *endp = bufferp;
size_t available_space = buffer_length;
rc = efx_dhcp_walk_tags(&endp, &available_space,
EFX_DHCP_END);
if (rc != 0)
goto fail4;
if (available_space < (value_length - old_length)) {
rc = EINVAL;
goto fail5;
}
}
if (DHCP_IS_ENCAP_OPT(opt)) {
uint8_t *encapp = bufferp;
size_t following_encap = buffer_length;
size_t new_length;
rc = efx_dhcp_walk_tags(&encapp, &following_encap,
DHCP_ENCAPSULATOR(opt));
if (rc != 0)
goto fail6;
encap_hdrp = (efx_dhcp_tag_hdr_t *)encapp;
new_length = ((size_t)encap_hdrp->length +
value_length - old_length);
/* Check encapsulator will not overflow */
if (new_length > DHCP_MAX_VALUE) {
rc = E2BIG;
goto fail7;
}
encap_hdrp->length = (uint8_t)new_length;
}
/*
* Move the following data up/down to accomodate the new payload
* length.
*/
if (old_length != value_length) {
uint8_t *destp = (uint8_t *)DHCP_NEXT_TAG(hdrp) +
value_length - old_length;
size_t count = &bufferp[buffer_length] -
(uint8_t *)DHCP_NEXT_TAG(hdrp);
memmove(destp, DHCP_NEXT_TAG(hdrp), count);
}
EFSYS_ASSERT(hdrp->tag == DHCP_ENCAPSULATED(opt));
efx_dhcp_write_tag(write_pointp, opt, valuep, value_length);
return (0);
fail7:
EFSYS_PROBE(fail7);
fail6:
EFSYS_PROBE(fail6);
fail5:
EFSYS_PROBE(fail5);
fail4:
EFSYS_PROBE(fail4);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
/*
* Copy bootcfg sector data to a target buffer which may differ in size.
* Optionally corrects format errors in source buffer.
*/
efx_rc_t
<API key>(
__in efx_nic_t *enp,
__inout_bcount(sector_length)
uint8_t *sector,
__in size_t sector_length,
__out_bcount(data_size) uint8_t *data,
__in size_t data_size,
__in boolean_t <API key>)
{
_NOTE(ARGUNUSED(enp))
size_t used_bytes;
efx_rc_t rc;
/* Minimum buffer is checksum byte and EFX_DHCP_END terminator */
if (data_size < 2) {
rc = ENOSPC;
goto fail1;
}
/* Verify that the area is correctly formatted and checksummed */
rc = efx_dhcp_verify(sector, sector_length,
&used_bytes);
if (!<API key>) {
if (rc != 0)
goto fail2;
if ((used_bytes < 2) ||
(sector[used_bytes - 1] != EFX_DHCP_END)) {
/* Block too short, or EFX_DHCP_END missing */
rc = ENOENT;
goto fail3;
}
}
/* Synthesize empty format on verification failure */
if (rc != 0 || used_bytes == 0) {
sector[0] = 0;
sector[1] = EFX_DHCP_END;
used_bytes = 2;
}
EFSYS_ASSERT(used_bytes >= 2); /* checksum and EFX_DHCP_END */
EFSYS_ASSERT(used_bytes <= sector_length);
EFSYS_ASSERT(sector_length >= 2);
/*
* Legacy bootcfg sectors don't terminate with an EFX_DHCP_END
* character. Modify the returned payload so it does.
* Reinitialise the sector if there isn't room for the character.
*/
if (sector[used_bytes - 1] != EFX_DHCP_END) {
if (used_bytes >= sector_length) {
sector[0] = 0;
used_bytes = 1;
}
sector[used_bytes] = EFX_DHCP_END;
++used_bytes;
}
/*
* Verify that the target buffer is large enough for the
* entire used bootcfg area, then copy into the target buffer.
*/
if (used_bytes > data_size) {
rc = ENOSPC;
goto fail4;
}
data[0] = 0; /* checksum, updated below */
/* Copy all after the checksum to the target buffer */
memcpy(data + 1, sector + 1, used_bytes - 1);
/* Zero out the unused portion of the target buffer */
if (used_bytes < data_size)
(void) memset(data + used_bytes, 0, data_size - used_bytes);
/*
* The checksum includes trailing data after any EFX_DHCP_END
* character, which we've just modified (by truncation or appending
* EFX_DHCP_END).
*/
data[0] -= efx_dhcp_csum(data, data_size);
return (0);
fail4:
EFSYS_PROBE(fail4);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
efx_rc_t
efx_bootcfg_read(
__in efx_nic_t *enp,
__out_bcount(size) uint8_t *data,
__in size_t size)
{
uint8_t *payload = NULL;
size_t used_bytes;
size_t partn_length;
size_t sector_length;
size_t sector_offset;
efx_rc_t rc;
uint32_t sector_number;
/* Minimum buffer is checksum byte and EFX_DHCP_END terminator */
if (size < 2) {
rc = ENOSPC;
goto fail1;
}
#if EFX_OPTS_EF10()
sector_number = enp->en_nic_cfg.enc_pf;
#else
sector_number = 0;
#endif
rc = efx_nvram_size(enp, <API key>, &partn_length);
if (rc != 0)
goto fail2;
/* The bootcfg sector may be stored in a (larger) shared partition */
rc = <API key>(enp, sector_number,
NULL, §or_offset, §or_length);
if (rc != 0)
goto fail3;
if (sector_length < 2) {
rc = EINVAL;
goto fail4;
}
if (sector_length > BOOTCFG_MAX_SIZE)
sector_length = BOOTCFG_MAX_SIZE;
if (sector_offset + sector_length > partn_length) {
/* Partition is too small */
rc = EFBIG;
goto fail5;
}
/*
* We need to read the entire BOOTCFG sector to ensure we read all
* tags, because legacy bootcfg sectors are not guaranteed to end
* with an EFX_DHCP_END character. If the user hasn't supplied a
* sufficiently large buffer then use our own buffer.
*/
if (sector_length > size) {
EFSYS_KMEM_ALLOC(enp->en_esip, sector_length, payload);
if (payload == NULL) {
rc = ENOMEM;
goto fail6;
}
} else
payload = (uint8_t *)data;
if ((rc = efx_nvram_rw_start(enp, <API key>, NULL)) != 0)
goto fail7;
if ((rc = <API key>(enp, <API key>,
sector_offset, (caddr_t)payload, sector_length)) != 0) {
(void) efx_nvram_rw_finish(enp, <API key>, NULL);
goto fail8;
}
if ((rc = efx_nvram_rw_finish(enp, <API key>, NULL)) != 0)
goto fail9;
/* Verify that the area is correctly formatted and checksummed */
rc = efx_dhcp_verify(payload, sector_length,
&used_bytes);
if (rc != 0 || used_bytes == 0) {
payload[0] = 0;
payload[1] = EFX_DHCP_END;
used_bytes = 2;
}
EFSYS_ASSERT(used_bytes >= 2); /* checksum and EFX_DHCP_END */
EFSYS_ASSERT(used_bytes <= sector_length);
/*
* Legacy bootcfg sectors don't terminate with an EFX_DHCP_END
* character. Modify the returned payload so it does.
* BOOTCFG_MAX_SIZE is by definition large enough for any valid
* (per-port) bootcfg sector, so reinitialise the sector if there
* isn't room for the character.
*/
if (payload[used_bytes - 1] != EFX_DHCP_END) {
if (used_bytes >= sector_length)
used_bytes = 1;
payload[used_bytes] = EFX_DHCP_END;
++used_bytes;
}
/*
* Verify that the user supplied buffer is large enough for the
* entire used bootcfg area, then copy into the user supplied buffer.
*/
if (used_bytes > size) {
rc = ENOSPC;
goto fail10;
}
data[0] = 0; /* checksum, updated below */
if (sector_length > size) {
/* Copy all after the checksum to the target buffer */
memcpy(data + 1, payload + 1, used_bytes - 1);
EFSYS_KMEM_FREE(enp->en_esip, sector_length, payload);
}
/* Zero out the unused portion of the user buffer */
if (used_bytes < size)
(void) memset(data + used_bytes, 0, size - used_bytes);
/*
* The checksum includes trailing data after any EFX_DHCP_END character,
* which we've just modified (by truncation or appending EFX_DHCP_END).
*/
data[0] -= efx_dhcp_csum(data, size);
return (0);
fail10:
EFSYS_PROBE(fail10);
fail9:
EFSYS_PROBE(fail9);
fail8:
EFSYS_PROBE(fail8);
fail7:
EFSYS_PROBE(fail7);
if (sector_length > size)
EFSYS_KMEM_FREE(enp->en_esip, sector_length, payload);
fail6:
EFSYS_PROBE(fail6);
fail5:
EFSYS_PROBE(fail5);
fail4:
EFSYS_PROBE(fail4);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
efx_rc_t
efx_bootcfg_write(
__in efx_nic_t *enp,
__in_bcount(size) uint8_t *data,
__in size_t size)
{
uint8_t *partn_data;
uint8_t checksum;
size_t partn_length;
size_t sector_length;
size_t sector_offset;
size_t used_bytes;
efx_rc_t rc;
uint32_t sector_number;
#if EFX_OPTS_EF10()
sector_number = enp->en_nic_cfg.enc_pf;
#else
sector_number = 0;
#endif
rc = efx_nvram_size(enp, <API key>, &partn_length);
if (rc != 0)
goto fail1;
/* The bootcfg sector may be stored in a (larger) shared partition */
rc = <API key>(enp, sector_number,
NULL, §or_offset, §or_length);
if (rc != 0)
goto fail2;
if (sector_length > BOOTCFG_MAX_SIZE)
sector_length = BOOTCFG_MAX_SIZE;
if (sector_offset + sector_length > partn_length) {
/* Partition is too small */
rc = EFBIG;
goto fail3;
}
if ((rc = efx_dhcp_verify(data, size, &used_bytes)) != 0)
goto fail4;
/*
* The caller *must* terminate their block with a EFX_DHCP_END
* character
*/
if ((used_bytes < 2) || ((uint8_t)data[used_bytes - 1] !=
EFX_DHCP_END)) {
/* Block too short or EFX_DHCP_END missing */
rc = ENOENT;
goto fail5;
}
/* Check that the hardware has support for this much data */
if (used_bytes > MIN(sector_length, BOOTCFG_MAX_SIZE)) {
rc = ENOSPC;
goto fail6;
}
/*
* If the BOOTCFG sector is stored in a shared partition, then we must
* read the whole partition and insert the updated bootcfg sector at the
* correct offset.
*/
EFSYS_KMEM_ALLOC(enp->en_esip, partn_length, partn_data);
if (partn_data == NULL) {
rc = ENOMEM;
goto fail7;
}
rc = efx_nvram_rw_start(enp, <API key>, NULL);
if (rc != 0)
goto fail8;
/* Read the entire partition */
rc = <API key>(enp, <API key>, 0,
(caddr_t)partn_data, partn_length);
if (rc != 0)
goto fail9;
/*
* Insert the BOOTCFG sector into the partition, Zero out all data
* after the EFX_DHCP_END tag, and adjust the checksum.
*/
(void) memset(partn_data + sector_offset, 0x0, sector_length);
(void) memcpy(partn_data + sector_offset, data, used_bytes);
checksum = efx_dhcp_csum(data, used_bytes);
partn_data[sector_offset] -= checksum;
if ((rc = efx_nvram_erase(enp, <API key>)) != 0)
goto fail10;
if ((rc = <API key>(enp, <API key>,
0, (caddr_t)partn_data, partn_length)) != 0)
goto fail11;
if ((rc = efx_nvram_rw_finish(enp, <API key>, NULL)) != 0)
goto fail12;
EFSYS_KMEM_FREE(enp->en_esip, partn_length, partn_data);
return (0);
fail12:
EFSYS_PROBE(fail12);
fail11:
EFSYS_PROBE(fail11);
fail10:
EFSYS_PROBE(fail10);
fail9:
EFSYS_PROBE(fail9);
(void) efx_nvram_rw_finish(enp, <API key>, NULL);
fail8:
EFSYS_PROBE(fail8);
EFSYS_KMEM_FREE(enp->en_esip, partn_length, partn_data);
fail7:
EFSYS_PROBE(fail7);
fail6:
EFSYS_PROBE(fail6);
fail5:
EFSYS_PROBE(fail5);
fail4:
EFSYS_PROBE(fail4);
fail3:
EFSYS_PROBE(fail3);
fail2:
EFSYS_PROBE(fail2);
fail1:
EFSYS_PROBE1(fail1, efx_rc_t, rc);
return (rc);
}
#endif /* EFSYS_OPT_BOOTCFG */
|
/*csslint adjoining-classes: false, star-property-hack: false, important: false, outline-none: false, <API key>: false */
.pure-form label {
display: inline-block;
*display: inline;
*zoom: 1;
}
.pure-form-stacked label {
display: block;
}
.<API key>,
.<API key>,
.<API key>,
.<API key> {
position: absolute !important;
visibility: hidden !important;
left: -9999px !important;
top: -9999px !important;
}
.itsa-widget-parent {
display: inline-block;
*display: inline;
*zoom: 1;
padding: 0;
}
.yui3-itsacheckbox .optionwrapper {
height: 0;
padding: 0;
margin: 0;
position: relative;
}
.yui3-itsacheckbox .optionon {
background-color: #6AA7F6;
color: #FFF;
}
.yui3-itsacheckbox .optionoff {
background-color: #FFF;
color: #444;
}
.yui3-itsacheckbox .optioncontainer {
position: relative;
cursor: pointer;
padding: 0;
margin: 0;
-<API key>: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.yui3-itsacheckbox .optionon,
.yui3-itsacheckbox .optionbtn,
.yui3-itsacheckbox .optionoff {
float: left;
}
.yui3-itsacheckbox .optionon,
.yui3-itsacheckbox .optionoff {
position: static;
text-align: center;
white-space: nowrap;
-webkit-box-shadow: inset 0 0.7em 0.2em rgba(0, 0, 0, 0.18);
-moz-box-shadow: inset 0 0.7em 0.2em rgba(0, 0, 0, 0.18);
box-shadow: inset 0 0.7em 0.2em rgba(0, 0, 0, 0.18);
}
.yui3-itsacheckbox .optionon {
padding: 2px 0.7em 0 1.1em;
}
.yui3-itsacheckbox .optionoff {
padding: 2px 1.1em 0 0.7em;
}
.yui3-itsacheckbox .optionbtn {
-webkit-box-shadow: inset 0 0.17em 0.5em rgba(0, 0, 0, 0.18);
-moz-box-shadow: inset 0 0.17em 0.5em rgba(0, 0, 0, 0.18);
box-shadow: inset 0 0.17em 0.5em rgba(0, 0, 0, 0.18);
background-color: #fff;
border: solid 1px #AAA;
}
.pure-form-stacked .yui3-itsacheckbox,
.pure-form-aligned .yui3-itsacheckbox,
.pure-form .yui3-itsacheckbox,
.yui3-itsacheckbox {
padding: 0;
}
.yui3-itsacheckbox {
padding: 0;
overflow: hidden;
margin: 0.5em 0;
display: inline-block;
*display: inline;
*zoom: 1;
vertical-align: middle;
border: 1px solid #CCC;
font-size: 0.8em;
-webkit-transition: 0.3s linear border;
-moz-transition: 0.3s linear border;
-ms-transition: 0.3s linear border;
-o-transition: 0.3s linear border;
transition: 0.3s linear border;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-<API key>: antialiased;
}
.yui3-itsacheckbox .optionwrapper div {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.pure-form-stacked .yui3-itsacheckbox {
margin: 0.25em 0;
}
.pure-form-aligned .yui3-itsacheckbox {
*zoom: 1;
}
.yui3-itsacheckbox:focus,
.itsa-widget-parent[data-type="itsacheckbox"]:focus .yui3-itsacheckbox {
outline: 0;
border-color: #129FEA;
}
.yui3-itsacheckbox.<API key> .optionon,
.yui3-itsacheckbox.<API key> .optionoff,
.yui3-itsacheckbox.<API key>.<API key> .optionon,
.yui3-itsacheckbox.<API key>.<API key> .optionoff {
background-color: #EAEDED;
color: #909596;
}
.yui3-itsacheckbox.<API key>,
.yui3-itsacheckbox.<API key> {
box-shadow: none;
}
.yui3-itsacheckbox.<API key>:focus,
.itsa-widget-parent[data-type="itsacheckbox"]:focus .yui3-itsacheckbox.<API key>,
.yui3-itsacheckbox.<API key>:focus .optionbtn,
.yui3-itsacheckbox.<API key>:focus,
.yui3-itsacheckbox.<API key>.<API key>,
.yui3-itsacheckbox.<API key>.<API key> .optionbtn {
border-color: #CCC;
}
.yui3-itsacheckbox.<API key> .optioncontainer,
.yui3-itsacheckbox.<API key> .optioncontainer {
cursor: default;
}
.pure-group .yui3-itsacheckbox {
margin-bottom: 10px;
margin: 0.35em 0;
}
@media only screen and (max-width : 480px) {
.yui3-itsacheckbox {
margin-bottom: 0.3em;
}
.pure-group .yui3-itsacheckbox {
margin-bottom: 0;
}
}
|
<template name="tableOfContents">
<div class="table-of-contents">
{{> nav}}
</div>
</template>
<template name="nav">
<h1>API</h1>
<div class="options">
<label class="show-all-types">
<input type="checkbox" checked="{{showAllTypes}}" />
Show all types
</label>
</div>
{{#each sections}}
{{#if type "spacer"}}
<div class="spacer"> </div>
{{/if}}
{{#if type "section"}}
{{#nav_section}}
<a href="#{{id}}" class="{{current}}">
{{#if prefix}}
{{prefix}}.
{{/if}}
{{#if instance}}
<i>{{instance}}</i>.
{{/if}}
{{name}}
</a>
{{/nav_section}}
{{/if}}
{{/each}}
</template>
<template name="nav_section">
{{#if depthIs 1}}
<h2>{{> UI.contentBlock}}</h2>
{{/if}}
{{#if depthIs 2}}
<h3>{{> UI.contentBlock}}</h3>
{{/if}}
{{#if depthIs 3}}
<h4>{{> UI.contentBlock}}</h4>
{{/if}}
{{#if depthIs 4}}
<h5>{{> UI.contentBlock}}</h5>
{{/if}}
{{#if depthIs 5}}
<h6>{{> UI.contentBlock}}</h6>
{{/if}}
</template>
|
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.<API key>;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.<API key>;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.<API key>;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
public class JavadocWriter {
private static final char PATH_SEPARATOR= '/'; // use forward slash for all platforms
private final IJavaProject[] fJavaProjects;
private final IPath fBasePath;
/**
* Create a JavadocWriter.
* @param basePath The base path to which all path will be made relative (if
* possible). If <code>null</code>, paths are not made relative.
* @param projects
*/
public JavadocWriter(IPath basePath, IJavaProject[] projects) {
fBasePath= basePath;
fJavaProjects= projects;
}
public Element createXML(<API key> store) throws <API key> {
DocumentBuilder docBuilder= null;
<API key> factory= <API key>.newInstance();
factory.setValidating(false);
docBuilder= factory.newDocumentBuilder();
Document document= docBuilder.newDocument();
// Create the document
Element project= document.createElement("project"); //$NON-NLS-1$
document.appendChild(project);
project.setAttribute("default", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
Element javadocTarget= document.createElement("target"); //$NON-NLS-1$
project.appendChild(javadocTarget);
javadocTarget.setAttribute("name", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
Element xmlJavadocDesc= document.createElement("javadoc"); //$NON-NLS-1$
javadocTarget.appendChild(xmlJavadocDesc);
if (!store.isFromStandard())
xmlWriteDoclet(store, document, xmlJavadocDesc);
else
<API key>(store, document, xmlJavadocDesc);
return xmlJavadocDesc;
}
/**
* Writes the document to the given stream.
* It is the client's responsibility to close the output stream.
* @param javadocElement the XML element defining the Javadoc tags
* @param encoding the encoding to use
* @param outputStream the output stream
* @throws <API key> thrown if writing fails
*/
public static void writeDocument(Element javadocElement, String encoding, OutputStream outputStream) throws <API key> {
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(javadocElement.getOwnerDocument());
StreamResult result = new StreamResult(new <API key>(outputStream));
transformer.transform(source, result);
}
//writes ant file, for now only worry about one project
private void <API key>(<API key> store, Document document, Element xmlJavadocDesc) throws DOMException {
String destination= getPathString(Path.fromOSString(store.getDestination()));
xmlJavadocDesc.setAttribute(store.DESTINATION, destination);
xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
String source= store.getSource();
if (source.length() > 0 && !source.equals("-")) { //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.SOURCE, store.getSource());
}
xmlJavadocDesc.setAttribute(store.USE, booleanToString(store.getBoolean("use"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NOTREE, booleanToString(store.getBoolean("notree"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NONAVBAR, booleanToString(store.getBoolean("nonavbar"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NOINDEX, booleanToString(store.getBoolean("noindex"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.SPLITINDEX, booleanToString(store.getBoolean("splitindex"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.AUTHOR, booleanToString(store.getBoolean("author"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.VERSION, booleanToString(store.getBoolean("version"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NODEPRECATEDLIST, booleanToString(store.getBoolean("nodeprecatedlist"))); //$NON-NLS-1$
xmlJavadocDesc.setAttribute(store.NODEPRECATED, booleanToString(store.getBoolean("nodeprecated"))); //$NON-NLS-1$
//set the packages and source files
List<String> packages= new ArrayList<String>();
List<String> sourcefiles= new ArrayList<String>();
sortSourceElement(store.getSourceElements(), sourcefiles, packages);
if (!packages.isEmpty())
xmlJavadocDesc.setAttribute(store.PACKAGENAMES, toSeparatedList(packages));
if (!sourcefiles.isEmpty())
xmlJavadocDesc.setAttribute(store.SOURCEFILES, toSeparatedList(sourcefiles));
xmlJavadocDesc.setAttribute(store.SOURCEPATH, getPathString(store.getSourcepath()));
xmlJavadocDesc.setAttribute(store.CLASSPATH, getPathString(store.getClasspath()));
String overview= store.getOverview();
if (overview.length() > 0)
xmlJavadocDesc.setAttribute(store.OVERVIEW, overview);
String styleSheet= store.getStyleSheet();
if (styleSheet.length() > 0)
xmlJavadocDesc.setAttribute(store.STYLESHEETFILE, styleSheet);
String title= store.getTitle();
if (title.length() > 0)
xmlJavadocDesc.setAttribute(store.TITLE, title);
String vmArgs= store.getVMParams();
String additionalArgs= store.getAdditionalParams();
if (vmArgs.length() + additionalArgs.length() > 0) {
String str= vmArgs + ' ' + additionalArgs;
xmlJavadocDesc.setAttribute(store.EXTRAOPTIONS, str);
}
String[] hrefs= store.getHRefs();
for (int i= 0; i < hrefs.length; i++) {
Element links= document.createElement("link"); //$NON-NLS-1$
xmlJavadocDesc.appendChild(links);
links.setAttribute(store.HREF, hrefs[i]);
}
}
private void sortSourceElement(IJavaElement[] iJavaElements, List<String> sourcefiles, List<String> packages) {
for (int i= 0; i < iJavaElements.length; i++) {
IJavaElement element= iJavaElements[i];
IPath p= element.getResource().getLocation();
if (p == null)
continue;
if (element instanceof ICompilationUnit) {
String relative= getPathString(p);
sourcefiles.add(relative);
} else if (element instanceof IPackageFragment) {
packages.add(element.getElementName());
}
}
}
private String getPathString(IPath[] paths) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < paths.length; i++) {
if (buf.length() != 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(getPathString(paths[i]));
}
if (buf.length() == 0) {
buf.append('.');
}
return buf.toString();
}
private boolean hasSameDevice(IPath p1, IPath p2) {
String dev= p1.getDevice();
if (dev == null) {
return p2.getDevice() == null;
}
return dev.equals(p2.getDevice());
}
//make the path relative to the base path
private String getPathString(IPath fullPath) {
if (fBasePath == null || !hasSameDevice(fullPath, fBasePath)) {
return fullPath.toOSString();
}
int matchingSegments= fBasePath.<API key>(fullPath);
if (fBasePath.segmentCount() == matchingSegments) {
return getRelativePath(fullPath, matchingSegments);
}
for (int i= 0; i < fJavaProjects.length; i++) {
IProject proj= fJavaProjects[i].getProject();
IPath projLoc= proj.getLocation();
if (projLoc != null && projLoc.segmentCount() <= matchingSegments && projLoc.isPrefixOf(fullPath)) {
return getRelativePath(fullPath, matchingSegments);
}
}
IPath workspaceLoc= ResourcesPlugin.getWorkspace().getRoot().getLocation();
if (workspaceLoc.segmentCount() <= matchingSegments && workspaceLoc.isPrefixOf(fullPath)) {
return getRelativePath(fullPath, matchingSegments);
}
return fullPath.toOSString();
}
private String getRelativePath(IPath fullPath, int matchingSegments) {
StringBuffer res= new StringBuffer();
int backSegments= fBasePath.segmentCount() - matchingSegments;
while (backSegments > 0) {
res.append(".."); //$NON-NLS-1$
res.append(PATH_SEPARATOR);
backSegments
}
int segCount= fullPath.segmentCount();
for (int i= matchingSegments; i < segCount; i++) {
if (i > matchingSegments) {
res.append(PATH_SEPARATOR);
}
res.append(fullPath.segment(i));
}
return res.toString();
}
private void xmlWriteDoclet(<API key> store, Document document, Element xmlJavadocDesc) throws DOMException {
//set the packages and source files
List<String> packages= new ArrayList<String>();
List<String> sourcefiles= new ArrayList<String>();
sortSourceElement(store.getSourceElements(), sourcefiles, packages);
if (!packages.isEmpty())
xmlJavadocDesc.setAttribute(store.PACKAGENAMES, toSeparatedList(packages));
if (!sourcefiles.isEmpty())
xmlJavadocDesc.setAttribute(store.SOURCEFILES, toSeparatedList(sourcefiles));
xmlJavadocDesc.setAttribute(store.SOURCEPATH, getPathString(store.getSourcepath()));
xmlJavadocDesc.setAttribute(store.CLASSPATH, getPathString(store.getClasspath()));
xmlJavadocDesc.setAttribute(store.VISIBILITY, store.getAccess());
Element doclet= document.createElement("doclet"); //$NON-NLS-1$
xmlJavadocDesc.appendChild(doclet);
doclet.setAttribute(store.NAME, store.getDocletName());
doclet.setAttribute(store.PATH, store.getDocletPath());
String str= store.getOverview();
if (str.length() > 0)
xmlJavadocDesc.setAttribute(store.OVERVIEW, str);
str= store.getAdditionalParams();
if (str.length() > 0)
xmlJavadocDesc.setAttribute(store.EXTRAOPTIONS, str);
}
private String toSeparatedList(List<String> packages) {
StringBuffer buf= new StringBuffer();
Iterator<String> iter= packages.iterator();
int nAdded= 0;
while (iter.hasNext()) {
if (nAdded > 0) {
buf.append(',');
}
nAdded++;
String curr= iter.next();
buf.append(curr);
}
return buf.toString();
}
private String booleanToString(boolean bool) {
if (bool)
return "true"; //$NON-NLS-1$
else
return "false"; //$NON-NLS-1$
}
}
|
Leaflet.draw Changelog
===================
## master
An in-progress version being developed on the master branch.
Improvements
* Refactored the `L.drawLocal' object to be better structured and use this object whereever text is used. *NOTE: THIS IS A NEW FORMAT, SO WILL BRESK ANY EXISTING CUSTOM `L.drawLocal` SETTINGS*.
* Added Imperial measurements to compliment the existing Metric measurements when drawing a polyline or polygon.
* Added `draw:editstart` and `draw:editstop` events. (by [@bhell](https://github.com/bhell)). [
* Added `repeatMode` option that will allow repeated drawing of features. (by [@jayhogan](https://github.com/jayhogan) and [@cscheid](https://github.com/cscheid)). [
* Added abilit to set circle radius measurement to imperial units.
* Added disabled state for edit/delete buttons when no layers present. (inspired by [@snkashis](https://github.com/snkashis)). [
* Add `showLength` and `showRadius` options to circle and polyline. (by [@Zverik](https://github.com/Zverik)). [
* Add option to disable tooltips. (by [@Zverik](https://github.com/Zverik)). [
Bugfixes
* Fixed bug where edit handlers could not be disabled.
* Added support for displaying the toolbar on the right hand side of the map. (by [@paulcpederson](https://github.com/paulcpederson)). [
* Add flexible width action buttons. (by [@Grsmto](https://github.com/Grsmto)). [
* Check for icon existence before disabling edit state. (by [@tmcw](https://github.com/tmcw)). [
* Only update guideslines when guidelines are present. (by [@jayhogan](https://github.com/jayhogan)). [
* Fixes to localization code so it can be correctly set after files have been loaded.
* Fix for firing `draw:edit` twice for Draw.SimpleShape. (by [@cazacugmihai](https://github.com/cazacugmihai)). [
* Fix last edit menu buttons from wrapping. (by [@moiarcsan](https://github.com/moiarcsan)). [
## 0.2.1 (July 5, 2013)
Improvements
* `draw:edited` now returns a `FeatureGroup` of features edited. (by [@jmkelly](https://github.com/jmkelly)). [
* Circle tooltip shows the radius (in m) while drawing.
* Added Leaflet version check to inform developers that Leaflet 0.6+ is required.
* Added ability to finish drawing polygons by double clicking. (inspired by [@snkashis](https://github.com/snkashis)). [
* Added test environment. (by [@iirvine](https://github.com/iirvine)). [
* Added `L.drawLocal` object to allow users to customize the text used in the plugin. Addresses localization issues. (by [@Starefossen](https://github.com/Starefossen)). [
* Added ability to disable edit mode path and marker styles. (inspired by [@markgibbons25](https://github.com/markgibbons25)). [
* Added area calculation when drawing a polygon.
* Polyline and Polygon tooltips update on click as well as mouse move.
Bugfixes
* Fixed issue where removing a vertex or adding a new one via midpoints would not update the edited state for polylines and polygons.
* Fixed issue where not passing in the context to `off()` would result in the event from not being unbound.(by [@koppelbakje](https://github.com/koppelbakje)). [
* Fixed issue where removing the draw control from the map would result in an error.
* Fixed bug where removing points created by dragging midpoints would cause the polyline to not reflect any newly created points.
* Fixed regression where handlers were not able to be disabled.(by [@yohanboniface](https://github.com/yohanboniface)). [
* Fixed bug where L.Draw.Polyline would try to remove a non-existant handler if the user cancelled and the polyline only had a single point.
## 0.2.0 (February 20, 2013)
Major new version. Added Edit toolbar which allows editing and deleting shapes.
Features
* Consistant event for shape creation. (by [@krikrou](https://github.com/krikrou)). [
Bugfixes
* Fixed adding markers over vector layers. (by [@Starefossen](https://github.com/Starefossen)). [
## 0.1.7 (February 11, 2013)
* Add sanity check for toolbar buttons when adding top and bottom classes. (by [@yohanboniface](https://github.com/yohanboniface)). [
## 0.1.6 (January 17, 2013)
* Updated toolbar styles to be in line with the new Leaflet zoom in/out styles.
## 0.1.5 (December 10, 2012)
Features
* Added 'drawing-disabled' event fired on the map when a draw handler is disabled. (by [@ajbeaven](https://github.com/thegreat)). [
* Added 'drawing' event fired on the map when a draw handler is actived. (by [@ajbeaven](https://github.com/thegreat)). [
Bugfixes
* Stopped L.Control.Draw from storing handlers in it's prototype. (by [@thegreat](https://github.com/thegreat)). [
## 0.1.4 (October 8, 2012)
Bugfixes
* Fixed a bug that would cause an error when creating rectangles/circles withought moving the mouse. (by [@inpursuit](https://github.com/inpursuit)). [
* Fixed a bug that would cause an error when clicking a different drawing tool while another mode enabled. (by [@thegreat](https://github.com/thegreat)). [
* Fixed control buttons breaking plugin in oldIE.
* Fixed drawing polylines and polygons in oldIE.
## 0.1.3 (October 3, 2012)
Bugfixes
* Tip label will now show over vertex markers.
* Added ability to draw on top of existing markers and vector layers.
* Clicking on a map object that has a click handler no longer triggers the click event when in drawing mode.
## Pre-0.1.3
Check the commit history for changes previous to 0.1.3.
|
<?php
use Peridot\Console\CliOptionParser;
describe('CliOptionParser', function() {
beforeEach(function() {
$this->search = ['-c', '--configuration'];
$this->args = ["test.php", "-c", "peridot.php", "another", "thing", '--configuration', 'file.php'];
$this->parser = new CliOptionParser($this->search, $this->args);
});
describe('->parse()', function() {
it('should return values associated with search', function() {
$values = $this->parser->parse();
$c = $values['c'];
$configuration = $values['configuration'];
assert($c == 'peridot.php', "expected c to equal peridot.php");
assert($configuration == "file.php", "expected configuration to equal file.php");
});
it('should return an empty array if no matches', function() {
$args = ['test.php', 'ham', 'sandwich'];
$parser = new CliOptionParser($this->search, $args);
$parsed = $parser->parse();
assert(empty($parsed), "empty array should be returned");
});
});
});
|
<div class="container view-space">
<div class="row">
<div class="col-md-12">
Coming Soon
</div>
</div>
</div>
|
// fix arrow end issues:
var chart_config = {
chart: {
container: "#<API key>",
levelSeparation: 45,
rootOrientation: "WEST",
nodeAlign: "BOTTOM",
connectors: {
type: "step",
style: {
"stroke-width": 2
}
},
node: {
HTMLclass: "big-commpany"
}
},
nodeStructure: {
text: { name: "CEO" },
connectors: {
style: {
'stroke': '#bbb',
'arrow-end': 'oval-wide-long'
}
},
children: [
{
text: { name: "Account" },
stackChildren: true,
connectors: {
style: {
'stroke': '#8080FF',
'arrow-end': 'block-wide-long'
}
},
children: [
{
text: {name: "Receptionist"},
HTMLclass: "reception"
},
{
text: {name: "Author"}
}
]
},
{
text: { name: "Operation Manager" },
connectors: {
style: {
'stroke': '#bbb',
"stroke-dasharray": "- .",
'arrow-start': 'classic-wide-long'
}
},
children: [
{
text: {name: "Manager I"},
connectors: {
style: {
stroke: "#00CE67"
}
},
children: [
{
text: {name: "Worker I"}
},
{
pseudo: true,
connectors: {
style: {
stroke: "#00CE67"
}
},
children: [
{
text: {name: "Worker II"}
}
]
},
{
text: {name: "Worker III"}
}
]
},
{
text: {name: "Manager II"},
connectors: {
type: "curve",
style: {
stroke: "#50688D"
}
},
children: [
{
text: {name: "Worker I"}
},
{
text: {name: "Worker II"}
}
]
},
{
text: {name: "Manager III"},
connectors: {
style: {
'stroke': '#FF5555'
}
},
children: [
{
text: {name: "Worker I"}
},
{
pseudo: true,
connectors: {
style: {
'stroke': '#FF5555'
}
},
children: [
{
text: {name: "Worker II"}
},
{
text: {name: "Worker III"}
}
]
},
{
text: {name: "Worker IV"}
}
]
}
]
},
{
text: { name: "Delivery Manager" },
stackChildren: true,
connectors: {
stackIndent: 30,
style: {
'stroke': '#E3C61A',
'arrow-end': 'block-wide-long'
}
},
children: [
{
text: {name: "Driver I"}
},
{
text: {name: "Driver II"}
},
{
text: {name: "Driver III"}
}
]
}
]
}
};
|
// Use of this source code is governed by a BSD-style
package main
import (
"fmt"
"strings"
)
// mdChangeLink returns the markdown for a link to CL n.
func mdChangeLink(n int) string {
return fmt.Sprintf("[CL %d](https://golang.org/cl/%d)", n, n)
}
// mdEscape escapes text so that it does not have any special meaning in Markdown.
func mdEscape(text string) string {
return mdEscaper.Replace(text)
}
var mdEscaper = strings.NewReplacer(
`\`, `\\`,
`{`, `\{`,
`}`, `\}`,
"`", "\\`",
`
`*`, `\*`,
`+`, `\+`,
`_`, `\_`,
`-`, `\-`,
`(`, `\(`,
`)`, `\)`,
`.`, `\.`,
`[`, `\[`,
`]`, `\]`,
`!`, `\!`,
)
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityTest
{
public abstract class <API key> : IComparable<<API key>>
{
public static Action<IList<ITestComponent>> RunTest;
protected static bool s_Refresh;
private static readonly GUIContent k_GUIRunSelected = new GUIContent("Run Selected");
private static readonly GUIContent k_GUIRun = new GUIContent("Run");
private static readonly GUIContent k_GUIDelete = new GUIContent("Delete");
private static readonly GUIContent k_GUIDeleteSelected = new GUIContent("Delete selected");
protected static GUIContent s_GUITimeoutIcon = new GUIContent(Icons.StopwatchImg, "Timeout");
protected GameObject m_GameObject;
public TestComponent test;
private readonly string m_Name;
protected <API key>(GameObject gameObject)
{
test = gameObject.GetComponent(typeof(TestComponent)) as TestComponent;
if (test == null) throw new ArgumentException("Provided GameObject is not a test object");
m_GameObject = gameObject;
m_Name = test.Name;
}
public int CompareTo(<API key> other)
{
return test.CompareTo(other.test);
}
public bool Render(RenderingOptions options)
{
s_Refresh = false;
EditorGUIUtility.SetIconSize(new Vector2(15, 15));
Render(0, options);
EditorGUIUtility.SetIconSize(Vector2.zero);
return s_Refresh;
}
protected internal virtual void Render(int indend, RenderingOptions options)
{
if (!IsVisible(options)) return;
EditorGUILayout.BeginHorizontal();
GUILayout.Space(indend * 10);
var tempColor = GUI.color;
if (m_IsRunning)
{
var frame = Mathf.Abs(Mathf.Cos(Time.<API key> * 4)) * 0.6f + 0.4f;
GUI.color = new Color(1, 1, 1, frame);
}
var isSelected = Selection.gameObjects.Contains(m_GameObject);
var value = GetResult();
var icon = GetIconForResult(value);
var label = new GUIContent(m_Name, icon);
var labelRect = GUILayoutUtility.GetRect(label, EditorStyles.label, GUILayout.ExpandWidth(true), GUILayout.Height(18));
<API key>(labelRect);
OnContextClick(labelRect);
DrawLine(labelRect, label, isSelected, options);
if (m_IsRunning) GUI.color = tempColor;
EditorGUILayout.EndHorizontal();
}
protected void OnSelect()
{
if (!Event.current.control && !Event.current.command)
{
Selection.objects = new Object[0];
GUIUtility.keyboardControl = 0;
}
if ((Event.current.control || Event.current.command) && Selection.gameObjects.Contains(test.gameObject))
Selection.objects = Selection.gameObjects.Where(o => o != test.gameObject).ToArray();
else
Selection.objects = Selection.gameObjects.Concat(new[] { test.gameObject }).ToArray();
}
protected void <API key>(Rect rect)
{
if (rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.mouseDown && Event.current.button == 0)
{
rect.width = 20;
if (rect.Contains(Event.current.mousePosition)) return;
Event.current.Use();
OnSelect();
}
}
protected void OnContextClick(Rect rect)
{
if (rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.ContextClick)
{
DrawContextMenu(test);
}
}
public static void DrawContextMenu(TestComponent testComponent)
{
if (EditorApplication.<API key>) return;
var selectedTests = Selection.gameObjects.Where(go => go.GetComponent(typeof(TestComponent)));
var manySelected = selectedTests.Count() > 1;
var m = new GenericMenu();
if (manySelected)
{
// var testsToRun
m.AddItem(k_GUIRunSelected, false, data => RunTest(selectedTests.Select(o => o.GetComponent(typeof(TestComponent))).Cast<ITestComponent>().ToList()), null);
}
m.AddItem(k_GUIRun, false, data => RunTest(new[] { testComponent }), null);
m.AddSeparator("");
m.AddItem(manySelected ? k_GUIDeleteSelected : k_GUIDelete, false, data => RemoveTests(selectedTests.ToArray()), null);
m.ShowAsContext();
}
private static void RemoveTests(GameObject[] testsToDelete)
{
foreach (var t in testsToDelete)
{
#if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Destroy Tests");
GameObject.DestroyImmediate(t);
#else
Undo.<API key>(t);
#endif
}
}
public static Texture GetIconForResult(TestResult.ResultType resultState)
{
switch (resultState)
{
case TestResult.ResultType.Success:
return Icons.SuccessImg;
case TestResult.ResultType.Timeout:
case TestResult.ResultType.Failed:
case TestResult.ResultType.FailedException:
return Icons.FailImg;
case TestResult.ResultType.Ignored:
return Icons.IgnoreImg;
default:
return Icons.UnknownImg;
}
}
protected internal bool m_IsRunning;
protected internal abstract void DrawLine(Rect rect, GUIContent label, bool isSelected, RenderingOptions options);
protected internal abstract TestResult.ResultType GetResult();
protected internal abstract bool IsVisible(RenderingOptions options);
public abstract bool SetCurrentTest(TestComponent tc);
}
}
|
-- Create a view
CREATE VIEW SalesLT.vCustomerAddress
AS
SELECT C.CustomerID, FirstName, LastName, AddressLine1, City, StateProvince
FROM
SalesLT.Customer C JOIN SalesLT.CustomerAddress CA
ON C.CustomerID=CA.CustomerID
JOIN SalesLT.Address A
ON CA.AddressID=A.AddressID
-- Query the view
SELECT CustomerID, City
FROM SalesLT.vCustomerAddress
-- Join the view to a table
SELECT c.StateProvince, c.City, ISNULL(SUM(s.TotalDue), 0.00) AS Revenue
FROM SalesLT.vCustomerAddress AS c
LEFT JOIN SalesLT.SalesOrderHeader AS s
ON s.CustomerID = c.CustomerID
GROUP BY c.StateProvince, c.City
ORDER BY c.StateProvince, Revenue DESC;
|
# <API key>: true
module Onebox
module Engine
class ImgurOnebox
include Engine
include StandardEmbed
matches_regexp(/^https?:\/\/(www\.)?imgur\.com/)
always_https
def to_html
og = get_opengraph
return video_html(og) if !og.video_secure_url.nil?
return album_html(og) if is_album?
return image_html(og) if !og.image.nil?
nil
end
private
def video_html(og)
<<-HTML
<video width='#{og.video_width}' height='#{og.video_height}' #{og.title_attr} controls loop>
<source src='#{og.video_secure_url}' type='video/mp4'>
<source src='#{og.video_secure_url.gsub('mp4', 'webm')}' type='video/webm'>
</video>
HTML
end
def album_html(og)
escaped_url = ::Onebox::Helpers.<API key>(url)
album_title = "[Album] #{og.title}"
<<-HTML
<div class='onebox imgur-album'>
<a href='#{escaped_url}' target='_blank' rel='noopener'>
<span class='outer-box' style='width:#{og.image_width}px'>
<span class='inner-box'>
<span class='album-title'>#{album_title}</span>
</span>
</span>
<img src='#{og.secure_image_url}' #{og.title_attr} height='#{og.image_height}' width='#{og.image_width}'>
</a>
</div>
HTML
end
def is_album?
response = Onebox::Helpers.fetch_response("https://api.imgur.com/oembed.json?url=#{url}") rescue "{}"
oembed_data = Onebox::Helpers.symbolize_keys(::MultiJson.load(response))
imgur_data_id = Nokogiri::HTML(oembed_data[:html]).xpath("//blockquote").attr("data-id")
imgur_data_id.to_s[/a\
end
def image_html(og)
escaped_url = ::Onebox::Helpers.<API key>(url)
<<-HTML
<a href='#{escaped_url}' target='_blank' rel='noopener' class="onebox">
<img src='#{og.secure_image_url.chomp("?fb")}' #{og.title_attr} alt='Imgur'>
</a>
HTML
end
end
end
end
|
/** \file
* \brief Master include file for the library USB functionality.
*
* Master include file for the library USB functionality.
*
* This file should be included in all user projects making use of the USB portions of the library, instead of
* the individual USB driver submodule headers.
*/
/** \defgroup Group_USB USB Core - LUFA/Drivers/USB/USB.h
*
* \section Sec_Dependencies Module Source Dependencies
* The following files must be built with any user project that uses this module:
* - LUFA/Drivers/USB/Core/ConfigDescriptor.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/DeviceStandardReq.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/Events.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/HostStandardReq.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/USBTask.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/Device_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/Endpoint_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/EndpointStream_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/Host_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/Pipe_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/PipeStream_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/USBController_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Core/<i>ARCH</i>/USBInterrupt_<i>ARCH</i>.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
* - LUFA/Drivers/USB/Class/Common/HIDParser.c <i>(Makefile source module name: LUFA_SRC_USB)</i>
*
* \section Sec_ModDescription Module Description
* Driver and framework for the USB controller of the selected architecture and microcontroller model. This module
* consists of many submodules, and is designed to provide an easy way to configure and control USB host, device
* or OTG mode USB applications.
*
* The USB stack requires the sole control over the USB controller in the microcontroller only; i.e. it does not
* require any additional timers or other peripherals to operate. This ensures that the USB stack requires as few
* resources as possible.
*
* The USB stack can be used in Device Mode for connections to USB Hosts (see \ref Group_Device), in Host mode for
* hosting of other USB devices (see \ref Group_Host), or as a dual role device which can either act as a USB host
* or device depending on what peripheral is connected (see \ref Group_OTG). Both modes also require a common set
* of USB management functions found \ref Group_USBManagement.
*/
/** \defgroup <API key> USB Class Drivers
*
* Drivers for both host and device mode of the standard USB classes, for rapid application development.
* Class drivers give a framework which sits on top of the low level library API, allowing for standard
* USB classes to be implemented in a project with minimal user code. These drivers can be used in
* conjunction with the library low level APIs to implement interfaces both via the class drivers and via
* the standard library APIs.
*
* Multiple device mode class drivers can be used within a project, including multiple instances of the
* same class driver. In this way, USB Hosts and Devices can be made quickly using the internal class drivers
* so that more time and effort can be put into the end application instead of the USB protocol.
*
* The available class drivers and their modes are listed below.
*
* <table>
* <tr>
* <th width="100px">USB Class</th>
* <th width="90px">Device Mode</th>
* <th width="90px">Host Mode</th>
* </tr>
* <tr>
* <td>Audio</td>
* <td bgcolor="#00EE00">Yes</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>CDC</td>
* <td bgcolor="#00EE00">Yes</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>HID</td>
* <td bgcolor="#00EE00">Yes</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>MIDI</td>
* <td bgcolor="#00EE00">Yes</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>Mass Storage</td>
* <td bgcolor="#00EE00">Yes</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>Printer</td>
* <td bgcolor="#EE0000">No</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>RNDIS</td>
* <td bgcolor="#00EE00">Yes</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* <tr>
* <td>Still Image</td>
* <td bgcolor="#EE0000">No</td>
* <td bgcolor="#00EE00">Yes</td>
* </tr>
* </table>
*
*
* \section <API key> Using the Class Drivers
* To make the Class drivers easy to integrate into a user application, they all implement a standardized
* design with similarly named/used function, enums, defines and types. The two different modes are implemented
* slightly differently, and thus will be explained separately. For information on a specific class driver, read
* the class driver's module documentation.
*
* \subsection <API key> Device Mode Class Drivers
* Implementing a Device Mode Class Driver in a user application requires a number of steps to be followed. Firstly,
* the module configuration and state structure must be added to the project source. These structures are named in a
* similar manner between classes, that of <tt>USB_ClassInfo_<i>{Class Name}</i>_Device_t</tt>, and are used to hold the
* complete state and configuration for each class instance. Multiple class instances is where the power of the class
* drivers lie; multiple interfaces of the same class simply require more instances of the Class Driver's \c USB_ClassInfo_*
* structure.
*
* Inside the ClassInfo structure lies two sections, a \c Config section, and a \c State section. The \c Config
* section contains the instance's configuration parameters, and <b>must have all fields set by the user application</b>
* before the class driver is used. Each Device mode Class driver typically contains a set of configuration parameters
* for the endpoint size/number of the associated logical USB interface, plus any class-specific configuration parameters.
*
* The \c State section of the \c USB_ClassInfo_* structures are designed to be controlled by the Class Drivers only for
* maintaining the Class Driver instance's state, and should not normally be set by the user application.
*
* The following is an example of a properly initialized instance of the Audio Class Driver structure:
*
* \code
* <API key> My_Audio_Interface =
* {
* .Config =
* {
* .<API key> = 1,
*
* .<API key> = 1,
* .DataINEndpointSize = 256,
* },
* };
* \endcode
*
* \note The class driver's configuration parameters should match those used in the device's descriptors that are
* sent to the host.
*
* To initialize the Class driver instance, the driver's <tt><i>{Class Name}</i><API key>()</tt> function
* should be called in response to the \ref <API key>() event. This function will return a
* boolean true value if the driver successfully initialized the instance. Like all the class driver functions, this function
* takes in the address of the specific instance you wish to initialize - in this manner, multiple separate instances of
* the same class type can be initialized like this:
*
* \code
* void <API key>(void)
* {
* LEDs_SetAllLEDs(LEDMASK_USB_READY);
*
* if (!(<API key>(&My_Audio_Interface)))
* LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
* }
* \endcode
*
* Once initialized, it is important to maintain the class driver's state by repeatedly calling the Class Driver's
* <tt><i>{Class Name}</i>_Device_USBTask()</tt> function in the main program loop. The exact implementation of this
* function varies between class drivers, and can be used for any internal class driver purpose to maintain each
* instance. Again, this function uses the address of the instance to operate on, and thus needs to be called for each
* separate instance, just like the main USB maintenance routine \ref USB_USBTask():
*
* \code
* int main(void)
* {
* SetupHardware();
*
* LEDs_SetAllLEDs(<API key>);
*
* for (;;)
* {
* <API key>();
*
* <API key>(&My_Audio_Interface);
* USB_USBTask();
* }
* }
* \endcode
*
* The final standardized Device Class Driver function is the Control Request handler function
* <tt><i>{Class Name}</i><API key>()</tt>, which should be called when the
* \ref <API key>() event fires. This function should also be called for
* each class driver instance, using the address of the instance to operate on as the function's
* parameter. The request handler will abort if it is determined that the current request is not
* targeted at the given class driver instance, thus these methods can safely be called
* one-after-another in the event handler with no form of error checking:
*
* \code
* void <API key>(void)
* {
* <API key>(&My_Audio_Interface);
* }
* \endcode
*
* Each class driver may also define a set of callback functions (which are prefixed by \c CALLBACK_*
* in the function's name) which <b>must</b> also be added to the user application - refer to each
* individual class driver's documentation for mandatory callbacks. In addition, each class driver may
* also define a set of events (identifiable by their prefix of \c EVENT_* in the function's name), which
* the user application <b>may</b> choose to implement, or ignore if not needed.
*
* The individual Device Mode Class Driver documentation contains more information on the non-standardized,
* class-specific functions which the user application can then use on the driver instances, such as data
* read and write routines. See each driver's individual documentation for more information on the
* class-specific functions.
*
* \subsection Sec_ClassDriverHost Host Mode Class Drivers
* Implementing a Host Mode Class Driver in a user application requires a number of steps to be followed. Firstly,
* the module configuration and state structure must be added to the project source. These structures are named in a
* similar manner between classes, that of <tt>USB_ClassInfo_<b>{Class Name}</b>_Host_t</tt>, and are used to hold the
* complete state and configuration for each class instance. Multiple class instances is where the power of the class
* drivers lie; multiple interfaces of the same class simply require more instances of the Class Driver's \c USB_ClassInfo_*
* structure.
*
* Inside the \c USB_ClassInfo_* structure lies two sections, a \c Config section, and a \c State section. The \c Config
* section contains the instance's configuration parameters, and <b>must have all fields set by the user application</b>
* before the class driver is used. Each Device mode Class driver typically contains a set of configuration parameters
* for the endpoint size/number of the associated logical USB interface, plus any class-specific configuration parameters.
*
* The \c State section of the \c USB_ClassInfo_* structures are designed to be controlled by the Class Drivers only for
* maintaining the Class Driver instance's state, and should not normally be set by the user application.
*
* The following is an example of a properly initialized instance of the MIDI Class Driver structure:
*
* \code
* <API key> My_MIDI_Interface =
* {
* .Config =
* {
* .DataINPipeNumber = 1,
* .<API key> = false,
*
* .DataOUTPipeNumber = 2,
* .<API key> = false,
* },
* };
* \endcode
*
* To initialize the Class driver instance, the driver's <tt><b>{Class Name}</b><API key>()</tt> function
* should be called in response to the host state machine entering the \ref <API key> state. This function
* will return an error code from the class driver's <tt><b>{Class Name}</b><API key></tt> enum
* to indicate if the driver successfully initialized the instance and bound it to an interface in the attached device.
* Like all the class driver functions, this function takes in the address of the specific instance you wish to initialize -
* in this manner, multiple separate instances of the same class type can be initialized. A fragment of a Class Driver
* based Host mode application may look like the following:
*
* \code
* switch (USB_HostState)
* {
* case <API key>:
* LEDs_SetAllLEDs(<API key>);
*
* uint16_t <API key>;
* uint8_t <API key>[512];
*
* if (<API key>(1, &<API key>, <API key>,
* sizeof(<API key>)) != <API key>)
* {
* LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
* USB_HostState = <API key>;
* break;
* }
*
* if (<API key>(&My_MIDI_Interface,
* <API key>, <API key>) != <API key>)
* {
* LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
* USB_HostState = <API key>;
* break;
* }
*
* // Other state handler code here
* \endcode
*
* Note that the function also required the device's configuration descriptor so that it can determine which interface
* in the device to bind to - this can be retrieved as shown in the above fragment using the
* \ref <API key>() function. If the device does not implement the interface the class driver
* is looking for, if all the matching interfaces are already bound to class driver instances or if an error occurs while
* binding to a device interface (for example, a device endpoint bank larger that the maximum supported bank size is used)
* the configuration will fail.
*
* Once initialized, it is important to maintain the class driver's state by repeatedly calling the Class Driver's
* <tt><b>{Class Name}</b>_Host_USBTask()</tt> function in the main program loop. The exact implementation of this
* function varies between class drivers, and can be used for any internal class driver purpose to maintain each
* instance. Again, this function uses the address of the instance to operate on, and thus needs to be called for each
* separate instance, just like the main USB maintenance routine \ref USB_USBTask():
*
* \code
* int main(void)
* {
* SetupHardware();
*
* LEDs_SetAllLEDs(<API key>);
*
* for (;;)
* {
* switch (USB_HostState)
* {
* // Host state machine handling here
* }
*
* MIDI_Host_USBTask(&My_Audio_Interface);
* USB_USBTask();
* }
* }
* \endcode
*
* Each class driver may also define a set of callback functions (which are prefixed by \c CALLBACK_*
* in the function's name) which <b>must</b> also be added to the user application - refer to each
* individual class driver's documentation for mandatory callbacks. In addition, each class driver may
* also define a set of events (identifiable by their prefix of \c EVENT_* in the function's name), which
* the user application <b>may</b> choose to implement, or ignore if not needed.
*
* The individual Host Mode Class Driver documentation contains more information on the non-standardized,
* class-specific functions which the user application can then use on the driver instances, such as data
* read and write routines. See each driver's individual documentation for more information on the
* class-specific functions.
*/
#ifndef __USB_H__
#define __USB_H__
/* Macros: */
#define <API key>
/* Includes: */
#include "../../Common/Common.h"
#include "Core/USBMode.h"
/* Includes: */
#include "Core/USBTask.h"
#include "Core/Events.h"
#include "Core/StdDescriptors.h"
#include "Core/ConfigDescriptor.h"
#include "Core/USBController.h"
#include "Core/USBInterrupt.h"
#if defined(USB_CAN_BE_HOST) || defined(__DOXYGEN__)
#include "Core/Host.h"
#include "Core/Pipe.h"
#include "Core/HostStandardReq.h"
#include "Core/PipeStream.h"
#endif
#if defined(USB_CAN_BE_DEVICE) || defined(__DOXYGEN__)
#include "Core/Device.h"
#include "Core/Endpoint.h"
#include "Core/DeviceStandardReq.h"
#include "Core/EndpointStream.h"
#endif
#if defined(USB_CAN_BE_BOTH) || defined(__DOXYGEN__)
#include "Core/OTG.h"
#endif
#include "Class/Audio.h"
#include "Class/CDC.h"
#include "Class/HID.h"
#include "Class/MassStorage.h"
#include "Class/MIDI.h"
#include "Class/Printer.h"
#include "Class/RNDIS.h"
#include "Class/StillImage.h"
#endif
|
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Replays;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Users;
namespace osu.Game.Rulesets.Mania.Mods
{
public class ManiaModAutoplay : ModAutoplay<ManiaHitObject>
{
public override Score CreateReplayScore(IBeatmap beatmap) => new Score
{
ScoreInfo = new ScoreInfo { User = new User { Username = "osu!topus!" } },
Replay = new ManiaAutoGenerator((ManiaBeatmap)beatmap).Generate(),
};
}
}
|
package org.knowm.xchange.gatecoin;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.gatecoin.dto.GatecoinException;
import org.knowm.xchange.gatecoin.dto.marketdata.Results.GatecoinDepthResult;
import org.knowm.xchange.gatecoin.dto.marketdata.Results.<API key>;
import org.knowm.xchange.gatecoin.dto.marketdata.Results.<API key>;
@Path("api")
@Produces(MediaType.APPLICATION_JSON)
public interface Gatecoin {
/**
* Returns "bids" and "asks". Each is a list of open orders and each order is represented as a list of price and amount.
*/
@GET
@Path("public/MarketDepth/{CurrencyPair}")
GatecoinDepthResult getOrderBook(@PathParam("CurrencyPair") String CurrencyPair) throws IOException, GatecoinException;
@GET
@Path("public/livetickers/")
<API key> getTicker() throws IOException, GatecoinException;
/**
* Returns descending list of transactions.
*/
@GET
@Path("public/transactions/{CurrencyPair}")
<API key> getTransactions(@PathParam("CurrencyPair") String CurrencyPair) throws IOException, GatecoinException;
/**
* Returns descending list of transactions.
*/
@GET
@Path("public/transactions/{CurrencyPair}")
<API key> getTransactions(@PathParam("CurrencyPair") String CurrencyPair, @QueryParam("Count") int Count,
@QueryParam("TransactionId") long TransactionId) throws IOException, GatecoinException;
}
|
# <API key>
An <API key> is an [ITICMaterial's](/Mods/Modtweaker/TConstruct/Materials/ITICMaterial/) definition.
You can use this to retrieve some information on the [ITICMaterial](/Mods/Modtweaker/TConstruct/Materials/ITICMaterial/) object.
## Importing the package
It might be required for you to import the package if you encounter any issues, so better be safe than sorry and add the import.
`import modtweaker.tconstruct.<API key>;`
## Retrieving such an object
You can retrieve an <API key> from an [ITICMaterial's](/Mods/Modtweaker/TConstruct/Materials/ITICMaterial/) `definition` ZenGetter:
zenscript
val def = <ticmat:stone>.definition;
## ZenGetters
| ZenGetter | Return Type | Description |
|
| name | string | The material's internal name |
| displayName | string | The material's localized name |
|
<?php namespace EchoIt\JsonApi;
/**
* A class used to represented a client request to the API.
*
* @author Ronni Egeriis Persson <[email protected]>
*/
class Request
{
/**
* Contains the url of the request
*
* @var string
*/
public $url;
/**
* Contains the HTTP method of the request
*
* @var string
*/
public $method;
/**
* Contains an optional model ID from the request
*
* @var int
*/
public $id;
/**
* Contains any content in request
*
* @var string
*/
public $content;
/**
* Contains an array of linked resource collections to load
*
* @var array
*/
public $include;
/**
* Contains an array of column names to sort on
*
* @var array
*/
public $sort;
/**
* Contains an array of key/value pairs to filter on
*
* @var array
*/
public $filter;
/**
* Specifies the page number to return results for
* @var integer
*/
public $pageNumber;
/**
* Specifies the number of results to return per page. Only used if
* pagination is requested (ie. pageNumber is not null)
*
* @var integer
*/
public $pageSize = 50;
/**
* Constructor.
*
* @param string $url
* @param string $method
* @param int $id
* @param mixed $content
* @param array $include
* @param array $sort
* @param array $filter
* @param integer $pageNumber
* @param integer $pageSize
*/
public function __construct($url, $method, $id = null, $content = null, $include = [], $sort = [], $filter = [], $pageNumber = null, $pageSize = null)
{
$this->url = $url;
$this->method = $method;
$this->id = $id;
$this->content = $content;
$this->include = $include ?: [];
$this->sort = $sort ?: [];
$this->filter = $filter ?: [];
$this->pageNumber = $pageNumber ?: null;
if ($pageSize) {
$this->pageSize = $pageSize;
}
}
}
|
namespace System.Reflection
{
using System;
internal static class MdConstant
{
public static unsafe Object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw)
{
CorElementType corElementType = 0;
long buffer = 0;
int length;
String stringVal;
stringVal = scope.GetDefaultValue(token, out buffer, out length, out corElementType);
RuntimeType fieldType = fieldTypeHandle.GetRuntimeType();
if (fieldType.IsEnum && raw == false)
{
long defaultValue = 0;
switch (corElementType)
{
#region Switch
case CorElementType.Void:
return DBNull.Value;
case CorElementType.Char:
defaultValue = *(char*)&buffer;
break;
case CorElementType.I1:
defaultValue = *(sbyte*)&buffer;
break;
case CorElementType.U1:
defaultValue = *(byte*)&buffer;
break;
case CorElementType.I2:
defaultValue = *(short*)&buffer;
break;
case CorElementType.U2:
defaultValue = *(ushort*)&buffer;
break;
case CorElementType.I4:
defaultValue = *(int*)&buffer;
break;
case CorElementType.U4:
defaultValue = *(uint*)&buffer;
break;
case CorElementType.I8:
defaultValue = buffer;
break;
case CorElementType.U8:
defaultValue = buffer;
break;
default:
throw new FormatException(Environment.GetResourceString("<API key>"));
#endregion
}
return RuntimeType.CreateEnum(fieldType, defaultValue);
}
else if (fieldType == typeof(DateTime))
{
long defaultValue = 0;
switch (corElementType)
{
#region Switch
case CorElementType.Void:
return DBNull.Value;
case CorElementType.I8:
defaultValue = buffer;
break;
case CorElementType.U8:
defaultValue = buffer;
break;
default:
throw new FormatException(Environment.GetResourceString("<API key>"));
#endregion
}
return new DateTime(defaultValue);
}
else
{
switch (corElementType)
{
#region Switch
case CorElementType.Void:
return DBNull.Value;
case CorElementType.Char:
return *(char*)&buffer;
case CorElementType.I1:
return *(sbyte*)&buffer;
case CorElementType.U1:
return *(byte*)&buffer;
case CorElementType.I2:
return *(short*)&buffer;
case CorElementType.U2:
return *(ushort*)&buffer;
case CorElementType.I4:
return *(int*)&buffer;
case CorElementType.U4:
return *(uint*)&buffer;
case CorElementType.I8:
return buffer;
case CorElementType.U8:
return (ulong)buffer;
case CorElementType.Boolean :
// The boolean value returned from the metadata engine is stored as a
// BOOL, which actually maps to an int. We need to read it out as an int
// to avoid problems on big-endian machines.
return (*(int*)&buffer != 0);
case CorElementType.R4 :
return *(float*)&buffer;
case CorElementType.R8:
return *(double*)&buffer;
case CorElementType.String:
// A string constant can be empty but never null.
// A nullref constant can only be type CorElementType.Class.
return stringVal == null ? String.Empty : stringVal;
case CorElementType.Class:
return null;
default:
throw new FormatException(Environment.GetResourceString("<API key>"));
#endregion
}
}
}
}
}
|
// This software is part of the Autofac IoC container
// 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,
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// 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.
using System;
using System.Linq;
using Autofac.Integration.WebApi;
using NUnit.Framework;
namespace Autofac.Tests.Integration.WebApi
{
[TestFixture]
public class <API key>
{
[Test]
public void <API key>()
{
var exception = Assert.Throws<<API key>>(
() => new <API key>(null));
Assert.That(exception.ParamName, Is.EqualTo("container"));
}
[Test]
public void <API key>()
{
var container = new ContainerBuilder().Build();
var resolver = new <API key>(container);
var service = resolver.GetService(typeof(object));
Assert.That(service, Is.Null);
}
[Test]
public void <API key>()
{
var builder = new ContainerBuilder();
builder.Register(c => new object());
var container = builder.Build();
var resolver = new <API key>(container);
var service = resolver.GetService(typeof(object));
Assert.That(service, Is.Not.Null);
}
[Test]
public void <API key>()
{
var container = new ContainerBuilder().Build();
var resolver = new <API key>(container);
var services = resolver.GetServices(typeof(object));
Assert.That(services.Count(), Is.EqualTo(0));
}
[Test]
public void <API key>()
{
var builder = new ContainerBuilder();
builder.Register(c => new object());
var container = builder.Build();
var resolver = new <API key>(container);
var services = resolver.GetServices(typeof(object));
Assert.That(services.Count(), Is.EqualTo(1));
}
[Test]
public void <API key>()
{
var builder = new ContainerBuilder();
builder.Register(c => new object());
builder.Register(c => new object());
var container = builder.Build();
var resolver = new <API key>(container);
var services = resolver.GetServices(typeof(object));
Assert.That(services.Count(), Is.EqualTo(2));
}
[Test]
public void <API key>()
{
var builder = new ContainerBuilder();
builder.Register(c => new object());
var container = builder.Build();
var resolver = new <API key>(container);
Assert.That(resolver.BeginScope(), Is.Not.SameAs(resolver.BeginScope()));
}
}
}
|
using System;
using Autofac.Core;
using Autofac.Core.Activators.Reflection;
namespace Autofac.Builder
{
<summary>
Reflection activator data for concrete types.
</summary>
public class <API key> : <API key>, <API key>
{
<summary>
Specify a reflection activator for the given type.
</summary>
<param name="implementer">Type that will be activated.</param>
public <API key>(Type implementer)
: base(implementer)
{
}
<summary>
The instance activator based on the provided data.
</summary>
public IInstanceActivator Activator
{
get
{
return new ReflectionActivator(
ImplementationType,
ConstructorFinder,
ConstructorSelector,
<API key>,
<API key>);
}
}
}
}
|
require File.expand_path('../../test_helper', __FILE__)
class <API key> < <API key>
def setup
$test_user = Person.find(1)
end
def replace_tags
put '/posts/15/relationships/tags', params:
{
'data' => [{type: 'tags', id: 11}, {type: 'tags', id: 3}, {type: 'tags', id: 12}, {type: 'tags', id: 13}, {type: 'tags', id: 14}
]
}.to_json,
headers: {
"CONTENT_TYPE" => JSONAPI::MEDIA_TYPE,
'Accept' => JSONAPI::MEDIA_TYPE
}
assert_response :no_content
post_object = Post.find(15)
assert_equal 5, post_object.tags.collect { |tag| tag.id }.length
put '/posts/15/relationships/tags', params:
{
'data' => [{type: 'tags', id: 2}, {type: 'tags', id: 3}, {type: 'tags', id: 4}
]
}.to_json,
headers: {
"CONTENT_TYPE" => JSONAPI::MEDIA_TYPE,
'Accept' => JSONAPI::MEDIA_TYPE
}
assert_response :no_content
post_object = Post.find(15)
assert_equal 3, post_object.tags.collect { |tag| tag.id }.length
end
# ToDo: Cleanup fixtures and session so benchmarks are consistent without an order dependence.
# def <API key>
# reflect = ENV['REFLECT']
# if reflect
# puts "relationship reflection on"
# else
# puts "relationship reflection off"
# end
# JSONAPI.configuration.<API key> = reflect
# 100.times do
# replace_tags
# end
# ensure
# JSONAPI.configuration.<API key> = false
# end
def <API key>
JSONAPI.configuration.<API key> = true
100.times do
replace_tags
end
ensure
JSONAPI.configuration.<API key> = false
end
def <API key>
JSONAPI.configuration.<API key> = false
100.times do
replace_tags
end
ensure
JSONAPI.configuration.<API key> = false
end
end
|
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// 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.
function LeapToy::<API key>( %this )
{
if (!isObject(<API key>))
{
%this.SwapImageBehavior = new BehaviorTemplate(<API key>);
%this.SwapImageBehavior.friendlyName = "Swap Image On Collision";
%this.SwapImageBehavior.behaviorType = "Effects";
%this.SwapImageBehavior.description = "Switches the image of an object when it collides";
%this.SwapImageBehavior.addBehaviorField(image, "The image to swap to", asset, "", ImageAsset);
%this.SwapImageBehavior.addBehaviorField(frame, "The frame of the image to swap to", int, 0);
%this.add(%this.SwapImageBehavior);
}
}
function <API key>::initialize(%this, %image, %frame)
{
%this.image = %image;
%this.frame = %frame;
}
function <API key>::onBehaviorAdd(%this)
{
%this.owner.collisionCallback = true;
}
function <API key>::onCollision(%this, %object, %collisionDetails)
{
%this.owner.setImage(%this.image, %this.frame);
}
|
function sample() {
alert('Hello from sample.js!')
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - interactive instances (gpu)</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
.info {
position: absolute;
background-color: black;
opacity: 0.8;
color: white;
text-align: center;
top: 0px;
width: 100%;
}
.info a {
color: #00ffff;
}
#notSupported {
width: 50%;
margin: auto;
border: 2px red solid;
margin-top: 20px;
padding: 10px;
}
</style>
</head>
<body>
<div class="info">
<a href="http://threejs.org" target="_blank">three.js</a> webgl - gpu picking of geometry instances
<div id="notSupported" style="display:none">Sorry your graphics card + browser does not support hardware instancing</div>
<br/><br/>
<div>This demo compares different methods of constructing and rendering many instances of a single geometry.</div>
<br/>
<div>
<div style="display:inline-block;">
<span>number of<br/>geometry instances</span>
<br/>
<select id="instanceCount">
<option>100</option>
<option>500</option>
<option selected>1000</option>
<option>2000</option>
<option>3000</option>
<option>5000</option>
<option>10000</option>
<option>20000</option>
<option>30000</option>
<option>50000</option>
<option>100000</option>
</select>
</div>
<div style="display:inline-block;">
<span>method of<br/>construction/rendering</span>
<br/>
<select id="method">
<option>instanced</option>
<option>merged</option>
<option selected>singleMaterial</option>
<option>multiMaterial</option>
</select>
</div>
<div style="display:inline-block;">
<span>render continuously<br/>(to get fps reading)</span>
<br/>
<input id="animate" type="checkbox" />
</div>
<div style="display:inline-block;">
<span>use override material<br/>(only effects singleMaterial method)</span>
<br/>
<input id="override" type="checkbox" checked/>
</div>
<div style="display:inline-block;">
<span>construct anew<br/>(to get additional timings)</span>
<br/>
<button id="construct" type="button">do it</button>
</div>
</div>
<br/>
<div>
<span>Materials: #<span id="materialCount"></span></span>
<span>Objects: #<span id="objectCount"></span></span>
<span>Drawcalls: #<span id="drawcalls"></span></span>
<span>Construction time: <span id="initTime"></span> ms</span>
</div>
</div>
<div id="container"></div>
<script src="../build/three.js"></script>
<script src="js/controls/TrackballControls.js"></script>
<script src="js/libs/stats.min.js"></script>
<script id="vertMerged" type="x-shader/x-vertex">
#define SHADER_NAME vertMerged
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
#ifdef PICKING
attribute vec3 pickingColor;
#else
attribute vec3 color;
#endif
varying vec3 vColor;
varying vec3 vPosition;
void main() {
#ifdef PICKING
vColor = pickingColor;
#else
vColor = color;
#endif
vPosition = ( modelViewMatrix * vec4( position, 1.0 ) ).xyz;
gl_Position = projectionMatrix * vec4( vPosition, 1.0 );
}
</script>
<script id="fragMerged" type="x-shader/x-fragment">
#define SHADER_NAME fragMerged
#extension <API key> : enable
precision highp float;
varying vec3 vColor;
varying vec3 vPosition;
void main() {
#ifdef PICKING
gl_FragColor = vec4( vColor, 1.0 );
#else
vec3 fdx = dFdx( vPosition );
vec3 fdy = dFdy( vPosition );
vec3 normal = normalize( cross( fdx, fdy ) );
float diffuse = dot( normal, vec3( 0.0, 0.0, 1.0 ) );
gl_FragColor = vec4( diffuse * vColor, 1.0 );
#endif
}
</script>
<script id="vertInstanced" type="x-shader/x-vertex">
#define SHADER_NAME vertInstanced
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
// attribute mat4 matrix;
attribute vec3 mcol0;
attribute vec3 mcol1;
attribute vec3 mcol2;
attribute vec3 mcol3;
#ifdef PICKING
attribute vec3 pickingColor;
#else
attribute vec3 color;
#endif
varying vec3 vColor;
varying vec3 vPosition;
void main() {
mat4 matrix = mat4(
vec4( mcol0, 0 ),
vec4( mcol1, 0 ),
vec4( mcol2, 0 ),
vec4( mcol3, 1 )
);
#ifdef PICKING
vColor = pickingColor;
#else
vColor = color;
#endif
vPosition = ( modelViewMatrix * matrix * vec4( position, 1.0 ) ).xyz;
gl_Position = projectionMatrix * vec4( vPosition, 1.0 );
}
</script>
<script id="fragInstanced" type="x-shader/x-fragment">
#define SHADER_NAME fragInstanced
#extension <API key> : enable
precision highp float;
varying vec3 vColor;
varying vec3 vPosition;
void main() {
#ifdef PICKING
gl_FragColor = vec4( vColor, 1.0 );
#else
vec3 fdx = dFdx( vPosition );
vec3 fdy = dFdy( vPosition );
vec3 normal = normalize( cross( fdx, fdy ) );
float diffuse = dot( normal, vec3( 0.0, 0.0, 1.0 ) );
gl_FragColor = vec4( diffuse * vColor, 1.0 );
#endif
}
</script>
<script id="vertMaterial" type="x-shader/x-vertex">
#define SHADER_NAME vertMaterial
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
varying vec3 vPosition;
void main() {
vPosition = ( modelViewMatrix * vec4( position, 1.0 ) ).xyz;
gl_Position = projectionMatrix * vec4( vPosition, 1.0 );
}
</script>
<script id="fragMaterial" type="x-shader/x-fragment">
#define SHADER_NAME fragMaterial
#extension <API key> : enable
precision highp float;
#ifdef PICKING
uniform vec3 pickingColor;
#else
uniform vec3 color;
#endif
varying vec3 vPosition;
void main() {
#ifdef PICKING
gl_FragColor = vec4( pickingColor, 1.0 );
#else
vec3 fdx = dFdx( vPosition );
vec3 fdy = dFdy( vPosition );
vec3 normal = normalize( cross( fdx, fdy ) );
float diffuse = dot( normal, vec3( 0.0, 0.0, 1.0 ) );
gl_FragColor = vec4( diffuse * color, 1.0 );
#endif
}
</script>
<script>
var container, stats;
var camera, controls, scene, renderer;
var pickingData, pickingRenderTarget, pickingScene;
var useOverrideMaterial = true;
var singleMaterial, <API key>;
var highlightBox;
var materialList = [];
var geometryList = [];
var objectCount = 0;
var geometrySize;
var mouse = new THREE.Vector2();
var scale = 1.03;
var loader = new THREE.JSONLoader();
//create buffer for reading a single pixel
var pixelBuffer = new Uint8Array( 4 );
// gui
var instanceCount, method, doAnimate;
gui();
init();
initMesh();
if ( doAnimate ) animate();
function gui() {
var instanceCountElm = document.getElementById( 'instanceCount' );
instanceCount = parseInt( instanceCountElm.value );
instanceCountElm.addEventListener( "change", function() {
instanceCount = parseInt( instanceCountElm.value );
initMesh();
} );
var methodElm = document.getElementById( 'method' );
method = methodElm.value;
methodElm.addEventListener( "change", function() {
method = methodElm.value;
initMesh();
} );
var animateElm = document.getElementById( 'animate' );
doAnimate = animateElm.checked;
animateElm.addEventListener( "click", function() {
doAnimate = animateElm.checked;
animate();
} );
var overrideElm = document.getElementById( 'override' );
useOverrideMaterial = overrideElm.checked;
overrideElm.addEventListener( "click", function() {
useOverrideMaterial = overrideElm.checked;
initMesh();
} );
var constructElm = document.getElementById( 'construct' );
constructElm.addEventListener( "click", function() {
initMesh();
} );
}
function clean() {
THREE.Cache.clear();
materialList.forEach( function( m ) {
m.dispose();
} );
geometryList.forEach( function( g ) {
g.dispose();
} );
scene = new THREE.Scene();
scene.add( camera );
scene.add( highlightBox );
pickingScene = new THREE.Scene();
pickingData = {};
materialList = [];
geometryList = [];
objectCount = 0;
singleMaterial = undefined;
<API key> = undefined;
}
var randomizeMatrix = function() {
var position = new THREE.Vector3();
var rotation = new THREE.Euler();
var quaternion = new THREE.Quaternion();
var scale = new THREE.Vector3();
return function( matrix ) {
position.x = Math.random() * 40 - 20;
position.y = Math.random() * 40 - 20;
position.z = Math.random() * 40 - 20;
rotation.x = Math.random() * 2 * Math.PI;
rotation.y = Math.random() * 2 * Math.PI;
rotation.z = Math.random() * 2 * Math.PI;
quaternion.setFromEuler( rotation, false );
scale.x = scale.y = scale.z = Math.random() * 1;
matrix.compose( position, quaternion, scale );
};
}();
function initMesh() {
clean();
// make instances
loader.load( 'obj/Suzanne.js', function ( geo ) {
geo.computeBoundingBox();
geometrySize = geo.boundingBox.size();
geometryList.push( geo );
console.log( "method:", method );
console.log( "instanceCount:", instanceCount );
console.time( "init mesh" );
var start = window.performance.now();
switch ( method ){
case "merged":
makeMerged( geo );
break;
case "instanced":
makeInstanced( geo );
break;
case "singleMaterial":
makeSingleMaterial( geo );
break;
case "multiMaterial":
makeMultiMaterial( geo );
break;
}
render();
console.timeEnd( "init mesh", method );
var end = window.performance.now();
console.log( "material count:", materialList.length );
console.log( "geometry count:", geometryList.length );
console.log( "object count:", objectCount );
console.log( renderer.info.memory )
console.log( renderer.info.render )
document.getElementById( 'materialCount' ).innerText = materialList.length;
document.getElementById( 'objectCount' ).innerText = objectCount;
document.getElementById( 'drawcalls' ).innerText = renderer.info.render.calls;
document.getElementById( 'initTime' ).innerText = ( end - start ).toFixed( 2 );
} );
}
function makeMultiMaterial( geo ) {
// material
var vert = document.getElementById( 'vertMaterial' ).textContent;
var frag = document.getElementById( 'fragMaterial' ).textContent;
var material = new THREE.RawShaderMaterial( {
vertexShader: vert,
fragmentShader: frag,
uniforms: {
color: {
value: new THREE.Color(),
}
}
} );
var pickingMaterial = new THREE.RawShaderMaterial( {
vertexShader: "#define PICKING\n" + vert,
fragmentShader: "#define PICKING\n" + frag,
uniforms: {
pickingColor: {
value: new THREE.Color(),
}
}
} );
// geometry / mesh
var matrix = new THREE.Matrix4();
for ( var i = 0; i < instanceCount; i ++ ) {
var object = new THREE.Mesh( geo, material );
objectCount ++;
randomizeMatrix( matrix );
object.applyMatrix( matrix );
var pickingObject = object.clone();
objectCount ++;
object.material = material.clone();
object.material.uniforms.color.value.setHex( Math.random() * 0xffffff );
materialList.push( object.material );
pickingObject.material = pickingMaterial.clone();
pickingObject.material.uniforms.pickingColor.value.setHex( i + 1 );
materialList.push( pickingObject.material );
pickingData[ i + 1 ] = object;
scene.add( object );
pickingScene.add( pickingObject );
}
material.dispose();
pickingMaterial.dispose();
}
function makeSingleMaterial( geo ) {
// material
var vert = document.getElementById( 'vertMaterial' ).textContent;
var frag = document.getElementById( 'fragMaterial' ).textContent;
function updateColor( object, material, camera ) {
this.value.setHex( object.userData.color );
}
var material = new THREE.RawShaderMaterial( {
vertexShader: vert,
fragmentShader: frag,
uniforms: {
color: new THREE.Uniform( new THREE.Color() ).onUpdate( updateColor )
}
} );
materialList.push( material );
function updatePickingColor( object, camera ) {
this.value.setHex( object.userData.pickingColor );
}
var pickingMaterial = new THREE.RawShaderMaterial( {
vertexShader: "#define PICKING\n" + vert,
fragmentShader: "#define PICKING\n" + frag,
uniforms: {
pickingColor: new THREE.Uniform( new THREE.Color() ).onUpdate( updatePickingColor )
}
} );
materialList.push( pickingMaterial );
if ( useOverrideMaterial ) {
// make globally available
singleMaterial = material;
<API key> = pickingMaterial;
}
// geometry / mesh
var matrix = new THREE.Matrix4();
for ( var i = 0; i < instanceCount; i ++ ) {
var object = new THREE.Mesh( geo, material );
objectCount ++;
randomizeMatrix( matrix );
object.applyMatrix( matrix );
var pickingObject;
if ( ! useOverrideMaterial ) {
pickingObject = object.clone();
objectCount ++;
}
object.material = material;
object.userData[ "color" ] = Math.random() * 0xffffff;
if ( useOverrideMaterial ) {
object.userData[ "pickingColor" ] = i + 1;
}else {
pickingObject.material = pickingMaterial;
pickingObject.userData[ "pickingColor" ] = i + 1;
}
pickingData[ i + 1 ] = object;
scene.add( object );
if ( ! useOverrideMaterial ) pickingScene.add( pickingObject );
}
}
function makeMerged( geo ) {
// material
var vert = document.getElementById( 'vertMerged' ).textContent;
var frag = document.getElementById( 'fragMerged' ).textContent;
var material = new THREE.RawShaderMaterial( {
vertexShader: vert,
fragmentShader: frag,
} );
materialList.push( material );
var pickingMaterial = new THREE.RawShaderMaterial( {
vertexShader: "#define PICKING\n" + vert,
fragmentShader: "#define PICKING\n" + frag,
} );
materialList.push( pickingMaterial );
// geometry
var bgeo = new THREE.BufferGeometry().fromGeometry( geo );
geometryList.push( bgeo );
var mgeo = new THREE.BufferGeometry();
geometryList.push( mgeo );
var pos = bgeo.attributes.position;
var posLen = bgeo.attributes.position.count * 3;
var vertices = new THREE.BufferAttribute(
new Float32Array( instanceCount * posLen ), 3
);
var matrix = new THREE.Matrix4();
for ( var i = 0, ul = instanceCount; i < ul; i ++ ) {
randomizeMatrix( matrix );
var object = new THREE.Object3D();
objectCount ++;
object.applyMatrix( matrix );
pickingData[ i + 1 ] = object;
vertices.set( pos.array, i * posLen );
matrix.applyToVector3Array( vertices.array, i * posLen, posLen )
}
mgeo.addAttribute( 'position', vertices );
var colCount = posLen / 3;
var colors = new THREE.BufferAttribute(
new Float32Array( instanceCount * colCount * 3 ), 3
);
var randCol = function() {
return Math.random();
};
for ( var i = 0, ul = instanceCount; i < ul; i ++ ) {
var r = randCol(), g = randCol(), b = randCol();
for ( var j = i * colCount, jl = ( i + 1 ) * colCount; j < jl; j ++ ) {
colors.setXYZ( j, r, g, b );
}
}
mgeo.addAttribute( 'color', colors );
var col = new THREE.Color();
var pickingColors = new THREE.BufferAttribute(
new Float32Array( instanceCount * colCount * 3 ), 3
);
for ( var i = 0, ul = instanceCount; i < ul; i ++ ) {
col.setHex( i + 1 );
for ( var j = i * colCount, jl = ( i + 1 ) * colCount; j < jl; j ++ ) {
pickingColors.setXYZ( j, col.r, col.g, col.b );
}
}
mgeo.addAttribute( 'pickingColor', pickingColors );
// mesh
var mesh = new THREE.Mesh( mgeo, material );
scene.add( mesh );
var pickingMesh = new THREE.Mesh( mgeo, pickingMaterial );
pickingScene.add( pickingMesh );
}
function makeInstanced( geo ) {
// material
var vert = document.getElementById( 'vertInstanced' ).textContent;
var frag = document.getElementById( 'fragInstanced' ).textContent;
var material = new THREE.RawShaderMaterial( {
vertexShader: vert,
fragmentShader: frag,
} );
materialList.push( material );
var pickingMaterial = new THREE.RawShaderMaterial( {
vertexShader: "#define PICKING\n" + vert,
fragmentShader: "#define PICKING\n" + frag,
} );
materialList.push( pickingMaterial );
// geometry
var bgeo = new THREE.BufferGeometry().fromGeometry( geo );
geometryList.push( bgeo );
var igeo = new THREE.<API key>();
geometryList.push( igeo );
var vertices = bgeo.attributes.position.clone();
igeo.addAttribute( 'position', vertices );
// var matrices = new THREE.<API key>(
// new Float32Array( instanceCount * 16 ), 16, 1
var mcol0 = new THREE.<API key>(
new Float32Array( instanceCount * 3 ), 3, 1
);
var mcol1 = new THREE.<API key>(
new Float32Array( instanceCount * 3 ), 3, 1
);
var mcol2 = new THREE.<API key>(
new Float32Array( instanceCount * 3 ), 3, 1
);
var mcol3 = new THREE.<API key>(
new Float32Array( instanceCount * 3 ), 3, 1
);
var matrix = new THREE.Matrix4();
var me = matrix.elements;
for ( var i = 0, ul = mcol0.count; i < ul; i ++ ) {
randomizeMatrix( matrix );
var object = new THREE.Object3D();
objectCount ++;
object.applyMatrix( matrix );
pickingData[ i + 1 ] = object;
// matrices.set( matrix.elements, i * 16 );
mcol0.setXYZ( i, me[ 0 ], me[ 1 ], me[ 2 ] );
mcol1.setXYZ( i, me[ 4 ], me[ 5 ], me[ 6 ] );
mcol2.setXYZ( i, me[ 8 ], me[ 9 ], me[ 10 ] );
mcol3.setXYZ( i, me[ 12 ], me[ 13 ], me[ 14 ] );
}
// igeo.addAttribute( 'matrix', matrices );
igeo.addAttribute( 'mcol0', mcol0 );
igeo.addAttribute( 'mcol1', mcol1 );
igeo.addAttribute( 'mcol2', mcol2 );
igeo.addAttribute( 'mcol3', mcol3 );
var randCol = function() {
return Math.random();
};
var colors = new THREE.<API key>(
new Float32Array( instanceCount * 3 ), 3, 1
);
for ( var i = 0, ul = colors.count; i < ul; i ++ ) {
colors.setXYZ( i, randCol(), randCol(), randCol() );
}
igeo.addAttribute( 'color', colors );
var col = new THREE.Color();
var pickingColors = new THREE.<API key>(
new Float32Array( instanceCount * 3 ), 3, 1
);
for ( var i = 0, ul = pickingColors.count; i < ul; i ++ ) {
col.setHex( i + 1 );
pickingColors.setXYZ( i, col.r, col.g, col.b );
}
igeo.addAttribute( 'pickingColor', pickingColors );
// mesh
var mesh = new THREE.Mesh( igeo, material );
scene.add( mesh );
var pickingMesh = new THREE.Mesh( igeo, pickingMaterial );
pickingScene.add( pickingMesh );
}
function init() {
// camera
camera = new THREE.PerspectiveCamera(
70, window.innerWidth / window.innerHeight, 1, 100
);
camera.position.z = 40;
// picking render target
pickingRenderTarget = new THREE.WebGLRenderTarget(
window.innerWidth, window.innerHeight
);
pickingRenderTarget.texture.generateMipmaps = false;
pickingRenderTarget.texture.minFilter = THREE.NearestFilter;
// highlight box
highlightBox = new THREE.Mesh(
new THREE.BoxGeometry( 1, 1, 1 ),
new THREE.MeshLambertMaterial( {
emissive: 0xffff00,
transparent: true,
opacity: 0.5,
side: THREE.FrontSide
} )
);
// renderer
container = document.getElementById( "container" );
renderer = new THREE.WebGLRenderer( {
antialias: true,
alpha: true
} );
if ( renderer.extensions.get( '<API key>' ) === false ) {
document.getElementById( "notSupported" ).style.display = "";
return;
}
renderer.setClearColor( 0xffffff );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
container.appendChild( renderer.domElement );
if ( renderer.extensions.get( '<API key>' ) === false ) {
throw '<API key> not supported';
}
// controls
controls = new THREE.TrackballControls(
camera, renderer.domElement
);
controls.staticMoving = true;
// stats
stats = new Stats();
container.appendChild( stats.dom );
// listeners
renderer.domElement.addEventListener( 'mousemove', onMouseMove );
window.addEventListener( 'resize', onWindowResize, false );
}
function onMouseMove( e ) {
mouse.x = e.clientX;
mouse.y = e.clientY;
controls.update();
<API key>( render );
}
function onWindowResize( event ) {
camera.aspect = window.innerWidth / window.innerHeight;
camera.<API key>();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
if ( doAnimate ) {
<API key>( animate );
}
controls.update();
stats.update();
render();
}
function pick() {
// render the picking scene off-screen
highlightBox.visible = false;
if ( <API key> ) {
scene.overrideMaterial = <API key>;
renderer.render( scene, camera, pickingRenderTarget );
scene.overrideMaterial = null;
}else {
renderer.render( pickingScene, camera, pickingRenderTarget );
}
// read the pixel under the mouse from the texture
renderer.<API key>(
pickingRenderTarget,
mouse.x,
pickingRenderTarget.height - mouse.y,
1,
1,
pixelBuffer
);
// interpret the pixel as an ID
var id =
( pixelBuffer[ 0 ] << 16 ) |
( pixelBuffer[ 1 ] << 8 ) |
( pixelBuffer[ 2 ] );
var object = pickingData[ id ];
if ( object ) {
// move the highlightBox so that it surrounds the picked object
if ( object.position && object.rotation && object.scale ) {
highlightBox.position.copy( object.position );
highlightBox.rotation.copy( object.rotation );
highlightBox.scale.copy( object.scale )
.multiply( geometrySize )
.multiplyScalar( scale );
highlightBox.visible = true;
}
} else {
highlightBox.visible = false;
}
}
function render() {
pick();
renderer.render( scene, camera );
}
</script>
</body>
</html>
|
//>>built
define("dojox/editor/plugins/nls/mk/PageBreak",{"pageBreak":"Прелом на страница"});
|
function test0(){
//Snippets:stfldprototype.ecs
function v710235()
{
}
v710235.prototype = 1;
var v710236 = new v710235();
// Make sure this literal's type isn't shared with the one with the constructor above
// as we would have the inline slot count locked for the literal
var litObj4 = {prop0: 1, prop1: 1, prop2: 1, prop3: 1, prop4: 1};
};
test0();
test0();
WScript.Echo("PASS");
|
<!doctype html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="http://cdn.jsdelivr.net/foundation/4.3.2/css/foundation.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<style>
input.ng-invalid {
border: 1px solid red;
}
input.ng-valid {
border: 1px solid green;
}
</style>
</head>
<body>
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
<div ng-repeat="field in fields" ng-form="signup_form_input">
<input type="text"
name="dynamic_input"
ng-required="field.isRequired"
ng-model="field.name"
placeholder="{{field.placeholder}}" />
<div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid">
<span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The field is required.</span>
</div>
</div>
<button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
</form>
<script>
angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.fields = [
{placeholder: 'Username', isRequired: true},
{placeholder: 'Password', isRequired: true},
{placeholder: 'Email (optional)', isRequired: false}
];
$scope.submitForm = function() {
alert("it works!");
};
});
</script>
</body>
</html>
|
import React from "react"
import { TypographyStyle, GoogleFont } from "react-typography"
import typography from "./.cache/typography"
exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
setHeadComponents([
<TypographyStyle key={`TypographyStyle`} typography={typography} />,
<GoogleFont key={`GoogleFont`} typography={typography} />,
])
}
|
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// to whom the Software is furnished to do so, subject to the following conditions:
// substantial portions of the Software.
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// 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.
using System;
using System.Globalization;
namespace ICSharpCode.AvalonEdit.Utils
{
<summary>
Contains exception-throwing helper methods.
</summary>
static class ThrowUtil
{
<summary>
Throws an <API key> if <paramref name="val"/> is null; otherwise
returns val.
</summary>
<example>
Use this method to throw an <API key> when using parameters for base
constructor calls.
<code>
public VisualLineText(string text) : base(ThrowUtil.CheckNotNull(text, "text").Length)
</code>
</example>
public static T CheckNotNull<T>(T val, string parameterName) where T : class
{
if (val == null)
throw new <API key>(parameterName);
return val;
}
public static int CheckNotNegative(int val, string parameterName)
{
if (val < 0)
throw new <API key>(parameterName, val, "value must not be negative");
return val;
}
public static int <API key>(int val, string parameterName, int lower, int upper)
{
if (val < lower || val > upper)
throw new <API key>(parameterName, val, "Expected: " + lower.ToString(CultureInfo.InvariantCulture) + " <= " + parameterName + " <= " + upper.ToString(CultureInfo.InvariantCulture));
return val;
}
public static <API key> NoDocumentAssigned()
{
return new <API key>("Document is null");
}
public static <API key> <API key>()
{
return new <API key>("Could not find a valid caret position in the line");
}
}
}
|
#!/bin/bash
set -e
#currentVersion=android-8.0.0_r36
#currentVersion=android-8.1.0_r22
currentVersion=android-9.0.0_r12
baseDir=`dirname $0`/..
<API key>="$HOME/Dev/AOSP/frameworks/base"
function showDiffs2() {
file="$1"
line="$2"
x=$(echo "$line" | sed -e 's/.*https:\/\/android.googlesource.com\/\([^ ]*\)\/[+]\/\([^/]*\)\/\([^ ]*\).*/\1 \2 \3/')
IFS=" " read -a parts <<< "$x"
repo="${parts[0]}"
version="${parts[1]}"
repoFile="${parts[2]}"
curSha=$(cd "$<API key>" && git rev-parse --verify "$currentVersion") || true
if [[ -z "$curSha" ]]; then
echo "Unknown $currentVersion!"
exit 1
fi
thisSha=$(cd "$<API key>" && git rev-parse --verify "$version") || true
if [[ -z "$thisSha" ]]; then
echo "Unknown $version!"
return
fi
if [ "x$curSha" != "x$thisSha" ]; then
(cd "$<API key>" && git diff --quiet "${version}..${currentVersion}" "--" "$repoFile")
if [ $? -eq 0 ]; then
echo "No changes in: $file"
echo " From $repoFile $version -> $currentVersion"
else
tmpFile="/tmp/diff.tmp"
rm -f "$tmpFile"
echo "Apply changes to: $file" > "$tmpFile"
echo " From $repoFile $version -> $currentVersion" >> "$tmpFile"
(cd "$<API key>" && git diff --color=always "${version}..${currentVersion}" "--" "$repoFile" >> "$tmpFile")
less -r "$tmpFile"
fi
fi
}
function showDiffs() {
file="$1"
grep -E 'https?:\/\/(android\.googlesource\.com|.*\.git\.corp\.google\.com)\/' "$file" | \
while read -r line ; do
showDiffs2 "$file" "$line"
done
}
files=$*
if [ -z "$files" ]; then
find . -name "*.java" -print0 | while read -d $'\0' file; do
showDiffs "$file"
done
else
for file in "$files"; do
showDiffs "$file"
done
fi
|
/* jshint node: true */
'use strict';
var Promise = require('ember-cli/lib/ext/promise');
var path = require('path');
var fs = require('fs');
var denodeify = require('rsvp').denodeify;
var readFile = denodeify(fs.readFile);
var DeployPluginBase = require('<API key>');
module.exports = {
name: '<API key>',
createDeployPlugin: function(options) {
var Redis = require('./lib/redis');
var DeployPlugin = DeployPluginBase.extend({
name: options.name,
defaultConfig: {
host: 'localhost',
port: 6379,
filePattern: 'index.html',
distDir: function(context) {
return context.distDir;
},
keyPrefix: function(context){
return context.project.name() + ':index';
},
didDeployMessage: function(context){
var revisionKey = context.revisionData && context.revisionData.revisionKey;
var <API key> = context.revisionData && context.revisionData.<API key>;
if (revisionKey && !<API key>) {
return "Deployed but did not activate revision " + revisionKey + ". "
+ "To activate, run: "
+ "ember deploy:activate " + context.deployTarget + " --revision=" + revisionKey + "\n";
}
},
revisionKey: function(context) {
return context.commandOptions.revision || (context.revisionData && context.revisionData.revisionKey);
},
redisDeployClient: function(context) {
var redisOptions = this.pluginConfig;
var redisLib = context._redisLib;
return new Redis(redisOptions, redisLib);
}
},
configure: function(/* context */) {
this.log('validating config');
if (!this.pluginConfig.url) {
['host', 'port'].forEach(this.<API key>.bind(this));
}
['filePattern', 'distDir', 'keyPrefix', 'revisionKey', 'didDeployMessage', 'redisDeployClient'].forEach(this.<API key>.bind(this));
this.log('config ok');
},
upload: function(/* context */) {
var redisDeployClient = this.readConfig('redisDeployClient');
var revisionKey = this.readConfig('revisionKey');
var distDir = this.readConfig('distDir');
var filePattern = this.readConfig('filePattern');
var keyPrefix = this.readConfig('keyPrefix');
var filePath = path.join(distDir, filePattern);
this.log('Uploading `' + filePath + '`');
return this._readFileContents(filePath)
.then(redisDeployClient.upload.bind(redisDeployClient, keyPrefix, revisionKey))
.then(this.<API key>.bind(this))
.then(function(key) {
return { redisKey: key };
})
.catch(this._errorMessage.bind(this));
},
activate: function(/* context */) {
var redisDeployClient = this.readConfig('redisDeployClient');
var revisionKey = this.readConfig('revisionKey');
var keyPrefix = this.readConfig('keyPrefix');
this.log('Activating revision `' + revisionKey + '`');
return Promise.resolve(redisDeployClient.activate(keyPrefix, revisionKey))
.then(this.log.bind(this, ' Activated revision `' + revisionKey + '`', {}))
.then(function(){
return {
revisionData: {
<API key>: revisionKey
}
};
})
.catch(this._errorMessage.bind(this));
},
didDeploy: function(/* context */){
var didDeployMessage = this.readConfig('didDeployMessage');
if (didDeployMessage) {
this.log(didDeployMessage);
}
},
fetchRevisions: function(context) {
var redisDeployClient = this.readConfig('redisDeployClient');
var keyPrefix = this.readConfig('keyPrefix');
this.log('Listing revisions for key: `' + keyPrefix + '`');
return Promise.resolve(redisDeployClient.fetchRevisions(keyPrefix))
.then(function(revisions){
return { revisions: revisions };
})
.catch(this._errorMessage.bind(this));
},
_readFileContents: function(path) {
return readFile(path)
.then(function(buffer) {
return buffer.toString();
});
},
<API key>: function(key) {
this.log('Uploaded with key `' + key + '`');
return Promise.resolve(key);
},
_errorMessage: function(error) {
this.log(error, { color: 'red' });
return Promise.reject(error);
}
});
return new DeployPlugin();
}
};
|
from test_support import verbose, TestFailed
if verbose:
print 'Running tests on argument handling'
try:
exec 'def f(a, a): pass'
raise TestFailed, "duplicate arguments"
except SyntaxError:
pass
try:
exec 'def f(a = 0, a = 1): pass'
raise TestFailed, "duplicate keyword arguments"
except SyntaxError:
pass
try:
exec 'def f(a): global a; a = 1'
raise TestFailed, "variable is global and local"
except SyntaxError:
pass
print "testing complex args"
def comp_args((a, b)):
print a,b
comp_args((1, 2))
def comp_args((a, b)=(3, 4)):
print a, b
comp_args((1, 2))
comp_args()
def comp_args(a, (b, c)):
print a, b, c
comp_args(1, (2, 3))
def comp_args(a=2, (b, c)=(3, 4)):
print a, b, c
comp_args(1, (2, 3))
comp_args()
try:
exec 'def f(a=1, (b, c)): pass'
raise TestFailed, "non-default args after default"
except SyntaxError:
pass
|
// ImageLib Sources
// Last modified: 03/07/2009
// Filename: src-IL/src/il_convert.cpp
// Description: Converts between several image formats
#include "il_internal.h"
#include <limits.h>
ILimage *iConvertPalette(ILimage *Image, ILenum DestFormat)
{
static const ILfloat LumFactor[3] = { 0.212671f, 0.715160f, 0.072169f };
ILimage *NewImage = NULL, *CurImage = NULL;
ILuint i, j, k, c, Size, LumBpp = 1;
ILfloat Resultf;
ILubyte *Temp = NULL;
ILboolean Converted;
ILboolean HasAlpha;
NewImage = (ILimage*)icalloc(1, sizeof(ILimage)); // Much better to have it all set to 0.
if (NewImage == NULL) {
return IL_FALSE;
}
ilCopyImageAttr(NewImage, Image);
if (!Image->Pal.Palette || !Image->Pal.PalSize || Image->Pal.PalType == IL_PAL_NONE || Image->Bpp != 1) {
ilCloseImage(NewImage);
ilSetError(<API key>);
return NULL;
}
if (DestFormat == IL_LUMINANCE || DestFormat == IL_LUMINANCE_ALPHA) {
if (NewImage->Pal.Palette)
ifree(NewImage->Pal.Palette);
if (DestFormat == IL_LUMINANCE_ALPHA)
LumBpp = 2;
switch (iCurImage->Pal.PalType)
{
case IL_PAL_RGB24:
case IL_PAL_RGB32:
case IL_PAL_RGBA32:
Temp = (ILubyte*)ialloc(LumBpp * Image->Pal.PalSize / ilGetBppPal(Image->Pal.PalType));
if (Temp == NULL)
goto alloc_error;
Size = ilGetBppPal(Image->Pal.PalType);
for (i = 0, k = 0; i < Image->Pal.PalSize; i += Size, k += LumBpp) {
Resultf = 0.0f;
for (c = 0; c < Size; c++) {
Resultf += Image->Pal.Palette[i + c] * LumFactor[c];
}
Temp[k] = (ILubyte)Resultf;
if (LumBpp == 2) {
if (iCurImage->Pal.PalType == IL_PAL_RGBA32)
Temp[k+1] = Image->Pal.Palette[i + 3];
else
Temp[k+1] = 0xff;
}
}
break;
case IL_PAL_BGR24:
case IL_PAL_BGR32:
case IL_PAL_BGRA32:
Temp = (ILubyte*)ialloc(LumBpp * Image->Pal.PalSize / ilGetBppPal(Image->Pal.PalType));
if (Temp == NULL)
goto alloc_error;
Size = ilGetBppPal(Image->Pal.PalType);
for (i = 0, k = 0; i < Image->Pal.PalSize; i += Size, k += LumBpp) {
Resultf = 0.0f; j = 2;
for (c = 0; c < Size; c++, j
Resultf += Image->Pal.Palette[i + c] * LumFactor[j];
}
Temp[k] = (ILubyte)Resultf;
if (LumBpp == 2) {
if (iCurImage->Pal.PalType == IL_PAL_RGBA32)
Temp[k+1] = Image->Pal.Palette[i + 3];
else
Temp[k+1] = 0xff;
}
}
break;
}
NewImage->Pal.Palette = NULL;
NewImage->Pal.PalSize = 0;
NewImage->Pal.PalType = IL_PAL_NONE;
NewImage->Format = DestFormat;
NewImage->Bpp = LumBpp;
NewImage->Bps = NewImage->Width * LumBpp;
NewImage->SizeOfData = NewImage->SizeOfPlane = NewImage->Bps * NewImage->Height;
NewImage->Data = (ILubyte*)ialloc(NewImage->SizeOfData);
if (NewImage->Data == NULL)
goto alloc_error;
if (LumBpp == 2) {
for (i = 0; i < Image->SizeOfData; i++) {
NewImage->Data[i*2] = Temp[Image->Data[i] * 2];
NewImage->Data[i*2+1] = Temp[Image->Data[i] * 2 + 1];
}
}
else {
for (i = 0; i < Image->SizeOfData; i++) {
NewImage->Data[i] = Temp[Image->Data[i]];
}
}
ifree(Temp);
return NewImage;
}
else if (DestFormat == IL_ALPHA) {
if (NewImage->Pal.Palette)
ifree(NewImage->Pal.Palette);
switch (iCurImage->Pal.PalType)
{
// Opaque, so all the values are 0xFF.
case IL_PAL_RGB24:
case IL_PAL_RGB32:
case IL_PAL_BGR24:
case IL_PAL_BGR32:
HasAlpha = IL_FALSE;
break;
case IL_PAL_BGRA32:
case IL_PAL_RGBA32:
HasAlpha = IL_TRUE;
Temp = (ILubyte*)ialloc(1 * Image->Pal.PalSize / ilGetBppPal(Image->Pal.PalType));
if (Temp == NULL)
goto alloc_error;
Size = ilGetBppPal(Image->Pal.PalType);
for (i = 0, k = 0; i < Image->Pal.PalSize; i += Size, k += 1) {
Temp[k] = Image->Pal.Palette[i + 3];
}
break;
}
NewImage->Pal.Palette = NULL;
NewImage->Pal.PalSize = 0;
NewImage->Pal.PalType = IL_PAL_NONE;
NewImage->Format = DestFormat;
NewImage->Bpp = LumBpp;
NewImage->Bps = NewImage->Width * 1; // Alpha is only one byte.
NewImage->SizeOfData = NewImage->SizeOfPlane = NewImage->Bps * NewImage->Height;
NewImage->Data = (ILubyte*)ialloc(NewImage->SizeOfData);
if (NewImage->Data == NULL)
goto alloc_error;
if (HasAlpha) {
for (i = 0; i < Image->SizeOfData; i++) {
NewImage->Data[i*2] = Temp[Image->Data[i] * 2];
NewImage->Data[i*2+1] = Temp[Image->Data[i] * 2 + 1];
}
}
else { // No alpha, opaque.
for (i = 0; i < Image->SizeOfData; i++) {
NewImage->Data[i] = 0xFF;
}
}
ifree(Temp);
return NewImage;
}
//NewImage->Format = ilGetPalBaseType(iCurImage->Pal.PalType);
NewImage->Format = DestFormat;
if (ilGetBppFormat(NewImage->Format) == 0) {
ilCloseImage(NewImage);
ilSetError(<API key>);
return NULL;
}
CurImage = iCurImage;
ilSetCurImage(NewImage);
switch (DestFormat)
{
case IL_RGB:
Converted = ilConvertPal(IL_PAL_RGB24);
break;
case IL_BGR:
Converted = ilConvertPal(IL_PAL_BGR24);
break;
case IL_RGBA:
Converted = ilConvertPal(IL_PAL_RGB32);
break;
case IL_BGRA:
Converted = ilConvertPal(IL_PAL_BGR32);
break;
case IL_COLOUR_INDEX:
// Just copy the original image over.
NewImage->Data = (ILubyte*)ialloc(CurImage->SizeOfData);
if (NewImage->Data == NULL)
goto alloc_error;
NewImage->Pal.Palette = (ILubyte*)ialloc(iCurImage->Pal.PalSize);
if (NewImage->Pal.Palette == NULL)
goto alloc_error;
memcpy(NewImage->Data, CurImage->Data, CurImage->SizeOfData);
memcpy(NewImage->Pal.Palette, Image->Pal.Palette, Image->Pal.PalSize);
NewImage->Pal.PalSize = Image->Pal.PalSize;
NewImage->Pal.PalType = Image->Pal.PalType;
ilSetCurImage(CurImage);
return NewImage;
default:
ilCloseImage(NewImage);
ilSetError(<API key>);
return NULL;
}
// Resize to new bpp
ilResizeImage(NewImage, NewImage->Width, NewImage->Height, NewImage->Depth, ilGetBppFormat(DestFormat), /*ilGetBpcType(DestType)*/1);
// ilConvertPal already sets the error message - no need to confuse the user.
if (!Converted) {
ilSetCurImage(CurImage);
ilCloseImage(NewImage);
return NULL;
}
Size = ilGetBppPal(NewImage->Pal.PalType);
for (i = 0; i < Image->SizeOfData; i++) {
for (c = 0; c < NewImage->Bpp; c++) {
NewImage->Data[i * NewImage->Bpp + c] = NewImage->Pal.Palette[Image->Data[i] * Size + c];
}
}
ifree(NewImage->Pal.Palette);
NewImage->Pal.Palette = NULL;
NewImage->Pal.PalSize = 0;
NewImage->Pal.PalType = IL_PAL_NONE;
ilSetCurImage(CurImage);
return NewImage;
alloc_error:
ifree(Temp);
if (NewImage)
ilCloseImage(NewImage);
if (CurImage != iCurImage)
ilSetCurImage(CurImage);
return NULL;
}
// In il_quantizer.c
ILimage *iQuantizeImage(ILimage *Image, ILuint NumCols);
// In il_neuquant.c
ILimage *iNeuQuant(ILimage *Image, ILuint NumCols);
// Converts an image from one format to another
ILAPI ILimage* ILAPIENTRY iConvertImage(ILimage *Image, ILenum DestFormat, ILenum DestType)
{
ILimage *NewImage, *CurImage;
ILuint i;
ILubyte *NewData;
CurImage = Image;
if (Image == NULL) {
ilSetError(<API key>);
return IL_FALSE;
}
// We don't support 16-bit color indices (or higher).
if (DestFormat == IL_COLOUR_INDEX && DestType >= IL_SHORT) {
ilSetError(<API key>);
return NULL;
}
if (Image->Format == IL_COLOUR_INDEX) {
NewImage = iConvertPalette(Image, DestFormat);
//added test 2003-09-01
if (NewImage == NULL)
return NULL;
if (DestType == NewImage->Type)
return NewImage;
NewData = (ILubyte*)ilConvertBuffer(NewImage->SizeOfData, NewImage->Format, DestFormat, NewImage->Type, DestType, NULL, NewImage->Data);
if (NewData == NULL) {
ifree(NewImage); // ilCloseImage not needed.
return NULL;
}
ifree(NewImage->Data);
NewImage->Data = NewData;
ilCopyImageAttr(NewImage, Image);
NewImage->Format = DestFormat;
NewImage->Type = DestType;
NewImage->Bpc = ilGetBpcType(DestType);
NewImage->Bpp = ilGetBppFormat(DestFormat);
NewImage->Bps = NewImage->Bpp * NewImage->Bpc * NewImage->Width;
NewImage->SizeOfPlane = NewImage->Bps * NewImage->Height;
NewImage->SizeOfData = NewImage->SizeOfPlane * NewImage->Depth;
}
else if (DestFormat == IL_COLOUR_INDEX && Image->Format != IL_LUMINANCE) {
if (iGetInt(<API key>) == IL_NEU_QUANT)
return iNeuQuant(Image, iGetInt(<API key>));
else // Assume IL_WU_QUANT otherwise.
return iQuantizeImage(Image, iGetInt(<API key>));
}
else {
NewImage = (ILimage*)icalloc(1, sizeof(ILimage)); // Much better to have it all set to 0.
if (NewImage == NULL) {
return NULL;
}
if (ilGetBppFormat(DestFormat) == 0) {
ilSetError(IL_INVALID_PARAM);
ifree(NewImage);
return NULL;
}
ilCopyImageAttr(NewImage, Image);
NewImage->Format = DestFormat;
NewImage->Type = DestType;
NewImage->Bpc = ilGetBpcType(DestType);
NewImage->Bpp = ilGetBppFormat(DestFormat);
NewImage->Bps = NewImage->Bpp * NewImage->Bpc * NewImage->Width;
NewImage->SizeOfPlane = NewImage->Bps * NewImage->Height;
NewImage->SizeOfData = NewImage->SizeOfPlane * NewImage->Depth;
if (DestFormat == IL_COLOUR_INDEX && Image->Format == IL_LUMINANCE) {
NewImage->Pal.PalSize = 768;
NewImage->Pal.PalType = IL_PAL_RGB24;
NewImage->Pal.Palette = (ILubyte*)ialloc(768);
for (i = 0; i < 256; i++) {
NewImage->Pal.Palette[i * 3] = i;
NewImage->Pal.Palette[i * 3 + 1] = i;
NewImage->Pal.Palette[i * 3 + 2] = i;
}
NewImage->Data = (ILubyte*)ialloc(Image->SizeOfData);
if (NewImage->Data == NULL) {
ilCloseImage(NewImage);
return NULL;
}
memcpy(NewImage->Data, Image->Data, Image->SizeOfData);
}
else {
NewImage->Data = (ILubyte*)ilConvertBuffer(Image->SizeOfData, Image->Format, DestFormat, Image->Type, DestType, NULL, Image->Data);
if (NewImage->Data == NULL) {
ifree(NewImage); // ilCloseImage not needed.
return NULL;
}
}
}
return NewImage;
}
//! Converts the current image to the DestFormat format.
/*! \param DestFormat An enum of the desired output format. Any format values are accepted.
\param DestType An enum of the desired output type. Any type values are accepted.
\exception <API key> No currently bound image
\exception <API key> DestFormat or DestType was an invalid identifier.
\exception IL_OUT_OF_MEMORY Could not allocate enough memory.
\return Boolean value of failure or success*/
ILboolean ILAPIENTRY ilConvertImage(ILenum DestFormat, ILenum DestType)
{
ILimage *Image, *pCurImage;
if (iCurImage == NULL) {
ilSetError(<API key>);
return IL_FALSE;
}
if (DestFormat == iCurImage->Format && DestType == iCurImage->Type)
return IL_TRUE; // No conversion needed.
if (DestType == iCurImage->Type) {
if (iFastConvert(DestFormat)) {
iCurImage->Format = DestFormat;
return IL_TRUE;
}
}
if (ilIsEnabled(IL_USE_KEY_COLOUR)) {
ilAddAlphaKey(iCurImage);
}
pCurImage = iCurImage;
while (pCurImage != NULL)
{
Image = iConvertImage(pCurImage, DestFormat, DestType);
if (Image == NULL)
return IL_FALSE;
//ilCopyImageAttr(pCurImage, Image); // Destroys subimages.
// We don't copy the colour profile here, since it stays the same.
// Same with the DXTC data.
pCurImage->Format = DestFormat;
pCurImage->Type = DestType;
pCurImage->Bpc = ilGetBpcType(DestType);
pCurImage->Bpp = ilGetBppFormat(DestFormat);
pCurImage->Bps = pCurImage->Width * pCurImage->Bpc * pCurImage->Bpp;
pCurImage->SizeOfPlane = pCurImage->Bps * pCurImage->Height;
pCurImage->SizeOfData = pCurImage->Depth * pCurImage->SizeOfPlane;
if (pCurImage->Pal.Palette && pCurImage->Pal.PalSize && pCurImage->Pal.PalType != IL_PAL_NONE)
ifree(pCurImage->Pal.Palette);
pCurImage->Pal.Palette = Image->Pal.Palette;
pCurImage->Pal.PalSize = Image->Pal.PalSize;
pCurImage->Pal.PalType = Image->Pal.PalType;
Image->Pal.Palette = NULL;
ifree(pCurImage->Data);
pCurImage->Data = Image->Data;
Image->Data = NULL;
ilCloseImage(Image);
pCurImage = pCurImage->Next;
}
return IL_TRUE;
}
// Swaps the colour order of the current image (rgb(a)->bgr(a) or vice-versa).
// Must be either an 8, 24 or 32-bit (coloured) image (or palette).
ILboolean ilSwapColours()
{
ILuint i = 0, Size = iCurImage->Bpp * iCurImage->Width * iCurImage->Height;
ILbyte PalBpp = ilGetBppPal(iCurImage->Pal.PalType);
ILushort *ShortPtr;
ILuint *IntPtr, Temp;
ILdouble *DoublePtr, DoubleTemp;
if ((iCurImage->Bpp != 1 && iCurImage->Bpp != 3 && iCurImage->Bpp != 4)) {
ilSetError(IL_INVALID_VALUE);
return IL_FALSE;
}
// Just check before we change the format.
if (iCurImage->Format == IL_COLOUR_INDEX) {
if (PalBpp == 0 || iCurImage->Format != IL_COLOUR_INDEX) {
ilSetError(<API key>);
return IL_FALSE;
}
}
switch (iCurImage->Format)
{
case IL_RGB:
iCurImage->Format = IL_BGR;
break;
case IL_RGBA:
iCurImage->Format = IL_BGRA;
break;
case IL_BGR:
iCurImage->Format = IL_RGB;
break;
case IL_BGRA:
iCurImage->Format = IL_RGBA;
break;
case IL_ALPHA:
case IL_LUMINANCE:
case IL_LUMINANCE_ALPHA:
return IL_TRUE; // No need to do anything to luminance or alpha images.
case IL_COLOUR_INDEX:
switch (iCurImage->Pal.PalType)
{
case IL_PAL_RGB24:
iCurImage->Pal.PalType = IL_PAL_BGR24;
break;
case IL_PAL_RGB32:
iCurImage->Pal.PalType = IL_PAL_BGR32;
break;
case IL_PAL_RGBA32:
iCurImage->Pal.PalType = IL_PAL_BGRA32;
break;
case IL_PAL_BGR24:
iCurImage->Pal.PalType = IL_PAL_RGB24;
break;
case IL_PAL_BGR32:
iCurImage->Pal.PalType = IL_PAL_RGB32;
break;
case IL_PAL_BGRA32:
iCurImage->Pal.PalType = IL_PAL_RGBA32;
break;
default:
ilSetError(<API key>);
return IL_FALSE;
}
break;
default:
ilSetError(<API key>);
return IL_FALSE;
}
if (iCurImage->Format == IL_COLOUR_INDEX) {
for (; i < iCurImage->Pal.PalSize; i += PalBpp) {
Temp = iCurImage->Pal.Palette[i];
iCurImage->Pal.Palette[i] = iCurImage->Pal.Palette[i+2];
iCurImage->Pal.Palette[i+2] = Temp;
}
}
else {
ShortPtr = (ILushort*)iCurImage->Data;
IntPtr = (ILuint*)iCurImage->Data;
DoublePtr = (ILdouble*)iCurImage->Data;
switch (iCurImage->Bpc)
{
case 1:
for (; i < Size; i += iCurImage->Bpp) {
Temp = iCurImage->Data[i];
iCurImage->Data[i] = iCurImage->Data[i+2];
iCurImage->Data[i+2] = Temp;
}
break;
case 2:
for (; i < Size; i += iCurImage->Bpp) {
Temp = ShortPtr[i];
ShortPtr[i] = ShortPtr[i+2];
ShortPtr[i+2] = Temp;
}
break;
case 4: // Works fine with ILint, ILuint and ILfloat.
for (; i < Size; i += iCurImage->Bpp) {
Temp = IntPtr[i];
IntPtr[i] = IntPtr[i+2];
IntPtr[i+2] = Temp;
}
break;
case 8:
for (; i < Size; i += iCurImage->Bpp) {
DoubleTemp = DoublePtr[i];
DoublePtr[i] = DoublePtr[i+2];
DoublePtr[i+2] = DoubleTemp;
}
break;
}
}
return IL_TRUE;
}
// Adds an opaque alpha channel to a 24-bit image
ILboolean ilAddAlpha()
{
ILubyte *NewData, NewBpp;
ILuint i = 0, j = 0, Size;
if (iCurImage == NULL) {
ilSetError(<API key>);
return IL_FALSE;
}
if (iCurImage->Bpp != 3) {
ilSetError(IL_INVALID_VALUE);
return IL_FALSE;
}
Size = iCurImage->Bps * iCurImage->Height / iCurImage->Bpc;
NewBpp = (ILubyte)(iCurImage->Bpp + 1);
NewData = (ILubyte*)ialloc(NewBpp * iCurImage->Bpc * iCurImage->Width * iCurImage->Height);
if (NewData == NULL) {
return IL_FALSE;
}
switch (iCurImage->Type)
{
case IL_BYTE:
case IL_UNSIGNED_BYTE:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
NewData[j] = iCurImage->Data[i];
NewData[j+1] = iCurImage->Data[i+1];
NewData[j+2] = iCurImage->Data[i+2];
NewData[j+3] = UCHAR_MAX; // Max opaqueness
}
break;
case IL_SHORT:
case IL_UNSIGNED_SHORT:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILushort*)NewData)[j] = ((ILushort*)iCurImage->Data)[i];
((ILushort*)NewData)[j+1] = ((ILushort*)iCurImage->Data)[i+1];
((ILushort*)NewData)[j+2] = ((ILushort*)iCurImage->Data)[i+2];
((ILushort*)NewData)[j+3] = USHRT_MAX;
}
break;
case IL_INT:
case IL_UNSIGNED_INT:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILuint*)NewData)[j] = ((ILuint*)iCurImage->Data)[i];
((ILuint*)NewData)[j+1] = ((ILuint*)iCurImage->Data)[i+1];
((ILuint*)NewData)[j+2] = ((ILuint*)iCurImage->Data)[i+2];
((ILuint*)NewData)[j+3] = UINT_MAX;
}
break;
case IL_FLOAT:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILfloat*)NewData)[j] = ((ILfloat*)iCurImage->Data)[i];
((ILfloat*)NewData)[j+1] = ((ILfloat*)iCurImage->Data)[i+1];
((ILfloat*)NewData)[j+2] = ((ILfloat*)iCurImage->Data)[i+2];
((ILfloat*)NewData)[j+3] = 1.0f;
}
break;
case IL_DOUBLE:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILdouble*)NewData)[j] = ((ILdouble*)iCurImage->Data)[i];
((ILdouble*)NewData)[j+1] = ((ILdouble*)iCurImage->Data)[i+1];
((ILdouble*)NewData)[j+2] = ((ILdouble*)iCurImage->Data)[i+2];
((ILdouble*)NewData)[j+3] = 1.0;
}
break;
default:
ifree(NewData);
ilSetError(IL_INTERNAL_ERROR);
return IL_FALSE;
}
iCurImage->Bpp = NewBpp;
iCurImage->Bps = iCurImage->Width * iCurImage->Bpc * NewBpp;
iCurImage->SizeOfPlane = iCurImage->Bps * iCurImage->Height;
iCurImage->SizeOfData = iCurImage->SizeOfPlane * iCurImage->Depth;
ifree(iCurImage->Data);
iCurImage->Data = NewData;
switch (iCurImage->Format)
{
case IL_RGB:
iCurImage->Format = IL_RGBA;
break;
case IL_BGR:
iCurImage->Format = IL_BGRA;
break;
}
return IL_TRUE;
}
//ILfloat KeyRed = 0, KeyGreen = 0, KeyBlue = 0, KeyAlpha = 0;
void ILAPIENTRY ilKeyColour(ILclampf Red, ILclampf Green, ILclampf Blue, ILclampf Alpha)
{
ILfloat KeyRed = 0, KeyGreen = 0, KeyBlue = 0, KeyAlpha = 0;
KeyRed = Red;
KeyGreen = Green;
KeyBlue = Blue;
KeyAlpha = Alpha;
return;
}
// Adds an alpha channel to an 8 or 24-bit image,
// making the image transparent where Key is equal to the pixel.
ILboolean ilAddAlphaKey(ILimage *Image)
{
ILfloat KeyRed = 0, KeyGreen = 0, KeyBlue = 0, KeyAlpha = 0;
ILubyte *NewData, NewBpp;
ILfloat KeyColour[3];
ILuint i = 0, j = 0, c, Size;
ILboolean Same;
if (Image == NULL) {
ilSetError(<API key>);
return IL_FALSE;
}
if (Image->Format != IL_COLOUR_INDEX) {
if (Image->Bpp != 3) {
ilSetError(IL_INVALID_VALUE);
return IL_FALSE;
}
if (Image->Format == IL_BGR || Image->Format == IL_BGRA) {
KeyColour[0] = KeyBlue;
KeyColour[1] = KeyGreen;
KeyColour[2] = KeyRed;
}
else {
KeyColour[0] = KeyRed;
KeyColour[1] = KeyGreen;
KeyColour[2] = KeyBlue;
}
Size = Image->Bps * Image->Height / Image->Bpc;
NewBpp = (ILubyte)(Image->Bpp + 1);
NewData = (ILubyte*)ialloc(NewBpp * Image->Bpc * Image->Width * Image->Height);
if (NewData == NULL) {
return IL_FALSE;
}
switch (Image->Type)
{
case IL_BYTE:
case IL_UNSIGNED_BYTE:
for (; i < Size; i += Image->Bpp, j += NewBpp) {
NewData[j] = Image->Data[i];
NewData[j+1] = Image->Data[i+1];
NewData[j+2] = Image->Data[i+2];
Same = IL_TRUE;
for (c = 0; c < Image->Bpp; c++) {
if (Image->Data[i+c] != KeyColour[c] * UCHAR_MAX)
Same = IL_FALSE;
}
if (Same)
NewData[j+3] = 0; // Transparent - matches key colour
else
NewData[j+3] = UCHAR_MAX;
}
break;
case IL_SHORT:
case IL_UNSIGNED_SHORT:
for (; i < Size; i += Image->Bpp, j += NewBpp) {
((ILushort*)NewData)[j] = ((ILushort*)Image->Data)[i];
((ILushort*)NewData)[j+1] = ((ILushort*)Image->Data)[i+1];
((ILushort*)NewData)[j+2] = ((ILushort*)Image->Data)[i+2];
Same = IL_TRUE;
for (c = 0; c < Image->Bpp; c++) {
if (((ILushort*)Image->Data)[i+c] != KeyColour[c] * USHRT_MAX)
Same = IL_FALSE;
}
if (Same)
((ILushort*)NewData)[j+3] = 0;
else
((ILushort*)NewData)[j+3] = USHRT_MAX;
}
break;
case IL_INT:
case IL_UNSIGNED_INT:
for (; i < Size; i += Image->Bpp, j += NewBpp) {
((ILuint*)NewData)[j] = ((ILuint*)Image->Data)[i];
((ILuint*)NewData)[j+1] = ((ILuint*)Image->Data)[i+1];
((ILuint*)NewData)[j+2] = ((ILuint*)Image->Data)[i+2];
Same = IL_TRUE;
for (c = 0; c < Image->Bpp; c++) {
if (((ILuint*)Image->Data)[i+c] != KeyColour[c] * UINT_MAX)
Same = IL_FALSE;
}
if (Same)
((ILuint*)NewData)[j+3] = 0;
else
((ILuint*)NewData)[j+3] = UINT_MAX;
}
break;
case IL_FLOAT:
for (; i < Size; i += Image->Bpp, j += NewBpp) {
((ILfloat*)NewData)[j] = ((ILfloat*)Image->Data)[i];
((ILfloat*)NewData)[j+1] = ((ILfloat*)Image->Data)[i+1];
((ILfloat*)NewData)[j+2] = ((ILfloat*)Image->Data)[i+2];
Same = IL_TRUE;
for (c = 0; c < Image->Bpp; c++) {
if (((ILfloat*)Image->Data)[i+c] != KeyColour[c])
Same = IL_FALSE;
}
if (Same)
((ILfloat*)NewData)[j+3] = 0.0f;
else
((ILfloat*)NewData)[j+3] = 1.0f;
}
break;
case IL_DOUBLE:
for (; i < Size; i += Image->Bpp, j += NewBpp) {
((ILdouble*)NewData)[j] = ((ILdouble*)Image->Data)[i];
((ILdouble*)NewData)[j+1] = ((ILdouble*)Image->Data)[i+1];
((ILdouble*)NewData)[j+2] = ((ILdouble*)Image->Data)[i+2];
Same = IL_TRUE;
for (c = 0; c < Image->Bpp; c++) {
if (((ILdouble*)Image->Data)[i+c] != KeyColour[c])
Same = IL_FALSE;
}
if (Same)
((ILdouble*)NewData)[j+3] = 0.0;
else
((ILdouble*)NewData)[j+3] = 1.0;
}
break;
default:
ifree(NewData);
ilSetError(IL_INTERNAL_ERROR);
return IL_FALSE;
}
Image->Bpp = NewBpp;
Image->Bps = Image->Width * Image->Bpc * NewBpp;
Image->SizeOfPlane = Image->Bps * Image->Height;
Image->SizeOfData = Image->SizeOfPlane * Image->Depth;
ifree(Image->Data);
Image->Data = NewData;
switch (Image->Format)
{
case IL_RGB:
Image->Format = IL_RGBA;
break;
case IL_BGR:
Image->Format = IL_BGRA;
break;
}
}
else { // IL_COLOUR_INDEX
if (Image->Bpp != 1) {
ilSetError(IL_INTERNAL_ERROR);
return IL_FALSE;
}
Size = ilGetInteger(IL_PALETTE_NUM_COLS);
if (Size == 0) {
ilSetError(IL_INTERNAL_ERROR);
return IL_FALSE;
}
if ((ILuint)(KeyAlpha * UCHAR_MAX) > Size) {
ilSetError(IL_INVALID_VALUE);
return IL_FALSE;
}
switch (Image->Pal.PalType)
{
case IL_PAL_RGB24:
case IL_PAL_RGB32:
case IL_PAL_RGBA32:
if (!ilConvertPal(IL_PAL_RGBA32))
return IL_FALSE;
break;
case IL_PAL_BGR24:
case IL_PAL_BGR32:
case IL_PAL_BGRA32:
if (!ilConvertPal(IL_PAL_BGRA32))
return IL_FALSE;
break;
default:
ilSetError(IL_INTERNAL_ERROR);
return IL_FALSE;
}
// Set the colour index to be transparent.
Image->Pal.Palette[(ILuint)(KeyAlpha * UCHAR_MAX) * 4 + 3] = 0;
// @TODO: Check if this is the required behaviour.
if (Image->Pal.PalType == IL_PAL_RGBA32)
ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
else
ilConvertImage(IL_BGRA, IL_UNSIGNED_BYTE);
}
return IL_TRUE;
}
// Removes alpha from a 32-bit image
// Should we maybe add an option that changes the image based on the alpha?
ILboolean ilRemoveAlpha()
{
ILubyte *NewData, NewBpp;
ILuint i = 0, j = 0, Size;
if (iCurImage == NULL) {
ilSetError(IL_INVALID_PARAM);
return IL_FALSE;
}
if (iCurImage->Bpp != 4) {
ilSetError(IL_INVALID_VALUE);
return IL_FALSE;
}
Size = iCurImage->Bps * iCurImage->Height;
NewBpp = (ILubyte)(iCurImage->Bpp - 1);
NewData = (ILubyte*)ialloc(NewBpp * iCurImage->Bpc * iCurImage->Width * iCurImage->Height);
if (NewData == NULL) {
return IL_FALSE;
}
switch (iCurImage->Type)
{
case IL_BYTE:
case IL_UNSIGNED_BYTE:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
NewData[j] = iCurImage->Data[i];
NewData[j+1] = iCurImage->Data[i+1];
NewData[j+2] = iCurImage->Data[i+2];
}
break;
case IL_SHORT:
case IL_UNSIGNED_SHORT:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILushort*)NewData)[j] = ((ILushort*)iCurImage->Data)[i];
((ILushort*)NewData)[j+1] = ((ILushort*)iCurImage->Data)[i+1];
((ILushort*)NewData)[j+2] = ((ILushort*)iCurImage->Data)[i+2];
}
break;
case IL_INT:
case IL_UNSIGNED_INT:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILuint*)NewData)[j] = ((ILuint*)iCurImage->Data)[i];
((ILuint*)NewData)[j+1] = ((ILuint*)iCurImage->Data)[i+1];
((ILuint*)NewData)[j+2] = ((ILuint*)iCurImage->Data)[i+2];
}
break;
case IL_FLOAT:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILfloat*)NewData)[j] = ((ILfloat*)iCurImage->Data)[i];
((ILfloat*)NewData)[j+1] = ((ILfloat*)iCurImage->Data)[i+1];
((ILfloat*)NewData)[j+2] = ((ILfloat*)iCurImage->Data)[i+2];
}
break;
case IL_DOUBLE:
for (; i < Size; i += iCurImage->Bpp, j += NewBpp) {
((ILdouble*)NewData)[j] = ((ILdouble*)iCurImage->Data)[i];
((ILdouble*)NewData)[j+1] = ((ILdouble*)iCurImage->Data)[i+1];
((ILdouble*)NewData)[j+2] = ((ILdouble*)iCurImage->Data)[i+2];
}
break;
default:
ifree(NewData);
ilSetError(IL_INTERNAL_ERROR);
return IL_FALSE;
}
iCurImage->Bpp = NewBpp;
iCurImage->Bps = iCurImage->Width * iCurImage->Bpc * NewBpp;
iCurImage->SizeOfPlane = iCurImage->Bps * iCurImage->Height;
iCurImage->SizeOfData = iCurImage->SizeOfPlane * iCurImage->Depth;
ifree(iCurImage->Data);
iCurImage->Data = NewData;
switch (iCurImage->Format)
{
case IL_RGBA:
iCurImage->Format = IL_RGB;
break;
case IL_BGRA:
iCurImage->Format = IL_BGR;
break;
}
return IL_TRUE;
}
ILboolean ilFixCur()
{
if (ilIsEnabled(IL_ORIGIN_SET)) {
if ((ILenum)ilGetInteger(IL_ORIGIN_MODE) != iCurImage->Origin) {
if (!ilFlipImage()) {
return IL_FALSE;
}
}
}
if (ilIsEnabled(IL_TYPE_SET)) {
if ((ILenum)ilGetInteger(IL_TYPE_MODE) != iCurImage->Type) {
if (!ilConvertImage(iCurImage->Format, ilGetInteger(IL_TYPE_MODE))) {
return IL_FALSE;
}
}
}
if (ilIsEnabled(IL_FORMAT_SET)) {
if ((ILenum)ilGetInteger(IL_FORMAT_MODE) != iCurImage->Format) {
if (!ilConvertImage(ilGetInteger(IL_FORMAT_MODE), iCurImage->Type)) {
return IL_FALSE;
}
}
}
if (iCurImage->Format == IL_COLOUR_INDEX) {
if (ilGetBoolean(IL_CONV_PAL) == IL_TRUE) {
if (!ilConvertImage(IL_BGR, IL_UNSIGNED_BYTE)) {
return IL_FALSE;
}
}
}
/* Swap Colors on Big Endian !!!!!
#ifdef __BIG_ENDIAN__
// Swap endian
EndianSwapData(iCurImage);
#endif
*/
return IL_TRUE;
}
/*
ILboolean ilFixImage()
{
ILuint NumImages, i;
NumImages = ilGetInteger(IL_NUM_IMAGES);
for (i = 0; i < NumImages; i++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveImage(i+1))
return IL_FALSE;
if (!ilFixCur())
return IL_FALSE;
}
NumImages = ilGetInteger(IL_NUM_MIPMAPS);
for (i = 0; i < NumImages; i++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveMipmap(i+1))
return IL_FALSE;
if (!ilFixCur())
return IL_FALSE;
}
NumImages = ilGetInteger(IL_NUM_LAYERS);
for (i = 0; i < NumImages; i++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveLayer(i+1))
return IL_FALSE;
if (!ilFixCur())
return IL_FALSE;
}
ilBindImage(ilGetCurName());
ilFixCur();
return IL_TRUE;
}
*/
/*
This function was replaced 20050304, because the previous version
didn't fix the mipmaps of the subimages etc. This version is not
completely correct either, because the subimages of the subimages
etc. are not fixed, but at the moment no images of this type can
be loaded anyway. Thanks to Chris Lux for pointing this out.
*/
ILboolean ilFixImage()
{
ILuint NumFaces, f;
ILuint NumImages, i;
ILuint NumMipmaps,j;
ILuint NumLayers, k;
NumImages = ilGetInteger(IL_NUM_IMAGES);
for (i = 0; i <= NumImages; i++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveImage(i))
return IL_FALSE;
NumFaces = ilGetInteger(IL_NUM_FACES);
for (f = 0; f <= NumFaces; f++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveImage(i))
return IL_FALSE;
if (!ilActiveFace(f))
return IL_FALSE;
NumLayers = ilGetInteger(IL_NUM_LAYERS);
for (k = 0; k <= NumLayers; k++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveImage(i))
return IL_FALSE;
if (!ilActiveFace(f))
return IL_FALSE;
if (!ilActiveLayer(k))
return IL_FALSE;
NumMipmaps = ilGetInteger(IL_NUM_MIPMAPS);
for (j = 0; j <= NumMipmaps; j++) {
ilBindImage(ilGetCurName()); // Set to parent image first.
if (!ilActiveImage(i))
return IL_FALSE;
if (!ilActiveFace(f))
return IL_FALSE;
if (!ilActiveLayer(k))
return IL_FALSE;
if (!ilActiveMipmap(j))
return IL_FALSE;
if (!ilFixCur())
return IL_FALSE;
}
}
}
}
ilBindImage(ilGetCurName());
return IL_TRUE;
}
|
/**
* Traditional Chinese spoken in Taiwan.
*/
$.Editable.LANGS['zh_tw'] = {
translation: {
"Bold": "\u7c97\u9ad4",
"Italic": "\u659c\u9ad4",
"Underline": "\u5e95\u7dda",
"Strikethrough": "\u522a\u9664\u7dda",
"Font Size": "\u5b57\u578b\u5927\u5c0f",
"Color": "\u984f\u8272",
"Background": "\u80cc\u666f",
"Text": "\u6587\u5b57",
"Format Block": "\u683c\u5f0f",
"Normal": "\u6b63\u5e38",
"Paragraph": "\u6bb5\u843d",
"Code": "\u7a0b\u5f0f\u78bc",
"Quote": "\u5f15\u7528",
"Heading 1": "\u6a19\u984c 1",
"Heading 2": "\u6a19\u984c 2",
"Heading 3": "\u6a19\u984c 3",
"Heading 4": "\u6a19\u984c 4",
"Heading 5": "\u6a19\u984c 5",
"Heading 6": "\u6a19\u984c 6",
"Block Style": "\u5ea7\u5f0f",
"Alignment": "\u5c0d\u9f4a",
"Align Left": "\u7f6e\u5de6\u5c0d\u9f4a",
"Align Center": "\u7f6e\u4e2d\u5c0d\u9f4a",
"Align Right": "\u7f6e\u53f3\u5c0d\u9f4a",
"Justify": "\u5de6\u53f3\u5c0d\u9f4a",
"Numbered List": "\u6578\u5b57\u6e05\u55ae",
"Bulleted List": "\u9805\u76ee\u6e05\u55ae",
"Indent Less": "\u6e1b\u5c11\u7e2e\u6392",
"Indent More": "\u589e\u52a0\u7e2e\u6392",
"Select All": "\u5168\u9078",
"Insert Link": "\u63d2\u5165\u9023\u7d50",
"Insert Image": "\u63d2\u5165\u5716\u7247",
"Insert Video": "\u63d2\u5165\u5f71\u97f3",
"Undo": "\u5fa9\u539f",
"Redo": "\u53d6\u6d88\u5fa9\u539f",
"Show HTML": "\u663e\u793a\u7684\u0048\u0054\u004d\u004c",
"Float Left": "\u5de6\u908a",
"Float None": "\u7121",
"Float Right": "\u53f3\u908a",
"Replace Image": "\u66f4\u6362\u56fe\u50cf",
"Remove Image": "\u5220\u9664\u56fe\u50cf",
"Title": "\u6a19\u984c",
"Drop image": "\u56fe\u50cf\u62d6\u653e",
"or click": "\u6216\u70b9\u51fb",
"or": "\u6216",
"Enter URL": "\u8f93\u5165\u7f51\u5740",
"Please wait!": "\u8bf7\u7a0d\u7b49\uff01",
"Are you sure? Image will be deleted.": "\u4f60\u786e\u5b9a\u5417\uff1f\u56fe\u50cf\u5c06\u88ab\u5220\u9664\u3002",
"UNLINK": "\u79fb\u9664\u9023\u7d50",
"Open in new tab": "\u5f00\u542f\u5728\u65b0\u6807\u7b7e\u9875",
"Type something": "\u8f93\u5165\u4e00\u4e9b\u5185\u5bb9",
"Cancel": "\u53d6\u6d88",
"OK": "\u78ba\u5b9a",
"Manage images": "\u7ba1\u7406\u5716\u50cf",
"Delete": "\u522a\u9664",
"Font Family": "\u5b57\u9ad4",
"Insert Horizontal Line": "\u63d2\u5165\u6c34\u5e73\u7dda",
"Table": "\u8868\u683c",
"Insert table": "\u63d2\u5165\u8868\u683c",
"Cell": "\u5355\u5143\u683c",
"Row": "\u884c",
"Column": "\u5217",
"Delete table": "\u5220\u9664\u8868\u683c",
"Insert cell before": "\u524d\u63d2\u5165\u55ae\u5143\u683c",
"Insert cell after": "\u5f8c\u63d2\u5165\u96fb\u6c60",
"Delete cell": "\u522a\u9664\u55ae\u5143\u683c",
"Merge cells": "\u5408\u4f75\u55ae\u5143\u683c",
"Horizontal split": "\u6c34\u5e73\u5206\u5272",
"Vertical split": "\u5782\u76f4\u5206\u5272",
"Insert row above": "\u5728\u4e0a\u65b9\u63d2\u5165",
"Insert row below": "\u5728\u4e0b\u65b9\u63d2\u5165",
"Delete row": "\u5220\u9664\u884c",
"Insert column before": "\u5728\u5de6\u4fa7\u63d2\u5165",
"Insert column after": "\u5728\u53f3\u4fa7\u63d2\u5165",
"Delete column": "\u5220\u9664\u5217",
"Uploading image": "\u4e0a\u50b3\u5716\u50cf",
"Upload File": "\u4e0a\u50b3\u6587\u4ef6",
"Drop File": "\u6587\u4ef6\u62d6\u653e",
"Clear formatting": "\u683c\u5f0f\u5316\u522a\u9664"
},
direction: "ltr"
};
|
exports.formatCoverage = function (n) {
var str = Math.floor(n * 10000)/100 + '%';
return str;
};
var symbols = {
ok: '',
warn: '⁍',
err: ''
};
// With node.js on Windows: use symbols available in terminal default fonts
if ('win32' === process.platform) {
symbols.ok = '\u221A';
symbols.warn = '\u204D';
symbols.err = '\u2731';
}
exports.getType = function (covlevel, coverage) {
var type;
var head;
if (coverage >= covlevel.high) {
type = 'GREEN';
head = symbols.ok;
} else if (coverage >= covlevel.middle) {
type = null;
head = symbols.ok;
} else if (coverage >= covlevel.low) {
type = 'YELLOW';
head = symbols.warn;
} else {
type = 'RED';
head = symbols.err;
}
return [type, head];
};
exports.colorful = function (str, type) {
if (!type) {
return str;
}
var head = '\x1B[', foot = '\x1B[0m';
var color = {
LINENUM : 36,
GREEN : 32,
YELLOW : 33,
RED : 31,
DEFAULT: 0
};
return head + color[type] + 'm' + str + foot;
};
|
Bulma is a **modern CSS framework** based on [Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/<API key>/<API key>).
[][npm-link]
[][npm-link]
[![Awesome][awesome-badge]][awesome-link]
[
You can either use that file, "out of the box", or download the Sass source files to customize the [variables](https://bulma.io/documentation/overview/variables/).
There is **no** JavaScript included. People generally want to use their own JS implementation (and usually already have one). Bulma can be considered "environment agnostic": it's just the style layer on top of the logic.
## Browser Support
Bulma uses [autoprefixer](https://github.com/postcss/autoprefixer) to make (most) Flexbox features compatible with earlier browser versions. According to [Can I use](https://caniuse.com/#feat=flexbox), Bulma is compatible with **recent** versions of:
* Chrome
* Edge
* Firefox
* Opera
* Safari
Internet Explorer (10+) is only partially supported.
## Documentation
The documentation resides in the [docs](docs) directory, and is built with the Ruby-based [Jekyll](https://jekyllrb.com/) tool.
Browse the [online documentation here.](https://bulma.io/documentation/overview/start/)
## Related projects
| Project | Description |
|
| [Bulma with Attribute Modules](https://github.com/j5bot/<API key>) | Adds support for attribute-based selectors |
| [Bulma with Rails](https://github.com/joshuajansen/bulma-rails) | Integrates Bulma with the rails asset pipeline |
| [Vue Admin](https://github.com/vue-bulma/vue-admin) | Vue Admin framework powered by Bulma |
| [Bulmaswatch](https://github.com/jenil/bulmaswatch) | Free themes for Bulma |
| [Goldfish](https://github.com/Caiyeon/goldfish) | Vault UI with Bulma, Golang, and Vue Admin |
| [ember-bulma](https://github.com/open-tux/ember-bulma) | Ember addon providing a collection of UI components for Bulma |
| [Bloomer](https://bloomer.js.org) | A set of React components for Bulma |
| [React-bulma](https://github.com/kulakowka/react-bulma) | React.js components for Bulma |
| [Buefy](https://buefy.github.io) | Lightweight UI components for Vue.js based on Bulma |
| [<API key>](https://github.com/vouill/<API key>) | Bulma components for Vue.js with straightforward syntax |
| [BulmaJS](https://github.com/VizuaaLOG/BulmaJS) | Javascript integration for Bulma. Written in ES6 with a data-* API |
| [Bulma-modal-fx](https://github.com/postare/bulma-modal-fx) | A set of modal window effects with CSS transitions and animations for Bulma |
| [Bulma.styl](https://github.com/log1x/bulma.styl) | 1:1 Stylus translation of Bulma |
| [elm-bulma](https://github.com/surprisetalk/elm-bulma) | Bulma + Elm |
| [elm-bulma-classes](https://github.com/ahstro/elm-bulma-classes) | Bulma classes prepared for usage with Elm |
| [Bulma Customizer](https://bulma-customizer.bstash.io/) | Bulma Customizer – Create your own **bespoke** Bulma build |
| [Fulma](https:
| [Laravel Enso](https://github.com/laravel-enso/enso) | SPA Admin Panel built with Bulma, VueJS and Laravel |
| [Django Bulma](https://github.com/timonweb/django-bulma) | Integrates Bulma with Django |
| [Bulma Templates](https://github.com/dansup/bulma-templates) | Free Templates for Bulma |
| [React Bulma Components](https://github.com/couds/<API key>) | Another React wrap on React for Bulma.io |
| [purescript-bulma](https://github.com/sectore/purescript-bulma) | PureScript bindings for Bulma |
| [Vue Datatable](https://github.com/laravel-enso/vuedatatable) | Bulma themed datatable based on Vue, Laravel & JSON templates |
| [bulma-fluent](https:
| [csskrt-csskrt](https://github.com/4d11/csskrt-csskrt) | Automatically add Bulma classes to HTML files |
| [<API key>](https://github.com/hipstersmoothie/<API key>) | Bulma pagination as a react component |
| [bulma-helpers](https://github.com/jmaczan/bulma-helpers) | Functional / Atomic CSS classes for Bulma |
| [bulma-swatch-hook](https://github.com/hipstersmoothie/bulma-swatch-hook) | Bulma swatches as a react hook and a component |
| [BulmaWP](https://github.com/tomhrtly/BulmaWP) | Starter WordPress theme for Bulma |
| [Ralma](https://github.com/aldi/ralma) | Stateless Ractive.js Components for Bulma |
| [Django Simple Bulma](https://github.com/python-discord/django-simple-bulma) | Lightweight integration of Bulma and Bulma-Extensions for your Django app |
| [rbx](https://dfee.github.io/rbx) | Comprehensive React UI Framework written in TypeScript |
| [Awesome Bulma Templates](https://github.com/aldi/<API key>) | Free real-world Templates built with Bulma |
| [Trunx](http://g14n.info/trunx) | Super Saiyan React components, son of awesome Bulma, implemented in TypeScript |
| [@aybolit/bulma](https://github.com/web-padawan/aybolit/tree/master/packages/bulma) | Web Components library inspired by Bulma and Bulma-extensions |
| [Drulma](https:
| [Bulrush](https://github.com/textbook/bulrush) | A Bulma-based Python Pelican blog theme |
Code copyright 2019 Jeremy Thomas. Code released under [the MIT license](https:
[npm-link]: https:
[awesome-link]: https://github.com/awesome-css-group/awesome-css
[awesome-badge]: https://cdn.rawgit.com/sindresorhus/awesome/<SHA1-like>/media/badge.svg
|
// CppNumericalSolver
#ifndef <API key>
#define <API key>
#include <Eigen/Core>
#include "isolver.h"
#include "../linesearch/morethuente.h"
namespace cppoptlib {
template<typename ProblemType>
class <API key> : public ISolver<ProblemType, 1> {
public:
using Superclass = ISolver<ProblemType, 1>;
using typename Superclass::Scalar;
using typename Superclass::TVector;
/**
* @brief minimize
* @details [long description]
*
* @param objFunc [description]
*/
void minimize(ProblemType &objFunc, TVector &x0) {
TVector direction(x0.rows());
this->m_current.reset();
do {
;
objFunc.gradient(x0, direction);
const Scalar rate = MoreThuente<ProblemType, 1>::linesearch(x0, -direction, objFunc) ;
x0 = x0 - rate * direction;
this->m_current.gradNorm = direction.template lpNorm<Eigen::Infinity>();
// std::cout << "iter: "<<iter<< " f = " << objFunc.value(x0) << " ||g||_inf "<<gradNorm << std::endl;
++this->m_current.iterations;
this->m_status = checkConvergence(this->m_stop, this->m_current);
} while (objFunc.callback(this->m_current, x0) && (this->m_status == Status::Continue));
if (this->m_debug > DebugLevel::None) {
std::cout << "Stop status was: " << this->m_status << std::endl;
std::cout << "Stop criteria were: " << std::endl << this->m_stop << std::endl;
std::cout << "Current values are: " << std::endl << this->m_current << std::endl;
}
}
};
} /* namespace cppoptlib */
#endif /* <API key> */
|
$(document).ready(function(){$(".dropdown-toggle").dropdown()});
|
<API key> @'
string1=string1 for en-US
string2=string2 for en-US
'@ # SIG # Begin signature block
|
require File.dirname(__FILE__) + '/support/setup'
# A background job to update all child models with the correct access level
# of the parent document, and update all assets on S3.
class UpdateAccess < CloudCrowd::Action
def process
begin
ActiveRecord::Base.<API key>
access = options['access']
document = Document.find(input)
[Page, Entity, EntityDate].each{ |model_klass| model_klass.where(:document_id => document.id).update_all(:access=>access) }
begin
DC::Store::AssetStore.new.set_access(document, access)
rescue AWS::S3::Errors::NoSuchKey
# Quite a few docs are missing text assets
# Even though they are incomplete, They should still
# be able to have their access manipulated
end
document.update_attributes(:access => access)
rescue Exception => e
LifecycleMailer.<API key>(e,options).deliver_now
document.update_attributes(:access => DC::Access::ERROR) if document
raise e
end
true
end
end
|
const isIntersecting = (a, b) =>
!(a.x >= (b.x + b.width) ||
(a.x + a.width) <= b.x ||
a.y >= (b.y + b.height) ||
(a.y + a.height) <= b.y);
export default (a, b) => {
if (isIntersecting(a, b)) {
const left = Math.max(a.x, b.x);
const right = Math.min(a.x + a.width, b.x + b.width);
const top = Math.max(a.y, b.y);
const bottom = Math.min(a.y + a.height, b.y + b.height);
return (right - left) * (bottom - top);
} else {
return 0;
}
};
|
// Because I don't want two files, we're going to fork ourselves.
var fakeProcess = new (require('./fake-process').FakeProcess)();
//if (!process.send) {
// This is the parent
var guid = 1;
var callbacks = {};
var callbackData = {};
//var child = require('child_process').fork('verifier.js');
exports.verify = function (data, signature, callback) {
var localGuid = guid++;
callbacks[localGuid] = callback;
callbackData[localGuid] = data;
fakeProcess.server.send({data: data, sig: signature, guid: localGuid});
};
fakeProcess.server.on('message', function (response) {
if (callbacks[response.guid]) {
callbacks[response.guid](response.success, callbackData[response.guid]);
delete callbacks[response.guid];
delete callbackData[response.guid];
}
});
//} else {
// This is the child
global.Config = require('./config/config.js');
var crypto = require('crypto');
var keyalgo = Config.loginServer.keyAlgorithm;
var pkey = Config.loginServer.publicKey;
fakeProcess.client.on('message', function (message) {
var verifier = crypto.createVerify(keyalgo);
verifier.update(message.data);
var success = false;
try {
success = verifier.verify(pkey, message.sig, 'hex');
} catch (e) {}
fakeProcess.client.send({
success: success,
guid: message.guid
});
});
|
class Gws::Qna::Category
include Gws::Model::Category
include Gws::Referenceable
include Gws::Reference::User
include Gws::Reference::Site
include Gws::Addon::SubscriptionSetting
include Gws::Addon::ReadableSetting
include Gws::Addon::GroupPermission
include Gws::Addon::History
default_scope ->{ where(model: "gws/qna/category").order_by(name: 1) }
validate :validate_name_depth
validate :<API key>
before_destroy :validate_children
class << self
def and_name_prefix(name_prefix)
name_prefix = name_prefix[1..-1] if name_prefix.starts_with?('/')
self.or({ name: name_prefix }, { name: /^#{::Regexp.escape(name_prefix)}\// })
end
end
private
def color_required?
false
end
def default_color
nil
end
def validate_name_depth
return if name.blank?
errors.add :name, :too_deep, max: 2 if name.count('/') >= 2
end
def <API key>
return if name.blank?
return if name.count('/') < 1
errors.add :base, :not_found_parent unless self.class.where(name: File.dirname(name)).exists?
end
def validate_children
if name.present? && self.class.where(name: /^#{::Regexp.escape(name)}\//).exists?
errors.add :base, :found_children
return false
end
true
end
end
|
/*global defineSuite*/
defineSuite([
'DataSources/<API key>',
'Core/Cartesian3',
'Core/ExtrapolationType',
'Core/JulianDate',
'Core/<API key>',
'Core/LinearApproximation',
'Core/ReferenceFrame',
'DataSources/PositionProperty'
], function(
<API key>,
Cartesian3,
ExtrapolationType,
JulianDate,
<API key>,
LinearApproximation,
ReferenceFrame,
PositionProperty) {
'use strict';
it('constructor sets expected defaults', function() {
var property = new <API key>();
expect(property.referenceFrame).toEqual(ReferenceFrame.FIXED);
expect(property.interpolationDegree).toEqual(1);
expect(property.<API key>).toEqual(LinearApproximation);
expect(property.numberOfDerivatives).toEqual(0);
expect(property.<API key>).toEqual(ExtrapolationType.NONE);
expect(property.<API key>).toEqual(0);
expect(property.<API key>).toEqual(ExtrapolationType.NONE);
expect(property.<API key>).toEqual(0);
});
it('constructor sets expected values', function() {
var property = new <API key>(ReferenceFrame.INERTIAL, 1);
expect(property.referenceFrame).toEqual(ReferenceFrame.INERTIAL);
expect(property.interpolationDegree).toEqual(1);
expect(property.<API key>).toEqual(LinearApproximation);
expect(property.numberOfDerivatives).toEqual(1);
expect(property.<API key>).toEqual(ExtrapolationType.NONE);
expect(property.<API key>).toEqual(0);
expect(property.<API key>).toEqual(ExtrapolationType.NONE);
expect(property.<API key>).toEqual(0);
});
it('getValue works without a result parameter', function() {
var time = JulianDate.now();
var value = new Cartesian3(1, 2, 3);
var property = new <API key>();
property.addSample(time, value);
var result = property.getValue(time);
expect(result).not.toBe(value);
expect(result).toEqual(value);
});
it('getValue works with a result parameter', function() {
var time = JulianDate.now();
var value = new Cartesian3(1, 2, 3);
var property = new <API key>();
property.addSample(time, value);
var expected = new Cartesian3();
var result = property.getValue(time, expected);
expect(result).toBe(expected);
expect(expected).toEqual(value);
});
it('getValue returns in fixed frame', function() {
var time = JulianDate.now();
var valueInertial = new Cartesian3(1, 2, 3);
var valueFixed = PositionProperty.<API key>(time, valueInertial, ReferenceFrame.INERTIAL, ReferenceFrame.FIXED);
var property = new <API key>(ReferenceFrame.INERTIAL);
property.addSample(time, valueInertial);
var result = property.getValue(time);
expect(result).toEqual(valueFixed);
});
it('<API key> works without a result parameter', function() {
var time = JulianDate.now();
var value = new Cartesian3(1, 2, 3);
var property = new <API key>();
property.addSample(time, value);
var result = property.<API key>(time, ReferenceFrame.INERTIAL);
expect(result).not.toBe(value);
expect(result).toEqual(PositionProperty.<API key>(time, value, ReferenceFrame.FIXED, ReferenceFrame.INERTIAL));
});
it('<API key> works with a result parameter', function() {
var time = JulianDate.now();
var value = new Cartesian3(1, 2, 3);
var property = new <API key>(ReferenceFrame.INERTIAL);
property.addSample(time, value);
var expected = new Cartesian3();
var result = property.<API key>(time, ReferenceFrame.FIXED, expected);
expect(result).toBe(expected);
expect(expected).toEqual(PositionProperty.<API key>(time, value, ReferenceFrame.INERTIAL, ReferenceFrame.FIXED));
});
it('<API key> works', function() {
var data = [0, 7, 8, 9, 1, 8, 9, 10, 2, 9, 10, 11];
var epoch = new JulianDate(0, 0);
var property = new <API key>();
property.<API key>(data, epoch);
expect(property.getValue(epoch)).toEqual(new Cartesian3(7, 8, 9));
expect(property.getValue(new JulianDate(0, 0.5))).toEqual(new Cartesian3(7.5, 8.5, 9.5));
});
it('addSample works', function() {
var values = [new Cartesian3(7, 8, 9), new Cartesian3(8, 9, 10), new Cartesian3(9, 10, 11)];
var times = [new JulianDate(0, 0), new JulianDate(1, 0), new JulianDate(2, 0)];
var property = new <API key>();
property.addSample(times[0], values[0]);
property.addSample(times[1], values[1]);
property.addSample(times[2], values[2]);
expect(property.getValue(times[0])).toEqual(values[0]);
expect(property.getValue(times[1])).toEqual(values[1]);
expect(property.getValue(times[2])).toEqual(values[2]);
expect(property.getValue(new JulianDate(0.5, 0))).toEqual(new Cartesian3(7.5, 8.5, 9.5));
});
it('addSamples works', function() {
var values = [new Cartesian3(7, 8, 9), new Cartesian3(8, 9, 10), new Cartesian3(9, 10, 11)];
var times = [new JulianDate(0, 0), new JulianDate(1, 0), new JulianDate(2, 0)];
var property = new <API key>();
property.addSamples(times, values);
expect(property.getValue(times[0])).toEqual(values[0]);
expect(property.getValue(times[1])).toEqual(values[1]);
expect(property.getValue(times[2])).toEqual(values[2]);
expect(property.getValue(new JulianDate(0.5, 0))).toEqual(new Cartesian3(7.5, 8.5, 9.5));
});
it('<API key> works with derivatives', function() {
var data = [0, 7, 8, 9, 1, 0, 0, 1, 8, 9, 10, 0, 1, 0, 2, 9, 10, 11, 0, 0, 1];
var epoch = new JulianDate(0, 0);
var property = new <API key>(ReferenceFrame.FIXED, 1);
property.<API key>(data, epoch);
expect(property.getValue(epoch)).toEqual(new Cartesian3(7, 8, 9));
expect(property.getValue(new JulianDate(0, 0.5))).toEqual(new Cartesian3(7.5, 8.5, 9.5));
});
it('addSample works with derivatives', function() {
var times = [new JulianDate(0, 0), new JulianDate(1, 0), new JulianDate(2, 0)];
var positions = [new Cartesian3(7, 8, 9), new Cartesian3(8, 9, 10), new Cartesian3(9, 10, 11)];
var velocities = [[new Cartesian3(0, 0, 1)], [new Cartesian3(0, 1, 0)], [new Cartesian3(1, 0, 0)]];
var property = new <API key>(ReferenceFrame.FIXED, 1);
property.addSample(times[0], positions[0], velocities[0]);
property.addSample(times[1], positions[1], velocities[1]);
property.addSample(times[2], positions[2], velocities[2]);
expect(property.getValue(times[0])).toEqual(positions[0]);
expect(property.getValue(times[1])).toEqual(positions[1]);
expect(property.getValue(times[2])).toEqual(positions[2]);
expect(property.getValue(new JulianDate(0.5, 0))).toEqual(new Cartesian3(7.5, 8.5, 9.5));
});
it('addSamples works with derivatives', function() {
var times = [new JulianDate(0, 0), new JulianDate(1, 0), new JulianDate(2, 0)];
var positions = [new Cartesian3(7, 8, 9), new Cartesian3(8, 9, 10), new Cartesian3(9, 10, 11)];
var velocities = [[new Cartesian3(0, 0, 1)], [new Cartesian3(0, 1, 0)], [new Cartesian3(1, 0, 0)]];
var property = new <API key>(ReferenceFrame.FIXED, 1);
property.addSamples(times, positions, velocities);
expect(property.getValue(times[0])).toEqual(positions[0]);
expect(property.getValue(times[1])).toEqual(positions[1]);
expect(property.getValue(times[2])).toEqual(positions[2]);
expect(property.getValue(new JulianDate(0.5, 0))).toEqual(new Cartesian3(7.5, 8.5, 9.5));
});
it('addSample throws when derivative is undefined but expected', function() {
var property = new <API key>(ReferenceFrame.FIXED, 1);
expect(function() {
property.addSample(new JulianDate(0, 0), new Cartesian3(7, 8, 9), undefined);
}).<API key>();
});
it('addSamples throws when derivative is undefined but expected', function() {
var times = [new JulianDate(0, 0), new JulianDate(1, 0), new JulianDate(2, 0)];
var positions = [new Cartesian3(7, 8, 9), new Cartesian3(8, 9, 10), new Cartesian3(9, 10, 11)];
var property = new <API key>(ReferenceFrame.FIXED, 1);
expect(function() {
property.addSamples(times, positions, undefined);
}).<API key>();
});
it('addSamples throws when derivative is not the correct length', function() {
var times = [new JulianDate(0, 0), new JulianDate(1, 0), new JulianDate(2, 0)];
var positions = [new Cartesian3(7, 8, 9), new Cartesian3(8, 9, 10), new Cartesian3(9, 10, 11)];
var velocities = [[new Cartesian3(7, 8, 9)], [new Cartesian3(8, 9, 10)]];
var property = new <API key>(ReferenceFrame.FIXED, 1);
expect(function() {
property.addSamples(times, positions, velocities);
}).<API key>();
});
it('can set <API key> and degree', function() {
var data = [0, 7, 8, 9, 1, 8, 9, 10, 2, 9, 10, 11];
var epoch = new JulianDate(0, 0);
var timesCalled = 0;
var MockInterpolation = {
type : 'Mock',
<API key> : function(degree) {
return 3;
},
<API key> : function(x, xTable, yTable, yStride, result) {
expect(x).toEqual(1);
expect(xTable.length).toEqual(3);
expect(xTable[0]).toBe(-2);
expect(xTable[1]).toBe(-1);
expect(xTable[2]).toBe(0);
expect(yTable.length).toEqual(9);
expect(yTable[0]).toBe(7);
expect(yTable[1]).toBe(8);
expect(yTable[2]).toBe(9);
expect(yTable[3]).toBe(8);
expect(yTable[4]).toBe(9);
expect(yTable[5]).toBe(10);
expect(yTable[6]).toBe(9);
expect(yTable[7]).toBe(10);
expect(yTable[8]).toBe(11);
expect(yStride).toEqual(3);
expect(result.length).toEqual(3);
result[0] = 2;
result[1] = 3;
result[2] = 4;
timesCalled++;
return result;
}
};
var property = new <API key>();
property.<API key> = ExtrapolationType.EXTRAPOLATE;
property.<API key>(data, epoch);
property.<API key>({
interpolationDegree : 2,
<API key> : MockInterpolation
});
expect(property.getValue(epoch)).toEqual(new Cartesian3(7, 8, 9));
expect(property.getValue(new JulianDate(0, 3))).toEqual(new Cartesian3(2, 3, 4));
expect(timesCalled).toEqual(1);
});
it('Returns undefined if trying to interpolate with less than enough samples.', function() {
var value = new Cartesian3(1, 2, 3);
var time = new JulianDate(0, 0);
var property = new <API key>();
property.addSample(time, value);
expect(property.getValue(time)).toEqual(value);
expect(property.getValue(JulianDate.addSeconds(time, 4, new JulianDate()))).toBeUndefined();
});
it('throws with no time parameter', function() {
var property = new <API key>();
expect(function() {
property.getValue(undefined);
}).<API key>();
});
it('throws with no reference frame parameter', function() {
var property = new <API key>();
var time = JulianDate.now();
expect(function() {
property.<API key>(time, undefined);
}).<API key>();
});
it('equals works when interpolators differ', function() {
var left = new <API key>();
var right = new <API key>();
expect(left.equals(right)).toEqual(true);
right.<API key>({
<API key> : <API key>
});
expect(left.equals(right)).toEqual(false);
});
it('equals works when interpolator degree differ', function() {
var left = new <API key>();
left.<API key>({
interpolationDegree : 2,
<API key> : <API key>
});
var right = new <API key>();
right.<API key>({
interpolationDegree : 2,
<API key> : <API key>
});
expect(left.equals(right)).toEqual(true);
right.<API key>({
interpolationDegree : 3,
<API key> : <API key>
});
expect(left.equals(right)).toEqual(false);
});
it('equals works when reference frames differ', function() {
var left = new <API key>(ReferenceFrame.FIXED);
var right = new <API key>(ReferenceFrame.INERTIAL);
expect(left.equals(right)).toEqual(false);
});
it('equals works when samples differ', function() {
var left = new <API key>();
var right = new <API key>();
expect(left.equals(right)).toEqual(true);
var time = JulianDate.now();
var value = new Cartesian3(1, 2, 3);
left.addSample(time, value);
expect(left.equals(right)).toEqual(false);
right.addSample(time, value);
expect(left.equals(right)).toEqual(true);
});
it('raises definitionChanged when extrapolation options change', function() {
var property = new <API key>();
var listener = jasmine.createSpy('listener');
property.definitionChanged.addEventListener(listener);
property.<API key> = ExtrapolationType.EXTRAPOLATE;
expect(listener).<API key>(property);
listener.calls.reset();
property.<API key> = 1.0;
expect(listener).<API key>(property);
listener.calls.reset();
property.<API key> = ExtrapolationType.HOLD;
expect(listener).<API key>(property);
listener.calls.reset();
property.<API key> = 1.0;
expect(listener).<API key>(property);
listener.calls.reset();
//No events when reassigning to the same value.
property.<API key> = ExtrapolationType.EXTRAPOLATE;
expect(listener).not.toHaveBeenCalled();
property.<API key> = 1.0;
expect(listener).not.toHaveBeenCalled();
property.<API key> = ExtrapolationType.HOLD;
expect(listener).not.toHaveBeenCalled();
property.<API key> = 1.0;
expect(listener).not.toHaveBeenCalled();
});
});
|
var util = require('util');
var events = require('events');
var Q = require('q');
var Nightwatch = require('../../index.js');
function ClientManager() {
events.EventEmitter.call(this);
this.setMaxListeners(0);
}
util.inherits(ClientManager, events.EventEmitter);
ClientManager.prototype.init = function(opts) {
try {
this['@client'] = Nightwatch.client(opts);
} catch (err) {
console.log(err.stack);
this.emit('error', err, false);
return;
}
var self = this;
this.options = opts;
this['@client'].once('selenium:session_create', function() {
self.options.report_prefix = this.api.capabilities.browserName.toUpperCase() +
'_' + this.api.capabilities.version +
'_' + this.api.capabilities.platform + '_';
});
};
ClientManager.prototype.start = function() {
var self = this;
this['@client'].once('nightwatch:finished', function(results, errors) {
self.emit('complete', results, errors);
});
this['@client'].once('error', function(data, error) {
var result = {message: '\nConnection refused! Is selenium server started?\n', data : error};
self.emit('error', result, false);
});
this['@client'].start();
return this;
};
ClientManager.prototype.get = function() {
return this['@client'];
};
ClientManager.prototype.set = function(prop, value) {
this['@client'][prop] = value;
return this;
};
ClientManager.prototype.publishTestResults = function(testcase, results, errors) {
if (!this['@client'].api.currentTest) {
return this;
}
var currentTestSuite = this['@client'].api.currentTest.results;
currentTestSuite.passed += results.passed;
currentTestSuite.failed += results.failed;
currentTestSuite.errors += results.errors;
currentTestSuite.skipped += results.skipped;
currentTestSuite.tests += results.tests.length;
currentTestSuite.testcases = currentTestSuite.testcases || {};
currentTestSuite.testcases[testcase] = {
passed : results.passed,
failed : results.failed,
errors : results.errors,
skipped : results.skipped,
tests : results.tests.length,
assertions : results.tests
};
return this;
};
ClientManager.prototype.results = function(type, value) {
if (typeof value == 'undefined') {
return this['@client'].results[type] || 0;
}
this['@client'].results[type] = value;
return this;
};
ClientManager.prototype.clearResult = function() {
return this['@client'].clearResult();
};
ClientManager.prototype.terminated = function() {
return this['@client'].terminated;
};
ClientManager.prototype.print = function(startTime) {
return this['@client'].printResult(startTime);
};
ClientManager.prototype.api = function(key, value) {
if (key && (typeof value != 'undefined')) {
this['@client'].api[key] = value;
}
return this['@client'].api;
};
ClientManager.prototype.restartQueue = function(onComplete) {
this['@client'].queue.reset();
this['@client'].queue.run(onComplete);
};
ClientManager.prototype.shouldRestartQueue = function() {
return this['@client'] && this['@client'].queue.list().length;
};
ClientManager.prototype.checkQueue = function() {
var deferred = Q.defer();
if (this.shouldRestartQueue()) {
this.restartQueue(function() {
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise;
};
ClientManager.prototype.endSessionOnFail = function(value) {
if (typeof value == 'undefined') {
return this['@client'].endSessionOnFail();
}
this['@client'].endSessionOnFail(value);
return this;
};
module.exports = ClientManager;
|
/*globals define, angular, alert*/
define([
'angular',
'text!./templates/propertyValue.html',
'css!./styles/propertyValue.css',
'./valueWidgets'
], function (ng, defaultTemplate) {
'use strict';
angular.module(
'isis.ui.propertyValue', [
'isis.ui.valueWidgets'
]
)
.directive(
'propertyValue', ['$log', '$compile', '$valueWidgets',
function ($log, $compile) {
return {
restrict: 'E',
replace: true,
template: defaultTemplate,
scope: false
};
}
]);
});
|
import{<API key>}from"./<API key>";import{useOptionalFactory}from"../useOptionalFactory";import{<API key>}from"./<API key>";import{<API key>}from"./<API key>";import{useCollectedProps}from"../useCollectedProps";import{<API key>}from"./connectors";function useDrop(o,r){var e=useOptionalFactory(o,r),o=<API key>(),r=<API key>(e.options);return <API key>(e,o,r),[useCollectedProps(e.collect,o,r),<API key>(r)]}export{useDrop};
|
package org.openhab.binding.hue.internal.hardware;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.openhab.binding.hue.internal.data.HueSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.<API key>;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
/**
* Represents a physical Hue bridge and grants access to data the bridge
* contains.
*
* @author Roman Hartmann
* @author Kai Kreuzer
* @since 1.2.0
*
*/
public class HueBridge {
private static final Logger logger = LoggerFactory.getLogger(HueBridge.class);
private final String ip;
private final String secret;
private Client client;
private static final int <API key> = 5;
/**
* Constructor for the HueBridge.
*
* @param ip
* The IP of the Hue bridge.
* @param secret
* A unique identifier, that is used as a kind of password. This
* password is registered at the Hue bridge while connecting to
* it the first time. To do this initial connect the connect
* button the the Hue bridge as to be pressed.
*/
public HueBridge(String ip, String secret) {
this.ip = ip;
this.secret = secret;
client = Client.create();
client.setConnectTimeout(5000);
}
/**
* Pings the bridge for an initial connect. This pinging will take place for 100 seconds.
* In this time the connect button on the Hue bridge has to be pressed to enable the pairing.
*/
public void pairBridge() {
Thread pairingThread = new Thread(new <API key>());
pairingThread.start();
}
/**
* Checks if the configured secret/user is authorized on the hue bridge.
*/
public boolean isAuthorized() {
boolean isAuthorized = false;
if (!StringUtils.isBlank(secret)) {
HueSettings settings = getSettings();
isAuthorized = (settings != null && settings.isAuthorized());
}
return isAuthorized;
}
/**
* Requests the settings of the Hue bridge that also contains the settings
* of all connected Hue devices.
*
* @return The settings determined from the bridge. Null if they could not
* be requested.
*/
public HueSettings getSettings() {
String json = getSettingsJson();
return json != null ? new HueSettings(json) : null;
}
/**
* Pings the Hue bridge for 100 seconds to establish a first pairing
* connection to the bridge. This requires the button on the Hue bridge to
* be pressed.
*
*/
private void pingForPairing() {
int countdownInSeconds = 100;
boolean isPaired = false;
while (countdownInSeconds > 0 && !isPaired) {
logger.info("Please press the connect button on the Hue bridge. Waiting for pairing for "
+ countdownInSeconds + " seconds...");
WebResource webResource = client.resource("http://" + ip + "/api");
String input = "{\"devicetype\":\"openHAB_binding\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 200) {
logger.error("Failed to connect to Hue bridge with IP '" + ip + "': HTTP error code: "
+ response.getStatus());
return;
}
String output = response.getEntity(String.class);
logger.debug("Received pairing response: {}", output);
isPaired = <API key>(output);
if (!isPaired) {
try {
Thread.sleep(<API key> * 1000);
countdownInSeconds -= <API key>;
} catch (<API key> e) {
}
}
}
}
private boolean <API key>(String response) {
try {
JsonNode node = convertToJsonNode(response);
if (node.has("success")) {
String userName = node.path("success").path("username").getTextValue();
logger.info("
logger.info("# Hue bridge successfully paired!");
logger.info("# Please set the following secret in your openhab.cfg (and restart openHAB):");
logger.info("# " + userName);
logger.info("
return true;
}
} catch (IOException e) {
logger.error("Could not read Settings-Json from Hue Bridge.", e);
}
return false;
}
private JsonNode convertToJsonNode(String response) throws IOException {
JsonNode rootNode;
ObjectMapper mapper = new ObjectMapper();
JsonNode arrayWrappedNode = mapper.readTree(response);
// Hue bridge returns the complete JSON response wrapped in an array, therefore the first
// element of the array has to be extracted
if (arrayWrappedNode.has(0)) {
rootNode = arrayWrappedNode.get(0);
} else {
throw new IOException("Unexpected response from hue bridge (not an array)");
}
return rootNode;
}
/**
* Determines the settings of the Hue bridge as a Json raw data String.
*
* @return The settings of the bridge if they could be determined. Null
* otherwise.
*/
private String getSettingsJson() {
WebResource webResource = client.resource(getUrl());
try {
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
String settingsString = response.getEntity(String.class);
if (response.getStatus() != 200) {
logger.warn("Failed to connect to Hue bridge: HTTP error code: " + response.getStatus());
return null;
}
logger.trace("Received Hue Bridge Settings: {}", settingsString);
return settingsString;
} catch (<API key> e) {
logger.warn("Failed to connect to Hue bridge: HTTP request timed out.");
return null;
}
}
/**
* @return The IP of the Hue bridge.
*/
public String getUrl() {
return "http://" + ip + "/api/" + secret + "/";
}
/**
* Thread to ping the Hue bridge for pairing.
*
*/
class <API key> implements Runnable {
@Override
public void run() {
pingForPairing();
}
}
}
|
Clazz.declarePackage ("org.eclipse.osgi.framework.adaptor");
c$ = Clazz.declareInterface (org.eclipse.osgi.framework.adaptor, "BundleData");
Clazz.defineStatics (c$,
"TYPE_FRAGMENT", 0x00000001,
"<API key>", 0x00000002,
"<API key>", 0x00000004,
"TYPE_SINGLETON", 0x00000008);
|
Clazz.declarePackage ("org.eclipse.jface.preference");
Clazz.load (null, "org.eclipse.jface.preference.ColorSelector", ["org.eclipse.jface.resource.JFaceResources", "org.eclipse.jface.util.ListenerList", "$.PropertyChangeEvent", "$wt.accessibility.AccessibleAdapter", "$wt.events.DisposeListener", "$.SelectionAdapter", "$wt.graphics.Color", "$.GC", "$.Image", "$.Point", "$wt.widgets.Button", "$.ColorDialog"], function () {
c$ = Clazz.decorateAsClass (function () {
this.fButton = null;
this.fColor = null;
this.fColorValue = null;
this.fExtent = null;
this.fImage = null;
this.listeners = null;
Clazz.instantialize (this, arguments);
}, org.eclipse.jface.preference, "ColorSelector");
Clazz.makeConstructor (c$,
function (parent) {
this.listeners = new org.eclipse.jface.util.ListenerList ();
this.fButton = new $wt.widgets.Button (parent, 8);
this.fExtent = this.computeImageSize (parent);
this.fImage = new $wt.graphics.Image (parent.getDisplay (), this.fExtent.x, this.fExtent.y);
var gc = new $wt.graphics.GC (this.fImage);
gc.setBackground (this.fButton.getBackground ());
gc.fillRectangle (0, 0, this.fExtent.x, this.fExtent.y);
gc.dispose ();
this.fButton.setImage (this.fImage);
this.fButton.<API key> (((Clazz.isClassDefined ("org.eclipse.jface.preference.ColorSelector$1") ? 0 : org.eclipse.jface.preference.ColorSelector.$ColorSelector$1$ ()), Clazz.innerTypeInstance (org.eclipse.jface.preference.ColorSelector$1, this, null)));
this.fButton.addDisposeListener (((Clazz.isClassDefined ("org.eclipse.jface.preference.ColorSelector$2") ? 0 : org.eclipse.jface.preference.ColorSelector.$ColorSelector$2$ ()), Clazz.innerTypeInstance (org.eclipse.jface.preference.ColorSelector$2, this, null)));
this.fButton.getAccessible ().<API key> (((Clazz.isClassDefined ("org.eclipse.jface.preference.ColorSelector$3") ? 0 : org.eclipse.jface.preference.ColorSelector.$ColorSelector$3$ ()), Clazz.innerTypeInstance (org.eclipse.jface.preference.ColorSelector$3, this, null)));
}, "$wt.widgets.Composite");
Clazz.defineMethod (c$, "addListener",
function (listener) {
this.listeners.add (listener);
}, "org.eclipse.jface.util.<API key>");
Clazz.defineMethod (c$, "computeImageSize",
($fz = function (window) {
var gc = new $wt.graphics.GC (window);
var f = org.eclipse.jface.resource.JFaceResources.getFontRegistry ().get ("org.eclipse.jface.defaultfont");
gc.setFont (f);
var height = gc.getFontMetrics ().getHeight ();
gc.dispose ();
var p = new $wt.graphics.Point (height * 3 - 6, height);
return p;
}, $fz.isPrivate = true, $fz), "$wt.widgets.Control");
Clazz.defineMethod (c$, "getButton",
function () {
return this.fButton;
});
Clazz.defineMethod (c$, "getColorValue",
function () {
return this.fColorValue;
});
Clazz.defineMethod (c$, "removeListener",
function (listener) {
this.listeners.remove (listener);
}, "org.eclipse.jface.util.<API key>");
Clazz.defineMethod (c$, "setColorValue",
function (rgb) {
this.fColorValue = rgb;
this.updateColorImage ();
}, "$wt.graphics.RGB");
Clazz.defineMethod (c$, "setEnabled",
function (state) {
this.getButton ().setEnabled (state);
}, "~B");
Clazz.defineMethod (c$, "updateColorImage",
function () {
var display = this.fButton.getDisplay ();
var gc = new $wt.graphics.GC (this.fImage);
gc.setForeground (display.getSystemColor (2));
gc.drawRectangle (0, 2, this.fExtent.x - 1, this.fExtent.y - 4);
if (this.fColor != null) this.fColor.dispose ();
this.fColor = new $wt.graphics.Color (display, this.fColorValue);
gc.setBackground (this.fColor);
gc.fillRectangle (1, 3, this.fExtent.x - 2, this.fExtent.y - 5);
gc.dispose ();
this.fButton.setImage (this.fImage);
});
c$.$ColorSelector$1$ = function () {
Clazz.pu$h ();
c$ = Clazz.declareAnonymous (org.eclipse.jface.preference, "ColorSelector$1", $wt.events.SelectionAdapter);
Clazz.overrideMethod (c$, "widgetSelected",
function (event) {
var colorDialog = new $wt.widgets.ColorDialog (this.b$["org.eclipse.jface.preference.ColorSelector"].fButton.getShell ());
colorDialog.setRGB (this.b$["org.eclipse.jface.preference.ColorSelector"].fColorValue);
DialogSync2Async.block (colorDialog, this, function () {
var newColor = colorDialog.dialogReturn;
if (newColor != null) {
var oldValue = this.b$["org.eclipse.jface.preference.ColorSelector"].fColorValue;
this.b$["org.eclipse.jface.preference.ColorSelector"].fColorValue = newColor;
var finalListeners = this.b$["org.eclipse.jface.preference.ColorSelector"].listeners.getListeners ();
if (finalListeners.length > 0) {
var pEvent = new org.eclipse.jface.util.PropertyChangeEvent (this, "colorValue", oldValue, newColor);
for (var i = 0; i < finalListeners.length; ++i) {
var listener = finalListeners[i];
listener.propertyChange (pEvent);
}
}this.b$["org.eclipse.jface.preference.ColorSelector"].updateColorImage ();
}});
return;
}, "$wt.events.SelectionEvent");
c$ = Clazz.p0p ();
};
c$.$ColorSelector$2$ = function () {
Clazz.pu$h ();
c$ = Clazz.declareAnonymous (org.eclipse.jface.preference, "ColorSelector$2", null, $wt.events.DisposeListener);
Clazz.overrideMethod (c$, "widgetDisposed",
function (event) {
if (this.b$["org.eclipse.jface.preference.ColorSelector"].fImage != null) {
this.b$["org.eclipse.jface.preference.ColorSelector"].fImage.dispose ();
this.b$["org.eclipse.jface.preference.ColorSelector"].fImage = null;
}if (this.b$["org.eclipse.jface.preference.ColorSelector"].fColor != null) {
this.b$["org.eclipse.jface.preference.ColorSelector"].fColor.dispose ();
this.b$["org.eclipse.jface.preference.ColorSelector"].fColor = null;
}}, "$wt.events.DisposeEvent");
c$ = Clazz.p0p ();
};
c$.$ColorSelector$3$ = function () {
Clazz.pu$h ();
c$ = Clazz.declareAnonymous (org.eclipse.jface.preference, "ColorSelector$3", $wt.accessibility.AccessibleAdapter);
Clazz.overrideMethod (c$, "getName",
function (e) {
e.result = org.eclipse.jface.resource.JFaceResources.getString ("ColorSelector.Name");
}, "$wt.accessibility.AccessibleEvent");
c$ = Clazz.p0p ();
};
Clazz.defineStatics (c$,
"PROP_COLORCHANGE", "colorValue");
});
|
#ifndef CANON_HOST_H
# define CANON_HOST_H 1
char *canon_host (char const *host);
char *canon_host_r (char const *host, int *cherror);
const char *ch_strerror (void);
# define ch_strerror_r(cherror) gai_strerror (cherror);
#endif /* !CANON_HOST_H */
|
<!DOCTYPE html PUBLIC "-
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_s">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_s')">s</a>
<div class="SRChildren">
<a id="Item0_c0" onkeydown="return searchResults.NavChild(event,0,0)" onkeypress="return searchResults.NavChild(event,0,0)" onkeyup="return searchResults.NavChild(event,0,0)" class="SRScope" doxygen="IWAVEBASE.tag:../../../../base/doc/html/" href="../../../../base/doc/html/<API key>.html#<API key>" target="_parent">s_SIZEDSTRING::s()</a>
<a id="Item0_c1" onkeydown="return searchResults.NavChild(event,0,1)" onkeypress="return searchResults.NavChild(event,0,1)" onkeyup="return searchResults.NavChild(event,0,1)" class="SRScope" href="../structSTENCIL__MASK.html#<API key>" target="_parent">STENCIL_MASK::s()</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_s_5ffield">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../structs__field.html" target="_parent">s_field</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fiokeys">
<div class="SREntry">
<a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../structs__iokeys.html" target="_parent">s_iokeys</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fiwave">
<div class="SREntry">
<a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../structs__IWAVE.html" target="_parent">s_IWAVE</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fkeyval">
<div class="SREntry">
<a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../../../../base/doc/html/structs__KEYVAL.html" target="_parent">s_KEYVAL</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fparallelinfo">
<div class="SREntry">
<a id="Item5" onkeydown="return searchResults.Nav(event,5)" onkeypress="return searchResults.Nav(event,5)" onkeyup="return searchResults.Nav(event,5)" class="SRSymbol" href="../<API key>.html" target="_parent">s_PARALLELINFO</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fpararray">
<div class="SREntry">
<a id="Item6" onkeydown="return searchResults.Nav(event,6)" onkeypress="return searchResults.Nav(event,6)" onkeyup="return searchResults.Nav(event,6)" class="SRSymbol" href="../../../../base/doc/html/structs__PARARRAY.html" target="_parent">s_PARARRAY</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fpslink">
<div class="SREntry">
<a id="Item7" onkeydown="return searchResults.Nav(event,7)" onkeypress="return searchResults.Nav(event,7)" onkeyup="return searchResults.Nav(event,7)" class="SRSymbol" href="../../../../base/doc/html/structs__PSLINK.html" target="_parent">s_PSLINK</a>
</div>
</div>
<div class="SRResult" id="SR_s_5fsizedstring">
<div class="SREntry">
<a id="Item8" onkeydown="return searchResults.Nav(event,8)" onkeypress="return searchResults.Nav(event,8)" onkeyup="return searchResults.Nav(event,8)" class="SRSymbol" href="../../../../base/doc/html/<API key>.html" target="_parent">s_SIZEDSTRING</a>
</div>
</div>
<div class="SRResult" id="SR_s_5ftask_5freln">
<div class="SREntry">
<a id="Item9" onkeydown="return searchResults.Nav(event,9)" onkeypress="return searchResults.Nav(event,9)" onkeyup="return searchResults.Nav(event,9)" class="SRSymbol" href="../<API key>.html" target="_parent">s_task_reln</a>
<span class="SRScope">TSOpt</span>
</div>
</div>
<div class="SRResult" id="SR_s_5fword">
<div class="SREntry">
<a id="Item10" onkeydown="return searchResults.Nav(event,10)" onkeypress="return searchResults.Nav(event,10)" onkeyup="return searchResults.Nav(event,10)" class="SRSymbol" href="../../../../base/doc/html/structs__WORD.html" target="_parent">s_WORD</a>
</div>
</div>
<div class="SRResult" id="SR_sample">
<div class="SREntry">
<a id="Item11" onkeydown="return searchResults.Nav(event,11)" onkeypress="return searchResults.Nav(event,11)" onkeyup="return searchResults.Nav(event,11)" class="SRSymbol" href="../<API key>.html#<API key>" target="_parent">sample</a>
<span class="SRScope">TSOpt::IWaveSampler</span>
</div>
</div>
<div class="SRResult" id="SR_schedule">
<div class="SREntry">
<a id="Item12" onkeydown="return searchResults.Nav(event,12)" onkeypress="return searchResults.Nav(event,12)" onkeyup="return searchResults.Nav(event,12)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_schedule')">Schedule</a>
<div class="SRChildren">
<a id="Item12_c0" onkeydown="return searchResults.NavChild(event,12,0)" onkeypress="return searchResults.NavChild(event,12,0)" onkeyup="return searchResults.NavChild(event,12,0)" class="SRScope" href="../classSchedule.html" target="_parent">Schedule</a>
<a id="Item12_c1" onkeydown="return searchResults.NavChild(event,12,1)" onkeypress="return searchResults.NavChild(event,12,1)" onkeyup="return searchResults.NavChild(event,12,1)" class="SRScope" href="../classSchedule.html#<API key>" target="_parent">Schedule::Schedule(int sn, Checkpoint *c)</a>
<a id="Item12_c2" onkeydown="return searchResults.NavChild(event,12,2)" onkeypress="return searchResults.NavChild(event,12,2)" onkeyup="return searchResults.NavChild(event,12,2)" class="SRScope" href="../classSchedule.html#<API key>" target="_parent">Schedule::Schedule(int sn)</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_seinfo">
<div class="SREntry">
<a id="Item13" onkeydown="return searchResults.Nav(event,13)" onkeypress="return searchResults.Nav(event,13)" onkeyup="return searchResults.Nav(event,13)" class="SRSymbol" href="../<API key>.html#<API key>" target="_parent">seinfo</a>
<span class="SRScope">s_PARALLELINFO</span>
</div>
</div>
<div class="SRResult" id="SR_set_5fcapo">
<div class="SREntry">
<a id="Item14" onkeydown="return searchResults.Nav(event,14)" onkeypress="return searchResults.Nav(event,14)" onkeyup="return searchResults.Nav(event,14)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_set_5fcapo')">set_capo</a>
<div class="SRChildren">
<a id="Item14_c0" onkeydown="return searchResults.NavChild(event,14,0)" onkeypress="return searchResults.NavChild(event,14,0)" onkeyup="return searchResults.NavChild(event,14,0)" class="SRScope" href="../classSchedule.html#<API key>" target="_parent">Schedule::set_capo()</a>
<a id="Item14_c1" onkeydown="return searchResults.NavChild(event,14,1)" onkeypress="return searchResults.NavChild(event,14,1)" onkeyup="return searchResults.NavChild(event,14,1)" class="SRScope" href="../classOnline.html#<API key>" target="_parent">Online::set_capo()</a>
<a id="Item14_c2" onkeydown="return searchResults.NavChild(event,14,2)" onkeypress="return searchResults.NavChild(event,14,2)" onkeyup="return searchResults.NavChild(event,14,2)" class="SRScope" href="../classOffline.html#<API key>" target="_parent">Offline::set_capo()</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_set_5ffine">
<div class="SREntry">
<a id="Item15" onkeydown="return searchResults.Nav(event,15)" onkeypress="return searchResults.Nav(event,15)" onkeyup="return searchResults.Nav(event,15)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_set_5ffine')">set_fine</a>
<div class="SRChildren">
<a id="Item15_c0" onkeydown="return searchResults.NavChild(event,15,0)" onkeypress="return searchResults.NavChild(event,15,0)" onkeyup="return searchResults.NavChild(event,15,0)" class="SRScope" href="../classSchedule.html#<API key>" target="_parent">Schedule::set_fine()</a>
<a id="Item15_c1" onkeydown="return searchResults.NavChild(event,15,1)" onkeypress="return searchResults.NavChild(event,15,1)" onkeyup="return searchResults.NavChild(event,15,1)" class="SRScope" href="../classOnline.html#<API key>" target="_parent">Online::set_fine()</a>
<a id="Item15_c2" onkeydown="return searchResults.NavChild(event,15,2)" onkeypress="return searchResults.NavChild(event,15,2)" onkeyup="return searchResults.NavChild(event,15,2)" class="SRScope" href="../classOnline__r2.html#<API key>" target="_parent">Online_r2::set_fine()</a>
<a id="Item15_c3" onkeydown="return searchResults.NavChild(event,15,3)" onkeypress="return searchResults.NavChild(event,15,3)" onkeyup="return searchResults.NavChild(event,15,3)" class="SRScope" href="../classOnline__r3.html#<API key>" target="_parent">Online_r3::set_fine()</a>
<a id="Item15_c4" onkeydown="return searchResults.NavChild(event,15,4)" onkeypress="return searchResults.NavChild(event,15,4)" onkeyup="return searchResults.NavChild(event,15,4)" class="SRScope" href="../classArevolve.html#<API key>" target="_parent">Arevolve::set_fine()</a>
<a id="Item15_c5" onkeydown="return searchResults.NavChild(event,15,5)" onkeypress="return searchResults.NavChild(event,15,5)" onkeyup="return searchResults.NavChild(event,15,5)" class="SRScope" href="../classMoin.html#<API key>" target="_parent">Moin::set_fine()</a>
<a id="Item15_c6" onkeydown="return searchResults.NavChild(event,15,6)" onkeypress="return searchResults.NavChild(event,15,6)" onkeyup="return searchResults.NavChild(event,15,6)" class="SRScope" href="../classOffline.html#<API key>" target="_parent">Offline::set_fine()</a>
</div>
</div>
</div>
<div class="SRResult" id="SR_set_5finfo">
<div class="SREntry">
<a id="Item16" onkeydown="return searchResults.Nav(event,16)" onkeypress="return searchResults.Nav(event,16)" onkeyup="return searchResults.Nav(event,16)" class="SRSymbol" href="../classRevolve.html#<API key>" target="_parent">set_info</a>
<span class="SRScope">Revolve</span>
</div>
</div>
<div class="SRResult" id="SR_setrecvexchange">
<div class="SREntry">
<a id="Item17" onkeydown="return searchResults.Nav(event,17)" onkeypress="return searchResults.Nav(event,17)" onkeyup="return searchResults.Nav(event,17)" class="SRSymbol" href="../iwave_8h.html#<API key>" target="_parent">setrecvexchange</a>
<span class="SRScope">iwave.h</span>
</div>
</div>
<div class="SRResult" id="SR_sfxxxx">
<div class="SREntry">
<a id="Item18" onkeydown="return searchResults.Nav(event,18)" onkeypress="return searchResults.Nav(event,18)" onkeyup="return searchResults.Nav(event,18)" class="SRSymbol" href="../usage__selfdoc_8h.html#<API key>" target="_parent">sfxxxx</a>
<span class="SRScope">usage_selfdoc.h</span>
</div>
</div>
<div class="SRResult" id="SR_snaps">
<div class="SREntry">
<a id="Item19" onkeydown="return searchResults.Nav(event,19)" onkeypress="return searchResults.Nav(event,19)" onkeyup="return searchResults.Nav(event,19)" class="SRSymbol" href="../classSchedule.html#<API key>" target="_parent">snaps</a>
<span class="SRScope">Schedule</span>
</div>
</div>
<div class="SRResult" id="SR_specs">
<div class="SREntry">
<a id="Item20" onkeydown="return searchResults.Nav(event,20)" onkeypress="return searchResults.Nav(event,20)" onkeyup="return searchResults.Nav(event,20)" class="SRSymbol" href="../structIMODEL.html#<API key>" target="_parent">specs</a>
<span class="SRScope">IMODEL</span>
</div>
</div>
<div class="SRResult" id="SR_sranks">
<div class="SREntry">
<a id="Item21" onkeydown="return searchResults.Nav(event,21)" onkeypress="return searchResults.Nav(event,21)" onkeyup="return searchResults.Nav(event,21)" class="SRSymbol" href="../<API key>.html#<API key>" target="_parent">sranks</a>
<span class="SRScope">s_PARALLELINFO</span>
</div>
</div>
<div class="SRResult" id="SR_stats">
<div class="SREntry">
<a id="Item22" onkeydown="return searchResults.Nav(event,22)" onkeypress="return searchResults.Nav(event,22)" onkeyup="return searchResults.Nav(event,22)" class="SRSymbol" href="../structs__IWAVE.html#<API key>" target="_parent">stats</a>
<span class="SRScope">s_IWAVE</span>
</div>
</div>
<div class="SRResult" id="SR_sten_5fcreate">
<div class="SREntry">
<a id="Item23" onkeydown="return searchResults.Nav(event,23)" onkeypress="return searchResults.Nav(event,23)" onkeyup="return searchResults.Nav(event,23)" class="SRSymbol" href="../stencil_8h.html#<API key>" target="_parent">sten_create</a>
<span class="SRScope">stencil.h</span>
</div>
</div>
<div class="SRResult" id="SR_sten_5fdestroy">
<div class="SREntry">
<a id="Item24" onkeydown="return searchResults.Nav(event,24)" onkeypress="return searchResults.Nav(event,24)" onkeyup="return searchResults.Nav(event,24)" class="SRSymbol" href="../stencil_8h.html#<API key>" target="_parent">sten_destroy</a>
<span class="SRScope">stencil.h</span>
</div>
</div>
<div class="SRResult" id="SR_sten_5fget">
<div class="SREntry">
<a id="Item25" onkeydown="return searchResults.Nav(event,25)" onkeypress="return searchResults.Nav(event,25)" onkeyup="return searchResults.Nav(event,25)" class="SRSymbol" href="../stencil_8h.html#<API key>" target="_parent">sten_get</a>
<span class="SRScope">stencil.h</span>
</div>
</div>
<div class="SRResult" id="SR_sten_5fout">
<div class="SREntry">
<a id="Item26" onkeydown="return searchResults.Nav(event,26)" onkeypress="return searchResults.Nav(event,26)" onkeyup="return searchResults.Nav(event,26)" class="SRSymbol" href="../stencil_8h.html#<API key>" target="_parent">sten_out</a>
<span class="SRScope">stencil.h</span>
</div>
</div>
<div class="SRResult" id="SR_sten_5fset">
<div class="SREntry">
<a id="Item27" onkeydown="return searchResults.Nav(event,27)" onkeypress="return searchResults.Nav(event,27)" onkeyup="return searchResults.Nav(event,27)" class="SRSymbol" href="../stencil_8h.html#<API key>" target="_parent">sten_set</a>
<span class="SRScope">stencil.h</span>
</div>
</div>
<div class="SRResult" id="SR_sten_5fsetnull">
<div class="SREntry">
<a id="Item28" onkeydown="return searchResults.Nav(event,28)" onkeypress="return searchResults.Nav(event,28)" onkeyup="return searchResults.Nav(event,28)" class="SRSymbol" href="../stencil_8h.html#<API key>" target="_parent">sten_setnull</a>
<span class="SRScope">stencil.h</span>
</div>
</div>
<div class="SRResult" id="SR_stencil">
<div class="SREntry">
<a id="Item29" onkeydown="return searchResults.Nav(event,29)" onkeypress="return searchResults.Nav(event,29)" onkeyup="return searchResults.Nav(event,29)" class="SRSymbol" href="../structSTENCIL.html" target="_parent">STENCIL</a>
</div>
</div>
<div class="SRResult" id="SR_stencil_2eh">
<div class="SREntry">
<a id="Item30" onkeydown="return searchResults.Nav(event,30)" onkeypress="return searchResults.Nav(event,30)" onkeyup="return searchResults.Nav(event,30)" class="SRSymbol" href="../stencil_8h.html" target="_parent">stencil.h</a>
</div>
</div>
<div class="SRResult" id="SR_stencil_5fmask">
<div class="SREntry">
<a id="Item31" onkeydown="return searchResults.Nav(event,31)" onkeypress="return searchResults.Nav(event,31)" onkeyup="return searchResults.Nav(event,31)" class="SRSymbol" href="../structSTENCIL__MASK.html" target="_parent">STENCIL_MASK</a>
</div>
</div>
<div class="SRResult" id="SR_storeparallel">
<div class="SREntry">
<a id="Item32" onkeydown="return searchResults.Nav(event,32)" onkeypress="return searchResults.Nav(event,32)" onkeyup="return searchResults.Nav(event,32)" class="SRSymbol" href="../iwave_8h.html#<API key>" target="_parent">storeparallel</a>
<span class="SRScope">iwave.h</span>
</div>
</div>
<div class="SRResult" id="SR_str">
<div class="SREntry">
<a id="Item33" onkeydown="return searchResults.Nav(event,33)" onkeypress="return searchResults.Nav(event,33)" onkeyup="return searchResults.Nav(event,33)" class="SRSymbol" href="../../../../base/doc/html/structs__WORD.html#<API key>" target="_parent">str</a>
<span class="SRScope">s_WORD</span>
</div>
</div>
<div class="SRResult" id="SR_substep">
<div class="SREntry">
<a id="Item34" onkeydown="return searchResults.Nav(event,34)" onkeypress="return searchResults.Nav(event,34)" onkeyup="return searchResults.Nav(event,34)" class="SRSymbol" href="../structs__field.html#<API key>" target="_parent">substep</a>
<span class="SRScope">s_field</span>
</div>
</div>
<div class="SRResult" id="SR_sumtmin">
<div class="SREntry">
<a id="Item35" onkeydown="return searchResults.Nav(event,35)" onkeypress="return searchResults.Nav(event,35)" onkeyup="return searchResults.Nav(event,35)" class="SRSymbol" href="../classArevolve.html#<API key>" target="_parent">sumtmin</a>
<span class="SRScope">Arevolve</span>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
|
#!/usr/bin/env python
import os, sys
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise RuntimeError("can't find toplevel directory!")
sys.path.append(os.path.join(path[0], "scripts"))
import TestUtil
TestUtil.clientServerTest()
|
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/inet_ecn.h>
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/structs.h>
static struct sctp_packet *sctp_abort_pkt_new(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen);
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands);
static struct sctp_packet *sctp_ootb_pkt_new(struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk);
static void <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk);
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk);
static sctp_disposition_t <API key>(struct net *net,
sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport);
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen);
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands);
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_ierror_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk);
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
/* Small helper function that checks if the chunk length
* is of the appropriate length. The 'required_length' argument
* is set to be the size of a specific chunk we are testing.
* Return Values: 1 = Valid length
* 0 = Invalid length
*
*/
static inline int
<API key>(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
/* Previously already marked? */
if (unlikely(chunk->pdiscard))
return 0;
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
sctp_disposition_t sctp_sf_do_4_C(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!<API key>(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 2960 6.10 Bundling
*
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return <API key>(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_COMPLETE chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* RFC 2960 10.2 SCTP-to-ULP
*
* H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = <API key>(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
/* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint
* will verify that it is in SHUTDOWN-ACK-SENT state, if it is
* not the chunk should be discarded. If the endpoint is in
* the SHUTDOWN-ACK-SENT state the endpoint should stop the
* T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED
* state).
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return <API key>;
}
/*
* Respond to a normal INIT chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, B
* B) "Z" shall respond immediately with an INIT ACK chunk. The
* destination IP address of the INIT ACK MUST be set to the source
* IP address of the INIT to which this INIT ACK is responding. In
* the response, besides filling in other parameters, "Z" must set the
* Verification Tag field to Tag_A, and also provide its own
* Verification Tag (Tag_Z) in the Initiate Tag field.
*
* Verification Tag: Must be 0.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
<API key> *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return <API key>(net, ep, asoc, type, arg, commands);
}
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return <API key>(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* Normally, this would cause an ABORT with a Protocol Violation
* error, but since we don't have an association, we'll
* just discard the packet.
*/
if (!<API key>(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the INIT is coming toward a closing socket, we'll send back
* and ABORT. Essentially, this catches the race of INIT being
* backloged to the socket at the same time as the user isses close().
* Since the socket and all its associations are going away, we
* can treat this OOTB
*/
if (sctp_sstate(ep->base.sk, CLOSING))
return <API key>(net, ep, asoc, type, arg, commands);
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
return <API key>;
} else {
return <API key>;
}
} else {
return <API key>(net, ep, asoc, type, arg,
commands);
}
}
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (<API key>(new_asoc,
sctp_scope(sctp_source(chunk)),
GFP_ATOMIC) < 0)
goto nomem_init;
/* The call, sctp_process_init(), can fail on memory allocation. */
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem_init;
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk)
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem_init;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (<API key> *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
sctp_chunk_free(err_chunk);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources, nor keep any states for the
* new association. Otherwise, "Z" will be vulnerable to resource
* attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return <API key>;
nomem_init:
<API key>(new_asoc);
nomem:
if (err_chunk)
sctp_chunk_free(err_chunk);
return <API key>;
}
/*
* Respond to a normal INIT ACK chunk.
* We are the side that is initiating the association.
*
* Section: 5.1 Normal Establishment of an Association, C
* C) Upon reception of the INIT ACK from "Z", "A" shall stop the T1-init
* timer and leave COOKIE-WAIT state. "A" shall then send the State
* Cookie received in the INIT ACK chunk in a COOKIE ECHO chunk, start
* the T1-cookie timer, and enter the COOKIE-ECHOED state.
*
* Note: The COOKIE ECHO chunk can be bundled with any pending outbound
* DATA chunks, but it MUST be the first chunk in the packet and
* until the COOKIE ACK is returned the sender MUST NOT send any
* other packets to the peer.
*
* Verification Tag: 3.3.3
* If the value of the Initiate Tag in a received INIT ACK chunk is
* found to be 0, the receiver MUST treat it as an error and close the
* association by transmitting an ABORT.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1C_ack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_init_chunk_t *initchunk;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return <API key>(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT-ACK chunk has a valid length */
if (!<API key>(chunk, sizeof(<API key>)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
sctp_error_t error = <API key>;
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes. If there are no causes,
* then there wasn't enough memory. Just terminate
* the association.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
error = <API key>;
}
}
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
return <API key>(net, commands, error, ECONNREFUSED,
asoc, chunk->transport);
}
/* Tag the variable length parameters. Note that we never
* convert the parameters in an INIT chunk.
*/
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
initchunk = (sctp_init_chunk_t *) chunk->chunk_hdr;
sctp_add_cmd_sf(commands, SCTP_CMD_PEER_INIT,
SCTP_PEER_INIT(initchunk));
/* Reset init error count upon receipt of INIT-ACK. */
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* 5.1 C) "A" shall stop the T1-init timer and leave
* COOKIE-WAIT state. "A" shall then ... start the T1-cookie
* timer, and enter the COOKIE-ECHOED state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
/* SCTP-AUTH: genereate the assocition shared keys so that
* we can potentially signe the COOKIE-ECHO.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* 5.1 C) "A" shall then send the State Cookie received in the
* INIT ACK chunk in a COOKIE ECHO chunk, ...
*/
/* If there is any errors to report, send the ERROR chunk generated
* for unknown parameters as well.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(err_chunk));
return <API key>;
}
/*
* Respond to a normal COOKIE ECHO chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, D
* D) Upon reception of the COOKIE ECHO chunk, Endpoint "Z" will reply
* with a COOKIE ACK chunk after building a TCB and moving to
* the ESTABLISHED state. A COOKIE ACK chunk may be bundled with
* any pending DATA chunks (and/or SACK chunks), but the COOKIE ACK
* chunk MUST be the first chunk in the packet.
*
* IMPLEMENTATION NOTE: An implementation may choose to send the
* Communication Up notification to the SCTP user upon reception
* of a valid COOKIE ECHO chunk.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* D) Rules for packet carrying a COOKIE ECHO
*
* - When sending a COOKIE ECHO, the endpoint MUST use the value of the
* Initial Tag received in the INIT ACK.
*
* - The receiver of a COOKIE ECHO follows the procedures in Section 5.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
struct sctp_ulpevent *ev, *ai_ev = NULL;
int error = 0;
struct sctp_chunk *err_chk_p;
struct sock *sk;
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return <API key>(net, ep, asoc, type, arg, commands);
}
/* Make sure that the COOKIE_ECHO chunk has a valid length.
* In this case, we check that we have enough for at least a
* chunk header. More detailed verification is done
* in sctp_unpack_cookie().
*/
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the endpoint is not listening or if the number of associations
* on the TCP-style socket exceed the max backlog, respond with an
* ABORT.
*/
sk = ep->base.sk;
if (!sctp_sstate(sk, LISTENING) ||
(sctp_style(sk, TCP) && sk_acceptq_is_full(sk)))
return <API key>(net, ep, asoc, type, arg, commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr =
(struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint
* "Z" will reply with a COOKIE ACK chunk after building a TCB
* and moving to the ESTABLISHED state.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -<API key>:
<API key>(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Delay state machine commands until later.
*
* Re-build the bind address for the association is done in
* the sctp_unpack_cookie() already.
*/
/* This is a brand-new association, so these are not yet side
* effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk,
&chunk->subh.cookie_hdr->c.peer_addr,
peer_init, GFP_ATOMIC))
goto nomem_init;
/* SCTP-AUTH: Now that we've populate required fields in
* sctp_process_init, set up the assocaition shared keys as
* necessary so that we can potentially authenticate the ACK
*/
error = sctp_<API key>(new_asoc, GFP_ATOMIC);
if (error)
goto nomem_init;
/* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo
* is supposed to be authenticated and we have to do delayed
* authentication. We've just recreated the association using
* the information in the cookie and now it's much easier to
* do the authentication.
*/
if (chunk->auth_chunk) {
struct sctp_chunk auth;
sctp_ierror_t ret;
/* Make sure that we and the peer are AUTH capable */
if (!net->sctp.auth_enable || !new_asoc->peer.auth_capable) {
<API key>(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* set-up our fake chunk so that we can process it */
auth.skb = chunk->auth_chunk;
auth.asoc = chunk->asoc;
auth.sctp_hdr = chunk->sctp_hdr;
auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk,
sizeof(sctp_chunkhdr_t));
skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t));
auth.transport = chunk->transport;
ret = <API key>(net, ep, new_asoc, type, &auth);
if (ret != <API key>) {
<API key>(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
repl = <API key>(new_asoc, chunk);
if (!repl)
goto nomem_init;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*/
ev = <API key>(new_asoc, 0, SCTP_COMM_UP, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (new_asoc->peer.adaptation_ind) {
ai_ev = <API key>(new_asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem_aiev;
}
/* Add all the state machine commands now since we've created
* everything. This way we don't introduce memory corruptions
* during side-effect processing and correclty count established
* associations.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, <API key>);
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
if (new_asoc->timeouts[<API key>])
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
/* This will send the COOKIE ACK */
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* Queue the ASSOC_CHANGE event */
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Send up the Adaptation Layer Indication event */
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return <API key>;
nomem_aiev:
sctp_ulpevent_free(ev);
nomem_ev:
sctp_chunk_free(repl);
nomem_init:
<API key>(new_asoc);
nomem:
return <API key>;
}
/*
* Respond to a normal COOKIE ACK chunk.
* We are the side that is asking for an association.
*
* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move from the
* COOKIE-ECHOED state to the ESTABLISHED state, stopping the T1-cookie
* timer. It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*
* Verification Tag:
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1E_ca(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Verify that the chunk length for the COOKIE-ACK is OK.
* If we don't do this, any bundled chunks may be junked.
*/
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Reset init error count upon receipt of COOKIE-ACK,
* to avoid problems with the managemement of this
* counter in stale cookie situations when a transition back
* from the COOKIE-ECHOED state to the COOKIE-WAIT
* state is performed.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move
* from the COOKIE-ECHOED state to the ESTABLISHED state,
* stopping the T1-cookie timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, <API key>);
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
if (asoc->timeouts[<API key>])
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
/* It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*/
ev = <API key>(asoc, 0, SCTP_COMM_UP,
0, asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ev = <API key>(asoc, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return <API key>;
nomem:
return <API key>;
}
/* Generate and sendout a heartbeat packet. */
static sctp_disposition_t sctp_sf_heartbeat(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
struct sctp_chunk *reply;
/* Send a heartbeat to our peer. */
reply = sctp_make_heartbeat(asoc, transport);
if (!reply)
return <API key>;
/* Set rto_pending indicating that an RTT measurement
* is started with this heartbeat chunk.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
}
/* Generate a HEARTBEAT packet on the given transport. */
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
/* Section 3.3.5.
* The Sender-specific Heartbeat Info field should normally include
* information about the sender's current time when this HEARTBEAT
* chunk is sent and the destination transport address to which this
* HEARTBEAT is sent (see Section 8.3).
*/
if (transport->param_flags & SPP_HB_ENABLE) {
if (<API key> ==
sctp_sf_heartbeat(ep, asoc, type, arg,
commands))
return <API key>;
/* Set transport error counter and association error counter
* when sending heartbeat.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TRANSPORT(transport));
}
sctp_add_cmd_sf(commands, <API key>,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, <API key>,
SCTP_TRANSPORT(transport));
return <API key>;
}
/*
* Process an heartbeat request.
*
* Section: 8.3 Path Heartbeat
* The receiver of the HEARTBEAT should immediately respond with a
* HEARTBEAT ACK that contains the Heartbeat Information field copied
* from the received HEARTBEAT chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* When receiving an SCTP packet, the endpoint MUST ensure that the
* value in the Verification Tag field of the received SCTP packet
* matches its own Tag. If the received Verification Tag value does not
* match the receiver's own tag value, the receiver shall silently
* discard the packet and shall not process it any further except for
* those cases listed in Section 8.5.1 below.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_beat_8_3(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_paramhdr_t *param_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
size_t paylen = 0;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT chunk has a valid length. */
if (!<API key>(chunk, sizeof(<API key>)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* 8.3 The receiver of the HEARTBEAT should immediately
* respond with a HEARTBEAT ACK that contains the Heartbeat
* Information field copied from the received HEARTBEAT chunk.
*/
chunk->subh.hb_hdr = (sctp_heartbeathdr_t *) chunk->skb->data;
param_hdr = (sctp_paramhdr_t *) chunk->subh.hb_hdr;
paylen = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
if (ntohs(param_hdr->length) > paylen)
return <API key>(net, ep, asoc, type, arg,
param_hdr, commands);
if (!pskb_pull(chunk->skb, paylen))
goto nomem;
reply = <API key>(asoc, chunk, param_hdr, paylen);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
nomem:
return <API key>;
}
/*
* Process the returning HEARTBEAT ACK.
*
* Section: 8.3 Path Heartbeat
* Upon the receipt of the HEARTBEAT ACK, the sender of the HEARTBEAT
* should clear the error counter of the destination transport
* address to which the HEARTBEAT was sent, and mark the destination
* transport address as active if it is not so marked. The endpoint may
* optionally report to the upper layer when an inactive destination
* address is marked as active due to the reception of the latest
* HEARTBEAT ACK. The receiver of the HEARTBEAT ACK must also
* clear the association overall error count as well (as defined
* in section 8.1).
*
* The receiver of the HEARTBEAT ACK should also perform an RTT
* measurement for that destination transport address using the time
* value carried in the HEARTBEAT ACK chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
union sctp_addr from_addr;
struct sctp_transport *link;
<API key> *hbinfo;
unsigned long max_interval;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT-ACK chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t) +
sizeof(<API key>)))
return <API key>(net, ep, asoc, type, arg,
commands);
hbinfo = (<API key> *) chunk->skb->data;
/* Make sure that the length of the parameter is what we expect */
if (ntohs(hbinfo->param_hdr.length) !=
sizeof(<API key>)) {
return <API key>;
}
from_addr = hbinfo->daddr;
link = <API key>(asoc, &from_addr);
/* This should never happen, but lets log it if so. */
if (unlikely(!link)) {
if (from_addr.sa.sa_family == AF_INET6) {
<API key>("%s association %p could not find address %pI6\n",
__func__,
asoc,
&from_addr.v6.sin6_addr);
} else {
<API key>("%s association %p could not find address %pI4\n",
__func__,
asoc,
&from_addr.v4.sin_addr.s_addr);
}
return <API key>;
}
/* Validate the 64-bit random nonce. */
if (hbinfo->hb_nonce != link->hb_nonce)
return <API key>;
max_interval = link->hbinterval + link->rto;
/* Check if the timestamp looks valid. */
if (time_after(hbinfo->sent_at, jiffies) ||
time_after(jiffies, hbinfo->sent_at + max_interval)) {
pr_debug("%s: HEARTBEAT ACK with invalid timestamp received "
"for transport:%p\n", __func__, link);
return <API key>;
}
/* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of
* the HEARTBEAT should clear the error counter of the
* destination transport address to which the HEARTBEAT was
* sent and mark the destination transport address as active if
* it is not so marked.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_TRANSPORT(link));
return <API key>;
}
/* Helper function to send out an abort for the restart
* condition.
*/
static int <API key>(struct net *net, union sctp_addr *ssa,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
int len;
struct sctp_packet *pkt;
union sctp_addr_param *addrparm;
struct sctp_errhdr *errhdr;
struct sctp_endpoint *ep;
char buffer[sizeof(struct sctp_errhdr)+sizeof(union sctp_addr_param)];
struct sctp_af *af = <API key>(ssa->v4.sin_family);
/* Build the error on the stack. We are way to malloc crazy
* throughout the code today.
*/
errhdr = (struct sctp_errhdr *)buffer;
addrparm = (union sctp_addr_param *)errhdr->variable;
/* Copy into a parm format. */
len = af->to_addr_param(ssa, addrparm);
len += sizeof(sctp_errhdr_t);
errhdr->cause = SCTP_ERROR_RESTART;
errhdr->length = htons(len);
/* Assign to the control socket. */
ep = sctp_sk(net->sctp.ctl_sock)->ep;
/* Association is NULL since this may be a restart attack and we
* want to send back the attacker's vtag.
*/
pkt = sctp_abort_pkt_new(net, ep, NULL, init, errhdr, len);
if (!pkt)
goto out;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(pkt));
SCTP_INC_STATS(net, <API key>);
/* Discard the rest of the inbound packet. */
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
out:
/* Even if there is no memory, treat as a failure so
* the packet will get dropped.
*/
return 0;
}
static bool list_has_sctp_addr(const struct list_head *list,
union sctp_addr *ipaddr)
{
struct sctp_transport *addr;
list_for_each_entry(addr, list, transports) {
if (sctp_cmp_addr_exact(ipaddr, &addr->ipaddr))
return true;
}
return false;
}
/* A restart is occurring, check to make sure no new addresses
* are being added as we may be under a takeover attack.
*/
static int <API key>(const struct sctp_association *new_asoc,
const struct sctp_association *asoc,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
struct net *net = sock_net(new_asoc->base.sk);
struct sctp_transport *new_addr;
int ret = 1;
/* Implementor's Guide - Section 5.2.2
* ...
* Before responding the endpoint MUST check to see if the
* unexpected INIT adds new addresses to the association. If new
* addresses are added to the association, the endpoint MUST respond
* with an ABORT..
*/
/* Search through all current addresses and make sure
* we aren't adding any new ones.
*/
list_for_each_entry(new_addr, &new_asoc->peer.transport_addr_list,
transports) {
if (!list_has_sctp_addr(&asoc->peer.transport_addr_list,
&new_addr->ipaddr)) {
<API key>(net, &new_addr->ipaddr, init,
commands);
ret = 0;
break;
}
}
/* Return success if all addresses were found. */
return ret;
}
/* Populate the verification/tie tags based on overlapping INIT
* scenario.
*
* Note: Do not use in CLOSED or SHUTDOWN-ACK-SENT state.
*/
static void <API key>(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
switch (asoc->state) {
/* 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State */
case <API key>:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = 0;
break;
case <API key>:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
/* 5.2.2 Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
* COOKIE-WAIT and SHUTDOWN-ACK-SENT
*/
default:
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
}
/* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
*/
new_asoc->rwnd = asoc->rwnd;
new_asoc->c.sinit_num_ostreams = asoc->c.sinit_num_ostreams;
new_asoc->c.sinit_max_instreams = asoc->c.sinit_max_instreams;
new_asoc->c.initial_tsn = asoc->c.initial_tsn;
}
/*
* Compare vtag/tietag values to determine unexpected COOKIE-ECHO
* handling action.
*
* RFC 2960 5.2.4 Handle a COOKIE ECHO when a TCB exists.
*
* Returns value representing action to be taken. These action values
* correspond to Action/Description values in RFC 2960, Table 2.
*/
static char <API key>(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
/* In this case, the peer may have restarted. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag != new_asoc->c.peer_vtag) &&
(asoc->c.my_vtag == new_asoc->c.my_ttag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_ttag))
return 'A';
/* Collision case B. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
((asoc->c.peer_vtag != new_asoc->c.peer_vtag) ||
(0 == asoc->c.peer_vtag))) {
return 'B';
}
/* Collision case D. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag))
return 'D';
/* Collision case C. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag) &&
(0 == new_asoc->c.my_ttag) &&
(0 == new_asoc->c.peer_ttag))
return 'C';
/* No match to any of the special cases; discard this packet. */
return 'E';
}
/* Common helper routine for both duplicate and simulataneous INIT
* chunk handling.
*/
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
<API key> *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return <API key>(net, ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* In this case, we generate a protocol violation since we have
* an association established.
*/
if (!<API key>(chunk, sizeof(sctp_init_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(net, ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
retval = <API key>;
} else {
retval = <API key>;
}
goto cleanup;
} else {
return <API key>(net, ep, asoc, type, arg,
commands);
}
}
/*
* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
* FIXME: We are copying parameters from the endpoint not the
* association.
*/
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (<API key>(new_asoc,
sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0)
goto nomem;
/* In the outbound INIT ACK the endpoint MUST copy its current
* Verification Tag and Peers Verification tag into a reserved
* place (local tie-tag and per tie-tag) within the state cookie.
*/
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Do not do this check for COOKIE-WAIT state,
* since there are no peer addresses to check against.
* Upon return an ABORT will have been sent if needed.
*/
if (!sctp_state(asoc, COOKIE_WAIT)) {
if (!<API key>(new_asoc, asoc, chunk,
commands)) {
retval = <API key>;
goto nomem_retval;
}
}
<API key>(new_asoc, asoc);
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk) {
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
}
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (<API key> *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources for this new association.
* Otherwise, "Z" will be vulnerable to resource attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
retval = <API key>;
return retval;
nomem:
retval = <API key>;
nomem_retval:
if (new_asoc)
<API key>(new_asoc);
cleanup:
if (err_chunk)
sctp_chunk_free(err_chunk);
return retval;
}
/*
* Handle simultaneous INIT.
* This means we started an INIT and then we got an INIT request from
* our peer.
*
* Section: 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State (Item B)
* This usually indicates an initialization collision, i.e., each
* endpoint is attempting, at about the same time, to establish an
* association with the other endpoint.
*
* Upon receipt of an INIT in the COOKIE-WAIT or COOKIE-ECHOED state, an
* endpoint MUST respond with an INIT ACK using the same parameters it
* sent in its original INIT chunk (including its Verification Tag,
* unchanged). These original parameters are combined with those from the
* newly received INIT chunk. The endpoint shall also generate a State
* Cookie with the INIT ACK. The endpoint uses the parameters sent in its
* INIT to calculate the State Cookie.
*
* After that, the endpoint MUST NOT change its state, the T1-init
* timer shall be left running and the corresponding TCB MUST NOT be
* destroyed. The normal procedures for handling State Cookies when
* a TCB exists will resolve the duplicate INITs to a single association.
*
* For an endpoint that is in the COOKIE-ECHOED state it MUST populate
* its Tie-Tags with the Tag information of itself and its peer (see
* section 5.2.2 for a description of the Tie-Tags).
*
* Verification Tag: Not explicit, but an INIT can not have a valid
* verification tag, so we skip the check.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Handle duplicated INIT messages. These are usually delayed
* restransmissions.
*
* Section: 5.2.2 Unexpected INIT in States Other than CLOSED,
* COOKIE-ECHOED and COOKIE-WAIT
*
* Unless otherwise stated, upon reception of an unexpected INIT for
* this association, the endpoint shall generate an INIT ACK with a
* State Cookie. In the outbound INIT ACK the endpoint MUST copy its
* current Verification Tag and peer's Verification Tag into a reserved
* place within the state cookie. We shall refer to these locations as
* the Peer's-Tie-Tag and the Local-Tie-Tag. The outbound SCTP packet
* containing this INIT ACK MUST carry a Verification Tag value equal to
* the Initiation Tag found in the unexpected INIT. And the INIT ACK
* MUST contain a new Initiation Tag (randomly generated see Section
* 5.3.1). Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of outbound
* streams) into the INIT ACK and cookie.
*
* After sending out the INIT ACK, the endpoint shall take no further
* actions, i.e., the existing association, including its current state,
* and the corresponding TCB MUST NOT be changed.
*
* Note: Only when a TCB exists and the association is not in a COOKIE-
* WAIT state are the Tie-Tags populated. For a normal association INIT
* (i.e. the endpoint is in a COOKIE-WAIT state), the Tie-Tags MUST be
* set to 0 (indicating that no previous TCB existed). The INIT ACK and
* State Cookie are populated as specified in section 5.2.1.
*
* Verification Tag: Not specified, but an INIT has no way of knowing
* what the verification tag could be, so we ignore it.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Unexpected INIT-ACK handler.
*
* Section 5.2.3
* If an INIT ACK received by an endpoint in any state other than the
* COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
* An unexpected INIT ACK usually indicates the processing of an old or
* duplicated INIT chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* Per the above section, we'll discard the chunk if we have an
* endpoint. If this is an OOTB INIT-ACK, treat it as such.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep)
return sctp_sf_ootb(net, ep, asoc, type, arg, commands);
else
return <API key>(net, ep, asoc, type, arg, commands);
}
/* Unexpected COOKIE-ECHO handler for peer restart (Table 2, action 'A')
*
* Section 5.2.4
* A) In this case, the peer may have restarted.
*/
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_ulpevent *ev;
struct sctp_chunk *repl;
struct sctp_chunk *err;
sctp_disposition_t disposition;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Though this is a pretty complicated attack
* since you'd have to get inside the cookie.
*/
if (!<API key>(new_asoc, asoc, chunk, commands)) {
return <API key>;
}
/* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
* the peer has restarted (Action A), it MUST NOT setup a new
* association but instead resend the SHUTDOWN ACK and send an ERROR
* chunk with a "Cookie Received while Shutting Down" error cause to
* its peer.
*/
if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) {
disposition = <API key>(net, ep, asoc,
SCTP_ST_CHUNK(chunk->chunk_hdr->type),
chunk, commands);
if (<API key> == disposition)
goto nomem;
err = sctp_make_op_error(asoc, chunk,
<API key>,
NULL, 0, 0);
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return <API key>;
}
/* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked
* data. Consider the optional choice of resending of this data.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue
* and ASCONF-ACK cache.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
repl = <API key>(new_asoc, chunk);
if (!repl)
goto nomem;
/* Report association restart to upper layer. */
ev = <API key>(asoc, 0, SCTP_RESTART, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, <API key>, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
if (sctp_state(asoc, SHUTDOWN_PENDING) &&
(sctp_sstate(asoc->base.sk, CLOSING) ||
sock_flag(asoc->base.sk, SOCK_DEAD))) {
/* if were currently in SHUTDOWN_PENDING, but the socket
* has been closed by user, don't transition to ESTABLISHED.
* Instead trigger SHUTDOWN bundled with COOKIE_ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return <API key>(net, ep, asoc,
SCTP_ST_CHUNK(0), NULL,
commands);
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
}
return <API key>;
nomem_ev:
sctp_chunk_free(repl);
nomem:
return <API key>;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'B')
*
* Section 5.2.4
* B) In this case, both sides may be attempting to start an association
* at about the same time but the peer endpoint started its INIT
* after responding to the local endpoint's INIT
*/
/* This case represents an initialization collision. */
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, <API key>, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
repl = <API key>(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*
* Sadly, this needs to be implemented as a side-effect, because
* we are not guaranteed to have set the association id of the real
* association and so these notifications need to be delayed until
* the association id is allocated.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_U8(SCTP_COMM_UP));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*
* This also needs to be done as a side effect for the same reason as
* above.
*/
if (asoc->peer.adaptation_ind)
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
return <API key>;
nomem:
return <API key>;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'C')
*
* Section 5.2.4
* C) In this case, the local endpoint's cookie has arrived late.
* Before it arrived, the local endpoint sent an INIT and received an
* INIT-ACK and finally sent a COOKIE ECHO with the peer's same tag
* but a new tag of its own.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
/* The cookie should be silently discarded.
* The endpoint SHOULD NOT change states and should leave
* any timers running.
*/
return <API key>;
}
/* Unexpected COOKIE-ECHO handler lost chunk (Table 2, action 'D')
*
* Section 5.2.4
*
* D) When both local and remote tags match the endpoint should always
* enter the ESTABLISHED state, if it has not already done so.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
struct sctp_ulpevent *ev = NULL, *ai_ev = NULL;
struct sctp_chunk *repl;
/* Clarification from Implementor's Guide:
* D) When both local and remote tags match the endpoint should
* enter the ESTABLISHED state, if it is in the COOKIE-ECHOED state.
* It should stop any cookie timer that may be running and send
* a COOKIE ACK.
*/
/* Don't accidentally move back into established state. */
if (asoc->state < <API key>) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose
* to send the Communication Up notification to the
* SCTP user upon reception of a valid COOKIE
* ECHO chunk.
*/
ev = <API key>(asoc, 0,
SCTP_COMM_UP, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter,
* SCTP delivers this notification to inform the application
* that of the peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ai_ev = <API key>(asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem;
}
}
repl = <API key>(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return <API key>;
nomem:
if (ai_ev)
sctp_ulpevent_free(ai_ev);
if (ev)
sctp_ulpevent_free(ev);
return <API key>;
}
/*
* Handle a duplicate COOKIE-ECHO. This usually means a cookie-carrying
* chunk was retransmitted and then delayed in the network.
*
* Section: 5.2.4 Handle a COOKIE ECHO when a TCB exists
*
* Verification Tag: None. Do cookie validation.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
int error = 0;
char action;
struct sctp_chunk *err_chk_p;
/* Make sure that the chunk has a valid length from the protocol
* perspective. In this case check to make sure we have at least
* enough for the chunk header. Cookie length verification is
* done later.
*/
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie
* of a duplicate COOKIE ECHO match the Verification Tags of the
* current association, consider the State Cookie valid even if
* the lifespan is exceeded.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -<API key>:
<API key>(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Compare the tie_tag in cookie with the verification tag of
* current association.
*/
action = <API key>(new_asoc, asoc);
switch (action) {
case 'A': /* Association restart. */
retval = <API key>(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'B': /* Collision case B. */
retval = <API key>(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'C': /* Collision case C. */
retval = <API key>(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'D': /* Collision case D. */
retval = <API key>(net, ep, asoc, chunk, commands,
new_asoc);
break;
default: /* Discard packet for all others. */
retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
break;
}
/* Delete the tempory new association. */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
/* Restore association pointer to provide SCTP command interpeter
* with a valid context in case it needs to manipulate
* the queues */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC,
SCTP_ASOC((struct sctp_association *)asoc));
return retval;
nomem:
return <API key>;
}
/*
* Process an ABORT. (SHUTDOWN-PENDING state)
*
* See <API key>().
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!<API key>(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!<API key>(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
<API key>(&asoc->base.bind_addr, &chunk->dest))
return <API key>(net, ep, asoc, type, arg, commands);
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-SENT state)
*
* See <API key>().
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!<API key>(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!<API key>(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
<API key>(&asoc->base.bind_addr, &chunk->dest))
return <API key>(net, ep, asoc, type, arg, commands);
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-ACK-SENT state)
*
* See <API key>().
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Handle an Error received in COOKIE_ECHOED state.
*
* Only handle the error type of stale COOKIE Error, the other errors will
* be ignored.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length.
* The parameter walking depends on this as well.
*/
if (!<API key>(chunk, sizeof(sctp_operr_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Process the error here */
/* FUTURE FIXME: When PR-SCTP related and other optional
* parms are emitted, this will have to change to handle multiple
* errors.
*/
sctp_walk_errors(err, chunk->chunk_hdr) {
if (<API key> == err->cause)
return <API key>(net, ep, asoc, type,
arg, commands);
}
/* It is possible to have malformed error causes, and that
* will cause us to end the walk early. However, since
* we are discarding the packet, there should be no adverse
* affects.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/*
* Handle a Stale COOKIE Error
*
* Section: 5.2.6 Handle Stale COOKIE Error
* If the association is in the COOKIE-ECHOED state, the endpoint may elect
* one of the following three alternatives.
* ...
* 3) Send a new INIT chunk to the endpoint, adding a Cookie
* Preservative parameter requesting an extension to the lifetime of
* the State Cookie. When calculating the time extension, an
* implementation SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no more
* than 1 second beyond the measured RTT, due to long State Cookie
* lifetimes making the endpoint more subject to a replay attack.
*
* Verification Tag: Not explicit, but safe to ignore.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
u32 stale;
<API key> bht;
sctp_errhdr_t *err;
struct sctp_chunk *reply;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
if (attempts > asoc->max_init_attempts) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
return <API key>;
}
err = (sctp_errhdr_t *)(chunk->skb->data);
/* When calculating the time extension, an implementation
* SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no
* more than 1 second beyond the measured RTT, due to long
* State Cookie lifetimes making the endpoint more subject to
* a replay attack.
* Measure of Staleness's unit is usec. (1/1000000 sec)
* Suggested Cookie Life-span Increment's unit is msec.
* (1/1000 sec)
* In general, if you use the suggested cookie life, the value
* found in the field of measure of staleness should be doubled
* to give ample time to retransmit the new cookie and thus
* yield a higher probability of success on the reattempt.
*/
stale = ntohl(*(__be32 *)((u8 *)err + sizeof(sctp_errhdr_t)));
stale = (stale * 2) / 1000;
bht.param_hdr.type = <API key>;
bht.param_hdr.length = htons(sizeof(bht));
bht.lifespan_increment = htonl(stale);
/* Build that new INIT chunk. */
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
reply = sctp_make_init(asoc, bp, GFP_ATOMIC, sizeof(bht));
if (!reply)
goto nomem;
sctp_addto_chunk(reply, sizeof(bht), &bht);
/* Clear peer's init_tag cached in assoc as we are sending a new INIT */
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* Stop pending T3-rtx and heartbeat timers */
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* Delete non-primary peer ip addresses since we are transitioning
* back to the COOKIE-WAIT state
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
/* If we've sent any data bundled with COOKIE-ECHO we will need to
* resend
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T1_RETRAN,
SCTP_TRANSPORT(asoc->peer.primary_path));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
nomem:
return <API key>;
}
/*
* Process an ABORT.
*
* Section: 9.1
* After checking the Verification Tag, the receiving endpoint shall
* remove the association from its record, and shall report the
* termination to its upper layer.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* B) Rules for packet carrying ABORT:
*
* - The endpoint shall always fill in the Verification Tag field of the
* outbound packet with the destination endpoint's tag value if it
* is known.
*
* - If the ABORT is sent in response to an OOTB packet, the endpoint
* MUST follow the procedure described in Section 8.4.
*
* - The receiver MUST accept the packet if the Verification Tag
* matches either its own tag, OR the tag of its peer. Otherwise, the
* receiver MUST silently discard the packet and take no further
* action.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!<API key>(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!<API key>(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
<API key>(&asoc->base.bind_addr, &chunk->dest))
return <API key>(net, ep, asoc, type, arg, commands);
return <API key>(net, ep, asoc, type, arg, commands);
}
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned int len;
__be16 error = SCTP_ERROR_NO_ERROR;
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr)) {
sctp_errhdr_t *err;
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
}
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNRESET));
/* ASSOC_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, <API key>, SCTP_PERR(error));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
/*
* Process an ABORT. (COOKIE-WAIT state)
*
* See <API key>() above.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned int len;
__be16 error = SCTP_ERROR_NO_ERROR;
if (!<API key>(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!<API key>(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr))
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
return <API key>(net, commands, error, ECONNREFUSED, asoc,
chunk->transport);
}
/*
* Process an incoming ICMP as an ABORT. (COOKIE-WAIT state)
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return <API key>(net, commands, SCTP_ERROR_NO_ERROR,
ENOPROTOOPT, asoc,
(struct sctp_transport *)arg);
}
/*
* Process an ABORT. (COOKIE-ECHOED state)
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Stop T1 timer and abort association with "INIT failed".
*
* This is common code called by several sctp_sf_*_abort() functions above.
*/
static sctp_disposition_t <API key>(struct net *net,
sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport)
{
pr_debug("%s: ABORT received (INIT)\n", __func__);
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(sk_err));
/* CMD_INIT_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(error));
return <API key>;
}
/*
* sctp_sf_do_9_2_shut
*
* Section: 9.2
* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
*
* - stop accepting new data from its SCTP user
*
* - verify, by checking the Cumulative TSN Ack field of the chunk,
* that all its outstanding DATA chunks have been received by the
* SHUTDOWN sender.
*
* Once an endpoint as reached the SHUTDOWN-RECEIVED state it MUST NOT
* send a SHUTDOWN in response to a ULP request. And should discard
* subsequent SHUTDOWN chunks.
*
* If there are still outstanding DATA chunks left, the SHUTDOWN
* receiver shall continue to follow normal data transmission
* procedures defined in Section 6 until all outstanding DATA chunks
* are acknowledged; however, the SHUTDOWN receiver MUST NOT accept
* new data from its SCTP user.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
sctp_disposition_t disposition;
struct sctp_ulpevent *ev;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!<API key>(chunk,
sizeof(struct <API key>)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Convert the elaborate header. */
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_shutdownhdr_t));
chunk->subh.shutdown_hdr = sdh;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return <API key>;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return <API key>(net, ep, asoc, type, arg, commands);
/* API 5.3.1.5 SCTP_SHUTDOWN_EVENT
* When a peer sends a SHUTDOWN, SCTP delivers this notification to
* inform the application that it should cease sending data.
*/
ev = <API key>(asoc, 0, GFP_ATOMIC);
if (!ev) {
disposition = <API key>;
goto out;
}
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
* - stop accepting new data from its SCTP user
*
* [This is implicit in the new state.]
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
disposition = <API key>;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = <API key>(net, ep, asoc, type,
arg, commands);
}
if (<API key> == disposition)
goto out;
/* - verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_BE32(chunk->subh.shutdown_hdr->cum_tsn_ack));
out:
return disposition;
}
/*
* <API key>
*
* Once an endpoint has reached the SHUTDOWN-RECEIVED state,
* it MUST NOT send a SHUTDOWN in response to a ULP request.
* The Cumulative TSN Ack of the received SHUTDOWN chunk
* MUST be processed.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!<API key>(chunk,
sizeof(struct <API key>)))
return <API key>(net, ep, asoc, type, arg,
commands);
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return <API key>;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return <API key>(net, ep, asoc, type, arg, commands);
/* verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_BE32(sdh->cum_tsn_ack));
return <API key>;
}
/* RFC 2960 9.2
* If an endpoint is in SHUTDOWN-ACK-SENT state and receives an INIT chunk
* (e.g., if the SHUTDOWN COMPLETE was lost) with source and destination
* transport addresses (either in the IP addresses or in the INIT chunk)
* that belong to this association, it should discard the INIT chunk and
* retransmit the SHUTDOWN ACK chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* Make sure that the chunk has a valid length */
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Since we are not going to really process this INIT, there
* is no point in verifying chunk boundries. Just generate
* the SHUTDOWN ACK.
*/
reply = <API key>(asoc, chunk);
if (NULL == reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-SHUTDOWN timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
nomem:
return <API key>;
}
/*
* sctp_sf_do_ecn_cwr
*
* Section: Appendix A: Explicit Congestion Notification
*
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecn_cwr(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_cwrhdr_t *cwr;
struct sctp_chunk *chunk = arg;
u32 lowest_tsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!<API key>(chunk, sizeof(sctp_ecne_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
cwr = (sctp_cwrhdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_cwrhdr_t));
lowest_tsn = ntohl(cwr->lowest_tsn);
/* Does this CWR ack the last sent congestion notification? */
if (TSN_lte(asoc->last_ecne_tsn, lowest_tsn)) {
/* Stop sending ECNE. */
sctp_add_cmd_sf(commands,
SCTP_CMD_ECN_CWR,
SCTP_U32(lowest_tsn));
}
return <API key>;
}
/*
* sctp_sf_do_ecne
*
* Section: Appendix A: Explicit Congestion Notification
*
* ECN-Echo
*
* RFC 2481 details a specific bit for a receiver to send back in its
* TCP acknowledgements to notify the sender of the Congestion
* Experienced (CE) bit having arrived from the network. For SCTP this
* same indication is made by including the ECNE chunk. This chunk
* contains one data element, i.e. the lowest TSN associated with the IP
* datagram marked with the CE bit.....
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecne(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_ecnehdr_t *ecne;
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
if (!<API key>(chunk, sizeof(sctp_ecne_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
ecne = (sctp_ecnehdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_ecnehdr_t));
/* If this is a newer ECNE than the last CWR packet we sent out */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_ECNE,
SCTP_U32(ntohl(ecne->lowest_tsn)));
return <API key>;
}
/*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of each valid
* DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated within
* 200 ms of the arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to be more
* conservative than the algorithms detailed in this document allow.
* However, an SCTP transmitter MUST NOT be more aggressive than the
* following algorithms allow.
*
* A SCTP receiver MUST NOT generate more than one SACK for every
* incoming packet, other than to update the offered window as the
* receiving application consumes new data.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_arg_t force = SCTP_NOFORCE();
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!<API key>(chunk, sizeof(sctp_data_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case <API key>:
break;
case <API key>:
case <API key>:
SCTP_INC_STATS(net, <API key>);
goto discard_noforce;
case SCTP_IERROR_DUP_TSN:
case <API key>:
SCTP_INC_STATS(net, <API key>);
goto discard_force;
case SCTP_IERROR_NO_DATA:
return <API key>;
case <API key>:
return <API key>(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
if (chunk->chunk_hdr->flags & SCTP_DATA_SACK_IMM)
force = SCTP_FORCE();
if (asoc->timeouts[<API key>]) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
}
/* If this is the last chunk in a packet, we need to count it
* toward sack generation. Note that we need to SACK every
* OTHER packet containing data chunks, EVEN IF WE DISCARD
* THEM. We elect to NOT generate SACK's if the chunk fails
* the verification tag test.
*
* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of
* each valid DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm
* specified in Section 4.2 of [RFC2581] SHOULD be followed.
* Specifically, an acknowledgement SHOULD be generated for at
* least every second packet (not every second DATA chunk)
* received, and SHOULD be generated within 200 ms of the
* arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to
* be more conservative than the algorithms detailed in this
* document allow. However, an SCTP transmitter MUST NOT be
* more aggressive than the following algorithms allow.
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return <API key>;
discard_force:
/* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* When a packet arrives with duplicate DATA chunk(s) and with
* no new DATA chunk(s), the endpoint MUST immediately send a
* SACK with no delay. If a packet arrives with duplicate
* DATA chunk(s) bundled with new DATA chunks, the endpoint
* MAY immediately send a SACK. Normally receipt of duplicate
* DATA chunks will occur when the original SACK chunk was lost
* and the peer's RTO has expired. The duplicate TSN number(s)
* SHOULD be reported in the SACK as duplicate.
*/
/* In our case, we split the MAY SACK advice up whether or not
* the last chunk is a duplicate.'
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return <API key>;
discard_noforce:
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return <API key>;
}
/*
* <API key>
*
* Section: 4 (4)
* (4) In SHUTDOWN-SENT state the endpoint MUST acknowledge any received
* DATA chunks without delay.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
if (!<API key>(chunk, sizeof(sctp_data_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands);
switch (error) {
case <API key>:
case <API key>:
case SCTP_IERROR_DUP_TSN:
case <API key>:
case <API key>:
break;
case SCTP_IERROR_NO_DATA:
return <API key>;
case <API key>:
return <API key>(net, ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
/* Go a head and force a SACK, since we are shutting down. */
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
if (chunk->end_of_packet) {
/* We must delay the chunk creation since the cumulative
* TSN has not been updated yet.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
}
return <API key>;
}
/*
* Section: 6.2 Processing a Received SACK
* D) Any time a SACK arrives, the endpoint performs the following:
*
* i) If Cumulative TSN Ack is less than the Cumulative TSN Ack Point,
* then drop the SACK. Since Cumulative TSN Ack is monotonically
* increasing, a SACK whose Cumulative TSN Ack is less than the
* Cumulative TSN Ack Point indicates an out-of-order SACK.
*
* ii) Set rwnd equal to the newly received a_rwnd minus the number
* of bytes still outstanding after processing the Cumulative TSN Ack
* and the Gap Ack Blocks.
*
* iii) If the SACK is missing a TSN that was previously
* acknowledged via a Gap Ack Block (e.g., the data receiver
* reneged on the data), then mark the corresponding DATA chunk
* as available for retransmit: Mark it as missing for fast
* retransmit as described in Section 7.2.4 and if no retransmit
* timer is running for the destination address to which the DATA
* chunk was originally transmitted, then T3-rtx is started for
* that destination address.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_sackhdr_t *sackh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SACK chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_sack_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Pull the SACK chunk from the data buffer */
sackh = sctp_sm_pull_sack(chunk);
/* Was this a bogus SACK? */
if (!sackh)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
chunk->subh.sack_hdr = sackh;
ctsn = ntohl(sackh->cum_tsn_ack);
/* i) If Cumulative TSN Ack is less than the Cumulative TSN
* Ack Point, then drop the SACK. Since Cumulative TSN
* Ack is monotonically increasing, a SACK whose
* Cumulative TSN Ack is less than the Cumulative TSN Ack
* Point indicates an out-of-order SACK.
*/
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn,
asoc->ctsn_ack_point);
return <API key>;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return <API key>(net, ep, asoc, type, arg, commands);
/* Return this SACK for further processing. */
sctp_add_cmd_sf(commands, <API key>, SCTP_CHUNK(chunk));
/* Note: We do the rest of the work on the PROCESS_SACK
* sideeffect.
*/
return <API key>;
}
/*
* Generate an ABORT in response to a packet.
*
* Section: 8.4 Handle "Out of the blue" Packets, sctpimpguide 2.41
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*
* Verification Tag:
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT. The T bit will be set if the asoc
* is NULL.
*/
abort = sctp_make_abort(asoc, chunk, 0);
if (!abort) {
sctp_ootb_pkt_free(packet);
return <API key>;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
<API key>(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return <API key>;
}
return <API key>;
}
/*
* Received an ERROR chunk from peer. Generate SCTP_REMOTE_ERROR
* event as ULP notification for each cause included in the chunk.
*
* API 5.3.1.3 - SCTP_REMOTE_ERROR
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_operr_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return <API key>(net, ep, asoc, type, arg,
(void *)err, commands);
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(chunk));
return <API key>;
}
/*
* Process an inbound SHUTDOWN ACK.
*
* From Section 9.2:
* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its
* peer, and remove all record of the association.
*
* The return value is the disposition.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* 10.2 H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = <API key>(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* ...send a SHUTDOWN COMPLETE chunk to its peer, */
reply = <API key>(asoc, chunk);
if (!reply)
goto nomem_chunk;
/* Do all the commands now (after allocation), so that we
* have consistent state if memory allocation failes
*/
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer,
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
/* ...and remove all record of the association. */
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return <API key>;
nomem_chunk:
sctp_ulpevent_free(ev);
nomem:
return <API key>;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*/
sctp_disposition_t sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (<API key> == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (<API key> == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Handle an "Out of the blue" SHUTDOWN ACK.
*
* Section: 8.4 5, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* Inputs
* (endpoint, asoc, type, arg, commands)
*
* Outputs
* (sctp_disposition_t)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *shut;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an SHUTDOWN_COMPLETE.
* The T bit will be set if the asoc is NULL.
*/
shut = <API key>(asoc, chunk);
if (!shut) {
sctp_ootb_pkt_free(packet);
return <API key>;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(shut))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
shut->skb->sk = ep->base.sk;
<API key>(packet, shut);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
/* If the chunk length is invalid, we don't want to process
* the reset of the packet.
*/
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* We need to discard the rest of the packet to prevent
* potential bomming attacks from additional bundled chunks.
* This is documented in SCTP Threats ID.
*/
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
return <API key>;
}
/*
* Handle SHUTDOWN ACK in COOKIE_ECHOED or COOKIE_WAIT state.
*
* Verification Tag: 8.5.1 E) Rules for packet carrying a SHUTDOWN ACK
* If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state the
* procedures in section 8.4 SHOULD be followed, in other words it
* should be treated as an Out Of The Blue packet.
* [This means that we do NOT check the Verification Tag on these
* chunks. --piggy ]
*
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
/* Although we do have an association in this case, it corresponds
* to a restarted association. So the packet is treated as an OOTB
* packet and the state function that handles OOTB SHUTDOWN_ACK is
* called with a NULL association.
*/
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_shut_8_4_5(net, ep, NULL, type, arg, commands);
}
/* ADDIP Section 4.2 Upon reception of an ASCONF Chunk. */
sctp_disposition_t sctp_sf_do_asconf(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *asconf_ack = NULL;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *hdr;
__u32 serial;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* ADD-IP: Section 4.1.1
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.<API key>]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.<API key>].
*/
if (!net->sctp.addip_noauth && !chunk->auth)
return <API key>(net, ep, asoc, type, arg, commands);
/* Make sure that the ASCONF ADDIP chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_addip_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
hdr = (sctp_addiphdr_t *)chunk->skb->data;
serial = ntohl(hdr->serial);
/* Verify the ASCONF chunk before processing it. */
if (!sctp_verify_asconf(asoc, chunk, true, &err_param))
return <API key>(net, ep, asoc, type, arg,
(void *)err_param, commands);
/* ADDIP 5.2 E1) Compare the value of the serial number to the value
* the endpoint stored in a new association variable
* 'Peer-Serial-Number'.
*/
if (serial == asoc->peer.addip_serial + 1) {
/* If this is the first instance of ASCONF in the packet,
* we can clean our old ASCONF-ACKs.
*/
if (!chunk->has_asconf)
<API key>(asoc);
/* ADDIP 5.2 E4) When the Sequence Number matches the next one
* expected, process the ASCONF as described below and after
* processing the ASCONF Chunk, append an ASCONF-ACK Chunk to
* the response packet and cache a copy of it (in the event it
* later needs to be retransmitted).
*
* Essentially, do V1-V5.
*/
asconf_ack = sctp_process_asconf((struct sctp_association *)
asoc, chunk);
if (!asconf_ack)
return <API key>;
} else if (serial < asoc->peer.addip_serial + 1) {
/* ADDIP 5.2 E2)
* If the value found in the Sequence Number is less than the
* ('Peer- Sequence-Number' + 1), simply skip to the next
* ASCONF, and include in the outbound response packet
* any previously cached ASCONF-ACK response that was
* sent and saved that matches the Sequence Number of the
* ASCONF. Note: It is possible that no cached ASCONF-ACK
* Chunk exists. This will occur when an older ASCONF
* arrives out of order. In such a case, the receiver
* should skip the ASCONF Chunk and not include ASCONF-ACK
* Chunk for that chunk.
*/
asconf_ack = <API key>(asoc, hdr->serial);
if (!asconf_ack)
return <API key>;
/* Reset the transport so that we select the correct one
* this time around. This is to make sure that we don't
* accidentally use a stale transport that's been removed.
*/
asconf_ack->transport = NULL;
} else {
/* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since
* it must be either a stale packet or from an attacker.
*/
return <API key>;
}
/* ADDIP 5.2 E6) The destination address of the SCTP packet
* containing the ASCONF-ACK Chunks MUST be the source address of
* the SCTP packet that held the ASCONF Chunks.
*
* To do this properly, we'll set the destination address of the chunk
* and at the transmit time, will try look up the transport to use.
* Since ASCONFs may be bundled, the correct transport may not be
* created until we process the entire packet, thus this workaround.
*/
asconf_ack->dest = chunk->source;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack));
if (asoc->new_transport) {
sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands);
((struct sctp_association *)asoc)->new_transport = NULL;
}
return <API key>;
}
/*
* ADDIP Section 4.3 General rules for address manipulation
* When building TLV parameters for the ASCONF Chunk that will add or
* delete IP addresses the D0 to D13 rules should be applied:
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *asconf_ack = arg;
struct sctp_chunk *last_asconf = asoc->addip_last_asconf;
struct sctp_chunk *abort;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *addip_hdr;
__u32 sent_serial, rcvd_serial;
if (!sctp_vtag_verify(asconf_ack, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* ADD-IP, Section 4.1.2:
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.<API key>]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.<API key>].
*/
if (!net->sctp.addip_noauth && !asconf_ack->auth)
return <API key>(net, ep, asoc, type, arg, commands);
/* Make sure that the ADDIP chunk has a valid length. */
if (!<API key>(asconf_ack, sizeof(sctp_addip_chunk_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data;
rcvd_serial = ntohl(addip_hdr->serial);
/* Verify the ASCONF-ACK chunk before processing it. */
if (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param))
return <API key>(net, ep, asoc, type, arg,
(void *)err_param, commands);
if (last_asconf) {
addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr;
sent_serial = ntohl(addip_hdr->serial);
} else {
sent_serial = asoc->addip_serial - 1;
}
/* D0) If an endpoint receives an ASCONF-ACK that is greater than or
* equal to the next serial number to be used but no ASCONF chunk is
* outstanding the endpoint MUST ABORT the association. Note that a
* sequence number is greater than if it is no more than 2^^31-1
* larger than the current sequence number (using serial arithmetic).
*/
if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&
!(asoc->addip_last_asconf)) {
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, <API key>, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
if (!<API key>((struct sctp_association *)asoc,
asconf_ack)) {
/* Successfully processed ASCONF_ACK. We can
* release the next asconf if we have one.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return <API key>;
}
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
return <API key>;
}
/*
* PR-SCTP Section 3.6 Receiver Side Implementation of PR-SCTP
*
* When a FORWARD TSN chunk arrives, the data receiver MUST first update
* its cumulative TSN point to the value carried in the FORWARD TSN
* chunk, and then MUST further advance its cumulative TSN point locally
* if possible.
* After the above processing, the data receiver MUST stop reporting any
* missing TSNs earlier than or equal to the new cumulative TSN point.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_fwd_tsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has valid length. */
if (!<API key>(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return <API key>(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto discard_noforce;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto discard_noforce;
}
sctp_add_cmd_sf(commands, <API key>, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(chunk));
/* Count this as receiving DATA. */
if (asoc->timeouts[<API key>]) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
}
/* FIXME: For now send a SACK, but DATA processing may
* send another.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE());
return <API key>;
discard_noforce:
return <API key>;
}
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has a valid length. */
if (!<API key>(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return <API key>(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto gen_shutdown;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto gen_shutdown;
}
sctp_add_cmd_sf(commands, <API key>, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(chunk));
/* Go a head and force a SACK, since we are shutting down. */
gen_shutdown:
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
return <API key>;
}
/*
* SCTP-AUTH Section 6.3 Receiving authenticated chukns
*
* The receiver MUST use the HMAC algorithm indicated in the HMAC
* Identifier field. If this algorithm was not specified by the
* receiver in the HMAC-ALGO parameter in the INIT or INIT-ACK chunk
* during association setup, the AUTH chunk and all chunks after it MUST
* be discarded and an ERROR chunk SHOULD be sent with the error cause
* defined in Section 4.1.
*
* If an endpoint with no shared key receives a Shared Key Identifier
* other than 0, it MUST silently discard all authenticated chunks. If
* the endpoint has at least one endpoint pair shared key for the peer,
* it MUST use the key specified by the Shared Key Identifier if a
* key has been configured for that Shared Key Identifier. If no
* endpoint pair shared key has been configured for that Shared Key
* Identifier, all authenticated chunks MUST be silently discarded.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
static sctp_ierror_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk)
{
struct sctp_authhdr *auth_hdr;
struct sctp_hmac *hmac;
unsigned int sig_len;
__u16 key_id;
__u8 *save_digest;
__u8 *digest;
/* Pull in the auth header, so we can do some more verification */
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
chunk->subh.auth_hdr = auth_hdr;
skb_pull(chunk->skb, sizeof(struct sctp_authhdr));
/* Make sure that we support the HMAC algorithm from the auth
* chunk.
*/
if (!sctp_<API key>(asoc, auth_hdr->hmac_id))
return <API key>;
/* Make sure that the provided shared key identifier has been
* configured
*/
key_id = ntohs(auth_hdr->shkey_id);
if (key_id != asoc->active_key_id && !sctp_auth_get_shkey(asoc, key_id))
return <API key>;
/* Make sure that the length of the signature matches what
* we expect.
*/
sig_len = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_auth_chunk_t);
hmac = sctp_auth_get_hmac(ntohs(auth_hdr->hmac_id));
if (sig_len != hmac->hmac_len)
return <API key>;
/* Now that we've done validation checks, we can compute and
* verify the hmac. The steps involved are:
* 1. Save the digest from the chunk.
* 2. Zero out the digest in the chunk.
* 3. Compute the new digest
* 4. Compare saved and new digests.
*/
digest = auth_hdr->hmac;
skb_pull(chunk->skb, sig_len);
save_digest = kmemdup(digest, sig_len, GFP_ATOMIC);
if (!save_digest)
goto nomem;
memset(digest, 0, sig_len);
<API key>(asoc, chunk->skb,
(struct sctp_auth_chunk *)chunk->chunk_hdr,
GFP_ATOMIC);
/* Discard the packet if the digests do not match */
if (memcmp(save_digest, digest, sig_len)) {
kfree(save_digest);
return SCTP_IERROR_BAD_SIG;
}
kfree(save_digest);
chunk->auth = 1;
return <API key>;
nomem:
return SCTP_IERROR_NOMEM;
}
sctp_disposition_t sctp_sf_eat_auth(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_authhdr *auth_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *err_chunk;
sctp_ierror_t error;
/* Make sure that the peer has AUTH capable */
if (!asoc->peer.auth_capable)
return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands);
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, <API key>,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the AUTH chunk has valid length. */
if (!<API key>(chunk, sizeof(struct sctp_auth_chunk)))
return <API key>(net, ep, asoc, type, arg,
commands);
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
error = <API key>(net, ep, asoc, type, chunk);
switch (error) {
case <API key>:
/* Generate the ERROR chunk and discard the rest
* of the packet
*/
err_chunk = sctp_make_op_error(asoc, chunk,
<API key>,
&auth_hdr->hmac_id,
sizeof(__u16), 0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Fall Through */
case <API key>:
case SCTP_IERROR_BAD_SIG:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case <API key>:
return <API key>(net, ep, asoc, type, arg,
commands);
case SCTP_IERROR_NOMEM:
return <API key>;
default: /* Prevent gcc warnings */
break;
}
if (asoc->active_key_id != ntohs(auth_hdr->shkey_id)) {
struct sctp_ulpevent *ev;
ev = <API key>(asoc, ntohs(auth_hdr->shkey_id),
SCTP_AUTH_NEWKEY, GFP_ATOMIC);
if (!ev)
return -ENOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return <API key>;
}
/*
* Process an unknown chunk.
*
* Section: 3.2. Also, 2.1 in the implementor's guide.
*
* Chunk Types are encoded such that the highest-order two bits specify
* the action that must be taken if the processing endpoint does not
* recognize the Chunk Type.
*
* 00 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it.
*
* 01 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it, and report the unrecognized
* chunk in an 'Unrecognized Chunk Type'.
*
* 10 - Skip this chunk and continue processing.
*
* 11 - Skip this chunk and continue processing, but report in an ERROR
* Chunk using the 'Unrecognized Chunk Type' cause of error.
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_unk_chunk(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *unk_chunk = arg;
struct sctp_chunk *err_chunk;
sctp_chunkhdr_t *hdr;
pr_debug("%s: processing unknown chunk id:%d\n", __func__, type.chunk);
if (!sctp_vtag_verify(unk_chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!<API key>(unk_chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
switch (type.chunk & <API key>) {
case <API key>:
/* Discard the packet. */
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case <API key>:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
<API key>, hdr,
WORD_ROUND(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Discard the packet. */
sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
return <API key>;
case <API key>:
/* Skip the chunk. */
return <API key>;
case <API key>:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
<API key>, hdr,
WORD_ROUND(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Skip the chunk. */
return <API key>;
default:
break;
}
return <API key>;
}
/*
* Discard the chunk.
*
* Section: 0.2, 5.2.3, 5.2.5, 5.2.6, 6.0, 8.4.6, 8.5.1c, 9.2
* [Too numerous to mention...]
* Verification Tag: No verification needed.
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
pr_debug("%s: chunk:%d is discarded\n", __func__, type.chunk);
return <API key>;
}
/*
* Discard the whole packet.
*
* Section: 8.4 2)
*
* 2) If the OOTB packet contains an ABORT chunk, the receiver MUST
* silently discard the OOTB packet and take no further action.
*
* Verification Tag: No verification necessary
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_pdiscard(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(net, <API key>);
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
return <API key>;
}
/*
* The other end is violating protocol.
*
* Section: Not specified
* Verification Tag: Not specified
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* We simply tag the chunk as a violation. The state machine will log
* the violation and continue.
*/
sctp_disposition_t sctp_sf_violation(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length. */
if (!<API key>(chunk, sizeof(sctp_chunkhdr_t)))
return <API key>(net, ep, asoc, type, arg,
commands);
return <API key>;
}
/*
* Common function to handle a protocol violation.
*/
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort = NULL;
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = <API key>(asoc, chunk, payload, paylen);
if (!abort)
goto nomem;
if (asoc) {
/* Treat INIT-ACK as a special case during COOKIE-WAIT. */
if (chunk->chunk_hdr->type == SCTP_CID_INIT_ACK &&
!asoc->peer.i.init_tag) {
<API key> *initack;
initack = (<API key> *)chunk->chunk_hdr;
if (!<API key>(chunk,
sizeof(<API key>)))
abort->chunk_hdr->flags |= SCTP_CHUNK_FLAG_T;
else {
unsigned int inittag;
inittag = ntohl(initack->init_hdr.init_tag);
sctp_add_cmd_sf(commands, <API key>,
SCTP_U32(inittag));
}
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, <API key>);
if (asoc->state <= <API key>) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
}
} else {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (!packet)
goto nomem_pkt;
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
abort->skb->sk = ep->base.sk;
<API key>(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
}
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return <API key>;
nomem_pkt:
sctp_chunk_free(abort);
nomem:
return <API key>;
}
/*
* Handle a protocol violation when the chunk length is invalid.
* "Invalid" length is identified as smaller than the minimal length a
* given chunk can be. For example, a SACK chunk has invalid length
* if its length is set to be smaller than the size of sctp_sack_chunk_t.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*
* Section: Not specified
* Verification Tag: Nothing to do
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (reply_msg, msg_up, counters)
*
* Generate an ABORT chunk and terminate the association.
*/
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The following chunk had invalid length:";
return <API key>(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/*
* Handle a protocol violation when the parameter length is invalid.
* If the length is smaller than the minimum length of a given parameter,
* or accumulated length in multi parameters exceeds the end of the chunk,
* the length is considered as invalid.
*/
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_paramhdr *param = ext;
struct sctp_chunk *abort = NULL;
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = <API key>(asoc, chunk, param);
if (!abort)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(net, <API key>);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return <API key>;
nomem:
return <API key>;
}
/* Handle a protocol violation when the peer trying to advance the
* cumulative tsn ack to a point beyond the max tsn currently sent.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*/
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The cumulative tsn ack beyond the max tsn currently sent:";
return <API key>(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/* Handle protocol violation of an invalid chunk bundling. For example,
* when we have an association and we receive bundled INIT-ACK, or
* SHUDOWN-COMPLETE, our peer is clearly violationg the "MUST NOT bundle"
* statement from the specs. Additionally, there might be an attacker
* on the path and we may not want to continue this communication.
*/
static sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[] = "The following chunk violates protocol:";
if (!asoc)
return sctp_sf_violation(net, ep, asoc, type, arg, commands);
return <API key>(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/*
* sctp_sf_do_prm_asoc
*
* Section: 10.1 ULP-to-SCTP
* B) Associate
*
* Format: ASSOCIATE(local SCTP instance name, destination transport addr,
* outbound stream count)
* -> association id [,destination transport addr list] [,outbound stream
* count]
*
* This primitive allows the upper layer to initiate an association to a
* specific peer endpoint.
*
* The peer endpoint shall be specified by one of the transport addresses
* which defines the endpoint (see Section 1.4). If the local SCTP
* instance has not been initialized, the ASSOCIATE is considered an
* error.
* [This is not relevant for the kernel implementation since we do all
* initialization at boot time. It we hadn't initialized we wouldn't
* get anywhere near this code.]
*
* An association id, which is a local handle to the SCTP association,
* will be returned on successful establishment of the association. If
* SCTP is not able to open an SCTP association with the peer endpoint,
* an error is returned.
* [In the kernel implementation, the struct sctp_association needs to
* be created BEFORE causing this primitive to run.]
*
* Other association parameters may be returned, including the
* complete destination transport addresses of the peer as well as the
* outbound stream count of the local endpoint. One of the transport
* address from the returned destination addresses will be selected by
* the local endpoint as default primary path for sending SCTP packets
* to this peer. The returned "destination transport addr list" can
* be used by the ULP to change the default primary path or to force
* sending a packet to a specific transport address. [All of this
* stuff happens when the INIT ACK arrives. This is a NON-BLOCKING
* function.]
*
* Mandatory attributes:
*
* o local SCTP instance name - obtained from the INITIALIZE operation.
* [This is the argument asoc.]
* o destination transport addr - specified as one of the transport
* addresses of the peer endpoint with which the association is to be
* established.
* [This is asoc->peer.active_path.]
* o outbound stream count - the number of outbound streams the ULP
* would like to open towards this peer endpoint.
* [BUG: This is not currently implemented.]
* Optional attributes:
*
* None.
*
* The return value is a disposition.
*/
sctp_disposition_t sctp_sf_do_prm_asoc(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl;
struct sctp_association *my_asoc;
/* The comment below says that we enter COOKIE-WAIT AFTER
* sending the INIT, but that doesn't actually work in our
* implementation...
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* A) "A" first sends an INIT chunk to "Z". In the INIT, "A"
* must provide its Verification Tag (Tag_A) in the Initiate
* Tag field. Tag_A SHOULD be a random number in the range of
* 1 to 4294967295 (see 5.3.1 for Tag value selection). ...
*/
repl = sctp_make_init(asoc, &asoc->base.bind_addr, GFP_ATOMIC, 0);
if (!repl)
goto nomem;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(repl));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
my_asoc = (struct sctp_association *)asoc;
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(my_asoc));
/* After sending the INIT, "A" starts the T1-init timer and
* enters the COOKIE-WAIT state.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return <API key>;
nomem:
return <API key>;
}
/*
* Process the SEND primitive.
*
* Section: 10.1 ULP-to-SCTP
* E) Send
*
* Format: SEND(association id, buffer address, byte count [,context]
* [,stream id] [,life time] [,destination transport address]
* [,unorder flag] [,no-bundle flag] [,payload protocol-id] )
* -> result
*
* This is the main method to send user data via SCTP.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o buffer address - the location where the user message to be
* transmitted is stored;
*
* o byte count - The size of the user data in number of bytes;
*
* Optional attributes:
*
* o context - an optional 32 bit integer that will be carried in the
* sending failure notification to the ULP if the transportation of
* this User Message fails.
*
* o stream id - to indicate which stream to send the data on. If not
* specified, stream 0 will be used.
*
* o life time - specifies the life time of the user data. The user data
* will not be sent by SCTP after the life time expires. This
* parameter can be used to avoid efforts to transmit stale
* user messages. SCTP notifies the ULP if the data cannot be
* initiated to transport (i.e. sent to the destination via SCTP's
* send primitive) within the life time variable. However, the
* user data will be transmitted if SCTP has attempted to transmit a
* chunk before the life time expired.
*
* o destination transport address - specified as one of the destination
* transport addresses of the peer endpoint to which this packet
* should be sent. Whenever possible, SCTP should use this destination
* transport address for sending the packets, instead of the current
* primary path.
*
* o unorder flag - this flag, if present, indicates that the user
* would like the data delivered in an unordered fashion to the peer
* (i.e., the U flag is set to 1 on all DATA chunks carrying this
* message).
*
* o no-bundle flag - instructs SCTP not to bundle this user data with
* other outbound DATA chunks. SCTP MAY still bundle even when
* this flag is present, when faced with network congestion.
*
* o payload protocol-id - A 32 bit unsigned integer that is to be
* passed to the peer indicating the type of payload protocol data
* being transmitted. This value is passed as opaque data by SCTP.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_prm_send(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_datamsg *msg = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_MSG, SCTP_DATAMSG(msg));
return <API key>;
}
/*
* Process the SHUTDOWN primitive.
*
* Section: 10.1:
* C) Shutdown
*
* Format: SHUTDOWN(association id)
* -> result
*
* Gracefully closes an association. Any locally queued user data
* will be delivered to the peer. The association will be terminated only
* after the peer acknowledges all the SCTP packets sent. A success code
* will be returned on successful termination of the association. If
* attempting to terminate the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
disposition = <API key>;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = <API key>(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*
* Process the ABORT primitive.
*
* Section: 10.1:
* C) Abort
*
* Format: Abort(association id [, cause code])
* -> result
*
* Ungracefully closes an association. Any locally queued user data
* will be discarded and an ABORT chunk is sent to the peer. A success code
* will be returned on successful abortion of the association. If
* attempting to abort the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* o cause code - reason of the abort to be passed to the peer
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* From 9.1 Abort of an Association
* Upon receipt of the ABORT primitive from its upper
* layer, the endpoint enters CLOSED state and
* discard all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
struct sctp_chunk *abort = arg;
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, <API key>, SCTP_ERROR(-EINVAL));
return <API key>;
}
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, <API key>,
SCTP_ERROR(-ESHUTDOWN));
return <API key>;
}
/*
* <API key>
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return <API key>;
}
/*
* <API key>
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* <API key>
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *abort = arg;
/* Stop T1-init timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(<API key>));
return <API key>;
}
/*
* <API key>
*
* Section: 4 Note: 3
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* <API key>
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-PENDING state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* <API key>
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-SENT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* <API key>
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return <API key>(net, ep, asoc, type, arg, commands);
}
/*
* Process the REQUESTHEARTBEAT primitive
*
* 10.1 ULP-to-SCTP
* J) Request Heartbeat
*
* Format: REQUESTHEARTBEAT(association id, destination transport address)
*
* -> result
*
* Instructs the local endpoint to perform a HeartBeat on the specified
* destination transport address of the given association. The returned
* result should indicate whether the transmission of the HEARTBEAT
* chunk to the destination address is successful.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o destination transport address - the transport address of the
* association on which a heartbeat should be issued.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
if (<API key> == sctp_sf_heartbeat(ep, asoc, type,
(struct sctp_transport *)arg, commands))
return <API key>;
/*
* RFC 2960 (bis), section 8.3
*
* D) Request an on-demand HEARTBEAT on a specific destination
* transport address of a given association.
*
* The endpoint should increment the respective error counter of
* the destination transport address each time a HEARTBEAT is sent
* to that address and not acknowledged within one RTO.
*
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TRANSPORT(arg));
return <API key>;
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do A1 to A9
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk));
return <API key>;
}
/*
* Ignore the primitive event
*
* The return value is the disposition of the primitive.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: primitive type:%d is ignored\n", __func__,
type.primitive);
return <API key>;
}
/*
* When the SCTP stack has no more user data to send or retransmit, this
* notification is given to the user. Also, at the time when a user app
* subscribes to this event, if there is no data to be sent or
* retransmit, the stack will immediately send up this notification.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_ulpevent *event;
event = <API key>(asoc, GFP_ATOMIC);
if (!event)
return <API key>;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(event));
return <API key>;
}
/*
* Start the shutdown negotiation.
*
* From Section 9.2:
* Once all its outstanding data has been acknowledged, the endpoint
* shall send a SHUTDOWN chunk to its peer including in the Cumulative
* TSN Ack field the last sequential TSN it has received from the peer.
* It shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
* state. If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* The return value is the disposition.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply;
/* Once all its outstanding data has been acknowledged, the
* endpoint shall send a SHUTDOWN chunk to its peer including
* in the Cumulative TSN Ack field the last sequential TSN it
* has received from the peer.
*/
reply = sctp_make_shutdown(asoc, NULL);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN chunk and the timeout for the
* T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* It shall then start the T2-shutdown timer */
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
/* RFC 4960 Section 9.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
if (asoc->timeouts[<API key>])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
/* and enter the SHUTDOWN-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
nomem:
return <API key>;
}
/*
* Generate a SHUTDOWN ACK now that everything is SACK'd.
*
* From Section 9.2:
*
* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK and start a T2-shutdown timer of its own,
* entering the SHUTDOWN-ACK-SENT state. If the timer expires, the
* endpoint must re-send the SHUTDOWN ACK.
*
* The return value is the disposition.
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* There are 2 ways of getting here:
* 1) called in response to a SHUTDOWN chunk
* 2) called when <API key> event is issued.
*
* For the case (2), the arg parameter is set to NULL. We need
* to check that we have a chunk before accessing it's fields.
*/
if (chunk) {
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!<API key>(chunk, sizeof(struct <API key>)))
return <API key>(net, ep, asoc, type, arg,
commands);
}
/* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK ...
*/
reply = <API key>(asoc, chunk);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and start/restart a T2-shutdown timer of its own, */
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
if (asoc->timeouts[<API key>])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
/* Enter the SHUTDOWN-ACK-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
nomem:
return <API key>;
}
/*
* Ignore the event defined as other
*
* The return value is the disposition of the event.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: the event other type:%d is ignored\n",
__func__, type.other);
return <API key>;
}
/*
* RTX Timeout
*
* Section: 6.3.3 Handle T3-rtx Expiration
*
* Whenever the retransmission timer T3-rtx expires for a destination
* address, do the following:
* [See below]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = arg;
SCTP_INC_STATS(net, <API key>);
if (asoc->overall_error_count >= asoc->max_retrans) {
if (asoc->peer.<API key> &&
asoc->state == <API key>) {
/*
* We are here likely because the receiver had its rwnd
* closed for a while and we have not been able to
* transmit the locally queued data within the maximum
* retransmission attempts limit. Start the T5
* shutdown guard timer to give the receiver one last
* chance and some additional time to recover before
* aborting.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
}
/* E1) For the destination address for which the timer
* expires, adjust its ssthresh with rules defined in Section
* 7.2.3 and set the cwnd <- MTU.
*/
/* E2) For the destination address for which the timer
* expires, set RTO <- RTO * 2 ("back off the timer"). The
* maximum value discussed in rule C7 above (RTO.max) may be
* used to provide an upper bound to this doubling operation.
*/
/* E3) Determine how many of the earliest (i.e., lowest TSN)
* outstanding DATA chunks for the address for which the
* T3-rtx has expired will fit into a single packet, subject
* to the MTU constraint for the path corresponding to the
* destination transport address to which the retransmission
* is being sent (this may be different from the address for
* which the timer expires [see Section 6.4]). Call this
* value K. Bundle and retransmit those K DATA chunks in a
* single packet to the destination endpoint.
*
* Note: Any DATA chunks that were sent to the address for
* which the T3-rtx timer expired but did not fit in one MTU
* (rule E3 above), should be marked for retransmission and
* sent as soon as cwnd allows (normally when a SACK arrives).
*/
/* Do some failure management (Section 8.2). */
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
/* NB: Rules E4 and F1 are implicit in R1. */
sctp_add_cmd_sf(commands, SCTP_CMD_RETRAN, SCTP_TRANSPORT(transport));
return <API key>;
}
/*
* Generate delayed SACK on timeout
*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated
* within 200 ms of the arrival of any unacknowledged DATA chunk. In
* some situations it may be beneficial for an SCTP transmitter to be
* more conservative than the algorithms detailed in this document
* allow. However, an SCTP transmitter MUST NOT be more aggressive than
* the following algorithms allow.
*/
sctp_disposition_t sctp_sf_do_6_2_sack(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(net, <API key>);
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return <API key>;
}
/*
* <API key>
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 2) If the T1-init timer expires, the endpoint MUST retransmit INIT
* and re-start the T1-init timer without changing state. This MUST
* be repeated up to 'Max.Init.Retransmits' times. After that, the
* endpoint MUST abort the initialization process and report the
* error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
pr_debug("%s: timer T1 expired (INIT)\n", __func__);
SCTP_INC_STATS(net, <API key>);
if (attempts <= asoc->max_init_attempts) {
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
repl = sctp_make_init(asoc, bp, GFP_ATOMIC, 0);
if (!repl)
return <API key>;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
pr_debug("%s: giving up on INIT, attempts:%d "
"max_init_attempts:%d\n", __func__, attempts,
asoc->max_init_attempts);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return <API key>;
}
return <API key>;
}
/*
* <API key>
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 3) If the T1-cookie timer expires, the endpoint MUST retransmit
* COOKIE ECHO and re-start the T1-cookie timer without changing
* state. This MUST be repeated up to 'Max.Init.Retransmits' times.
* After that, the endpoint MUST abort the initialization process and
* report the error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
int attempts = asoc->init_err_counter + 1;
pr_debug("%s: timer T1 expired (COOKIE-ECHO)\n", __func__);
SCTP_INC_STATS(net, <API key>);
if (attempts <= asoc->max_init_attempts) {
repl = <API key>(asoc, NULL);
if (!repl)
return <API key>;
sctp_add_cmd_sf(commands, <API key>,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return <API key>;
}
return <API key>;
}
/* RFC2960 9.2 If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* An endpoint should limit the number of retransmissions of the
* SHUTDOWN chunk to the protocol parameter 'Association.Max.Retrans'.
* If this threshold is exceeded the endpoint should destroy the TCB and
* MUST report the peer endpoint unreachable to the upper layer (and
* thus the association enters the CLOSED state). The reception of any
* packet from its peer (i.e. as the peer sends all of its queued DATA
* chunks) should clear the endpoint's retransmission count and restart
* the T2-Shutdown timer, giving its peer ample opportunity to transmit
* all of its queued DATA chunks that have not yet been sent.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T2 expired\n", __func__);
SCTP_INC_STATS(net, <API key>);
((struct sctp_association *)asoc)->shutdown_retries++;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* Note: CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
switch (asoc->state) {
case <API key>:
reply = sctp_make_shutdown(asoc, NULL);
break;
case <API key>:
reply = <API key>(asoc, NULL);
break;
default:
BUG();
break;
}
if (!reply)
goto nomem;
/* Do some failure management (Section 8.2).
* If we remove the transport an SHUTDOWN was last sent to, don't
* do failure management.
*/
if (asoc-><API key>)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(asoc-><API key>));
/* Set the transport for the SHUTDOWN/ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* Restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return <API key>;
nomem:
return <API key>;
}
/*
* ADDIP Section 4.1 ASCONF CHunk Procedures
* If the T4 RTO timer expires the endpoint should do B1 to B5
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = asoc->addip_last_asconf;
struct sctp_transport *transport = chunk->transport;
SCTP_INC_STATS(net, <API key>);
/* ADDIP 4.1 B1) Increment the error counters and perform path failure
* detection on the appropriate destination address as defined in
* RFC2960 [5] section 8.1 and 8.2.
*/
if (transport)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(transport));
/* Reconfig T4 timer and transport. */
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
/* ADDIP 4.1 B2) Increment the association error counters and perform
* endpoint failure detection on the association as defined in
* RFC2960 [5] section 8.1 and 8.2.
* association error counter is incremented in SCTP_CMD_STRIKE.
*/
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(<API key>));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
}
/* ADDIP 4.1 B3) Back-off the destination address RTO value to which
* the ASCONF chunk was sent by doubling the RTO timer value.
* This is done in SCTP_CMD_STRIKE.
*/
/* ADDIP 4.1 B4) Re-transmit the ASCONF Chunk last sent and if possible
* choose an alternate destination address (please refer to RFC2960
* [5] section 6.4.1). An endpoint MUST NOT add new parameters to this
* chunk, it MUST be the same (including its serial number) as the last
* ASCONF sent.
*/
sctp_chunk_hold(asoc->addip_last_asconf);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(asoc->addip_last_asconf));
/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different
* destination is selected, then the RTO used will be that of the new
* destination address.
*/
sctp_add_cmd_sf(commands, <API key>,
SCTP_TO(<API key>));
return <API key>;
}
/* sctpimpguide-05 Section 2.12.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
* At the expiration of this timer the sender SHOULD abort the association
* by sending an ABORT chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
pr_debug("%s: timer T5 expired\n", __func__);
SCTP_INC_STATS(net, <API key>);
reply = sctp_make_abort(asoc, NULL, 0);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return <API key>;
nomem:
return <API key>;
}
/* Handle expiration of AUTOCLOSE timer. When the autoclose timer expires,
* the association is automatically closed by starting the shutdown process.
* The work that needs to be done is same as when SHUTDOWN is initiated by
* the user. So this routine looks same as <API key>().
*/
sctp_disposition_t <API key>(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
SCTP_INC_STATS(net, <API key>);
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(<API key>));
disposition = <API key>;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = <API key>(net, ep, asoc, type,
arg, commands);
}
return disposition;
}
/*
* This table entry is not implemented.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_not_impl(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return <API key>;
}
/*
* This table entry represents a bug.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_bug(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return <API key>;
}
/*
* This table entry represents the firing of a timer in the wrong state.
* Since timer deletion cannot be guaranteed a timer 'may' end up firing
* when the association is in the wrong state. This event should
* be ignored, so as to prevent any rearming of the timer.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
pr_debug("%s: timer %d ignored\n", __func__, type.chunk);
return <API key>;
}
/* Pull the SACK chunk based on the SACK header. */
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk)
{
struct sctp_sackhdr *sack;
unsigned int len;
__u16 num_blocks;
__u16 num_dup_tsns;
/* Protect ourselves from reading too far into
* the skb from a bogus sender.
*/
sack = (struct sctp_sackhdr *) chunk->skb->data;
num_blocks = ntohs(sack->num_gap_ack_blocks);
num_dup_tsns = ntohs(sack->num_dup_tsns);
len = sizeof(struct sctp_sackhdr);
len += (num_blocks + num_dup_tsns) * sizeof(__u32);
if (len > chunk->skb->len)
return NULL;
skb_pull(chunk->skb, len);
return sack;
}
/* Create an ABORT packet to be sent as a response, with the specified
* error causes.
*/
static struct sctp_packet *sctp_abort_pkt_new(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen)
{
struct sctp_packet *packet;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
/* Make an ABORT.
* The T bit will be set if the asoc is NULL.
*/
abort = sctp_make_abort(asoc, chunk, paylen);
if (!abort) {
sctp_ootb_pkt_free(packet);
return NULL;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Add specified error causes, i.e., payload, to the
* end of the chunk.
*/
sctp_addto_chunk(abort, paylen, payload);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
<API key>(packet, abort);
}
return packet;
}
/* Allocate a packet for responding in the OOTB conditions. */
static struct sctp_packet *sctp_ootb_pkt_new(struct net *net,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_packet *packet;
struct sctp_transport *transport;
__u16 sport;
__u16 dport;
__u32 vtag;
/* Get the source and destination port from the inbound packet. */
sport = ntohs(chunk->sctp_hdr->dest);
dport = ntohs(chunk->sctp_hdr->source);
/* The V-tag is going to be the same as the inbound packet if no
* association exists, otherwise, use the peer's vtag.
*/
if (asoc) {
/* Special case the INIT-ACK as there is no peer's vtag
* yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT_ACK:
{
<API key> *initack;
initack = (<API key> *)chunk->chunk_hdr;
vtag = ntohl(initack->init_hdr.init_tag);
break;
}
default:
vtag = asoc->peer.i.init_tag;
break;
}
} else {
/* Special case the INIT and stale COOKIE_ECHO as there is no
* vtag yet.
*/
switch (chunk->chunk_hdr->type) {
case SCTP_CID_INIT:
{
sctp_init_chunk_t *init;
init = (sctp_init_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(init->init_hdr.init_tag);
break;
}
default:
vtag = ntohl(chunk->sctp_hdr->vtag);
break;
}
}
/* Make a transport for the bucket, Eliza... */
transport = sctp_transport_new(net, sctp_source(chunk), GFP_ATOMIC);
if (!transport)
goto nomem;
/* Cache a route for the transport with the chunk's destination as
* the source address.
*/
<API key>(transport, (union sctp_addr *)&chunk->dest,
sctp_sk(net->sctp.ctl_sock));
packet = sctp_packet_init(&transport->packet, transport, sport, dport);
packet = sctp_packet_config(packet, vtag, 0);
return packet;
nomem:
return NULL;
}
/* Free the packet allocated earlier for responding in the OOTB condition. */
void sctp_ootb_pkt_free(struct sctp_packet *packet)
{
sctp_transport_free(packet->transport);
}
/* Send a stale cookie error when a invalid COOKIE ECHO chunk is found */
static void <API key>(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk)
{
struct sctp_packet *packet;
if (err_chunk) {
packet = sctp_ootb_pkt_new(net, asoc, chunk);
if (packet) {
struct sctp_signed_cookie *cookie;
/* Override the OOTB vtag from the cookie. */
cookie = chunk->subh.cookie_hdr;
packet->vtag = cookie->c.peer_vtag;
/* Set the skb to the belonging sock for accounting. */
err_chunk->skb->sk = ep->base.sk;
<API key>(packet, err_chunk);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(net, <API key>);
} else
sctp_chunk_free (err_chunk);
}
}
/* Process a data chunk */
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands)
{
sctp_datahdr_t *data_hdr;
struct sctp_chunk *err;
size_t datalen;
sctp_verb_t deliver;
int tmp;
__u32 tsn;
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
u16 ssn;
u16 sid;
u8 ordered = 0;
data_hdr = chunk->subh.data_hdr = (sctp_datahdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_datahdr_t));
tsn = ntohl(data_hdr->tsn);
pr_debug("%s: TSN 0x%x\n", __func__, tsn);
/* ASSERT: Now skb->data is really the user data. */
/* Process ECN based congestion.
*
* Since the chunk structure is reused for all chunks within
* a packet, we use ecn_ce_done to track if we've already
* done CE processing for this packet.
*
* We need to do ECN processing even if we plan to discard the
* chunk later.
*/
if (asoc->peer.ecn_capable && !chunk->ecn_ce_done) {
struct sctp_af *af = SCTP_INPUT_CB(chunk->skb)->af;
chunk->ecn_ce_done = 1;
if (af->is_ce(sctp_gso_headskb(chunk->skb))) {
/* Do real work as sideffect. */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CE,
SCTP_U32(tsn));
}
}
tmp = sctp_tsnmap_check(&asoc->peer.tsn_map, tsn);
if (tmp < 0) {
/* The TSN is too high--silently discard the chunk and
* count on it getting retransmitted later.
*/
if (chunk->asoc)
chunk->asoc->stats.outofseqtsns++;
return <API key>;
} else if (tmp > 0) {
/* This is a duplicate. Record it. */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_DUP, SCTP_U32(tsn));
return SCTP_IERROR_DUP_TSN;
}
/* This is a new TSN. */
/* Discard if there is no room in the receive window.
* Actually, allow a little bit of overflow (up to a MTU).
*/
datalen = ntohs(chunk->chunk_hdr->length);
datalen -= sizeof(sctp_data_chunk_t);
deliver = SCTP_CMD_CHUNK_ULP;
/* Think about partial delivery. */
if ((datalen >= asoc->rwnd) && (!asoc->ulpq.pd_mode)) {
/* Even if we don't accept this chunk there is
* memory pressure.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
}
/* Spill over rwnd a little bit. Note: While allowed, this spill over
* seems a bit troublesome in that frag_point varies based on
* PMTU. In cases, such as loopback, this might be a rather
* large spill over.
*/
if ((!chunk->data_accepted) && (!asoc->rwnd || asoc->rwnd_over ||
(datalen > asoc->rwnd + asoc->frag_point))) {
/* If this is the next TSN, consider reneging to make
* room. Note: Playing nice with a confused sender. A
* malicious sender can still eat up all our buffer
* space and in the future we may want to detect and
* do more drastic reneging.
*/
if (sctp_tsnmap_has_gap(map) &&
(<API key>(map) + 1) == tsn) {
pr_debug("%s: reneging for tsn:%u\n", __func__, tsn);
deliver = SCTP_CMD_RENEGE;
} else {
pr_debug("%s: discard tsn:%u len:%zu, rwnd:%d\n",
__func__, tsn, datalen, asoc->rwnd);
return <API key>;
}
}
/*
* Also try to renege to limit our memory usage in the event that
* we are under memory pressure
* If we can't renege, don't worry about it, the sk_rmem_schedule
* in <API key> will drop the frame if we grow our
* memory usage too much
*/
if (*sk->sk_prot_creator->memory_pressure) {
if (sctp_tsnmap_has_gap(map) &&
(<API key>(map) + 1) == tsn) {
pr_debug("%s: under pressure, reneging for tsn:%u\n",
__func__, tsn);
deliver = SCTP_CMD_RENEGE;
}
}
if (unlikely(0 == datalen)) {
err = <API key>(asoc, chunk, tsn);
if (err) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, <API key>, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, <API key>,
SCTP_PERR(SCTP_ERROR_NO_DATA));
SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB);
return SCTP_IERROR_NO_DATA;
}
chunk->data_accepted = 1;
/* Note: Some chunks may get overcounted (if we drop) or overcounted
* if we renege and the chunk arrives again.
*/
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
SCTP_INC_STATS(net, <API key>);
if (chunk->asoc)
chunk->asoc->stats.iuodchunks++;
} else {
SCTP_INC_STATS(net, <API key>);
if (chunk->asoc)
chunk->asoc->stats.iodchunks++;
ordered = 1;
}
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* If an endpoint receive a DATA chunk with an invalid stream
* identifier, it shall acknowledge the reception of the DATA chunk
* following the normal procedure, immediately send an ERROR chunk
* with cause set to "Invalid Stream Identifier" (See Section 3.3.10)
* and discard the DATA chunk.
*/
sid = ntohs(data_hdr->stream);
if (sid >= asoc->c.sinit_max_instreams) {
/* Mark tsn as received even though we drop it */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_TSN, SCTP_U32(tsn));
err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_INV_STRM,
&data_hdr->stream,
sizeof(data_hdr->stream),
sizeof(u16));
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return <API key>;
}
/* Check to see if the SSN is possible for this TSN.
* The biggest gap we can record is 4K wide. Since SSNs wrap
* at an unsigned short, there is no way that an SSN can
* wrap and for a valid TSN. We can simply check if the current
* SSN is smaller then the next expected one. If it is, it wrapped
* and is invalid.
*/
ssn = ntohs(data_hdr->ssn);
if (ordered && SSN_lt(ssn, sctp_ssn_peek(&asoc->ssnmap->in, sid))) {
return <API key>;
}
/* Send the data up to the user. Note: Schedule the
* SCTP_CMD_CHUNK_ULP cmd before the SCTP_CMD_GEN_SACK, as the SACK
* chunk needs the updated rwnd.
*/
sctp_add_cmd_sf(commands, deliver, SCTP_CHUNK(chunk));
return <API key>;
}
|
#ifndef QEMU_PLUGIN_API_H
#define QEMU_PLUGIN_API_H
#include <inttypes.h>
#include <stdbool.h>
#include <stddef.h>
#if defined _WIN32 || defined __CYGWIN__
#ifdef BUILDING_DLL
#define QEMU_PLUGIN_EXPORT __declspec(dllexport)
#else
#define QEMU_PLUGIN_EXPORT __declspec(dllimport)
#endif
#define QEMU_PLUGIN_LOCAL
#else
#if __GNUC__ >= 4
#define QEMU_PLUGIN_EXPORT __attribute__((visibility("default")))
#define QEMU_PLUGIN_LOCAL __attribute__((visibility("hidden")))
#else
#define QEMU_PLUGIN_EXPORT
#define QEMU_PLUGIN_LOCAL
#endif
#endif
typedef uint64_t qemu_plugin_id_t;
/*
* Versioning plugins:
*
* The plugin API will pass a minimum and current API version that
* QEMU currently supports. The minimum API will be incremented if an
* API needs to be deprecated.
*
* The plugins export the API they were built against by exposing the
* symbol qemu_plugin_version which can be checked.
*/
extern QEMU_PLUGIN_EXPORT int qemu_plugin_version;
#define QEMU_PLUGIN_VERSION 0
typedef struct {
/* string describing architecture */
const char *target_name;
struct {
int min;
int cur;
} version;
/* is this a full system emulation? */
bool system_emulation;
union {
/*
* smp_vcpus may change if vCPUs can be hot-plugged, max_vcpus
* is the system-wide limit.
*/
struct {
int smp_vcpus;
int max_vcpus;
} system;
};
} qemu_info_t;
/**
* qemu_plugin_install() - Install a plugin
* @id: this plugin's opaque ID
* @info: a block describing some details about the guest
* @argc: number of arguments
* @argv: array of arguments (@argc elements)
*
* All plugins must export this symbol.
*
* Note: Calling <API key>() from this function is a bug. To raise
* an error during install, return !0.
*
* Note: @info is only live during the call. Copy any information we
* want to keep.
*
* Note: @argv remains valid throughout the lifetime of the loaded plugin.
*/
QEMU_PLUGIN_EXPORT int qemu_plugin_install(qemu_plugin_id_t id,
const qemu_info_t *info,
int argc, char **argv);
/*
* Prototypes for the various callback styles we will be registering
* in the following functions.
*/
typedef void (*<API key>)(qemu_plugin_id_t id);
typedef void (*<API key>)(qemu_plugin_id_t id, void *userdata);
typedef void (*<API key>)(qemu_plugin_id_t id,
unsigned int vcpu_index);
typedef void (*<API key>)(unsigned int vcpu_index,
void *userdata);
/**
* <API key>() - Uninstall a plugin
* @id: this plugin's opaque ID
* @cb: callback to be called once the plugin has been removed
*
* Do NOT assume that the plugin has been uninstalled once this function
* returns. Plugins are uninstalled asynchronously, and therefore the given
* plugin receives callbacks until @cb is called.
*
* Note: Calling this function from qemu_plugin_install() is a bug.
*/
void <API key>(qemu_plugin_id_t id, <API key> cb);
/**
* qemu_plugin_reset() - Reset a plugin
* @id: this plugin's opaque ID
* @cb: callback to be called once the plugin has been reset
*
* Unregisters all callbacks for the plugin given by @id.
*
* Do NOT assume that the plugin has been reset once this function returns.
* Plugins are reset asynchronously, and therefore the given plugin receives
* callbacks until @cb is called.
*/
void qemu_plugin_reset(qemu_plugin_id_t id, <API key> cb);
/**
* <API key>() - register a vCPU initialization callback
* @id: plugin ID
* @cb: callback function
*
* The @cb function is called every time a vCPU is initialized.
*
* See also: <API key>()
*/
void <API key>(qemu_plugin_id_t id,
<API key> cb);
/**
* <API key>() - register a vCPU exit callback
* @id: plugin ID
* @cb: callback function
*
* The @cb function is called every time a vCPU exits.
*
* See also: <API key>()
*/
void <API key>(qemu_plugin_id_t id,
<API key> cb);
/**
* <API key>() - register a vCPU idle callback
* @id: plugin ID
* @cb: callback function
*
* The @cb function is called every time a vCPU idles.
*/
void <API key>(qemu_plugin_id_t id,
<API key> cb);
/**
* <API key>() - register a vCPU resume callback
* @id: plugin ID
* @cb: callback function
*
* The @cb function is called every time a vCPU resumes execution.
*/
void <API key>(qemu_plugin_id_t id,
<API key> cb);
/*
* Opaque types that the plugin is given during the translation and
* instrumentation phase.
*/
struct qemu_plugin_tb;
struct qemu_plugin_insn;
enum <API key> {
<API key>, /* callback does not access the CPU's regs */
<API key>, /* callback reads the CPU's regs */
<API key>, /* callback reads and writes the CPU's regs */
};
enum qemu_plugin_mem_rw {
QEMU_PLUGIN_MEM_R = 1,
QEMU_PLUGIN_MEM_W,
QEMU_PLUGIN_MEM_RW,
};
/**
* <API key>() - register a translate cb
* @id: plugin ID
* @cb: callback function
*
* The @cb function is called every time a translation occurs. The @cb
* function is passed an opaque qemu_plugin_type which it can query
* for additional information including the list of translated
* instructions. At this point the plugin can register further
* callbacks to be triggered when the block or individual instruction
* executes.
*/
typedef void (*<API key>)(qemu_plugin_id_t id,
struct qemu_plugin_tb *tb);
void <API key>(qemu_plugin_id_t id,
<API key> cb);
/**
* <API key>() - register execution callback
* @tb: the opaque qemu_plugin_tb handle for the translation
* @cb: callback function
* @flags: does the plugin read or write the CPU's registers?
* @userdata: any plugin data to pass to the @cb?
*
* The @cb function is called every time a translated unit executes.
*/
void <API key>(struct qemu_plugin_tb *tb,
<API key> cb,
enum <API key> flags,
void *userdata);
enum qemu_plugin_op {
<API key>,
};
/**
* <API key>() - execution inline op
* @tb: the opaque qemu_plugin_tb handle for the translation
* @op: the type of qemu_plugin_op (e.g. ADD_U64)
* @ptr: the target memory location for the op
* @imm: the op data (e.g. 1)
*
* Insert an inline op to every time a translated unit executes.
* Useful if you just want to increment a single counter somewhere in
* memory.
*/
void <API key>(struct qemu_plugin_tb *tb,
enum qemu_plugin_op op,
void *ptr, uint64_t imm);
/**
* <API key>() - register insn execution cb
* @insn: the opaque qemu_plugin_insn handle for an instruction
* @cb: callback function
* @flags: does the plugin read or write the CPU's registers?
* @userdata: any plugin data to pass to the @cb?
*
* The @cb function is called every time an instruction is executed
*/
void <API key>(struct qemu_plugin_insn *insn,
<API key> cb,
enum <API key> flags,
void *userdata);
/**
* <API key>() - insn execution inline op
* @insn: the opaque qemu_plugin_insn handle for an instruction
* @cb: callback function
* @op: the type of qemu_plugin_op (e.g. ADD_U64)
* @ptr: the target memory location for the op
* @imm: the op data (e.g. 1)
*
* Insert an inline op to every time an instruction executes. Useful
* if you just want to increment a single counter somewhere in memory.
*/
void <API key>(struct qemu_plugin_insn *insn,
enum qemu_plugin_op op,
void *ptr, uint64_t imm);
/*
* Helpers to query information about the instructions in a block
*/
size_t <API key>(const struct qemu_plugin_tb *tb);
uint64_t <API key>(const struct qemu_plugin_tb *tb);
struct qemu_plugin_insn *
<API key>(const struct qemu_plugin_tb *tb, size_t idx);
const void *<API key>(const struct qemu_plugin_insn *insn);
size_t <API key>(const struct qemu_plugin_insn *insn);
uint64_t <API key>(const struct qemu_plugin_insn *insn);
void *<API key>(const struct qemu_plugin_insn *insn);
/*
* Memory Instrumentation
*
* The anonymous <API key> and qemu_plugin_hwaddr types
* can be used in queries to QEMU to get more information about a
* given memory access.
*/
typedef uint32_t <API key>;
struct qemu_plugin_hwaddr;
/* meminfo queries */
unsigned int <API key>(<API key> info);
bool <API key>(<API key> info);
bool <API key>(<API key> info);
bool <API key>(<API key> info);
/*
* <API key>():
* @vaddr: the virtual address of the memory operation
*
* For system emulation returns a qemu_plugin_hwaddr handle to query
* details about the actual physical address backing the virtual
* address. For linux-user guests it just returns NULL.
*
* This handle is *only* valid for the duration of the callback. Any
* information about the handle should be recovered before the
* callback returns.
*/
struct qemu_plugin_hwaddr *<API key>(<API key> info,
uint64_t vaddr);
/*
* The following additional queries can be run on the hwaddr structure
* to return information about it. For non-IO accesses the device
* offset will be into the appropriate block of RAM.
*/
bool <API key>(const struct qemu_plugin_hwaddr *haddr);
uint64_t <API key>(const struct qemu_plugin_hwaddr *haddr);
typedef void
(*<API key>)(unsigned int vcpu_index,
<API key> info, uint64_t vaddr,
void *userdata);
void <API key>(struct qemu_plugin_insn *insn,
<API key> cb,
enum <API key> flags,
enum qemu_plugin_mem_rw rw,
void *userdata);
void <API key>(struct qemu_plugin_insn *insn,
enum qemu_plugin_mem_rw rw,
enum qemu_plugin_op op, void *ptr,
uint64_t imm);
typedef void
(*<API key>)(qemu_plugin_id_t id, unsigned int vcpu_index,
int64_t num, uint64_t a1, uint64_t a2,
uint64_t a3, uint64_t a4, uint64_t a5,
uint64_t a6, uint64_t a7, uint64_t a8);
void <API key>(qemu_plugin_id_t id,
<API key> cb);
typedef void
(*<API key>)(qemu_plugin_id_t id, unsigned int vcpu_idx,
int64_t num, int64_t ret);
void
<API key>(qemu_plugin_id_t id,
<API key> cb);
/**
* <API key>() - return disassembly string for instruction
* @insn: instruction reference
*
* Returns an allocated string containing the disassembly
*/
char *<API key>(const struct qemu_plugin_insn *insn);
/**
* <API key>() - iterate over the existing vCPU
* @id: plugin ID
* @cb: callback function
*
* The @cb function is called once for each existing vCPU.
*
* See also: <API key>()
*/
void <API key>(qemu_plugin_id_t id,
<API key> cb);
void <API key>(qemu_plugin_id_t id,
<API key> cb);
void <API key>(qemu_plugin_id_t id,
<API key> cb, void *userdata);
/* returns -1 in user-mode */
int qemu_plugin_n_vcpus(void);
/* returns -1 in user-mode */
int <API key>(void);
/**
* qemu_plugin_outs() - output string via QEMU's logging system
* @string: a string
*/
void qemu_plugin_outs(const char *string);
#endif /* QEMU_PLUGIN_API_H */
|
.rtl { direction: rtl;}
@font-face {
font-family: 'revicons';
src: url('../fonts/revicons/revicons.eot?5510888');
src: url('../fonts/revicons/revicons.eot?5510888#iefix') format('embedded-opentype'),
url('../fonts/revicons/revicons.woff?5510888') format('woff'),
url('../fonts/revicons/revicons.ttf?5510888') format('truetype'),
url('../fonts/revicons/revicons.svg?5510888#revicons') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="revicon-"]:before, [class*=" revicon-"]:before {
font-family: "revicons";
font-style: normal;
font-weight: normal;
speak: none;
display: inline-block;
text-decoration: inherit;
width: 1em;
margin-right: .2em;
text-align: center;
/* For safety - reset parent styles, that can break glyph codes*/
font-variant: normal;
text-transform: none;
/* fix buttons height, for twitter bootstrap */
line-height: 1em;
/* Animation center compensation - margins should be symmetric */
/* remove if not needed */
margin-left: .2em;
/* you can be more comfortable with increased icons size */
/* font-size: 120%; */
/* Uncomment for 3D effect */
/* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */
}
.revicon-search-1:before { content: '\e802'; }
.revicon-pencil-1:before { content: '\e831'; }
.revicon-picture-1:before { content: '\e803'; }
.revicon-cancel:before { content: '\e80a'; }
.<API key>:before { content: '\e80f'; }
.revicon-trash:before { content: '\e801'; }
.revicon-left-dir:before { content: '\e817'; }
.revicon-right-dir:before { content: '\e818'; }
.revicon-down-open:before { content: '\e83b'; }
.revicon-left-open:before { content: '\e819'; }
.revicon-right-open:before { content: '\e81a'; }
.revicon-angle-left:before { content: '\e820'; }
.revicon-angle-right:before { content: '\e81d'; }
.revicon-left-big:before { content: '\e81f'; }
.revicon-right-big:before { content: '\e81e'; }
.revicon-magic:before { content: '\e807'; }
.revicon-picture:before { content: '\e800'; }
.revicon-export:before { content: '\e80b'; }
.revicon-cog:before { content: '\e832'; }
.revicon-login:before { content: '\e833'; }
.revicon-logout:before { content: '\e834'; }
.revicon-video:before { content: '\e805'; }
.revicon-arrow-combo:before { content: '\e827'; }
.revicon-left-open-1:before { content: '\e82a'; }
.<API key>:before { content: '\e82b'; }
.<API key>:before { content: '\e822'; }
.<API key>:before { content: '\e823'; }
.<API key>:before { content: '\e824'; }
.<API key>:before { content: '\e825'; }
.revicon-left:before { content: '\e836'; }
.revicon-right:before { content: '\e826'; }
.revicon-ccw:before { content: '\e808'; }
.revicon-arrows-ccw:before { content: '\e806'; }
.revicon-palette:before { content: '\e829'; }
.revicon-list-add:before { content: '\e80c'; }
.revicon-doc:before { content: '\e809'; }
.<API key>:before { content: '\e82e'; }
.revicon-left-open-2:before { content: '\e82c'; }
.<API key>:before { content: '\e82f'; }
.<API key>:before { content: '\e82d'; }
.revicon-equalizer:before { content: '\e83a'; }
.revicon-layers-alt:before { content: '\e804'; }
.revicon-popup:before { content: '\e828'; }
.rev_slider_wrapper{
position:relative;
z-index: 0;
}
.rev_slider{
position:relative;
overflow:visible;
}
.tp-overflow-hidden { overflow:hidden;}
.tp-simpleresponsive img,
.rev_slider img{
max-width:none !important;
-moz-transition: none;
-webkit-transition: none;
-o-transition: none;
transition: none;
margin:0px;
padding:0px;
border-width:0px;
border:none;
}
.rev_slider .no-slides-text{
font-weight:bold;
text-align:center;
padding-top:80px;
}
.rev_slider >ul,
.rev_slider_wrapper >ul,
.tp-revslider-mainul >li,
.rev_slider >ul >li,
.rev_slider >ul >li:before,
.tp-revslider-mainul >li:before,
.tp-simpleresponsive >ul,
.tp-simpleresponsive >ul >li,
.tp-simpleresponsive >ul >li:before,
.tp-revslider-mainul >li,
.tp-simpleresponsive >ul >li{
list-style:none !important;
position:absolute;
margin:0px !important;
padding:0px !important;
overflow-x: visible;
overflow-y: visible;
list-style-type: none !important;
background-image:none;
background-position:0px 0px;
text-indent: 0em;
top:0px;left:0px;
}
.tp-revslider-mainul >li,
.rev_slider >ul >li,
.rev_slider >ul >li:before,
.tp-revslider-mainul >li:before,
.tp-simpleresponsive >ul >li,
.tp-simpleresponsive >ul >li:before,
.tp-revslider-mainul >li,
.tp-simpleresponsive >ul >li {
visibility:hidden;
}
.<API key>,
.tp-revslider-mainul {
padding:0 !important;
margin:0 !important;
list-style:none !important;
}
.rev_slider li.<API key> {
position: absolute !important;
}
.tp-caption .<API key> { display:block;}
.tp-caption .rs-toggled-content { display:none;}
.<API key>.tp-caption .rs-toggled-content { display:block;}
.<API key>.tp-caption .<API key> { display:none;}
.rev_slider .tp-caption,
.rev_slider .caption {
position:relative;
visibility:hidden;
white-space: nowrap;
display: block;
}
.rev_slider .tp-mask-wrap .tp-caption,
.rev_slider .tp-mask-wrap *:last-child,
.wpb_text_column .rev_slider .tp-mask-wrap .tp-caption,
.wpb_text_column .rev_slider .tp-mask-wrap *:last-child{
margin-bottom:0;
}
.tp-svg-layer svg { width:100%; height:100%;position: relative;vertical-align: top}
/* CAROUSEL FUNCTIONS */
.tp-carousel-wrapper {
cursor:url(openhand.cur), move;
}
.tp-carousel-wrapper.dragged {
cursor:url(closedhand.cur), move;
}
/* ADDED FOR SLIDELINK MANAGEMENT */
.tp-caption {
z-index:1
}
.tp_inner_padding {
box-sizing:border-box;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
max-height:none !important;
}
.tp-caption {
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
position:absolute;
-<API key>: antialiased !important;
}
.tp-caption.tp-layer-selectable {
-moz-user-select: all;
-khtml-user-select: all;
-webkit-user-select: all;
-o-user-select: all;
}
.tp-forcenotvisible,
.tp-hide-revslider,
.tp-caption.tp-hidden-caption {
visibility:hidden !important;
display:none !important
}
.rev_slider embed,
.rev_slider iframe,
.rev_slider object,
.rev_slider audio,
.rev_slider video {
max-width: none !important
}
.rev_slider_wrapper { width:100%;}
.<API key> {
position:relative;
padding:0;
}
.<API key>{
position:relative;
padding:0;
overflow:hidden;
}
.<API key> .fullwidthabanner{
width:100%;
position:relative;
}
.tp-static-layers {
position:absolute; z-index:101; top:0px;left:0px;
/*pointer-events:none;*/
}
.tp-caption .frontcorner {
width: 0;
height: 0;
border-left: 40px solid transparent;
border-right: 0px solid transparent;
border-top: 40px solid #00A8FF;
position: absolute;left:-40px;top:0px;
}
.tp-caption .backcorner {
width: 0;
height: 0;
border-left: 0px solid transparent;
border-right: 40px solid transparent;
border-bottom: 40px solid #00A8FF;
position: absolute;right:0px;top:0px;
}
.tp-caption .frontcornertop {
width: 0;
height: 0;
border-left: 40px solid transparent;
border-right: 0px solid transparent;
border-bottom: 40px solid #00A8FF;
position: absolute;left:-40px;top:0px;
}
.tp-caption .backcornertop {
width: 0;
height: 0;
border-left: 0px solid transparent;
border-right: 40px solid transparent;
border-top: 40px solid #00A8FF;
position: absolute;right:0px;top:0px;
}
.<API key> {
position: relative !important;
}
img.<API key> {
width:100%; height:auto;
}
.noFilterClass {
filter:none !important;
}
.<API key> { position: absolute;top:0px;left:0px; width:100%;height:100%;visibility: hidden;z-index: 0;}
.tp-caption.coverscreenvideo { width:100%;height:100%;top:0px;left:0px;position:absolute;}
.caption.fullscreenvideo,
.tp-caption.fullscreenvideo { left:0px; top:0px; position:absolute;width:100%;height:100%}
.caption.fullscreenvideo iframe,
.caption.fullscreenvideo audio,
.caption.fullscreenvideo video,
.tp-caption.fullscreenvideo iframe,
.tp-caption.fullscreenvideo iframe audio,
.tp-caption.fullscreenvideo iframe video { width:100% !important; height:100% !important; display: none}
.fullcoveredvideo audio,
.fullscreenvideo audio
.fullcoveredvideo video,
.fullscreenvideo video { background: #000}
.fullcoveredvideo .tp-poster { background-position: center center;background-size: cover;width:100%;height:100%;top:0px;left:0px}
.videoisplaying .html5vid .tp-poster { display: none}
.<API key> {
background:#000;
background:rgba(0,0,0,0.3);
border-radius:5px;-moz-border-radius:5px;-<API key>:5px;
position: absolute;
top: 50%;
left: 50%;
color: #FFF;
z-index: 3;
margin-top: -25px;
margin-left: -25px;
line-height: 50px !important;
text-align: center;
cursor: pointer;
width: 50px;
height:50px;
box-sizing: border-box;
-moz-box-sizing: border-box;
display: inline-block;
vertical-align: top;
z-index: 4;
opacity: 0;
-webkit-transition:opacity 300ms ease-out !important;
-moz-transition:opacity 300ms ease-out !important;
-o-transition:opacity 300ms ease-out !important;
transition:opacity 300ms ease-out !important;
}
.tp-hiddenaudio,
.tp-audio-html5 .<API key> { display:none !important;}
.tp-caption .html5vid { width:100% !important; height:100% !important;}
.<API key> i { width:50px;height:50px; display:inline-block; text-align: center; vertical-align: top; line-height: 50px !important; font-size: 40px !important;}
.tp-caption:hover .<API key> { opacity: 1;}
.tp-caption .tp-revstop { display:none; border-left:5px solid #fff !important; border-right:5px solid #fff !important;margin-top:15px !important;line-height: 20px !important;vertical-align: top; font-size:25px !important;}
.videoisplaying .revicon-right-dir { display:none}
.videoisplaying .tp-revstop { display:inline-block}
.videoisplaying .<API key> { display:none}
.tp-caption:hover .<API key> { display:block}
.fullcoveredvideo .<API key> { display:none !important}
.fullscreenvideo .fullscreenvideo audio { object-fit:contain !important;}
.fullscreenvideo .fullscreenvideo video { object-fit:contain !important;}
.fullscreenvideo .fullcoveredvideo audio { object-fit:cover !important;}
.fullscreenvideo .fullcoveredvideo video { object-fit:cover !important;}
.tp-video-controls {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 5px;
opacity: 0;
-webkit-transition: opacity .3s;
-moz-transition: opacity .3s;
-o-transition: opacity .3s;
-ms-transition: opacity .3s;
transition: opacity .3s;
background-image: linear-gradient(to bottom, rgb(0,0,0) 13%, rgb(50,50,50) 100%);
background-image: -o-linear-gradient(bottom, rgb(0,0,0) 13%, rgb(50,50,50) 100%);
background-image: -moz-linear-gradient(bottom, rgb(0,0,0) 13%, rgb(50,50,50) 100%);
background-image: -<API key>(bottom, rgb(0,0,0) 13%, rgb(50,50,50) 100%);
background-image: -ms-linear-gradient(bottom, rgb(0,0,0) 13%, rgb(50,50,50) 100%);
background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0.13, rgb(0,0,0)),color-stop(1, rgb(50,50,50)));
display:table;max-width:100%; overflow:hidden;box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;
}
.tp-caption:hover .tp-video-controls { opacity: .9;}
.tp-video-button {
background: rgba(0,0,0,.5);
border: 0;
color: #EEE;
-<API key>: 3px;
-moz-border-radius: 3px;
-o-border-radius: 3px;
border-radius: 3px;
cursor:pointer;
line-height:12px;
font-size:12px;
color:#fff;
padding:0px;
margin:0px;
outline: none;
}
.tp-video-button:hover { cursor: pointer;}
.<API key>,
.<API key>,
.<API key> { padding:0px 5px;display:table-cell; vertical-align: middle;}
.<API key> { width:80%}
.<API key> { width:20%}
.tp-volume-bar,
.tp-seek-bar { width:100%; cursor: pointer; outline:none; line-height:12px;margin:0; padding:0;}
.rs-fullvideo-cover { width:100%;height:100%;top:0px;left:0px;position: absolute; background:transparent;z-index:5;}
.<API key> video::-<API key> { display:none !important;}
.<API key> audio::-<API key> { display:none !important;}
.tp-audio-html5 .tp-video-controls { opacity: 1 !important; visibility: visible !important}
.tp-dottedoverlay { background-repeat:repeat;width:100%;height:100%;position:absolute;top:0px;left:0px;z-index:3}
.tp-dottedoverlay.twoxtwo { background:url(../assets/gridtile.png)}
.tp-dottedoverlay.twoxtwowhite { background:url(../assets/gridtile_white.png)}
.tp-dottedoverlay.threexthree { background:url(../assets/gridtile_3x3.png)}
.tp-dottedoverlay.threexthreewhite { background:url(../assets/gridtile_3x3_white.png)}
.tp-shadowcover { width:100%;height:100%;top:0px;left:0px;background: #fff;position: absolute; z-index: -1;}
.tp-shadow1 {
-webkit-box-shadow: 0 10px 6px -6px rgba(0,0,0,0.8);
-moz-box-shadow: 0 10px 6px -6px rgba(0,0,0,0.8);
box-shadow: 0 10px 6px -6px rgba(0,0,0,0.8);
}
.tp-shadow2:before, .tp-shadow2:after,
.tp-shadow3:before, .tp-shadow4:after
{
z-index: -2;
position: absolute;
content: "";
bottom: 10px;
left: 10px;
width: 50%;
top: 85%;
max-width:300px;
background: transparent;
-webkit-box-shadow: 0 15px 10px rgba(0,0,0,0.8);
-moz-box-shadow: 0 15px 10px rgba(0,0,0,0.8);
box-shadow: 0 15px 10px rgba(0,0,0,0.8);
-webkit-transform: rotate(-3deg);
-moz-transform: rotate(-3deg);
-o-transform: rotate(-3deg);
-ms-transform: rotate(-3deg);
transform: rotate(-3deg);
}
.tp-shadow2:after,
.tp-shadow4:after
{
-webkit-transform: rotate(3deg);
-moz-transform: rotate(3deg);
-o-transform: rotate(3deg);
-ms-transform: rotate(3deg);
transform: rotate(3deg);
right: 10px;
left: auto;
}
.tp-shadow5
{
position:relative;
-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.tp-shadow5:before, .tp-shadow5:after
{
content:"";
position:absolute;
z-index:-2;
-webkit-box-shadow:0 0 25px 0px rgba(0,0,0,0.6);
-moz-box-shadow:0 0 25px 0px rgba(0,0,0,0.6);
box-shadow:0 0 25px 0px rgba(0,0,0,0.6);
top:30%;
bottom:0;
left:20px;
right:20px;
-moz-border-radius:100px / 20px;
border-radius:100px / 20px;
}
.tp-button{
padding:6px 13px 5px;
border-radius: 3px;
-moz-border-radius: 3px;
-<API key>: 3px;
height:30px;
cursor:pointer;
color:#fff !important; text-shadow:0px 1px 1px rgba(0, 0, 0, 0.6) !important; font-size:15px; line-height:45px !important;
font-family: arial, sans-serif; font-weight: bold; letter-spacing: -1px;
text-decoration:none;
}
.tp-button.big { color:#fff; text-shadow:0px 1px 1px rgba(0, 0, 0, 0.6); font-weight:bold; padding:9px 20px; font-size:19px; line-height:57px !important; }
.purchase:hover,
.tp-button:hover,
.tp-button.big:hover { background-position:bottom, 15px 11px}
/* BUTTON COLORS */
.tp-button.green, .tp-button:hover.green,
.purchase.green, .purchase:hover.green { background-color:#21a117; -webkit-box-shadow: 0px 3px 0px 0px #104d0b; -moz-box-shadow: 0px 3px 0px 0px #104d0b; box-shadow: 0px 3px 0px 0px #104d0b; }
.tp-button.blue, .tp-button:hover.blue,
.purchase.blue, .purchase:hover.blue { background-color:#1d78cb; -webkit-box-shadow: 0px 3px 0px 0px #0f3e68; -moz-box-shadow: 0px 3px 0px 0px #0f3e68; box-shadow: 0px 3px 0px 0px #0f3e68}
.tp-button.red, .tp-button:hover.red,
.purchase.red, .purchase:hover.red { background-color:#cb1d1d; -webkit-box-shadow: 0px 3px 0px 0px #7c1212; -moz-box-shadow: 0px 3px 0px 0px #7c1212; box-shadow: 0px 3px 0px 0px #7c1212}
.tp-button.orange, .tp-button:hover.orange,
.purchase.orange, .purchase:hover.orange { background-color:#ff7700; -webkit-box-shadow: 0px 3px 0px 0px #a34c00; -moz-box-shadow: 0px 3px 0px 0px #a34c00; box-shadow: 0px 3px 0px 0px #a34c00}
.tp-button.darkgrey,.tp-button.grey,
.tp-button:hover.darkgrey,.tp-button:hover.grey,
.purchase.darkgrey, .purchase:hover.darkgrey { background-color:#555; -webkit-box-shadow: 0px 3px 0px 0px #222; -moz-box-shadow: 0px 3px 0px 0px #222; box-shadow: 0px 3px 0px 0px #222}
.tp-button.lightgrey, .tp-button:hover.lightgrey,
.purchase.lightgrey, .purchase:hover.lightgrey { background-color:#888; -webkit-box-shadow: 0px 3px 0px 0px #555; -moz-box-shadow: 0px 3px 0px 0px #555; box-shadow: 0px 3px 0px 0px #555}
/* TP BUTTONS DESKTOP SIZE */
.rev-btn,
.rev-btn:visited { outline:none !important; box-shadow:none !important; text-decoration: none !important; line-height: 44px; font-size: 17px; font-weight: 500; padding: 12px 35px; box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box; font-family: "Roboto", sans-serif; cursor: pointer;}
.rev-btn.rev-uppercase,
.rev-btn.rev-uppercase:visited { text-transform: uppercase; letter-spacing: 1px; font-size: 15px; font-weight: 900; }
.rev-btn.rev-withicon i { font-size: 15px; font-weight: normal; position: relative; top: 0px; -webkit-transition: all 0.2s ease-out !important; -moz-transition: all 0.2s ease-out !important; -o-transition: all 0.2s ease-out !important; -ms-transition: all 0.2s ease-out !important; margin-left:10px !important;}
.rev-btn.rev-hiddenicon i { font-size: 15px; font-weight: normal; position: relative; top: 0px; -webkit-transition: all 0.2s ease-out !important; -moz-transition: all 0.2s ease-out !important; -o-transition: all 0.2s ease-out !important; -ms-transition: all 0.2s ease-out !important; opacity: 0; margin-left:0px !important; width:0px !important; }
.rev-btn.rev-hiddenicon:hover i { opacity: 1 !important; margin-left:10px !important; width:auto !important;}
/* REV BUTTONS MEDIUM */
.rev-btn.rev-medium,
.rev-btn.rev-medium:visited { line-height: 36px; font-size: 14px; padding: 10px 30px; }
.rev-btn.rev-medium.rev-withicon i { font-size: 14px; top: 0px; }
.rev-btn.rev-medium.rev-hiddenicon i { font-size: 14px; top: 0px; }
/* REV BUTTONS SMALL */
.rev-btn.rev-small,
.rev-btn.rev-small:visited { line-height: 28px; font-size: 12px; padding: 7px 20px; }
.rev-btn.rev-small.rev-withicon i { font-size: 12px; top: 0px; }
.rev-btn.rev-small.rev-hiddenicon i { font-size: 12px; top: 0px; }
/* ROUNDING OPTIONS */
.rev-maxround { -<API key>: 30px; -moz-border-radius: 30px; border-radius: 30px; }
.rev-minround { -<API key>: 3px; -moz-border-radius: 3px; border-radius: 3px; }
/* BURGER BUTTON */
.rev-burger {
position: relative;
width: 60px;
height: 60px;
box-sizing: border-box;
padding: 22px 0 0 14px;
border-radius: 50%;
border: 1px solid rgba(51,51,51,0.25);
tap-highlight-color: transparent;
cursor: pointer;
}
.rev-burger span {
display: block;
width: 30px;
height: 3px;
background: #333;
transition: .7s;
pointer-events: none;
transform-style: flat !important;
}
.rev-burger span:nth-child(2) {
margin: 3px 0;
}
#dialog_addbutton .rev-burger:hover :first-child,
.open .rev-burger :first-child,
.open.rev-burger :first-child {
transform: translateY(6px) rotate(-45deg);
-webkit-transform: translateY(6px) rotate(-45deg);
}
#dialog_addbutton .rev-burger:hover :nth-child(2),
.open .rev-burger :nth-child(2),
.open.rev-burger :nth-child(2) {
transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
opacity: 0;
}
#dialog_addbutton .rev-burger:hover :last-child,
.open .rev-burger :last-child,
.open.rev-burger :last-child {
transform: translateY(-6px) rotate(-135deg);
-webkit-transform: translateY(-6px) rotate(-135deg);
}
.rev-burger.revb-white {
border: 2px solid rgba(255,255,255,0.2);
}
.rev-burger.revb-white span {
background: #fff;
}
.rev-burger.revb-whitenoborder {
border: 0;
}
.rev-burger.revb-whitenoborder span {
background: #fff;
}
.rev-burger.revb-darknoborder {
border: 0;
}
.rev-burger.revb-darknoborder span {
background: #333;
}
.rev-burger.revb-whitefull {
background: #fff;
border:none;
}
.rev-burger.revb-whitefull span {
background:#333;
}
.rev-burger.revb-darkfull {
background: #333;
border:none;
}
.rev-burger.revb-darkfull span {
background:#fff;
}
/* SCROLL DOWN BUTTON */
@-webkit-keyframes rev-ani-mouse {
0% { opacity: 1;top: 29%;}
15% {opacity: 1;top: 50%;}
50% { opacity: 0;top: 50%;}
100% { opacity: 0;top: 29%;}
}
@-moz-keyframes rev-ani-mouse {
0% {opacity: 1;top: 29%;}
15% {opacity: 1;top: 50%;}
50% {opacity: 0;top: 50%;}
100% {opacity: 0;top: 29%;}
}
@keyframes rev-ani-mouse {
0% {opacity: 1;top: 29%;}
15% {opacity: 1;top: 50%;}
50% {opacity: 0;top: 50%;}
100% {opacity: 0;top: 29%;}
}
.rev-scroll-btn {
display: inline-block;
position: relative;
left: 0;
right: 0;
text-align: center;
cursor: pointer;
width:35px;
height:55px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 3px solid white;
border-radius: 23px;
}
.rev-scroll-btn > * {
display: inline-block;
line-height: 18px;
font-size: 13px;
font-weight: normal;
color: #7f8c8d;
color: #ffffff;
font-family: "proxima-nova", "Helvetica Neue", Helvetica, Arial, sans-serif;
letter-spacing: 2px;
}
.rev-scroll-btn > *:hover,
.rev-scroll-btn > *:focus,
.rev-scroll-btn > *.active {
color: #ffffff;
}
.rev-scroll-btn > *:hover,
.rev-scroll-btn > *:focus,
.rev-scroll-btn > *:active,
.rev-scroll-btn > *.active {
filter: alpha(opacity=80);
}
.rev-scroll-btn.revs-fullwhite {
background:#fff;
}
.rev-scroll-btn.revs-fullwhite span {
background: #333;
}
.rev-scroll-btn.revs-fulldark {
background:#333;
border:none;
}
.rev-scroll-btn.revs-fulldark span {
background: #fff;
}
.rev-scroll-btn span {
position: absolute;
display: block;
top: 29%;
left: 50%;
width: 8px;
height: 8px;
margin: -4px 0 0 -4px;
background: white;
border-radius: 50%;
-webkit-animation: rev-ani-mouse 2.5s linear infinite;
-moz-animation: rev-ani-mouse 2.5s linear infinite;
animation: rev-ani-mouse 2.5s linear infinite;
}
.rev-scroll-btn.revs-dark {
border-color:#333;
}
.rev-scroll-btn.revs-dark span {
background: #333;
}
.rev-control-btn {
position: relative;
display: inline-block;
z-index: 5;
color: #FFF;
font-size: 20px;
line-height: 60px;
font-weight: 400;
font-style: normal;
font-family: Raleway;
text-decoration: none;
text-align: center;
background-color: #000;
border-radius: 50px;
text-shadow: none;
background-color: rgba(0, 0, 0, 0.50);
width:60px;
height:60px;
box-sizing: border-box;
cursor: pointer;
}
.rev-cbutton-dark-sr {
border-radius: 3px;
}
.rev-cbutton-light {
color: #333;
background-color: rgba(255,255,255, 0.75);
}
.<API key> {
color: #333;
border-radius: 3px;
background-color: rgba(255,255,255, 0.75);
}
.rev-sbutton {
line-height: 37px;
width:37px;
height:37px;
}
.rev-sbutton-blue {
background-color: #3B5998
}
.<API key> {
background-color: #00A0D1;
}
.rev-sbutton-red {
background-color: #DD4B39;
}
.tp-bannertimer { visibility: hidden; width:100%; height:5px; /*background:url(../assets/timer.png);*/ background: #fff; background: rgba(0,0,0,0.15); position:absolute; z-index:200; top:0px}
.tp-bannertimer.tp-bottom { top:auto; bottom:0px !important;height:5px}
.tp-simpleresponsive img {
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
.tp-caption img {
background: transparent;
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)";
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF);
zoom: 1;
}
/* CAPTION SLIDELINK **/
.caption.slidelink a div,
.tp-caption.slidelink a div { width:3000px; height:1500px; background:url(../assets/coloredbg.png) repeat}
.tp-caption.slidelink a span{ background:url(../assets/coloredbg.png) repeat}
.tp-shape { width:100%;height:100%;}
.tp-caption .rs-starring { display: inline-block}
.tp-caption .rs-starring .star-rating { float: none;}
.tp-caption .rs-starring .star-rating {
color: #FFC321 !important;
display: inline-block;
vertical-align: top;
}
.tp-caption .rs-starring .star-rating,
.tp-caption .rs-starring-page .star-rating {
position: relative;
height: 1em;
width: 5.4em;
font-family: star;
}
.tp-caption .rs-starring .star-rating:before,
.tp-caption .rs-starring-page .star-rating:before {
content: "\73\73\73\73\73";
color: #E0DADF;
float: left;
top: 0;
left: 0;
position: absolute;
}
.tp-caption .rs-starring .star-rating span {
overflow: hidden;
float: left;
top: 0;
left: 0;
position: absolute;
padding-top: 1.5em;
font-size: 1em !important;
}
.tp-caption .rs-starring .star-rating span:before,
.tp-caption .rs-starring .star-rating span:before {
content: "\53\53\53\53\53";
top: 0;
position: absolute;
left: 0;
}
.tp-caption .rs-starring .star-rating {
color: #FFC321 !important;
}
.tp-caption .rs-starring .star-rating,
.tp-caption .rs-starring-page .star-rating {
font-size: 1em !important;
font-family: star;
}
.tp-loader {
top:50%; left:50%;
z-index:10000;
position:absolute;
}
.tp-loader.spinner0 {
width: 40px;
height: 40px;
background-color: #fff;
background:url(../assets/loader.gif) no-repeat center center;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
-webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
margin-top:-20px;
margin-left:-20px;
-webkit-animation: tp-rotateplane 1.2s infinite ease-in-out;
animation: tp-rotateplane 1.2s infinite ease-in-out;
border-radius: 3px;
-moz-border-radius: 3px;
-<API key>: 3px;
}
.tp-loader.spinner1 {
width: 40px;
height: 40px;
background-color: #fff;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
-webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
margin-top:-20px;
margin-left:-20px;
-webkit-animation: tp-rotateplane 1.2s infinite ease-in-out;
animation: tp-rotateplane 1.2s infinite ease-in-out;
border-radius: 3px;
-moz-border-radius: 3px;
-<API key>: 3px;
}
.tp-loader.spinner5 {
background:url(../assets/loader.gif) no-repeat 10px 10px;
background-color:#fff;
margin:-22px -22px;
width:44px;height:44px;
border-radius: 3px;
-moz-border-radius: 3px;
-<API key>: 3px;
}
@-webkit-keyframes tp-rotateplane {
0% { -webkit-transform: perspective(120px) }
50% { -webkit-transform: perspective(120px) rotateY(180deg) }
100% { -webkit-transform: perspective(120px) rotateY(180deg) rotateX(180deg) }
}
@keyframes tp-rotateplane {
0% { transform: perspective(120px) rotateX(0deg) rotateY(0deg);}
50% { transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);}
100% { transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);}
}
.tp-loader.spinner2 {
width: 40px;
height: 40px;
margin-top:-20px;margin-left:-20px;
background-color: #ff0000;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
-webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
border-radius: 100%;
-webkit-animation: tp-scaleout 1.0s infinite ease-in-out;
animation: tp-scaleout 1.0s infinite ease-in-out;
}
@-webkit-keyframes tp-scaleout {
0% { -webkit-transform: scale(0.0) }
100% {-webkit-transform: scale(1.0); opacity: 0;}
}
@keyframes tp-scaleout {
0% {transform: scale(0.0);-webkit-transform: scale(0.0);}
100% {transform: scale(1.0);-webkit-transform: scale(1.0);opacity: 0;}
}
.tp-loader.spinner3 {
margin: -9px 0px 0px -35px;
width: 70px;
text-align: center;
}
.tp-loader.spinner3 .bounce1,
.tp-loader.spinner3 .bounce2,
.tp-loader.spinner3 .bounce3 {
width: 18px;
height: 18px;
background-color: #fff;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
-webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
border-radius: 100%;
display: inline-block;
-webkit-animation: tp-bouncedelay 1.4s infinite ease-in-out;
animation: tp-bouncedelay 1.4s infinite ease-in-out;
/* Prevent first frame from flickering when animation starts */
-<API key>: both;
animation-fill-mode: both;
}
.tp-loader.spinner3 .bounce1 {
-<API key>: -0.32s;
animation-delay: -0.32s;
}
.tp-loader.spinner3 .bounce2 {
-<API key>: -0.16s;
animation-delay: -0.16s;
}
@-webkit-keyframes tp-bouncedelay {
0%, 80%, 100% { -webkit-transform: scale(0.0) }
40% { -webkit-transform: scale(1.0) }
}
@keyframes tp-bouncedelay {
0%, 80%, 100% {transform: scale(0.0);}
40% {transform: scale(1.0);}
}
.tp-loader.spinner4 {
margin: -20px 0px 0px -20px;
width: 40px;
height: 40px;
text-align: center;
-webkit-animation: tp-rotate 2.0s infinite linear;
animation: tp-rotate 2.0s infinite linear;
}
.tp-loader.spinner4 .dot1,
.tp-loader.spinner4 .dot2 {
width: 60%;
height: 60%;
display: inline-block;
position: absolute;
top: 0;
background-color: #fff;
border-radius: 100%;
-webkit-animation: tp-bounce 2.0s infinite ease-in-out;
animation: tp-bounce 2.0s infinite ease-in-out;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
-webkit-box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.15);
}
.tp-loader.spinner4 .dot2 {
top: auto;
bottom: 0px;
-<API key>: -1.0s;
animation-delay: -1.0s;
}
@-webkit-keyframes tp-rotate { 100% { -webkit-transform: rotate(360deg) }}
@keyframes tp-rotate { 100% { transform: rotate(360deg); -webkit-transform: rotate(360deg) }}
@-webkit-keyframes tp-bounce {
0%, 100% { -webkit-transform: scale(0.0) }
50% { -webkit-transform: scale(1.0) }
}
@keyframes tp-bounce {
0%, 100% {transform: scale(0.0);}
50% { transform: scale(1.0);}
}
.tp-thumbs.navbar,
.tp-bullets.navbar,
.tp-tabs.navbar { border:none; min-height: 0; margin:0; border-radius: 0; -moz-border-radius:0; -<API key>:0;}
.tp-tabs,
.tp-thumbs,
.tp-bullets { position:absolute; display:block; z-index:1000; top:0px; left:0px;}
.tp-tab,
.tp-thumb { cursor: pointer; position:absolute;opacity:0.5; box-sizing: border-box;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;}
.tp-arr-imgholder,
.tp-videoposter,
.tp-thumb-image,
.tp-tab-image { background-position: center center; background-size:cover;width:100%;height:100%; display:block; position:absolute;top:0px;left:0px;}
.tp-tab:hover,
.tp-tab.selected,
.tp-thumb:hover,
.tp-thumb.selected { opacity:1;}
.tp-tab-mask,
.tp-thumb-mask { box-sizing:border-box !important; -webkit-box-sizing:border-box !important; -moz-box-sizing:border-box !important}
.tp-tabs,
.tp-thumbs { box-sizing:content-box !important; -webkit-box-sizing:content-box !important; -moz-box-sizing: content-box !important}
.tp-bullet { width:15px;height:15px; position:absolute; background:#fff; background:rgba(255,255,255,0.3); cursor: pointer;}
.tp-bullet.selected,
.tp-bullet:hover { background:#fff;}
.tp-bannertimer { background:#000; background:rgba(0,0,0,0.15); height:5px;}
.tparrows { cursor:pointer; background:#000; background:rgba(0,0,0,0.5); width:40px;height:40px;position:absolute; display:block; z-index:1000; }
.tparrows:hover { background:#000;}
.tparrows:before { font-family: "revicons"; font-size:15px; color:#fff; display:block; line-height: 40px; text-align: center;}
.tparrows.tp-leftarrow:before { content: '\e824'; }
.tparrows.tp-rightarrow:before { content: '\e825'; }
body.rtl .tp-kbimg {left: 0 !important}
.dddwrappershadow { box-shadow:0 45px 100px rgba(0, 0, 0, 0.4);}
.hglayerinfo { position: fixed;
bottom: 0px;
left: 0px;
color: #FFF;
font-size: 12px;
line-height: 20px;
font-weight: 600;
background: rgba(0, 0, 0, 0.75);
padding: 5px 10px;
z-index: 2000;
white-space: normal;}
.hginfo { position:absolute;top:-2px;left:-2px;color:#e74c3c;font-size:12px;font-weight:600; background:#000;padding:2px 5px;}
.indebugmode .tp-caption:hover { border:1px dashed #c0392b !important;}
.helpgrid { border:2px dashed #c0392b;position:absolute;top:0px;left:0px;z-index:0 }
#revsliderlogloglog { padding:15px;color:#fff;position:fixed; top:0px;left:0px;width:200px;height:150px;background:rgba(0,0,0,0.7); z-index:100000; font-size:10px; overflow:scroll;}
|
#include "clConnectionString.h"
#include "file_logger.h"
clConnectionString::clConnectionString(const wxString& connectionString)
: m_port(wxNOT_FOUND)
, m_isOK(false)
{
DoParse(connectionString);
}
clConnectionString::~clConnectionString() {}
void clConnectionString::DoParse(const wxString& connectionString)
{
m_isOK = false; // default
// get the protocol part
clDEBUG() << "Parsing connection string:" << connectionString << clEndl;
wxString protocol = connectionString.BeforeFirst(':');
if(protocol == "tcp") {
m_protocol = kTcp;
} else if(protocol == "unix") {
#ifdef __WXMSW__
clWARNING() << "unix protocol is not suppported on Windows" << clEndl;
return;
#endif
m_protocol = kUnixLocalSocket;
} else {
clWARNING() << "Invalid protocol in connection string:" << connectionString << clEndl;
return;
}
wxString address = connectionString.AfterFirst(':');
address = address.Mid(2); // Skip the "//"
if(m_protocol == kUnixLocalSocket) {
// The rest is the file path
m_path = address;
m_isOK = !m_path.IsEmpty();
} else {
// we now expect host[:port]
m_host = address.BeforeFirst(':');
wxString port = address.AfterFirst(':');
if(!port.IsEmpty()) {
port.ToCLong(&m_port);
}
m_isOK = !m_host.IsEmpty() && (m_port != wxNOT_FOUND);
}
}
|
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/ioctl.h>
#include <linux/spinlock.h>
#include <linux/videodev2.h>
#include <linux/proc_fs.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/videobuf2-core.h>
#include <media/msm_camera.h>
#include <media/msm_isp.h>
#include <mach/iommu.h>
#include "msm.h"
#include "msm_buf_mgr.h"
/*#define CONFIG_MSM_ISP_DBG*/
#undef CDBG
#ifdef CONFIG_MSM_ISP_DBG
#define CDBG(fmt, args...) pr_err(fmt, ##args)
#else
#define CDBG(fmt, args...) do { } while (0)
#endif
static struct msm_isp_bufq *msm_isp_get_bufq(
struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle)
{
struct msm_isp_bufq *bufq = NULL;
uint32_t bufq_index = bufq_handle & 0xFF;
/* bufq_handle cannot be 0 */
if ((bufq_handle == 0) ||
(bufq_index > buf_mgr->num_buf_q))
return NULL;
bufq = &buf_mgr->bufq[bufq_index];
if (bufq->bufq_handle == bufq_handle)
return bufq;
return NULL;
}
static struct msm_isp_buffer *msm_isp_get_buf_ptr(
struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index)
{
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return buf_info;
}
if (bufq->num_bufs <= buf_index) {
pr_err("%s: Invalid buf index\n", __func__);
return buf_info;
}
buf_info = &bufq->bufs[buf_index];
return buf_info;
}
static uint32_t <API key>(
struct msm_isp_buf_mgr *buf_mgr,
uint32_t session_id, uint32_t stream_id)
{
int i;
if ((buf_mgr->buf_handle_cnt << 8) == 0)
buf_mgr->buf_handle_cnt++;
for (i = 0; i < buf_mgr->num_buf_q; i++) {
if (buf_mgr->bufq[i].session_id == session_id &&
buf_mgr->bufq[i].stream_id == stream_id)
return 0;
}
for (i = 0; i < buf_mgr->num_buf_q; i++) {
if (buf_mgr->bufq[i].bufq_handle == 0) {
memset(&buf_mgr->bufq[i],
0, sizeof(struct msm_isp_bufq));
buf_mgr->bufq[i].bufq_handle =
(++buf_mgr->buf_handle_cnt) << 8 | i;
return buf_mgr->bufq[i].bufq_handle;
}
}
return 0;
}
static int <API key>(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle)
{
struct msm_isp_bufq *bufq =
msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq)
return -EINVAL;
memset(bufq, 0, sizeof(struct msm_isp_bufq));
return 0;
}
static int <API key>(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_buffer *buf_info,
struct v4l2_buffer *v4l2_buf)
{
int i, rc = -1;
struct <API key> *mapped_info;
for (i = 0; i < v4l2_buf->length; i++) {
mapped_info = &buf_info->mapped_info[i];
mapped_info->handle =
ion_import_dma_buf(buf_mgr->client,
v4l2_buf->m.planes[i].m.userptr);
if (IS_ERR_OR_NULL(mapped_info->handle)) {
pr_err("%s: buf has null/error ION handle %p\n",
__func__, mapped_info->handle);
goto ion_map_error;
}
if (ion_map_iommu(buf_mgr->client, mapped_info->handle,
buf_mgr->iommu_domain_num, 0, SZ_4K,
0, &(mapped_info->paddr),
&(mapped_info->len), 0, 0) < 0) {
rc = -EINVAL;
pr_err("%s: cannot map address", __func__);
ion_free(buf_mgr->client, mapped_info->handle);
goto ion_map_error;
}
mapped_info->paddr += v4l2_buf->m.planes[i].data_offset;
CDBG("%s: plane: %d addr:%lu\n",
__func__, i, mapped_info->paddr);
}
buf_info->num_planes = v4l2_buf->length;
return 0;
ion_map_error:
for (--i; i >= 0; i
mapped_info = &buf_info->mapped_info[i];
ion_unmap_iommu(buf_mgr->client, mapped_info->handle,
buf_mgr->iommu_domain_num, 0);
ion_free(buf_mgr->client, mapped_info->handle);
}
return rc;
}
static void <API key>(
struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_buffer *buf_info)
{
int i;
struct <API key> *mapped_info;
for (i = 0; i < buf_info->num_planes; i++) {
mapped_info = &buf_info->mapped_info[i];
ion_unmap_iommu(buf_mgr->client, mapped_info->handle,
buf_mgr->iommu_domain_num, 0);
ion_free(buf_mgr->client, mapped_info->handle);
}
return;
}
static int msm_isp_buf_prepare(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_qbuf_info *info, struct vb2_buffer *vb2_buf)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
struct v4l2_buffer *buf = NULL;
struct v4l2_plane *plane = NULL;
buf_info = msm_isp_get_buf_ptr(buf_mgr,
info->handle, info->buf_idx);
if (!buf_info) {
pr_err("Invalid buffer prepare\n");
return rc;
}
bufq = msm_isp_get_bufq(buf_mgr, buf_info->bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (buf_info->state == <API key>) {
rc = buf_info->state;
<API key>(&bufq->bufq_lock, flags);
return rc;
}
if (buf_info->state != <API key>) {
pr_err("%s: Invalid buffer state: %d\n",
__func__, buf_info->state);
<API key>(&bufq->bufq_lock, flags);
return rc;
}
<API key>(&bufq->bufq_lock, flags);
if (vb2_buf) {
buf = &vb2_buf->v4l2_buf;
buf_info->vb2_buf = vb2_buf;
} else {
buf = &info->buffer;
if (buf->length > VIDEO_MAX_PLANES) {
pr_err("%s: Unsupported length %d!\n", __func__, buf->length);
return rc;
}
plane = kzalloc(sizeof(struct v4l2_plane) * buf->length,
GFP_KERNEL);
if (!plane) {
pr_err("%s: Cannot alloc plane: %d\n",
__func__, buf_info->state);
return rc;
}
if (copy_from_user(plane,
(void __user *)(buf->m.planes),
sizeof(struct v4l2_plane) * buf->length)) {
kfree(plane);
return rc;
}
buf->m.planes = plane;
}
rc = <API key>(buf_mgr, buf_info, buf);
if (rc < 0) {
pr_err("%s: Prepare buffer error\n", __func__);
kfree(plane);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
buf_info->state = <API key>;
<API key>(&bufq->bufq_lock, flags);
kfree(plane);
return rc;
}
static int <API key>(struct msm_isp_buf_mgr *buf_mgr,
uint32_t buf_handle)
{
int rc = -1, i;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, buf_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
for (i = 0; i < bufq->num_bufs; i++) {
buf_info = msm_isp_get_buf_ptr(buf_mgr, buf_handle, i);
if (buf_info->state == <API key> ||
buf_info->state ==
<API key>)
continue;
if (<API key> == BUF_SRC(bufq->stream_id)) {
if (buf_info->state == <API key> ||
buf_info->state == <API key>)
buf_mgr->vb2_ops->put_buf(buf_info->vb2_buf,
bufq->session_id, bufq->stream_id);
}
<API key>(buf_mgr, buf_info);
}
return 0;
}
static int msm_isp_get_buf(struct msm_isp_buf_mgr *buf_mgr, uint32_t id,
uint32_t bufq_handle, struct msm_isp_buffer **buf_info)
{
int rc = -1;
unsigned long flags;
struct msm_isp_buffer *temp_buf_info;
struct msm_isp_bufq *bufq = NULL;
struct vb2_buffer *vb2_buf = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
*buf_info = NULL;
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (bufq->buf_type == ISP_SHARE_BUF) {
list_for_each_entry(temp_buf_info,
&bufq->share_head, share_list) {
if (!temp_buf_info->buf_used[id]) {
temp_buf_info->buf_used[id] = 1;
temp_buf_info->buf_get_count++;
if (temp_buf_info->buf_get_count ==
bufq->buf_client_count)
list_del_init(
&temp_buf_info->share_list);
if (temp_buf_info->buf_reuse_flag) {
kfree(temp_buf_info);
} else {
*buf_info = temp_buf_info;
rc = 0;
}
<API key>(
&bufq->bufq_lock, flags);
return rc;
}
}
}
switch(BUF_SRC(bufq->stream_id)) {
case <API key>:
list_for_each_entry(temp_buf_info, &bufq->head, list) {
if (temp_buf_info->state ==
<API key>) {
/* found one buf */
list_del_init(&temp_buf_info->list);
*buf_info = temp_buf_info;
break;
}
}
break;
case <API key>:
vb2_buf = buf_mgr->vb2_ops->get_buf(
bufq->session_id, bufq->stream_id);
if (vb2_buf) {
if (vb2_buf->v4l2_buf.index < bufq->num_bufs) {
*buf_info =
&bufq->bufs[vb2_buf->v4l2_buf.index];
(*buf_info)->vb2_buf = vb2_buf;
} else {
pr_err("%s: Incorrect buf index %d\n",
__func__, vb2_buf->v4l2_buf.index);
rc = -EINVAL;
}
}
break;
case <API key>:
/* In scratch buf case we have only on buffer in queue.
* We return every time same buffer. */
*buf_info = list_entry(bufq->head.next, typeof(**buf_info),
list);
break;
default:
pr_err("%s: Incorrect buf source.\n", __func__);
rc = -EINVAL;
return rc;
}
if (!(*buf_info)) {
if (bufq->buf_type == ISP_SHARE_BUF) {
temp_buf_info = kzalloc(
sizeof(struct msm_isp_buffer), GFP_ATOMIC);
temp_buf_info->buf_reuse_flag = 1;
temp_buf_info->buf_used[id] = 1;
temp_buf_info->buf_get_count = 1;
list_add_tail(&temp_buf_info->share_list,
&bufq->share_head);
}
} else {
(*buf_info)->state = <API key>;
if (bufq->buf_type == ISP_SHARE_BUF) {
memset((*buf_info)->buf_used, 0,
sizeof(uint8_t) * bufq->buf_client_count);
(*buf_info)->buf_used[id] = 1;
(*buf_info)->buf_get_count = 1;
(*buf_info)->buf_put_count = 0;
(*buf_info)->buf_reuse_flag = 0;
list_add_tail(&(*buf_info)->share_list,
&bufq->share_head);
}
rc = 0;
}
<API key>(&bufq->bufq_lock, flags);
return rc;
}
static int msm_isp_put_buf(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return rc;
}
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, buf_index);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
switch (buf_info->state) {
case <API key>:
if (<API key> == BUF_SRC(bufq->stream_id))
list_add_tail(&buf_info->list, &bufq->head);
case <API key>:
case <API key>:
if (<API key> == BUF_SRC(bufq->stream_id))
list_add_tail(&buf_info->list, &bufq->head);
else if (<API key> == BUF_SRC(bufq->stream_id))
buf_mgr->vb2_ops->put_buf(buf_info->vb2_buf,
bufq->session_id, bufq->stream_id);
buf_info->state = <API key>;
rc = 0;
break;
case <API key>:
buf_info->state = <API key>;
rc = 0;
break;
case <API key>:
rc = 0;
break;
default:
pr_err("%s: incorrect state = %d",
__func__, buf_info->state);
break;
}
<API key>(&bufq->bufq_lock, flags);
return rc;
}
static int msm_isp_buf_done(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index,
struct timeval *tv, uint32_t frame_id)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
enum <API key> state;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq\n");
return rc;
}
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, buf_index);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
state = buf_info->state;
<API key>(&bufq->bufq_lock, flags);
if (state == <API key> ||
state == <API key>) {
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (bufq->buf_type == ISP_SHARE_BUF) {
buf_info->buf_put_count++;
if (buf_info->buf_put_count != <API key>) {
rc = buf_info->buf_put_count;
<API key>(&bufq->bufq_lock, flags);
return rc;
}
}
buf_info->state = <API key>;
<API key>(&bufq->bufq_lock, flags);
if (<API key> == BUF_SRC(bufq->stream_id)) {
buf_info->vb2_buf->v4l2_buf.timestamp = *tv;
buf_info->vb2_buf->v4l2_buf.sequence = frame_id;
buf_mgr->vb2_ops->buf_done(buf_info->vb2_buf,
bufq->session_id, bufq->stream_id);
} else {
rc = msm_isp_put_buf(buf_mgr, buf_info->bufq_handle,
buf_info->buf_idx);
if (rc < 0) {
pr_err("%s: Buf put failed\n", __func__);
return rc;
}
}
}
return 0;
}
static int msm_isp_flush_buf(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, enum <API key> flush_type)
{
int rc = -1, i;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq\n");
return rc;
}
for (i = 0; i < bufq->num_bufs; i++) {
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, i);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
continue;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (flush_type == <API key> &&
buf_info->state == <API key>) {
buf_info->state = <API key>;
} else if (flush_type == <API key> &&
(buf_info->state == <API key> ||
buf_info->state == <API key> ||
buf_info->state == <API key>)) {
buf_info->state = <API key>;
}
<API key>(&bufq->bufq_lock, flags);
}
return 0;
}
static int msm_isp_buf_divert(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t buf_index,
struct timeval *tv, uint32_t frame_id)
{
int rc = -1;
unsigned long flags;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq\n");
return rc;
}
buf_info = msm_isp_get_buf_ptr(buf_mgr, bufq_handle, buf_index);
if (!buf_info) {
pr_err("%s: buf not found\n", __func__);
return rc;
}
spin_lock_irqsave(&bufq->bufq_lock, flags);
if (bufq->buf_type == ISP_SHARE_BUF) {
buf_info->buf_put_count++;
if (buf_info->buf_put_count != <API key>) {
rc = buf_info->buf_put_count;
<API key>(&bufq->bufq_lock, flags);
return rc;
}
}
if (buf_info->state == <API key>) {
buf_info->state = <API key>;
buf_info->tv = tv;
buf_info->frame_id = frame_id;
}
<API key>(&bufq->bufq_lock, flags);
return 0;
}
static int msm_isp_buf_enqueue(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_qbuf_info *info)
{
int rc = -1, buf_state;
struct msm_isp_bufq *bufq = NULL;
struct msm_isp_buffer *buf_info = NULL;
buf_state = msm_isp_buf_prepare(buf_mgr, info, NULL);
if (buf_state < 0) {
pr_err("%s: Buf prepare failed\n", __func__);
return -EINVAL;
}
if (buf_state == <API key>) {
buf_info = msm_isp_get_buf_ptr(buf_mgr,
info->handle, info->buf_idx);
if (info->dirty_buf)
msm_isp_put_buf(buf_mgr, info->handle, info->buf_idx);
else
msm_isp_buf_done(buf_mgr, info->handle, info->buf_idx,
buf_info->tv, buf_info->frame_id);
} else {
bufq = msm_isp_get_bufq(buf_mgr, info->handle);
if (<API key> != BUF_SRC(bufq->stream_id)) {
rc = msm_isp_put_buf(buf_mgr,
info->handle, info->buf_idx);
if (rc < 0) {
pr_err("%s: Buf put failed\n", __func__);
return rc;
}
}
}
return rc;
}
static int <API key>(struct msm_isp_buf_mgr *buf_mgr,
uint32_t session_id, uint32_t stream_id)
{
int i;
for (i = 0; i < buf_mgr->num_buf_q; i++) {
if (buf_mgr->bufq[i].session_id == session_id &&
buf_mgr->bufq[i].stream_id == stream_id) {
return buf_mgr->bufq[i].bufq_handle;
}
}
return 0;
}
static int msm_isp_get_buf_src(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle, uint32_t *buf_src)
{
struct msm_isp_bufq *bufq = NULL;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("%s: Invalid bufq\n", __func__);
return -EINVAL;
}
*buf_src = BUF_SRC(bufq->stream_id);
return 0;
}
static int <API key>(struct msm_isp_buf_mgr *buf_mgr,
struct msm_isp_buf_request *buf_request)
{
int rc = -1, i;
struct msm_isp_bufq *bufq = NULL;
CDBG("%s: E\n", __func__);
if (!buf_request->num_buf) {
pr_err("Invalid buffer request\n");
return rc;
}
buf_request->handle = <API key>(buf_mgr,
buf_request->session_id, buf_request->stream_id);
if (!buf_request->handle) {
pr_err("Invalid buffer handle\n");
return rc;
}
bufq = msm_isp_get_bufq(buf_mgr, buf_request->handle);
if (!bufq) {
pr_err("Invalid buffer queue\n");
return rc;
}
bufq->bufs = kzalloc(sizeof(struct msm_isp_buffer) *
buf_request->num_buf, GFP_KERNEL);
if (!bufq->bufs) {
pr_err("No free memory for buf info\n");
<API key>(buf_mgr, buf_request->handle);
return rc;
}
spin_lock_init(&bufq->bufq_lock);
bufq->bufq_handle = buf_request->handle;
bufq->session_id = buf_request->session_id;
bufq->stream_id = buf_request->stream_id;
bufq->num_bufs = buf_request->num_buf;
bufq->buf_type = buf_request->buf_type;
if (bufq->buf_type == ISP_SHARE_BUF)
bufq->buf_client_count = <API key>;
INIT_LIST_HEAD(&bufq->head);
INIT_LIST_HEAD(&bufq->share_head);
for (i = 0; i < buf_request->num_buf; i++) {
bufq->bufs[i].state = <API key>;
bufq->bufs[i].bufq_handle = bufq->bufq_handle;
bufq->bufs[i].buf_idx = i;
}
return 0;
}
static int <API key>(struct msm_isp_buf_mgr *buf_mgr,
uint32_t bufq_handle)
{
struct msm_isp_bufq *bufq = NULL;
int rc = -1;
bufq = msm_isp_get_bufq(buf_mgr, bufq_handle);
if (!bufq) {
pr_err("Invalid bufq release\n");
return rc;
}
<API key>(buf_mgr, bufq_handle);
kfree(bufq->bufs);
<API key>(buf_mgr, bufq_handle);
return 0;
}
static void <API key>(
struct msm_isp_buf_mgr *buf_mgr)
{
struct msm_isp_bufq *bufq = NULL;
int i;
for (i = 0; i < buf_mgr->num_buf_q; i++) {
bufq = &buf_mgr->bufq[i];
if (!bufq->bufq_handle)
continue;
<API key>(buf_mgr, bufq->bufq_handle);
kfree(bufq->bufs);
<API key>(buf_mgr, bufq->bufq_handle);
}
}
static void <API key>(struct msm_isp_buf_mgr *buf_mgr,
struct device **iommu_ctx, int num_iommu_ctx)
{
int i;
buf_mgr->num_iommu_ctx = num_iommu_ctx;
for (i = 0; i < num_iommu_ctx; i++)
buf_mgr->iommu_ctx[i] = iommu_ctx[i];
}
static int msm_isp_attach_ctx(struct msm_isp_buf_mgr *buf_mgr)
{
int rc, i;
for (i = 0; i < buf_mgr->num_iommu_ctx; i++) {
rc = iommu_attach_device(buf_mgr->iommu_domain,
buf_mgr->iommu_ctx[i]);
if (rc) {
pr_err("%s: Iommu attach error\n", __func__);
return -EINVAL;
}
}
return 0;
}
static void msm_isp_detach_ctx(struct msm_isp_buf_mgr *buf_mgr)
{
int i;
for (i = 0; i < buf_mgr->num_iommu_ctx; i++)
iommu_detach_device(buf_mgr->iommu_domain,
buf_mgr->iommu_ctx[i]);
}
static int <API key>(
struct msm_isp_buf_mgr *buf_mgr,
const char *ctx_name, uint16_t num_buf_q)
{
int rc = -1;
if (buf_mgr->open_count++)
return 0;
if (!num_buf_q) {
pr_err("Invalid buffer queue number\n");
return rc;
}
CDBG("%s: E\n", __func__);
msm_isp_attach_ctx(buf_mgr);
buf_mgr->num_buf_q = num_buf_q;
buf_mgr->bufq =
kzalloc(sizeof(struct msm_isp_bufq) * num_buf_q,
GFP_KERNEL);
if (!buf_mgr->bufq) {
pr_err("Bufq malloc error\n");
goto bufq_error;
}
buf_mgr->client = <API key>(-1, ctx_name);
buf_mgr->buf_handle_cnt = 0;
return 0;
bufq_error:
return rc;
}
static int <API key>(
struct msm_isp_buf_mgr *buf_mgr)
{
if (--buf_mgr->open_count)
return 0;
<API key>(buf_mgr);
ion_client_destroy(buf_mgr->client);
kfree(buf_mgr->bufq);
buf_mgr->num_buf_q = 0;
msm_isp_detach_ctx(buf_mgr);
return 0;
}
int <API key>(struct msm_isp_buf_mgr *buf_mgr,
unsigned int cmd, void *arg)
{
switch (cmd) {
case <API key>: {
struct msm_isp_buf_request *buf_req = arg;
buf_mgr->ops->request_buf(buf_mgr, buf_req);
break;
}
case <API key>: {
struct msm_isp_qbuf_info *qbuf_info = arg;
buf_mgr->ops->enqueue_buf(buf_mgr, qbuf_info);
break;
}
case <API key>: {
struct msm_isp_buf_request *buf_req = arg;
buf_mgr->ops->release_buf(buf_mgr, buf_req->handle);
break;
}
}
return 0;
}
static struct msm_isp_buf_ops isp_buf_ops = {
.request_buf = <API key>,
.enqueue_buf = msm_isp_buf_enqueue,
.release_buf = <API key>,
.get_bufq_handle = <API key>,
.get_buf_src = msm_isp_get_buf_src,
.get_buf = msm_isp_get_buf,
.put_buf = msm_isp_put_buf,
.flush_buf = msm_isp_flush_buf,
.buf_done = msm_isp_buf_done,
.buf_divert = msm_isp_buf_divert,
.register_ctx = <API key>,
.buf_mgr_init = <API key>,
.buf_mgr_deinit = <API key>,
};
int <API key>(
struct msm_isp_buf_mgr *buf_mgr,
struct msm_sd_req_vb2_q *vb2_ops,
struct msm_iova_layout *iova_layout)
{
int rc = 0;
if (buf_mgr->init_done)
return rc;
buf_mgr->iommu_domain_num = msm_register_domain(iova_layout);
if (buf_mgr->iommu_domain_num < 0) {
pr_err("%s: Invalid iommu domain number\n", __func__);
rc = -1;
goto iommu_domain_error;
}
buf_mgr->iommu_domain = <API key>(
buf_mgr->iommu_domain_num);
if (!buf_mgr->iommu_domain) {
pr_err("%s: Invalid iommu domain\n", __func__);
rc = -1;
goto iommu_domain_error;
}
buf_mgr->ops = &isp_buf_ops;
buf_mgr->vb2_ops = vb2_ops;
buf_mgr->init_done = 1;
buf_mgr->open_count = 0;
return 0;
iommu_domain_error:
return rc;
}
|
#include <stdint.h>
#include <string.h>
#include <arch/io.h>
#include <device/device.h>
#include <device/pci.h>
#include <soc/gpio.h>
#include <soc/iomap.h>
#include <soc/pm.h>
/*
* This function will return a number that indicates which PIRQ
* this GPIO maps to. If this is not a PIRQ capable GPIO then
* it will return -1. The GPIO to PIRQ mapping is not linear.
*/
static int gpio_to_pirq(int gpio)
{
switch (gpio) {
case 8: return 0; /* PIRQI */
case 9: return 1; /* PIRQJ */
case 10: return 2; /* PIRQK */
case 13: return 3; /* PIRQL */
case 14: return 4; /* PIRQM */
case 45: return 5; /* PIRQN */
case 46: return 6; /* PIRQO */
case 47: return 7; /* PIRQP */
case 48: return 8; /* PIRQQ */
case 49: return 9; /* PIRQR */
case 50: return 10; /* PIRQS */
case 51: return 11; /* PIRQT */
case 52: return 12; /* PIRQU */
case 53: return 13; /* PIRQV */
case 54: return 14; /* PIRQW */
case 55: return 15; /* PIRQX */
default: return -1;
};
}
void init_one_gpio(int gpio_num, struct gpio_config *config)
{
u32 owner, route, irqen, reset;
int set, bit;
if (gpio_num > MAX_GPIO_NUMBER || !config)
return;
outl(config->conf0, GPIO_BASE_ADDRESS + GPIO_CONFIG0(gpio_num));
outl(config->conf1, GPIO_BASE_ADDRESS + GPIO_CONFIG1(gpio_num));
/* Determine set and bit based on GPIO number */
set = gpio_num >> 5;
bit = gpio_num % 32;
/* Save settings from current GPIO config */
owner = inl(GPIO_BASE_ADDRESS + GPIO_OWNER(set));
route = inl(GPIO_BASE_ADDRESS + GPIO_ROUTE(set));
irqen = inl(GPIO_BASE_ADDRESS + GPIO_IRQ_IE(set));
reset = inl(GPIO_BASE_ADDRESS + GPIO_RESET(set));
owner |= config->owner << bit;
route |= config->route << bit;
irqen |= config->irqen << bit;
reset |= config->reset << bit;
outl(owner, GPIO_BASE_ADDRESS + GPIO_OWNER(set));
outl(route, GPIO_BASE_ADDRESS + GPIO_ROUTE(set));
outl(irqen, GPIO_BASE_ADDRESS + GPIO_IRQ_IE(set));
outl(reset, GPIO_BASE_ADDRESS + GPIO_RESET(set));
if (set == 0) {
u32 blink = inl(GPIO_BASE_ADDRESS + GPIO_BLINK);
blink |= config->blink << bit;
outl(blink, GPIO_BASE_ADDRESS + GPIO_BLINK);
}
/* PIRQ to IO-APIC map */
if (config->pirq == <API key>) {
u32 pirq2apic = inl(GPIO_BASE_ADDRESS + GPIO_PIRQ_APIC_EN);
set = gpio_to_pirq(gpio_num);
if (set >= 0) {
pirq2apic |= 1 << set;
outl(pirq2apic, GPIO_BASE_ADDRESS + GPIO_PIRQ_APIC_EN);
}
}
}
void init_gpios(const struct gpio_config config[])
{
const struct gpio_config *entry;
u32 owner[3] = {0};
u32 route[3] = {0};
u32 irqen[3] = {0};
u32 reset[3] = {0};
u32 blink = 0;
u16 pirq2apic = 0;
int set, bit, gpio = 0;
for (entry = config; entry->conf0 != GPIO_LIST_END; entry++, gpio++) {
if (gpio > MAX_GPIO_NUMBER)
break;
/* Setup Configuration registers 1 and 2 */
outl(entry->conf0, GPIO_BASE_ADDRESS + GPIO_CONFIG0(gpio));
outl(entry->conf1, GPIO_BASE_ADDRESS + GPIO_CONFIG1(gpio));
/* Determine set and bit based on GPIO number */
set = gpio >> 5;
bit = gpio % 32;
/* Apply settings to set specific bits */
owner[set] |= entry->owner << bit;
route[set] |= entry->route << bit;
irqen[set] |= entry->irqen << bit;
reset[set] |= entry->reset << bit;
if (set == 0)
blink |= entry->blink << bit;
/* PIRQ to IO-APIC map */
if (entry->pirq == <API key>) {
set = gpio_to_pirq(gpio);
if (set >= 0)
pirq2apic |= 1 << set;
}
}
for (set = 0; set <= 2; set++) {
outl(owner[set], GPIO_BASE_ADDRESS + GPIO_OWNER(set));
outl(route[set], GPIO_BASE_ADDRESS + GPIO_ROUTE(set));
outl(irqen[set], GPIO_BASE_ADDRESS + GPIO_IRQ_IE(set));
outl(reset[set], GPIO_BASE_ADDRESS + GPIO_RESET(set));
}
outl(blink, GPIO_BASE_ADDRESS + GPIO_BLINK);
outl(pirq2apic, GPIO_BASE_ADDRESS + GPIO_PIRQ_APIC_EN);
}
int get_gpio(int gpio_num)
{
if (gpio_num > MAX_GPIO_NUMBER)
return 0;
return !!(inl(GPIO_BASE_ADDRESS + GPIO_CONFIG0(gpio_num)) & GPI_LEVEL);
}
/*
* get a number comprised of multiple GPIO values. gpio_num_array points to
* the array of gpio pin numbers to scan, terminated by -1.
*/
unsigned get_gpios(const int *gpio_num_array)
{
int gpio;
unsigned bitmask = 1;
unsigned vector = 0;
while (bitmask &&
((gpio = *gpio_num_array++) != -1)) {
if (get_gpio(gpio))
vector |= bitmask;
bitmask <<= 1;
}
return vector;
}
void set_gpio(int gpio_num, int value)
{
u32 conf0;
if (gpio_num > MAX_GPIO_NUMBER)
return;
conf0 = inl(GPIO_BASE_ADDRESS + GPIO_CONFIG0(gpio_num));
conf0 &= ~GPO_LEVEL_MASK;
conf0 |= value << GPO_LEVEL_SHIFT;
outl(conf0, GPIO_BASE_ADDRESS + GPIO_CONFIG0(gpio_num));
}
int gpio_is_native(int gpio_num)
{
return !(inl(GPIO_BASE_ADDRESS + GPIO_CONFIG0(gpio_num)) & 1);
}
|
#!/bin/sh
test_description='Test the mail command'
. ./test-lib.sh
test_expect_success \
'Initialize the StGIT repository' \
'
git config stgit.sender "A U Thor <[email protected]>" &&
for i in 1 2 3 4 5; do
touch foo.txt &&
echo "line $i" >> foo.txt &&
stg add foo.txt &&
git commit -a -m "Patch $i"
done &&
stg init &&
stg uncommit -n 5 foo
'
test_expect_success \
'Put all the patches in an mbox' \
'stg mail --to="Inge Ström <[email protected]>" -a -m \
-t $STG_ROOT/templates/patchmail.tmpl > mbox0'
test_expect_success \
'Import the mbox and compare' \
'
t1=$(git cat-file -p $(stg id) | grep ^tree)
stg pop -a &&
stg import -M mbox0 &&
t2=$(git cat-file -p $(stg id) | grep ^tree) &&
[ "$t1" = "$t2" ]
'
test_expect_success \
'Put all the patches in an mbox with patch attachments' \
'stg mail --to="Inge Ström <[email protected]>" -a -m \
-t $STG_ROOT/templates/mailattch.tmpl > mbox1'
test_expect_success \
'Import the mbox containing patch attachments and compare' \
'
t1=$(git cat-file -p $(stg id) | grep ^tree)
stg pop -a &&
stg import -M mbox1 &&
t2=$(git cat-file -p $(stg id) | grep ^tree) &&
[ "$t1" = "$t2" ]
'
test_expect_success \
'Check the To:, Cc: and Bcc: headers' \
'
stg mail --to=a@a --cc="b@b, c@c" --bcc=d@d $(stg top) -m \
-t $STG_ROOT/templates/patchmail.tmpl > mbox &&
test "$(cat mbox | grep -e "^To:")" = "To: a@a" &&
test "$(cat mbox | grep -e "^Cc:")" = "Cc: b@b, c@c" &&
test "$(cat mbox | grep -e "^Bcc:")" = "Bcc: d@d"
'
test_expect_success \
'Check the --auto option' \
'
stg edit --sign &&
stg mail --to=a@a --cc="b@b, c@c" --bcc=d@d --auto $(stg top) -m \
-t $STG_ROOT/templates/patchmail.tmpl > mbox &&
test "$(cat mbox | grep -e "^To:")" = "To: a@a" &&
test "$(cat mbox | grep -e "^Cc:")" = \
"Cc: C O Mitter <[email protected]>, b@b, c@c" &&
test "$(cat mbox | grep -e "^Bcc:")" = "Bcc: d@d"
'
test_expect_success \
'Check the e-mail address duplicates' \
'
stg mail --to="a@a, b b <b@b>" --cc="b@b, c@c" \
--bcc="c@c, d@d, [email protected]" --auto $(stg top) -m \
-t $STG_ROOT/templates/patchmail.tmpl > mbox &&
test "$(cat mbox | grep -e "^To:")" = "To: b b <b@b>, a@a" &&
test "$(cat mbox | grep -e "^Cc:")" = \
"Cc: C O Mitter <[email protected]>, c@c" &&
test "$(cat mbox | grep -e "^Bcc:")" = "Bcc: d@d"
'
test_done
|
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kdev_t.h>
#include <linux/notifier.h>
#include <linux/genhd.h>
#include <linux/kallsyms.h>
#include <linux/semaphore.h>
#include <linux/mutex.h>
#include <linux/async.h>
#include "base.h"
#include "power/power.h"
int (*platform_notify)(struct device *dev) = NULL;
int (*<API key>)(struct device *dev) = NULL;
static struct kobject *dev_kobj;
struct kobject *sysfs_dev_char_kobj;
struct kobject *<API key>;
#ifdef CONFIG_BLOCK
static inline int <API key>(struct device *dev)
{
return !(dev->type == &part_type);
}
#else
static inline int <API key>(struct device *dev)
{
return 1;
}
#endif
/**
* dev_driver_string - Return a device's driver name, if at all possible
* @dev: struct device to get the name of
*
* Will return the device's driver's name if it is bound to a device. If
* the device is not bound to a device, it will return the name of the bus
* it is attached to. If it is not attached to a bus either, an empty
* string will be returned.
*/
const char *dev_driver_string(const struct device *dev)
{
struct device_driver *drv;
/* dev->driver can change to NULL underneath us because of unbinding,
* so be careful about accessing it. dev->bus and dev->class should
* never change once they are set, so they don't need special care.
*/
drv = ACCESS_ONCE(dev->driver);
return drv ? drv->name :
(dev->bus ? dev->bus->name :
(dev->class ? dev->class->name : ""));
}
EXPORT_SYMBOL(dev_driver_string);
#define to_dev(obj) container_of(obj, struct device, kobj)
#define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct device_attribute *dev_attr = to_dev_attr(attr);
struct device *dev = to_dev(kobj);
ssize_t ret = -EIO;
if (dev_attr->show)
ret = dev_attr->show(dev, dev_attr, buf);
if (ret >= (ssize_t)PAGE_SIZE) {
print_symbol("dev_attr_show: %s returned bad count\n",
(unsigned long)dev_attr->show);
}
return ret;
}
static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct device_attribute *dev_attr = to_dev_attr(attr);
struct device *dev = to_dev(kobj);
ssize_t ret = -EIO;
if (dev_attr->store)
ret = dev_attr->store(dev, dev_attr, buf, count);
return ret;
}
static struct sysfs_ops dev_sysfs_ops = {
.show = dev_attr_show,
.store = dev_attr_store,
};
/**
* device_release - free device structure.
* @kobj: device's kobject.
*
* This is called once the reference count for the object
* reaches 0. We forward the call to the device's release
* method, which should handle actually freeing the structure.
*/
static void device_release(struct kobject *kobj)
{
struct device *dev = to_dev(kobj);
struct device_private *p = dev->p;
if (dev->release)
dev->release(dev);
else if (dev->type && dev->type->release)
dev->type->release(dev);
else if (dev->class && dev->class->dev_release)
dev->class->dev_release(dev);
else
WARN(1, KERN_ERR "Device '%s' does not have a release() "
"function, it is broken and must be fixed.\n",
dev_name(dev));
kfree(p);
}
static struct kobj_type device_ktype = {
.release = device_release,
.sysfs_ops = &dev_sysfs_ops,
};
static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
{
struct kobj_type *ktype = get_ktype(kobj);
if (ktype == &device_ktype) {
struct device *dev = to_dev(kobj);
if (dev->bus)
return 1;
if (dev->class)
return 1;
}
return 0;
}
static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
{
struct device *dev = to_dev(kobj);
if (dev->bus)
return dev->bus->name;
if (dev->class)
return dev->class->name;
return NULL;
}
static int dev_uevent(struct kset *kset, struct kobject *kobj,
struct kobj_uevent_env *env)
{
struct device *dev = to_dev(kobj);
int retval = 0;
/* add device node properties if present */
if (MAJOR(dev->devt)) {
const char *tmp;
const char *name;
mode_t mode = 0;
add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
name = device_get_devnode(dev, &mode, &tmp);
if (name) {
add_uevent_var(env, "DEVNAME=%s", name);
kfree(tmp);
if (mode)
add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
}
}
if (dev->type && dev->type->name)
add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
if (dev->driver)
add_uevent_var(env, "DRIVER=%s", dev->driver->name);
#ifdef <API key>
if (dev->class) {
struct device *parent = dev->parent;
/* find first bus device in parent chain */
while (parent && !parent->bus)
parent = parent->parent;
if (parent && parent->bus) {
const char *path;
path = kobject_get_path(&parent->kobj, GFP_KERNEL);
if (path) {
add_uevent_var(env, "PHYSDEVPATH=%s", path);
kfree(path);
}
add_uevent_var(env, "PHYSDEVBUS=%s", parent->bus->name);
if (parent->driver)
add_uevent_var(env, "PHYSDEVDRIVER=%s",
parent->driver->name);
}
} else if (dev->bus) {
add_uevent_var(env, "PHYSDEVBUS=%s", dev->bus->name);
if (dev->driver)
add_uevent_var(env, "PHYSDEVDRIVER=%s",
dev->driver->name);
}
#endif
/* have the bus specific function add its stuff */
if (dev->bus && dev->bus->uevent) {
retval = dev->bus->uevent(dev, env);
if (retval)
pr_debug("device: '%s': %s: bus uevent() returned %d\n",
dev_name(dev), __func__, retval);
}
/* have the class specific function add its stuff */
if (dev->class && dev->class->dev_uevent) {
retval = dev->class->dev_uevent(dev, env);
if (retval)
pr_debug("device: '%s': %s: class uevent() "
"returned %d\n", dev_name(dev),
__func__, retval);
}
/* have the device type specific fuction add its stuff */
if (dev->type && dev->type->uevent) {
retval = dev->type->uevent(dev, env);
if (retval)
pr_debug("device: '%s': %s: dev_type uevent() "
"returned %d\n", dev_name(dev),
__func__, retval);
}
return retval;
}
static struct kset_uevent_ops device_uevent_ops = {
.filter = dev_uevent_filter,
.name = dev_uevent_name,
.uevent = dev_uevent,
};
static ssize_t show_uevent(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct kobject *top_kobj;
struct kset *kset;
struct kobj_uevent_env *env = NULL;
int i;
size_t count = 0;
int retval;
/* search the kset, the device belongs to */
top_kobj = &dev->kobj;
while (!top_kobj->kset && top_kobj->parent)
top_kobj = top_kobj->parent;
if (!top_kobj->kset)
goto out;
kset = top_kobj->kset;
if (!kset->uevent_ops || !kset->uevent_ops->uevent)
goto out;
/* respect filter */
if (kset->uevent_ops && kset->uevent_ops->filter)
if (!kset->uevent_ops->filter(kset, &dev->kobj))
goto out;
env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
/* let the kset specific function add its keys */
retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
if (retval)
goto out;
/* copy keys to file */
for (i = 0; i < env->envp_idx; i++)
count += sprintf(&buf[count], "%s\n", env->envp[i]);
out:
kfree(env);
return count;
}
static ssize_t store_uevent(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
enum kobject_action action;
if (kobject_action_type(buf, count, &action) == 0) {
kobject_uevent(&dev->kobj, action);
goto out;
}
dev_err(dev, "uevent: unsupported action-string; this will "
"be ignored in a future kernel version\n");
kobject_uevent(&dev->kobj, KOBJ_ADD);
out:
return count;
}
static struct device_attribute uevent_attr =
__ATTR(uevent, S_IRUGO | S_IWUSR, show_uevent, store_uevent);
static int <API key>(struct device *dev,
struct device_attribute *attrs)
{
int error = 0;
int i;
if (attrs) {
for (i = 0; attr_name(attrs[i]); i++) {
error = device_create_file(dev, &attrs[i]);
if (error)
break;
}
if (error)
while (--i >= 0)
device_remove_file(dev, &attrs[i]);
}
return error;
}
static void <API key>(struct device *dev,
struct device_attribute *attrs)
{
int i;
if (attrs)
for (i = 0; attr_name(attrs[i]); i++)
device_remove_file(dev, &attrs[i]);
}
static int device_add_groups(struct device *dev,
const struct attribute_group **groups)
{
int error = 0;
int i;
if (groups) {
for (i = 0; groups[i]; i++) {
error = sysfs_create_group(&dev->kobj, groups[i]);
if (error) {
while (--i >= 0)
sysfs_remove_group(&dev->kobj,
groups[i]);
break;
}
}
}
return error;
}
static void <API key>(struct device *dev,
const struct attribute_group **groups)
{
int i;
if (groups)
for (i = 0; groups[i]; i++)
sysfs_remove_group(&dev->kobj, groups[i]);
}
static int device_add_attrs(struct device *dev)
{
struct class *class = dev->class;
struct device_type *type = dev->type;
int error;
if (class) {
error = <API key>(dev, class->dev_attrs);
if (error)
return error;
}
if (type) {
error = device_add_groups(dev, type->groups);
if (error)
goto <API key>;
}
error = device_add_groups(dev, dev->groups);
if (error)
goto <API key>;
return 0;
<API key>:
if (type)
<API key>(dev, type->groups);
<API key>:
if (class)
<API key>(dev, class->dev_attrs);
return error;
}
static void device_remove_attrs(struct device *dev)
{
struct class *class = dev->class;
struct device_type *type = dev->type;
<API key>(dev, dev->groups);
if (type)
<API key>(dev, type->groups);
if (class)
<API key>(dev, class->dev_attrs);
}
static ssize_t show_dev(struct device *dev, struct device_attribute *attr,
char *buf)
{
return print_dev_t(buf, dev->devt);
}
static struct device_attribute devt_attr =
__ATTR(dev, S_IRUGO, show_dev, NULL);
/* kset to create /sys/devices/ */
struct kset *devices_kset;
/**
* device_create_file - create sysfs attribute file for device.
* @dev: device.
* @attr: device attribute descriptor.
*/
int device_create_file(struct device *dev,
const struct device_attribute *attr)
{
int error = 0;
if (dev)
error = sysfs_create_file(&dev->kobj, &attr->attr);
return error;
}
/**
* device_remove_file - remove sysfs attribute file.
* @dev: device.
* @attr: device attribute descriptor.
*/
void device_remove_file(struct device *dev,
const struct device_attribute *attr)
{
if (dev)
sysfs_remove_file(&dev->kobj, &attr->attr);
}
/**
* <API key> - create sysfs binary attribute file for device.
* @dev: device.
* @attr: device binary attribute descriptor.
*/
int <API key>(struct device *dev,
const struct bin_attribute *attr)
{
int error = -EINVAL;
if (dev)
error = <API key>(&dev->kobj, attr);
return error;
}
EXPORT_SYMBOL_GPL(<API key>);
/**
* <API key> - remove sysfs binary attribute file
* @dev: device.
* @attr: device binary attribute descriptor.
*/
void <API key>(struct device *dev,
const struct bin_attribute *attr)
{
if (dev)
<API key>(&dev->kobj, attr);
}
EXPORT_SYMBOL_GPL(<API key>);
/**
* <API key> - helper to schedule a callback for a device
* @dev: device.
* @func: callback function to invoke later.
* @owner: module owning the callback routine
*
* Attribute methods must not unregister themselves or their parent device
* (which would amount to the same thing). Attempts to do so will deadlock,
* since unregistration is mutually exclusive with driver callbacks.
*
* Instead methods can call this routine, which will attempt to allocate
* and schedule a workqueue request to call back @func with @dev as its
* argument in the workqueue's process context. @dev will be pinned until
* @func returns.
*
* This routine is usually called via the inline <API key>(),
* which automatically sets @owner to THIS_MODULE.
*
* Returns 0 if the request was submitted, -ENOMEM if storage could not
* be allocated, -ENODEV if a reference to @owner isn't available.
*
* NOTE: This routine won't work if CONFIG_SYSFS isn't set! It uses an
* underlying sysfs routine (since it is intended for use by attribute
* methods), and if sysfs isn't available you'll get nothing but -ENOSYS.
*/
int <API key>(struct device *dev,
void (*func)(struct device *), struct module *owner)
{
return <API key>(&dev->kobj,
(void (*)(void *)) func, dev, owner);
}
EXPORT_SYMBOL_GPL(<API key>);
static void klist_children_get(struct klist_node *n)
{
struct device_private *p = <API key>(n);
struct device *dev = p->device;
get_device(dev);
}
static void klist_children_put(struct klist_node *n)
{
struct device_private *p = <API key>(n);
struct device *dev = p->device;
put_device(dev);
}
/**
* device_initialize - init device structure.
* @dev: device.
*
* This prepares the device for use by other layers by initializing
* its fields.
* It is the first half of device_register(), if called by
* that function, though it can also be called separately, so one
* may use @dev's fields. In particular, get_device()/put_device()
* may be used for reference counting of @dev after calling this
* function.
*
* NOTE: Use put_device() to give up your reference instead of freeing
* @dev directly once you have called this function.
*/
void device_initialize(struct device *dev)
{
dev->kobj.kset = devices_kset;
kobject_init(&dev->kobj, &device_ktype);
INIT_LIST_HEAD(&dev->dma_pools);
init_MUTEX(&dev->sem);
spin_lock_init(&dev->devres_lock);
INIT_LIST_HEAD(&dev->devres_head);
device_init_wakeup(dev, 0);
device_pm_init(dev);
set_dev_node(dev, -1);
}
#ifdef <API key>
static struct kobject *get_device_parent(struct device *dev,
struct device *parent)
{
/* class devices without a parent live in /sys/class/<classname>/ */
if (dev->class && (!parent || parent->class != dev->class))
return &dev->class->p->class_subsys.kobj;
/* all other devices keep their parent */
else if (parent)
return &parent->kobj;
return NULL;
}
static inline void <API key>(struct device *dev) {}
static inline void cleanup_glue_dir(struct device *dev,
struct kobject *glue_dir) {}
#else
static struct kobject *<API key>(struct device *dev)
{
static struct kobject *virtual_dir = NULL;
if (!virtual_dir)
virtual_dir = <API key>("virtual",
&devices_kset->kobj);
return virtual_dir;
}
static struct kobject *get_device_parent(struct device *dev,
struct device *parent)
{
int retval;
if (dev->class) {
static DEFINE_MUTEX(gdp_mutex);
struct kobject *kobj = NULL;
struct kobject *parent_kobj;
struct kobject *k;
/*
* If we have no parent, we live in "virtual".
* Class-devices with a non class-device as parent, live
* in a "glue" directory to prevent namespace collisions.
*/
if (parent == NULL)
parent_kobj = <API key>(dev);
else if (parent->class)
return &parent->kobj;
else
parent_kobj = &parent->kobj;
mutex_lock(&gdp_mutex);
/* find our class-directory at the parent and reference it */
spin_lock(&dev->class->p->class_dirs.list_lock);
list_for_each_entry(k, &dev->class->p->class_dirs.list, entry)
if (k->parent == parent_kobj) {
kobj = kobject_get(k);
break;
}
spin_unlock(&dev->class->p->class_dirs.list_lock);
if (kobj) {
mutex_unlock(&gdp_mutex);
return kobj;
}
/* or create a new class-directory at the parent device */
k = kobject_create();
if (!k) {
mutex_unlock(&gdp_mutex);
return NULL;
}
k->kset = &dev->class->p->class_dirs;
retval = kobject_add(k, parent_kobj, "%s", dev->class->name);
if (retval < 0) {
mutex_unlock(&gdp_mutex);
kobject_put(k);
return NULL;
}
/* do not emit an uevent for this simple "glue" directory */
mutex_unlock(&gdp_mutex);
return k;
}
if (parent)
return &parent->kobj;
return NULL;
}
static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
{
/* see if we live in a "glue" directory */
if (!glue_dir || !dev->class ||
glue_dir->kset != &dev->class->p->class_dirs)
return;
kobject_put(glue_dir);
}
static void <API key>(struct device *dev)
{
cleanup_glue_dir(dev, dev->kobj.parent);
}
#endif
static void setup_parent(struct device *dev, struct device *parent)
{
struct kobject *kobj;
kobj = get_device_parent(dev, parent);
if (kobj)
dev->kobj.parent = kobj;
}
static int <API key>(struct device *dev)
{
int error;
if (!dev->class)
return 0;
error = sysfs_create_link(&dev->kobj,
&dev->class->p->class_subsys.kobj,
"subsystem");
if (error)
goto out;
#ifdef <API key>
/* stacked class devices need a symlink in the class directory */
if (dev->kobj.parent != &dev->class->p->class_subsys.kobj &&
<API key>(dev)) {
error = sysfs_create_link(&dev->class->p->class_subsys.kobj,
&dev->kobj, dev_name(dev));
if (error)
goto out_subsys;
}
if (dev->parent && <API key>(dev)) {
struct device *parent = dev->parent;
char *class_name;
/*
* stacked class devices have the 'device' link
* pointing to the bus device instead of the parent
*/
while (parent->class && !parent->bus && parent->parent)
parent = parent->parent;
error = sysfs_create_link(&dev->kobj,
&parent->kobj,
"device");
if (error)
goto out_busid;
class_name = make_class_name(dev->class->name,
&dev->kobj);
if (class_name)
error = sysfs_create_link(&dev->parent->kobj,
&dev->kobj, class_name);
kfree(class_name);
if (error)
goto out_device;
}
return 0;
out_device:
if (dev->parent && <API key>(dev))
sysfs_remove_link(&dev->kobj, "device");
out_busid:
if (dev->kobj.parent != &dev->class->p->class_subsys.kobj &&
<API key>(dev))
sysfs_remove_link(&dev->class->p->class_subsys.kobj,
dev_name(dev));
#else
/* link in the class directory pointing to the device */
error = sysfs_create_link(&dev->class->p->class_subsys.kobj,
&dev->kobj, dev_name(dev));
if (error)
goto out_subsys;
if (dev->parent && <API key>(dev)) {
error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
"device");
if (error)
goto out_busid;
}
return 0;
out_busid:
sysfs_remove_link(&dev->class->p->class_subsys.kobj, dev_name(dev));
#endif
out_subsys:
sysfs_remove_link(&dev->kobj, "subsystem");
out:
return error;
}
static void <API key>(struct device *dev)
{
if (!dev->class)
return;
#ifdef <API key>
if (dev->parent && <API key>(dev)) {
char *class_name;
class_name = make_class_name(dev->class->name, &dev->kobj);
if (class_name) {
sysfs_remove_link(&dev->parent->kobj, class_name);
kfree(class_name);
}
sysfs_remove_link(&dev->kobj, "device");
}
if (dev->kobj.parent != &dev->class->p->class_subsys.kobj &&
<API key>(dev))
sysfs_remove_link(&dev->class->p->class_subsys.kobj,
dev_name(dev));
#else
if (dev->parent && <API key>(dev))
sysfs_remove_link(&dev->kobj, "device");
sysfs_remove_link(&dev->class->p->class_subsys.kobj, dev_name(dev));
#endif
sysfs_remove_link(&dev->kobj, "subsystem");
}
/**
* dev_set_name - set a device name
* @dev: device
* @fmt: format string for the device's name
*/
int dev_set_name(struct device *dev, const char *fmt, ...)
{
va_list vargs;
int err;
va_start(vargs, fmt);
err = <API key>(&dev->kobj, fmt, vargs);
va_end(vargs);
return err;
}
EXPORT_SYMBOL_GPL(dev_set_name);
/**
* device_to_dev_kobj - select a /sys/dev/ directory for the device
* @dev: device
*
* By default we select char/ for new entries. Setting class->dev_obj
* to NULL prevents an entry from being created. class->dev_kobj must
* be set (or cleared) before any devices are registered to the class
* otherwise <API key>() and
* <API key>() will disagree about the the presence
* of the link.
*/
static struct kobject *device_to_dev_kobj(struct device *dev)
{
struct kobject *kobj;
if (dev->class)
kobj = dev->class->dev_kobj;
else
kobj = sysfs_dev_char_kobj;
return kobj;
}
static int <API key>(struct device *dev)
{
struct kobject *kobj = device_to_dev_kobj(dev);
int error = 0;
char devt_str[15];
if (kobj) {
format_dev_t(devt_str, dev->devt);
error = sysfs_create_link(kobj, &dev->kobj, devt_str);
}
return error;
}
static void <API key>(struct device *dev)
{
struct kobject *kobj = device_to_dev_kobj(dev);
char devt_str[15];
if (kobj) {
format_dev_t(devt_str, dev->devt);
sysfs_remove_link(kobj, devt_str);
}
}
int device_private_init(struct device *dev)
{
dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
if (!dev->p)
return -ENOMEM;
dev->p->device = dev;
klist_init(&dev->p->klist_children, klist_children_get,
klist_children_put);
return 0;
}
/**
* device_add - add device to device hierarchy.
* @dev: device.
*
* This is part 2 of device_register(), though may be called
* separately _iff_ device_initialize() has been called separately.
*
* This adds @dev to the kobject hierarchy via kobject_add(), adds it
* to the global and sibling lists for the device, then
* adds it to the other relevant subsystems of the driver model.
*
* NOTE: _Never_ directly free @dev after calling this function, even
* if it returned an error! Always use put_device() to give up your
* reference instead.
*/
int device_add(struct device *dev)
{
struct device *parent = NULL;
struct class_interface *class_intf;
int error = -EINVAL;
dev = get_device(dev);
if (!dev)
goto done;
if (!dev->p) {
error = device_private_init(dev);
if (error)
goto done;
}
/*
* for statically allocated devices, which should all be converted
* some day, we need to initialize the name. We prevent reading back
* the name, and force the use of dev_name()
*/
if (dev->init_name) {
dev_set_name(dev, "%s", dev->init_name);
dev->init_name = NULL;
}
if (!dev_name(dev)) {
error = -EINVAL;
goto name_error;
}
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
parent = get_device(dev->parent);
setup_parent(dev, parent);
/* use parent numa_node */
if (parent)
set_dev_node(dev, dev_to_node(parent));
/* first, register with generic layer. */
/* we require the name to be set before, and pass NULL */
error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
if (error)
goto Error;
/* notify platform of device entry */
if (platform_notify)
platform_notify(dev);
error = device_create_file(dev, &uevent_attr);
if (error)
goto attrError;
if (MAJOR(dev->devt)) {
error = device_create_file(dev, &devt_attr);
if (error)
goto ueventattrError;
error = <API key>(dev);
if (error)
goto devtattrError;
<API key>(dev);
}
error = <API key>(dev);
if (error)
goto SymlinkError;
error = device_add_attrs(dev);
if (error)
goto AttrsError;
error = bus_add_device(dev);
if (error)
goto BusError;
error = dpm_sysfs_add(dev);
if (error)
goto DPMError;
device_pm_add(dev);
/* Notify clients of device addition. This call must come
* after dpm_sysf_add() and before kobject_uevent().
*/
if (dev->bus)
<API key>(&dev->bus->p->bus_notifier,
<API key>, dev);
kobject_uevent(&dev->kobj, KOBJ_ADD);
bus_probe_device(dev);
if (parent)
klist_add_tail(&dev->p->knode_parent,
&parent->p->klist_children);
if (dev->class) {
mutex_lock(&dev->class->p->class_mutex);
/* tie the class to the device */
klist_add_tail(&dev->knode_class,
&dev->class->p->class_devices);
/* notify any interfaces that the device is here */
list_for_each_entry(class_intf,
&dev->class->p->class_interfaces, node)
if (class_intf->add_dev)
class_intf->add_dev(dev, class_intf);
mutex_unlock(&dev->class->p->class_mutex);
}
done:
put_device(dev);
return error;
DPMError:
bus_remove_device(dev);
BusError:
device_remove_attrs(dev);
AttrsError:
<API key>(dev);
SymlinkError:
if (MAJOR(dev->devt))
<API key>(dev);
if (MAJOR(dev->devt))
<API key>(dev);
devtattrError:
if (MAJOR(dev->devt))
device_remove_file(dev, &devt_attr);
ueventattrError:
device_remove_file(dev, &uevent_attr);
attrError:
kobject_uevent(&dev->kobj, KOBJ_REMOVE);
kobject_del(&dev->kobj);
Error:
<API key>(dev);
if (parent)
put_device(parent);
name_error:
kfree(dev->p);
dev->p = NULL;
goto done;
}
/**
* device_register - register a device with the system.
* @dev: pointer to the device structure
*
* This happens in two clean steps - initialize the device
* and add it to the system. The two steps can be called
* separately, but this is the easiest and most common.
* I.e. you should only call the two helpers separately if
* have a clearly defined need to use and refcount the device
* before it is added to the hierarchy.
*
* NOTE: _Never_ directly free @dev after calling this function, even
* if it returned an error! Always use put_device() to give up the
* reference initialized in this function instead.
*/
int device_register(struct device *dev)
{
device_initialize(dev);
return device_add(dev);
}
/**
* get_device - increment reference count for device.
* @dev: device.
*
* This simply forwards the call to kobject_get(), though
* we do take care to provide for the case that we get a NULL
* pointer passed in.
*/
struct device *get_device(struct device *dev)
{
return dev ? to_dev(kobject_get(&dev->kobj)) : NULL;
}
/**
* put_device - decrement reference count.
* @dev: device in question.
*/
void put_device(struct device *dev)
{
/* might_sleep(); */
if (dev)
kobject_put(&dev->kobj);
}
/**
* device_del - delete device from system.
* @dev: device.
*
* This is the first part of the device unregistration
* sequence. This removes the device from the lists we control
* from here, has it removed from the other driver model
* subsystems it was added to in device_add(), and removes it
* from the kobject hierarchy.
*
* NOTE: this should be called manually _iff_ device_add() was
* also called manually.
*/
void device_del(struct device *dev)
{
struct device *parent = dev->parent;
struct class_interface *class_intf;
/* Notify clients of device removal. This call must come
* before dpm_sysfs_remove().
*/
if (dev->bus)
<API key>(&dev->bus->p->bus_notifier,
<API key>, dev);
device_pm_remove(dev);
dpm_sysfs_remove(dev);
if (parent)
klist_del(&dev->p->knode_parent);
if (MAJOR(dev->devt)) {
<API key>(dev);
<API key>(dev);
device_remove_file(dev, &devt_attr);
}
if (dev->class) {
<API key>(dev);
mutex_lock(&dev->class->p->class_mutex);
/* notify any interfaces that the device is now gone */
list_for_each_entry(class_intf,
&dev->class->p->class_interfaces, node)
if (class_intf->remove_dev)
class_intf->remove_dev(dev, class_intf);
/* remove the device from the class list */
klist_del(&dev->knode_class);
mutex_unlock(&dev->class->p->class_mutex);
}
device_remove_file(dev, &uevent_attr);
device_remove_attrs(dev);
bus_remove_device(dev);
/*
* Some platform devices are driven without driver attached
* and managed resources may have been acquired. Make sure
* all resources are released.
*/
devres_release_all(dev);
/* Notify the platform of the removal, in case they
* need to do anything...
*/
if (<API key>)
<API key>(dev);
kobject_uevent(&dev->kobj, KOBJ_REMOVE);
<API key>(dev);
kobject_del(&dev->kobj);
put_device(parent);
}
/**
* device_unregister - unregister device from system.
* @dev: device going away.
*
* We do this in two parts, like we do device_register(). First,
* we remove it from all the subsystems with device_del(), then
* we decrement the reference count via put_device(). If that
* is the final reference count, the device will be cleaned up
* via device_release() above. Otherwise, the structure will
* stick around until the final reference to the device is dropped.
*/
void device_unregister(struct device *dev)
{
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
device_del(dev);
put_device(dev);
}
static struct device *next_device(struct klist_iter *i)
{
struct klist_node *n = klist_next(i);
struct device *dev = NULL;
struct device_private *p;
if (n) {
p = <API key>(n);
dev = p->device;
}
return dev;
}
/**
* device_get_devnode - path of device node file
* @dev: device
* @mode: returned file access mode
* @tmp: possibly allocated string
*
* Return the relative path of a possible device node.
* Non-default names may need to allocate a memory to compose
* a name. This memory is returned in tmp and needs to be
* freed by the caller.
*/
const char *device_get_devnode(struct device *dev,
mode_t *mode, const char **tmp)
{
char *s;
*tmp = NULL;
/* the device type may provide a specific name */
if (dev->type && dev->type->devnode)
*tmp = dev->type->devnode(dev, mode);
if (*tmp)
return *tmp;
/* the class may provide a specific name */
if (dev->class && dev->class->devnode)
*tmp = dev->class->devnode(dev, mode);
if (*tmp)
return *tmp;
/* return name without allocation, tmp == NULL */
if (strchr(dev_name(dev), '!') == NULL)
return dev_name(dev);
/* replace '!' in the name with '/' */
*tmp = kstrdup(dev_name(dev), GFP_KERNEL);
if (!*tmp)
return NULL;
while ((s = strchr(*tmp, '!')))
s[0] = '/';
return *tmp;
}
/**
* <API key> - device child iterator.
* @parent: parent struct device.
* @data: data for the callback.
* @fn: function to be called for each device.
*
* Iterate over @parent's child devices, and call @fn for each,
* passing it @data.
*
* We check the return of @fn each time. If it returns anything
* other than 0, we break out and return that value.
*/
int <API key>(struct device *parent, void *data,
int (*fn)(struct device *dev, void *data))
{
struct klist_iter i;
struct device *child;
int error = 0;
if (!parent->p)
return 0;
klist_iter_init(&parent->p->klist_children, &i);
while ((child = next_device(&i)) && !error)
error = fn(child, data);
klist_iter_exit(&i);
return error;
}
/**
* device_find_child - device iterator for locating a particular device.
* @parent: parent struct device
* @data: Data to pass to match function
* @match: Callback function to check device
*
* This is similar to the <API key>() function above, but it
* returns a reference to a device that is 'found' for later use, as
* determined by the @match callback.
*
* The callback should return 0 if the device doesn't match and non-zero
* if it does. If the callback returns non-zero and a reference to the
* current device can be obtained, this function will return to the caller
* and not iterate over any more devices.
*/
struct device *device_find_child(struct device *parent, void *data,
int (*match)(struct device *dev, void *data))
{
struct klist_iter i;
struct device *child;
if (!parent)
return NULL;
klist_iter_init(&parent->p->klist_children, &i);
while ((child = next_device(&i)))
if (match(child, data) && get_device(child))
break;
klist_iter_exit(&i);
return child;
}
int __init devices_init(void)
{
devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
if (!devices_kset)
return -ENOMEM;
dev_kobj = <API key>("dev", NULL);
if (!dev_kobj)
goto dev_kobj_err;
<API key> = <API key>("block", dev_kobj);
if (!<API key>)
goto block_kobj_err;
sysfs_dev_char_kobj = <API key>("char", dev_kobj);
if (!sysfs_dev_char_kobj)
goto char_kobj_err;
return 0;
char_kobj_err:
kobject_put(<API key>);
block_kobj_err:
kobject_put(dev_kobj);
dev_kobj_err:
kset_unregister(devices_kset);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(<API key>);
EXPORT_SYMBOL_GPL(device_find_child);
EXPORT_SYMBOL_GPL(device_initialize);
EXPORT_SYMBOL_GPL(device_add);
EXPORT_SYMBOL_GPL(device_register);
EXPORT_SYMBOL_GPL(device_del);
EXPORT_SYMBOL_GPL(device_unregister);
EXPORT_SYMBOL_GPL(get_device);
EXPORT_SYMBOL_GPL(put_device);
EXPORT_SYMBOL_GPL(device_create_file);
EXPORT_SYMBOL_GPL(device_remove_file);
struct root_device
{
struct device dev;
struct module *owner;
};
#define to_root_device(dev) container_of(dev, struct root_device, dev)
static void root_device_release(struct device *dev)
{
kfree(to_root_device(dev));
}
/**
* <API key> - allocate and register a root device
* @name: root device name
* @owner: owner module of the root device, usually THIS_MODULE
*
* This function allocates a root device and registers it
* using device_register(). In order to free the returned
* device, use <API key>().
*
* Root devices are dummy devices which allow other devices
* to be grouped under /sys/devices. Use this function to
* allocate a root device and then use it as the parent of
* any device which should appear under /sys/devices/{name}
*
* The /sys/devices/{name} directory will also contain a
* 'module' symlink which points to the @owner directory
* in sysfs.
*
* Note: You probably want to use <API key>().
*/
struct device *<API key>(const char *name, struct module *owner)
{
struct root_device *root;
int err = -ENOMEM;
root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
if (!root)
return ERR_PTR(err);
err = dev_set_name(&root->dev, "%s", name);
if (err) {
kfree(root);
return ERR_PTR(err);
}
root->dev.release = root_device_release;
err = device_register(&root->dev);
if (err) {
put_device(&root->dev);
return ERR_PTR(err);
}
#ifdef CONFIG_MODULE /* gotta find a "cleaner" way to do this */
if (owner) {
struct module_kobject *mk = &owner->mkobj;
err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
if (err) {
device_unregister(&root->dev);
return ERR_PTR(err);
}
root->owner = owner;
}
#endif
return &root->dev;
}
EXPORT_SYMBOL_GPL(<API key>);
void <API key>(struct device *dev)
{
struct root_device *root = to_root_device(dev);
if (root->owner)
sysfs_remove_link(&root->dev.kobj, "module");
device_unregister(dev);
}
EXPORT_SYMBOL_GPL(<API key>);
static void <API key>(struct device *dev)
{
pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
kfree(dev);
}
/**
* device_create_vargs - creates a device and registers it with sysfs
* @class: pointer to the struct class that this device should be registered to
* @parent: pointer to the parent struct device of this new device, if any
* @devt: the dev_t for the char device to be added
* @drvdata: the data to be added to the device for callbacks
* @fmt: string for the device's name
* @args: va_list for the device's name
*
* This function can be used by char device classes. A struct device
* will be created in sysfs, registered to the specified class.
*
* A "dev" file will be created, showing the dev_t for the device, if
* the dev_t is not 0,0.
* If a pointer to a parent struct device is passed in, the newly created
* struct device will be a child of that device in sysfs.
* The pointer to the struct device will be returned from the call.
* Any further sysfs files that might be required can be created using this
* pointer.
*
* Note: the struct class passed to this function must have previously
* been created with a call to class_create().
*/
struct device *device_create_vargs(struct class *class, struct device *parent,
dev_t devt, void *drvdata, const char *fmt,
va_list args)
{
struct device *dev = NULL;
int retval = -ENODEV;
if (class == NULL || IS_ERR(class))
goto error;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
retval = -ENOMEM;
goto error;
}
dev->devt = devt;
dev->class = class;
dev->parent = parent;
dev->release = <API key>;
dev_set_drvdata(dev, drvdata);
retval = <API key>(&dev->kobj, fmt, args);
if (retval)
goto error;
retval = device_register(dev);
if (retval)
goto error;
return dev;
error:
put_device(dev);
return ERR_PTR(retval);
}
EXPORT_SYMBOL_GPL(device_create_vargs);
/**
* device_create - creates a device and registers it with sysfs
* @class: pointer to the struct class that this device should be registered to
* @parent: pointer to the parent struct device of this new device, if any
* @devt: the dev_t for the char device to be added
* @drvdata: the data to be added to the device for callbacks
* @fmt: string for the device's name
*
* This function can be used by char device classes. A struct device
* will be created in sysfs, registered to the specified class.
*
* A "dev" file will be created, showing the dev_t for the device, if
* the dev_t is not 0,0.
* If a pointer to a parent struct device is passed in, the newly created
* struct device will be a child of that device in sysfs.
* The pointer to the struct device will be returned from the call.
* Any further sysfs files that might be required can be created using this
* pointer.
*
* Note: the struct class passed to this function must have previously
* been created with a call to class_create().
*/
struct device *device_create(struct class *class, struct device *parent,
dev_t devt, void *drvdata, const char *fmt, ...)
{
va_list vargs;
struct device *dev;
va_start(vargs, fmt);
dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs);
va_end(vargs);
return dev;
}
EXPORT_SYMBOL_GPL(device_create);
static int __match_devt(struct device *dev, void *data)
{
dev_t *devt = data;
return dev->devt == *devt;
}
/**
* device_destroy - removes a device that was created with device_create()
* @class: pointer to the struct class that this device was registered with
* @devt: the dev_t of the device that was previously registered
*
* This call unregisters and cleans up a device that was created with a
* call to device_create().
*/
void device_destroy(struct class *class, dev_t devt)
{
struct device *dev;
dev = class_find_device(class, NULL, &devt, __match_devt);
if (dev) {
put_device(dev);
device_unregister(dev);
}
}
EXPORT_SYMBOL_GPL(device_destroy);
/**
* device_rename - renames a device
* @dev: the pointer to the struct device to be renamed
* @new_name: the new name of the device
*
* It is the responsibility of the caller to provide mutual
* exclusion between two different calls of device_rename
* on the same device to ensure that new_name is valid and
* won't conflict with other devices.
*/
int device_rename(struct device *dev, char *new_name)
{
char *old_class_name = NULL;
char *new_class_name = NULL;
char *old_device_name = NULL;
int error;
dev = get_device(dev);
if (!dev)
return -EINVAL;
pr_debug("device: '%s': %s: renaming to '%s'\n", dev_name(dev),
__func__, new_name);
#ifdef <API key>
if ((dev->class) && (dev->parent))
old_class_name = make_class_name(dev->class->name, &dev->kobj);
#endif
old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
if (!old_device_name) {
error = -ENOMEM;
goto out;
}
error = kobject_rename(&dev->kobj, new_name);
if (error)
goto out;
#ifdef <API key>
if (old_class_name) {
new_class_name = make_class_name(dev->class->name, &dev->kobj);
if (new_class_name) {
error = <API key>(&dev->parent->kobj,
&dev->kobj,
new_class_name);
if (error)
goto out;
sysfs_remove_link(&dev->parent->kobj, old_class_name);
}
}
#else
if (dev->class) {
error = <API key>(&dev->class->p->class_subsys.kobj,
&dev->kobj, dev_name(dev));
if (error)
goto out;
sysfs_remove_link(&dev->class->p->class_subsys.kobj,
old_device_name);
}
#endif
out:
put_device(dev);
kfree(new_class_name);
kfree(old_class_name);
kfree(old_device_name);
return error;
}
EXPORT_SYMBOL_GPL(device_rename);
static int <API key>(struct device *dev,
struct device *old_parent,
struct device *new_parent)
{
int error = 0;
#ifdef <API key>
char *class_name;
class_name = make_class_name(dev->class->name, &dev->kobj);
if (!class_name) {
error = -ENOMEM;
goto out;
}
if (old_parent) {
sysfs_remove_link(&dev->kobj, "device");
sysfs_remove_link(&old_parent->kobj, class_name);
}
if (new_parent) {
error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
"device");
if (error)
goto out;
error = sysfs_create_link(&new_parent->kobj, &dev->kobj,
class_name);
if (error)
sysfs_remove_link(&dev->kobj, "device");
} else
error = 0;
out:
kfree(class_name);
return error;
#else
if (old_parent)
sysfs_remove_link(&dev->kobj, "device");
if (new_parent)
error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
"device");
return error;
#endif
}
/**
* device_move - moves a device to a new parent
* @dev: the pointer to the struct device to be moved
* @new_parent: the new parent of the device (can by NULL)
* @dpm_order: how to reorder the dpm_list
*/
int device_move(struct device *dev, struct device *new_parent,
enum dpm_order dpm_order)
{
int error;
struct device *old_parent;
struct kobject *new_parent_kobj;
dev = get_device(dev);
if (!dev)
return -EINVAL;
device_pm_lock();
new_parent = get_device(new_parent);
new_parent_kobj = get_device_parent(dev, new_parent);
pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
__func__, new_parent ? dev_name(new_parent) : "<NULL>");
error = kobject_move(&dev->kobj, new_parent_kobj);
if (error) {
cleanup_glue_dir(dev, new_parent_kobj);
put_device(new_parent);
goto out;
}
old_parent = dev->parent;
dev->parent = new_parent;
if (old_parent)
klist_remove(&dev->p->knode_parent);
if (new_parent) {
klist_add_tail(&dev->p->knode_parent,
&new_parent->p->klist_children);
set_dev_node(dev, dev_to_node(new_parent));
}
if (!dev->class)
goto out_put;
error = <API key>(dev, old_parent, new_parent);
if (error) {
/* We ignore errors on cleanup since we're hosed anyway... */
<API key>(dev, new_parent, old_parent);
if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
if (new_parent)
klist_remove(&dev->p->knode_parent);
dev->parent = old_parent;
if (old_parent) {
klist_add_tail(&dev->p->knode_parent,
&old_parent->p->klist_children);
set_dev_node(dev, dev_to_node(old_parent));
}
}
cleanup_glue_dir(dev, new_parent_kobj);
put_device(new_parent);
goto out;
}
switch (dpm_order) {
case DPM_ORDER_NONE:
break;
case <API key>:
<API key>(dev, new_parent);
break;
case <API key>:
<API key>(new_parent, dev);
break;
case DPM_ORDER_DEV_LAST:
device_pm_move_last(dev);
break;
}
out_put:
put_device(old_parent);
out:
device_pm_unlock();
put_device(dev);
return error;
}
EXPORT_SYMBOL_GPL(device_move);
/**
* device_shutdown - call ->shutdown() on each device to shutdown.
*/
void device_shutdown(void)
{
struct device *dev, *devn;
<API key>(dev, devn, &devices_kset->list,
kobj.entry) {
if (dev->bus && dev->bus->shutdown) {
dev_dbg(dev, "shutdown\n");
dev->bus->shutdown(dev);
} else if (dev->driver && dev->driver->shutdown) {
dev_dbg(dev, "shutdown\n");
dev->driver->shutdown(dev);
}
}
<API key>();
}
|
/* This particular implementation was written by Eric Blake, 2008. */
#ifndef _LIBC
# include <config.h>
#endif
/* Specification of memmem. */
#include <string.h>
#ifndef _LIBC
# define __builtin_expect(expr, val) (expr)
#endif
#define RETURN_TYPE void *
#define AVAILABLE(h, h_l, j, n_l) ((j) <= (h_l) - (n_l))
#include "str-two-way.h"
/* Return the first occurrence of NEEDLE in HAYSTACK. Return HAYSTACK
if NEEDLE_LEN is 0, otherwise NULL if NEEDLE is not found in
HAYSTACK. */
void *
memmem (const void *haystack_start, size_t haystack_len,
const void *needle_start, size_t needle_len)
{
/* Abstract memory is considered to be an array of 'unsigned char' values,
not an array of 'char' values. See ISO C 99 section 6.2.6.1. */
const unsigned char *haystack = (const unsigned char *) haystack_start;
const unsigned char *needle = (const unsigned char *) needle_start;
if (needle_len == 0)
/* The first occurrence of the empty string is deemed to occur at
the beginning of the string. */
return (void *) haystack;
/* Sanity check, otherwise the loop might search through the whole
memory. */
if (__builtin_expect (haystack_len < needle_len, 0))
return NULL;
/* Use optimizations in memchr when possible, to reduce the search
size of haystack using a linear algorithm with a smaller
coefficient. However, avoid memchr for long needles, since we
can often achieve sublinear performance. */
if (needle_len < <API key>)
{
haystack = memchr (haystack, *needle, haystack_len);
if (!haystack || __builtin_expect (needle_len == 1, 0))
return (void *) haystack;
haystack_len -= haystack - (const unsigned char *) haystack_start;
if (haystack_len < needle_len)
return NULL;
return <API key> (haystack, haystack_len, needle, needle_len);
}
else
return two_way_long_needle (haystack, haystack_len, needle, needle_len);
}
#undef <API key>
|
# -*- coding: utf-8 -*-
# This file is part of Invenio.
# Invenio is free software; you can redistribute it and/or
# published by the Free Software Foundation; either version 2 of the
# Invenio is distributed in the hope that it will be useful, but
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from invenio.bibauthorid_config import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_config import <API key> # emitting #pylint: disable-msg=W0611
# import invenio.bibauthorid_webapi as webapi
# import invenio.bibauthorid_config as bconfig
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import get_names_of_author # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import get_authors_by_name # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import get_title_of_paper # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import author_has_papers # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import is_valid_bibref # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_webapi import get_hepnames # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key> # emitting #pylint: disable-msg=W0611
from invenio.bib<API key> import <API key>
from invenio.bib<API key> import <API key>
from invenio.bib<API key> import <API key>
from invenio.<API key> import split_name_parts # emitting #pylint: disable-msg=W0611
# from invenio.bibauthorid_config import <API key>
from invenio.bibauthorid_config import AID_ENABLED # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_config import AID_ON_AUTHORPAGES # emitting #pylint: disable-msg=W0611
from invenio import bib<API key> as pt # emitting #pylint: disable-msg=W0611
def <API key>(pid):
return [p[0] for p in <API key>(pid)]
|
#include "packet_list_record.h"
#include <file.h>
#include <epan/epan_dissect.h>
#include <epan/column-info.h>
#include <epan/column.h>
#include <epan/conversation.h>
#include <epan/color_filters.h>
#include "frame_tvbuff.h"
#include <QStringList>
QMap<int, int> PacketListRecord::cinfo_column_;
unsigned PacketListRecord::col_data_ver_ = 1;
PacketListRecord::PacketListRecord(frame_data *frameData) :
fdata_(frameData),
lines_(1),
line_count_changed_(false),
data_ver_(0),
colorized_(false),
conv_(NULL)
{
}
// We might want to return a const char * instead. This would keep us from
// creating excessive QByteArrays, e.g. in PacketListModel::recordLessThan.
const QByteArray PacketListRecord::columnString(capture_file *cap_file, int column, bool colorized)
{
// packet_list_store.c:<API key>
g_assert(fdata_);
if (!cap_file || column < 0 || column > cap_file->cinfo.num_cols) {
return QByteArray();
}
bool dissect_color = colorized && !colorized_;
if (column >= col_text_.size() || !col_text_[column] || data_ver_ != col_data_ver_ || dissect_color) {
dissect(cap_file, dissect_color);
}
return col_text_.value(column, QByteArray());
}
void PacketListRecord::resetColumns(column_info *cinfo)
{
col_data_ver_++;
if (!cinfo) {
return;
}
cinfo_column_.clear();
int i, j;
for (i = 0, j = 0; i < cinfo->num_cols; i++) {
if (!<API key>(cinfo, i)) {
cinfo_column_[i] = j;
j++;
}
}
}
void PacketListRecord::resetColorized()
{
colorized_ = false;
}
void PacketListRecord::dissect(capture_file *cap_file, bool dissect_color)
{
// packet_list_store.c:<API key>
epan_dissect_t edt;
column_info *cinfo = NULL;
gboolean create_proto_tree;
struct wtap_pkthdr phdr; /* Packet header */
Buffer buf; /* Packet data */
gboolean dissect_columns = col_text_.isEmpty() || data_ver_ != col_data_ver_;
if (!cap_file) {
return;
}
memset(&phdr, 0, sizeof(struct wtap_pkthdr));
if (dissect_columns) {
cinfo = &cap_file->cinfo;
}
ws_buffer_init(&buf, 1500);
if (!cf_read_record_r(cap_file, fdata_, &phdr, &buf)) {
/*
* Error reading the record.
*
* Don't set the color filter for now (we might want
* to colorize it in some fashion to warn that the
* row couldn't be filled in or colorized), and
* set the columns to placeholder values, except
* for the Info column, where we'll put in an
* error message.
*/
if (dissect_columns) {
col_fill_in_error(cinfo, fdata_, FALSE, FALSE /* fill_fd_columns */);
cacheColumnStrings(cinfo);
}
if (dissect_color) {
fdata_->color_filter = NULL;
colorized_ = true;
}
ws_buffer_free(&buf);
return; /* error reading the record */
}
create_proto_tree = ((dissect_color && color_filters_used()) ||
(dissect_columns && (have_custom_cols(cinfo) ||
<API key>())));
epan_dissect_init(&edt, cap_file->epan,
create_proto_tree,
FALSE /* proto_tree_visible */);
/* Re-color when the coloring rules are changed via the UI. */
if (dissect_color) {
<API key>(&edt);
fdata_->flags.need_colorize = 1;
}
if (dissect_columns)
<API key>(&edt, cinfo);
/*
* XXX - need to catch an OutOfMemoryError exception and
* attempt to recover from it.
*/
epan_dissect_run(&edt, cap_file->cd_t, &phdr, <API key>(fdata_, &buf), fdata_, cinfo);
if (dissect_columns) {
/* "Stringify" non frame_data vals */
<API key>(&edt, FALSE, FALSE /* fill_fd_columns */);
cacheColumnStrings(cinfo);
}
if (dissect_color) {
colorized_ = true;
}
data_ver_ = col_data_ver_;
packet_info *pi = &edt.pi;
conv_ = find_conversation(pi->num, &pi->src, &pi->dst, pi->ptype,
pi->srcport, pi->destport, 0);
<API key>(&edt);
ws_buffer_free(&buf);
}
// This assumes only one packet list. We might want to move this to
// PacketListModel (or replace this with a wmem allocator).
struct _GStringChunk *PacketListRecord::string_pool_ = g_string_chunk_new(1 * 1024 * 1024);
void PacketListRecord::clearStringPool()
{
<API key>(string_pool_);
}
//#define <API key> 1
void PacketListRecord::cacheColumnStrings(column_info *cinfo)
{
// packet_list_store.c:<API key>(PacketList *packet_list, PacketListRecord *record, gint col, column_info *cinfo)
if (!cinfo) {
return;
}
col_text_.clear();
lines_ = 1;
line_count_changed_ = false;
for (int column = 0; column < cinfo->num_cols; ++column) {
int col_lines = 1;
#ifdef <API key>
int text_col = cinfo_column_.value(column, -1);
/* Column based on frame_data or it already contains a value */
if (text_col < 0) {
<API key>(fdata_, cinfo, column, FALSE);
col_text_.append(cinfo->columns[column].col_data);
continue;
}
switch (cinfo->col_fmt[column]) {
case COL_PROTOCOL:
case COL_INFO:
case COL_IF_DIR:
case COL_DCE_CALL:
case COL_8021Q_VLAN_ID:
case COL_EXPERT:
case COL_FREQ_CHAN:
if (cinfo->columns[column].col_data && cinfo->columns[column].col_data != cinfo->columns[column].col_buf) {
/* This is a constant string, so we don't have to copy it */
// XXX - ui/gtk/packet_list_store.c uses G_MAXUSHORT. We don't do proper UTF8
// truncation in either case.
int col_text_len = MIN(qstrlen(cinfo->col_data[column]) + 1, COL_MAX_INFO_LEN);
col_text_.append(QByteArray::fromRawData(cinfo->columns[column].col_data, col_text_len));
break;
}
/* !! FALL-THROUGH!! */
case COL_DEF_SRC:
case COL_RES_SRC: /* COL_DEF_SRC is currently just like COL_RES_SRC */
case COL_UNRES_SRC:
case COL_DEF_DL_SRC:
case COL_RES_DL_SRC:
case COL_UNRES_DL_SRC:
case COL_DEF_NET_SRC:
case COL_RES_NET_SRC:
case COL_UNRES_NET_SRC:
case COL_DEF_DST:
case COL_RES_DST: /* COL_DEF_DST is currently just like COL_RES_DST */
case COL_UNRES_DST:
case COL_DEF_DL_DST:
case COL_RES_DL_DST:
case COL_UNRES_DL_DST:
case COL_DEF_NET_DST:
case COL_RES_NET_DST:
case COL_UNRES_NET_DST:
default:
if (!get_column_resolved(column) && cinfo->col_expr.col_expr_val[column]) {
/* Use the unresolved value in col_expr_val */
// XXX Use QContiguousCache?
col_text_.append(cinfo->col_expr.col_expr_val[column]);
} else {
col_text_.append(cinfo->columns[column].col_data);
}
break;
}
#else // <API key>
const char *col_str;
if (!get_column_resolved(column) && cinfo->col_expr.col_expr_val[column]) {
/* Use the unresolved value in col_expr_val */
col_str = cinfo->col_expr.col_expr_val[column];
} else {
int text_col = cinfo_column_.value(column, -1);
if (text_col < 0) {
<API key>(fdata_, cinfo, column, FALSE);
}
col_str = cinfo->columns[column].col_data;
}
// <API key> manages a hash table of pointers to
// strings:
// We might be better off adding the equivalent functionality to
// wmem_tree.
col_text_.append(<API key>(string_pool_, col_str));
for (int i = 0; col_str[i]; i++) {
if (col_str[i] == '\n') col_lines++;
}
if (col_lines > lines_) {
lines_ = col_lines;
line_count_changed_ = true;
}
#endif // <API key>
}
}
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
|
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/spinlock.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/writeback.h>
#include <linux/init.h>
#include <linux/backing-dev.h>
#include <linux/<API key>.h>
#include <linux/blkdev.h>
#include <linux/mpage.h>
#include <linux/rmap.h>
#include <linux/percpu.h>
#include <linux/notifier.h>
#include <linux/smp.h>
#include <linux/sysctl.h>
#include <linux/cpu.h>
#include <linux/syscalls.h>
#include <linux/buffer_head.h> /* <API key> */
#include <linux/pagevec.h>
#include <linux/timer.h>
#include <linux/sched/rt.h>
#include <trace/events/writeback.h>
#ifdef <API key>
#include <linux/powersuspend.h>
#endif
/*
* Sleep at most 200ms at a time in balance_dirty_pages().
*/
#define MAX_PAUSE max(HZ/5, 1)
/*
* Try to keep balance_dirty_pages() call intervals higher than this many pages
* by raising pause time to max_pause when falls below it.
*/
#define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
/*
* Estimate write bandwidth at 200ms intervals.
*/
#define BANDWIDTH_INTERVAL max(HZ/5, 1)
#define <API key> 10
/*
* After a CPU has dirtied this many pages, <API key>
* will look to see if it needs to force writeback or throttling.
*/
static long ratelimit_pages = 32;
/* The following parameters are exported via /proc/sys/vm */
/*
* Start background writeback (via writeback threads) at this percentage
*/
int <API key> = 10;
/*
* <API key> starts at 0 (disabled) so that it is a function of
* <API key> * the amount of dirtyable memory
*/
unsigned long <API key>;
/*
* free highmem will not be subtracted from the total free memory
* for calculating free ratios if <API key> is true
*/
int <API key>;
/*
* The generator of dirty data starts writeback at this percentage
*/
int vm_dirty_ratio = 20;
/*
* vm_dirty_bytes starts at 0 (disabled) so that it is a function of
* vm_dirty_ratio * the amount of dirtyable memory
*/
unsigned long vm_dirty_bytes;
/*
* The default intervals between `kupdate'-style writebacks
*/
#define <API key> 5 * 100 /* centiseconds */
#define <API key> 15 * 100 /* centiseconds */
/*
* The interval between `kupdate'-style writebacks
*/
unsigned int <API key> = <API key>; /* centiseconds */
EXPORT_SYMBOL_GPL(<API key>);
#ifdef <API key>
/*
* The dynamic writeback activation status
*/
int <API key> = 1;
EXPORT_SYMBOL_GPL(<API key>);
/*
* The interval between `kupdate'-style writebacks when the system is active
*/
unsigned int <API key> = <API key>; /* centiseconds */
EXPORT_SYMBOL_GPL(<API key>);
/*
* The interval between `kupdate'-style writebacks when the system is suspended
*/
unsigned int <API key> = <API key>; /* centiseconds */
EXPORT_SYMBOL_GPL(<API key>);
#endif
/*
* The longest time for which data is allowed to remain dirty
*/
#define <API key> 2000 /* centiseconds */
#define <API key> 12000 /* centiseconds */
unsigned int <API key>,
<API key>;
unsigned int <API key>,
<API key>;
/*
* Flag that makes the machine dump writes/reads and block dirtyings.
*/
int block_dump;
/*
* Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
* a full sync is triggered after this time elapses without any disk activity.
*/
int laptop_mode;
EXPORT_SYMBOL(laptop_mode);
/* End of sysctl-exported parameters */
unsigned long global_dirty_limit;
/*
* Scale the writeback cache size proportional to the relative writeout speeds.
*
* We do this by keeping a floating proportion between BDIs, based on page
* writeback completions [end_page_writeback()]. Those devices that write out
* pages fastest will get the larger share, while the slower will get a smaller
* share.
*
* We use page writeout completions because we are interested in getting rid of
* dirty pages. Having them written out is the primary goal.
*
* We introduce a concept of time, a period over which we measure these events,
* because demand can/will vary over time. The length of this period itself is
* measured in page writeback completions.
*
*/
static struct fprop_global <API key>;
static void writeout_period(unsigned long t);
/* Timer for aging of <API key> */
static struct timer_list <API key> =
<API key>(writeout_period, 0, 0);
static unsigned long <API key> = 0;
/*
* Length of period for aging writeout fractions of bdis. This is an
* arbitrarily chosen number. The longer the period, the slower fractions will
* reflect changes in current writeout rate.
*/
#define <API key> (3*HZ)
/*
* Work out the current dirty-memory clamping and background writeout
* thresholds.
*
* The main aim here is to lower them aggressively if there is a lot of mapped
* memory around. To avoid stressing page reclaim with lots of unreclaimable
* pages. It is better to clamp down on writers than to start swapping, and
* performing lots of scanning.
*
* We only allow 1/2 of the currently-unmapped memory to be dirtied.
*
* We don't permit the clamping level to fall below 5% - that is getting rather
* excessive.
*
* We make sure that the background writeout level is below the adjusted
* clamping level.
*/
/*
* In a memory zone, there is a certain amount of pages we consider
* available for the page cache, which is essentially the number of
* free and reclaimable pages, minus some zone reserves to protect
* lowmem and the ability to uphold the zone's watermarks without
* requiring writeback.
*
* This number of dirtyable pages is the base value of which the
* user-configurable dirty ratio is the effictive number of pages that
* are allowed to be actually dirtied. Per individual zone, or
* globally by using the sum of dirtyable pages over all zones.
*
* Because the user is allowed to specify the dirty limit globally as
* absolute number of bytes, calculating the per-zone dirty limit can
* require translating the configured limit into a percentage of
* global dirtyable memory first.
*/
/**
* <API key> - number of dirtyable pages in a zone
* @zone: the zone
*
* Returns the zone's number of pages potentially available for dirty
* page cache. This is the base value for the per-zone dirty limits.
*/
static unsigned long <API key>(struct zone *zone)
{
unsigned long nr_pages;
nr_pages = zone_page_state(zone, NR_FREE_PAGES);
nr_pages -= min(nr_pages, zone-><API key>);
nr_pages += zone_page_state(zone, NR_INACTIVE_FILE);
nr_pages += zone_page_state(zone, NR_ACTIVE_FILE);
return nr_pages;
}
static unsigned long <API key>(unsigned long total)
{
#ifdef CONFIG_HIGHMEM
int node;
unsigned long x = 0;
for_each_node_state(node, N_HIGH_MEMORY) {
unsigned long nr_pages;
struct zone *z =
&NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
nr_pages = zone_page_state(z, NR_FREE_PAGES) +
<API key>(z);
/*
* make sure that the number of pages for this node
* is never "negative".
*/
nr_pages -= min(nr_pages, z-><API key>);
x += nr_pages;
}
/*
* Unreclaimable memory (kernel memory or anonymous memory
* without swap) can bring down the dirtyable pages below
* the zone's dirty balance reserve and the above calculation
* will underflow. However we still want to add in nodes
* which are below threshold (negative values) to get a more
* accurate calculation but make sure that the total never
* underflows.
*/
if ((long)x < 0)
x = 0;
/*
* Make sure that the number of highmem pages is never larger
* than the number of the total dirtyable memory. This can only
* occur in very strange VM situations but we want to make sure
* that this does not occur.
*/
return min(x, total);
#else
return 0;
#endif
}
/**
* <API key> - number of globally dirtyable pages
*
* Returns the global number of pages potentially available for dirty
* page cache. This is the base value for the global dirty limits.
*/
static unsigned long <API key>(void)
{
unsigned long x;
x = global_page_state(NR_FREE_PAGES);
x -= min(x, <API key>);
x += global_page_state(NR_INACTIVE_FILE);
x += global_page_state(NR_ACTIVE_FILE);
if (!<API key>)
x -= min(x, <API key>(x));
/* Subtract min_free_kbytes */
x -= min_t(unsigned long, x, min_free_kbytes >> (PAGE_SHIFT - 10));
return x + 1; /* Ensure that we never return 0 */
}
/*
* global_dirty_limits - <API key> and dirty-throttling thresholds
*
* Calculate the dirty thresholds based on sysctl parameters
* - vm.<API key> or vm.<API key>
* - vm.dirty_ratio or vm.dirty_bytes
* The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
* real-time tasks.
*/
void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
{
unsigned long background;
unsigned long dirty;
unsigned long uninitialized_var(available_memory);
struct task_struct *tsk;
if (!vm_dirty_bytes || !<API key>)
available_memory = <API key>();
if (vm_dirty_bytes)
dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
else
dirty = (vm_dirty_ratio * available_memory) / 100;
if (<API key>)
background = DIV_ROUND_UP(<API key>, PAGE_SIZE);
else
background = (<API key> * available_memory) / 100;
#if defined(<API key>) && <API key> > 0
if (!vm_dirty_bytes && dirty < <API key>) {
dirty = <API key>;
if (!<API key>)
background = dirty / 2;
}
#endif
if (background >= dirty)
background = dirty / 2;
tsk = current;
if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
background += background / 4;
dirty += dirty / 4;
}
*pbackground = background;
*pdirty = dirty;
<API key>(background, dirty);
}
/**
* zone_dirty_limit - maximum number of dirty pages allowed in a zone
* @zone: the zone
*
* Returns the maximum number of dirty pages allowed in a zone, based
* on the zone's dirtyable memory.
*/
static unsigned long zone_dirty_limit(struct zone *zone)
{
unsigned long zone_memory = <API key>(zone);
struct task_struct *tsk = current;
unsigned long dirty;
if (vm_dirty_bytes)
dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
zone_memory / <API key>();
else
dirty = vm_dirty_ratio * zone_memory / 100;
if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk))
dirty += dirty / 4;
return dirty;
}
/**
* zone_dirty_ok - tells whether a zone is within its dirty limits
* @zone: the zone to check
*
* Returns %true when the dirty pages in @zone are within the zone's
* dirty limit, %false if the limit is exceeded.
*/
bool zone_dirty_ok(struct zone *zone)
{
unsigned long limit = zone_dirty_limit(zone);
return zone_page_state(zone, NR_FILE_DIRTY) +
zone_page_state(zone, NR_UNSTABLE_NFS) +
zone_page_state(zone, NR_WRITEBACK) <= limit;
}
int <API key>(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
ret = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write)
<API key> = 0;
return ret;
}
int <API key>(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret;
ret = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write)
<API key> = 0;
return ret;
}
int dirty_ratio_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int old_ratio = vm_dirty_ratio;
int ret;
ret = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
<API key>();
vm_dirty_bytes = 0;
}
return ret;
}
int dirty_bytes_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
unsigned long old_bytes = vm_dirty_bytes;
int ret;
ret = <API key>(table, write, buffer, lenp, ppos);
if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
<API key>();
vm_dirty_ratio = 0;
}
return ret;
}
static unsigned long wp_next_time(unsigned long cur_time)
{
cur_time += <API key>;
/* 0 has a special meaning... */
if (!cur_time)
return 1;
return cur_time;
}
/*
* Increment the BDI's writeout completion count and the global writeout
* completion count. Called from <API key>().
*/
static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
{
__inc_bdi_stat(bdi, BDI_WRITTEN);
<API key>(&<API key>, &bdi->completions,
bdi->max_prop_frac);
/* First event after period switching was turned off? */
if (!unlikely(<API key>)) {
/*
* We can race with other __bdi_writeout_inc calls here but
* it does not cause any harm since the resulting time when
* timer will fire and what is in <API key> will be
* roughly the same.
*/
<API key> = wp_next_time(jiffies);
mod_timer(&<API key>, <API key>);
}
}
void bdi_writeout_inc(struct backing_dev_info *bdi)
{
unsigned long flags;
local_irq_save(flags);
__bdi_writeout_inc(bdi);
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(bdi_writeout_inc);
/*
* Obtain an accurate fraction of the BDI's portion.
*/
static void <API key>(struct backing_dev_info *bdi,
long *numerator, long *denominator)
{
<API key>(&<API key>, &bdi->completions,
numerator, denominator);
}
/*
* On idle system, we can be called long after we scheduled because we use
* deferred timers so count with missed periods.
*/
static void writeout_period(unsigned long t)
{
int miss_periods = (jiffies - <API key>) /
<API key>;
if (fprop_new_period(&<API key>, miss_periods + 1)) {
<API key> = wp_next_time(<API key> +
miss_periods * <API key>);
mod_timer(&<API key>, <API key>);
} else {
/*
* Aging has zeroed all fractions. Stop wasting CPU on period
* updates.
*/
<API key> = 0;
}
}
/*
* bdi_min_ratio keeps the sum of the minimum dirty shares of all
* registered backing devices, which, for obvious reasons, can not
* exceed 100%.
*/
static unsigned int bdi_min_ratio;
int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
{
int ret = 0;
spin_lock_bh(&bdi_lock);
if (min_ratio > bdi->max_ratio) {
ret = -EINVAL;
} else {
min_ratio -= bdi->min_ratio;
if (bdi_min_ratio + min_ratio < 100) {
bdi_min_ratio += min_ratio;
bdi->min_ratio += min_ratio;
} else {
ret = -EINVAL;
}
}
spin_unlock_bh(&bdi_lock);
return ret;
}
int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
{
int ret = 0;
if (max_ratio > 100)
return -EINVAL;
spin_lock_bh(&bdi_lock);
if (bdi->min_ratio > max_ratio) {
ret = -EINVAL;
} else {
bdi->max_ratio = max_ratio;
bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 100;
}
spin_unlock_bh(&bdi_lock);
return ret;
}
EXPORT_SYMBOL(bdi_set_max_ratio);
static unsigned long <API key>(unsigned long thresh,
unsigned long bg_thresh)
{
return (thresh + bg_thresh) / 2;
}
static unsigned long hard_dirty_limit(unsigned long thresh)
{
return max(thresh, global_dirty_limit);
}
/**
* bdi_dirty_limit - @bdi's share of dirty throttling threshold
* @bdi: the backing_dev_info to query
* @dirty: global dirty limit in pages
*
* Returns @bdi's dirty limit in pages. The term "dirty" in the context of
* dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
*
* Note that balance_dirty_pages() will only seriously take it as a hard limit
* when sleeping max_pause per page is not enough to keep the dirty pages under
* control. For example, when the device is completely stalled due to some error
* conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
* In the other normal situations, it acts more gently by throttling the tasks
* more (rather than completely block them) when the bdi dirty pages go high.
*
* It allocates high/low dirty limits to fast/slow devices, in order to prevent
* - starving fast devices
* - piling up dirty pages (that will take long time to sync) on slow devices
*
* The bdi's share of dirty limit will be adapting to its throughput and
* bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
*/
unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
{
u64 bdi_dirty;
long numerator, denominator;
/*
* Calculate this BDI's share of the dirty ratio.
*/
<API key>(bdi, &numerator, &denominator);
bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
bdi_dirty *= numerator;
do_div(bdi_dirty, denominator);
bdi_dirty += (dirty * bdi->min_ratio) / 100;
if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
bdi_dirty = dirty * bdi->max_ratio / 100;
return bdi_dirty;
}
static unsigned long bdi_position_ratio(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty)
{
unsigned long write_bw = bdi->avg_write_bandwidth;
unsigned long freerun = <API key>(thresh, bg_thresh);
unsigned long limit = hard_dirty_limit(thresh);
unsigned long x_intercept;
unsigned long setpoint; /* dirty pages' target balance point */
unsigned long bdi_setpoint;
unsigned long span;
long long pos_ratio; /* for scaling up/down the rate limit */
long x;
if (unlikely(dirty >= limit))
return 0;
setpoint = (freerun + limit) / 2;
x = div_s64(((s64)setpoint - (s64)dirty) << <API key>,
limit - setpoint + 1);
pos_ratio = x;
pos_ratio = pos_ratio * x >> <API key>;
pos_ratio = pos_ratio * x >> <API key>;
pos_ratio += 1 << <API key>;
/*
* We have computed basic pos_ratio above based on global situation. If
* the bdi is over/under its share of dirty pages, we want to scale
* pos_ratio further down/up. That is done by the following mechanism.
*/
if (unlikely(bdi_thresh > thresh))
bdi_thresh = thresh;
/*
* It's very possible that bdi_thresh is close to 0 not because the
* device is slow, but that it has remained inactive for long time.
* Honour such devices a reasonable good (hopefully IO efficient)
* threshold, so that the occasional writes won't be blocked and active
* writes can rampup the threshold quickly.
*/
bdi_thresh = max(bdi_thresh, (limit - dirty) / 8);
/*
* scale global setpoint to bdi's:
* bdi_setpoint = setpoint * bdi_thresh / thresh
*/
x = div_u64((u64)bdi_thresh << 16, thresh + 1);
bdi_setpoint = setpoint * (u64)x >> 16;
span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16;
x_intercept = bdi_setpoint + span;
if (bdi_dirty < x_intercept - span / 4) {
pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty),
x_intercept - bdi_setpoint + 1);
} else
pos_ratio /= 4;
/*
* bdi reserve area, safeguard against dirty pool underrun and disk idle
* It may push the desired control point of global dirty pages higher
* than setpoint.
*/
x_intercept = bdi_thresh / 2;
if (bdi_dirty < x_intercept) {
if (bdi_dirty > x_intercept / 8)
pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty);
else
pos_ratio *= 8;
}
return pos_ratio;
}
static void <API key>(struct backing_dev_info *bdi,
unsigned long elapsed,
unsigned long written)
{
const unsigned long period = roundup_pow_of_two(3 * HZ);
unsigned long avg = bdi->avg_write_bandwidth;
unsigned long old = bdi->write_bandwidth;
u64 bw;
bw = written - min(written, bdi->written_stamp);
bw *= HZ;
if (unlikely(elapsed > period)) {
do_div(bw, elapsed);
avg = bw;
goto out;
}
bw += (u64)bdi->write_bandwidth * (period - elapsed);
bw >>= ilog2(period);
/*
* one more level of smoothing, for filtering out sudden spikes
*/
if (avg > old && old >= (unsigned long)bw)
avg -= (avg - old) >> 3;
if (avg < old && old <= (unsigned long)bw)
avg += (old - avg) >> 3;
out:
bdi->write_bandwidth = bw;
bdi->avg_write_bandwidth = avg;
}
/*
* The global dirtyable memory and dirty threshold could be suddenly knocked
* down by a large amount (eg. on the startup of KVM in a swapless system).
* This may throw the system into deep dirty exceeded state and throttle
* heavy/light dirtiers alike. To retain good responsiveness, maintain
* global_dirty_limit for tracking slowly down to the knocked down dirty
* threshold.
*/
static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
{
unsigned long limit = global_dirty_limit;
/*
* Follow up in one step.
*/
if (limit < thresh) {
limit = thresh;
goto update;
}
/*
* Follow down slowly. Use the higher one as the target, because thresh
* may drop below dirty. This is exactly the reason to introduce
* global_dirty_limit which is guaranteed to lie above the dirty pages.
*/
thresh = max(thresh, dirty);
if (limit > thresh) {
limit -= (limit - thresh) >> 5;
goto update;
}
return;
update:
global_dirty_limit = limit;
}
static void <API key>(unsigned long thresh,
unsigned long dirty,
unsigned long now)
{
static DEFINE_SPINLOCK(dirty_lock);
static unsigned long update_time = INITIAL_JIFFIES;
/*
* check locklessly first to optimize away locking for the most time
*/
if (time_before(now, update_time + BANDWIDTH_INTERVAL))
return;
spin_lock(&dirty_lock);
if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
update_dirty_limit(thresh, dirty);
update_time = now;
}
spin_unlock(&dirty_lock);
}
/*
* Maintain bdi->dirty_ratelimit, the base dirty throttle rate.
*
* Normal bdi tasks will be curbed at or below it in long term.
* Obviously it should be around (write_bw / N) when there are N dd tasks.
*/
static void <API key>(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty,
unsigned long dirtied,
unsigned long elapsed)
{
unsigned long freerun = <API key>(thresh, bg_thresh);
unsigned long limit = hard_dirty_limit(thresh);
unsigned long setpoint = (freerun + limit) / 2;
unsigned long write_bw = bdi->avg_write_bandwidth;
unsigned long dirty_ratelimit = bdi->dirty_ratelimit;
unsigned long dirty_rate;
unsigned long task_ratelimit;
unsigned long <API key>;
unsigned long pos_ratio;
unsigned long step;
unsigned long x;
/*
* The dirty rate will match the writeout rate in long term, except
* when dirty pages are truncated by userspace or re-dirtied by FS.
*/
dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed;
pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty);
/*
* task_ratelimit reflects each dd's dirty rate for the past 200ms.
*/
task_ratelimit = (u64)dirty_ratelimit *
pos_ratio >> <API key>;
task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
/*
* A linear estimation of the "balanced" throttle rate. The theory is,
* if there are N dd tasks, each throttled at task_ratelimit, the bdi's
* dirty_rate will be measured to be (N * task_ratelimit). So the below
* formula will yield the balanced rate limit (write_bw / N).
*
* Note that the expanded form is not a pure rate feedback:
* rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
* but also takes pos_ratio into account:
* rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
*
* (1) is not realistic because pos_ratio also takes part in balancing
* the dirty rate. Consider the state
* pos_ratio = 0.5 (3)
* rate = 2 * (write_bw / N) (4)
* If (1) is used, it will stuck in that state! Because each dd will
* be throttled at
* task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
* yielding
* dirty_rate = N * task_ratelimit = write_bw (6)
* put (6) into (1) we get
* rate_(i+1) = rate_(i) (7)
*
* So we end up using (2) to always keep
* rate_(i+1) ~= (write_bw / N) (8)
* regardless of the value of pos_ratio. As long as (8) is satisfied,
* pos_ratio is able to drive itself to 1.0, which is not only where
* the dirty count meet the setpoint, but also where the slope of
* pos_ratio is most flat and hence task_ratelimit is least fluctuated.
*/
<API key> = div_u64((u64)task_ratelimit * write_bw,
dirty_rate | 1);
/*
* <API key> ~= (write_bw / N) <= write_bw
*/
if (unlikely(<API key> > write_bw))
<API key> = write_bw;
/*
* We could safely do this and return immediately:
*
* bdi->dirty_ratelimit = <API key>;
*
* However to get a more stable dirty_ratelimit, the below elaborated
* code makes use of task_ratelimit to filter out singular points and
* limit the step size.
*
* The below code essentially only uses the relative value of
*
* task_ratelimit - dirty_ratelimit
* = (pos_ratio - 1) * dirty_ratelimit
*
* which reflects the direction and size of dirty position error.
*/
/*
* dirty_ratelimit will follow <API key> iff
* task_ratelimit is on the same side of dirty_ratelimit, too.
* For example, when
* - dirty_ratelimit > <API key>
* - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
* lowering dirty_ratelimit will help meet both the position and rate
* control targets. Otherwise, don't update dirty_ratelimit if it will
* only help meet the rate target. After all, what the users ultimately
* feel and care are stable dirty rate and small position error.
*
* |task_ratelimit - dirty_ratelimit| is used to limit the step size
* and filter out the singular points of <API key>. Which
* keeps jumping around randomly and can even leap far away at times
* due to the small 200ms estimation period of dirty_rate (we want to
* keep that period small to reduce time lags).
*/
step = 0;
if (dirty < setpoint) {
x = min(bdi-><API key>,
min(<API key>, task_ratelimit));
if (dirty_ratelimit < x)
step = x - dirty_ratelimit;
} else {
x = max(bdi-><API key>,
max(<API key>, task_ratelimit));
if (dirty_ratelimit > x)
step = dirty_ratelimit - x;
}
/*
* Don't pursue 100% rate matching. It's impossible since the balanced
* rate itself is constantly fluctuating. So decrease the track speed
* when it gets close to the target. Helps eliminate pointless tremors.
*/
step >>= dirty_ratelimit / (2 * step + 1);
/*
* Limit the tracking speed to avoid overshooting.
*/
step = (step + 7) / 8;
if (dirty_ratelimit < <API key>)
dirty_ratelimit += step;
else
dirty_ratelimit -= step;
bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
bdi-><API key> = <API key>;
<API key>(bdi, dirty_rate, task_ratelimit);
}
void <API key>(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty,
unsigned long start_time)
{
unsigned long now = jiffies;
unsigned long elapsed = now - bdi->bw_time_stamp;
unsigned long dirtied;
unsigned long written;
/*
* rate-limit, only update once every 200ms.
*/
if (elapsed < BANDWIDTH_INTERVAL)
return;
dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]);
written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
/*
* Skip quiet periods when disk bandwidth is under-utilized.
* (at least 1s idle time between two flusher runs)
*/
if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
goto snapshot;
if (thresh) {
<API key>(thresh, dirty, now);
<API key>(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty,
dirtied, elapsed);
}
<API key>(bdi, elapsed, written);
snapshot:
bdi->dirtied_stamp = dirtied;
bdi->written_stamp = written;
bdi->bw_time_stamp = now;
}
static void <API key>(struct backing_dev_info *bdi,
unsigned long thresh,
unsigned long bg_thresh,
unsigned long dirty,
unsigned long bdi_thresh,
unsigned long bdi_dirty,
unsigned long start_time)
{
if (<API key>(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
return;
spin_lock(&bdi->wb.list_lock);
<API key>(bdi, thresh, bg_thresh, dirty,
bdi_thresh, bdi_dirty, start_time);
spin_unlock(&bdi->wb.list_lock);
}
/*
* After a task dirtied this many pages, <API key>()
* will look to see if it needs to start dirty throttling.
*
* If dirty_poll_interval is too low, big NUMA machines will call the expensive
* global_page_state() too often. So scale it near-sqrt to the safety margin
* (the number of pages we may dirty without exceeding the dirty limits).
*/
static unsigned long dirty_poll_interval(unsigned long dirty,
unsigned long thresh)
{
if (thresh > dirty)
return 1UL << (ilog2(thresh - dirty) >> 1);
return 1;
}
static unsigned long bdi_max_pause(struct backing_dev_info *bdi,
unsigned long bdi_dirty)
{
unsigned long bw = bdi->avg_write_bandwidth;
unsigned long t;
/*
* Limit pause time for small memory systems. If sleeping for too long
* time, a small pool of dirty/writeback pages may go empty and disk go
* idle.
*
* 8 serves as the safety ratio.
*/
t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
t++;
return min_t(unsigned long, t, MAX_PAUSE);
}
static long bdi_min_pause(struct backing_dev_info *bdi,
long max_pause,
unsigned long task_ratelimit,
unsigned long dirty_ratelimit,
int *nr_dirtied_pause)
{
long hi = ilog2(bdi->avg_write_bandwidth);
long lo = ilog2(bdi->dirty_ratelimit);
long t; /* target pause */
long pause; /* estimated next pause */
int pages; /* target nr_dirtied_pause */
/* target for 10ms pause on 1-dd case */
t = max(1, HZ / 100);
/*
* Scale up pause time for concurrent dirtiers in order to reduce CPU
* overheads.
*
* (N * 10ms) on 2^N concurrent tasks.
*/
if (hi > lo)
t += (hi - lo) * (10 * HZ) / 1024;
/*
* This is a bit convoluted. We try to base the next nr_dirtied_pause
* on the much more stable dirty_ratelimit. However the next pause time
* will be computed based on task_ratelimit and the two rate limits may
* depart considerably at some time. Especially if task_ratelimit goes
* below dirty_ratelimit/2 and the target pause is max_pause, the next
* pause time will be max_pause*2 _trimmed down_ to max_pause. As a
* result task_ratelimit won't be executed faithfully, which could
* eventually bring down dirty_ratelimit.
*
* We apply two rules to fix it up:
* 1) try to estimate the next pause time and if necessary, use a lower
* nr_dirtied_pause so as not to exceed max_pause. When this happens,
* nr_dirtied_pause will be "dancing" with task_ratelimit.
* 2) limit the target pause time to max_pause/2, so that the normal
* small fluctuations of task_ratelimit won't trigger rule (1) and
* nr_dirtied_pause will remain as stable as dirty_ratelimit.
*/
t = min(t, 1 + max_pause / 2);
pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
/*
* Tiny nr_dirtied_pause is found to hurt I/O performance in the test
* case <API key>, which does 16*{sync read, async write}.
* When the 16 consecutive reads are often interrupted by some dirty
* throttling pause during the async writes, cfq will go into idles
* (deadline is fine). So push nr_dirtied_pause as high as possible
* until reaches DIRTY_POLL_THRESH=32 pages.
*/
if (pages < DIRTY_POLL_THRESH) {
t = max_pause;
pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
if (pages > DIRTY_POLL_THRESH) {
pages = DIRTY_POLL_THRESH;
t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
}
}
pause = HZ * pages / (task_ratelimit + 1);
if (pause > max_pause) {
t = max_pause;
pages = task_ratelimit * t / roundup_pow_of_two(HZ);
}
*nr_dirtied_pause = pages;
/*
* The minimal pause time will normally be half the target pause time.
*/
return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
}
/*
* balance_dirty_pages() must be called by processes which are generating dirty
* data. It looks at the number of dirty pages in the machine and will force
* the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
* If we're over `background_thresh' then the writeback threads are woken to
* perform some writeout.
*/
static void balance_dirty_pages(struct address_space *mapping,
unsigned long pages_dirtied)
{
unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
unsigned long bdi_reclaimable;
unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
unsigned long bdi_dirty;
unsigned long freerun;
unsigned long background_thresh;
unsigned long dirty_thresh;
unsigned long bdi_thresh;
long period;
long pause;
long max_pause;
long min_pause;
int nr_dirtied_pause;
bool dirty_exceeded = false;
unsigned long task_ratelimit;
unsigned long dirty_ratelimit;
unsigned long pos_ratio;
struct backing_dev_info *bdi = mapping->backing_dev_info;
unsigned long start_time = jiffies;
for (;;) {
unsigned long now = jiffies;
/*
* Unstable writes are a feature of certain networked
* filesystems (i.e. NFS) in which data may have been
* written to the server's write cache, but has not yet
* been flushed to permanent storage.
*/
nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS);
nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
global_dirty_limits(&background_thresh, &dirty_thresh);
/*
* Throttle it only when the background writeback cannot
* catch-up. This avoids (excessively) small writeouts
* when the bdi limits are ramping up.
*/
freerun = <API key>(dirty_thresh,
background_thresh);
if (nr_dirty <= freerun) {
current->dirty_paused_when = now;
current->nr_dirtied = 0;
current->nr_dirtied_pause =
dirty_poll_interval(nr_dirty, dirty_thresh);
break;
}
if (unlikely(!<API key>(bdi)))
<API key>(bdi);
/*
* bdi_thresh is not treated as some limiting factor as
* dirty_thresh, due to reasons
* - in JBOD setup, bdi_thresh can fluctuate a lot
* - in a system with HDD and USB key, the USB key may somehow
* go into state (bdi_dirty >> bdi_thresh) either because
* bdi_dirty starts high, or because bdi_thresh drops low.
* In this case we don't want to hard throttle the USB key
* dirtiers for 100 seconds until bdi_dirty drops under
* bdi_thresh. Instead the auxiliary bdi control line in
* bdi_position_ratio() will let the dirtier task progress
* at some rate <= (write_bw / 2) for bringing down bdi_dirty.
*/
bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
/*
* In order to avoid the stacked BDI deadlock we need
* to ensure we accurately count the 'dirty' pages when
* the threshold is low.
*
* Otherwise it would be possible to get thresh+n pages
* reported dirty, even though there are thresh-m pages
* actually dirty; with m+n sitting in the percpu
* deltas.
*/
if (bdi_thresh < 2 * bdi_stat_error(bdi)) {
bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
bdi_dirty = bdi_reclaimable +
bdi_stat_sum(bdi, BDI_WRITEBACK);
} else {
bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
bdi_dirty = bdi_reclaimable +
bdi_stat(bdi, BDI_WRITEBACK);
}
dirty_exceeded = (bdi_dirty > bdi_thresh) &&
(nr_dirty > dirty_thresh);
if (dirty_exceeded && !bdi->dirty_exceeded)
bdi->dirty_exceeded = 1;
<API key>(bdi, dirty_thresh, background_thresh,
nr_dirty, bdi_thresh, bdi_dirty,
start_time);
dirty_ratelimit = bdi->dirty_ratelimit;
pos_ratio = bdi_position_ratio(bdi, dirty_thresh,
background_thresh, nr_dirty,
bdi_thresh, bdi_dirty);
task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >>
<API key>;
max_pause = bdi_max_pause(bdi, bdi_dirty);
min_pause = bdi_min_pause(bdi, max_pause,
task_ratelimit, dirty_ratelimit,
&nr_dirtied_pause);
if (unlikely(task_ratelimit == 0)) {
period = max_pause;
pause = max_pause;
goto pause;
}
period = HZ * pages_dirtied / task_ratelimit;
pause = period;
if (current->dirty_paused_when)
pause -= now - current->dirty_paused_when;
/*
* For less than 1s think time (ext3/4 may block the dirtier
* for up to 800ms from time to time on 1-HDD; so does xfs,
* however at much less frequency), try to compensate it in
* future periods by updating the virtual time; otherwise just
* do a reset, as it may be a light dirtier.
*/
if (pause < min_pause) {
<API key>(bdi,
dirty_thresh,
background_thresh,
nr_dirty,
bdi_thresh,
bdi_dirty,
dirty_ratelimit,
task_ratelimit,
pages_dirtied,
period,
min(pause, 0L),
start_time);
if (pause < -HZ) {
current->dirty_paused_when = now;
current->nr_dirtied = 0;
} else if (period) {
current->dirty_paused_when += period;
current->nr_dirtied = 0;
} else if (current->nr_dirtied_pause <= pages_dirtied)
current->nr_dirtied_pause += pages_dirtied;
break;
}
if (unlikely(pause > max_pause)) {
/* for occasional dropped task_ratelimit */
now += min(pause - max_pause, max_pause);
pause = max_pause;
}
pause:
<API key>(bdi,
dirty_thresh,
background_thresh,
nr_dirty,
bdi_thresh,
bdi_dirty,
dirty_ratelimit,
task_ratelimit,
pages_dirtied,
period,
pause,
start_time);
__set_current_state(TASK_KILLABLE);
io_schedule_timeout(pause);
current->dirty_paused_when = now + pause;
current->nr_dirtied = 0;
current->nr_dirtied_pause = nr_dirtied_pause;
/*
* This is typically equal to (nr_dirty < dirty_thresh) and can
* also keep "1000+ dd on a slow USB stick" under control.
*/
if (task_ratelimit)
break;
/*
* In the case of an unresponding NFS server and the NFS dirty
* pages exceeds dirty_thresh, give the other good bdi's a pipe
* to go through, so that tasks on them still remain responsive.
*
* In theory 1 page is enough to keep the comsumer-producer
* pipe going: the flusher cleans 1 page => the task dirties 1
* more page. However bdi_dirty has accounting errors. So use
* the larger and more IO friendly bdi_stat_error.
*/
if (bdi_dirty <= bdi_stat_error(bdi))
break;
if (<API key>(current))
break;
}
if (!dirty_exceeded && bdi->dirty_exceeded)
bdi->dirty_exceeded = 0;
if (<API key>(bdi))
return;
/*
* In laptop mode, we wait until hitting the higher threshold before
* starting background writeout, and then write out all the way down
* to the lower threshold. So slow writers cause minimal disk activity.
*
* In normal mode, we start background writeout at the lower
* background_thresh, to keep the amount of dirty memory low.
*/
if (laptop_mode)
return;
if (nr_reclaimable > background_thresh)
<API key>(bdi);
}
void <API key>(struct page *page, int page_mkwrite)
{
if (set_page_dirty(page) || page_mkwrite) {
struct address_space *mapping = page_mapping(page);
if (mapping)
<API key>(mapping);
}
}
static DEFINE_PER_CPU(int, bdp_ratelimits);
/*
* Normal tasks are throttled by
* loop {
* dirty tsk->nr_dirtied_pause pages;
* take a snap in balance_dirty_pages();
* }
* However there is a worst case. If every task exit immediately when dirtied
* (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
* called to throttle the page dirties. The solution is to save the not yet
* throttled page dirties in <API key> on task exit and charge them
* randomly into the running tasks. This works well for the above worst case,
* as the new task will pick up and accumulate the old task's leaked dirty
* count and eventually get throttled.
*/
DEFINE_PER_CPU(int, <API key>) = 0;
/**
* <API key> - balance dirty memory state
* @mapping: address_space which was dirtied
*
* Processes which are dirtying memory should call in here once for each page
* which was newly dirtied. The function will periodically check the system's
* dirty state and will initiate writeback if needed.
*
* On really big machines, get_writeback_state is expensive, so try to avoid
* calling it too often (ratelimiting). But once we're over the dirty memory
* limit we decrease the ratelimiting by a lot, to prevent individual processes
* from overshooting the limit by (ratelimit_pages) each.
*/
void <API key>(struct address_space *mapping)
{
struct backing_dev_info *bdi = mapping->backing_dev_info;
int ratelimit;
int *p;
if (!<API key>(bdi))
return;
ratelimit = current->nr_dirtied_pause;
if (bdi->dirty_exceeded)
ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
preempt_disable();
/*
* This prevents one CPU to accumulate too many dirtied pages without
* calling into balance_dirty_pages(), which can happen when there are
* 1000+ tasks, all of them start dirtying pages at exactly the same
* time, hence all honoured too large initial task->nr_dirtied_pause.
*/
p = &__get_cpu_var(bdp_ratelimits);
if (unlikely(current->nr_dirtied >= ratelimit))
*p = 0;
else if (unlikely(*p >= ratelimit_pages)) {
*p = 0;
ratelimit = 0;
}
/*
* Pick up the dirtied pages by the exited tasks. This avoids lots of
* short-lived tasks (eg. gcc invocations in a kernel build) escaping
* the dirty throttling and livelock other long-run dirtiers.
*/
p = &__get_cpu_var(<API key>);
if (*p > 0 && current->nr_dirtied < ratelimit) {
unsigned long nr_pages_dirtied;
nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
*p -= nr_pages_dirtied;
current->nr_dirtied += nr_pages_dirtied;
}
preempt_enable();
if (unlikely(current->nr_dirtied >= ratelimit))
balance_dirty_pages(mapping, current->nr_dirtied);
}
EXPORT_SYMBOL(<API key>);
void <API key>(gfp_t gfp_mask)
{
unsigned long background_thresh;
unsigned long dirty_thresh;
for ( ; ; ) {
global_dirty_limits(&background_thresh, &dirty_thresh);
dirty_thresh = hard_dirty_limit(dirty_thresh);
/*
* Boost the allowable dirty threshold a bit for page
* allocators so they don't get DoS'ed by heavy writers
*/
dirty_thresh += dirty_thresh / 10; /* wheeee... */
if (global_page_state(NR_UNSTABLE_NFS) +
global_page_state(NR_WRITEBACK) <= dirty_thresh)
break;
congestion_wait(BLK_RW_ASYNC, HZ/10);
/*
* The caller might hold locks which can prevent IO completion
* or progress in the filesystem. So we cannot just sit here
* waiting for IO to complete.
*/
if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
break;
}
}
/*
* sysctl handler for /proc/sys/vm/<API key>
*/
int <API key>(ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
proc_dointvec(table, write, buffer, length, ppos);
return 0;
}
#ifdef <API key>
/*
* Manages the dirty page writebacks activation status
*/
static void <API key>(bool active) {
/* Change the current dirty writeback interval according to the
* status provided */
<API key> = (active) ?
<API key> :
<API key>;
/* Print debug info */
pr_debug("%s: Set <API key> = %d centisecs\n",
__func__, <API key>);
}
/*
* sysctl handler for /proc/sys/vm/<API key>
*/
int <API key>(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
int ret;
int old_status = <API key>;
/* Get and store the new status */
ret = <API key>(table, write, buffer, lenp, ppos);
/* If the dynamic writeback has been enabled then set the active
* dirty writebacks interval, otherwise if the feature has been
* disabled, set the suspend interval (the default interval)
* to restore the standard functionality */
if (ret == 0 && write && <API key> != old_status)
<API key>(!!<API key>);
return ret;
}
/*
* sysctl handler for /proc/sys/vm/<API key>
*/
int <API key>(ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
<API key>(table, write, buffer, length, ppos);
return 0;
}
/*
* sysctl handler for /proc/sys/vm/<API key>
*/
int <API key>(ctl_table *table, int write,
void __user *buffer, size_t *length, loff_t *ppos)
{
<API key>(table, write, buffer, length, ppos);
return 0;
}
#endif
#ifdef CONFIG_BLOCK
void <API key>(unsigned long data)
{
struct request_queue *q = (struct request_queue *)data;
int nr_pages = global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS);
/*
* We want to write everything out, not just down to the dirty
* threshold
*/
if (bdi_has_dirty_io(&q->backing_dev_info))
bdi_start_writeback(&q->backing_dev_info, nr_pages,
<API key>);
}
/*
* We've spun up the disk and we're in laptop mode: schedule writeback
* of all dirty data a few seconds from now. If the flush is already scheduled
* then push it back - the user is still using the disk.
*/
void <API key>(struct backing_dev_info *info)
{
mod_timer(&info-><API key>, jiffies + laptop_mode);
}
/*
* We're in laptop mode and we've just synced. The sync's writes will have
* caused another writeback to be scheduled by <API key>.
* Nothing needs to be written back anymore, so we unschedule the writeback.
*/
void <API key>(void)
{
struct backing_dev_info *bdi;
rcu_read_lock();
<API key>(bdi, &bdi_list, bdi_list)
del_timer(&bdi-><API key>);
rcu_read_unlock();
}
#endif
/*
* If ratelimit_pages is too high then we can get into dirty-data overload
* if a large number of processes all perform writes at the same time.
* If it is too low then SMP machines will call the (expensive)
* get_writeback_state too often.
*
* Here we set ratelimit_pages to a level which ensures that when all CPUs are
* dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
* thresholds.
*/
void <API key>(void)
{
unsigned long background_thresh;
unsigned long dirty_thresh;
global_dirty_limits(&background_thresh, &dirty_thresh);
global_dirty_limit = dirty_thresh;
ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
if (ratelimit_pages < 16)
ratelimit_pages = 16;
}
static int __cpuinit
ratelimit_handler(struct notifier_block *self, unsigned long action,
void *hcpu)
{
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_ONLINE:
case CPU_DEAD:
<API key>();
return NOTIFY_OK;
default:
return NOTIFY_DONE;
}
}
static struct notifier_block __cpuinitdata ratelimit_nb = {
.notifier_call = ratelimit_handler,
.next = NULL,
};
#ifdef <API key>
/*
* Sets the dirty page writebacks interval for suspended system
*/
static void <API key>(struct power_suspend *handler)
{
if (<API key>)
<API key>(false);
}
/*
* Sets the dirty page writebacks interval for active system
*/
static void <API key>(struct power_suspend *handler)
{
if (<API key>)
<API key>(true);
}
/*
* Struct for the dirty page writeback management during suspend/resume
*/
static struct power_suspend <API key> = {
.suspend = <API key>,
.resume = <API key>,
};
#endif
static void dirty_power_suspend(struct power_suspend *handler)
{
if (<API key> != <API key>)
<API key> = <API key>;
<API key> = <API key>;
}
static void dirty_power_resume(struct power_suspend *handler)
{
if (<API key> != <API key>)
<API key> = <API key>;
<API key> = <API key>;
}
static struct power_suspend dirty_suspend = {
.suspend = dirty_power_suspend,
.resume = dirty_power_resume,
};
/*
* Called early on to tune the page writeback dirty limits.
*
* We used to scale dirty pages according to how total memory
* related to pages that could be allocated for buffers (by
* comparing <API key>() to vm_total_pages.
*
* However, that was when we used "dirty_ratio" to scale with
* all memory, and we don't do that any more. "dirty_ratio"
* is now applied to total non-HIGHPAGE memory (by subtracting
* totalhigh_pages from vm_total_pages), and as such we can't
* get into the old insane situation any more where we had
* large amounts of dirty pages compared to a small amount of
* non-HIGHMEM memory.
*
* But we might still want to scale the dirty_ratio by how
* much memory the box has..
*/
void __init page_writeback_init(void)
{
<API key> = <API key> =
<API key>;
<API key> = <API key> =
<API key>;
<API key>(&dirty_suspend);
#ifdef <API key>
/* Register the dirty page writeback management during suspend/resume */
<API key>(&<API key>);
#endif
<API key>();
<API key>(&ratelimit_nb);
fprop_global_init(&<API key>);
}
/**
* <API key> - tag pages to be written by write_cache_pages
* @mapping: address space structure to write
* @start: starting page index
* @end: ending page index (inclusive)
*
* This function scans the page range from @start to @end (inclusive) and tags
* all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
* that write_cache_pages (or whoever calls this function) will then use
* TOWRITE tag to identify pages eligible for writeback. This mechanism is
* used to avoid livelocking of writeback by a process steadily creating new
* dirty pages in the file (thus it is important for this function to be quick
* so that it can tag pages faster than a dirtying process can create them).
*/
/*
* We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
*/
void <API key>(struct address_space *mapping,
pgoff_t start, pgoff_t end)
{
#define WRITEBACK_TAG_BATCH 4096
unsigned long tagged;
do {
spin_lock_irq(&mapping->tree_lock);
tagged = <API key>(&mapping->page_tree,
&start, end, WRITEBACK_TAG_BATCH,
PAGECACHE_TAG_DIRTY, <API key>);
spin_unlock_irq(&mapping->tree_lock);
WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
cond_resched();
/* We check 'start' to handle wrapping when end == ~0UL */
} while (tagged >= WRITEBACK_TAG_BATCH && start);
}
EXPORT_SYMBOL(<API key>);
/**
* write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
* @mapping: address space structure to write
* @wbc: subtract the number of written pages from *@wbc->nr_to_write
* @writepage: function called for each page
* @data: data passed to writepage function
*
* If a page is already under I/O, write_cache_pages() skips it, even
* if it's dirty. This is desirable behaviour for memory-cleaning writeback,
* but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
* and msync() need to guarantee that all the data which was dirty at the time
* the call was made get new I/O started against them. If wbc->sync_mode is
* WB_SYNC_ALL then we were called for data integrity and we must wait for
* existing IO to complete.
*
* To avoid livelocks (when other process dirties new pages), we first tag
* pages which should be written back with TOWRITE tag and only then start
* writing them. For data-integrity sync we have to be careful so that we do
* not miss some pages (e.g., because some other process has cleared TOWRITE
* tag we set). The rule we follow is that TOWRITE tag can be cleared only
* by the process clearing the DIRTY tag (and submitting the page for IO).
*/
int write_cache_pages(struct address_space *mapping,
struct writeback_control *wbc, writepage_t writepage,
void *data)
{
int ret = 0;
int done = 0;
struct pagevec pvec;
int nr_pages;
pgoff_t uninitialized_var(writeback_index);
pgoff_t index;
pgoff_t end; /* Inclusive */
pgoff_t done_index;
int cycled;
int range_whole = 0;
int tag;
pagevec_init(&pvec, 0);
if (wbc->range_cyclic) {
writeback_index = mapping->writeback_index; /* prev offset */
index = writeback_index;
if (index == 0)
cycled = 1;
else
cycled = 0;
end = -1;
} else {
index = wbc->range_start >> PAGE_CACHE_SHIFT;
end = wbc->range_end >> PAGE_CACHE_SHIFT;
if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
range_whole = 1;
cycled = 1; /* ignore range_cyclic tests */
}
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
tag = <API key>;
else
tag = PAGECACHE_TAG_DIRTY;
retry:
if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
<API key>(mapping, index, end);
done_index = index;
while (!done && (index <= end)) {
int i;
nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
/*
* At this point, the page may be truncated or
* invalidated (changing page->mapping to NULL), or
* even swizzled back from swapper_space to tmpfs file
* mapping. However, page->index will not change
* because we have a reference on the page.
*/
if (page->index > end) {
/*
* can't be range_cyclic (1st pass) because
* end == -1 in that case.
*/
done = 1;
break;
}
done_index = page->index;
lock_page(page);
/*
* Page truncated or invalidated. We can freely skip it
* then, even for data integrity operations: the page
* has disappeared concurrently, so there could be no
* real expectation of this data interity operation
* even if there is now a new, dirty page at the same
* pagecache address.
*/
if (unlikely(page->mapping != mapping)) {
continue_unlock:
unlock_page(page);
continue;
}
if (!PageDirty(page)) {
/* someone wrote it for us */
goto continue_unlock;
}
if (PageWriteback(page)) {
if (wbc->sync_mode != WB_SYNC_NONE)
<API key>(page);
else
goto continue_unlock;
}
BUG_ON(PageWriteback(page));
if (!<API key>(page))
goto continue_unlock;
trace_wbc_writepage(wbc, mapping->backing_dev_info);
ret = (*writepage)(page, wbc, data);
if (unlikely(ret)) {
if (ret == <API key>) {
unlock_page(page);
ret = 0;
} else {
/*
* done_index is set past this page,
* so media errors will not choke
* background writeout for the entire
* file. This has consequences for
* range_cyclic semantics (ie. it may
* not be suitable for data integrity
* writeout).
*/
done_index = page->index + 1;
done = 1;
break;
}
}
/*
* We stop writing back only if we are not doing
* integrity sync. In case of integrity sync we have to
* keep going until we have written all the pages
* we tagged for writeback prior to entering this loop.
*/
if (--wbc->nr_to_write <= 0 &&
wbc->sync_mode == WB_SYNC_NONE) {
done = 1;
break;
}
}
pagevec_release(&pvec);
cond_resched();
}
if (!cycled && !done) {
/*
* range_cyclic:
* We hit the last page and there is more work to be done: wrap
* back to the start of the file
*/
cycled = 1;
index = 0;
end = writeback_index - 1;
goto retry;
}
if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
mapping->writeback_index = done_index;
return ret;
}
EXPORT_SYMBOL(write_cache_pages);
/*
* Function used by generic_writepages to call the real writepage
* function and set the mapping flags on error
*/
static int __writepage(struct page *page, struct writeback_control *wbc,
void *data)
{
struct address_space *mapping = data;
int ret = mapping->a_ops->writepage(page, wbc);
mapping_set_error(mapping, ret);
return ret;
}
/**
* generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
* @mapping: address space structure to write
* @wbc: subtract the number of written pages from *@wbc->nr_to_write
*
* This is a library function, which implements the writepages()
* <API key>.
*/
int generic_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct blk_plug plug;
int ret;
/* deal with chardevs and other special file */
if (!mapping->a_ops->writepage)
return 0;
blk_start_plug(&plug);
ret = write_cache_pages(mapping, wbc, __writepage, mapping);
blk_finish_plug(&plug);
return ret;
}
EXPORT_SYMBOL(generic_writepages);
int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
int ret;
if (wbc->nr_to_write <= 0)
return 0;
if (mapping->a_ops->writepages)
ret = mapping->a_ops->writepages(mapping, wbc);
else
ret = generic_writepages(mapping, wbc);
return ret;
}
/**
* write_one_page - write out a single page and optionally wait on I/O
* @page: the page to write
* @wait: if true, wait on writeout
*
* The page must be locked by the caller and will be unlocked upon return.
*
* write_one_page() returns a negative error code if I/O failed.
*/
int write_one_page(struct page *page, int wait)
{
struct address_space *mapping = page->mapping;
int ret = 0;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_ALL,
.nr_to_write = 1,
};
BUG_ON(!PageLocked(page));
if (wait)
<API key>(page);
if (<API key>(page)) {
page_cache_get(page);
ret = mapping->a_ops->writepage(page, &wbc);
if (ret == 0 && wait) {
<API key>(page);
if (PageError(page))
ret = -EIO;
}
page_cache_release(page);
} else {
unlock_page(page);
}
return ret;
}
EXPORT_SYMBOL(write_one_page);
/*
* For address_spaces which do not use buffers nor write back.
*/
int <API key>(struct page *page)
{
if (!PageDirty(page))
return !TestSetPageDirty(page);
return 0;
}
/*
* Helper function for set_page_dirty family.
* NOTE: This relies on being atomic wrt interrupts.
*/
void <API key>(struct page *page, struct address_space *mapping)
{
<API key>(page, mapping);
if (<API key>(mapping)) {
<API key>(page, NR_FILE_DIRTY);
<API key>(page, NR_DIRTIED);
__inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
__inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
<API key>(PAGE_CACHE_SIZE);
current->nr_dirtied++;
this_cpu_inc(bdp_ratelimits);
}
}
EXPORT_SYMBOL(<API key>);
/*
* Helper function for set_page_writeback family.
* NOTE: Unlike <API key> this does not rely on being atomic
* wrt interrupts.
*/
void <API key>(struct page *page)
{
inc_zone_page_state(page, NR_WRITEBACK);
}
EXPORT_SYMBOL(<API key>);
/*
* For address_spaces which do not use buffers. Just tag the page as dirty in
* its radix tree.
*
* This is also used when a single buffer is being dirtied: we want to set the
* page dirty in that case, but not all the buffers. This is a "bottom-up"
* dirtying, whereas <API key>() is a "top-down" dirtying.
*
* Most callers have locked the page, which pins the address_space in memory.
* But zap_pte_range() does not lock the page, however in that case the
* mapping is pinned by the vma's ->vm_file reference.
*
* We take care to handle the case where the page was truncated from the
* mapping by re-checking page_mapping() inside tree_lock.
*/
int <API key>(struct page *page)
{
if (!TestSetPageDirty(page)) {
struct address_space *mapping = page_mapping(page);
struct address_space *mapping2;
unsigned long flags;
if (!mapping)
return 1;
spin_lock_irqsave(&mapping->tree_lock, flags);
mapping2 = page_mapping(page);
if (mapping2) { /* Race with truncate? */
BUG_ON(mapping2 != mapping);
WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
<API key>(page, mapping);
radix_tree_tag_set(&mapping->page_tree,
page_index(page), PAGECACHE_TAG_DIRTY);
}
<API key>(&mapping->tree_lock, flags);
if (mapping->host) {
/* !PageAnon && !swapper_space */
__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
}
return 1;
}
return 0;
}
EXPORT_SYMBOL(<API key>);
/*
* Call this whenever redirtying a page, to de-account the dirty counters
* (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written
* counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to
* systematic errors in <API key> and the dirty pages position
* control.
*/
void <API key>(struct page *page)
{
struct address_space *mapping = page->mapping;
if (mapping && <API key>(mapping)) {
current->nr_dirtied
dec_zone_page_state(page, NR_DIRTIED);
dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
}
}
EXPORT_SYMBOL(<API key>);
/*
* When a writepage implementation decides that it doesn't want to write this
* page for some reason, it should redirty the locked page via
* <API key>() and it should then unlock the page and return 0
*/
int <API key>(struct writeback_control *wbc, struct page *page)
{
wbc->pages_skipped++;
<API key>(page);
return <API key>(page);
}
EXPORT_SYMBOL(<API key>);
/*
* Dirty a page.
*
* For pages with a mapping this should be done under the page lock
* for the benefit of asynchronous memory errors who prefer a consistent
* dirty state. This rule can be broken in some special cases,
* but should be better not to.
*
* If the mapping doesn't provide a set_page_dirty a_op, then
* just fall through and assume that it wants buffer_heads.
*/
int set_page_dirty(struct page *page)
{
struct address_space *mapping = page_mapping(page);
if (likely(mapping)) {
int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
/*
* readahead/lru_deactivate_page could remain
* PG_readahead/PG_reclaim due to race with end_page_writeback
* About readahead, if the page is written, the flags would be
* reset. So no problem.
* About lru_deactivate_page, if the page is redirty, the flag
* will be reset. So no problem. but if the page is used by readahead
* it will confuse readahead and make it restart the size rampup
* process. But it's a trivial problem.
*/
ClearPageReclaim(page);
#ifdef CONFIG_BLOCK
if (!spd)
spd = <API key>;
#endif
return (*spd)(page);
}
if (!PageDirty(page)) {
if (!TestSetPageDirty(page))
return 1;
}
return 0;
}
EXPORT_SYMBOL(set_page_dirty);
/*
* set_page_dirty() is racy if the caller has no reference against
* page->mapping->host, and if the page is unlocked. This is because another
* CPU could truncate the page off the mapping and then free the mapping.
*
* Usually, the page _is_ locked, or the caller is a user-space process which
* holds a reference on the inode by having an open file.
*
* In other cases, the page should be locked before running set_page_dirty().
*/
int set_page_dirty_lock(struct page *page)
{
int ret;
lock_page(page);
ret = set_page_dirty(page);
unlock_page(page);
return ret;
}
EXPORT_SYMBOL(set_page_dirty_lock);
/*
* Clear a page's dirty flag, while caring for dirty memory accounting.
* Returns true if the page was previously dirty.
*
* This is for preparing to put the page under writeout. We leave the page
* tagged as dirty in the radix tree so that a concurrent write-for-sync
* can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
* implementation will run either set_page_writeback() or set_page_dirty(),
* at which stage we bring the page's dirty flag and radix-tree dirty tag
* back into sync.
*
* This incoherency between the page's dirty flag and radix-tree tag is
* unfortunate, but it only exists while the page is locked.
*/
int <API key>(struct page *page)
{
struct address_space *mapping = page_mapping(page);
BUG_ON(!PageLocked(page));
if (mapping && <API key>(mapping)) {
if (page_mkclean(page))
set_page_dirty(page);
/*
* We carefully synchronise fault handlers against
* installing a dirty pte and marking the page dirty
* at this point. We do this by having them hold the
* page lock at some point after installing their
* pte, but before marking the page dirty.
* Pages are always locked coming in here, so we get
* the desired exclusion. See mm/memory.c:do_wp_page()
* for more comments.
*/
if (TestClearPageDirty(page)) {
dec_zone_page_state(page, NR_FILE_DIRTY);
dec_bdi_stat(mapping->backing_dev_info,
BDI_RECLAIMABLE);
return 1;
}
return 0;
}
return TestClearPageDirty(page);
}
EXPORT_SYMBOL(<API key>);
int <API key>(struct page *page)
{
struct address_space *mapping = page_mapping(page);
int ret;
if (mapping) {
struct backing_dev_info *bdi = mapping->backing_dev_info;
unsigned long flags;
spin_lock_irqsave(&mapping->tree_lock, flags);
ret = <API key>(page);
if (ret) {
<API key>(&mapping->page_tree,
page_index(page),
<API key>);
if (<API key>(bdi)) {
__dec_bdi_stat(bdi, BDI_WRITEBACK);
__bdi_writeout_inc(bdi);
}
}
<API key>(&mapping->tree_lock, flags);
} else {
ret = <API key>(page);
}
if (ret) {
dec_zone_page_state(page, NR_WRITEBACK);
inc_zone_page_state(page, NR_WRITTEN);
}
return ret;
}
int <API key>(struct page *page)
{
struct address_space *mapping = page_mapping(page);
int ret;
if (mapping) {
struct backing_dev_info *bdi = mapping->backing_dev_info;
unsigned long flags;
spin_lock_irqsave(&mapping->tree_lock, flags);
ret = <API key>(page);
if (!ret) {
radix_tree_tag_set(&mapping->page_tree,
page_index(page),
<API key>);
if (<API key>(bdi))
__inc_bdi_stat(bdi, BDI_WRITEBACK);
}
if (!PageDirty(page))
<API key>(&mapping->page_tree,
page_index(page),
PAGECACHE_TAG_DIRTY);
<API key>(&mapping->page_tree,
page_index(page),
<API key>);
<API key>(&mapping->tree_lock, flags);
} else {
ret = <API key>(page);
}
if (!ret)
<API key>(page);
return ret;
}
EXPORT_SYMBOL(<API key>);
/*
* Return true if any of the pages in the mapping are marked with the
* passed tag.
*/
int mapping_tagged(struct address_space *mapping, int tag)
{
return radix_tree_tagged(&mapping->page_tree, tag);
}
EXPORT_SYMBOL(mapping_tagged);
/**
* <API key>() - wait for writeback to finish, if necessary.
* @page: The page to wait on.
*
* This function determines if the given page is related to a backing device
* that requires page contents to be held stable during writeback. If so, then
* it will wait for any pending writeback to complete.
*/
void <API key>(struct page *page)
{
struct address_space *mapping = page_mapping(page);
struct backing_dev_info *bdi = mapping->backing_dev_info;
if (!<API key>(bdi))
return;
<API key>(page);
}
EXPORT_SYMBOL_GPL(<API key>);
|
/* Return error-text for system error messages and handler messages */
#define PERROR_VERSION "2.11"
#include <my_global.h>
#include <my_sys.h>
#include <m_string.h>
#include <errno.h>
#include <my_getopt.h>
#ifdef <API key>
#include "../storage/ndb/src/ndbapi/ndberror.c"
#include "../storage/ndb/src/kernel/error/ndbd_exit_codes.c"
#include "../storage/ndb/include/mgmapi/mgmapi_error.h"
#endif
#include <<API key>.h> /* <API key> */
static my_bool verbose;
#include "../include/my_base.h"
#include "../mysys/my_handler_errors.h"
#ifdef <API key>
static my_bool ndb_code;
static char ndb_string[1024];
int mgmapi_error_string(int err_no, char *str, int size)
{
int i;
for (i= 0; i < <API key>; i++)
{
if ((int)ndb_mgm_error_msgs[i].code == err_no)
{
my_snprintf(str, size-1, "%s", ndb_mgm_error_msgs[i].msg);
str[size-1]= '\0';
return 0;
}
}
return -1;
}
#endif
static struct my_option my_long_options[] =
{
{"help", '?', "Displays this help and exits.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"info", 'I', "Synonym for --help.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
#ifdef <API key>
{"ndb", 257, "Ndbcluster storage engine specific error codes.", &ndb_code,
&ndb_code, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"silent", 's', "Only print the error message.", 0, 0, 0, GET_NO_ARG, NO_ARG,
0, 0, 0, 0, 0, 0},
{"verbose", 'v', "Print error code and message (default).", &verbose,
&verbose, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
{"version", 'V', "Displays version information and exits.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
static void print_version(void)
{
printf("%s Ver %s, for %s (%s)\n",my_progname,PERROR_VERSION,
SYSTEM_TYPE,MACHINE_TYPE);
}
static void usage(void)
{
print_version();
puts(<API key>("2000"));
printf("Print a description for a system error code or a MySQL error code.\n");
printf("If you want to get the error for a negative error code, you should use\n-- before the first error code to tell perror that there was no more options.\n\n");
printf("Usage: %s [OPTIONS] [ERRORCODE [ERRORCODE...]]\n",my_progname);
my_print_help(my_long_options);
my_print_variables(my_long_options);
}
static my_bool
get_one_option(int optid, const struct my_option *opt MY_ATTRIBUTE((unused)),
char *argument MY_ATTRIBUTE((unused)))
{
switch (optid) {
case 's':
verbose=0;
break;
case 'V':
print_version();
exit(0);
break;
case 'I':
case '?':
usage();
exit(0);
break;
}
return 0;
}
static int get_options(int *argc,char ***argv)
{
int ho_error;
if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
if (!*argc)
{
usage();
return 1;
}
return 0;
} /* get_options */
static const char *get_ha_error_msg(int code)
{
/*
If you got compilation error here about compile_time_assert array, check
that every HA_ERR_xxx constant has a corresponding error message in
<API key>[] list (check mysys/my_handler_errors.h and
include/my_base.h).
*/
compile_time_assert(HA_ERR_FIRST + array_elements(<API key>) ==
HA_ERR_LAST + 1);
if (code >= HA_ERR_FIRST && code <= HA_ERR_LAST)
return <API key>[code - HA_ERR_FIRST];
return NullS;
}
typedef struct
{
const char *name;
uint code;
const char *text;
} st_error;
static st_error global_error_names[] =
{
#include <mysqld_ername.h>
{ 0, 0, 0 }
};
/**
Lookup an error by code in the global_error_names array.
@param code the code to lookup
@param [out] name_ptr the error name, when found
@param [out] msg_ptr the error text, when found
@return 1 when found, otherwise 0
*/
int get_ER_error_msg(uint code, const char **name_ptr, const char **msg_ptr)
{
st_error *tmp_error;
tmp_error= & global_error_names[0];
while (tmp_error->name != NULL)
{
if (tmp_error->code == code)
{
*name_ptr= tmp_error->name;
*msg_ptr= tmp_error->text;
return 1;
}
tmp_error++;
}
return 0;
}
#if defined(_WIN32)
static my_bool print_win_error_msg(DWORD error, my_bool verbose)
{
LPTSTR s;
if (FormatMessage(<API key> |
<API key>,
NULL, error, 0, (LPTSTR)&s, 0,
NULL))
{
if (verbose)
printf("Win32 error code %d: %s", error, s);
else
puts(s);
LocalFree(s);
return 0;
}
return 1;
}
#endif
static const char *<API key>(int nr)
{
return <API key>[nr - HA_ERR_FIRST];
}
/*
Register handler error messages for usage with my_error()
NOTES
This is safe to call multiple times as my_error_register()
will ignore calls to register already registered error numbers.
*/
void <API key>()
{
/*
If you got compilation error here about compile_time_assert array, check
that every HA_ERR_xxx constant has a corresponding error message in
<API key>[] list (check mysys/ma_handler_errors.h and
include/my_base.h).
*/
compile_time_assert(HA_ERR_FIRST + array_elements(<API key>) ==
HA_ERR_LAST + 1);
my_error_register(<API key>, HA_ERR_FIRST,
HA_ERR_FIRST+ array_elements(<API key>)-1);
}
void <API key>(void)
{
my_error_unregister(HA_ERR_FIRST,
HA_ERR_FIRST+ array_elements(<API key>)-1);
}
int main(int argc,char *argv[])
{
int error,code,found;
const char *msg;
const char *name;
char *unknown_error = 0;
#if defined(_WIN32)
my_bool skip_win_message= 0;
#endif
MY_INIT(argv[0]);
if (get_options(&argc,&argv))
exit(1);
<API key>();
error=0;
{
/*
On some system, like Linux, strerror(unknown_error) returns a
string 'Unknown Error'. To avoid printing it we try to find the
error string by asking for an impossible big error message.
On Solaris 2.8 it might return NULL
*/
if ((msg= strerror(10000)) == NULL)
msg= "Unknown Error";
/*
Allocate a buffer for unknown_error since strerror always returns
the same pointer on some platforms such as Windows
*/
unknown_error= malloc(strlen(msg)+1);
my_stpcpy(unknown_error, msg);
for ( ; argc-- > 0 ; argv++)
{
found=0;
code=atoi(*argv);
#ifdef <API key>
if (ndb_code)
{
if ((ndb_error_string(code, ndb_string, sizeof(ndb_string)) < 0) &&
(ndbd_exit_string(code, ndb_string, sizeof(ndb_string)) < 0) &&
(mgmapi_error_string(code, ndb_string, sizeof(ndb_string)) < 0))
{
msg= 0;
}
else
msg= ndb_string;
if (msg)
{
if (verbose)
printf("NDB error code %3d: %s\n",code,msg);
else
puts(msg);
}
else
{
fprintf(stderr,"Illegal ndb error code: %d\n",code);
error= 1;
}
found= 1;
msg= 0;
}
else
#endif
msg = strerror(code);
/*
We don't print the OS error message if it is the same as the
unknown_error message we retrieved above, or it starts with
'Unknown Error' (without regard to case).
*/
if (msg &&
my_strnncoll(&my_charset_latin1, (const uchar*) msg, 13,
(const uchar*) "Unknown Error", 13) &&
(!unknown_error || strcmp(msg, unknown_error)))
{
found= 1;
if (verbose)
printf("OS error code %3d: %s\n", code, msg);
else
puts(msg);
}
if ((msg= get_ha_error_msg(code)))
{
found= 1;
if (verbose)
printf("MySQL error code %3d: %s\n", code, msg);
else
puts(msg);
}
if (get_ER_error_msg(code, & name, & msg))
{
found= 1;
if (verbose)
printf("MySQL error code %3d (%s): %s\n", code, name, msg);
else
puts(msg);
}
if (!found)
{
#if defined(_WIN32)
if (!(skip_win_message= !print_win_error_msg((DWORD)code, verbose)))
{
#endif
fprintf(stderr,"Illegal error code: %d\n",code);
error=1;
#if defined(_WIN32)
}
#endif
}
#if defined(_WIN32)
if (!skip_win_message)
print_win_error_msg((DWORD)code, verbose);
#endif
}
}
/* if we allocated a buffer for unknown_error, free it now */
if (unknown_error)
free(unknown_error);
exit(error);
return error;
}
|
#include <linux/errno.h>
#include <linux/platform_device.h>
#include <linux/clkdev.h>
#include <linux/i2c.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/fimg2d.h>
#include <plat/jpeg.h>
#include <plat/tv-core.h>
#include <media/exynos_gscaler.h>
#include <mach/hs-iic.h>
#include <mach/exynos-mfc.h>
#include <mach/exynos-scaler.h>
#include <mach/exynos-tv.h>
#include "board-xyref5260.h"
#ifdef <API key>
static struct s5p_mfc_qos <API key>[] = {
[0] = {
.thrd_mb = 0,
.freq_mfc = 111000,
.freq_int = 111000,
.freq_mif = 200000,
#ifdef <API key>
.freq_cpu = 0,
#else
.freq_cpu = 0,
.freq_kfc = 0,
#endif
},
[1] = {
.thrd_mb = 163200,
.freq_mfc = 167000,
.freq_int = 222000,
.freq_mif = 266000,
#ifdef <API key>
.freq_cpu = 0,
#else
.freq_cpu = 0,
.freq_kfc = 0,
#endif
},
[2] = {
.thrd_mb = 244800,
.freq_mfc = 222000,
.freq_int = 333000,
.freq_mif = 266000,
#ifdef <API key>
.freq_cpu = 400000,
#else
.freq_cpu = 0,
.freq_kfc = 400000,
#endif
},
[3] = {
.thrd_mb = 326400,
.freq_mfc = 333000,
.freq_int = 400000,
.freq_mif = 400000,
#ifdef <API key>
.freq_cpu = 400000,
#else
.freq_cpu = 0,
.freq_kfc = 400000,
#endif
},
};
#endif
static struct s5p_mfc_platdata xyref5260_mfc_pd = {
.ip_ver = IP_VER_MFC_6R_0,
.clock_rate = 333 * MHZ,
.min_rate = 84000, /* in KHz */
#ifdef <API key>
.num_qos_steps = ARRAY_SIZE(<API key>),
.qos_table = <API key>,
#endif
};
static struct <API key> xyref5260_mscl_pd = {
.platid = SCID_RH,
.clk_rate = 400 * MHZ,
.gate_clk = "mscl",
.clk = { "aclk_m2m_400", },
.clksrc = { "aclk_gscl_400", },
};
struct platform_device exynos_device_md0 = {
.name = "exynos-mdev",
.id = 0,
};
struct platform_device exynos_device_md1 = {
.name = "exynos-mdev",
.id = 1,
};
static struct platform_device *<API key>[] __initdata = {
&exynos_device_md0,
&exynos_device_md1,
&exynos5_device_gsc0,
&exynos5_device_gsc1,
&s5p_device_fimg2d,
#ifdef <API key>
&s5p_device_mfc,
#endif
&<API key>,
&<API key>,
&<API key>,
&<API key>,
&s5p_device_mixer,
&s5p_device_hdmi,
&s5p_device_cec,
};
static struct fimg2d_platdata fimg2d_data __initdata = {
.ip_ver = IP_VER_G2D_5R,
.hw_ver = 0x43,
.parent_clkname = "sclk_mediatop_pll",
.clkname = "aclk_g2d_333",
.gate_clkname = "fimg2d",
.clkrate = 333 * MHZ,
.cpu_min = 400000, /* KFC 800MHz */
.mif_min = 667000,
.int_min = 333000,
};
#ifdef <API key>
static struct <API key> <API key> __initdata = {
.ip_ver = IP_VER_JPEG_HX_5R,
.gateclk = "jpeg-hx",
};
#endif
static struct s5p_platform_cec hdmi_cec_data __initdata = {
};
static struct s5p_mxr_platdata mxr_platdata __initdata = {
.ip_ver = IP_VER_TV_5R,
};
static struct s5p_hdmi_platdata hdmi_platdata __initdata = {
.ip_ver = IP_VER_TV_5R,
};
static struct i2c_board_info hs_i2c_devs2[] __initdata = {
{
I2C_BOARD_INFO("exynos_hdcp", (0x74 >> 1)),
},
{
I2C_BOARD_INFO("exynos_edid", (0xA0 >> 1)),
},
};
struct <API key> hs_i2c2_data __initdata = {
.bus_number = 2,
.operation_mode = HSI2C_INTERRUPT,
.speed_mode = HSI2C_FAST_SPD,
.fast_speed = 100000,
.high_speed = 2500000,
.cfg_gpio = NULL,
};
void __init <API key>(void)
{
#ifdef <API key>
<API key>(&xyref5260_mfc_pd);
dev_set_name(&s5p_device_mfc.dev, "s3c-mfc");
clk_add_alias("mfc", "s5p-mfc-v6", "mfc", &s5p_device_mfc.dev);
s5p_mfc_setname(&s5p_device_mfc, "s5p-mfc-v6");
#endif
<API key>(<API key>,
ARRAY_SIZE(<API key>));
<API key>(IP_VER_GSC_5A);
<API key>(160000, 111000);
s3c_set_platdata(&<API key>,
sizeof(<API key>), &exynos5_device_gsc0);
s3c_set_platdata(&<API key>,
sizeof(<API key>), &exynos5_device_gsc1);
<API key>(&fimg2d_data);
#ifdef <API key>
s3c_set_platdata(&<API key>, sizeof(<API key>),
&<API key>);
#endif
s3c_set_platdata(&xyref5260_mscl_pd, sizeof(xyref5260_mscl_pd),
&<API key>);
s3c_set_platdata(&xyref5260_mscl_pd, sizeof(xyref5260_mscl_pd),
&<API key>);
dev_set_name(&s5p_device_hdmi.dev, "exynos5-hdmi");
s5p_tv_setup();
<API key>(&hdmi_cec_data);
s3c_set_platdata(&mxr_platdata, sizeof(mxr_platdata), &s5p_device_mixer);
<API key>(&hdmi_platdata);
<API key>(&hs_i2c2_data);
<API key>(2, hs_i2c_devs2, ARRAY_SIZE(hs_i2c_devs2));
}
|
#ifndef <API key>
#define <API key>
#include "SdoCommand.h"
class CommandDownload:
public SdoCommand
{
public:
CommandDownload();
string helpString(const string &) const;
void execute(const StringVector &);
protected:
enum {DefaultBufferSize = 1024};
};
#endif
|
import Carousel from '../../../../../node_modules/bootstrap/js/src/carousel';
window.bootstrap = window.bootstrap || {};
window.bootstrap.Carousel = Carousel;
if (Joomla && Joomla.getOptions) {
// Get the elements/configurations from the PHP
const carousels = Joomla.getOptions('bootstrap.carousel');
// Initialise the elements
if (typeof carousels === 'object' && carousels !== null) {
Object.keys(carousels).forEach((carousel) => {
const opt = carousels[carousel];
const options = {
interval: opt.interval ? opt.interval : 5000,
keyboard: opt.keyboard ? opt.keyboard : true,
pause: opt.pause ? opt.pause : 'hover',
slide: opt.slide ? opt.slide : false,
wrap: opt.wrap ? opt.wrap : true,
touch: opt.touch ? opt.touch : true,
};
const elements = Array.from(document.querySelectorAll(carousel));
if (elements.length) {
elements.map((el) => new window.bootstrap.Carousel(el, options));
}
});
}
}
export default Carousel;
|
;(function($) {
$.noty.layouts.centerRight = {
name: 'centerRight',
options: { // overrides options
},
container: {
object: '<ul id="<API key>" />',
selector: 'ul#<API key>',
style: function() {
$(this).css({
right: 20,
position: 'fixed',
width: '310px',
height: 'auto',
margin: 0,
padding: 0,
listStyleType: 'none',
zIndex: 10000000
});
// getting hidden height
var dupe = $(this).clone().css({visibility:"hidden", display:"block", position:"absolute", top: 0, left: 0}).attr('id', 'dupe');
$("body").append(dupe);
dupe.find('.i-am-closing-now').remove();
dupe.find('li').css('display', 'block');
var actual_height = dupe.height();
dupe.remove();
if ($(this).hasClass('i-am-new')) {
$(this).css({
top: ($(window).height() - actual_height) / 2 + 'px'
});
} else {
$(this).animate({
top: ($(window).height() - actual_height) / 2 + 'px'
}, 500);
}
if (window.innerWidth < 600) {
$(this).css({
right: 5
});
}
}
},
parent: {
object: '<li />',
selector: 'li',
css: {}
},
css: {
display: 'none',
width: '310px'
},
addClass: ''
};
})(jQuery);
|
class CfgWeapons {
class ACE_ItemCore;
class <API key>;
class ACE_CableTie: ACE_ItemCore {
displayName = "$<API key>";
descriptionShort = "$<API key>";
model = QUOTE(PATHTOF(models\ace_cabletie.p3d));
picture = QUOTE(PATHTOF(UI\ace_cabletie_ca.paa));
scope = 2;
class ItemInfo: <API key> {
mass = 1;
};
};
};
|
function c16550875.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(<API key>)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(<API key>)
e1:SetTarget(c16550875.target)
e1:SetOperation(c16550875.operation)
c:RegisterEffect(e1)
--Atk
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(<API key>)
e2:SetValue(800)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(<API key>)
c:RegisterEffect(e3)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(<API key>)
e3:SetValue(c16550875.eqlimit)
c:RegisterEffect(e3)
--Search
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(16550875,0))
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_SINGLE+<API key>)
e4:SetProperty(<API key>)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c16550875.thcon)
e4:SetTarget(c16550875.thtg)
e4:SetOperation(c16550875.thop)
c:RegisterEffect(e4)
end
function c16550875.eqlimit(e,c)
return c:IsSetCard(0x56)
end
function c16550875.filter(c)
return c:IsFaceup() and c:IsSetCard(0x56)
end
function c16550875.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c16550875.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c16550875.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c16550875.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c16550875.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
end
end
function c16550875.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousPosition(POS_FACEUP)
and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c16550875.thfilter(c)
return c:IsSetCard(0x56) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c16550875.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c16550875.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c16550875.thfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c16550875.thfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0)
end
function c16550875.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
|
<?php
class Block {
/** @var string */
public $mReason;
/** @var bool|string */
public $mTimestamp;
/** @var int */
public $mAuto;
/** @var bool|string */
public $mExpiry;
public $mHideName;
/** @var int */
public $mParentBlockId;
/** @var int */
protected $mId;
/** @var bool */
protected $mFromMaster;
/** @var bool */
protected $mBlockEmail;
/** @var bool */
protected $mDisableUsertalk;
/** @var bool */
protected $mCreateAccount;
/** @var User|string */
protected $target;
/** @var int Hack for foreign blocking (CentralAuth) */
protected $forcedTargetID;
/** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
protected $type;
/** @var User */
protected $blocker;
/** @var bool */
protected $isHardblock = true;
/** @var bool */
protected $isAutoblocking = true;
# TYPE constants
const TYPE_USER = 1;
const TYPE_IP = 2;
const TYPE_RANGE = 3;
const TYPE_AUTO = 4;
const TYPE_ID = 5;
/**
* @todo FIXME: Don't know what the best format to have for this constructor
* is, but fourteen optional parameters certainly isn't it.
* @param string $address
* @param int $user
* @param int $by
* @param string $reason
* @param mixed $timestamp
* @param int $auto
* @param string $expiry
* @param int $anonOnly
* @param int $createAccount
* @param int $enableAutoblock
* @param int $hideName
* @param int $blockEmail
* @param int $allowUsertalk
* @param string $byText
*/
function __construct( $address = '', $user = 0, $by = 0, $reason = '',
$timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
$hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = ''
) {
if ( $timestamp === 0 ) {
$timestamp = wfTimestampNow();
}
if ( count( func_get_args() ) > 0 ) {
# Soon... :D
# wfDeprecated( __METHOD__ . " with arguments" );
}
$this->setTarget( $address );
if ( $this->target instanceof User && $user ) {
$this->forcedTargetID = $user; // needed for foreign users
}
if ( $by ) { // local user
$this->setBlocker( User::newFromId( $by ) );
} else { // foreign user
$this->setBlocker( $byText );
}
$this->mReason = $reason;
$this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
$this->mAuto = $auto;
$this->isHardblock( !$anonOnly );
$this->prevents( 'createaccount', $createAccount );
if ( $expiry == 'infinity' || $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
$this->mExpiry = 'infinity';
} else {
$this->mExpiry = wfTimestamp( TS_MW, $expiry );
}
$this->isAutoblocking( $enableAutoblock );
$this->mHideName = $hideName;
$this->prevents( 'sendemail', $blockEmail );
$this->prevents( 'editownusertalk', !$allowUsertalk );
$this->mFromMaster = false;
}
/**
* Load a blocked user from their block id.
*
* @param int $id Block id to search for
* @return Block|null
*/
public static function newFromID( $id ) {
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->selectRow(
'ipblocks',
self::selectFields(),
array( 'ipb_id' => $id ),
__METHOD__
);
if ( $res ) {
return self::newFromRow( $res );
} else {
return null;
}
}
/**
* Return the list of ipblocks fields that should be selected to create
* a new block.
* @return array
*/
public static function selectFields() {
return array(
'ipb_id',
'ipb_address',
'ipb_by',
'ipb_by_text',
'ipb_reason',
'ipb_timestamp',
'ipb_auto',
'ipb_anon_only',
'ipb_create_account',
'<API key>',
'ipb_expiry',
'ipb_deleted',
'ipb_block_email',
'ipb_allow_usertalk',
'ipb_parent_block_id',
);
}
/**
* Check if two blocks are effectively equal. Doesn't check irrelevant things like
* the blocking user or the block timestamp, only things which affect the blocked user
*
* @param Block $block
*
* @return bool
*/
public function equals( Block $block ) {
return (
(string)$this->target == (string)$block->target
&& $this->type == $block->type
&& $this->mAuto == $block->mAuto
&& $this->isHardblock() == $block->isHardblock()
&& $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
&& $this->mExpiry == $block->mExpiry
&& $this->isAutoblocking() == $block->isAutoblocking()
&& $this->mHideName == $block->mHideName
&& $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
&& $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
&& $this->mReason == $block->mReason
);
}
/**
* Load a block from the database which affects the already-set $this->target:
* 1) A block directly on the given user or IP
* 2) A rangeblock encompassing the given IP (smallest first)
* 3) An autoblock on the given IP
* @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
* make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
* @throws MWException
* @return bool Whether a relevant block was found
*/
protected function newLoad( $vagueTarget = null ) {
$db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
if ( $this->type !== null ) {
$conds = array(
'ipb_address' => array( (string)$this->target ),
);
} else {
$conds = array( 'ipb_address' => array() );
}
# Be aware that the != '' check is explicit, since empty values will be
# passed by some callers (bug 29116)
if ( $vagueTarget != '' ) {
list( $target, $type ) = self::parseTarget( $vagueTarget );
switch ( $type ) {
case self::TYPE_USER:
# Slightly weird, but who are we to argue?
$conds['ipb_address'][] = (string)$target;
break;
case self::TYPE_IP:
$conds['ipb_address'][] = (string)$target;
$conds[] = self::getRangeCond( IP::toHex( $target ) );
$conds = $db->makeList( $conds, LIST_OR );
break;
case self::TYPE_RANGE:
list( $start, $end ) = IP::parseRange( $target );
$conds['ipb_address'][] = (string)$target;
$conds[] = self::getRangeCond( $start, $end );
$conds = $db->makeList( $conds, LIST_OR );
break;
default:
throw new MWException( "Tried to load block with invalid type" );
}
}
$res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );
# This result could contain a block on the user, a block on the IP, and a russian-doll
# set of rangeblocks. We want to choose the most specific one, so keep a leader board.
$bestRow = null;
# Lower will be better
$bestBlockScore = 100;
# This is begging for $this = $bestBlock, but that's not allowed in PHP :(
$<API key> = null;
foreach ( $res as $row ) {
$block = self::newFromRow( $row );
# Don't use expired blocks
if ( $block->deleteIfExpired() ) {
continue;
}
# Don't use anon only blocks on users
if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
continue;
}
if ( $block->getType() == self::TYPE_RANGE ) {
# This is the number of bits that are allowed to vary in the block, give
# or take some floating point errors
$end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
$start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
$size = log( $end - $start + 1, 2 );
# This has the nice property that a /32 block is ranked equally with a
# single-IP block, which is exactly what it is...
$score = self::TYPE_RANGE - 1 + ( $size / 128 );
} else {
$score = $block->getType();
}
if ( $score < $bestBlockScore ) {
$bestBlockScore = $score;
$bestRow = $row;
$<API key> = $block->prevents( 'edit' );
}
}
if ( $bestRow !== null ) {
$this->initFromRow( $bestRow );
$this->prevents( 'edit', $<API key> );
return true;
} else {
return false;
}
}
/**
* Get a set of SQL conditions which will select rangeblocks encompassing a given range
* @param string $start Hexadecimal IP representation
* @param string $end Hexadecimal IP representation, or null to use $start = $end
* @return string
*/
public static function getRangeCond( $start, $end = null ) {
if ( $end === null ) {
$end = $start;
}
# Per bug 14634, we want to include relevant active rangeblocks; for
# rangeblocks, we want to include larger ranges which enclose the given
# range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
# so we can improve performance by filtering on a LIKE clause
$chunk = self::getIpFragment( $start );
$dbr = wfGetDB( DB_SLAVE );
$like = $dbr->buildLike( $chunk, $dbr->anyString() );
# Fairly hard to make a malicious SQL statement out of hex characters,
# but stranger things have happened...
$safeStart = $dbr->addQuotes( $start );
$safeEnd = $dbr->addQuotes( $end );
return $dbr->makeList(
array(
"ipb_range_start $like",
"ipb_range_start <= $safeStart",
"ipb_range_end >= $safeEnd",
),
LIST_AND
);
}
/**
* Get the component of an IP address which is certain to be the same between an IP
* address and a rangeblock containing that IP address.
* @param string $hex Hexadecimal IP representation
* @return string
*/
protected static function getIpFragment( $hex ) {
global $wgBlockCIDRLimit;
if ( substr( $hex, 0, 3 ) == 'v6-' ) {
return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
} else {
return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
}
}
/**
* Given a database row from the ipblocks table, initialize
* member variables
* @param stdClass $row A row from the ipblocks table
*/
protected function initFromRow( $row ) {
$this->setTarget( $row->ipb_address );
if ( $row->ipb_by ) { // local user
$this->setBlocker( User::newFromId( $row->ipb_by ) );
} else { // foreign user
$this->setBlocker( $row->ipb_by_text );
}
$this->mReason = $row->ipb_reason;
$this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
$this->mAuto = $row->ipb_auto;
$this->mHideName = $row->ipb_deleted;
$this->mId = $row->ipb_id;
$this->mParentBlockId = $row->ipb_parent_block_id;
// I wish I didn't have to do this
$db = wfGetDB( DB_SLAVE );
if ( $row->ipb_expiry == $db->getInfinity() ) {
$this->mExpiry = 'infinity';
} else {
$this->mExpiry = wfTimestamp( TS_MW, $row->ipb_expiry );
}
$this->isHardblock( !$row->ipb_anon_only );
$this->isAutoblocking( $row-><API key> );
$this->prevents( 'createaccount', $row->ipb_create_account );
$this->prevents( 'sendemail', $row->ipb_block_email );
$this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
}
/**
* Create a new Block object from a database row
* @param stdClass $row Row from the ipblocks table
* @return Block
*/
public static function newFromRow( $row ) {
$block = new Block;
$block->initFromRow( $row );
return $block;
}
/**
* Delete the row from the IP blocks table.
*
* @throws MWException
* @return bool
*/
public function delete() {
if ( wfReadOnly() ) {
return false;
}
if ( !$this->getId() ) {
throw new MWException( "Block::delete() requires that the mId member be filled\n" );
}
$dbw = wfGetDB( DB_MASTER );
$dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__ );
$dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__ );
return $dbw->affectedRows() > 0;
}
/**
* Insert a block into the block table. Will fail if there is a conflicting
* block (same name and options) already in the database.
*
* @param DatabaseBase $dbw If you have one available
* @return bool|array False on failure, assoc array on success:
* ('id' => block ID, 'autoIds' => array of autoblock IDs)
*/
public function insert( $dbw = null ) {
wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
if ( $dbw === null ) {
$dbw = wfGetDB( DB_MASTER );
}
# Don't collide with expired blocks
Block::purgeExpired();
$row = $this->getDatabaseArray();
$row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
$dbw->insert(
'ipblocks',
$row,
__METHOD__,
array( 'IGNORE' )
);
$affected = $dbw->affectedRows();
$this->mId = $dbw->insertId();
if ( $affected ) {
$auto_ipd_ids = $this-><API key>();
return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
}
return false;
}
/**
* Update a block in the DB with new parameters.
* The ID field needs to be loaded first.
*
* @return bool|array False on failure, array on success:
* ('id' => block ID, 'autoIds' => array of autoblock IDs)
*/
public function update() {
wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
$dbw = wfGetDB( DB_MASTER );
$dbw->startAtomic( __METHOD__ );
$dbw->update(
'ipblocks',
$this->getDatabaseArray( $dbw ),
array( 'ipb_id' => $this->getId() ),
__METHOD__
);
$affected = $dbw->affectedRows();
if ( $this->isAutoblocking() ) {
// update corresponding autoblock(s) (bug 48813)
$dbw->update(
'ipblocks',
$this-><API key>(),
array( 'ipb_parent_block_id' => $this->getId() ),
__METHOD__
);
} else {
// autoblock no longer required, delete corresponding autoblock(s)
$dbw->delete(
'ipblocks',
array( 'ipb_parent_block_id' => $this->getId() ),
__METHOD__
);
}
$dbw->endAtomic( __METHOD__ );
if ( $affected ) {
$auto_ipd_ids = $this-><API key>();
return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
}
return false;
}
/**
* Get an array suitable for passing to $dbw->insert() or $dbw->update()
* @param DatabaseBase $db
* @return array
*/
protected function getDatabaseArray( $db = null ) {
if ( !$db ) {
$db = wfGetDB( DB_SLAVE );
}
$expiry = $db->encodeExpiry( $this->mExpiry );
if ( $this->forcedTargetID ) {
$uid = $this->forcedTargetID;
} else {
$uid = $this->target instanceof User ? $this->target->getID() : 0;
}
$a = array(
'ipb_address' => (string)$this->target,
'ipb_user' => $uid,
'ipb_by' => $this->getBy(),
'ipb_by_text' => $this->getByName(),
'ipb_reason' => $this->mReason,
'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
'ipb_auto' => $this->mAuto,
'ipb_anon_only' => !$this->isHardblock(),
'ipb_create_account' => $this->prevents( 'createaccount' ),
'<API key>' => $this->isAutoblocking(),
'ipb_expiry' => $expiry,
'ipb_range_start' => $this->getRangeStart(),
'ipb_range_end' => $this->getRangeEnd(),
'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
'ipb_block_email' => $this->prevents( 'sendemail' ),
'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
'ipb_parent_block_id' => $this->mParentBlockId
);
return $a;
}
/**
* @return array
*/
protected function <API key>() {
return array(
'ipb_by' => $this->getBy(),
'ipb_by_text' => $this->getByName(),
'ipb_reason' => $this->mReason,
'ipb_create_account' => $this->prevents( 'createaccount' ),
'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
);
}
/**
* Retroactively autoblocks the last IP used by the user (if it is a user)
* blocked by this Block.
*
* @return array Block IDs of retroactive autoblocks made
*/
protected function <API key>() {
$blockIds = array();
# If autoblock is enabled, autoblock the LAST IP(s) used
if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
$continue = Hooks::run(
'<API key>', array( $this, &$blockIds ) );
if ( $continue ) {
self::<API key>( $this, $blockIds );
}
}
return $blockIds;
}
/**
* Retroactively autoblocks the last IP used by the user (if it is a user)
* blocked by this Block. This will use the recentchanges table.
*
* @param Block $block
* @param array &$blockIds
*/
protected static function <API key>( Block $block, array &$blockIds ) {
global $wgPutIPinRC;
// No IPs are in recentchanges table, so nothing to select
if ( !$wgPutIPinRC ) {
return;
}
$dbr = wfGetDB( DB_SLAVE );
$options = array( 'ORDER BY' => 'rc_timestamp DESC' );
$conds = array( 'rc_user_text' => (string)$block->getTarget() );
// Just the last IP used.
$options['LIMIT'] = 1;
$res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
__METHOD__, $options );
if ( !$res->numRows() ) {
# No results, don't autoblock anything
wfDebug( "No IP found to retroactively autoblock\n" );
} else {
foreach ( $res as $row ) {
if ( $row->rc_ip ) {
$id = $block->doAutoblock( $row->rc_ip );
if ( $id ) {
$blockIds[] = $id;
}
}
}
}
}
/**
* Checks whether a given IP is on the autoblock whitelist.
* TODO: this probably belongs somewhere else, but not sure where...
*
* @param string $ip The IP to check
* @return bool
*/
public static function <API key>( $ip ) {
global $wgMemc;
// Try to get the autoblock_whitelist from the cache, as it's faster
// than getting the msg raw and explode()'ing it.
$key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
$lines = $wgMemc->get( $key );
if ( !$lines ) {
$lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
$wgMemc->set( $key, $lines, 3600 * 24 );
}
wfDebug( "Checking the autoblock whitelist..\n" );
foreach ( $lines as $line ) {
# List items only
if ( substr( $line, 0, 1 ) !== '*' ) {
continue;
}
$wlEntry = substr( $line, 1 );
$wlEntry = trim( $wlEntry );
wfDebug( "Checking $ip against $wlEntry..." );
# Is the IP in this range?
if ( IP::isInRange( $ip, $wlEntry ) ) {
wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
return true;
} else {
wfDebug( " No match\n" );
}
}
return false;
}
/**
* Autoblocks the given IP, referring to this Block.
*
* @param string $autoblockIP The IP to autoblock.
* @return int|bool Block ID if an autoblock was inserted, false if not.
*/
public function doAutoblock( $autoblockIP ) {
# If autoblocks are disabled, go away.
if ( !$this->isAutoblocking() ) {
return false;
}
# Check for presence on the autoblock whitelist.
if ( self::<API key>( $autoblockIP ) ) {
return false;
}
# Allow hooks to cancel the autoblock.
if ( !Hooks::run( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
wfDebug( "Autoblock aborted by hook.\n" );
return false;
}
# It's okay to autoblock. Go ahead and insert/update the block...
# Do not add a *new* block if the IP is already blocked.
$ipblock = Block::newFromTarget( $autoblockIP );
if ( $ipblock ) {
# Check if the block is an autoblock and would exceed the user block
# if renewed. If so, do nothing, otherwise prolong the block time...
if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
$this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
) {
# Reset block timestamp to now and its expiry to
# $wgAutoblockExpiry in the future
$ipblock->updateTimestamp();
}
return false;
}
# Make a new block object with the desired properties.
$autoblock = new Block;
wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
$autoblock->setTarget( $autoblockIP );
$autoblock->setBlocker( $this->getBlocker() );
$autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
->inContentLanguage()->plain();
$timestamp = wfTimestampNow();
$autoblock->mTimestamp = $timestamp;
$autoblock->mAuto = 1;
$autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
# Continue suppressing the name if needed
$autoblock->mHideName = $this->mHideName;
$autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
$autoblock->mParentBlockId = $this->mId;
if ( $this->mExpiry == 'infinity' ) {
# Original block was indefinite, start an autoblock now
$autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
} else {
# If the user is already blocked with an expiry date, we don't
# want to pile on top of that.
$autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
}
# Insert the block...
$status = $autoblock->insert();
return $status
? $status['id']
: false;
}
/**
* Check if a block has expired. Delete it if it is.
* @return bool
*/
public function deleteIfExpired() {
if ( $this->isExpired() ) {
wfDebug( "Block::deleteIfExpired() -- deleting\n" );
$this->delete();
$retVal = true;
} else {
wfDebug( "Block::deleteIfExpired() -- not expired\n" );
$retVal = false;
}
return $retVal;
}
/**
* Has the block expired?
* @return bool
*/
public function isExpired() {
$timestamp = wfTimestampNow();
wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
if ( !$this->mExpiry ) {
return false;
} else {
return $timestamp > $this->mExpiry;
}
}
/**
* Is the block address valid (i.e. not a null string?)
* @return bool
*/
public function isValid() {
return $this->getTarget() != null;
}
/**
* Update the timestamp on autoblocks.
*/
public function updateTimestamp() {
if ( $this->mAuto ) {
$this->mTimestamp = wfTimestamp();
$this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
$dbw = wfGetDB( DB_MASTER );
$dbw->update( 'ipblocks',
array( /* SET */
'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
),
array( /* WHERE */
'ipb_address' => (string)$this->getTarget()
),
__METHOD__
);
}
}
/**
* Get the IP address at the start of the range in Hex form
* @throws MWException
* @return string IP in Hex form
*/
public function getRangeStart() {
switch ( $this->type ) {
case self::TYPE_USER:
return '';
case self::TYPE_IP:
return IP::toHex( $this->target );
case self::TYPE_RANGE:
list( $start, ) = IP::parseRange( $this->target );
return $start;
default:
throw new MWException( "Block with invalid type" );
}
}
/**
* Get the IP address at the end of the range in Hex form
* @throws MWException
* @return string IP in Hex form
*/
public function getRangeEnd() {
switch ( $this->type ) {
case self::TYPE_USER:
return '';
case self::TYPE_IP:
return IP::toHex( $this->target );
case self::TYPE_RANGE:
list( , $end ) = IP::parseRange( $this->target );
return $end;
default:
throw new MWException( "Block with invalid type" );
}
}
/**
* Get the user id of the blocking sysop
*
* @return int (0 for foreign users)
*/
public function getBy() {
$blocker = $this->getBlocker();
return ( $blocker instanceof User )
? $blocker->getId()
: 0;
}
/**
* Get the username of the blocking sysop
*
* @return string
*/
public function getByName() {
$blocker = $this->getBlocker();
return ( $blocker instanceof User )
? $blocker->getName()
: (string)$blocker; // username
}
/**
* Get the block ID
* @return int
*/
public function getId() {
return $this->mId;
}
/**
* Get/set a flag determining whether the master is used for reads
*
* @param bool|null $x
* @return bool
*/
public function fromMaster( $x = null ) {
return wfSetVar( $this->mFromMaster, $x );
}
/**
* Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
* @param bool|null $x
* @return bool
*/
public function isHardblock( $x = null ) {
wfSetVar( $this->isHardblock, $x );
# You can't *not* hardblock a user
return $this->getType() == self::TYPE_USER
? true
: $this->isHardblock;
}
/**
* @param null|bool $x
* @return bool
*/
public function isAutoblocking( $x = null ) {
wfSetVar( $this->isAutoblocking, $x );
# You can't put an autoblock on an IP or range as we don't have any history to
# look over to get more IPs from
return $this->getType() == self::TYPE_USER
? $this->isAutoblocking
: false;
}
/**
* Get/set whether the Block prevents a given action
* @param string $action
* @param bool|null $x
* @return bool
*/
public function prevents( $action, $x = null ) {
switch ( $action ) {
case 'edit':
# For now... <evil laugh>
return true;
case 'createaccount':
return wfSetVar( $this->mCreateAccount, $x );
case 'sendemail':
return wfSetVar( $this->mBlockEmail, $x );
case 'editownusertalk':
return wfSetVar( $this->mDisableUsertalk, $x );
default:
return null;
}
}
/**
* Get the block name, but with autoblocked IPs hidden as per standard privacy policy
* @return string Text is escaped
*/
public function getRedactedName() {
if ( $this->mAuto ) {
return Html::rawElement(
'span',
array( 'class' => 'mw-autoblockid' ),
wfMessage( 'autoblockid', $this->mId )
);
} else {
return htmlspecialchars( $this->getTarget() );
}
}
/**
* Get a timestamp of the expiry for autoblocks
*
* @param string|int $timestamp
* @return string
*/
public static function getAutoblockExpiry( $timestamp ) {
global $wgAutoblockExpiry;
return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
}
/**
* Purge expired blocks from the ipblocks table
*/
public static function purgeExpired() {
if ( wfReadOnly() ) {
return;
}
$method = __METHOD__;
$dbw = wfGetDB( DB_MASTER );
$dbw->onTransactionIdle( function () use ( $dbw, $method ) {
$dbw->delete( 'ipblocks',
array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
} );
}
/**
* Given a target and the target's type, get an existing Block object if possible.
* @param string|User|int $specificTarget A block target, which may be one of several types:
* * A user to block, in which case $target will be a User
* * An IP to block, in which case $target will be a User generated by using
* User::newFromName( $ip, false ) to turn off name validation
* * An IP range, in which case $target will be a String "123.123.123.123/18" etc
* * The ID of an existing block, in the format "#12345" (since pure numbers are valid
* usernames
* Calling this with a user, IP address or range will not select autoblocks, and will
* only select a block where the targets match exactly (so looking for blocks on
* 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
* @param string|User|int $vagueTarget As above, but we will search for *any* block which
* affects that target (so for an IP address, get ranges containing that IP; and also
* get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
* @param bool $fromMaster Whether to use the DB_MASTER database
* @return Block|null (null if no relevant block could be found). The target and type
* of the returned Block will refer to the actual block which was found, which might
* not be the same as the target you gave if you used $vagueTarget!
*/
public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
list( $target, $type ) = self::parseTarget( $specificTarget );
if ( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ) {
return Block::newFromID( $target );
} elseif ( $target === null && $vagueTarget == '' ) {
# We're not going to find anything useful here
# Be aware that the == '' check is explicit, since empty values will be
# passed by some callers (bug 29116)
return null;
} elseif ( in_array(
$type,
array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) )
) {
$block = new Block();
$block->fromMaster( $fromMaster );
if ( $type !== null ) {
$block->setTarget( $target );
}
if ( $block->newLoad( $vagueTarget ) ) {
return $block;
}
}
return null;
}
/**
* Get all blocks that match any IP from an array of IP addresses
*
* @param array $ipChain List of IPs (strings), usually retrieved from the
* X-Forwarded-For header of the request
* @param bool $isAnon Exclude anonymous-only blocks if false
* @param bool $fromMaster Whether to query the master or slave database
* @return array Array of Blocks
* @since 1.22
*/
public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
if ( !count( $ipChain ) ) {
return array();
}
$conds = array();
foreach ( array_unique( $ipChain ) as $ipaddr ) {
# Discard invalid IP addresses. Since XFF can be spoofed and we do not
# necessarily trust the header given to us, make sure that we are only
# checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
# Do not treat private IP spaces as special as it may be desirable for wikis
# to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
if ( !IP::isValid( $ipaddr ) ) {
continue;
}
# Don't check trusted IPs (includes local squids which will be in every request)
if ( IP::isTrustedProxy( $ipaddr ) ) {
continue;
}
# Check both the original IP (to check against single blocks), as well as build
# the clause to check for rangeblocks for the given IP.
$conds['ipb_address'][] = $ipaddr;
$conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
}
if ( !count( $conds ) ) {
return array();
}
if ( $fromMaster ) {
$db = wfGetDB( DB_MASTER );
} else {
$db = wfGetDB( DB_SLAVE );
}
$conds = $db->makeList( $conds, LIST_OR );
if ( !$isAnon ) {
$conds = array( $conds, 'ipb_anon_only' => 0 );
}
$selectFields = array_merge(
array( 'ipb_range_start', 'ipb_range_end' ),
Block::selectFields()
);
$rows = $db->select( 'ipblocks',
$selectFields,
$conds,
__METHOD__
);
$blocks = array();
foreach ( $rows as $row ) {
$block = self::newFromRow( $row );
if ( !$block->deleteIfExpired() ) {
$blocks[] = $block;
}
}
return $blocks;
}
/**
* From a list of multiple blocks, find the most exact and strongest Block.
*
* The logic for finding the "best" block is:
* - Blocks that match the block's target IP are preferred over ones in a range
* - Hardblocks are chosen over softblocks that prevent account creation
* - Softblocks that prevent account creation are chosen over other softblocks
* - Other softblocks are chosen over autoblocks
* - If there are multiple exact or range blocks at the same level, the one chosen
* is random
* This should be used when $blocks where retrieved from the user's IP address
* and $ipChain is populated from the same IP address information.
*
* @param array $blocks Array of Block objects
* @param array $ipChain List of IPs (strings). This is used to determine how "close"
* a block is to the server, and if a block matches exactly, or is in a range.
* The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
* local-squid, ...)
* @throws MWException
* @return Block|null The "best" block from the list
*/
public static function chooseBlock( array $blocks, array $ipChain ) {
if ( !count( $blocks ) ) {
return null;
} elseif ( count( $blocks ) == 1 ) {
return $blocks[0];
}
// Sort hard blocks before soft ones and secondarily sort blocks
// that disable account creation before those that don't.
usort( $blocks, function ( Block $a, Block $b ) {
$aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
$bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
return strcmp( $bWeight, $aWeight ); // highest weight first
} );
$blocksListExact = array(
'hard' => false,
'disable_create' => false,
'other' => false,
'auto' => false
);
$blocksListRange = array(
'hard' => false,
'disable_create' => false,
'other' => false,
'auto' => false
);
$ipChain = array_reverse( $ipChain );
/** @var Block $block */
foreach ( $blocks as $block ) {
// Stop searching if we have already have a "better" block. This
// is why the order of the blocks matters
if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
break;
} elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
break;
}
foreach ( $ipChain as $checkip ) {
$checkipHex = IP::toHex( $checkip );
if ( (string)$block->getTarget() === $checkip ) {
if ( $block->isHardblock() ) {
$blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
} elseif ( $block->prevents( 'createaccount' ) ) {
$blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
} elseif ( $block->mAuto ) {
$blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
} else {
$blocksListExact['other'] = $blocksListExact['other'] ?: $block;
}
// We found closest exact match in the ip list, so go to the next Block
break;
} elseif ( array_filter( $blocksListExact ) == array()
&& $block->getRangeStart() <= $checkipHex
&& $block->getRangeEnd() >= $checkipHex
) {
if ( $block->isHardblock() ) {
$blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
} elseif ( $block->prevents( 'createaccount' ) ) {
$blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
} elseif ( $block->mAuto ) {
$blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
} else {
$blocksListRange['other'] = $blocksListRange['other'] ?: $block;
}
break;
}
}
}
if ( array_filter( $blocksListExact ) == array() ) {
$blocksList = &$blocksListRange;
} else {
$blocksList = &$blocksListExact;
}
$chosenBlock = null;
if ( $blocksList['hard'] ) {
$chosenBlock = $blocksList['hard'];
} elseif ( $blocksList['disable_create'] ) {
$chosenBlock = $blocksList['disable_create'];
} elseif ( $blocksList['other'] ) {
$chosenBlock = $blocksList['other'];
} elseif ( $blocksList['auto'] ) {
$chosenBlock = $blocksList['auto'];
} else {
throw new MWException( "Proxy block found, but couldn't be classified." );
}
return $chosenBlock;
}
/**
* From an existing Block, get the target and the type of target.
* Note that, except for null, it is always safe to treat the target
* as a string; for User objects this will return User::__toString()
* which in turn gives User::getName().
*
* @param string|int|User|null $target
* @return array( User|String|null, Block::TYPE_ constant|null )
*/
public static function parseTarget( $target ) {
# We may have been through this before
if ( $target instanceof User ) {
if ( IP::isValid( $target->getName() ) ) {
return array( $target, self::TYPE_IP );
} else {
return array( $target, self::TYPE_USER );
}
} elseif ( $target === null ) {
return array( null, null );
}
$target = trim( $target );
if ( IP::isValid( $target ) ) {
# We can still create a User if it's an IP address, but we need to turn
# off validation checking (which would exclude IP addresses)
return array(
User::newFromName( IP::sanitizeIP( $target ), false ),
Block::TYPE_IP
);
} elseif ( IP::isValidBlock( $target ) ) {
# Can't create a User from an IP range
return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
}
# Consider the possibility that this is not a username at all
# but actually an old subpage (bug #29797)
if ( strpos( $target, '/' ) !== false ) {
# An old subpage, drill down to the user behind it
$parts = explode( '/', $target );
$target = $parts[0];
}
$userObj = User::newFromName( $target );
if ( $userObj instanceof User ) {
# Note that since numbers are valid usernames, a $target of "12345" will be
# considered a User. If you want to pass a block ID, prepend a hash "#12345",
# since hash characters are not valid in usernames or titles generally.
return array( $userObj, Block::TYPE_USER );
} elseif ( preg_match( '/^#\d+$/', $target ) ) {
# Autoblock reference in the form "#12345"
return array( substr( $target, 1 ), Block::TYPE_AUTO );
} else {
# WTF?
return array( null, null );
}
}
/**
* Get the type of target for this particular block
* @return int Block::TYPE_ constant, will never be TYPE_ID
*/
public function getType() {
return $this->mAuto
? self::TYPE_AUTO
: $this->type;
}
/**
* Get the target and target type for this particular Block. Note that for autoblocks,
* this returns the unredacted name; frontend functions need to call $block->getRedactedName()
* in this situation.
* @return array( User|String, Block::TYPE_ constant )
* @todo FIXME: This should be an integral part of the Block member variables
*/
public function getTargetAndType() {
return array( $this->getTarget(), $this->getType() );
}
/**
* Get the target for this particular Block. Note that for autoblocks,
* this returns the unredacted name; frontend functions need to call $block->getRedactedName()
* in this situation.
* @return User|string
*/
public function getTarget() {
return $this->target;
}
/**
* @since 1.19
*
* @return mixed|string
*/
public function getExpiry() {
return $this->mExpiry;
}
/**
* Set the target for this block, and update $this->type accordingly
* @param mixed $target
*/
public function setTarget( $target ) {
list( $this->target, $this->type ) = self::parseTarget( $target );
}
/**
* Get the user who implemented this block
* @return User|string Local User object or string for a foreign user
*/
public function getBlocker() {
return $this->blocker;
}
/**
* Set the user who implemented (or will implement) this block
* @param User|string $user Local User object or username string for foreign users
*/
public function setBlocker( $user ) {
$this->blocker = $user;
}
/**
* Get the key and parameters for the corresponding error message.
*
* @since 1.22
* @param IContextSource $context
* @return array
*/
public function getPermissionsError( IContextSource $context ) {
$blocker = $this->getBlocker();
if ( $blocker instanceof User ) { // local user
$blockerUserpage = $blocker->getUserPage();
$link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
} else { // foreign user
$link = $blocker;
}
$reason = $this->mReason;
if ( $reason == '' ) {
$reason = $context->msg( 'blockednoreason' )->text();
}
/* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
* This could be a username, an IP range, or a single IP. */
$intended = $this->getTarget();
$lang = $context->getLanguage();
return array(
$this->mAuto ? 'autoblockedtext' : 'blockedtext',
$link,
$reason,
$context->getRequest()->getIP(),
$this->getByName(),
$this->getId(),
$lang->formatExpiry( $this->mExpiry ),
(string)$intended,
$lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
);
}
}
|
/**
* @ngdoc factory
* @name Bastion.factory:BastionResource
*
* @requires BastionResource
*
* @description
* Base module that defines the Katello module namespace and includes any thirdparty
* modules used by the application.
*/
angular.module('Bastion').factory('BastionResource', ['$resource', function ($resource) {
return function (url, paramDefaults, actions) {
var defaultActions;
defaultActions = {
queryPaged: {method: 'GET', isArray: false},
queryUnpaged: {method: 'GET', isArray: false, params: {'full_result': true}}
};
actions = angular.extend({}, defaultActions, actions);
return $resource(url, paramDefaults, actions);
};
}]);
|
#ifndef <API key>
#define <API key>
#include <linux/regulator/consumer.h>
#include <linux/suspend.h>
struct regulator;
/*
* Regulator operation constraint flags. These flags are used to enable
* certain regulator operations and can be OR'ed together.
*
* VOLTAGE: Regulator output voltage can be changed by software on this
* board/machine.
* CURRENT: Regulator output current can be changed by software on this
* board/machine.
* MODE: Regulator operating mode can be changed by software on this
* board/machine.
* STATUS: Regulator can be enabled and disabled.
* DRMS: Dynamic Regulator Mode Switching is enabled for this regulator.
* BYPASS: Regulator can be put into bypass mode
* CONTROL: Dynamic change control mode of Regulator i.e I2C or PWM.
*/
#define <API key> 0x1
#define <API key> 0x2
#define <API key> 0x4
#define <API key> 0x8
#define <API key> 0x10
#define <API key> 0x20
#define <API key> 0x40
/**
* struct regulator_state - regulator state during low power system states
*
* This describes a regulators state during a system wide low power
* state. One of enabled or disabled must be set for the
* configuration to be applied.
*
* @uV: Operating voltage during suspend.
* @mode: Operating mode during suspend.
* @enabled: Enabled during suspend.
* @disabled: Disabled during suspend.
*/
struct regulator_state {
int uV; /* suspend voltage */
unsigned int mode; /* suspend regulator operating mode */
int enabled; /* is regulator enabled in this suspend state */
int disabled; /* is the regulator disbled in this suspend state */
};
/**
* struct <API key> - regulator operating constraints.
*
* This struct describes regulator and board/machine specific constraints.
*
* @name: Descriptive name for the constraints, used for display purposes.
*
* @min_uV: Smallest voltage consumers may set.
* @max_uV: Largest voltage consumers may set.
* @init_uV: Initial voltage consumers may set.
* @uV_offset: Offset applied to voltages from consumer to compensate for
* voltage drops.
*
* @min_uA: Smallest current consumers may set.
* @max_uA: Largest current consumers may set.
*
* @valid_modes_mask: Mask of modes which may be configured by consumers.
* @valid_ops_mask: Operations which may be performed by consumers.
*
* @always_on: Set if the regulator should never be disabled.
* @boot_on: Set if the regulator is enabled when the system is initially
* started. If the regulator is not enabled by the hardware or
* bootloader then it will be enabled when the constraints are
* applied.
* @apply_uV: Apply the voltage constraint when initialising.
*
* @input_uV: Input voltage for regulator when supplied by another regulator.
*
* @state_disk: State for regulator when system is suspended in disk mode.
* @state_mem: State for regulator when system is suspended in mem mode.
* @state_standby: State for regulator when system is suspended in standby
* mode.
* @initial_state: Suspend state to set by default.
* @initial_mode: Mode to set at startup.
* @ramp_delay: Time to settle down after voltage change (unit: uV/us)
* @enable_time: Turn-on time of the rails (unit: microseconds)
* @disable_time: Turn-off time of the rails (unit: microseconds)
*/
struct <API key> {
const char *name;
/* voltage output range (inclusive) - for voltage control */
int min_uV;
int max_uV;
int init_uV;
int uV_offset;
/* current output range (inclusive) - for current control */
int min_uA;
int max_uA;
/* valid regulator operating modes for this machine */
unsigned int valid_modes_mask;
/* valid operations for regulator on this machine */
unsigned int valid_ops_mask;
/* regulator input voltage - only if supply is another regulator */
int input_uV;
/* regulator suspend states for global PMIC STANDBY/HIBERNATE */
struct regulator_state state_disk;
struct regulator_state state_mem;
struct regulator_state state_standby;
suspend_state_t initial_state; /* suspend state to set at init */
/* mode to set on startup */
unsigned int initial_mode;
/* mode to be set on sleep mode */
unsigned int sleep_mode;
unsigned int ramp_delay;
unsigned int enable_time;
unsigned int disable_time;
unsigned int startup_delay;
/* constraint flags */
unsigned always_on:1; /* regulator never off when system is on */
unsigned boot_on:1; /* bootloader/firmware enabled regulator */
unsigned apply_uV:1; /* apply uV constraint if min == max */
unsigned boot_off:1; /* bootloader/firmware disabled regulator */
unsigned int <API key>:1;
};
/**
* struct <API key> - supply -> device mapping
*
* This maps a supply name to a device. Use of dev_name allows support for
* buses which make struct device available late such as I2C.
*
* @dev_name: Result of dev_name() for the consumer.
* @supply: Name for the supply.
*/
struct <API key> {
const char *dev_name; /* dev_name() for consumer */
const char *supply; /* consumer supply - e.g. "vcc" */
};
/* Initialize struct <API key> */
#define REGULATOR_SUPPLY(_name, _dev_name) \
{ \
.supply = _name, \
.dev_name = _dev_name, \
}
/**
* struct regulator_init_data - regulator platform initialisation data.
*
* Initialisation constraints, our supply and consumers supplies.
*
* @supply_regulator: Parent regulator. Specified using the regulator name
* as it appears in the name field in sysfs, which can
* be explicitly set using the constraints field 'name'.
*
* @constraints: Constraints. These must be specified for the regulator to
* be usable.
* @<API key>: Number of consumer device supplies.
* @consumer_supplies: Consumer device supply configuration.
*
* @regulator_init: Callback invoked when the regulator has been registered.
* @driver_data: Data passed to regulator_init.
*/
struct regulator_init_data {
const char *supply_regulator; /* or NULL for system supply */
struct <API key> constraints;
int <API key>;
struct <API key> *consumer_supplies;
/* optional regulator machine specific init */
int (*regulator_init)(void *driver_data);
void *driver_data; /* core does not touch this */
};
int <API key>(suspend_state_t state);
int <API key>(void);
#ifdef CONFIG_REGULATOR
void <API key>(void);
void <API key>(void);
#else
static inline void <API key>(void)
{
}
static inline void <API key>(void)
{
}
#endif
#endif
|
<?php
/**
* @file
* Definition of Drupal\block\Tests\BlockAdminThemeTest.
*/
namespace Drupal\block\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the block system with admin themes.
*
* @group block
*/
class BlockAdminThemeTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('block');
/**
* Check for the accessibility of the admin theme on the block admin page.
*/
function testAdminTheme() {
// Create administrative user.
$admin_user = $this->drupalCreateUser(array('administer blocks', 'administer themes'));
$this->drupalLogin($admin_user);
// Ensure that access to block admin page is denied when theme is disabled.
$this->drupalGet('admin/structure/block/list/bartik');
$this->assertResponse(403);
// Enable admin theme and confirm that tab is accessible.
theme_enable(array('bartik'));
$edit['admin_theme'] = 'bartik';
$this->drupalPostForm('admin/appearance', $edit, t('Save configuration'));
$this->drupalGet('admin/structure/block/list/bartik');
$this->assertResponse(200);
}
}
|
<?php
// Load the Zend framework -- this will automatically trigger the appropriate
// controller action based on directory and file names
define('CLI_DIR', __DIR__); // save directory name of current script
require_once __DIR__ . '/../public/index.php';
|
/* ScriptData
SDName: Shattrath_City
SD%Complete: 100
SDComment: Quest support: 10004, 10009, 10211. Flask vendors, Teleport to Caverns of Time
SDCategory: Shattrath City
EndScriptData */
/* ContentData
npc_raliq_the_drunk
npc_salsalabim
<API key>
npc_zephyr
npc_kservant
EndContentData */
#include "ScriptMgr.h"
#include "Player.h"
#include "ScriptedGossip.h"
#include "ScriptedEscortAI.h"
#include "WorldSession.h"
enum RaliqTheDrunk
{
SAY_RALIQ_ATTACK = 0,
<API key> = 0,
<API key> = 45,
<API key> = 7729,
<API key> = 9440,
CRACKIN_SOME_SKULLS = 10009,
SPELL_UPPERCUT = 10966
};
class npc_raliq_the_drunk : public CreatureScript
{
public:
npc_raliq_the_drunk() : CreatureScript("npc_raliq_the_drunk") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
ClearGossipMenuFor(player);
if (action == <API key>+1)
{
CloseGossipMenuFor(player);
creature->setFaction(<API key>);
creature->AI()->Talk(SAY_RALIQ_ATTACK, player);
creature->AI()->AttackStart(player);
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature) override
{
if (player->GetQuestStatus(CRACKIN_SOME_SKULLS) == <API key>)
{
AddGossipItemFor(player, <API key>, <API key>, GOSSIP_SENDER_MAIN, <API key>+1);
SendGossipMenuFor(player, <API key>, creature->GetGUID());
}
else
{
ClearGossipMenuFor(player);
SendGossipMenuFor(player, player->GetGossipTextId(creature), creature->GetGUID());
}
return true;
}
CreatureAI* GetAI(Creature* creature) const override
{
return new <API key>(creature);
}
struct <API key> : public ScriptedAI
{
<API key>(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
Uppercut_Timer = 5000;
}
uint32 Uppercut_Timer;
void Reset() override
{
Initialize();
me->RestoreFaction();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (Uppercut_Timer <= diff)
{
DoCastVictim(SPELL_UPPERCUT);
Uppercut_Timer = 15000;
} else Uppercut_Timer -= diff;
<API key>();
}
};
};
enum Salsalabim
{
SAY_DEMONIC_AGGRO = 0,
<API key> = 0,
FACTION_FRIENDLY = 35,
<API key> = 90,
<API key> = 7725,
<API key> = 9435,
<API key> = 10004,
SPELL_MAGNETIC_PULL = 31705
};
class npc_salsalabim : public CreatureScript
{
public:
npc_salsalabim() : CreatureScript("npc_salsalabim") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
ClearGossipMenuFor(player);
if (action == <API key>+1)
{
CloseGossipMenuFor(player);
creature->setFaction(<API key>);
creature->AI()->Talk(SAY_DEMONIC_AGGRO, player);
creature->AI()->AttackStart(player);
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature) override
{
if (player->GetQuestStatus(<API key>) == <API key>)
{
AddGossipItemFor(player, <API key>, <API key>, GOSSIP_SENDER_MAIN, <API key>+1);
SendGossipMenuFor(player, <API key>, creature->GetGUID());
}
else
{
if (creature->IsQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
SendGossipMenuFor(player, player->GetGossipTextId(creature), creature->GetGUID());
}
return true;
}
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_salsalabimAI(creature);
}
struct npc_salsalabimAI : public ScriptedAI
{
npc_salsalabimAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
MagneticPull_Timer = 15000;
}
uint32 MagneticPull_Timer;
void Reset() override
{
Initialize();
me->RestoreFaction();
}
void DamageTaken(Unit* done_by, uint32 &damage) override
{
if (done_by->GetTypeId() == TYPEID_PLAYER && me-><API key>(20, damage))
{
done_by->ToPlayer()->GroupEventHappens(<API key>, me);
damage = 0;
EnterEvadeMode();
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (MagneticPull_Timer <= diff)
{
DoCastVictim(SPELL_MAGNETIC_PULL);
MagneticPull_Timer = 15000;
} else MagneticPull_Timer -= diff;
<API key>();
}
};
};
enum FlaskVendors
{
ALDOR_REPUTATION = 932,
SCRYERS_REPUTATION = 934,
<API key> = 935,
<API key> = 942,
<API key> = 11083, // (need to be exalted with Sha'tar, Cenarion Expedition and the Aldor)
<API key> = 11084, // (need to be exalted with Sha'tar, Cenarion Expedition and the Scryers)
<API key> = 11085, // Access granted
ARCANIST_XORITH = 23483, // Scryer Apothecary
<API key> = 23484 // Aldor Apothecary
};
class <API key> : public CreatureScript
{
public:
<API key>() : CreatureScript("<API key>") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
ClearGossipMenuFor(player);
if (action == GOSSIP_ACTION_TRADE)
player->GetSession()->SendListInventory(creature->GetGUID());
return true;
}
bool OnGossipHello(Player* player, Creature* creature) override
{
if (creature->GetEntry() == <API key>)
{
// Aldor vendor
if (creature->IsVendor() && (player->GetReputationRank(ALDOR_REPUTATION) == REP_EXALTED) && (player->GetReputationRank(<API key>) == REP_EXALTED) && (player->GetReputationRank(<API key>) == REP_EXALTED))
{
AddGossipItemFor(player, GOSSIP_ICON_VENDOR, <API key>, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE);
SendGossipMenuFor(player, <API key>, creature->GetGUID());
}
else
{
SendGossipMenuFor(player, <API key>, creature->GetGUID());
}
}
if (creature->GetEntry() == ARCANIST_XORITH)
{
// Scryers vendor
if (creature->IsVendor() && (player->GetReputationRank(SCRYERS_REPUTATION) == REP_EXALTED) && (player->GetReputationRank(<API key>) == REP_EXALTED) && (player->GetReputationRank(<API key>) == REP_EXALTED))
{
AddGossipItemFor(player, GOSSIP_ICON_VENDOR, <API key>, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE);
SendGossipMenuFor(player, <API key>, creature->GetGUID());
}
else
{
SendGossipMenuFor(player, <API key>, creature->GetGUID());
}
}
return true;
}
};
enum Zephyr
{
<API key> = 0,
<API key> = 989,
<API key> = 9205,
<API key> = 37778
};
class npc_zephyr : public CreatureScript
{
public:
npc_zephyr() : CreatureScript("npc_zephyr") { }
bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) override
{
ClearGossipMenuFor(player);
if (action == <API key>+1)
player->CastSpell(player, <API key>, false);
return true;
}
bool OnGossipHello(Player* player, Creature* creature) override
{
if (player->GetReputationRank(<API key>) >= REP_REVERED)
AddGossipItemFor(player, <API key>, <API key>, GOSSIP_SENDER_MAIN, <API key>+1);
SendGossipMenuFor(player, player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
};
enum KServant
{
SAY1 = 0,
WHISP1 = 1,
WHISP2 = 2,
WHISP3 = 3,
WHISP4 = 4,
WHISP5 = 5,
WHISP6 = 6,
WHISP7 = 7,
WHISP8 = 8,
WHISP9 = 9,
WHISP10 = 10,
WHISP11 = 11,
WHISP12 = 12,
WHISP13 = 13,
WHISP14 = 14,
WHISP15 = 15,
WHISP16 = 16,
WHISP17 = 17,
WHISP18 = 18,
WHISP19 = 19,
WHISP20 = 20,
WHISP21 = 21,
CITY_OF_LIGHT = 10211
};
class npc_kservant : public CreatureScript
{
public:
npc_kservant() : CreatureScript("npc_kservant") { }
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_kservantAI(creature);
}
struct npc_kservantAI : public npc_escortAI
{
public:
npc_kservantAI(Creature* creature) : npc_escortAI(creature) { }
void WaypointReached(uint32 waypointId) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 0:
Talk(SAY1, player);
break;
case 4:
Talk(WHISP1, player);
break;
case 6:
Talk(WHISP2, player);
break;
case 7:
Talk(WHISP3, player);
break;
case 8:
Talk(WHISP4, player);
break;
case 17:
Talk(WHISP5, player);
break;
case 18:
Talk(WHISP6, player);
break;
case 19:
Talk(WHISP7, player);
break;
case 33:
Talk(WHISP8, player);
break;
case 34:
Talk(WHISP9, player);
break;
case 35:
Talk(WHISP10, player);
break;
case 36:
Talk(WHISP11, player);
break;
case 43:
Talk(WHISP12, player);
break;
case 44:
Talk(WHISP13, player);
break;
case 49:
Talk(WHISP14, player);
break;
case 50:
Talk(WHISP15, player);
break;
case 51:
Talk(WHISP16, player);
break;
case 52:
Talk(WHISP17, player);
break;
case 53:
Talk(WHISP18, player);
break;
case 54:
Talk(WHISP19, player);
break;
case 55:
Talk(WHISP20, player);
break;
case 56:
Talk(WHISP21, player);
player->GroupEventHappens(CITY_OF_LIGHT, me);
break;
}
}
void MoveInLineOfSight(Unit* who) override
{
if (HasEscortState(<API key>))
return;
Player* player = who->ToPlayer();
if (player && player->GetQuestStatus(CITY_OF_LIGHT) == <API key>)
{
float Radius = 10.0f;
if (me->IsWithinDistInMap(who, Radius))
{
Start(false, false, who->GetGUID());
}
}
}
void Reset() override { }
};
};
void <API key>()
{
new npc_raliq_the_drunk();
new npc_salsalabim();
new <API key>();
new npc_zephyr();
new npc_kservant();
}
|
#ifndef TAB_PLOT_H
#define TAB_PLOT_H
#include <globalsearch/ui/abstracttab.h>
#include "ui_tab_plot.h"
class QReadWriteLock;
namespace GlobalSearch {
class Structure;
}
namespace Avogadro {
class PlotPoint;
class PlotObject;
}
// Workaround for Qt's ignorance of namespaces in signals/slots
using Avogadro::PlotPoint;
namespace ExampleSearch {
class ExampleSearchDialog;
class ExampleSearch;
class TabPlot : public GlobalSearch::AbstractTab
{
Q_OBJECT
public:
explicit TabPlot( ExampleSearchDialog *parent, ExampleSearch *p );
virtual ~TabPlot();
enum PlotAxes {
Structure_T = 0,
Energy_T
};
enum PlotType {
Trend_PT = 0,
DistHist_PT
};
enum LabelTypes {
Index_L = 0,
Energy_L
};
public slots:
void readSettings(const QString &filename = "");
void writeSettings(const QString &filename = "");
void updateGUI();
void disconnectGUI();
void <API key>(PlotPoint *pp);
void <API key>(PlotPoint *pp);
void refreshPlot();
void updatePlot();
void plotTrends();
void plotDistHist();
void <API key>();
void <API key>(int index);
void highlightStructure(GlobalSearch::Structure *stucture);
signals:
private:
Ui::Tab_Plot ui;
QReadWriteLock *m_plot_mutex;
Avogadro::PlotObject *m_plotObject;
};
}
#endif
|
#define KMSG_COMPONENT "TZIC"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/platform_device.h>
#include <linux/debugfs.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/android_pmem.h>
#include <linux/io.h>
#include <linux/types.h>
#include <asm/smc.h>
#define TZIC_DEV "tzic"
#define SMC_CMD_STORE_BINFO (-201)
static int gotoCpu0(void);
static int gotoAllCpu(void) __attribute__ ((unused));
u32 exynos_smc1(u32 cmd, u32 arg1, u32 arg2, u32 arg3)
{
register u32 reg0 __asm__("r0") = cmd;
register u32 reg1 __asm__("r1") = arg1;
register u32 reg2 __asm__("r2") = arg2;
register u32 reg3 __asm__("r3") = arg3;
__asm__ volatile (
".arch_extension sec\n"
"smc 0\n"
: "+r"(reg0), "+r"(reg1), "+r"(reg2), "+r"(reg3)
);
return reg0;
}
int <API key>(u32 ctrl_word, u32 *val)
{
register u32 reg0 __asm__("r0");
register u32 reg1 __asm__("r1");
register u32 reg2 __asm__("r2");
register u32 reg3 __asm__("r3");
u32 idx = 0;
for (idx = 0; reg2 != ctrl_word; idx++) {
reg0 = -202;
reg1 = 1;
reg2 = idx;
__asm__ volatile (
".arch_extension sec\n"
"smc 0\n" : "+r" (reg0), "+r"(reg2), "+r"(reg3)
);
if (reg1)
return -1;
}
reg0 = -202;
reg1 = 1;
reg2 = idx;
__asm__ volatile (
".arch_extension sec\n"
"smc 0\n" : "+r" (reg0), "+r"(reg1), "+r"(reg2), "+r"(reg3)
);
if (reg1)
return -1;
*val = reg2;
return 0;
}
static DEFINE_MUTEX(tzic_mutex);
static struct class *driver_class;
static dev_t tzic_device_no;
static struct cdev tzic_cdev;
#define LOG printk
#define TZIC_IOC_MAGIC 0x9E
#define <API key> _IO(TZIC_IOC_MAGIC, 1)
#define <API key> _IOR(TZIC_IOC_MAGIC, 0, unsigned int)
static long tzic_ioctl(struct file *file, unsigned cmd, unsigned long arg)
{
int ret = 0;
ret = gotoCpu0();
if (0 != ret) {
LOG(KERN_INFO "changing core failed!");
return -1;
}
if (cmd == <API key>) {
LOG(KERN_INFO "set_fuse");
exynos_smc1(SMC_CMD_STORE_BINFO, 0x80010001, 0, 0);
exynos_smc1(SMC_CMD_STORE_BINFO, 0x00000001, 0, 0);
} else if (cmd == <API key>) {
LOG(KERN_INFO "get_fuse");
<API key>(0x80010001, (u32 *) arg);
} else {
LOG(KERN_INFO "command error");
}
gotoAllCpu();
return 0;
}
static const struct file_operations tzic_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = tzic_ioctl,
};
static int __init tzic_init(void)
{
int rc;
struct device *class_dev;
rc = alloc_chrdev_region(&tzic_device_no, 0, 1, TZIC_DEV);
if (rc < 0) {
LOG(KERN_INFO "alloc_chrdev_region failed %d", rc);
return rc;
}
driver_class = class_create(THIS_MODULE, TZIC_DEV);
if (IS_ERR(driver_class)) {
rc = -ENOMEM;
LOG(KERN_INFO "class_create failed %d", rc);
goto <API key>;
}
class_dev = device_create(driver_class, NULL, tzic_device_no, NULL,
TZIC_DEV);
if (!class_dev) {
LOG(KERN_INFO "class_device_create failed %d", rc);
rc = -ENOMEM;
goto class_destroy;
}
cdev_init(&tzic_cdev, &tzic_fops);
tzic_cdev.owner = THIS_MODULE;
rc = cdev_add(&tzic_cdev, MKDEV(MAJOR(tzic_device_no), 0), 1);
if (rc < 0) {
LOG(KERN_INFO "cdev_add failed %d", rc);
goto <API key>;
}
return 0;
<API key>:
device_destroy(driver_class, tzic_device_no);
class_destroy:
class_destroy(driver_class);
<API key>:
<API key>(tzic_device_no, 1);
return rc;
}
static void __exit tzic_exit(void)
{
device_destroy(driver_class, tzic_device_no);
class_destroy(driver_class);
<API key>(tzic_device_no, 1);
}
static int gotoCpu0(void)
{
int ret = 0;
struct cpumask mask = CPU_MASK_CPU0;
LOG(KERN_INFO "System has %d CPU's, we are on CPU
"\tBinding this process to CPU
"\tactive mask is %lx, setting it to mask=%lx\n",
nr_cpu_ids,
<API key>(), cpu_active_mask->bits[0], mask.bits[0]);
ret = <API key>(current, &mask);
if (0 != ret)
LOG(KERN_INFO "<API key>=%d.\n", ret);
LOG(KERN_INFO "And now we are on CPU #%d", <API key>());
return ret;
}
static int gotoAllCpu(void)
{
int ret = 0;
struct cpumask mask = CPU_MASK_ALL;
LOG(KERN_INFO "System has %d CPU's, we are on CPU
"\tBinding this process to CPU
"\tactive mask is %lx, setting it to mask=%lx\n",
nr_cpu_ids,
<API key>(), cpu_active_mask->bits[0], mask.bits[0]);
ret = <API key>(current, &mask);
if (0 != ret)
LOG(KERN_INFO "<API key>=%d.\n", ret);
LOG(KERN_INFO "And now we are on CPU #%d", <API key>());
return ret;
}
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Samsung TZIC Driver");
MODULE_VERSION("1.00");
module_init(tzic_init);
module_exit(tzic_exit);
|
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
obj-y += emi_bwl.o
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
ld a, ff
ldff(45), a
ld b, 42
call lwaitly_b
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 0f
.text@1000
lstatint:
ld a, 48
ldff(41), a
ldff(45), a
xor a, a
.text@1032
ldff(c), a
ld a, 44
ldff(45), a
ldff a, (c)
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
srl a
srl a
srl a
srl a
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
#include <locale.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#define LKC_DIRECT_LINK
#include "lkc.h"
static void conf(struct menu *menu);
static void check_conf(struct menu *menu);
enum {
ask_all,
ask_new,
ask_silent,
set_default,
set_yes,
set_mod,
set_no,
set_random
} input_mode = ask_all;
char *defconfig_file;
static int indent = 1;
static int valid_stdin = 1;
static int sync_kconfig;
static int conf_cnt;
static char line[128];
static struct menu *rootEntry;
static void print_help(struct menu *menu)
{
struct gstr help = str_new();
menu_get_ext_help(menu, &help);
printf("\n%s\n", str_get(&help));
str_free(&help);
}
static void strip(char *str)
{
char *p = str;
int l;
while ((isspace(*p)))
p++;
l = strlen(p);
if (p != str)
memmove(str, p, l + 1);
if (!l)
return;
p = str + l - 1;
while ((isspace(*p)))
*p
}
static void check_stdin(void)
{
if (!valid_stdin) {
printf(_("aborted!\n\n"));
printf(_("Console input/output is redirected. "));
printf(_("Run 'make oldconfig' to update configuration.\n\n"));
exit(1);
}
}
static int conf_askvalue(struct symbol *sym, const char *def)
{
enum symbol_type type = sym_get_type(sym);
if (!sym_has_value(sym))
printf(_("(NEW) "));
line[0] = '\n';
line[1] = 0;
if (!sym_is_changable(sym)) {
printf("%s\n", def);
line[0] = '\n';
line[1] = 0;
return 0;
}
switch (input_mode) {
case ask_new:
case ask_silent:
if (sym_has_value(sym)) {
printf("%s\n", def);
return 0;
}
check_stdin();
case ask_all:
fflush(stdout);
xfgets(line, 128, stdin);
return 1;
default:
break;
}
switch (type) {
case S_INT:
case S_HEX:
case S_STRING:
printf("%s\n", def);
return 1;
default:
;
}
printf("%s", line);
return 1;
}
static int conf_string(struct menu *menu)
{
struct symbol *sym = menu->sym;
const char *def;
while (1) {
printf("%*s%s ", indent - 1, "", _(menu->prompt->text));
printf("(%s) ", sym->name);
def = <API key>(sym);
if (<API key>(sym))
printf("[%s] ", def);
if (!conf_askvalue(sym, def))
return 0;
switch (line[0]) {
case '\n':
break;
case '?':
/* print help */
if (line[1] == '\n') {
print_help(menu);
def = NULL;
break;
}
default:
line[strlen(line)-1] = 0;
def = line;
}
if (def && <API key>(sym, def))
return 0;
}
}
static int conf_sym(struct menu *menu)
{
struct symbol *sym = menu->sym;
int type;
tristate oldval, newval;
while (1) {
printf("%*s%s ", indent - 1, "", _(menu->prompt->text));
if (sym->name)
printf("(%s) ", sym->name);
type = sym_get_type(sym);
putchar('[');
oldval = <API key>(sym);
switch (oldval) {
case no:
putchar('N');
break;
case mod:
putchar('M');
break;
case yes:
putchar('Y');
break;
}
if (oldval != no && <API key>(sym, no))
printf("/n");
if (oldval != mod && <API key>(sym, mod))
printf("/m");
if (oldval != yes && <API key>(sym, yes))
printf("/y");
if (menu_has_help(menu))
printf("/?");
printf("] ");
if (!conf_askvalue(sym, <API key>(sym)))
return 0;
strip(line);
switch (line[0]) {
case 'n':
case 'N':
newval = no;
if (!line[1] || !strcmp(&line[1], "o"))
break;
continue;
case 'm':
case 'M':
newval = mod;
if (!line[1])
break;
continue;
case 'y':
case 'Y':
newval = yes;
if (!line[1] || !strcmp(&line[1], "es"))
break;
continue;
case 0:
newval = oldval;
break;
case '?':
goto help;
default:
continue;
}
if (<API key>(sym, newval))
return 0;
help:
print_help(menu);
}
}
static int conf_choice(struct menu *menu)
{
struct symbol *sym, *def_sym;
struct menu *child;
int type;
bool is_new;
sym = menu->sym;
type = sym_get_type(sym);
is_new = !sym_has_value(sym);
if (sym_is_changable(sym)) {
conf_sym(menu);
sym_calc_value(sym);
switch (<API key>(sym)) {
case no:
return 1;
case mod:
return 0;
case yes:
break;
}
} else {
switch (<API key>(sym)) {
case no:
return 1;
case mod:
printf("%*s%s\n", indent - 1, "", _(menu_get_prompt(menu)));
return 0;
case yes:
break;
}
}
while (1) {
int cnt, def;
printf("%*s%s\n", indent - 1, "", _(menu_get_prompt(menu)));
def_sym = <API key>(sym);
cnt = def = 0;
line[0] = 0;
for (child = menu->list; child; child = child->next) {
if (!menu_is_visible(child))
continue;
if (!child->sym) {
printf("%*c %s\n", indent, '*', _(menu_get_prompt(child)));
continue;
}
cnt++;
if (child->sym == def_sym) {
def = cnt;
printf("%*c", indent, '>');
} else
printf("%*c", indent, ' ');
printf(" %d. %s", cnt, _(menu_get_prompt(child)));
if (child->sym->name)
printf(" (%s)", child->sym->name);
if (!sym_has_value(child->sym))
printf(_(" (NEW)"));
printf("\n");
}
printf(_("%*schoice"), indent - 1, "");
if (cnt == 1) {
printf("[1]: 1\n");
goto conf_childs;
}
printf("[1-%d", cnt);
if (menu_has_help(menu))
printf("?");
printf("]: ");
switch (input_mode) {
case ask_new:
case ask_silent:
if (!is_new) {
cnt = def;
printf("%d\n", cnt);
break;
}
check_stdin();
case ask_all:
fflush(stdout);
xfgets(line, 128, stdin);
strip(line);
if (line[0] == '?') {
print_help(menu);
continue;
}
if (!line[0])
cnt = def;
else if (isdigit(line[0]))
cnt = atoi(line);
else
continue;
break;
default:
break;
}
conf_childs:
for (child = menu->list; child; child = child->next) {
if (!child->sym || !menu_is_visible(child))
continue;
if (!--cnt)
break;
}
if (!child)
continue;
if (line[0] && line[strlen(line) - 1] == '?') {
print_help(child);
continue;
}
<API key>(sym, child->sym);
for (child = child->list; child; child = child->next) {
indent += 2;
conf(child);
indent -= 2;
}
return 1;
}
}
static void conf(struct menu *menu)
{
struct symbol *sym;
struct property *prop;
struct menu *child;
if (!menu_is_visible(menu))
return;
sym = menu->sym;
prop = menu->prompt;
if (prop) {
const char *prompt;
switch (prop->type) {
case P_MENU:
if (input_mode == ask_silent && rootEntry != menu) {
check_conf(menu);
return;
}
case P_COMMENT:
prompt = menu_get_prompt(menu);
if (prompt)
printf("%*c\n%*c %s\n%*c\n",
indent, '*',
indent, '*', _(prompt),
indent, '*');
default:
;
}
}
if (!sym)
goto conf_childs;
if (sym_is_choice(sym)) {
conf_choice(menu);
if (sym->curr.tri != mod)
return;
goto conf_childs;
}
switch (sym->type) {
case S_INT:
case S_HEX:
case S_STRING:
conf_string(menu);
break;
default:
conf_sym(menu);
break;
}
conf_childs:
if (sym)
indent += 2;
for (child = menu->list; child; child = child->next)
conf(child);
if (sym)
indent -= 2;
}
static void check_conf(struct menu *menu)
{
struct symbol *sym;
struct menu *child;
if (!menu_is_visible(menu))
return;
sym = menu->sym;
if (sym && !sym_has_value(sym)) {
if (sym_is_changable(sym) ||
(sym_is_choice(sym) && <API key>(sym) == yes)) {
if (!conf_cnt++)
printf(_("*\n* Restart config...\n*\n"));
rootEntry = <API key>(menu);
conf(rootEntry);
}
}
for (child = menu->list; child; child = child->next)
check_conf(child);
}
int main(int ac, char **av)
{
int opt;
const char *name;
struct stat tmpstat;
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
while ((opt = getopt(ac, av, "osdD:nmyrh")) != -1) {
switch (opt) {
case 'o':
input_mode = ask_silent;
break;
case 's':
input_mode = ask_silent;
sync_kconfig = 1;
break;
case 'd':
input_mode = set_default;
break;
case 'D':
input_mode = set_default;
defconfig_file = optarg;
break;
case 'n':
input_mode = set_no;
break;
case 'm':
input_mode = set_mod;
break;
case 'y':
input_mode = set_yes;
break;
case 'r':
{
struct timeval now;
unsigned int seed;
/*
* Use microseconds derived seed,
* compensate for systems where it may be zero
*/
gettimeofday(&now, NULL);
seed = (unsigned int)((now.tv_sec + 1) * (now.tv_usec + 1));
srand(seed);
input_mode = set_random;
break;
}
case 'h':
printf(_("See README for usage info\n"));
exit(0);
break;
default:
fprintf(stderr, _("See README for usage info\n"));
exit(1);
}
}
if (ac == optind) {
printf(_("%s: Kconfig file missing\n"), av[0]);
exit(1);
}
name = av[optind];
conf_parse(name);
//zconfdump(stdout);
if (sync_kconfig) {
name = conf_get_configname();
if (stat(name, &tmpstat)) {
fprintf(stderr, _("***\n"
"*** You have not yet configured your kernel!\n"
"*** (missing kernel config file \"%s\")\n"
"***\n"
"*** Please run some configurator (e.g. \"make oldconfig\" or\n"
"*** \"make menuconfig\" or \"make xconfig\").\n"
"***\n"), name);
exit(1);
}
}
switch (input_mode) {
case set_default:
if (!defconfig_file)
defconfig_file = <API key>();
if (conf_read(defconfig_file)) {
printf(_("***\n"
"*** Can't find default configuration \"%s\"!\n"
"***\n"), defconfig_file);
exit(1);
}
break;
case ask_silent:
case ask_all:
case ask_new:
conf_read(NULL);
break;
case set_no:
case set_mod:
case set_yes:
case set_random:
name = getenv("KCONFIG_ALLCONFIG");
if (name && !stat(name, &tmpstat)) {
conf_read_simple(name, S_DEF_USER);
break;
}
switch (input_mode) {
case set_no: name = "allno.config"; break;
case set_mod: name = "allmod.config"; break;
case set_yes: name = "allyes.config"; break;
case set_random: name = "allrandom.config"; break;
default: break;
}
if (!stat(name, &tmpstat))
conf_read_simple(name, S_DEF_USER);
else if (!stat("all.config", &tmpstat))
conf_read_simple("all.config", S_DEF_USER);
break;
default:
break;
}
if (sync_kconfig) {
if (conf_get_changed()) {
name = getenv("<API key>");
if (name && *name) {
fprintf(stderr,
_("\n*** Kernel configuration requires explicit update.\n\n"));
return 1;
}
}
valid_stdin = isatty(0) && isatty(1) && isatty(2);
}
switch (input_mode) {
case set_no:
<API key>(def_no);
break;
case set_yes:
<API key>(def_yes);
break;
case set_mod:
<API key>(def_mod);
break;
case set_random:
<API key>(def_random);
break;
case set_default:
<API key>(def_default);
break;
case ask_new:
case ask_all:
rootEntry = &rootmenu;
conf(&rootmenu);
input_mode = ask_silent;
/* fall through */
case ask_silent:
/* Update until a loop caused no more changes */
do {
conf_cnt = 0;
check_conf(&rootmenu);
} while (conf_cnt);
break;
}
if (sync_kconfig) {
/* silentoldconfig is used during the build so we shall update autoconf.
* All other commands are only used to generate a config.
*/
if (conf_get_changed() && conf_write(NULL)) {
fprintf(stderr, _("\n*** Error during writing of the kernel configuration.\n\n"));
exit(1);
}
if (conf_write_autoconf()) {
fprintf(stderr, _("\n*** Error during update of the kernel configuration.\n\n"));
return 1;
}
} else {
if (conf_write(NULL)) {
fprintf(stderr, _("\n*** Error during writing of the kernel configuration.\n\n"));
exit(1);
}
}
return 0;
}
void xfgets(str, size, in)
char *str;
int size;
FILE *in;
{
if (fgets(str, size, in) == NULL)
fprintf(stderr, "\nError in reading or end of file.\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.